> 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/trading/deferred-sell.md).

# Deferred Sell

Deferred sell lets a whitelisted partner place a sell order for a stock **without first depositing it into their exchange (sellable) balance**. The filled quantity becomes an on-chain **debt** that the partner must later repay by depositing the stock. It is a sell-now, deliver-later flow, distinct from a plain sell (which locks stock you already hold in your exchange balance).

All deferred-sell endpoints target `StockRouter`. The API surfaces the current debt per stock so integrators can track outstanding obligations.

## Access Control (Whitelist)

Placing a deferred sell is **whitelisted per address**. Your address must be enabled by the Anchored team before it can place a deferred sell — you do not configure this yourself. The API checks this **before** building calldata, so an address that is not permitted is rejected up front (e.g. `deferred sell is not allowed for this address`) instead of broadcasting a transaction that would revert on-chain.

The gate applies only to **placing** a deferred sell (`/orders/calldata` / `/orders/send` with `deferred: true`). Repaying debt is always allowed.

## Risk Control (Balance & Quantity Limits)

The whitelist above is the **first** gate — a synchronous, pre-placement check at the API. There is now a **second** gate: a **risk control** applied *after* the order is on-chain, while the indexer processes the `OrderPlaced` event. It runs only for **deferred sell** orders (`side = Sell`, `deferred = true`) and enforces two limits:

| # | Check                    | Rejected when                                                                                                                       | `brokerFailedReason`                                  |
| - | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| 1 | **Already holds enough** | The partner's current exchange balance for the stock is `>= quantity` — you don't need a deferred sell, place a plain sell instead. | `Stock balance is enough,can not use deferred order.` |
| 2 | **Sellable quantity**    | `quantity` exceeds the net amount the partner is allowed to defer-sell (see formula below).                                         | `Insufficient quantity to place deferred order.`      |

Check 1 runs first; if the partner has no balance record or holds less than `quantity`, it passes to check 2.

**Sellable quantity** is computed across the partner's **relation-address group** (see below), from indexed order state:

```
totalCanSell = totalBuy − totalSell − totalSelling

  totalBuy     = Σ filled_quantity of all BUY  orders in history
  totalSell    = Σ filled_quantity of all SELL orders in history
  totalSelling = Σ place_quantity  of current OPEN sell orders
```

i.e. a deferred sell is capped at the group's net-acquired position minus what is already resting on the sell side. A new deferred sell passes only if `totalCanSell >= quantity`.

### Relation-address group

Each deferred-sell config carries a `relation_address` list. `totalBuy` / `totalSell` / `totalSelling` are summed over **every address in that list**, so a partner operating several wallets has their buys, sells and open sells netted together into one limit. The list **defaults to just the partner's own address** and is provisioned by the Anchored team alongside the whitelist config.

### How a risk rejection surfaces (differs from the whitelist gate)

Because this gate runs *after* the on-chain placement, a deferred sell that fails risk control is **not** rejected at the API — the transaction is broadcast and the on-chain order is created normally. The rejection happens at the **broker step**:

* The order is marked internally as failing risk control (with the reason), and **is never routed to the broker**.
* A broker order is recorded directly as **`FAILED`**, its fail reason set to the reason string above (surfaced to integrators as `brokerFailedReason`).
* The on-chain order is then settled/cancelled.

