A successful order response doesn't mean you bought anything. It usually means a broker received your request, while execution, rejection, or a partial fill arrives later. That gap, plus incomplete price data and duties you still own after outsourcing execution, causes most brokerage API failures. U.S. market structure explains part of the problem. The FINRA 2025 Industry Snapshot reports 16,347,249 listed-equity executions on alternative trading systems in 2024, up from 7,791,035 in 2021, an increase of approximately 110%. If your app can't tell exchange trading from off-exchange trading, it can't fully explain volume, fills, or prices.
Table of Contents
- Core Brokerage API Endpoints at a Glance
- What a Brokerage API Is and How It Connects
- Authentication Methods Compared and When to Use Each
- Market Data Coverage, Latency and Delay
- How to Place, Track and Cancel an Order
- Order States and Pre-Trade Controls Explained
- Error Codes, Rate Limits and Retry Handling
- Compliance Duties Your App Still Owns
- Trading-App Use Cases and What Each Needs
- Shortlist and Test a Brokerage API Before Building
Core Brokerage API Endpoints at a Glance
Start by mapping product features to endpoint groups. Names differ between providers, but a production brokerage API usually exposes the same nine areas. If one group is missing, you'll feel it later in reconciliation, support, or audit work.
| Endpoint group | Typical calls | What it returns |
|---|---|---|
| Session and authentication | Token issue, refresh, revoke | Access token, expiry, scopes |
| Accounts | Get account, get account status | Account ID, status, currency, trading restrictions |
| Balances and buying power | Get balances | Cash, buying power, margin, equity |
| Positions | List positions, get position | Symbol, quantity, average cost, market value |
| Assets and instruments | List assets, get asset | Symbol, exchange, tradability, fractionable flag |
| Market data | Latest quote, last trade, historical bars | Bid and ask, last trade, OHLCV by interval |
| Orders | Place, get, replace, cancel | Order ID, status, filled quantity, timestamps |
| Activities and statements | List fills, dividends, transfers | Ledger entries for reconciliation |
| Streams and webhooks | Trade updates, quote streams | Pushed order-state and price events |
How to read the map
Accounts and balances tell you whether trading is allowed and what the customer can spend. Positions and activities are your source for holdings and the ledger behind them. Assets prevents a common error, offering a symbol that's visible but not tradable, not fractionable, or restricted for that account. Market data supplies quotes, trades, and bars, but you still need to know its venue coverage and delay.
REST endpoints answer a question at the moment you ask. Streams and webhooks report changes when they happen, such as a fill, rejection, or new quote. Most trading apps need both. Polling an order endpoint every second burns rate limits and still feels slow to users. A live stream without a REST fallback leaves you blind after a disconnect.
Lookup rule: Keep this table beside your product spec. If a feature can't name its endpoint group, its fallback, and its reconciliation source, it isn't ready to build.
A trading app usually starts with accounts, balances, assets, and orders. A portfolio dashboard starts with positions, activities, and historical bars, then adds streams only where live prices change a user decision.
What a Brokerage API Is and How It Connects
A brokerage API is the programmatic link between your application and a licensed broker-dealer that executes trades, holds custody, and supplies account data. Submitting an order does not make your app the broker. The hard parts are knowing which party owns each duty, which data source may answer each question, and what an order state means after the first response.

