> ## Documentation Index
> Fetch the complete documentation index at: https://docs.services.payward.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Derivatives

> Offer perpetual futures trading through the US and International/EEA offerings: place orders, then track fills, positions and margin.

Use the Derivatives API to offer perpetual futures trading in your application. Eligible users can open long or short positions and monitor their exposure, PnL, and margin. Two regional offerings are available:

* **US:** For the US and its supported territories, with crypto perpetuals such as BTC and ETH.
* **International/EEA:** For other supported countries, with perpetuals on crypto, [xStocks](https://docs.services.payward.com/tabs/developer-documentation/get-started/asset-funding-rail-and-geo-coverage.md#supported-assets), equities, indices and commodities, such as BTC, AAPLx, AMD, US100 and gold.

Availability depends on the user's country and eligibility.

> [!WARNING]
>
> Derivatives functionality is currently available only in Sandbox.

## Prerequisites

* Payward Services API credentials and permission to access the user and account. See [Authentication](https://docs.services.payward.com/tabs/developer-documentation/get-started/authentication.md).
* A user with an account enabled for derivatives trading.
* Enough collateral in the account's derivatives balance. See [deposits and withdrawals](https://docs.services.payward.com/tabs/developer-documentation/payments/deposits-and-withdrawals.md) and [derivatives transfers](https://docs.services.payward.com/tabs/developer-documentation/payments/transfers.md#transfer-between-spot-and-futures).

Enable the following scopes in Payward Console on the API key used for this workflow:

| Scope | Used for |
| - | - |
| `query-funds` | Reading Portfolio balances and margin. |
| `withdraw-funds` | Transfers between spot and derivatives. |
| `query-open-trades` | Reading orders and positions. |
| `query-closed-trades` | Reading orders and trade history. |
| `modify-trades` | Placing and cancelling orders. |

[Get order](https://docs.services.payward.com/api-reference/derivatives-orders/get-order.md) and [List orders](https://docs.services.payward.com/api-reference/derivatives-orders/list-orders.md) require both `query-open-trades` and `query-closed-trades`, even when listing only open orders.

Enable `query-ledger` as well if you use Portfolio transaction history to track transfers or read settled funding payments. A cancellation-only key can use `close-trades` instead of `modify-trades`.

## Regional differences

Funding payments are exchanged between long and short positions, separately from trading fees. Positive rates mean longs pay shorts; negative rates mean shorts pay longs.

Both offerings follow the workflow below. The main differences are:

| Topic | US offering | International/EEA offering |
| - | - | - |
| Order quantities | Whole contracts; base-asset exposure depends on contract size. | Base-asset amounts for perpetuals. |
| Market statistics | Grouped by exchange trading day, which ends at 16:00 US Central Time. | Rolling 24-hour statistics. |
| Funding | Eight-hour rate intervals; daily settlement at 15:00 US Central Time. | Hourly rate intervals; settlement hourly or when the net position changes. |
| Client order IDs | Not supported. | Submission and filtering are supported. |
| Leverage settings API | Unavailable. | Isolated-margin overrides per instrument. |

## Workflow

1. [Discover markets](#step-1-discover-markets).
2. [Enable and fund the user](#step-2-enable-and-fund-the-user).
3. [Place an order](#step-3-place-an-order).
4. [Track orders and fills](#step-4-track-orders-and-fills).
5. [Monitor positions and margin](#step-5-monitor-positions-and-margin).

## Authentication setup

Authenticated endpoints require an HMAC-SHA512 request signature in the `API-Sign` header and the signing time in the `API-Timestamp` header. The helpers below compute both. The examples call `signed_headers` (`signedHeaders` in JavaScript) with the request's method, its path including any query string, and the exact body string they send. See the [Authentication guide](https://docs.services.payward.com/tabs/developer-documentation/get-started/authentication.md) for the full algorithm.

The examples read the API base URL from the `PWS_BASE_URL` environment variable, and your credentials from `PWS_API_KEY` and `PWS_API_SECRET`. Set `PWS_BASE_URL` to the sandbox or production base URL, listed in [Environments](https://docs.services.payward.com/tabs/developer-documentation/testing/overview.md#environments).

```python Python theme={null}
import base64
import hashlib
import hmac
import json
import os
import time
import uuid
from urllib.parse import urlencode

import requests

API_KEY = os.environ["PWS_API_KEY"]
API_SECRET = os.environ["PWS_API_SECRET"]
BASE_URL = os.environ["PWS_BASE_URL"]


def payward_signature(secret, timestamp, method, path_with_query, body=""):
    """Return the API-Sign value for one request.

    body is the exact string sent on the wire, or "" for a request without a body.
    """
    body_hash = hashlib.sha256(body.encode("utf-8")).hexdigest().upper()
    message = f"{timestamp}\n{method.upper()}\n{path_with_query}\n{body_hash}"
    mac = hmac.new(base64.b64decode(secret), message.encode("utf-8"), hashlib.sha512)
    return base64.b64encode(mac.digest()).decode()


def signed_headers(method, path_with_query, body="", idempotent=False):
    """Return the headers for one request, signed now."""
    timestamp = str(time.time_ns() // 1_000_000)
    headers = {
        "API-Key": API_KEY,
        "API-Timestamp": timestamp,
        "API-Sign": payward_signature(
            API_SECRET, timestamp, method, path_with_query, body
        ),
    }
    if body:
        headers["Content-Type"] = "application/json"
    if idempotent:
        headers["Idempotency-Key"] = str(uuid.uuid4())
    return headers
```

```javascript JavaScript theme={null}
import crypto from 'node:crypto';

const API_KEY = process.env.PWS_API_KEY;
const API_SECRET = process.env.PWS_API_SECRET;
const BASE_URL = process.env.PWS_BASE_URL;

/**
 * Returns the API-Sign value for one request.
 * `body` is the exact string sent on the wire, or '' for a request without a body.
 */
function paywardSignature(secret, timestamp, method, pathWithQuery, body = '') {
  const bodyHash = crypto.createHash('sha256').update(body, 'utf8').digest('hex').toUpperCase();
  const message = `${timestamp}\n${method.toUpperCase()}\n${pathWithQuery}\n${bodyHash}`;
  return crypto.createHmac('sha512', Buffer.from(secret, 'base64')).update(message, 'utf8').digest('base64');
}

/** Returns the headers for one request, signed now. */
function signedHeaders(method, pathWithQuery, body = '', { idempotent = false } = {}) {
  const timestamp = String(Date.now());
  const headers = {
    'API-Key': API_KEY,
    'API-Timestamp': timestamp,
    'API-Sign': paywardSignature(API_SECRET, timestamp, method, pathWithQuery, body),
  };
  if (body) {
    headers['Content-Type'] = 'application/json';
  }
  if (idempotent) {
    headers['Idempotency-Key'] = crypto.randomUUID();
  }
  return headers;
}
```

The examples use a US instrument. Set `PWS_ACCOUNT_ID` to the user's account ID. In Step 4, set `PWS_ORDER_ID` to the `data.id` returned by [Create order](https://docs.services.payward.com/api-reference/derivatives-orders/create-order.md).

The cURL examples read the signature headers from `PWS_API_TIMESTAMP` and `PWS_API_SIGN`. Compute both for each request, as [Authentication](https://docs.services.payward.com/tabs/developer-documentation/get-started/authentication.md) describes.

## Step 1: discover markets

Use [List instruments](https://docs.services.payward.com/api-reference/derivatives-instruments/list-instruments.md) to build the market browser. Read the instrument's contract size, quantity precision, and tick size before formatting quantities and prices. Its `base_asset` is the ticker of the underlying asset: for example, `AAPLx` for `PF_AAPLXUSD`, a perpetual on the AAPLx [xStock](https://docs.services.payward.com/tabs/developer-documentation/get-started/asset-funding-rail-and-geo-coverage.md#supported-assets), and `AMD` for `PF_AMDUSD`, a perpetual on AMD stock.

Use [Get ticker](https://docs.services.payward.com/api-reference/derivatives-tickers/get-ticker.md), [Get order book](https://docs.services.payward.com/api-reference/derivatives-order-books/get-order-book.md), and [Get OHLC history](https://docs.services.payward.com/api-reference/derivatives-ohlc/get-ohlc-history.md) for the selected market.

These routes require API authentication, even when your application shows markets before the user signs in. Each also requires `country`, which selects the offering. See each endpoint's reference for its other filters.

The example fetches the first page. For a complete instrument list, pass each response's `next_page_token` as `page_token`, keeping the filters and sort order unchanged. Continue until the token is absent, even if a page is empty.

```python Python theme={null}
def list_instruments():
    params = {"country": "US", "asset_type": "perpetual", "page_size": 20}
    path = f"/v1/instruments?{urlencode(params)}"

    response = requests.get(
        BASE_URL + path, headers=signed_headers("GET", path), timeout=10
    )
    response.raise_for_status()
    return response.json()


instruments = list_instruments()
print(instruments)
```

```javascript JavaScript theme={null}
async function listInstruments() {
  const params = new URLSearchParams({ country: 'US', asset_type: 'perpetual', page_size: 20 });
  const path = `/v1/instruments?${params}`;

  const response = await fetch(BASE_URL + path, {
    method: 'GET',
    headers: signedHeaders('GET', path),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const instruments = await listInstruments();
console.log(instruments);
```

```bash cURL theme={null}
curl -X GET "$PWS_BASE_URL/v1/instruments?country=US&asset_type=perpetual&page_size=20" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN"
```

## Step 2: enable and fund the user

Completing identity verification alone does not confirm derivatives approval.

Once approved, use [List user instruments](https://docs.services.payward.com/api-reference/derivatives-instruments/list-user-instruments.md) or [Get user instrument](https://docs.services.payward.com/api-reference/derivatives-instruments/get-user-instrument.md) to check the user's available markets. Selecting a country-scoped catalog does not change that user's eligibility.

Use [Create derivatives transfer](https://docs.services.payward.com/api-reference/derivatives-transfers/create-derivatives-transfer.md) to move funds from spot into the account's derivatives balance: `futures` in the transfer request and `assets[].balances.derivatives` in [Get portfolio](https://docs.services.payward.com/api-reference/portfolio/get-portfolio.md).

> [!NOTE]
>
> For the US offering, derivatives transfers support USD only.
>
> For International/EEA, see Kraken's [supported collateral currencies, haircuts and conversion fees](https://support.kraken.com/articles/collateral-currencies-eea). Kraken's [funding guide](https://support.kraken.com/articles/360022627692-funding-your-derivatives-account) lists transfer minimums.

For example, transfer USD 1,000:

```python Python theme={null}
def create_derivatives_transfer(account_id):
    path = f"/v1/accounts/{account_id}/transfers/derivatives"
    body = json.dumps({"asset": "USD", "amount": "1000.00", "from": "spot", "to": "futures"})

    response = requests.post(
        BASE_URL + path, headers=signed_headers("POST", path, body),
        data=body, timeout=10,
    )
    response.raise_for_status()
    return response.json()


transfer = create_derivatives_transfer(os.environ["PWS_ACCOUNT_ID"])
print(transfer)
```

```javascript JavaScript theme={null}
async function createDerivativesTransfer(accountId) {
  const path = `/v1/accounts/${accountId}/transfers/derivatives`;
  const body = JSON.stringify({ asset: 'USD', amount: '1000.00', from: 'spot', to: 'futures' });

  const response = await fetch(BASE_URL + path, {
    method: 'POST',
    headers: signedHeaders('POST', path, body),
    body,
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const transfer = await createDerivativesTransfer(process.env.PWS_ACCOUNT_ID);
console.log(transfer);
```

```bash cURL theme={null}
curl -X POST "$PWS_BASE_URL/v1/accounts/$PWS_ACCOUNT_ID/transfers/derivatives" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN" \
  -H "Content-Type: application/json" \
  -d '{
  "asset": "USD",
  "amount": "1000.00",
  "from": "spot",
  "to": "futures"
}'
```

A status of `accepted` means processing has started. For the requested asset, check `assets[].balances.derivatives.total` in [Get portfolio](https://docs.services.payward.com/api-reference/portfolio/get-portfolio.md) to confirm the destination balance. To check funds available to move back to spot, use `assets[].balances.derivatives.available`.

Derivatives transfers are not idempotent: retrying can create a second transfer. If the outcome is unclear, reconcile it as described in [Track the transfer](https://docs.services.payward.com/tabs/developer-documentation/payments/transfers.md#track-the-transfer) before trying again. That section also says when to contact Payward Services support.

### Optional: set leverage for International/EEA users

For International/EEA users, [Set leverage settings](https://docs.services.payward.com/api-reference/derivatives-leverage/set-leverage-settings.md) and [Get leverage settings](https://docs.services.payward.com/api-reference/derivatives-leverage/get-leverage-settings.md) manage isolated-margin overrides. Read the user's leverage limit from [Get user instrument](https://docs.services.payward.com/api-reference/derivatives-instruments/get-user-instrument.md) before offering an override. A change affects existing positions and open orders and can be rejected by margin or risk checks.

## Step 3: place an order

Use [Create order](https://docs.services.payward.com/api-reference/derivatives-orders/create-order.md) with the selected account.

For example, buy two US perpetual contracts with a limit price of USD 80,000 per BTC. With a `contract_size` of `0.01`, two contracts represent 0.02 BTC.

```python Python theme={null}
def create_order(account_id):
    path = f"/v1/accounts/{account_id}/orders"
    body = json.dumps({"asset_type": "perpetual", "type": "limit", "symbol": "PBTCUCZ0.BTNL", "side": "buy", "quantity": "2", "limit_price": "80000", "time_in_force": "gtc"})

    response = requests.post(
        BASE_URL + path, headers=signed_headers("POST", path, body),
        data=body, timeout=10,
    )
    response.raise_for_status()
    return response.json()


order = create_order(os.environ["PWS_ACCOUNT_ID"])
print(order)
```

```javascript JavaScript theme={null}
async function createOrder(accountId) {
  const path = `/v1/accounts/${accountId}/orders`;
  const body = JSON.stringify({
    asset_type: 'perpetual',
    type: 'limit',
    symbol: 'PBTCUCZ0.BTNL',
    side: 'buy',
    quantity: '2',
    limit_price: '80000',
    time_in_force: 'gtc',
  });

  const response = await fetch(BASE_URL + path, {
    method: 'POST',
    headers: signedHeaders('POST', path, body),
    body,
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const order = await createOrder(process.env.PWS_ACCOUNT_ID);
console.log(order);
```

```bash cURL theme={null}
curl -X POST "$PWS_BASE_URL/v1/accounts/$PWS_ACCOUNT_ID/orders" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN" \
  -H "Content-Type: application/json" \
  -d '{
  "asset_type": "perpetual",
  "type": "limit",
  "symbol": "PBTCUCZ0.BTNL",
  "side": "buy",
  "quantity": "2",
  "limit_price": "80000",
  "time_in_force": "gtc"
}'
```

Store the returned order ID and use [Get order](https://docs.services.payward.com/api-reference/derivatives-orders/get-order.md) to check its status and `filled_quantity`. A successful *Create order* response does not guarantee the order stays open. See [Track orders and fills](#step-4-track-orders-and-fills) for ongoing updates.

For International/EEA orders, you can supply [`client_order_id`](https://docs.services.payward.com/api-reference/derivatives-orders/create-order), an optional reference you assign to correlate the order and its fills. Use a lowercase, hyphenated UUID. Reusing an ID held by an active order or pending trigger in the same account returns `409`. Once the original order or trigger is no longer active, reusing the ID can create another order. This field is not an idempotency key; the retry guidance below still applies. US orders don't support `client_order_id` yet and return `400` if you send it, so match their fills to the order by `order_id`.

[List orders](https://docs.services.payward.com/api-reference/derivatives-orders/list-orders.md) returns only open orders by default. If an order's outcome is uncertain, check `state=open` first, then `state=closed`, following pagination for both.

If the response is HTTP `503` with an `error.code` of `order_request_not_submitted`, or HTTP `504` with `request_expired_before_submission`, the order was not submitted, so retry with backoff. Do not automatically resubmit after HTTP `504` with `order_outcome_unknown`, or after a timeout without a definitive result. If the outcome remains unclear, contact Payward Services support with the `X-Trace-Id` response header. See the `503` and `504` responses of *Create order*.

## Step 4: track orders and fills

Subscribe to [`derivatives.order_updated`](https://docs.services.payward.com/api-reference/webhooks/derivatives-order-updated) for order placement, changes, fills, cancellations, expiry and rejection, and [`derivatives.trade_executed`](https://docs.services.payward.com/api-reference/webhooks/derivatives-trade-executed) for individual fills, including liquidations. See each event's API reference for coverage and [Receiving webhooks](https://docs.services.payward.com/tabs/developer-documentation/webhooks/receiving-webhooks.md) for setup and delivery handling.

> [!NOTE]
>
> Derivatives webhooks are currently available only in Sandbox. Alternatively, poll *Get order*; stop once the order's
> `status` is `closed`, `cancelled`, or `expired`.

Use *Get order* after order creation, to track International/EEA trigger orders, and to reconcile missed or out-of-order updates.

Use [List orders](https://docs.services.payward.com/api-reference/derivatives-orders/list-orders.md) for open and closed orders, and [List trades](https://docs.services.payward.com/api-reference/derivatives-trades/list-trades.md) for executions. *List orders* returns open orders by default; pass `state=closed` for closed orders. Pass `order_id` to *List trades* to retrieve executions for a specific order. Use each order's `filled_quantity` to track execution; an order `status` of `closed` does not guarantee a full fill. For International/EEA requests, you can also filter both lists by the submitted `client_order_id`. This filter is case-sensitive. The *List trades* example below fetches only the first page. For complete order and trade listings, pass each response's `next_page_token` as `page_token`, keeping the account and filters unchanged, and continue until the token is absent.

### Get order

```python Python theme={null}
def get_order(account_id, order_id):
    path = f"/v1/accounts/{account_id}/orders/{order_id}"

    response = requests.get(
        BASE_URL + path, headers=signed_headers("GET", path), timeout=10
    )
    response.raise_for_status()
    return response.json()


fetched_order = get_order(os.environ["PWS_ACCOUNT_ID"], os.environ["PWS_ORDER_ID"])
print(fetched_order)
```

```javascript JavaScript theme={null}
async function getOrder(accountId, orderId) {
  const path = `/v1/accounts/${accountId}/orders/${orderId}`;

  const response = await fetch(BASE_URL + path, {
    method: 'GET',
    headers: signedHeaders('GET', path),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const fetchedOrder = await getOrder(process.env.PWS_ACCOUNT_ID, process.env.PWS_ORDER_ID);
console.log(fetchedOrder);
```

```bash cURL theme={null}
curl -X GET "$PWS_BASE_URL/v1/accounts/$PWS_ACCOUNT_ID/orders/$PWS_ORDER_ID" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN"
```

### List closed orders

```python Python theme={null}
def list_closed_orders(account_id):
    params = {"asset_type": "perpetual", "state": "closed", "page_size": 100}
    path = f"/v1/accounts/{account_id}/orders?{urlencode(params)}"

    response = requests.get(
        BASE_URL + path, headers=signed_headers("GET", path), timeout=10
    )
    response.raise_for_status()
    return response.json()


orders = list_closed_orders(os.environ["PWS_ACCOUNT_ID"])
print(orders)
```

```javascript JavaScript theme={null}
async function listClosedOrders(accountId) {
  const params = new URLSearchParams({ asset_type: 'perpetual', state: 'closed', page_size: 100 });
  const path = `/v1/accounts/${accountId}/orders?${params}`;

  const response = await fetch(BASE_URL + path, {
    method: 'GET',
    headers: signedHeaders('GET', path),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const orders = await listClosedOrders(process.env.PWS_ACCOUNT_ID);
console.log(orders);
```

```bash cURL theme={null}
curl -X GET "$PWS_BASE_URL/v1/accounts/$PWS_ACCOUNT_ID/orders?asset_type=perpetual&state=closed&page_size=100" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN"
```

### List trades

```python Python theme={null}
def list_trades(account_id, order_id):
    params = {"asset_type": "perpetual", "order_id": order_id, "page_size": 100}
    path = f"/v1/accounts/{account_id}/trades?{urlencode(params)}"

    response = requests.get(
        BASE_URL + path, headers=signed_headers("GET", path), timeout=10
    )
    response.raise_for_status()
    return response.json()


trades = list_trades(os.environ["PWS_ACCOUNT_ID"], os.environ["PWS_ORDER_ID"])
print(trades)
```

```javascript JavaScript theme={null}
async function listTrades(accountId, orderId) {
  const params = new URLSearchParams({ asset_type: 'perpetual', order_id: orderId, page_size: 100 });
  const path = `/v1/accounts/${accountId}/trades?${params}`;

  const response = await fetch(BASE_URL + path, {
    method: 'GET',
    headers: signedHeaders('GET', path),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const trades = await listTrades(process.env.PWS_ACCOUNT_ID, process.env.PWS_ORDER_ID);
console.log(trades);
```

```bash cURL theme={null}
curl -X GET "$PWS_BASE_URL/v1/accounts/$PWS_ACCOUNT_ID/trades?asset_type=perpetual&order_id=$PWS_ORDER_ID&page_size=100" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN"
```

After [Cancel order](https://docs.services.payward.com/api-reference/derivatives-orders/cancel-order.md), refresh the order status with [Get order](https://docs.services.payward.com/api-reference/derivatives-orders/get-order.md).

## Step 5: monitor positions and margin

Use [List open positions](https://docs.services.payward.com/api-reference/portfolio/list-open-positions.md) for exposure and position PnL. Use [Get portfolio](https://docs.services.payward.com/api-reference/portfolio/get-portfolio.md) for collateral, account-level PnL, and margin requirements and capacity. Refresh both as orders fill and market prices change.

Use [List funding history](https://docs.services.payward.com/api-reference/portfolio/list-funding-history.md) to read settled funding payments. These are separate from trading PnL and execution fees.

### List open positions

```python Python theme={null}
def list_positions(account_id):
    params = {"asset_type": "perpetual"}
    path = f"/v1/accounts/{account_id}/positions?{urlencode(params)}"

    response = requests.get(
        BASE_URL + path, headers=signed_headers("GET", path), timeout=10
    )
    response.raise_for_status()
    return response.json()


positions = list_positions(os.environ["PWS_ACCOUNT_ID"])
print(positions)
```

```javascript JavaScript theme={null}
async function listPositions(accountId) {
  const params = new URLSearchParams({ asset_type: 'perpetual' });
  const path = `/v1/accounts/${accountId}/positions?${params}`;

  const response = await fetch(BASE_URL + path, {
    method: 'GET',
    headers: signedHeaders('GET', path),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const positions = await listPositions(process.env.PWS_ACCOUNT_ID);
console.log(positions);
```

```bash cURL theme={null}
curl -X GET "$PWS_BASE_URL/v1/accounts/$PWS_ACCOUNT_ID/positions?asset_type=perpetual" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN"
```

### Get portfolio

```python Python theme={null}
def get_portfolio(account_id):
    params = {"quote_symbol": "USD", "quote_type": "fiat"}
    path = f"/v1/accounts/{account_id}/portfolio?{urlencode(params)}"

    response = requests.get(
        BASE_URL + path, headers=signed_headers("GET", path), timeout=10
    )
    response.raise_for_status()
    return response.json()


portfolio = get_portfolio(os.environ["PWS_ACCOUNT_ID"])
print(portfolio)
```

```javascript JavaScript theme={null}
async function getPortfolio(accountId) {
  const params = new URLSearchParams({ quote_symbol: 'USD', quote_type: 'fiat' });
  const path = `/v1/accounts/${accountId}/portfolio?${params}`;

  const response = await fetch(BASE_URL + path, {
    method: 'GET',
    headers: signedHeaders('GET', path),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response.json();
}

const portfolio = await getPortfolio(process.env.PWS_ACCOUNT_ID);
console.log(portfolio);
```

```bash cURL theme={null}
curl -X GET "$PWS_BASE_URL/v1/accounts/$PWS_ACCOUNT_ID/portfolio?quote_symbol=USD&quote_type=fiat" \
  -H "API-Key: $PWS_API_KEY" \
  -H "API-Timestamp: $PWS_API_TIMESTAMP" \
  -H "API-Sign: $PWS_API_SIGN"
```

## Error handling

Read the HTTP status, `error.code`, and any `error.causes`. Use codes for application decisions; messages can change.

| HTTP status | Code | Cause | Remediation |
| - | - | - | - |
| `400` | `bad_request` | Invalid account, instrument, or order parameters. | Correct the fields identified in `error.causes`. |
| `401` | `unauthenticated` or `gateway` | Credentials or request signing failed. | Check the API key and signature before retrying. |
| `403` | `forbidden` or `gateway` | Access is not permitted. | Check account permissions and eligibility. Resolve the restriction first. |
| `403` | `trading_not_allowed` | Derivatives trading is not allowed for this user. | Check the user's derivatives access and onboarding status before retrying. |
| `403` | `account_trading_suspended` | Order entry is suspended. | Stop order entry for the account and contact support. |
| `404` | `order_not_found` | No order with this ID exists in the account. | Check the order ID and the `account_id` in the path. |
| `409` | `order_insufficient_funds` | Collateral or available margin is insufficient. | Fund the derivatives balance or reduce the order size. |
| `409` | `order_must_reduce_position` | The order would not reduce an existing position. | Check the existing position and the order’s `reduce_only` setting. |
| `429` | `resource_exhausted` | Rate limit exceeded. | Honor `Retry-After` if present; otherwise back off before retrying. |

For other order rejections, follow the [Create order reference](https://docs.services.payward.com/api-reference/derivatives-orders/create-order.md) before resubmitting.

## API reference

| Method | Endpoint | Description |
| - | - | - |
| GET | [`/v1/instruments`](https://docs.services.payward.com/api-reference/derivatives-instruments/list-instruments) | List instruments |
| GET | [`/v1/instruments/{asset_type}/{symbol}`](https://docs.services.payward.com/api-reference/derivatives-instruments/get-instrument) | Get instrument metadata |
| GET | [`/v1/tickers/{asset_type}/{symbol}`](https://docs.services.payward.com/api-reference/derivatives-tickers/get-ticker) | Get current market data |
| GET | [`/v1/orderbooks/{asset_type}/{symbol}`](https://docs.services.payward.com/api-reference/derivatives-order-books/get-order-book) | Get the order book |
| GET | [`/v1/ohlc/{asset_type}/{symbol}`](https://docs.services.payward.com/api-reference/derivatives-ohlc/get-ohlc-history) | Get recent candles |
| POST | [`/v1/accounts/{account_id}/orders`](https://docs.services.payward.com/api-reference/derivatives-orders/create-order) | Create an order |
| GET | [`/v1/accounts/{account_id}/orders`](https://docs.services.payward.com/api-reference/derivatives-orders/list-orders) | List active orders or history |
| GET | [`/v1/accounts/{account_id}/orders/{order_id}`](https://docs.services.payward.com/api-reference/derivatives-orders/get-order) | Get an order |
| POST | [`/v1/accounts/{account_id}/orders/{order_id}/cancel`](https://docs.services.payward.com/api-reference/derivatives-orders/cancel-order) | Request cancellation |
| GET | [`/v1/accounts/{account_id}/trades`](https://docs.services.payward.com/api-reference/derivatives-trades/list-trades) | List executions |
| GET | [`/v1/accounts/{account_id}/trades/{trade_id}`](https://docs.services.payward.com/api-reference/derivatives-trades/get-trade) | Get an execution |
| PUT | [`/v1/accounts/{account_id}/leverage-settings/{asset_type}/{symbol}`](https://docs.services.payward.com/api-reference/derivatives-leverage/set-leverage-settings) | Set a leverage override |
| GET | [`/v1/accounts/{account_id}/leverage-settings`](https://docs.services.payward.com/api-reference/derivatives-leverage/get-leverage-settings) | Get leverage overrides |
| GET | [`/v1/accounts/{account_id}/positions`](https://docs.services.payward.com/api-reference/portfolio/list-open-positions) | List open positions |
| GET | [`/v1/accounts/{account_id}/funding-history`](https://docs.services.payward.com/api-reference/portfolio/list-funding-history) | List settled funding payments |
| GET | [`/v1/accounts/{account_id}/portfolio`](https://docs.services.payward.com/api-reference/portfolio/get-portfolio) | Get collateral, PnL, and margin |

The reference also includes user-scoped instrument, ticker, order-book, and OHLC routes. See each endpoint for field definitions, execution policies, and pagination rules.
