> For the complete documentation index, see [llms.txt](https://docs.anchored.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.anchored.finance/trading-api/getting-started/trader-questions.md).

# API Integration Playbook

Use this page as the practical operating guide for an RWA API integration. Before submitting orders, moving cash, or reconciling portfolio state, verify these request and state checks.

The most important habit is to separate **wallet state**, **mUSD**, **exchangeBalance**, and **final settlement state**. The API connects these systems, but they do not update at the same time.

## Integration Mental Model

```mermaid
sequenceDiagram
    participant Client as Integrator client
    participant API as Trading API
    participant Wallet as User wallet
    participant OCR as OneClickRouter
    participant Router as StockRouter
    participant Cashier as Cashier
    participant Stock as Stock

    Client->>API: GET state
    API-->>Client: musdBalance, exchangeBalance, orders

    alt Self-submit
        rect rgb(232, 244, 255)
            Client->>API: POST /calldata
            API-->>Client: toAddress, value, callData
            Client->>Wallet: submit transaction
            Wallet->>Router: execute calldata
            Client->>API: POST /tx with txHash
        end
    else One Click
        rect rgb(246, 239, 255)
            Client->>API: POST /send
            API->>OCR: submit delegated tx
            OCR->>Router: forward as user
        end
    end

    Router->>Cashier: update mUSD
    Router->>Stock: update orders / stockBalance
    Cashier-->>API: indexed state
    Stock-->>API: indexed state
```

Diagram color key: blue is self-submit, purple is One Click.

For self-submit requests, call the API to build `StockRouter` calldata, submit the transaction with the user wallet, then record `txHash`. For One Click requests, call `/send`; the API submits through `OneClickRouter`. For state reads, the API indexes `Cashier` and `Stock` into fields such as `musdBalance`, orders, and `exchangeBalance`.

`StockRouter` enforces on-chain entry, `Cashier` accounts for `mUSD`, and `Stock` accounts for orders and `Stock.stockBalance`. Build integrations around the async lifecycle instead of assuming a trade is final when the transaction is mined.

## Discover Tradable Stocks

Start every trading flow from the symbol list. Treat a stock token as tradable only when the API marks it tradable for the current `chainId` and `x-api-p`.

1. Call `GET /api/v1/symbols`.
2. Keep only symbols where `tradable` is `true`.
3. Use `contractAddress` as `stockAddress` when building orders.
4. Refresh quote context with `GET /api/v1/prices/{symbol}`.
5. Check `GET /api/v1/corporate-action?symbol=AAPL` when splits/dividends may affect downstream accounting.

Do not hardcode token addresses unless your release process also verifies they match the active API response.

## Check Buying Power

For plain buys, the important value is `musdBalance`, not the cash token `walletBalance`. A user can have USDC in their wallet and still have no `mUSD` until a deposit happens. If the cash token is approved and instant deposit is available, `/orders/with-deposit/*` can deposit and place the buy in one transaction.

| Field             | API meaning                                       |
| ----------------- | ------------------------------------------------- |
| `musdBalance`     | `mUSD` available for buys and withdrawals         |
| `walletBalance`   | ERC-20 tokens in wallet; not automatically `mUSD` |
| `walletAllowance` | Whether deposit can succeed on-chain              |

Use `musdBalance` for plain market buys and limit buys. If it is insufficient, deposit cash first. When cash token approval and instant deposit conditions are met, `/orders/with-deposit/*` can deposit and place the buy in one transaction.

## Check Stock Available To Sell

For plain sells, the important value is `exchangeBalance`. `walletBalance` means the user owns an ERC-20 stock token in their wallet, but it is not yet credited inside `Stock`.

Do not treat wallet stock as plain-sell balance. A plain sell uses `exchangeBalance`, the API view of `Stock.stockBalance`. To sell wallet-held stock with separate calls, approve the stock token and call `/stock/deposits/*` first. To deposit and sell in one transaction, use `/orders/with-deposit/*` after stock token approval.

## Prepare Deposits Correctly

Deposit means: **wallet cash token -> mUSD -> buy power**. Track the conversion so the integration does not treat wallet balance as spendable `mUSD`.

Before building deposit calldata:

1. Check wallet cash balance.
2. Check allowance with `GET /api/v1/users/{userId}/balance?spenderAddress={spender}`.
3. Request ERC-20 approval from the owner wallet if `walletAllowance` is too low.
4. For self-submit, build deposit calldata and submit the returned `StockRouter` transaction.
5. For One Click, call `/cash/deposits/send` after delegation is enabled.
6. Record `txHash` for self-submit flows and poll the deposit operation.

If allowance is too low, `/cash/deposits/calldata` can still return calldata, but the chain transaction will fail.

## Place A Market Buy

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant C as Cashier
    participant TS as Trading service

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST /orders/calldata
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST /orders/send
            API->>R: submit via OneClickRouter
        end
    end
    R->>R: placeMarketOrder buy notional
    R->>C: Lock max mUSD spend
    TS->>TS: Execute at best available price
    TS->>C: Apply mUSD spend or refund
```

Market buy input is `notional`: the maximum `mUSD` amount to spend. The final fill may spend less and refund the rest. The order is not economically final until settlement has credited stock and refunded unused `mUSD`.

## Place A Market Sell

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant Stock as Stock
    participant TS as Trading service
    participant C as Cashier

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST /orders/calldata
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST /orders/send
            API->>R: submit via OneClickRouter
        end
    end
    R->>R: placeMarketOrder sell quantity
    R->>Stock: Lock max stock quantity
    TS->>TS: Execute at best available price
    TS->>Stock: Apply filled and unfilled result
    TS->>C: Credit mUSD proceeds
```

Market sell input is `quantity`: the maximum stock quantity to sell. `Stock` locks that quantity first; settlement applies only the filled amount and returns any unfilled stock to `Stock.stockBalance`.

## Place A Limit Order

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant S as Stock
    participant C as Cashier
    participant B as Backend bots

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST /orders/calldata
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST /orders/send
            API->>R: submit via OneClickRouter
        end
    end
    R->>S: placeLimitOrder
    alt Buy
        S->>C: Lock mUSD
    else Sell
        S->>S: Lock stockBalance
    end
    B->>B: Execute when market conditions match
    alt Filled or partial
        B->>C: Apply mUSD spend/refund
        B->>S: Apply stock fill/remainder
    else Open
        B-->>API: Keep order in openOrder
    else Cancel
        T->>API: DELETE /orders/{orderId}/calldata or /send
        API->>R: cancelLimitOrder
        B->>C: Refund locked mUSD if needed
        B->>S: Return locked stock if needed
    end
```

Limit orders have a `price`, `quantity`, and `timeInForce`. Current production contracts accept only `DAY`; backend processing and settlement handle the practical lifecycle after placement.

Treat a limit order as an open commitment that locks `mUSD` or stock until fill, cancel, expiry, or settlement. Keep it separate from final portfolio balances.

## Reconcile Order Finality

A mined transaction means the order was accepted on-chain; it does not mean execution and settlement are final. Watch both mapping state and order detail:

1. `POST /api/v1/orders/tx` records a self-submitted tx.
2. `GET /api/v1/orders/tx/{txHash}` finds the tx mapping.
3. The indexer backfills `orderId`.
4. `GET /api/v1/orders/{orderId}` tracks open or historical state.
5. Portfolio balances update after settlement.

An order is economically final only after settlement updates `mUSD` and `exchangeBalance`.

## Understand Instant Vs Queued Cash

```mermaid
sequenceDiagram
    participant T as Client
    participant API as Trading API
    participant R as StockRouter
    participant C as Cashier
    participant B as Backend bots

    alt Self-submit
        rect rgb(232, 244, 255)
            T->>API: POST cash calldata endpoint
            T->>R: submit returned calldata
        end
    else One Click
        rect rgb(246, 239, 255)
            T->>API: POST cash send endpoint
            API->>R: submit via OneClickRouter
        end
    end
    R->>C: Record cash operation
    alt Buffer can cover operation
        C->>C: Apply mUSD credit or token payout
        API-->>T: operationStatus settled
    else Buffer cannot cover operation
        C->>C: Mark processing
        B->>B: Complete final cash settlement
        B->>C: Settle operation
        API-->>T: operationStatus settled
    end
```

Cash can be instant when buffers are available. Otherwise it is queued until final settlement completes. Track status with:

* `GET /api/v1/cash/deposits/{operationId}`
* `GET /api/v1/cash/withdrawals/{operationId}`

Handle both instant and queued outcomes. A queued operation is not necessarily failed; it may be waiting for final cash settlement.

The underlying contracts use two buffers: a global `creditBuffer` for instant deposits and a per-token `withdrawalBuffer` for instant withdrawals. Deposits and withdrawals can replenish each other's buffers. See [cash/buffer-mechanism.md](/trading-api/cash-operations/buffer-mechanism.md).

## Choose Execution Mode

Both modes call the same router methods. One Click only changes who submits the router transaction.

| Mode        | Use when                                           | Trade-off                                                |
| ----------- | -------------------------------------------------- | -------------------------------------------------------- |
| Self-submit | You manage wallets, custody, or transaction policy | More control; must record `txHash`                       |
| One Click   | You use delegated transaction submission           | Requires user delegation and API key bound `userAddress` |

Use Self-submit when your integration owns transaction policy or custody. Use One Click when the integration needs delegated submission after explicit authorization.

## Treat API Calldata As A Router Instruction

For self-submit, use `toAddress`, `value`, and `callData` exactly as returned by the API. Do not reconstruct calldata by hand unless you are deliberately bypassing the partner API. The API output is already shaped for the correct router method and product context.

## Pre-Trade Checklist

Before placing an order, confirm:

* Symbol is tradable for the selected chain/product.
* `x-api-chain-id`, wallet network, and `x-api-p` match.
* Portfolio has been refreshed.
* Plain buys use `musdBalance`; plain sells use `exchangeBalance`.
* Order-with-deposit flows require token allowance and, for buys, instant deposit availability.
* Deposit allowance is sufficient if funding is required.
* Execution mode is selected.
* Self-submit flows record `txHash`; One Click flows have `/1ct/status = enable`.

If a trade fails or appears stuck, check these in order: API response `code`, tx receipt, `/orders/tx/{txHash}`, `/orders/{orderId}`, then portfolio balances.

## Related Docs

| Need                             | Doc                                                                                                                      |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| First API trade flow             | [../guides/quickstart-first-trade.md](/trading-api/guides/quickstart-first-trade.md)                                     |
| How do I authenticate?           | [authenticate/](https://github.com/AnchoredLabs/anchored-knowledge/blob/main/02-products/rwa/api/authenticate/README.md) |
| How do I read balances?          | [portfolio/overview.md](/trading-api/portfolio/overview.md)                                                              |
| How do I deposit?                | [cash/deposits.md](/trading-api/cash-operations/deposits.md)                                                             |
| How do I place or cancel orders? | [trading/place-and-cancel-orders.md](/trading-api/trading/place-and-cancel-orders.md)                                    |
| How do I track status?           | [trading/order-status-and-history.md](/trading-api/trading/order-status-and-history.md)                                  |
| How do I submit with viem?       | [guides/demo-code.md](/trading-api/guides/demo-code.md)                                                                  |
| How do I debug issues?           | [../reference/troubleshooting.md](/trading-api/reference/troubleshooting.md)                                             |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.anchored.finance/trading-api/getting-started/trader-questions.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