Four parties sit in the chain. Your application presents the workflow. The broker-dealer accepts and routes orders and maintains customer accounts. A clearing firm settles trades and holds assets through the custody chain. Data providers supply quotes, trades, and reference data, sometimes through the broker and sometimes under a separate contract.
Say a user taps Buy for 10 shares. Your server authenticates, checks account status and buying power, then sends a REST request over HTTPS. The broker returns JSON with an order ID and an initial state. Treat that as a receipt. Your server then listens on a WebSocket stream or webhook for routed, partially filled, filled, or rejected updates, and it updates cash and positions only from confirmed executions and activity records. If the app credits shares at acknowledgement, a later rejection becomes both a customer incident and a reconciliation break.
Requests, streams, and environments
Most modern platforms use REST over HTTPS returning JSON for balances, positions, and order submission. They use WebSocket or server-sent streams for live events. Some institutional connections use FIX, which suits high-volume order flow and strict session controls, but it is heavier to build and operate. Choose FIX when message volume, venue access, or counterparty requirements demand it, not for status.
Use a sandbox or paper account first, but expect gaps from live trading. Paper fills can be instant, halts may not appear, and partial fills may be rare. Record rate limits per minute and per day in your design, especially for market data and order polling. For allowlists or webhook source checks, confirm which public IP your server presents before blaming the broker; a lookup that can retrieve IP address information helps separate an egress or NAT change from a bad signature.
Fintech apps, robo-advisors, banks, brokers, research desks, and academic teams all build on these connections. Their endpoint calls look similar. Their risk, supervision, and evidence duties do not. The easy part is sending POST; the owned part is proving what happened, when, and from which source.
Authentication Methods Compared and When to Use Each
Pick authentication by who's acting and what they can damage. A read-only market data call from your server isn't the same risk as a token that can place orders or move money from a customer's account.
| Method | Best for | Main risk | Control to add |
|---|---|---|---|
| API key | Server-to-server market data and read-only account data | Leaked key gives full access as its owner | Keep server-side and rotate from the dashboard if exposed |
| OAuth 2.0 authorization code with PKCE | End users connecting their own brokerage accounts | Authorization code interception | PKCE, strict redirect URI matching, short-lived tokens |
| OAuth 2.0 with FAPI profile | High-risk reads and trade or funding writes | Tampered requests and token phishing | State hash, signed ID token, JWKS key verification |
| Mutual TLS or signed requests | Institutional server links with fixed IP or certificate policy | Certificate or key management failure | Scheduled rotation and tested failover |
| Username and password | Not recommended for brokerage APIs | Credential reuse and no scope control | Replace with OAuth 2.0 or an API key with scopes |
An API key authenticates requests as its owner, so keep it server-side and rotate it from the dashboard if it's exposed. Never ship a key with order permissions inside a browser bundle or mobile app. Anyone who extracts it becomes that owner until you revoke it.
For customer account access, the OpenID Financial-grade API profile strengthens OAuth 2.0 for high-risk read and write access. It specifies protections against authorization-request tampering, authorization-response tampering, code injection, state injection, and token-request phishing. Its guidance includes TLS for all interactions, a state hash (s_hash), a detached-signature ID token, and public keys through a JWKS URI.
Production baseline
Use authorization code flow with PKCE, strict redirect URI matching, nonce validation, short-lived access tokens, and refresh-token rotation or sender-constrained tokens where supported. Split scopes into portfolio read, order placement, cancellation, and funding. A portfolio widget shouldn't hold a token that can trade. For a practical breakdown of roles and scopes, review guidance on managing tokens and access permissions before you freeze your permission model.
Fail closed when authorization is uncertain. Test token expiry, refresh, revocation, and key rotation before go-live, not during an incident. Log who authorized what, with account ID, scope, token ID, and timestamp.
Never place a bearer token that can submit orders inside a browser or mobile front end.
Market Data Coverage, Latency and Delay
Two APIs can both return a field called last price and describe different markets. U.S. equities trade across exchanges, alternative trading systems, and other off-exchange venues. Coverage is the first question to settle, before latency or cost.
The Massive stocks API overview gives a useful scale check. IEX represents approximately 2.5% of U.S. market volume, whereas a Securities Information Processor feed is designed to cover 100% of U.S. market volume across exchanges. Off-exchange venues report executed trades to FINRA on a short regulatory delay, so a trade report from an ATS can arrive after the consolidated quote has already moved. A feed that looks slow may be honest about venue order.
What to verify for every stream
- Source and consolidation: Is it one venue, a consolidated SIP feed, or a vendor blend that includes ATS and OTC prints?
- Timestamp meaning: Exchange time, SIP time, vendor receipt time, and your server's receipt time are four different clocks. Mixing them in one calculation inflates or hides latency.
- Delay: Is the stream real time or delayed, and does your licence permit display to your users?
- Trading status: Do you receive halts, auction states, and pre-market or after-hours flags with the quote?
- Historical completeness: Do bars use the same universe as the live feed, or do they exclude ATS and OTC activity?
Wrong coverage fails in specific ways. A dashboard built on one exchange understates cumulative volume. A router using delayed or non-consolidated quotes chooses worse prices. A backtest that excludes off-exchange activity misstates liquidity and fills. Historical open, high, low, close, and volume records are useful only when you know the interval rules and the venues behind them.
Run a simple test during regular hours. Request the same active symbol from two sources at the same moment. Compare last trade, best bid and ask, cumulative volume, and timestamps. A sharp volume difference usually means you are comparing a single venue with a consolidated feed, not a coding bug.
Screening inputs deserve the same discipline. We offer a financial data API for application inputs, and our API does not include real-time stock prices. Keep price sourcing and eligibility sourcing as separate contracts in your architecture, each with its own timestamps and failure handling, so a stale quote never becomes a stale verdict.
How to Place, Track and Cancel an Order
Treat order placement as a state machine, not a single POST. The steps below work in a sandbox first, then in paper trading with halted, illiquid, and partially filled cases added on purpose.

