Skip to content

Architecture

The Hydra is built on an event-driven architecture designed for high-frequency trading and low-latency execution. It uses a central event bus to decouple data providers, trading logic, and execution handlers.

The following diagram illustrates the flow of data through the system, from external price feeds to order execution and state updates.

flowchart TD
    %% Data Sources
    BinanceWS[Binance WS] --> RPE[ReferencePriceEvent]
    PolymarketWS[Polymarket WS] --> MDU[MarketDataUpdated]

    %% Events to EventBus
    RPE --> EventBus
    MDU --> EventBus

    %% EventBus fanout
    EventBus --> RiskManager["RiskManager<br/>Pre-trade Gate"]
    EventBus --> BotStore["BotStore<br/>State Updates"]
    EventBus --> JsonlWriter["JsonlWriter<br/>Persistence"]
    EventBus --> TradeLedger["TradeLedger<br/>Audit Trail"]
    EventBus --> IPCServer[IPC Server]
    EventBus --> TradingEngine

    %% Secondary connections
    IPCServer --> TUI
    BotStore --> Telemetry["Telemetry<br/>InfluxDB"]
    JsonlWriter --> Telemetry

    %% Trading flow
    TradingEngine --> TradeIntent
    RiskManager -.-> Execution

    TradeIntent --> Execution["Execution<br/>Sim / Real"]
    Execution --> CanExecute{canExecute?}
    CanExecute --> OrderFill
    OrderFill --> EventBus

The core of the system is a central pub/sub mechanism. Components communicate by emitting and subscribing to typed events rather than direct method calls. This pattern provides several advantages:

  • Decoupling: Data sources (Integrations) do not need to know which strategies are listening.
  • Observability: Every state change and market update can be logged or monitored by simply attaching a new listener.
  • Testability: Events can be recorded to disk and replayed into the system to verify strategy behavior deterministically.

The central communication hub. It manages the lifecycle of events and ensures they are distributed to all registered subscribers. It is the only component that touches almost every other part of the system.

The source of truth for the bot’s internal state. It follows a reducer pattern similar to Redux, where state is updated by applying events to the current state. This ensures state remains immutable and predictable.

Subscribes to the EventBus and streams metrics to InfluxDB via Telegraf. It converts internal bot events (orderbook updates, trades, risk trips) into time-series data for real-time monitoring and post-mortem analysis. To avoid the CPU jitter associated with pull-based systems like Prometheus, Hydra uses a push-based architecture over UDP or HTTP.

Monitors the Node.js event loop lag using high-resolution timers. It detects blocking operations or garbage collection pauses that could impact trading latency and reports them as telemetry metrics.

Provides high-precision latency tracking with percentile support (P50, P90, P99, P99.9). It captures the time taken for events to flow through the system, enabling deep visibility into the bot’s execution performance.

Adapters for external services that convert proprietary API formats into internal bot events.

  • PolymarketIntegration: Maintains WebSocket connections to Polymarket to provide real-time orderbook updates.
  • BinanceIntegration: Connects to Binance price feeds to provide the high-frequency reference prices used for arbitrage. Captures exchange timestamps and arrival times for sub-millisecond network latency tracking. Includes backpressure handling to prevent memory exhaustion during high volatility.
  • ConsolidatedPriceFeed: Aggregates prices from multiple exchanges (Binance, Coinbase, etc.) for more robust reference pricing.

Handles the lifecycle of orders. It translates abstract trade intents into concrete API calls.

  • SimExecution: A paper trading simulation that matches orders against real-time market data without risking actual capital. Includes liquidity-aware partial fill and slippage simulation.
  • RealExecution: Connects to the Polymarket CLOB (Central Limit Order Book) to execute live trades. Includes a heartbeat mechanism (dead man’s switch) to ensure continuous health monitoring and captures precise execution timestamps for latency analysis.

Acts as a preventive safety layer for all trading activity. Rather than just detecting breaches after they occur, the RiskManager actively blocks trades that would violate limits.

Pre-trade validation: Before any order is executed, RealExecution calls riskManager.canExecute() to verify:

  • The risk mode is active (not killed or paused)
  • The trade would not breach position limits for that market
  • The trade would not breach total exposure limits across all positions
  • The trade would not exceed the maxActiveMarkets limit

Continuous monitoring: The RiskManager performs periodic checks including:

  • Staleness checks on price data (Binance, Polymarket, Chainlink)
  • Maximum drawdown and daily loss enforcement
  • Position reconciliation with the exchange

Account metrics: The RiskManager tracks key financial metrics:

  • USDC balance (from exchange)
  • Position value (mark-to-market)
  • Total equity (balance + positions)
  • Peak equity (high water mark)
  • Unrealized PnL (position value - cost basis)
  • Drawdown percentage from peak

If any limit is breached or data becomes stale, the kill switch is triggered, which cancels all open orders and neutralizes positions.

Provides time abstraction for the system.

  • SystemClock: Uses the local system time.
  • NtpClock: Periodically synchronizes with external HTTP-based time servers to correct local clock drift and ensure accurate latency measurements.
  • SimClock: Used in replay mode to simulate time based on recorded event timestamps.

The bot uses an AsyncMutex to ensure that event processing happens serially. This prevents race conditions when multiple market data or price events arrive simultaneously. The mutex guarantees that:

  • Only one event handler runs at a time
  • Risk checks complete before trading logic executes
  • State updates are atomic and consistent

The system uses multiple persistence mechanisms:

Event Log (JsonlWriter): Subscribes to the EventBus to record every event to disk in JSON Lines format. This provides a complete, high-fidelity audit trail of market data and bot actions, which can be used for debugging, analysis, and backtesting.

Trade Ledger: A specialized, append-only log of all trade executions (buys and sells). It provides a high-level summary of trading performance, including volume, fees, and realized P&L, accessible via the hydra trades CLI command.

State Database (SQLite): Persists critical risk management state across restarts:

  • Peak equity (for drawdown calculations)
  • Cost basis per market (for PnL tracking)

This ensures that restarting the bot does not reset risk metrics or lose track of trading history.

In live trading mode, the RealExecution layer maintains a heartbeat with the Polymarket API. If the bot stops sending heartbeats (due to crash, network failure, or other issues), the exchange will automatically cancel all open orders. This prevents orphaned orders from remaining on the book during outages.

Provides an Inter-Process Communication layer that allows the core trading bot to communicate with the Terminal User Interface (TUI). The server enriches snapshots with account metrics (balance, PnL, drawdown) for real-time display. This separation ensures that UI rendering does not impact the performance of the trading engine.

Pluggable logic units that define when and how to trade. Strategies subscribe to events via the TradingEngine and emit trade signals based on their specific algorithms.

Strategies that depend on historical data (like volatility calculations) implement a warmup period. During warmup:

  • The strategy collects price history
  • No trades are executed
  • Once sufficient data is accumulated, trading becomes active

This prevents the bot from making poorly-informed trades immediately after startup.