> 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.

# Get order history 7 days

GET https://www.okx.com/api/v5/trade/orders-history

Get completed orders which are placed in the last 7 days, including those placed 7 days ago but completed in the last 7 days.

The incomplete orders that have been canceled are only reserved for 2 hours.

Reference: https://okx-demo.ferndocs.com/api/api-reference/trade/get-orders-history

## 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

### Query parameters

- `instType` (enum, required) — Instrument type `SPOT` `MARGIN` `SWAP` `FUTURES` `OPTION` `EVENTS`
  - Allowed values: `SPOT`, `MARGIN`, `SWAP`, `FUTURES`, `OPTION`
- `uly` (string, optional) — Underlying. Applicable to FUTURES/SWAP/OPTION.
- `instFamily` (string, optional) — Instrument family Applicable to `FUTURES`/`SWAP`/`OPTION`
- `instId` (string, optional) — Instrument ID, e.g. `BTC-USDT`
- `ordType` (string, optional) — Order type `market`: market order `limit`: limit order `post_only`: Post-only order `fok`: Fill-or-kill order `ioc`: Immediate-or-cancel order `optimal_limit_ioc`: Market order with immediate-or-cancel order `mmp`: Market Maker Protection (only applicable to Option in Portfolio Margin mode) `mmp_and_post_only`: Market Maker Protection and Post-only order(only applicable to Option in Portfolio Margin mode) `op_fok`: Simple options (fok) `rpi`: Retail Price Improvement order `elp`: Enhanced Liquidity Program order (Deprecated; use `rpi`. Accepted until October 31, 2026.)
- `state` (enum, optional) — State `canceled` `filled` `mmp_canceled`: Order canceled automatically due to Market Maker Protection
  - Allowed values: `canceled`, `filled`, `mmp_canceled`
- `after` (string, optional) — Pagination of data to return records earlier than the requested `ordId`
- `before` (string, optional) — Pagination of data to return records newer than the requested `ordId`
- `begin` (string, optional) — Filter with a begin timestamp `cTime`. Unix timestamp format in milliseconds, e.g. 1597026383085
- `end` (string, optional) — Filter with an end timestamp `cTime`. Unix timestamp format in milliseconds, e.g. 1597026383085
- `limit` (string, optional) — Number of results per request. The maximum is `100`; The default is `100`

## 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 ApiV5TradeOrdersHistoryGetResponsesContentApplicationJsonSchemaDataItems, optional)

## Types

### ApiV5TradeOrdersHistoryGetResponsesContentApplicationJsonSchemaDataItems

- `instType` (string, optional) — Instrument type `SPOT` `MARGIN` `SWAP` `FUTURES` `OPTION` `EVENTS`
- `instId` (string, optional) — Instrument ID
- `ordId` (string, optional) — Order ID
- `clOrdId` (string, optional) — Client Order ID as assigned by the client
- `px` (string, optional) — Price For options, use coin as unit (e.g. BTC, ETH)
- `sz` (string, optional) — Quantity to buy or sell
- `ordType` (string, optional) — Order type `market`: market order `limit`: limit order `post_only`: Post-only order `fok`: Fill-or-kill order `ioc`: Immediate-or-cancel order `optimal_limit_ioc`: Market order with immediate-or-cancel order `mmp`: Market Maker Protection (only applicable to Option in Portfolio Margin mode) `mmp_and_post_only`: Market Maker Protection and Post-only order(only applicable to Option in Portfolio Margin mode) `op_fok`: Simple options (fok) `rpi`: Retail Price Improvement order `elp`: Enhanced Liquidity Program order (Deprecated; use `rpi`. Accepted until October 31, 2026.)
- `side` (string, optional) — Order side
- `posSide` (string, optional) — Position side
- `accFillSz` (string, optional) — Accumulated fill quantity
- `avgPx` (string, optional) — Average filled price. If none is filled, it will return "".
- `state` (string, optional) — State `canceled` `filled` `mmp_canceled`
- `fee` (string, optional) — Fee amount For Spot and Margin (excluding maker sell orders): accumulated fee charged by the platform, always negative For maker sell orders in Spot and Margin, Expiry Futures, Perpetual Futures and Options: accumulated fee and rebate (always in quote currency for maker sell orders in Spot and Margin)
- `pnl` (string, optional) — Profit and loss (excluding the fee). Applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
- `cancelSource` (string, optional) — Code of the cancellation source.
- `uTime` (string, optional) — Update time, Unix timestamp format in milliseconds, e.g. `1597026383085`
- `cTime` (string, optional) — Creation time, Unix timestamp format in milliseconds, e.g. `1597026383085`

