Agentic Trading Index

Broker API risk controls for unattended trading

Trader reviewing a dashboard with broker API risk controls and order status information
Photo by Rafael Minguet Delgado on Pexels

At the end of a bad week, an operator looks at a dashboard showing three rejected orders, one partial fill and a position larger than the strategy expected. The agent is offline now. The question is whether the broker record, the agent's ledger and the risk limits agree on what happened.

That is the standard a broker API must meet for unattended trading. Order submission is only one part of the interface. Permissions, state transitions, limits, records and failure behaviour determine whether the system can stop safely and explain its actions later.

Make permissions and limits enforceable

Start with the account boundary. Use a dedicated trading account or sub-account where possible, with no withdrawal permission and no broader access than the service needs. Separate credentials by environment and strategy. A paper key should not be able to reach a live account, and a live key should not sit in a developer laptop's configuration file.

Prefer scoped credentials, short-lived access tokens and a documented revocation path. Store secrets in a managed secret store, rotate them on a schedule and alert on authentication failures. If the broker only offers long-lived keys, restrict access by network where supported and treat rotation as an operational task, not a one-time setup.

Broker-side controls matter because the agent can fail or be compromised. Check whether the account can set order-size caps, restrict products, disable short selling, set a maximum position or block trading outside specified hours.

Do not assume that a control shown in the web interface is also applied to API orders. Confirm its scope with the broker and test it in the relevant environment.

Keep a second set of limits in the execution service. Useful controls include:

  • Maximum order quantity and notional value, checked against the current price.
  • Maximum gross and net exposure by account, instrument and strategy.
  • Daily loss and drawdown thresholds, with a clear rule for realised and unrealised P&L.
  • Allowed instruments, order types, trading sessions and short-sale permissions.
  • Price collars that reject orders too far from a fresh reference price.
  • A kill switch that blocks new orders and attempts to cancel working orders.

Independent controls are deliberate duplication. The broker may reject an order after the agent's check, while a local process may catch a strategy error before the request leaves the system. Set conservative defaults for missing data or failed checks. If the risk service is unavailable, do not quietly submit the order without the check.

Design for order state, not request success

An HTTP success response means the broker received or accepted a request. It does not mean the order filled, or that the order remains open.

Treat order state as an asynchronous stream of events. Depending on the broker, an order can be accepted, partially filled, cancelled, rejected, replaced or expired, and messages may arrive late or out of order.

Persist the broker order ID as soon as it is returned. Give each intent an internal ID and use an idempotency key if the API supports one. If a request times out, do not send a second order on the assumption that the first one failed. Query by client order ID, inspect open orders and reconcile fills first. Otherwise, a retry can double the intended exposure.

Cancellation is not an undo button. A fill can occur between the cancel request and its acknowledgement.

A replace request can also create a race between the old and new quantities. Keep the original order live in your internal state until the broker confirms cancellation or replacement, and account for fills received during that interval.

Streaming updates are useful for low-latency state changes, but they are not a complete ledger. Connections drop, messages can be missed, and sequence numbers may restart after reconnecting. Combine streaming with periodic REST reconciliation. Compare positions, open orders, executions and cash balances, then alert when the difference exceeds a defined tolerance or remains unresolved past a time limit.

Rate limits affect the design. Polling every account endpoint once per second may work for one account and fail as strategies, instruments or accounts grow. Use event streams for routine updates, back off on throttling responses, and reserve capacity for cancellations and reconciliation. A rate limit that prevents a cancel request is a risk control problem, not just an integration inconvenience.

Test the operational envelope

Broker specifications vary, so the figures below are typical planning ranges seen across API trading workflows, not guarantees for any provider. Verify actual limits, market-data entitlements and order behaviour in current broker documentation before sizing a system around them.

API characteristicTypical rangeRisk design implicationVerify before launch
REST request allowance1-10 requests per second per account or endpointReserve capacity for cancels and recovery; avoid tight polling loopsWhether limits are shared across endpoints, keys or accounts
Order acknowledgement round trip50-500 ms in ordinary conditionsUse asynchronous state handling and avoid treating latency as failureWhether the response means received, accepted or routed
Fresh quote age for liquid instrumentsAbout 100 ms-2 seconds, depending on feed and transportReject or reprice decisions made from stale reference dataTimestamp meaning, feed delay and entitlement level
Access token lifetimeAbout 15-60 minutes for short-lived tokensRefresh safely and alert before expiry interrupts order managementRefresh-token behaviour and revocation semantics

