Broker Adapters & Order Entry Layer

Code Version: 0.9.1 | Wiki Version: 0.9.5 (sections 1 - 5 describe the 0.4.0 adapter layer; section 0 the venues today)

0. Venues Today (2026-12)

VenueWorker / containerConnectionUsed by
IG (demo)services/venue_ig / drt-venue-ig (IGBrokerClient)IG REST API for orders and account, Lightstreamer for prices and 5-minute candles (closed candles only); NAS100 is IX.D.NASDAQ.IFS.IP (GBP 1 per point)C* IG paper bot, IG dry_run bots, dashboard
FXCM (demo)services/venue_fxcm / drt-venue-fxcm + services/fxcm_gateway / drt-fxcm-gatewayPython 3.7 FastAPI gateway on the ForexConnect SDK (x86_64 under QEMU on ARM), port 5001 (section 3); /bars/recent also serves the bots' warm-up and C*'s history seedC* FXCM paper bot, FXCM dry_run bots, dashboard; the data downloader shares the account
IBKR (paper)services/venue_ibkr / drt-venue-ibkr + drt-ib-gatewayib_insync to IB Gateway; since 2026-11-28 IBKR's own CFDs (free market data): NAS100 IBUST100, SPX500 IBUS500, US30, UK100, GER40, FRA40, EU50, JPN225, XAUUSD, XAGUSD and forex CFDs (forex data from IDEALPRO); one position per trade (trade_book.py, OCA stop / target)dashboard, manual orders (no bot)
Binanceservices/venue_binance / drt-venue-binanceUSDⓈ-M futures (testnet / demo profile)dashboard, manual orders
Hyperliquidservices/venue_hyperliquid / drt-venue-hyperliquidHyperliquid (testnet / demo profile)dashboard, manual orders

The bots never talk to a broker directly: they read closed 5-minute bars from md.bars.{venue}.{symbol} and the venue's book (book:{VENUE}), and send orders through the order router to the venue worker (orders.request.{VENUE}). See Integration Flow.

1. BrokerClient Protocol & Lifecycle

All broker adapters in drt-multi-venue implement the runtime-checkable BrokerClient protocol defined in common/broker/protocol.py. This standardizes market data ingestion and order management across venues.

Method Signature Description
connect() async def connect() -> None Establishes asynchronous connection to venue gateway; raises BrokerConnectionError on failure.
disconnect() async def disconnect() -> None Closes client sessions, cancels active market subscriptions, and cleans up sockets.
stream_bars() async def stream_bars(symbols: list[str]) -> AsyncIterator[Bar] Streams confirmed 5-minute candle bars satisfying strict OHLC invariants.
stream_ticks() async def stream_ticks(symbols: list[str]) -> AsyncIterator[Tick] Streams real-time intra-bar ticks with microsecond UTC timestamps.
place_order() async def place_order(order: OrderRequest) -> str Submits market or limit order to broker; returns assigned order ID.
cancel_order() async def cancel_order(order_id: str) -> None Cancels open order by identifier.
get_positions() async def get_positions() -> list[dict] Retrieves active open positions normalized to internal symbol naming.
reconnect() async def reconnect() -> None Executes clean disconnect and triggers exponential backoff reconnection.

2. Interactive Brokers Adapter (IBKR) & Contract Resolution

The IBKR adapter (services/venue_ibkr/broker_client.py) communicates with IB Gateway (port 4002) using ib_insync. Superseded on 2026-11-28: the futures below need paid exchange data and never worked on production; the IBKR catalogue is now CFDs only (section 0). The futures roll logic is kept for reference.

Front-Month Auto-Roll Algorithm

Equity indices (MNQ, MES, M2K, MNK) and currency futures (M6E, M6B, MSF) follow quarterly cycle months:

$$\mathcal{M}_{\text{quarterly}} = \{3 \text{ (H)}, 6 \text{ (M)}, 9 \text{ (U)}, 12 \text{ (Z)}\}$$