Numbered procedure
- Authenticate server-side. Exchange credentials for a short-lived access token and store it in a server secret store. The usual slip is letting the client call the broker directly, which exposes credentials and bypasses your controls.
- Check buying power and trading status. Read account restrictions, cash, margin, and asset tradability before submission. Insufficient funds and restricted accounts are routine rejections, and they're cheaper to catch before routing.
- Build the order with a unique client order ID. Include symbol, side, quantity or notional amount, order type, limit or stop price where required, time in force, and account ID. Reuse that same client order ID on retries so a timeout doesn't create a duplicate order.
- Submit and record the acknowledgement. Store the broker order ID, request payload hash, response, and timestamps. Show the user a pending state. Don't update the position as if the trade executed.
- Track updates until a terminal state. Subscribe to trade updates by stream or webhook, with REST polling as recovery after disconnects. Our notes on webhook delivery for event updates cover the same delivery pattern you'd use for verdict changes. If no update arrives within your timeout, query by broker ID before you act.
- Handle partial fills explicitly. Read filled quantity and average fill price after every execution report. A 100-share order with 35 filled isn't almost filled for accounting purposes. It's 35 filled and 65 still exposed to price movement or cancellation.
- Cancel or replace by order ID. Send the request, then wait for confirmation. A cancel can lose the race to a fill that occurred at the venue first. Never release reserved buying power or show a final canceled state until the broker confirms it.
Test the awkward cases before launch. Place a limit order away from the market, replace its price, partially fill it if your sandbox supports that, then cancel the remainder. Repeat with a halted symbol and an expired token. If your UI, database, and broker records agree after those cases, your basic order flow is credible.
Order States and Pre-Trade Controls Explained
Order state names carry legal and accounting meaning. If your app collapses them into processing and done, support teams can't explain what happened and users will assume a fill that never occurred.
| Order state | What it means | What your app should do |
|---|---|---|
| Received | Broker accepted the request for processing | Store the broker ID and show as pending |
| Accepted | Passed pre-trade checks | Keep waiting for routing or fill updates |
| Routed or pending | Sent to a venue, not yet executed | Set a timeout and poll if no update arrives |
| Partially filled | Some quantity executed | Show filled quantity and average price, keep watching |
| Filled | Full quantity executed | Update positions and reconcile with the execution report |
| Canceled | Cancellation confirmed | Release reserved buying power and show final quantity |
| Rejected | Failed a check such as funds or restrictions | Show the reason code and do not retry blindly |
| Expired | Time in force ended without a full fill | Close the order and show the unfilled quantity |
Why orders get blocked
Under SEC Rule 15c3-5 on market access, broker-dealers providing direct or sponsored access must maintain documented controls for financial, regulatory, and operational risk. Controls run before routing and reject orders that exceed customer or firm credit or capital limits, violate price or size tolerances, duplicate recent orders, target restricted securities, or fail required regulatory checks. The rule also expects access limited to authorized users and regular review, including at least an annual business-activity review.
Your application still needs its own server-side layer. Don't trust client-side validation. Enforce per-account and aggregate notional limits, buying-power checks, duplicate detection, restricted lists, and a kill switch that stops new orders without breaking reads or cancellations. Write an immutable audit event for every state change, with actor, account, broker ID, reason code, and timestamp.
Design point: A rejection isn't an API failure. It's often the control system doing its job, and your UI should say which check failed in plain language.
Reconcile daily against broker execution reports and activity records. Flag mismatches in quantity, price, fees, account, or final state for manual review. Keep your local order record, but treat the broker execution report as the execution record when they conflict.
Error Codes, Rate Limits and Retry Handling
Errors need product behaviour, not just log lines. Sort failures into three families first. Validation errors mean the request must change, such as a missing limit price on a limit order. Authentication errors mean refresh or re-issue the token, then check whether the original request reached the broker. Rate-limit responses, typically HTTP 429, mean wait and reduce pressure.
Retry rules that prevent duplicates
- Retry only safe failures. Timeouts, connection resets, and 429 responses can be retried. A validation rejection won't succeed unchanged.
- Back off exponentially with jitter. Start near one second, double the delay, add random jitter, and cap the wait. Synchronized retries from many workers create a second outage.
- Reuse the same client order ID. Every retry of an order submission must carry the original idempotency key or client order ID. Generating a fresh ID after a timeout is how duplicate orders happen.
- Query before resubmitting. After a timeout, look up the order by client order ID or broker ID. If it exists, resume tracking it. Don't send a replacement order on suspicion.
- Stop and escalate. After a fixed number of attempts, move the item to a manual review queue with the full request history. Infinite retries turn a broker incident into corrupt local state.
Check rate limits per minute and per day against peak load, not average load. Market open, earnings releases, and rebalancing runs create bursts. Replace broad polling with streams where possible. Cache asset reference data. Batch historical bar requests where the provider allows it. Spread portfolio refresh jobs instead of waking every account at the same second.
Log request ID, endpoint, account ID, error code, broker reason code, attempt count, and client order ID for every failed call. Redact tokens and secrets. When a user asks why an order didn't appear, that log should answer whether your server sent it, the broker rejected it, or the response was lost and recovered by lookup.
Compliance Duties Your App Still Owns
A managed brokerage stack doesn't transfer every duty to the broker. Delegating execution, custody, onboarding, or compliance infrastructure still leaves your firm accountable for supervision, best execution, suitability or Regulation Best Interest, books and records, AML, continuity, privacy, and customer protection. Write down who owns which side before launch, because after the first regulator letter the answer gets expensive.
| Duty | Usually the broker-dealer | Usually your application | Evidence to keep |
|---|---|---|---|
| Best execution | Routing and execution quality | Monitoring fill quality by client | Execution reports and routing logs |
| Supervision of automated tools | Firm-level supervisory system | Testing and approval of each automated workflow | Test records and sign-off history |
| Suitability or Regulation Best Interest | Firm-level review standards | Capturing investor profile and recommendation rationale | Profile snapshots and recommendation records |
| Books and records | Official account and trade ledger | Application-side event log | Immutable audit events with timestamps |
| AML and onboarding | Customer identity and screening | Passing verified data without gaps | Verification results and data lineage |
| Screening decision inputs | Not typically in scope | Methodology, financial inputs, data version and timestamp | Stored inputs for each eligibility decision |
| Corporate actions and rejected orders | Official corporate action processing | Handling in-app status and user notice | Runbook and notification logs |
FINRA Rule 3110 requires a reasonably designed supervisory system, and that obligation extends to automated tools as well as human advisers. In practice each automated workflow needs documented testing, approval, change records, and a named owner. A deploy pipeline alone doesn't satisfy that. If a rebalancing job or an eligibility gate makes a flawed call at scale, examiners ask who supervised it, and "the vendor" is not an acceptable answer.
Three artifacts to produce
First, a responsibility matrix naming an owner for screening decisions, stale data, rejected orders, corporate actions, suitability evidence, incident response, and audit retention. Second, retention rules for event logs and decision records, covering how long each record type lives and where it's stored. Third, a runbook for broker outages, mass rejections, corporate actions, and customer notices, with named escalation paths.
For eligibility-screened trading, record the methodology, financial inputs, data version, security identifier, and timestamp behind each decision. Our guide to Shariah screening for robo-advisors and brokerages shows how that evidence trail works in practice, because a later verdict change shouldn't rewrite why a past trade was allowed.
The trap is confidence created by abstraction. The more managed the stack feels, the easier it is to assume someone else owns the evidence. They often don't.
Trading-App Use Cases and What Each Needs
A brokerage API demo proves the easy thing: a request returns JSON. Production fails on three harder questions: what an order state really means, which venues and corporate actions the data covers, and who owns evidence when a trade is challenged.

