# OCO

Create a standalone OCO, a take-profit and a stop-loss over a quantity you already hold that share one reserve, and know how it fires, ends, and is canceled.

A standalone OCO (one-cancels-the-other) is a take-profit and a stop-loss over a quantity the account already holds, created in one request. Both legs trade the same Pair, side, and quantity, and share one reserve. When one leg's exit order has traded the whole quantity, the other leg is canceled with cancel reason `OCO`.

Create one with [`CreateOco`](https://testnet.polyester.com/docs/api-docs/connect/triggers.v1.TriggersService/CreateOco) ([`POST /v1/triggers/oco`](https://testnet.polyester.com/docs/api-docs/rest/POST/v1/triggers/oco)) and cancel it with [`CancelOco`](https://testnet.polyester.com/docs/api-docs/connect/triggers.v1.TriggersService/CancelOco) ([`DELETE /v1/triggers/oco/{orderListId}`](https://testnet.polyester.com/docs/api-docs/rest/DELETE/v1/triggers/oco/order_list_id)). The trade WebSocket takes the same requests; see [Trade WebSocket](#trade-websocket).

## Standalone OCO and attached legs

[Attached take-profit and stop-loss](https://testnet.polyester.com/docs/developer-docs/shared-concepts/triggers/attached-tp-sl) legs belong to an order: they arm as it fills and protect what it filled. A standalone OCO has no parent order. It protects a balance already in the account, from the moment it is created:

- Both legs are `RUNNING` from the create, over the full quantity.
- Its reserve is created at once and in full, not as fills settle.
- The legs are always linked as OCO. There is no `oco` switch.
- The legs carry `order_list_id`, and no `parent_order_id`.

The legs otherwise follow the attached-leg rules for firing, switching, and ending.

## Request

`CreateOcoRequest` carries an optional `subaccount_id` and one `oco` (`OcoIntent`):

| Field                        | Rule                                                                                    |
| ---------------------------- | --------------------------------------------------------------------------------------- |
| `symbol_id`                  | Required. REST takes the Pair `symbol`                                                  |
| `side`                       | Required: `SELL` protects held base, `BUY` spends held quote. Both legs trade this side |
| `qty_scaled`                 | Required, positive, a multiple of the Pair's step size. REST `qty`, a decimal string    |
| `client_list_id`             | Required. 1 to 36 ASCII letters, digits, `.`, `_`, `:`, `/` or `-`                      |
| `take_profit`, `stop_loss`   | Required. Each an `OcoLeg`                                                              |
| `self_trade_prevention_mode` | Optional. Defaults to `EXPIRE_MAKER`. `DECREMENT` is refused                            |

Each `OcoLeg` has:

- **`trigger_price_ticks`** (REST `triggerPrice`)\
  Required, positive, and on the Pair's tick size.
- **`child`**\
  Required: `market_ioc`, an empty object, or `limit_gtc` with `price_ticks` (REST `price`), a resting limit exit. Post-only is not supported.
- **`trigger_price_source`**\
  Optional: `LAST_PRICE` (default) or `INDEX_PRICE`.

There is no fee asset field: each exit pays its fee in the quote Asset. Neither the quantity nor the side can change later; cancel the OCO and create a new one.

## Trigger prices

| Side   | Take-profit                                        | Stop-loss               |
| ------ | -------------------------------------------------- | ----------------------- |
| `SELL` | Above the watched price, and above the stop-loss's | Below the watched price |
| `BUY`  | Below the watched price, and below the stop-loss's | Above the watched price |

Each leg compares its trigger price with the price its own `trigger_price_source` names. See [The price a trigger watches](https://testnet.polyester.com/docs/developer-docs/shared-concepts/triggers/overview#the-price-a-trigger-watches).

- A take-profit at or past the stop-loss, at or below it for a `SELL` or at or above it for a `BUY`, is refused with `TRIGGER_PRICE_INVALID` and a violation on `oco.take_profit.trigger_price_ticks` (REST `oco.takeProfit.triggerPrice`). Nothing is created.
- A leg whose trigger price the watched price has already reached is checked after the create is acknowledged. Both legs then end `FAILED` with `TRIGGER_WOULD_TRIGGER_IMMEDIATELY`, the reserve is released, and nothing is placed. Read the legs after a create to confirm they are `RUNNING`.
- On a Pair without an index price, an OCO with an `INDEX_PRICE` leg fails the same way, with `INDEX_PRICE_UNAVAILABLE` on both legs.

## Funds reserved at creation

An OCO reserves funds once, for both legs, so the quantity can be sold or bought only once. A create that the available balance cannot cover is rejected with `INSUFFICIENT_FUNDS`, and nothing is held.

- **`SELL`**\
  The quantity, in the base Asset.
- **`BUY`**\
  The larger of the two legs' costs, in the quote Asset. A leg costs its maximum price times the quantity, plus the fee at the Pair's `reserveFeeRatePercent`. A limit exit's maximum is its limit price. A market exit's maximum is its trigger price raised by the Pair's `defaultMarketSlippageBpsBuy`, on the tick size.

For a `BUY` with market exits, the stop-loss usually sets the reserve, because its trigger price is the higher one. See [Size a buy that pays its fee in quote](https://testnet.polyester.com/docs/developer-docs/account/fees-and-vip#size-a-buy-that-pays-its-fee-in-quote) for the fee reserve rate.

While the OCO lives, orders and withdrawals that would use the reserved funds are rejected with `INSUFFICIENT_FUNDS`. Each fire moves its exit's share of the reserve to the exit order. What an exit does not use comes back to the reserve, and the reserve is released when the last leg ends.

### Slippage of a market exit

`market_ioc` takes no slippage cap. A market exit uses the Pair's default market slippage for the OCO's side, `defaultMarketSlippageBpsBuy` or `defaultMarketSlippageBpsSell` from `GetSpotConfig`, measured from the fire price. On a price gap past that bound, the exit fills partly or not at all. See [Market order price protection](https://testnet.polyester.com/docs/developer-docs/shared-concepts/market-order-price-protection#read-the-current-pair-policy).

### Pair minimums

A create whose exit could never pass the Pair's order limits at the full quantity is refused with that check's code: `MIN_QTY`, `QTY_STEP_SIZE`, `MIN_NOTIONAL`, or `MAX_NOTIONAL`. Each exit is valued where its fire would value it: a buy at its maximum price, a sell at its limit price, or a market sell at its trigger price lowered by `defaultMarketSlippageBpsSell`.

## Examples

A sell OCO over 0.5 BTC on BTC-USDT: a take-profit at 72,000 that rests a limit sell at 72,000, and a stop-loss at 60,000 that sells at market.

## REST JSON

`POST /v1/triggers/oco`

```json
{
	"oco": {
		"symbol": "BTC-USDT",
		"side": "SELL",
		"qty": "0.5",
		"clientListId": "oco-btc-1",
		"takeProfit": {
			"triggerPrice": "72000",
			"child": { "limitGtc": { "price": "72000" } }
		},
		"stopLoss": {
			"triggerPrice": "60000",
			"triggerPriceSource": "LAST_PRICE",
			"child": { "marketIoc": {} }
		}
	}
}
```

## ConnectRPC ProtoJSON

`/triggers.v1.TriggersService/CreateOco`. The example assumes BTC-USDT has Pair ID `1` and a `base_quantity_scale` of 8; read both from `GetSpotConfig`.

```json
{
	"oco": {
		"symbolId": 1,
		"side": "SELL",
		"qtyScaled": "50000000",
		"clientListId": "oco-btc-1",
		"takeProfit": {
			"triggerPriceTicks": "72000000000000",
			"child": { "limitGtc": { "priceTicks": "72000000000000" } }
		},
		"stopLoss": {
			"triggerPriceTicks": "60000000000000",
			"triggerPriceSource": "LAST_PRICE",
			"child": { "marketIoc": {} }
		}
	}
}
```

The response names the OCO, `orderListId`, and each leg's trigger ID. Over REST:

```json
{
	"orderListId": "2NEpo7TZRRrLZSi2X",
	"clientListId": "oco-btc-1",
	"takeProfitTriggerId": "2NEpo7TZRRrLZSi2Y",
	"stopLossTriggerId": "2NEpo7TZRRrLZSi2Z",
	"acceptedAt": "2026-11-03T09:15:02.481Z",
	"acceptedAtTsNs": "1793697302481000000"
}
```

### A buy OCO with market exits

Buys 0.5 BTC at market if the price dips to 62,000 or breaks out to 70,000. If the Pair's `defaultMarketSlippageBpsBuy` is 500 (5%), the stop-loss sets the reserve: 70,000 × 1.05 × 0.5 = 36,750 USDT, plus the fee. The take-profit would need 32,550 USDT.

```json
{
	"oco": {
		"symbol": "BTC-USDT",
		"side": "BUY",
		"qty": "0.5",
		"clientListId": "oco-btc-buy-1",
		"takeProfit": { "triggerPrice": "62000", "child": { "marketIoc": {} } },
		"stopLoss": { "triggerPrice": "70000", "child": { "marketIoc": {} } }
	}
}
```

## When a leg fires

The first leg whose trigger price is reached fires: it records `EVENT_FIRED` and places one exit order for the OCO's remaining quantity, rounded down to the Pair's step size. Only one exit works at a time. Follow the exit as an ordinary order through `child_order_id`.

- **The exit trades the whole quantity:** the leg whose exit traded last ends `COMPLETED`, and the other ends `CANCELED` with cancel reason `OCO`. The reserve is released.
- **The exit trades only part,** for example a resting limit exit or a market exit on a thin book: both legs keep protecting the rest. If the other leg's trigger price is reached, it cancels the working exit, whose fills stand, and fires for what is left.
- **An exit ends unfilled for another cause,** such as the end of an IOC or self-trade prevention: the legs stay live and protect the rest.

## Cancel

`CancelOco` takes the `order_list_id` from the create. Canceling either leg with `CancelTrigger` does the same. Either way, both legs end `CANCELED` with `USER_REQUEST` in one step, so no price between two cancels can fire the other leg. A working exit is canceled with them, its fills standing, and the reserve is released. The answer's `status` is `CANCELED`.

```http
DELETE https://api.testnet.polyester.com/v1/triggers/oco/2NEpo7TZRRrLZSi2X?subaccountId=45LUmqjT
```

- An `order_list_id` that names no OCO of the account, such as a trigger ID, is refused with `TRIGGER_NOT_FOUND`, and nothing is canceled.
- An OCO that has already ended answers `TRIGGER_STATUS_INVALID`.

[Cancel all orders](https://testnet.polyester.com/docs/developer-docs/shared-concepts/cancel-all-orders) and the [dead-man switch](https://testnet.polyester.com/docs/developer-docs/shared-concepts/dead-man-switch) stop an OCO only with `include_triggers` set. Then each leg ends `CANCELED` with cancel reason `CANCEL_ALL`, a working exit is canceled with the account's other orders, and the reserve is released.

Without `include_triggers`, they cancel orders only, so an OCO with no working exit is untouched. When a leg has fired, they cancel its working exit order like any open order, and canceling that exit ends both legs `CANCELED` with `USER_REQUEST`. A cancel of the exit with `CancelOrder` does the same. [Cancel-on-disconnect](https://testnet.polyester.com/docs/developer-docs/sbe-websocket/order-entry#cancel-on-disconnect) cancels orders only, never triggers. If it cancels an OCO's working exit, that ends the OCO as above; an OCO with no working exit survives.

## Modify

`ModifyTrigger` changes one leg's `trigger_price_ticks`:

- A price that would cross the other leg, including a price that the other leg's pending modify asks for, is refused with `TRIGGER_PRICE_INVALID`.
- A price the watched price has already reached is refused with `TRIGGER_WOULD_TRIGGER_IMMEDIATELY`.
- While an exit works, the change is refused with `ATTACHED_EXIT_WORKING`.

A limit exit's price cannot change. A refused modify changes nothing.

## Reads and events

Each leg is an ordinary trigger of type `TAKE_PROFIT` or `STOP_LOSS`. Read it with `GetTrigger` and `ListTriggers` like any trigger; see [Read triggers](https://testnet.polyester.com/docs/developer-docs/shared-concepts/triggers/overview#read-triggers).

- **`order_list_id`** (REST `orderListId`)\
  The OCO both legs belong to. Empty for every other trigger.
- **`client_list_id`** (REST `clientListId`)\
  The OCO's client ID, on both legs. A leg's `client_trigger_id` is empty.
- **`ListTriggers` filters**\
  `order_list_id` and `client_list_id` (REST `orderListId` and `clientListId`) list both legs of one OCO.

Each leg records its own events on the trigger events channel: `EVENT_ARMED` when it is created, `EVENT_FIRED` with `child_order_id` for each exit it places, then `EVENT_CANCELED` with `OCO`, `USER_REQUEST`, or `CANCEL_ALL`, or `EVENT_FAILED`.

| How the OCO ended                                       | Legs end as                                                             |
| ------------------------------------------------------- | ----------------------------------------------------------------------- |
| An exit traded the whole quantity                       | The leg whose exit traded last `COMPLETED`; the other `CANCELED`, `OCO` |
| `CancelOco`, or `CancelTrigger` on either leg           | Both `CANCELED`, `USER_REQUEST`                                         |
| You canceled a working exit, alone or with a cancel-all | Both `CANCELED`, `USER_REQUEST`                                         |
| A cancel-all or dead-man switch with `include_triggers` | Both `CANCELED`, `CANCEL_ALL`                                           |
| A leg's trigger price was already reached at create     | Both `FAILED`, `TRIGGER_WOULD_TRIGGER_IMMEDIATELY`                      |

## Create once, retry safely

`client_list_id` is unique per account and Pair among OCOs, separately from client trigger IDs.

- While a leg is live, and for 60 seconds after both legs ended, the same request with the same ID answers the same OCO. The same ID with a different request is refused with `CONFLICT_DUPLICATE_CLIENT_TRIGGER_ID`.
- `TRIGGER_CREATE_OUTCOME_UNKNOWN` means the create was not confirmed in time and may have succeeded. List the triggers with `client_list_id` before retrying.

## Limits and rate limits

There is no separate OCO limit: each leg counts as one trigger toward the [account's trigger limits](https://testnet.polyester.com/docs/developer-docs/shared-concepts/triggers/overview#limits). An OCO uses two of the 100 triggers allowed on one Pair, so at most 50 OCOs fit on a Pair with no other triggers. A create that would pass a limit is refused with `MARKET_TRIGGER_LIMIT_EXCEEDED` or `TRIGGER_LIMIT_EXCEEDED`, and nothing is created.

| Action                       | Pool             | Cost |
| ---------------------------- | ---------------- | ---: |
| `CreateOco`                  | `TRADING_PLACE`  |    1 |
| Each exit order a leg places | `TRADING_PLACE`  |    1 |
| `CancelOco`                  | `TRADING_CANCEL` |    1 |

See [Rate limits](https://testnet.polyester.com/docs/developer-docs/shared-concepts/rate-limits).

## Trade WebSocket

The [protobuf trade WebSocket](https://testnet.polyester.com/docs/developer-docs/connectrpc/protobuf-trade-websocket) takes `create_oco` and `cancel_oco` in `ClientFrame`, with the `CreateOcoRequest` and `CancelOcoRequest` messages above, and answers with `create_oco` or `cancel_oco` in its acknowledgement. The [SBE WebSocket](https://testnet.polyester.com/docs/developer-docs/sbe-websocket/order-entry) has `CreateOco` and `CancelOco`, both answered by `OcoAck`, which carries `orderListId` and, for a create, both legs' trigger IDs. Refusals arrive as `CommandReject` with the codes below.

## Errors

- **`TRIGGER_PRICE_INVALID`** · HTTP 400\
  A leg's trigger price is not positive, the take-profit is not on the profit side of the stop-loss, or a modify would cross the other leg.
- **`PRICE_TICK_SIZE`** · HTTP 400\
  A trigger or limit price is not on the Pair's tick size.
- **`STP_MODE_NOT_ALLOWED`** · HTTP 400\
  `self_trade_prevention_mode` is `DECREMENT`.
- **`TRIGGER_PRICE_SOURCE_UNSUPPORTED`** · HTTP 400\
  A leg names `MARK_PRICE`.
- **`INSUFFICIENT_FUNDS`** · HTTP 400\
  The available balance cannot cover the reserve.
- **`MIN_QTY`, `QTY_STEP_SIZE`, `MIN_NOTIONAL`, `MAX_NOTIONAL`** · HTTP 400\
  An exit could never pass the Pair's order limits at the full quantity.
- **`TRIGGER_QTY_INVALID`** · HTTP 400\
  The quantity is not positive, or over REST a malformed or negative `qty`. The violation names `oco.qty_scaled` (REST `oco.qty`). The trade WebSocket answers the same code.
- **`BAD_PRICE`** · HTTP 400\
  A leg's limit price is not positive.
- **`CLIENT_LIST_ID_INVALID`** · 318 · HTTP 400\
  The `client_list_id` is empty, longer than 36 characters, or has a character other than an ASCII letter, digit, `.`, `_`, `:`, `/` or `-`. Every API answers this code, the trade WebSockets included; ConnectRPC with `invalid_argument`. The `ListTriggers` `client_list_id` filter answers it too. Nothing changed.
- **`VALIDATION_ERROR`** · HTTP 400\
  A required field is missing, such as a leg's `child`. ConnectRPC answers `invalid_argument`, and the trade WebSocket `BAD_REQUEST`.
- **`CONFLICT_DUPLICATE_CLIENT_TRIGGER_ID`** · HTTP 409\
  The `client_list_id` names another OCO. List triggers by `client_list_id`, then use a new ID.
- **`MARKET_TRIGGER_LIMIT_EXCEEDED`, `TRIGGER_LIMIT_EXCEEDED`** · HTTP 429\
  The two legs would pass the account's trigger limits.
- **`RATE_LIMIT_EXCEEDED`** · HTTP 429\
  Retry after the `Retry-After` delay.
- **`TRIGGER_CREATE_OUTCOME_UNKNOWN`** · HTTP 504\
  List triggers by `client_list_id` before retrying the create.
- **`TRIGGER_NOT_FOUND`** · HTTP 404\
  `CancelOco` named an ID that is not an OCO of the account.
- **`TRIGGER_STATUS_INVALID`** · HTTP 400\
  The OCO has already ended. Treat the cancel as done.

`TRIGGER_WOULD_TRIGGER_IMMEDIATELY` and `INDEX_PRICE_UNAVAILABLE` on a create are not errors: they are the legs' `failure_reason` after the create was acknowledged. See [Error codes](https://testnet.polyester.com/docs/developer-docs/error-handling/error-codes) for every code and its ConnectRPC status.
