Agentic Trading Index

What a broker API needs for unattended trading

Trading terminal screens beside notes on broker API requirements for an unattended trading agent
Photo by Rafael Minguet Delgado on Pexels

A broker API is a software interface for reading account data and placing, changing or cancelling trades.

That definition hides the hard part: a successful HTTP response does not prove that an order reached the market, that it filled, or that the agent can recover its true state after a timeout. For unattended execution, the API is a set of behaviours under normal conditions and failure, not just a list of endpoints.

Treat the API as an order state machine

Before connecting a strategy, write down the order states the broker exposes and the transitions it permits. A useful minimum model includes submitted, acknowledged, partially filled, filled, cancel pending, cancelled and rejected. Some APIs add pending-new, expired or replaced. Map the broker's exact status values to your internal model, and preserve the original value for diagnosis.

Track cumulative filled quantity and remaining quantity separately. A partial fill followed by a cancel is still a position, not a failed order.

Likewise, a cancel request is not proof of cancellation: the order may fill while cancellation is in flight. Do not release reserved buying power or submit a replacement until the broker confirms the resulting state or reconciliation resolves the uncertainty.

Build a contract test around each transition. For a 100-share order, test a 30-share partial fill, a cancellation request, and a later fill of 10 more shares. The internal position should change by 40 shares, regardless of how many events arrive or whether they arrive twice. Store broker order IDs, your own client order IDs, event timestamps and raw responses.

Compare API behaviour against typical market ranges, not as service guarantees. Asset class, account type, market session and broker implementation can move results well outside these bands.

BenchmarkTypical market rangeAgent design implication
Order acknowledgement100 ms to 2 sKeep requests asynchronous; a slow response is not a rejection.
Order status update100 ms to 5 sExpect delayed events and reconcile before acting on stale state.
REST request allowance10 to 120 requests per minuteBudget calls by endpoint and reserve capacity for risk and recovery.
Streaming quote cadence100 ms to 2 sMeasure feed age locally and block strategies that require fresher data.
Reconnect gapSeconds to several minutesAssume some events are missed; request snapshots and rebuild state.

Make submission safe to retry

Timeouts create the most dangerous order ambiguity. The client sends an order, the broker accepts it, and the response is lost. If the agent blindly retries, it can create a duplicate position. Use a unique client order ID for every intended order and ask whether the API treats repeated IDs as idempotent. Verify the behaviour in the broker's documentation and in tests. Do not assume that a request ID or HTTP retry provides this protection.

When a submission times out, mark it unknown. Query by client order ID or broker order ID before sending another order. If the API offers no reliable lookup, stop new orders for that instrument and reconcile against open orders, executions and positions. This may delay trading, but it is safer than treating uncertainty as permission to repeat.

Retries should be limited to errors that are genuinely transient. Use exponential backoff with jitter, for example 250 ms, 500 ms and 1 s, then open a circuit breaker rather than retrying forever.

Do not retry validation failures, insufficient buying power or a rejected order without changing the cause. Log the request payload after removing credentials, the response code, latency and retry count.

  • Generate a stable client order ID before the first submission and keep it with the strategy decision.
  • On timeout, query order state before creating a replacement.
  • Set a maximum retry count and a maximum time spent in an unknown state.
  • Make cancel and replace separate state transitions, with explicit handling for fills during the race.

Budget latency, limits and market data

Measure the complete path from strategy decision to broker acknowledgement, and from acknowledgement to fill event. Record median, 95th and 99th percentile latency by endpoint and session.

A median of 200 ms can conceal a 3 s tail that matters to a short-lived signal. Keep separate timings for network time, broker response time and event delivery where the API makes that possible.

Read rate-limit headers if available. Apply a shared token bucket across workers, since five independent processes can each stay within a local limit while exceeding the account limit together. Reserve capacity for cancels, position checks and recovery. When throttled, stop discretionary submissions first. A cancel or risk-reducing action should not compete with routine quote polling for the last available request.

