What a trading API does

An application programming interface (API) is a documented way for one piece of software to request information or actions from another. For a trading bot, the API is often the connection to a broker, exchange, or other venue. The bot sends a request in the format the provider accepts; the provider checks it and returns a response or later update.

A simplified relationship is: trading bot → API → broker or exchange → orders and account data. The API is not the strategy and does not decide whether a trade makes sense. It transports requests and information between systems, subject to the provider's functions, permissions, and operating rules.

This article focuses on how that connection behaves from the bot's perspective. For the larger system context, see Trading Bot Architecture; for a broader introduction to software interfaces across trading workflows, see Trading APIs Explained.

Information and actions an API may expose

Depending on the provider, an API may let software request prices, trades, quotes, instrument details, account balances, positions, and open-order information. It may also accept instructions to submit, amend, or cancel an order, then return status details. Some interfaces provide ongoing updates over a streaming connection; others require the client to request the latest state.

These capabilities are not universal. A provider may restrict which instruments or order types are available, separate market-data access from account actions, or offer different permissions across account types. The documented API behavior and account agreement determine what a particular integration can do. A bot should not assume that a method available in one environment exists or behaves identically in another.

The bot's role can be narrow. It may retrieve data and create alerts but have no order permission. It may prepare an order for a person to approve, or submit and manage orders within its configured scope. The definition of a trading bot includes these different levels of automation; API access alone does not imply autonomous trading.

Authentication and permissions

An API must usually identify the client making a request. Providers may use keys, secrets, tokens, signatures, or other authentication mechanisms. These values establish access; they are not ordinary configuration text and should be treated as sensitive credentials. Never place real secrets in public source control, screenshots, example articles, or logs.

Permissions define what authenticated software may do. Read-only access may permit data and account queries while preventing order actions. Trading permission can enable order operations and carries greater consequence if a credential or program is misused. Where a provider offers permission scopes or access restrictions, grant only what the workflow needs. This is the principle of least privilege.

Store secrets using an appropriate protected mechanism for the environment, restrict who and what can read them, and avoid printing them during debugging. Separate development or test credentials from production credentials so that experiments cannot unintentionally operate on a live account. If a credential may have been exposed, use the provider's documented revocation or rotation process and investigate its use.

Permissions and account controls vary among providers. A bot's safeguards should be designed around the actual interface and account configuration rather than assumptions based on the phrase “API key.” Documentation should specify which credentials are used, where they are stored, what each can access, and how access is disabled.

The order lifecycle: a request is not a fill

An order passes through several distinct steps. A bot first forms a decision according to its own logic, then creates an API request containing fields such as instrument, side, quantity, and order instructions. The provider validates the request against its format, account, permissions, market rules, and current conditions. A valid request may be accepted for processing; an invalid or unavailable request may be rejected.

After submission, the order has a state that can change as events arrive. Provider-neutral descriptions include submitted, accepted, partially filled, filled, cancelled, rejected, or expired. Exact names and transitions differ. An accepted order may remain open without executing; a partial fill means only some quantity has traded; a cancellation request may race with an execution already in progress.

The key distinction is that sending a request does not prove that it was received, accepted, or filled. A successful transport response may only confirm receipt of a request. The bot needs to interpret the provider's order identifier and subsequent state updates, then compare them with the account's positions and balances. The lifecycle is part of the architecture of a trading bot, not a single API call.

  1. Decision. The bot's configured logic produces a proposed action; this is not yet an order.
  2. Request. The client submits a formatted instruction using an authenticated API operation.
  3. Validation. The provider checks permissions, parameters, account conditions, and applicable venue rules.
  4. Order state. The request can be accepted or rejected, then remain open, partially fill, fill, expire, or be cancelled.
  5. Account update. The bot reconciles fills and resulting balances or positions with provider records.

A robust client records identifiers and state transitions so it can determine which event belongs to which request. It should not infer completion merely because its local function returned without an error.

Failures, timeouts, and duplicate requests

Failures can occur at different layers. Authentication may fail because a credential is invalid or lacks permission. A request may contain an unsupported order type or malformed quantity. The provider can reject an order based on its rules or current account state. Rate limits can defer or reject requests when a client sends too many within a defined period.

Network errors and timeouts are especially ambiguous. If a client sends an order and then loses the connection before receiving a response, it may not know whether the provider received it. Repeating the same request without first checking its state can create a duplicate order. A client should use provider-supported identifiers or idempotency behavior where available, and reconcile state before deciding whether a retry is safe.