| Product | Calls it leans on | Where it usually breaks |
|---|---|---|
| Read-only portfolio tracker | Accounts, positions, activities, historical bars | Transfers, dividends, splits, fees, and delayed-price labels drift apart |
| Robo-advisor rebalancing | Balances, assets, orders, webhooks | Drift math, fractional shares, tradability, and sequencing collide with partial fills |
| Fund and ETF platform | Positions, constituent holdings, weights, corporate actions | A fund-level price cannot show exposure or eligibility inside the basket |
| Retail trading app | Full order flow plus streams | Pending states, halts, extended hours, and cancels after partial fills confuse users |
| Institutional desk or bank product | Streaming or FIX with strict pre-trade controls | Credit limits, restricted lists, allocation, and surveillance evidence dominate |
| Agent-assisted investing | Read endpoints plus constrained order endpoints | Policy enforcement is the product, and authority must stay bounded |
The FCA open finance roadmap points toward permissioned investment data and connected accounts. Interest in AI-assisted investing is rising, while complex, concentrated, private-market, and heavily regulated portfolios still need human oversight.
Design agents with policy-constrained execution. The agent can recommend; deterministic eligibility rules, account permissions, risk limits, and human approval decide execution. Isolate accounts so one agent cannot leak data or authority across customers. Prompt text must never raise a limit. Block or escalate when market or screening data is incomplete, coverage is insufficient, or a verdict changed. For Shariah-focused apps, preserve the methodology, treat null as different from zero, and check ETF constituent coverage before any order is released.
Shortlist and Test a Brokerage API Before Building
Don't shortlist from endpoint lists and pricing pages. Shortlist from behaviour you can observe in a sandbox, documents you can audit, and failure cases you can trigger on purpose.

