> This page is for API Reference.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://okx-demo.ferndocs.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://okx-demo.ferndocs.com/_mcp/server.

# Place algo order

POST https://www.okx.com/api/v5/trade/order-algo
Content-Type: application/json

The algo order includes `trigger` order, `oco` order, `chase` order, `conditional` order, `twap` order and trailing order.

Reference: https://okx-demo.ferndocs.com/api/api-reference/trade/place-algo-order

## Authentication

- `OK-ACCESS-KEY` header (required) — Your API key.
- `OK-ACCESS-SIGN` header (required) — Base64-encoded HMAC-SHA256 signature of the prehash string.
- `OK-ACCESS-TIMESTAMP` header (required) — ISO 8601 UTC timestamp, e.g. 2020-12-08T09:08:57.715Z.
- `OK-ACCESS-PASSPHRASE` header (required) — The passphrase you set when creating the API key.

## Request

### Body (application/json)

This endpoint expects an object.

- `instId` (string, required) — Instrument ID, e.g. `BTC-USDT`
- `tdMode` (enum, required) — Trade mode Margin mode `cross` `isolated` Non-Margin mode `cash` `spot_isolated` (only applicable to SPOT lead trading) Note: `isolated` is not available in multi-currency margin mode and portfolio margin mode.
  - Allowed values: `cross`, `isolated`, `cash`, `spot_isolated`
- `side` (enum, required) — Order side, `buy` `sell`
  - Allowed values: `buy`, `sell`
- `ordType` (enum, required) — Order type `conditional`: One-way stop order `oco`: One-cancels-the-other order `chase`: chase order, only applicable to FUTURES and SWAP `trigger`: Trigger order `move_order_stop`: Trailing order `twap`: TWAP order `smart_iceberg`: Iceberg order
  - Allowed values: `conditional`, `oco`, `trigger`, `move_order_stop`, `iceberg`, `twap`, `chase`
- `sz` (string, required) — Quantity to buy or sell Either `sz` or `closeFraction` is required.
- `ccy` (string, optional) — Margin currency Applicable to all `isolated` `MARGIN` orders and `cross` `MARGIN` orders in `Futures mode`.
- `posSide` (enum, optional) — Position side Required in `long/short` mode and only be `long` or `short`
  - Allowed values: `long`, `short`
- `algoClOrdId` (string, optional) — Client-supplied Algo ID A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
- `tag` (string, optional) — Order tag A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
- `reduceOnly` (boolean, optional) — Whether the order can only reduce the position size. Valid options: `true` or `false`. The default value is `false`. This parameter is only valid in the `FUTRUES`/`SWAP` net mode, and is ignored in the long/short mode.
- `tgtCcy` (string, optional) — Order quantity unit setting for `sz` `base_ccy`: Base currency ,`quote_ccy`: Quote currency Only applicable to `SPOT` traded with Market buy `conditional` order Default is `quote_ccy` for buy, `base_ccy` for sell
- `tpTriggerPx` (string, optional) — Take-profit trigger price If you fill in this parameter, you should fill in the take-profit order price as well.
- `tpTriggerPxType` (enum, optional) — Take-profit trigger price type `last`: last price `index`: index price `mark`: mark price The default is `last`
  - Allowed values: `last`, `index`, `mark`
- `tpOrdPx` (string, optional) — Take-profit order price For condition TP order, if you fill in this parameter, you should fill in the take-profit trigger price as well. For limit TP order, you need to fill in this parameter, but the take-profit trigger price doesn’t need to be filled. If the price is `-1`, take-profit will be executed at the market price.
- `slTriggerPx` (string, optional) — Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price.
- `slTriggerPxType` (enum, optional) — Stop-loss trigger price type `last`: last price `index`: index price `mark`: mark price The default is `last`
  - Allowed values: `last`, `index`, `mark`
- `slOrdPx` (string, optional) — Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is `-1`, stop-loss will be executed at the market price.
- `triggerPx` (string, optional) — The price level that activates this algo order. Unit: same as `px` for the instrument. Which price feed is compared depends on `triggerPxType` (default: last trade price). Direction: for a sell stop-loss, trigger must be below orderPx; for a buy stop, above orderPx. Error codes 51046–51049 are returned for direction violations.
- `triggerPxType` (enum, optional) — Trigger price type: `last`: triggers when any trade occurs at or beyond `triggerPx` — most responsive but vulnerable to brief price wicks in thin markets. `index`: triggers on the underlying multi-exchange composite index — stable, not affected by OKX-specific wicks. `mark`: triggers on OKX mark price — smoothed and wick-resistant; recommended for derivatives. `last` is the only option available for SPOT instruments. The default is `last`.
  - Allowed values: `last`, `index`, `mark`
