Broker Adapters & Order Entry Layer
0. Venues Today (2026-12)
| Venue | Worker / container | Connection | Used 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-gateway | Python 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 seed | C* FXCM paper bot, FXCM dry_run bots, dashboard; the data downloader shares the account |
| IBKR (paper) | services/venue_ibkr / drt-venue-ibkr + drt-ib-gateway | ib_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) |
| Binance | services/venue_binance / drt-venue-binance | USDⓈ-M futures (testnet / demo profile) | dashboard, manual orders |
| Hyperliquid | services/venue_hyperliquid / drt-venue-hyperliquid | Hyperliquid (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:
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$:
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):
- Architecture: An external service (
fxcm-gateway,services/fxcm_gateway/app.py: FastAPI on the ForexConnect C++ SDK,python:3.7-slimforlinux/amd64, run under QEMU on the ARM VM) holds the FXCM session on port5001. (The original plan was an OpenJDK gateway; it was replaced by ForexConnect.) It also serves/offers,/ticks/latest,/ws/book,/closed_trades,/positions/{trade_id}/close|modifyand/orders/{id}/modifybeyond the endpoints listed below. - Client Adapter (
services/venue_fxcm/broker_client.py): Uses high-performance async HTTP/WebSocket viaaiohttp. - Bidirectional Symbol Translation: $$S_{\text{internal}} \text{ (e.g. 'EURUSD')} \longleftrightarrow E_{\text{FXCM}} \text{ (e.g. 'EUR/USD')}$$
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.