## Examples

**Response**

```json
{
  "code": "0",
  "msg": "",
  "data": [
    {
      "instType": "SPOT",
      "instId": "BTC-USDT",
      "ordId": "680800019749904384",
      "clOrdId": "",
      "px": "",
      "sz": "100",
      "ordType": "market",
      "side": "buy",
      "posSide": "",
      "accFillSz": "0.00192834",
      "avgPx": "51858",
      "state": "filled",
      "fee": "-0.00000192834",
      "pnl": "0",
      "cancelSource": "",
      "uTime": "1708587373362",
      "cTime": "1708587373361",
      "algoClOrdId": "",
      "algoId": "",
      "attachAlgoClOrdId": "",
      "attachAlgoOrds": [],
      "cancelSourceReason": "",
      "category": "normal",
      "ccy": "",
      "feeCcy": "BTC",
      "fillPx": "51858",
      "fillSz": "0.00192834",
      "fillTime": "1708587373361",
      "isTpLimit": "false",
      "lever": "",
      "linkedAlgoOrd": {
        "algoId": ""
      },
      "pxType": "",
      "pxUsd": "",
      "pxVol": "",
      "quickMgnType": "",
      "rebate": "0",
      "rebateCcy": "USDT",
      "reduceOnly": "false",
      "slOrdPx": "",
      "slTriggerPx": "",
      "slTriggerPxType": "",
      "source": "",
      "stpId": "",
      "stpMode": "",
      "tag": "",
      "tdMode": "cash",
      "tgtCcy": "quote_ccy",
      "tpOrdPx": "",
      "tpTriggerPx": "",
      "tpTriggerPxType": "",
      "tradeId": "744876980",
      "tradeQuoteCcy": "USDT"
    }
  ]
}
```

**SDK Code**

```python trade_getOrdersHistory_example
import requests

url = "https://www.okx.com/api/v5/trade/orders-history"

querystring = {"instType":"SPOT"}

headers = {"OK-ACCESS-KEY": "<apiKey>"}

response = requests.get(url, headers=headers, params=querystring)

print(response.json())
```

```javascript trade_getOrdersHistory_example
const url = 'https://www.okx.com/api/v5/trade/orders-history?instType=SPOT';
const options = {method: 'GET', headers: {'OK-ACCESS-KEY': '<apiKey>'}};

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

```go trade_getOrdersHistory_example
package main

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

func main() {

	url := "https://www.okx.com/api/v5/trade/orders-history?instType=SPOT"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("OK-ACCESS-KEY", "<apiKey>")

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

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

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

}
```

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

url = URI("https://www.okx.com/api/v5/trade/orders-history?instType=SPOT")

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

request = Net::HTTP::Get.new(url)
request["OK-ACCESS-KEY"] = '<apiKey>'

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

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

HttpResponse<String> response = Unirest.get("https://www.okx.com/api/v5/trade/orders-history?instType=SPOT")
  .header("OK-ACCESS-KEY", "<apiKey>")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://www.okx.com/api/v5/trade/orders-history?instType=SPOT', [
  'headers' => [
    'OK-ACCESS-KEY' => '<apiKey>',
  ],
]);

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

```csharp trade_getOrdersHistory_example
using RestSharp;

var client = new RestClient("https://www.okx.com/api/v5/trade/orders-history?instType=SPOT");
var request = new RestRequest(Method.GET);
request.AddHeader("OK-ACCESS-KEY", "<apiKey>");
IRestResponse response = client.Execute(request);
```

```swift trade_getOrdersHistory_example
import Foundation

let headers = ["OK-ACCESS-KEY": "<apiKey>"]

let request = NSMutableURLRequest(url: NSURL(string: "https://www.okx.com/api/v5/trade/orders-history?instType=SPOT")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

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()
```