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

# Position builder

POST https://www.okx.com/api/v5/account/position-builder
Content-Type: application/json

Calculate the portfolio margin information for virtual (simulated) positions and/or existing positions, only applicable to portfolio margin accounts.

Reference: https://okx-demo.ferndocs.com/api/api-reference/account/position-builder

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

- `acctLv` (string, optional) — Account level for the simulation.
- `inclRealPosAndEq` (boolean, optional) — Whether to include existing positions and account balance. Default true.
- `lever` (string, optional) — Leverage used for the simulation.
- `greeksType` (enum, optional) — Greeks type.
  - Allowed values: `BS`, `PA`, `CASH`
- `simPos` (list of ApiV5AccountPositionBuilderPostRequestBodyContentApplicationJsonSchemaSimPosItems, optional) — List of simulated positions.
- `simAsset` (list of ApiV5AccountPositionBuilderPostRequestBodyContentApplicationJsonSchemaSimAssetItems, optional) — List of simulated assets.
- `idxVol` (string, optional) — Volatility of the index used in the simulation.

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

## Types

### ApiV5AccountPositionBuilderPostRequestBodyContentApplicationJsonSchemaSimPosItems

- `instId` (string, optional) — Instrument ID, e.g. BTC-USDT-SWAP.
- `pos` (string, optional) — Quantity of position.

### ApiV5AccountPositionBuilderPostRequestBodyContentApplicationJsonSchemaSimAssetItems

- `ccy` (string, optional) — Currency.
- `amt` (string, optional) — Amount of the currency.

### ApiV5AccountPositionBuilderPostResponsesContentApplicationJsonSchemaDataItems

- `eq` (string, optional) — Account equity in USD.
- `totalMmr` (string, optional) — Total maintenance margin requirement in USD.
- `borrowMmr` (string, optional) — Borrow maintenance margin requirement in USD.
- `derivMmr` (string, optional) — Derivatives maintenance margin requirement in USD.
- `marginBal` (string, optional) — Margin balance in USD.
- `upl` (string, optional) — Unrealized profit and loss in USD.
- `riskUnitData` (list of ApiV5AccountPositionBuilderPostResponsesContentApplicationJsonSchemaDataItemsRiskUnitDataItems, optional) — Risk unit details.

### ApiV5AccountPositionBuilderPostResponsesContentApplicationJsonSchemaDataItemsRiskUnitDataItems

- `riskUnit` (string, optional) — Risk unit identifier.
- `mmr` (string, optional) — Maintenance margin requirement of the risk unit.
- `imr` (string, optional) — Initial margin requirement of the risk unit.

## Examples

**Request**

```json
{}
```

**Response**

