Skip to content

Orders

Market Orders

Market orders use deterministic pricing — every order targets a specific timestamp (Math.floor(Date.now() / 1000)).

If the price is available at the target timestamp, the order executes immediately. Otherwise, it enters the pending state machine and executes asynchronously via onPriceArrival().

Limit Orders

Limit orders specify a target price. When submitted:

  1. If current price already meets the condition, executes immediately
  2. Otherwise, margin is reserved and a PRICE_CONDITION alert is registered with PriceAlert

The alert fires when the price crosses the threshold, triggering execution via onAlert().

Pending State Machine

CREATED → PENDING → EXECUTED / FAILED
  • CREATED: Order recorded, margin reserved
  • PENDING: Awaiting price data or condition
  • EXECUTED: Successfully filled
  • FAILED: Execution failed (e.g., insufficient margin at execution time)

This state machine survives DO eviction — all state is persisted in SQLite.

Price Arrival Alert Optimization

The registerPriceArrivalAlert() method uses a three-level strategy:

  1. Level 1: Returns cached data immediately if available (no alert created)
  2. Level 2: For historical timestamps (>1s old), proactively fetches from PriceCollector with 1 retry attempt. Skips for very recent timestamps to avoid blocking.
  3. Level 3: Creates alert for async delivery via alarm loop if price unavailable

This reduces unnecessary alert creation and improves responsiveness for both recent market orders (~50ms) and historical queries (immediate execution when data exists).