So an integrator sees the order reach a **failed / cancelled** terminal state with `brokerFailedReason` populated — **not** an HTTP error at placement time. **Always confirm a deferred sell via order status** (see [Tracking a Deferred Sell Order](#tracking-a-deferred-sell-order)); a successful broadcast does not guarantee the order was placed at the broker.

## Place a Deferred Sell

A deferred sell is a regular sell order — it is placed through the **standard order endpoints** with `deferred: true`; there are no separate deferred placement endpoints.

```
POST /api/v1/orders/calldata   (self-submit)
POST /api/v1/orders/send       (One Click)
```

Same body as a normal order (see [place-and-cancel-orders.md](/trading-api/trading/place-and-cancel-orders.md)) plus `deferred: true`. Rules:

* `side` **must be `Sell`** — deferred is sell-only; `deferred` with `Buy` is rejected (`deferred is only supported for sell orders`).
* `type: Limit` → `quantity` + `price` + `timeInForce: "DAY"`; `type: Market` → `quantity`. No `notional`.
* The address must be whitelisted (see [Access Control](#access-control-whitelist)); a **market** deferred sell is only accepted during the regular US session.
* Even when whitelisted, the order must pass the balance & quantity **risk control** (see [Risk Control](#risk-control-balance--quantity-limits)) — this is checked after placement, so a failing order lands in a **FAILED** state with `brokerFailedReason` rather than being rejected at the API.

### Limit deferred sell

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Sell",
  "type": "Limit",
  "quantity": "1.25",
  "price": "180.50",
  "timeInForce": "DAY",
  "deadline": 1893456000,
  "deferred": true
}
```

### Market deferred sell

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Sell",
  "type": "Market",
  "quantity": "1.25",
  "deadline": 1893456000,
  "deferred": true
}
```

`/orders/calldata` returns calldata with `method` `deferredLimitSell` / `deferredMarketSell`. `/orders/send` returns the **order-tx mapping** (`operationType: "trade"`). The order is then tracked like any other order (with `deferred: true` on the response) — see [Tracking a Deferred Sell Order](#tracking-a-deferred-sell-order).

## Repay Deferred Sell Debt

```
POST /api/v1/deferred-sell/repay/calldata
```

| Field          | Type            | Required | Description                                                        |
| -------------- | --------------- | -------- | ------------------------------------------------------------------ |
| `stockAddress` | string          | Yes      | Stock token whose deferred-sell debt is repaid.                    |
| `amount`       | string / number | Yes      | Human-readable stock amount to repay against the outstanding debt. |

Response `data` is the standard calldata shape above; `method` is `repayDeferredStockDebt`.

> **Repay pulls the stock from the partner's wallet, not from `exchangeBalance`.** `repayDeferredStockDebt` does an ERC-20 `transferFrom(wallet → …)` and burns it, so before repaying you must:
>
> 1. Hold the stock token in the **wallet** — if it currently sits in `exchangeBalance` (e.g., just bought), withdraw it first via `POST /api/v1/stock/withdrawals/send`.
> 2. **Approve `StockRouter`** for the repay amount on the stock token (One Click does **not** perform the approval for you — it must be a wallet transaction).
>
> Missing either step reverts: no wallet balance / allowance → `ERC20InsufficientAllowance`; repaying more than the outstanding debt → `DeferredDebtExceeded`.

## One Click Repay

```
POST /api/v1/deferred-sell/repay/send
```

Same body as `/deferred-sell/repay/calldata`, plus optional `gasLimit`. Returns the order-tx mapping (`operationType: "deferred_repay"`). The wallet-balance and approval prerequisites above still apply.

## Query Deferred Sell Debts

```
GET /api/v1/deferred-sell/debts
GET /api/v1/deferred-sell/debts?stockAddress=0x0000000000000000000000000000000000000001
```

Returns the authenticated user's current outstanding deferred-sell debts from indexed state. Pass an optional `stockAddress` to filter to a single stock.

Response `data` is an array of:

| Field                 | Type            | Description                                          |
| --------------------- | --------------- | ---------------------------------------------------- |
| `stockAddress`        | string          | Stock token contract address.                        |
| `stockSymbol`         | string          | Stock symbol.                                        |
| `stockContractSymbol` | string          | Stock contract symbol.                               |
| `debt`                | string / number | Current outstanding debt in stock units.             |
| `lastUpdateTxHash`    | string          | Tx hash of the last debt change (fill or repayment). |
| `lastUpdateBlockTime` | string          | Block time of the last debt change.                  |

Debt increases as a deferred order fills and decreases on repayment. A stock with no outstanding debt is not returned.

## Tracking a Deferred Sell Order

A deferred sell **is a regular exchange order** (same order lifecycle, orderId, open/history tables), so it is tracked through the **standard order endpoints** — there are no deferred-specific order/tx query endpoints:

| Need                         | Endpoint                                              |
| ---------------------------- | ----------------------------------------------------- |
| List orders                  | `GET /api/v1/orders`                                  |
| Order detail (status + fill) | `GET /api/v1/orders/{orderId}`                        |
| Find order by tx             | `GET /api/v1/orders/tx/{txHash}`                      |
| Cancel                       | `DELETE /api/v1/orders/{orderId}/calldata` or `/send` |

These responses carry a **`deferred`** boolean (`true` for deferred sells) so you can distinguish them from plain sells. A deferred sell that was blocked by [risk control](#risk-control-balance--quantity-limits) reaches a **failed/cancelled** status with `brokerFailedReason` set to the reason string. See [order-status-and-history.md](/trading-api/trading/order-status-and-history.md).

The order-tx mapping for a deferred sell is recorded with `operationType: "trade"` (it is an order). Only **repay** uses a distinct `operationType: "deferred_repay"`, and repay is not an order (no `orderId`, not in the order tables), so it does not appear in `/orders`.

> Note: the current outstanding **debt** is not on the order object; read it from `GET /api/v1/deferred-sell/debts`.