Test failures, not only a clean order round trip. In a paper or certification environment, exercise timeouts, rate-limit responses, partial fills, rejected orders, duplicate requests, disconnects and session expiry.

Confirm that the agent stops opening risk when it cannot establish account state. A useful test report records the input, expected control, observed broker response and resulting position.

Build the test sequence around a small set of explicit scenarios:

  1. Submit a valid limit order and confirm its broker ID, status and eventual execution record.
  2. Submit an order that exceeds the notional cap and confirm rejection before transmission, then check broker-side rejection separately.
  3. Force a timeout after submission and verify that recovery queries the existing order instead of creating a duplicate.
  4. Drop the event stream during a partial fill, reconnect, and reconcile the final quantity against the broker's execution history.
  5. Trigger the kill switch with working orders and confirm that new risk is blocked while cancellation outcomes remain visible.
  6. Expire or revoke credentials and verify that the agent fails closed, alerts an operator and does not loop through repeated submissions.

A simulator can help exercise these paths before live capital is involved. An agentic paper-trading environment is useful when it exposes order events and failure cases, but its behaviour still needs comparison with the chosen broker. A test environment is evidence about that environment, not proof of live execution semantics.

Keep evidence that can reconstruct a decision

Risk controls need a record of what they checked and what the broker did. For each order intent, retain the strategy and software version, account and instrument, side, quantity, order type, limit price, reference-data timestamp, risk-check result and decision time. Link that record to the broker's client order ID, broker order ID, acknowledgements, fills, cancels and rejects.

Use UTC timestamps with enough precision to order events, and keep the raw broker messages where contract terms and privacy rules permit. Store a normalised event log as well, so monitoring does not depend on parsing old payloads. Protect records from silent edits. Access controls, retention schedules and export procedures should reflect the firm's jurisdiction, broker agreement and applicable recordkeeping obligations.

Do not log credentials or unnecessary personal information. Redact tokens at the application boundary.

A useful audit record explains the decision without creating a second security problem. Retention length is not one universal number: requirements depend on activity and jurisdiction, so obtain compliance advice rather than selecting an arbitrary period because storage is cheap.

Monitor risk and system health together. An agent may be within its exposure limit while operating on stale data, or may have a healthy connection while repeatedly sending rejected orders. Alert on conditions such as:

  • Position or cash differences between the internal ledger and broker account.
  • Orders left in an unknown state beyond a set interval.
  • Repeated rejects, throttling responses or authentication failures.
  • Market data older than the strategy's permitted age.
  • Daily loss, exposure or order-rate limits approaching their thresholds.

Escalation should name an action, not just a metric. For example, on a position mismatch, block new orders for that instrument, reconcile executions and notify an operator.

Set separate rules for cancel failures and account-wide uncertainty. A strategy should not resume automatically merely because the API reconnects; require reconciled state and, where policy demands it, an explicit operator release.

Before deployment, have engineering, risk and compliance agree on the permitted instruments, control owners, escalation path and evidence retained for each decision. The controls should be testable and versioned. A short runbook should explain how to revoke credentials, stop order submission, inspect working orders and recover from a mismatch. Paper trading for agents can support rehearsal, while the live broker's documented constraints remain the source for production configuration.

The mistake most readers will still make is treating a successful order response as proof that the broker, agent and ledger agree on the position.

Frequently Asked Questions

What should a broker API provide for unattended trading?

It should provide scoped credentials, clear order and execution states, documented rate limits, account data and a way to reconcile positions. Broker-side restrictions and reliable cancellation behaviour are also important. The agent still needs independent pre-trade controls.

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

Do not blindly retry. Query by the client order ID or inspect open orders and executions to determine whether the broker received the original request. Retry only when the state is known and the API's idempotency rules permit it.

Which risk limits should run before an API order is sent?

Common checks include maximum order notional and quantity, gross and net exposure, permitted instruments, price collars and daily loss limits. The checks should use current data and fail closed when required inputs are missing or stale.

Are broker API sandbox results enough to approve live trading?

No. A sandbox can test request formats and selected failure paths, but it may not match live liquidity, latency, order handling or market-data entitlements. Confirm broker semantics and reconcile carefully during any controlled live rollout.

What records should a trading agent keep for compliance?

Keep the order intent, strategy version, risk-check result, timestamps, reference-data context and linked broker acknowledgements, fills and cancellations. Retention requirements vary by jurisdiction and activity, so set the schedule with compliance advice.