To avoid illiquidity in expiring contracts, rollover occurs 8 calendar days prior to the 3rd Friday of the expiry month (threshold day $d_{\text{roll}} = 10$):

$$m_{\text{front}} = \begin{cases} \min \{ q \in \mathcal{M} \mid q > m \lor (q = m \land d \le 10) \}, & \text{if } m \le 12 \text{ and } (m \ne 12 \lor d \le 10) \\ 3 \text{ (Year } Y + 1\text{)}, & \text{if } m = 12 \land d > 10 \end{cases}$$

For monthly commodity futures such as Micro WTI Crude Oil (MCL), expiration occurs monthly with roll threshold $d_{\text{oil}} = 15$:

$$m_{\text{oil}} = \begin{cases} m, & \text{if } d \le 15 \\ m + 1, & \text{if } d > 15 \text{ (with year rollover if } m = 12\text{)} \end{cases}$$

Contract Specifications

Symbol Epic SecType Exchange Front Month Example (Sept 2026)
NAS100 MNQ FUT GLOBEX Future('MNQ', '202609', 'GLOBEX', 'USD')
SPX500 MES FUT GLOBEX Future('MES', '202609', 'GLOBEX', 'USD')
EURUSD M6E FUT GLOBEX Future('M6E', '202609', 'GLOBEX', 'USD')
USOil MCL FUT NYMEX Future('MCL', '202609', 'NYMEX', 'USD')
EURUSD_CASH EUR.USD CASH IDEALPRO Forex('EURUSD', 'IDEALPRO')

3. FXCM Adapter (Gateway Pattern)

Legacy fxcmpy is deprecated and incompatible with Python 3.11+ and ARM64 architecture (ForexConnect binary library is x86_64 only). To ensure production stability on our Oracle Cloud Ampere A1 ARM VM, FXCM connectivity uses the Java Gateway Pattern (mirroring IBKR's ib-gateway architecture):

Gateway Endpoints

Endpoint Protocol Description
GET /health HTTP Gateway connectivity and FXCM trading session health status check.
GET /bars/stream SSE / NDJSON Push stream of confirmed 5-minute candle bars.
GET /bars/recent HTTP Polling endpoint for bar closures and backfill recovery.
WS /ws/ticks WebSocket Sub-millisecond real-time market tick stream.
POST /orders HTTP Submits market or limit orders to demo/live accounts.
DELETE /orders/{id} HTTP Cancels active working order or closes open position.
GET /positions HTTP Queries open positions and unrealized PnL.

4. Synthetic Mock Broker (Offline Testing Only)

The MockBrokerClient (common/broker/mock.py) is isolated strictly for standalone unit tests. In production and demo runtime, all order routing, positions, and market data queries route exclusively to live concrete brokers (IGBrokerClient, FXCMBrokerClient, IBKRBrokerClient, BinanceBrokerClient, HyperliquidBrokerClient).

Zero-Mock Runtime Guarantee

The OrderRouter and Next-Gen Dashboard have completely eliminated mock fallbacks. If a broker adapter is not immediately registered, the engine dynamically auto-instantiates and connects to the target venue gateway (e.g. drt-fxcm-gateway or drt-ib-gateway), guaranteeing genuine broker execution.

5. Disconnection Recovery & Exponential Backoff

Both venue adapters incorporate resilient reconnection state machines. When a socket disconnects or gateway heartbeats time out, adapters execute exponential backoff retries:

$$\Delta t_k = \min\left(\Delta t_0 \cdot 2^{k-1}, \, \Delta t_{\max}\right), \quad k \in \{1, 2, \dots, K_{\max}\}$$

where base delay $\Delta t_0 = 1.0\text{s}$ and maximum attempts $K_{\max} = 5$. If connection cannot be restored after $K_{\max}$ attempts, BrokerConnectionError is raised, triggering worker failover and alerts.