How the Grid Bot Works
How the Grid Bot Works
Understanding the internal mechanics of the grid bot helps you interpret its behavior, troubleshoot issues, and make informed configuration decisions. This guide covers the main cycle, state management, reconciliation, and the safety systems that keep the bot running correctly.
The Main Cycle
The bot operates on a fixed-interval cycle, defaulting to every 15 seconds. Each cycle follows a precise sequence of steps that evaluate the market, check existing orders, detect fills, and place new orders.
Step 1 - Price check: The bot reads the current mark price from the WebSocket feed. If the WebSocket is disconnected, it falls back to a REST API call. If no price is available, the entire cycle is skipped.
Step 2 - REST snapshot: The bot fetches all open orders from the exchange via REST API. This single snapshot is used throughout the entire cycle. If this call fails, no orders are placed during this cycle. This prevents the bot from acting on stale or incomplete data.
Step 3 - Data health check: The bot verifies that both the price and order snapshot are fresh (less than 15 seconds old). Stale data causes the cycle to skip, preventing decisions based on outdated information.
Step 4 - Grid break evaluation: The bot checks whether the current price is outside the configured grid range. If the price has been outside the range (with buffer) for the configured confirmation period, the bot triggers a clean shutdown.
Step 5 - Trade history sync: The bot checks for new fills via the trade history. Any new buy fills update the internal state and trigger TP order placement. Any new sell (TP) fills clear positions from the state.
Step 6 - TP restoration: The bot verifies that every filled grid level has a corresponding TP order. If any TP order is missing (perhaps it was cancelled or rejected), a new one is placed.
Step 7 - Reconciliation: The bot compares its internal state against the REST snapshot to detect discrepancies. Missing buy orders, missing TP orders, and orphan orders are identified and queued for correction.
Step 8 - Grid evaluation: The bot identifies which grid levels below the current price should have buy orders and filters out levels that already have orders, positions, or active locks.
Step 9 - Order placement: Remaining grid levels are submitted as limit buy orders, up to 10 per cycle (the exchange batch limit).
State Management
The bot maintains an in-memory state called GridState that tracks three things for each grid level:
Position status: Whether a buy has filled at this level and how much was bought. This is updated only by the trade history processor, never by order events or cycle logic directly.
TP status: Whether a take-profit order exists for this level. Tracks three sub-states: active (TP order confirmed on exchange), written (TP sent but not yet confirmed), and pending (TP planned but not yet sent).
Lock status: Whether the level is temporarily locked from new orders. Locks prevent duplicate orders during the gap between sending an order and seeing it appear in the REST snapshot.
This state is ephemeral. It does not persist across bot restarts. When the bot starts, the state is empty. The trade history sync rebuilds it by processing recent trade history from the exchange, ensuring the state matches reality.
The Reconciliation Engine
Reconciliation is the self-healing mechanism that detects and corrects discrepancies between the bot’s internal state and the actual exchange state. It runs every cycle with a throttle to prevent excessive API calls.
Missing buy detection: The reconciliation compares the expected set of grid levels (those below market price without positions) against the actual open buy orders on the exchange. Levels that should have orders but do not are flagged as missing.
Missing TP detection: For every grid level that has a filled position, reconciliation checks whether a TP sell order exists on the exchange. Missing TPs are flagged for re-creation.
Orphan TP detection: If a TP sell order exists on the exchange but the corresponding grid level has no position, the TP is an orphan. This can happen if a position was closed by other means. Orphan TPs are candidates for cancellation.
Confirmation debounce: A discrepancy must be detected in 5 consecutive cycles before the bot acts on it. This prevents false positives from temporary API delays, network latency, or brief order book inconsistencies. Only after 5 consecutive confirmations does the bot place corrective orders.
Safety Systems
Multiple safety layers prevent the bot from harmful actions:
Duplicate prevention: Grid locks, pending level tracking, and in-flight order tracking work together to prevent placing two orders at the same grid level. Each mechanism covers a different time window in the order lifecycle.
Data freshness guards: If the REST snapshot or price data is older than 15 seconds, the bot skips order placement. This prevents acting on stale data after network interruptions.
Bootstrap protection: When the bot detects no open orders and no positions (a clean-slate condition), it requires two consecutive cycles confirming this state before triggering bootstrap. This prevents a single API timeout (which returns empty data) from incorrectly triggering a full grid bootstrap.
Clean shutdown sequence: When the bot needs to stop, it follows a strict sequence: close WebSockets, cancel entry orders, cancel all orders, close positions, and reset flags. This sequence runs exactly once, protected by an idempotency flag.
WebSocket Architecture
The bot uses three WebSocket connections:
Price feed: Receives real-time mark price updates. Falls back to REST polling if disconnected.
Order WebSocket: Receives order status updates (new, filled, cancelled, rejected). Used to clear pending locks quickly but never updates inventory.
Trade history WebSocket: Receives confirmed trade fills. This is the only source that updates positions in GridState. Separating this from order events ensures that only confirmed, settled trades affect inventory tracking.
Summary
- The bot runs a fixed-interval cycle that checks price, fetches orders, detects fills, reconciles state, and places new orders in a strict sequence.
- GridState tracks positions, TPs, and locks in memory; it is rebuilt from trade history on restart rather than persisted.
- Reconciliation self-heals discrepancies with a 5-cycle confirmation debounce to prevent false positive corrections.
Next Step
Explore how machine learning can suggest optimal grid parameters in AI Grid Optimization.
✨ Was this article helpful?
Ask your questions on Ask on Discord →