How the Grid Bot Works
How the Grid Bot Works
Understanding the internal mechanics of el grid bot te ayuda a interpret its behavior, troubleshoot issues, and make informed configuration decisions. This guide covers el principal cycle, state management, reconciliation, and the safety systems that keep el bot running correctly.
The Main Cycle
El bot operates on a fixed-interval cycle, defaulting to every 15 seconds. Each cycle follows a precise sequence of steps that evaluate el mercado, check existing orders, detect fills, and place new orders.
Paso 1 - Price check: El bot reads the current precio 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.
Paso 2 - REST snapshot: El bot fetches all open orders from el exchange via REST API. This single snapshot is used throughout the entire cycle. If this call fails, no orders are placed during this cycle. Esto previene el bot from acting on stale or incomplete data.
Paso 3 - Data health check: El bot verifies that ambos el precio and order snapshot are fresh (menos que 15 seconds old). Stale data causes the cycle to skip, preventing decisions based on outdated information.
Paso 4 - Grid break evaluation: El bot checks si the precio actual is outside the configured rango de grid. If el precio has been outside the range (with buffer) for the configured confirmation period, el bot triggers a clean shutdown.
Paso 5 - Trade history sync: El 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.
Paso 6 - TP restoration: El 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: El bot compares its internal state contra el REST snapshot to detect discrepancies. Missing orden de compras, missing TP orders, and orphan orders are identified and queued for correction.
Step 8 - Grid evaluation: El bot identifies which nivel de grids below the precio actual should have orden 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 orden de compras, up to 10 per cycle (el exchange batch limit).
State Management
El 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 el bot starts, the state is empty. The trade history sync rebuilds it by processing recent trade history from el exchange, ensuring the state matches reality.
The Reconciliation Engine
Reconciliation is the self-healing mechanism that detects and corrects discrepancies entre el 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 sin positions) contra el actual open orden de compras on el 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 si a TP orden de venta exists on el exchange. Missing TPs are flagged for re-creation.
Orphan TP detection: If a TP orden de venta exists on el 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 el bot acts on it. Esto previene false positives from temporary API delays, network latency, or brief libro de ordenes inconsistencies. Only after 5 consecutive confirmations does el bot place corrective orders.
Safety Systems
Multiple safety layers prevent el bot from harmful actions:
Duplicate prevention: Grid locks, pending level tracking, and in-flight order tracking work together para prevenir placing two orders at el mismo nivel de grid. Each mechanism covers a different time window in la orden lifecycle.
Data freshness guards: If the REST snapshot or price data is older than 15 seconds, el bot skips order placement. Esto previene acting on stale data after network interruptions.
Bootstrap protection: When el bot detecta no open orders and no positions (a clean-slate condition), it requires two consecutive cycles confirming this state before triggering bootstrap. Esto previene a single API timeout (which returns empty data) from incorrectly triggering a full grid bootstrap.
Clean shutdown sequence: When el 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
El bot uses three WebSocket connections:
Price feed: Receives en tiempo real precio 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. Este es el only source that updates positions in GridState. Separating this from order events ensures that only confirmed, settled trades affect inventory tracking.
Resumen
- El 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; es rebuilt from trade history on restart rather than persisted.
- Reconciliation self-heals discrepancies with a 5-cycle confirmation debounce para prevenir false positive corrections.
Siguiente Paso
Explore how machine learning can suggest optimal grid parameters in AI Grid Optimization.
✨ Te fue util este articulo?
Haz tus preguntas en Discord →