How the Grid Bot Works
How the Grid Bot Works
Understanding the internal mechanics of o grid bot te ajuda a 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 o bot running correctly.
The Main Cycle
O bot operates on a fixed-interval cycle, defaulting to every 15 seconds. Each cycle follows a precise sequence of steps that evaluate o mercado, check existing orders, detect fills, and place new orders.
Passo 1 - Price check: O bot reads the current preco mark 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.
Passo 2 - REST snapshot: O bot fetches all open orders from o exchange via REST API. This single snapshot is used throughout the entire cycle. If this call fails, no orders are placed during this cycle. Isso previne o bot from acting on stale or incomplete data.
Passo 3 - Data health check: O bot verifies that ambos o preco and order snapshot are fresh (menos que 15 seconds old). Stale data causes the cycle to skip, preventing decisions based on outdated information.
Passo 4 - Grid break evaluation: O bot checks se the preco atual is outside the configured faixa de grid. If o preco has been outside the range (with buffer) for the configured confirmation period, o bot triggers a clean shutdown.
Passo 5 - Trade history sync: O 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.
Passo 6 - TP restoration: O bot verifies that every filled nivel de grid 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: O bot compares its internal state against the REST snapshot to detect discrepancies. Missing ordem de compras, missing TP orders, and orphan orders are identified and queued for correction.
Step 8 - Grid evaluation: O bot identifies which nivel de grids below the preco atual should have ordem de compras and filters out levels that already have orders, positions, or active locks.
Step 9 - Order placement: Remaining nivel de grids are submitted as limit ordem de compras, up to 10 per cycle (o exchange batch limit).
State Management
O bot maintains an in-memory state called GridState that tracks three things for each nivel de grid:
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 o bot starts, the state is empty. The trade history sync rebuilds it by processing recent trade history from o exchange, ensuring the state matches reality.
The Reconciliation Engine
Reconciliation is the self-healing mechanism that detects and corrects discrepancies entre o bot’s internal state and the actual exchange state. It runs every cycle with a throttle para prevenir excessive API calls.
Missing buy detection: The reconciliation compares the expected set of nivel de grids (those below market price sem positions) against the actual open ordem de compras on o exchange. Levels that should have orders but do not are flagged as missing.
Missing TP detection: For every nivel de grid that has a filled position, reconciliation checks se a TP ordem de venda exists on o exchange. Missing TPs are flagged for re-creation.
Orphan TP detection: If a TP ordem de venda exists on o exchange but the corresponding nivel de grid 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 o bot acts on it. Isso previne false positives from temporary API delays, network latency, or brief livro de ordens inconsistencies. Only after 5 consecutive confirmations does o bot place corrective orders.
Safety Systems
Multiple safety layers prevent o bot from harmful actions:
Duplicate prevention: Grid locks, pending level tracking, and in-flight order tracking work together para prevenir placing two orders at o mesmo nivel de grid. Each mechanism covers a different time window in a ordem lifecycle.
Data freshness guards: If the REST snapshot or price data is older than 15 seconds, o bot skips order placement. Isso previne acting on stale data after network interruptions.
Bootstrap protection: When o bot detecta no open orders and no positions (a clean-slate condition), it requires two consecutive cycles confirming this state before triggering bootstrap. Isso previne a single API timeout (which returns empty data) from incorrectly triggering a full grid bootstrap.
Clean shutdown sequence: When o 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
O bot uses three WebSocket connections:
Price feed: Receives em tempo real preco mark 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.
Resumo
- O 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; e rebuilt from trade history on restart rather than persisted.
- Reconciliation self-heals discrepancies with a 5-cycle confirmation debounce para prevenir false positive corrections.
Proximo Passo
Explore how machine learning can suggest optimal grid parameters in AI Grid Optimization.
✨ Este artigo foi util?
Faca suas perguntas no Discord →