```json
{
  "code": "0",
  "msg": "",
  "data": [
    {
      "eq": "-78553.21888979999",
      "totalMmr": "2946.5480841048",
      "borrowMmr": "1571.064377796",
      "derivMmr": "1375.4837063088003",
      "upl": "-78653.1728898",
      "riskUnitData": [
        {
          "riskUnit": "BTC",
          "mmr": "1183.8207318516002",
          "imr": "1538.9669514070802",
          "delta": "-9704.903689800001",
          "gamma": "0",
          "imrBf": "",
          "mmrBf": "",
          "mr1": "1164.4109244719994",
          "mr1FinalResult": {
            "pnl": "-1164.4109244719994",
            "spotShock": "0.12",
            "volShock": "up"
          },
          "mr1Scenarios": {
            "volSame": {
              "0": "0",
              "-0.04": "388.1369748240002",
              "-0.08": "776.2739496480004",
              "-0.12": "1164.4109244719994",
              "0.04": "-388.1369748240002",
              "0.08": "-776.2739496480004",
              "0.12": "-1164.4109244719994"
            },
            "volShockDown": {
              "0": "0",
              "-0.04": "388.1369748240002",
              "-0.08": "776.2739496480004",
              "-0.12": "1164.4109244719994",
              "0.04": "-388.1369748240002",
              "0.08": "-776.2739496480004",
              "0.12": "-1164.4109244719994"
            },
            "volShockUp": {
              "0": "0",
              "-0.04": "388.1369748240002",
              "-0.08": "776.2739496480004",
              "-0.12": "1164.4109244719994",
              "0.04": "-388.1369748240002",
              "0.08": "-776.2739496480004",
              "0.12": "-1164.4109244719994"
            }
          },
          "mr2": "0",
          "mr3": "0",
          "mr4": "19.4098073796",
          "mr5": "0",
          "mr6": "1164.4109244720003",
          "mr6FinalResult": {
            "pnl": "-2328.8218489440005",
            "spotShock": "0.24"
          },
          "mr7": "43.67206660410001",
          "mr8": "1571.064377796",
          "mr9": "0",
          "portfolios": [
            {
              "amt": "-10",
              "avgPx": "100000",
              "delta": "-9704.903689800001",
              "floatPnl": "290.6300000000003",
              "gamma": "0",
              "instId": "BTC-USDT-SWAP",
              "instType": "SWAP",
              "isRealPos": false,
              "markPx": "97093.7",
              "markPxBf": "",
              "notionalUsd": "9703.22",
              "posSide": "net",
              "theta": "0",
              "vega": "0"
            }
          ],
          "theta": "0",
          "upl": "290.49631020000027",
          "vega": "0"
        },
        {
          "riskUnit": "LTC",
          "mmr": "191.6629744572",
          "imr": "249.16186679436",
          "delta": "1019.5308",
          "gamma": "0",
          "imrBf": "",
          "mmrBf": "",
          "mr1": "183.50672805719995",
          "mr1FinalResult": {
            "pnl": "-183.50672805719995",
            "spotShock": "-0.18",
            "volShock": "up"
          },
          "mr1Scenarios": {
            "volSame": {
              "0": "0",
              "-0.06": "-61.168909352399936",
              "-0.12": "-122.33781870480001",
              "-0.18": "-183.50672805719995",
              "0.06": "61.168909352399936",
              "0.12": "122.33781870480001",
              "0.18": "183.50672805719995"
            },
            "volShockDown": {
              "0": "0",
              "-0.06": "-61.168909352399936",
              "-0.12": "-122.33781870480001",
              "-0.18": "-183.50672805719995",
              "0.06": "61.168909352399936",
              "0.12": "122.33781870480001",
              "0.18": "183.50672805719995"
            },
            "volShockUp": {
              "0": "0",
              "-0.06": "-61.168909352399936",
              "-0.12": "-122.33781870480001",
              "-0.18": "-183.50672805719995",
              "0.06": "61.168909352399936",
              "0.12": "122.33781870480001",
              "0.18": "183.50672805719995"
            }
          },
          "mr2": "0",
          "mr3": "0",
          "mr4": "8.1562464",
          "mr5": "0",
          "mr6": "183.5067280572",
          "mr6FinalResult": {
            "pnl": "-367.0134561144",
            "spotShock": "-0.36"
          },
          "mr7": "7.1367156",
          "mr8": "1571.064377796",
          "mr9": "0",
          "portfolios": [
            {
              "amt": "10",
              "avgPx": "8000",
              "delta": "1019.5308",
              "floatPnl": "-78980",
              "gamma": "0",
              "instId": "LTC-USDT-SWAP",
              "instType": "SWAP",
              "isRealPos": false,
              "markPx": "102",
              "markPxBf": "",
              "notionalUsd": "1018.9",
              "posSide": "net",
              "theta": "0",
              "vega": "0"
            }
          ],
          "theta": "0",
          "upl": "-78943.6692",
          "vega": "0"
        }
      ],
      "acctLever": "-0.1364949794742562",
      "assets": [
        {
          "availEq": "0",
          "borrowImr": "0",
          "borrowMmr": "",
          "ccy": "BTC",
          "spotInUse": "0"
        },
        {
          "availEq": "0",
          "borrowImr": "0",
          "borrowMmr": "",
          "ccy": "LTC",
          "spotInUse": "0"
        },
        {
          "availEq": "0",
          "borrowImr": "0",
          "borrowMmr": "",
          "ccy": "USDC",
          "spotInUse": "0"
        },
        {
          "availEq": "-78589.37",
          "borrowImr": "7855.32188898",
          "borrowMmr": "",
          "ccy": "USDT",
          "spotInUse": "0"
        }
      ],
      "marginRatio": "-25.95365779811705",
      "positions": [],
      "totalImr": "9643.45070718144",
      "ts": "1736936801642"
    }
  ]
}
```

**SDK Code**

```python account_positionBuilder_example
import requests

url = "https://www.okx.com/api/v5/account/position-builder"

payload = {}
headers = {
    "OK-ACCESS-KEY": "<apiKey>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript account_positionBuilder_example
const url = 'https://www.okx.com/api/v5/account/position-builder';
const options = {
  method: 'POST',
  headers: {'OK-ACCESS-KEY': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{}'
};

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

```go account_positionBuilder_example
package main

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

func main() {

	url := "https://www.okx.com/api/v5/account/position-builder"

	payload := strings.NewReader("{}")

	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 account_positionBuilder_example
require 'uri'
require 'net/http'

url = URI("https://www.okx.com/api/v5/account/position-builder")

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 = "{}"

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

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

HttpResponse<String> response = Unirest.post("https://www.okx.com/api/v5/account/position-builder")
  .header("OK-ACCESS-KEY", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://www.okx.com/api/v5/account/position-builder', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
    'OK-ACCESS-KEY' => '<apiKey>',
  ],
]);

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

```csharp account_positionBuilder_example
using RestSharp;

var client = new RestClient("https://www.okx.com/api/v5/account/position-builder");
var request = new RestRequest(Method.POST);
request.AddHeader("OK-ACCESS-KEY", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift account_positionBuilder_example
import Foundation

let headers = [
  "OK-ACCESS-KEY": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://www.okx.com/api/v5/account/position-builder")! 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()
```