
After we canceled an unfilled AAPL paper buy order, the account still held 1 AAPL share. The final order showed zero filled quantity. A position snapshot saved before submission established that the share was already there.
Trace before trade is a proposed pattern for linking the application’s instruction and approval to Alpaca’s order records. A developer investigating an AI-assisted order can then review why it was submitted, follow the outcome, and identify what remains unresolved.
This example was conducted entirely in Alpaca's simulated paper trading environment and did not involve real money or actual market executions.
Key takeaways
- Keep the decision and the order history together. Save the original instruction, application approval, exact request, and broker records so a reviewer can reconstruct the sequence.
- Read a canceled order alongside its fills and positions. In the AAPL paper run, zero filled quantity, activity records, and a pre-submission position snapshot explained why 1 share remained.
- Resolve uncertain submissions before retrying. Assign a client order ID before submission and use it to investigate an ambiguous response. Wait for Alpaca Support or the trading team to confirm the outcome before resending.
- Understand the limitations of automated controls. Maintaining an order trace can assist with identifying and investigating errors but does not prevent unintended orders, system failures, or financial losses when trading in live accounts.
Following the AAPL order
We’ll follow the AAPL paper order from submission through cancellation and reconciliation. Alpaca supplies the account, asset, order, position, and activity data needed to explain that outcome.
For an AI-assisted workflow, your application must also retain the original instruction, proposed request, approval policy, and evidence behind any recovery action. Keeping those records together lets the next person review the decision alongside the broker’s records.
Assign ownership at each handoff
The application's side of the order can span several components. For example, an agent prepares the request, a policy service authorizes it, and a background process checks the outcome. Roles can share a component where policy allows, provided the trace records who or what performed each step.
| Role | Responsibility in the trace |
|---|---|
| Principal | The person or entity on whose behalf the workflow runs. In this paper example, the principal is the paper-account holder. |
| Operator | The application, agent, or person that interprets the instruction and prepares the candidate request. |
| Authorizer | The human or policy service that records whether the request satisfies application-level policy. |
| Executor | The authenticated component that submits the application-approved request to Alpaca through the selected interface. |
| Verifier | The application, service, or person that follows the order state, resolves exceptions, and reconciles the outcome. |
The application remains responsible for authorizing requests and keeping the approval records, trace, and supporting evidence. Permission to prepare an order does not grant submission permission or satisfy a required separation of duties.
Preserve what was known before submission
The operator begins by turning the instruction into a request that can be reviewed. For a whole-share equity order like the AAPL example, that means a symbol, side, quantity, order type, time in force, and any required price fields, while short-sale and options workflows need controls of their own. Alongside the request, the application records the intended environment, a preassigned client_order_id for recovery, and timestamped observations of the account, asset, and market session.
Approval means the candidate request passed the application's pre-submission policy when that policy ran. By the time Alpaca receives the request, the account and market observations behind the approval may be stale, and Alpaca checks the authenticated request against the account, asset, session, and order constraints in force at that point. A complete trace can explain why the application approved an order, but it cannot guarantee acceptance, execution, or safety.
Keep the approved request immutable. Append later observations with their source and observation time, so a reviewer can tell what was known at approval from what became clear afterward. A fresh account snapshot cannot stand in for the one used to authorize the order. In the AAPL run, a snapshot taken after cancellation could show the share, but only the one saved before submission could establish that it predated the order.
Keep the request and its evidence together
The records saved before submission give us a starting point for the investigation. As the order moves from approval to reconciliation, each phase adds evidence for a different decision.
| Phase | Evidence to preserve | Decision supported |
|---|---|---|
| Before submission | Original instruction Named roles Application policy and approval Timestamped account, asset, buying-power, and market-session observations Exact request Interface client_order_id |
Whether the candidate order satisfies the application's policy for submission |
| After Alpaca responds | Returned record, Alpaca order ID, client_order_id, and first observed order state. Preserve HTTP status and X-Request-ID when the interface exposes them. |
How the application correlates, retrieves, and follows the order |
| Through reconciliation | Observed lifecycle events Exceptions Recovery actions Fills Position, account, and activity evidence Verifier conclusion |
Whether evidence supports reconciliation, leaves an unresolved gap, or permits documented closure by exception |
An account_checked flag set to true records that a check ran, but a reviewer also needs the account values behind it. Save those values, or a durable snapshot reference, with the source, its timestamp when available, and the application's observation time, so the record shows eligibility and buying power as the application observed them before submission.
Assign client_order_id before submission, because a preassigned ID lets the application find the order if the submission response is lost. Generate it once per logical order attempt, for example as a 36-character UUID, and keep it no longer than Alpaca's 128-character limit.
Retain the same ID when retrieving or reconciling that attempt. Alpaca can generate an ID when the field is omitted, but the application would then learn it only from the submission response. Use the identifier for correlation and retrieval, without assuming a universal idempotency guarantee.
The JSON below is an illustrative record that your application would create and store. It is not a response from an Alpaca endpoint. It keeps the instruction and approval attached to the exact request, so they can be reviewed alongside the order’s outcome.
{
"trace_id": "tbt-paper-001",
"trace_status": "open",
"environment": {
"intended": "paper",
"evidence_ref": "resolved-config-001"
},
"roles": {
"principal": "paper-account-owner",
"operator": "order-agent-01",
"application_authorizer": "policy-service-01",
"executor": "trading-service-01",
"verifier": "reconciliation-worker-01"
},
"instruction_ref": "instruction-001",
"observed_state_refs": [
"account-snapshot-001",
"asset-snapshot-001",
"clock-snapshot-001"
],
"request": {
"request_ref": "request-tbt-paper-001",
"symbol": "AAPL",
"side": "buy",
"qty": "1",
"type": "limit",
"limit_price": "1.00",
"time_in_force": "day",
"client_order_id": "tbt-paper-001"
},
"approval": {
"decision": "approved",
"approved_request_ref": "request-tbt-paper-001",
"approved_at_ref": "approval-time-001",
"policy_ref": "paper-equity-policy-v1",
"evidence_ref": "approval-event-001"
},
"submission": {
"status": "pending",
"alpaca_order_id": null,
"x_request_id": null
},
"reconciliation": {
"status": "open"
}
}The JSON uses placeholder references. In your application, each approval reference must lead to the actual approval time, policy version, and authorization event for that exact request. Keep full responses in controlled storage, and if you add a cryptographic hash, specify whether it covers the submitted bytes or a defined canonical JSON serialization.
In the submission block, the null alpaca_order_id and x_request_id are pending because the request has not been sent. Later nulls can mean something else, so when an order is canceled, rejected, expired, or unfilled, distinguish pending evidence from evidence that is absent or not applicable.
Save the approved request and its approval record before submission, and coordinate approval with the application’s order state through atomic local transitions or a single writer. Even then, the broker’s order and the local record cannot be committed as one local transaction, so a crash between sending and recording the response still requires reconciliation. When timestamps alone leave the order of events uncertain, record an application sequence alongside them.
Follow the Alpaca order to a reconciled outcome
Once the request is sent, we can begin following Alpaca’s handling of it. The submission response is one observation, and a successful response alone cannot establish a fill. Alpaca documents new as the usual initial state and accepted as a less common state before routing. In the paper run described here, the submission response showed pending_new, followed by a new event on trade_updates. Later observations may include partially_filled, filled, canceled, expired, replaced, or rejected. Retain the states the application actually saw, without filling gaps from an expected sequence.
To capture lifecycle events, connect a separate WebSocket client to wss://paper-api.alpaca.markets/stream, authenticate, and wait for the server to confirm subscription to the trade_updates stream before submitting the paper order. Save the messages received for that order, including the event, order ID, client_order_id, and available timestamps.
An order lookup returns the current order record. It does not replay the event stream. Polling can retain successive snapshots but may miss intermediate transitions. For recovery and reconciliation, retrieve the order by Alpaca order ID or client_order_id.
Keep four identifiers distinct
Four identifiers follow the order through these observations. Your application assigns two of them and Alpaca assigns the other two, and each connects a different part of the history.
| Identifier | Assigned by | What it connects | Primary use |
|---|---|---|---|
trace_id |
Your application | The complete application-maintained workflow history | Find and reconstruct the trace |
client_order_id |
Your application | The candidate request and Alpaca order | Correlate, retrieve, and govern recovery |
| Alpaca order ID | Alpaca | The returned order resource | Retrieve the order and observe its lifecycle |
X-Request-ID |
Alpaca | One Trading API request and response | Correlate support and troubleshooting records |
The order response body supplies the Alpaca order ID and client_order_id. X-Request-ID is an HTTP response header, not a field in that JSON body. A direct HTTP client can retain it from the response headers.
With the CLI, add --debug to inspect request and response headers on stderr. Normal JSON output omits them. Debug output also includes bodies, so control access, retention, and redaction. Keep credentials and authorization headers out of retained evidence.
Resolve an ambiguous submission before retrying
A timeout or ambiguous submission result leaves the application unsure whether Alpaca created the order. Retrieve it by client_order_id, or by Alpaca order ID if the response supplied one, and check the Trading API dashboard. A failed lookup does not establish that no order was created. Contact Alpaca Support and wait for Support or the trading team to confirm the outcome before resending or treating the timed-out order as canceled.
Automatic retries can get ahead of that lookup by resending the request before the application regains control. The CLI retries HTTP 429, 500, 502, 503, and 504 responses, including order submissions, for up to 3 total attempts, and it exposes no setting to disable them. A workflow that requires confirmation before resubmission needs a submission client with automatic order-submission retries disabled. Preserve the submission attempt’s records for lookup and reconciliation, retaining the original client_order_id.
Unintended or duplicate order submissions can result in unexpected positions and financial losses in live trading accounts. An order trace may help identify these events but does not guarantee their prevention.
Recovery establishes whether an uncertain submission produced an order. Reconciliation then follows the outcome by comparing the order and fills with position, account, and activity records. Save the evidence for each match or mismatch, and name the owner and closure condition for any exception.
Account for client behavior
What we can retain also depends on the client. The trace needs to show which account and environment it actually used, along with the response details it exposed. These details connect the request to the broker records needed to investigate it.
- The Trading API exposes account, asset, order, position, activity, and order-lifecycle records, including response headers available to a direct HTTP client.
The CLI (version 0.0.15) prints JSON by default. Its order commands have no confirmation prompt, and
--dry-runprints the request body without submitting it.For the paper-or-live choice, the
ALPACA_LIVE_TRADEenvironment variable takes precedence over the profile when it is nonempty, with a trimmed, case-insensitivetrueselecting live and any other nonempty value selecting paper. When the variable is absent or empty, credentials loaded from a profile follow that profile’slive_tradesetting, and every other case falls back to paper.The dry-run body establishes neither the profile nor the endpoint, so resolve both separately.
Alpaca's MCP server (version 2.4.1) exposes Trading API and Market Data API operations through configurable toolsets.
The
ALPACA_PAPER_TRADEenvironment variable defaults totrue, but onlytrue,1, oryes(case-insensitive) keep the server in paper. Any other value selects live, including a typo or surrounding whitespace, so have your configuration layer accept only an explicittrueorfalsebefore startup.Successful stock-order tool results wrap the parsed API body without the HTTP response status or
X-Request-ID. API-error results can include an HTTP status. Preserve the fields each result exposes, and mark missing transport metadata as unavailable. Approval, trace retention, and reconciliation still belong to the application.- Alpaca's order API reference describes the request fields and response schema used by clients and generated tools.
The two environment switches fail in opposite directions, since a mistyped CLI value falls back to paper while a mistyped MCP value selects live. Save the resolved configuration, endpoint, and account with the trace so the behavior of a request can be checked against the client that sent it.
Verify serialization before contacting a trading endpoint
Before submitting an order, the CLI's --dry-run flag shows the serialized request without sending an order. It still requires a complete credential bundle. The AAPL command below produces the request body shown afterward. This is not an order response.
alpaca order submit \
--symbol AAPL --side buy --qty 1 \
--type limit --limit-price 1.00 \
--client-order-id tbt-paper-001 --dry-run{
"client_order_id": "tbt-paper-001",
"limit_price": "1.00",
"qty": "1",
"side": "buy",
"symbol": "AAPL",
"time_in_force": "day",
"type": "limit"
}The output shows the serialized fields, including day as the default time_in_force for this equity request. An unset advanced_instructions field is omitted. Confirm the account and environment separately, then retain the broker records needed to follow the order through reconciliation.
What paper evidence can establish
The AAPL example ran entirely in paper, which bounds what its records can establish. Alpaca paper trading uses the same API specification as live trading through a separate endpoint and paper-account credentials, so a reviewer confirms a paper run from the saved endpoint and account. Orders stay in a simulation, with fills modeled from market quotes rather than routed to a live exchange.
Paper trading omits or simplifies market impact, information leakage, latency-related slippage, queue position, price improvement, regulatory fees, dividends, and available liquidity. Live execution quality and strategy performance therefore need separate evidence.
Reconstruct the AAPL order from its records
We can now return to the canceled AAPL order and read the request, order history, fill activity, and position snapshots together.
The request was to buy 1 AAPL share at a $1.00 day limit, with a unique client order ID. The $1.00 limit was an illustrative input for the paper example, rather than a market-price estimate. The records below show how to follow the request through retrieval and cancellation, then explain its effect on the account.
- The submission response showed
pending_new. Its body supplied the Alpaca order ID andclient_order_id, whileX-Request-IDcame from the HTTP response headers. - A lookup by the same
client_order_idreturned the same order in thepending_newstate before cancellation. This lookup supplied a current order record, rather than a replay of lifecycle events. - The saved
trade_updatesmessages recordedpending_new,new, and thencanceled. These messages supplied lifecycle observations separately from the order lookup. - The final order was
canceledwithfilled_qty0. Fill activity showed no fills for the order or other fills during the observation window. Both AAPL position snapshots showed 1 share, and the order no longer appeared among open orders.
Together, these records explain why 1 share remained after cancellation. The application’s instruction and approval records are still needed to reconstruct the decision that led to submission.
Close the trace on evidence
Someone taking over an order investigation should be able to see what the application approved, what Alpaca recorded, and what still needs checking. Automate the checks you can and review the rest periodically, with a separate reviewer where policy requires one.
Mark the broker outcome reconciled when the retained order and account evidence supports it. A complete trace must also connect that outcome to the original instruction, approved request, and approval evidence. If a link is missing or records disagree, keep the trace unresolved and assign an owner and a next check. Where application policy permits closure by exception, record the authorization, missing evidence, and disposition under a distinct application status for closure by exception.
Try a paper trace
To try this in your own workflow, revisit one paper order after the session ends. Share the saved records with a teammate who was not part of the agent conversation, and see whether they can reconstruct the approved request, the final position, and any unresolved discrepancy.
- Set up the paper environment. Create an Alpaca account and follow the paper-trading guide.
- Choose an interface. Use the MCP server setup or CLI guide to reproduce the request.
- Follow the outcome. Reconcile the order records with account activities, keeping any missing evidence visible in the trace.
Disclosures
The content of this article is for general informational purposes only. All examples are for educational and illustrative purposes only. The trading example was conducted in a simulated paper trading environment and did not involve real money or actual market executions.
Information and outputs generated through Alpaca’s CLI, MCP Server, or connected AI agents are provided for educational and informational purposes only and do not constitute investment advice or a recommendation to buy, sell, or hold any security. AI-generated outputs may contain errors, omissions, inaccuracies, or outdated information and should be independently reviewed and verified before use or reliance. Alpaca does not recommend any specific security, or investment strategy. Users should conduct their own due diligence before making investment decisions.
AI-assisted and automated trading involve risks, including incorrect or unintended instructions, programming errors, configuration errors, API connectivity issues, system failures, and unintended, missing, or duplicate orders. These risks may result in financial losses when using live brokerage accounts. Application-level approvals, automated checks, logging, and reconciliation procedures cannot guarantee the prevention of errors, unintended trading activity, or losses. Users should independently verify their trading environment and monitor automated trading activity.
The Paper Trading API is offered by AlpacaDB, Inc. and does not require real money or permit a user to transact in real securities in the market. Providing use of the Paper Trading API is not an offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, given or in any manner endorsed by AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate and the information made available through the Paper Trading API is not an offer or solicitation of any kind in any jurisdiction where AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate (collectively, “Alpaca”) is not authorized to do business.
Securities brokerage services are provided by Alpaca Securities LLC (dba "Alpaca Clearing"), member FINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.
This is not an offer, solicitation of an offer, or advice to buy or sell securities or open a brokerage account in any jurisdiction where Alpaca Securities is not registered or licensed, as applicable.
For additional information, please review Alpaca's Disclosure Library, including the Risks of Automated Trading disclosure.
