Broker Integrations
Broker & Exchange Integration Patterns
Connect reliably. Fail safely.
The integration layer between strategy logic and live execution venues is where most automated trading systems encounter their first production failures. This hub covers the engineering patterns that make broker connections reliable, observable, and recoverable, from adapter architecture and order type mapping to WebSocket reconnect logic, error retry policy, and contract testing.
What this hub covers
Broker and exchange integration is the discipline of translating high-level strategy intent, "buy 200 shares of SPY at market", into the exact wire-format messages a specific venue expects, then correctly interpreting every response, error, and state change that comes back. Every broker has a different API surface: different field names, different authentication flows, different order type enumerations, different WebSocket heartbeat requirements, and different behavior under rate limits.
This hub walks through the full lifecycle of a production broker integration: designing the adapter layer that isolates venue specifics from strategy logic, discovering what a broker actually supports vs. what its documentation claims, mapping order types and time-in-force values, handling connection failures and missed events, classifying errors by retryability, reconciling account state, respecting trading calendars, understanding sandbox vs. live differences, designing multi-broker failover, and building automated contract tests that catch API changes before they cause live trading errors.
Key principles
- Abstract the venue behind an interface: Strategy logic should speak in terms of order intent and position state, never in broker-specific field names or enum values. The adapter owns the translation.
- Discover. Don't assume: Documentation lies. Test every claimed capability against the sandbox and document what the API actually does, including undocumented constraints like minimum order sizes and symbol-level lot restrictions.
- Classify errors before you retry: A validation rejection (4xx) should never be retried automatically. A rate-limit response (429) requires a specific backoff. A timeout on order submission is an ambiguous state that requires querying before retrying, not blind retransmission.
- Reconnect without losing state: WebSocket reconnects must restore all active subscriptions and reconcile any missed updates during the gap. Assume you missed at least one fill or status change during every reconnect window.
- Sandbox tests connectivity; live tests behavior: Sandbox fills are typically instant and unrealistic. Do not confuse passing sandbox tests with production readiness. Certain broker behaviors, real partial fills, margin calls, early session order rejections, only appear in production.
- Failover adds reconciliation debt: Routing orders to a backup broker during a primary outage means open positions can diverge between venues. Multi-broker design requires explicit reconciliation logic and an authoritative source of truth for net exposure.
- Contract tests catch breaking changes: Brokers change their APIs without notice. An automated contract test suite that snapshots expected request/response shapes and runs against the sandbox on a schedule is the earliest warning system for changes that would break live trading.
- Buying power is not your balance: Brokers compute available buying power using margin multipliers, unsettled trade exclusions, and open order holds. Your internal state machine must sync with broker-reported values at critical moments, not trust its own running total.
Curriculum: Broker & Exchange Integration Patterns
Ten guides cover the integration layer in sequence, from adapter design through contract testing, plus three interactive tools for capability comparison, contract test generation, and sandbox-to-live readiness assessment.
Guides
-
Broker Adapter Architecture
Designing a broker adapter layer that normalizes venue-specific APIs into a consistent interface, decoupling strategy logic from execution venue details.
Guide
-
Broker API Capability Discovery
How to systematically discover what an API supports: order types, time-in-force values, asset classes, and undocumented constraints found only through testing.
Guide
-
Order Type and Time-in-Force Mapping
Translating strategy-level order intent into broker-specific field values, and handling brokers that don't support a required type.
Guide
-
Broker WebSocket Reconnect & Resubscribe
Designing reconnect logic for broker WebSocket channels: exponential backoff, state recovery on reconnect, subscription restoration, and handling missed events during the gap.
Guide
-
Broker Error Taxonomy and Retry Policy
Classifying broker error responses by retryability: transient network errors, rate limits, validation rejections, and ambiguous states.
Guide
-
Account, Position, and Buying-Power Semantics
How brokers compute account equity, open position exposure, settled vs. unsettled funds, and buying power, and why these differ from your internal state.
Guide
-
Trading Calendar and Session Differences by Venue
Market holidays, early close days, session hours by asset class, and how to maintain an authoritative trading calendar that matches venue behavior exactly.
Guide
-
Sandbox vs. Live Broker APIs
Key differences between sandbox and live environments: fill simulation quality, rate limit enforcement, margin behavior, and bugs that only appear in live.
Guide
-
Failover and Multi-Broker Design
Routing orders across multiple brokers, defining failover triggers, managing open positions during a venue outage, and multi-broker reconciliation.
Guide
-
Broker Integration Contract Testing
Building automated contract tests that verify broker API behavior against a documented specification, catching breaking changes before they cause live trading errors.
Guide
Interactive Tools
-
Broker Capability Matrix
Compare hypothetical broker capabilities across order types, time-in-force values, asset classes, and API features in a structured comparison matrix.
Tool
-
Adapter Contract Test Harness
Simulate a broker adapter test harness: define expected API behaviors and generate a structured contract test checklist for integration validation.
Tool
-
Sandbox-to-Live Readiness Checklist
Interactive readiness checklist for moving from sandbox to live trading: authentication, order type validation, risk limits, logging, monitoring, and kill switch verification.
Tool
Frequently Asked Questions
What is a broker adapter and why does it matter?
A broker adapter is an abstraction layer that translates your strategy's generic order intent, buy 100 shares of AAPL at limit $195, into the exact API call, field names, and authentication tokens that a specific broker or exchange expects. Without one, each strategy contains hard-coded broker logic that breaks every time the broker changes its API or you add a new venue. A well-designed adapter lets you swap venues without changing strategy code.
How do I handle order types my broker doesn't support?
First, discover the gap through capability discovery, query or document which order types the broker actually accepts. Then choose a synthesis strategy: decompose the unsupported type into supported primitives (e.g., a trailing stop as a recurring limit cancel-and-replace loop), route that order type to an alternative venue that does support it, or reject the order at the adapter boundary with a clear error rather than silently modifying the order in ways the strategy didn't intend.
What causes most broker API outages and how do I design around them?
Most outages fall into three categories: planned maintenance windows (documented in advance), unplanned rate limit cascades (one client floods the endpoint and the broker throttles everyone), and infrastructure failures (database saturation, CDN issues, or upstream exchange connectivity loss). Designing around them requires circuit breakers that stop sending when error rates spike, fallback routes to a secondary broker for new orders, and position reconciliation logic to audit open trades against broker state after reconnection.
Are sandbox environments accurate enough to test production behavior?
Sandbox environments are useful for basic connectivity, authentication, and order flow testing, but they diverge from production in important ways: fill simulation is typically immediate and unrealistic, rate limits are often more lenient or differently enforced, margin and buying power calculations may not match production rules, and some endpoints (especially account-level queries) return static mock data. The sandbox validates that your code can send and receive the right message shapes; it does not validate that your logic handles realistic execution, partial fills, or market-microstructure edge cases.
What is the right retry policy for broker API errors?
Retry policy depends on error category. Network timeouts and 5xx server errors are generally safe to retry with exponential backoff (1s, 2s, 4s, up to a cap). Rate limit errors (429) require honoring the Retry-After header before retrying. Validation errors (4xx rejections for bad parameters) must never be retried, the request will always fail without changing your input. The most dangerous category is ambiguous state: if you submit an order and receive a timeout before getting an acknowledgment, query the broker for the order status before deciding whether to retry, because a duplicate submission can double your position.
How do you test that a broker adapter works correctly?
Integration contract testing verifies that the adapter correctly translates between your internal model and the broker's wire format, and that the broker's actual responses match your documented expectations. A contract test suite includes: field mapping assertions (does your 'limit' order type translate to the exact string the broker expects?), response parsing tests (does an unexpected field from the broker cause a crash or a silent ignore?), error handling tests (does a 429 trigger backoff?), and state recovery tests (does reconnection restore subscriptions after a WebSocket drop?). Run these against the sandbox and snapshot the results; any future sandbox response change that breaks a snapshot is a signal to investigate before it hits production.