For streamed data, track sequence numbers and timestamps. If there are sequence gaps, stale timestamps or a disconnect, mark the affected symbols unusable until a fresh snapshot has been applied and the stream is caught up. Define a maximum data age per strategy.

A liquid intraday strategy might reject a quote older than 500 ms; a slower strategy may tolerate several seconds. Those are strategy limits, not universal market standards.

Synchronise host clocks with a reliable time service and store event time in UTC alongside local receive time. This helps distinguish delayed broker events from delayed processing in your own system. Also test session boundaries, daylight-saving changes, market halts and instruments with different trading calendars. A valid order at one time of day can be invalid or routed differently at another.

Put independent controls around the strategy

The strategy should not be the only component deciding whether an order is safe. Put limits in an execution or risk service that checks every order before it reaches the broker. Include a maximum order notional, position limit, daily loss threshold, maximum open orders and a limit on order frequency. Set the values from the mandate and instrument characteristics, rather than copying generic examples.

Use broker-side controls where they are available, but do not assume they replace local checks. A local pre-trade control can reject an order before submission; a broker-side limit can still protect the account if your process misbehaves. Test how each control treats open orders, partial fills, short positions, corporate actions and currency conversion. Confirm whether buying power updates immediately or arrives on a delayed account stream.

Separate the kill switch from the strategy process. It should be able to block new orders and, if required by the operating plan, cancel open orders without depending on the strategy loop.

Decide whether it also closes positions. That choice has execution risk: an automatic close can incur spread, slippage or a poor fill during a fast market. Log who or what activated the switch, and require an explicit reset after an incident.

For each order, record the decision inputs, risk checks, final payload and broker outcome. Keep secrets out of logs, rotate tokens, and scope credentials to the minimum permissions available.

A read-only credential for monitoring is useful where the broker supports separate credentials. Test expiry and rotation before live deployment, not during a market session.

Prove recovery before unattended deployment

A sandbox is useful for checking request formats, but it may not reproduce live liquidity, queue position, partial fills or rate limiting. Test the API's mechanics independently from assumptions about fills. Force network timeouts, duplicate events, rejected orders, disconnects and process restarts. After each failure, compare your internal ledger with broker snapshots of positions, open orders and executions.

Recovery should be deterministic. On startup, pause new orders, fetch account state, load open orders and recent executions, then reconcile local state before enabling the strategy. Use a defined lookback that covers the longest expected outage, and detect if the broker's history endpoint cannot return enough records. If the account does not reconcile within a set time, keep trading disabled and alert an operator.

Paper trading helps test the control flow without risking capital, but its fills are simulated and should not be treated as evidence of live execution quality. Agentic paper trading is available from $9.99 a month through FX-Tech. Use a paper environment to exercise order generation, logging and recovery; separately measure live slippage and fill behaviour with small, controlled orders when the deployment process permits it.

Before release, set explicit acceptance thresholds. For example, require 100 consecutive recovery tests with no unexplained position mismatch, zero duplicate orders under injected timeouts, and alerts within 30 seconds of a stale data stream. These are engineering gates to choose and document, not universal broker standards. Run a canary with restricted symbols, small order sizes and a daily loss cap, then expand only after the operational record supports it.

This week, build and run one fault-injection test that times out an order submission, then verifies the agent finds the broker's actual order state without submitting a duplicate.

Frequently Asked Questions

What should a trading agent check before choosing a broker API?

Check order-state semantics, client order ID behaviour, rate limits, streaming data recovery and available account risk controls. Test timeouts and duplicate events, not only successful order submissions.

How should an agent handle a broker API timeout after placing an order?

Mark the order state as unknown and query the broker using the client order ID or broker order ID. Do not submit a replacement until reconciliation confirms that the first order was not accepted.

How fast should a broker API acknowledge an order?

Typical market ranges can run from about 100 ms to 2 seconds, depending on the broker, endpoint, session and network path. Measure latency percentiles in the target environment and design for slower responses without treating a timeout as a rejection.