Provider outages, delayed updates, stale account information, and reconnects can also leave the bot with an incomplete view. Recovery logic should distinguish a definite rejection from an unknown outcome. Depending on the workflow, it may pause new order actions, query current orders and positions, or require a person to review an unresolved state. Retrying indefinitely or treating every failure as a transient network problem can compound an incident.

Failure handling should be explicit and observable. Record the operation, request identifier, response category, and timing without recording authentication secrets. Alerts should indicate whether the bot has stopped acting, has an order in an unknown state, or needs reconciliation. The correct response depends on the bot's permissions and purpose.

Reconciling bot state with venue state

A bot maintains an internal view of its requests, open orders, fills, and positions. That view can diverge from the broker or exchange if a response was missed, events arrived out of order, a process restarted, or a person changed the account outside the bot. The venue's current records may therefore differ from what the bot believes is true.

For example, the bot may still mark an order as open even though the venue has filled it. If it acts on its stale local state, it could submit another request or calculate risk from an incorrect position. A reconciliation process periodically or event-by-event compares local identifiers and quantities with provider state, investigates differences, and updates the internal record under defined rules.

Reconciliation is not just a final reporting step. When order state is uncertain, the bot may need to stop further actions until it can establish what happened. Logs should preserve the sequence of requests and updates so an operator can distinguish a missed event from an actual venue rejection or a manual account change. The broader system flow and position handling are explained in the bot architecture guide.

Request limits and controlled retries

Providers commonly limit the volume or pace of requests to manage shared capacity and protect service reliability. Limits can differ by operation, account, or interface. A client should read and follow the provider's current documentation rather than assume one request rate applies everywhere.

A bot can reduce unnecessary traffic by requesting only the information it needs, using supported batching, and preferring a stream for suitable updates where the provider offers one. When a response indicates temporary throttling, a bounded backoff can space subsequent attempts. The client should also respect any retry guidance supplied by the provider.

Uncontrolled retries can create a loop of repeated requests or duplicate actions, especially when the outcome of an earlier order request is unknown. Read-only data requests and order-changing operations may need different retry policies. Before retrying an uncertain order operation, check whether the original request exists or use a provider-supported mechanism designed to prevent duplicate processing.

Request-response and streaming interfaces

A REST-style interface commonly follows a request → response pattern: the client asks for a resource or submits an action, and the server returns a response. It can be suitable for discrete operations such as querying balances or submitting a particular request. The client may need to make another request to check for later changes.

A WebSocket or other streaming interface maintains a connection over which updates can arrive over time. A service may use it for market observations or order events, but stream availability and message behavior depend on the provider. A persistent connection can still disconnect, miss data, or require resubscription and state recovery.

Some systems use both: request-response operations for commands or snapshots, and a stream for ongoing updates. A stream should not automatically be treated as a complete permanent record; reconnect logic may need to request a fresh snapshot and reconcile it with locally recorded events. The integration should define how the two channels are combined.

Hypothetical order-flow example

Imagine a hypothetical bot that is allowed to submit orders only after a configured rule and risk check both pass. It receives a current data update, evaluates its rule, and creates a proposed order. Before submission, it checks that its API credential has the required permission and that the account state it last retrieved is recent enough for its own policy.

The bot sends a request with a client-side identifier. The provider validates the fields and acknowledges the request, returning an order reference. The acknowledgment says the order was accepted for processing, not that it filled. A later update reports that part of the quantity executed; the bot records that event, updates its expected position, and queries or reconciles the venue's account state.

Suppose the connection drops before the next status update. The bot does not assume the remaining quantity is either still open or cancelled. It pauses additional actions for that order, reconnects, retrieves current order and position information, and reconciles the result before continuing. This hypothetical flow illustrates API and state handling only; it makes no claim about a trading outcome.

Use the provider's interface deliberately

Before connecting a bot, document which endpoints or streams it uses, what data each returns, which account actions are permitted, how order states are reported, and what limits or recovery behavior apply. Test rejected parameters, missing permissions, timeouts, reconnects, and state queries in an appropriate non-production environment where available.

A provider's API is one dependency in a larger system. The bot still needs clear decision boundaries, risk checks, records, and monitoring. For a staged process that exercises these connections and failure cases, see How to Test Trading Bots. After deployment, bot risk management addresses failure controls, while monitoring and maintenance covers ongoing system health. The general Trading Bots hub links this venue-specific material with the rest of the cluster.