A broker API is a software interface that lets a trading programme read account and market information, then submit and manage orders.
That definition hides the hard part: an HTTP response is not proof that an order filled, and a timeout is not proof that it failed. An unattended agent must keep its own view of positions and orders aligned with the broker's record, including when updates arrive late or connections break.
Start with the contract, not the endpoint
Before building a strategy, establish exactly what the API permits and what each response means. Broker documentation often describes an order request, but the implementation also depends on account permissions, asset type, market session and regional rules. A stock account may support fractional quantities while a futures account requires whole contracts. Short selling, options, extended-hours trading and particular order types may need separate permissions.
Check whether the API offers both a request-response interface and a streaming connection. REST is usually convenient for submitting orders and retrieving account snapshots.
A WebSocket or similar stream can deliver quote and order updates without repeated polling. Neither should be treated as infallible. Streaming connections can drop, and snapshots can become stale between requests.
Record these details before writing execution code:
- Authentication method, token lifetime, refresh behaviour and whether credentials can be restricted to trading or read-only access.
- Supported order types, time-in-force values, trading sessions, quantity increments and minimum price ticks.
- Rate limits and whether they apply per key, account, endpoint or connection.
- How the API identifies orders and reports rejection reasons, partial fills and cancel requests.
- Whether market data is real-time, delayed or subject to a separate permission.
A useful API specification explains limits and failure responses as clearly as the successful path. If the documentation is vague, ask the broker for an answer that can be tested, rather than inferring behaviour from a successful sandbox request.
Market data and timing are part of execution
An agent cannot make a sound order decision with a quote that is stale, incomplete or in a different format from the one it expects. Check timestamps, time zones, session markers and whether prices represent trades, bids, asks or a midpoint.
A midpoint is not necessarily an executable price. For a marketable order, the relevant quote is usually the offer when buying and the bid when selling, though displayed size and subsequent movement still affect the fill.
Typical operating ranges vary by broker, instrument, network and market conditions. The figures below are indicative ranges for planning, not service guarantees or audited results. Measure the actual API in the intended account and session.
| API characteristic | Typical range | Operational implication |
|---|---|---|
| Order acknowledgement over REST | 50 to 500 ms | Record acknowledgement time, but wait for order events or query status to learn whether it filled. |
| Streaming quote update interval for liquid instruments | 10 to 250 ms | Track event timestamps and detect a quiet or disconnected feed before using its prices. |
| Request rate limit | 5 to 60 requests per second | Use bounded queues and backoff; confirm the actual limit for each endpoint and account. |
| Order-history retention available by API | 1 to 90 days | Persist your own events so a restart does not depend on a short broker history window. |
Use a monotonic local clock for elapsed-time checks and retain the broker's event timestamp for ordering and audit. Keep a feed-health indicator, such as the age of the latest valid quote. A strategy can then stop opening positions when data exceeds its freshness threshold, rather than trading on a plausible-looking but old price.
An accepted request is an acknowledgement, not an execution report.
Model the order lifecycle explicitly
Broker order states are not always a neat sequence. A request can be pending, accepted, partially filled, filled, pending cancellation, cancelled or rejected. The names differ across APIs, so map broker-specific states into an internal model while preserving the original status and reason code.
Store at least the broker order ID, your client order ID, instrument, side, requested quantity, cumulative filled quantity, remaining quantity, average fill price, status and timestamps. Apply fill events as changes in cumulative quantity, not as assumptions that the requested amount traded. A 100-share order might fill 30 shares, remain open for 70, then receive a cancellation. The first fill still creates exposure.
Cancellation is also a request, not an undo button. A fill may arrive while cancellation is pending.
A replace request can race with an execution of the original order, and some brokers implement replacement as cancel followed by a new order. Recalculate exposure from confirmed fills and open orders after either action.
Use a stable client order ID for each intended order if the broker supports it. Learn whether duplicate submissions with that ID are rejected, returned as the original order, or accepted as separate orders. Do not assume that the word idempotent in a library or API description covers every timeout case.
Make recovery and reconciliation routine
Network failures are normal operating conditions. If the connection times out after order submission, the agent does not know whether the broker received the request.
Sending it again immediately can create a duplicate position. Recovery needs a defined sequence that uses broker state as the source of truth for executions.
- Persist the intended order and its client order ID before sending the request.
- On a timeout, mark the result as unknown. Do not submit a fresh order with a new ID.
- Query by client order ID if supported. Otherwise retrieve recent open orders and executions, then match using available identifiers and order details.
- Apply any confirmed fills to the local ledger, including partial fills received during the outage.
- Only retry when the broker confirms the original was not accepted, or when documented duplicate handling makes the retry safe.
- Reconcile positions, cash and open orders against a broker snapshot before allowing the strategy to resume.
Run reconciliation at startup and after reconnects, not only in practice. Compare both quantities and order states.
If local and broker records disagree, pause new risk, log the mismatch and follow a pre-defined resolution path. Do not silently overwrite the local ledger: retaining the discrepancy helps diagnose delayed events, duplicate orders and mapping errors.
Keep a durable event log containing requests, responses, stream events, timestamps and correlation IDs. Avoid logging secrets or full authentication tokens.
Alerts should distinguish a recoverable feed interruption from a position mismatch or repeated order rejection. Those failures need different responses.
Test the operating limits before going live
A sandbox is useful for checking authentication, schemas and basic order transitions. It usually cannot reproduce real liquidity, queue position, exchange behaviour or the full cost of execution. Treat it as an integration test, not evidence that live fills will match simulated fills.
Test the cases that force the agent to make a decision without a human present:
- Drop the stream while an order is open, then reconnect and compare events with a fresh snapshot.
- Simulate an HTTP timeout after submission and verify that recovery does not create a duplicate order.
- Exercise partial fills, rejected orders, cancel races, market closures and rate-limit responses.
- Restart the process with outstanding orders and check that it rebuilds state before trading resumes.
- Set limits for position size, order value, daily loss and the number of unresolved orders. Check that they apply before submission.
Start with paper trading and small live exposure only after the order ledger, rate-limit handling and kill switch have been exercised. A paper environment such as agentic paper trading can help test the agent's control flow, but its fills should not be treated as a forecast of a live broker's execution. Measure acknowledgement delays, rejection rates and slippage in the actual deployment environment, using typical ranges as a starting point rather than a target.
This advice does not apply in full to a read-only research integration or a workflow where a person reviews and submits every order. Those systems do not need autonomous retry and recovery logic, although they still need clear data timestamps and accurate order information wherever execution is reported.
Frequently Asked Questions
What should a broker API provide for automated trading?
It should provide documented authentication, market and account data, order submission, order status updates and a way to retrieve executions and positions. Rate limits, error meanings and supported order types must also be clear enough to handle in code.
Is an order acknowledgement the same as a fill?
No. An acknowledgement usually means the broker received or accepted the request for processing. The order can still be open, partially filled, rejected or cancelled, so the agent must track later status and execution events.
How should an agent handle a broker API timeout?
Treat the outcome as unknown until the broker's order record is checked. Reuse a stable client order ID if supported, query for the original order and reconcile executions before deciding whether a retry is safe.
Can a broker API sandbox prove that live trading will work?
A sandbox can test authentication, request formats and basic order-state handling. It generally cannot prove live liquidity, queue position, slippage or production reliability, so live behaviour still needs careful measurement.