Evaluation checklist
- Market data source: Which venues are included, what do timestamps mean, and is the feed real time or delayed?
- Order-state model: Are states, reason codes, partial fills, and terminal states documented, with streams or webhooks for updates?
- Sandbox realism: Can you trigger rejections, expiries, cancels, halts, and partial fills, or does everything fill instantly?
- Rate limits and retries: Are limits stated per minute and per day, and are idempotency keys and error codes documented?
- Authentication fit: Does the model match server-to-server access, customer OAuth, or institutional controls without workarounds?
- Reconciliation: Can you export activities, executions, dividends, transfers, and corporate actions in a stable format?
- Support and incidents: Is there a status history, named escalation path, and clear incident communication?
- Contract terms: Who owns data display rights, redistribution limits, audit records, and each compliance duty?
Structure the trial like a test campaign, not a demo. AskYourQA's API testing framework is a useful model for defining cases, expected results, and exit criteria before engineers start building screens.
Run a two-week test with one account. Place, partially fill, cancel, expire, and reconcile at least 50 test orders. Log every discrepancy between your database and the broker's reports. Choose the API whose order-state model and data source you can explain to an auditor in plain language. Build only after that explanation holds under failure cases.
If your brokerage build needs a separate eligibility layer beside execution, Akinda supplies Shariah screening verdicts, reports, methodology data, ETF holdings analysis, and verdict-change events through REST endpoints you can store with each order decision. That gives your team the methodology, inputs, and timestamp evidence a broker execution record doesn't provide. Visit Akinda to review the endpoints and start with the free tier.