- `orderPx` (string, optional) — Price of the order submitted when `triggerPx` is reached. This is separate from `triggerPx` (which determines when the algo activates). Set to `-1` to submit a market order when triggered; set to a specific price to submit a limit order. Not applicable when `advanceOrdType` is `chase` (a chase has no fixed price).
- `callbackRatio` (string, optional) — Callback price ratio, e.g. `0.01` represents `1%` Either `callbackRatio` or `callbackSpread` is allowed to be passed.
- `callbackSpread` (string, optional) — Callback price variance
- `activePx` (string, optional) — Active price The system will only start tracking the market and calculating your trigger price after the activation price is reached. If you don’t set a price, your order will be activated as soon as it’s placed.
- `pxVar` (string, optional) — Price variance by percentage, range between [0.0001 ~ 0.01], e.g. `0.01` represents `1%` Take buy orders as an example. When the market price is lower than the limit price, small buy orders will be placed above the best bid price within a certain range. This parameter determines the range by percentage. Either `pxVar` or `pxSpread` is allowed to be passed.
- `pxSpread` (string, optional) — Price variance by constant, should be no less then 0 (no upper limit) Take buy orders as an example. When the market price is lower than the limit price, small buy orders will be placed above the best bid price within a certain range. This parameter determines the range by constant.
- `szLimit` (string, optional) — Minimum order size per execution. Only applicable to `smart_iceberg`
- `pxLimit` (string, optional) — Price limit. Only applicable to `smart_iceberg`
- `timeInterval` (string, optional) — Time interval in unit of `second` ake buy orders as an example. When the market price is lower than the limit price, small buy orders will be placed above the best bid price within a certain range based on the time cycle. This parameter represents the time cycle.

## Response

### 200

Successful response

- `code` (string, optional) — Result code. `0` means success; any other value is an error code.
- `msg` (string, optional) — Error message. Empty on success.
- `data` (list of ApiV5TradeOrderAlgoPostResponsesContentApplicationJsonSchemaDataItems, optional)

## Types

### ApiV5TradeOrderAlgoPostResponsesContentApplicationJsonSchemaDataItems

- `algoId` (string, optional) — Algo ID
- `algoClOrdId` (string, optional) — Client-supplied Algo ID
- `sCode` (string, optional) — The code of the event execution result, `0` means success.
- `sMsg` (string, optional) — Rejection message if the request is unsuccessful.

## Examples

**Request**

```json
{
  "instId": "BTC-USDT",
  "tdMode": "cross",
  "side": "buy",
  "ordType": "conditional",
  "sz": "0.01"
}
```

**Response**

```json
{
  "code": "0",
  "msg": "",
  "data": [
    {
      "algoId": "1836487817828872192",
      "algoClOrdId": "order1234",
      "sCode": "0",
      "sMsg": "",
      "clOrdId": "",
      "tag": ""
    }
  ]
}
```

**SDK Code**

```python trade_placeAlgoOrder_example
import requests

url = "https://www.okx.com/api/v5/trade/order-algo"

payload = {
    "instId": "BTC-USDT",
    "tdMode": "cross",
    "side": "buy",
    "ordType": "conditional",
    "sz": "0.01"
}
headers = {
    "OK-ACCESS-KEY": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript trade_placeAlgoOrder_example
const url = 'https://www.okx.com/api/v5/trade/order-algo';
const options = {
  method: 'POST',
  headers: {'OK-ACCESS-KEY': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"instId":"BTC-USDT","tdMode":"cross","side":"buy","ordType":"conditional","sz":"0.01"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go trade_placeAlgoOrder_example
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://www.okx.com/api/v5/trade/order-algo"

	payload := strings.NewReader("{\n  \"instId\": \"BTC-USDT\",\n  \"tdMode\": \"cross\",\n  \"side\": \"buy\",\n  \"ordType\": \"conditional\",\n  \"sz\": \"0.01\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("OK-ACCESS-KEY", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby trade_placeAlgoOrder_example
require 'uri'
require 'net/http'

url = URI("https://www.okx.com/api/v5/trade/order-algo")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["OK-ACCESS-KEY"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"instId\": \"BTC-USDT\",\n  \"tdMode\": \"cross\",\n  \"side\": \"buy\",\n  \"ordType\": \"conditional\",\n  \"sz\": \"0.01\"\n}"

response = http.request(request)
puts response.read_body
```

```java trade_placeAlgoOrder_example
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://www.okx.com/api/v5/trade/order-algo")
  .header("OK-ACCESS-KEY", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"instId\": \"BTC-USDT\",\n  \"tdMode\": \"cross\",\n  \"side\": \"buy\",\n  \"ordType\": \"conditional\",\n  \"sz\": \"0.01\"\n}")
  .asString();
```

```php trade_placeAlgoOrder_example
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://www.okx.com/api/v5/trade/order-algo', [
  'body' => '{
  "instId": "BTC-USDT",
  "tdMode": "cross",
  "side": "buy",
  "ordType": "conditional",
  "sz": "0.01"
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'OK-ACCESS-KEY' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp trade_placeAlgoOrder_example
using RestSharp;

var client = new RestClient("https://www.okx.com/api/v5/trade/order-algo");
var request = new RestRequest(Method.POST);
request.AddHeader("OK-ACCESS-KEY", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"instId\": \"BTC-USDT\",\n  \"tdMode\": \"cross\",\n  \"side\": \"buy\",\n  \"ordType\": \"conditional\",\n  \"sz\": \"0.01\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift trade_placeAlgoOrder_example
import Foundation

let headers = [
  "OK-ACCESS-KEY": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "instId": "BTC-USDT",
  "tdMode": "cross",
  "side": "buy",
  "ordType": "conditional",
  "sz": "0.01"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://www.okx.com/api/v5/trade/order-algo")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```