# Welcome

Welcome to sFOX APIs. sFOX is a unified prime brokerage for professional investors, providing global liquidity, flexible & scaleable credit, and bankruptcy-safe custody in a fully integrated and high-performance platform.

## APIs

sFOX offers feature-rich REST, WebSocket, and FIX APIs to access market data, manage your account, and create/cancel orders.

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>REST API</strong></td><td>For trading and general requests.</td><td></td><td><a href="/pages/uNE3QRhQ3rD6U6LaDQOV">/pages/uNE3QRhQ3rD6U6LaDQOV</a></td></tr><tr><td><strong>WebSocket API</strong></td><td>For real-time market data and account updates.</td><td></td><td><a href="/pages/X2NwSb3SpynHCChfDWeJ">/pages/X2NwSb3SpynHCChfDWeJ</a></td></tr><tr><td><strong>FIX API</strong></td><td>For higher-frequency trading and real-time market data.</td><td></td><td><a href="/pages/fQIAgXMnkJAxObvhX1oq">/pages/fQIAgXMnkJAxObvhX1oq</a></td></tr></tbody></table>


# Getting Started

Follow these steps to get started with sFOX APIs.

## Create an sFOX Account

Sign up at [sFOX](https://trade.sfox.com/signup).

## Setup

**1. Create an API Key:** Navigate your account menu -> API  ([or click here](https://trade.sfox.com/account/api)) and click the 'Generate API Key' button.

<div align="left"><figure><img src="/files/qaa0oybya5CEfcwItbCu" alt="" width="375"><figcaption></figcaption></figure></div>

**2. Authenticate:** See [REST API Authentication documentation](/rest-api/authentication) to learn about authenticating your requests with your API key.

**3. Select an API:**

* [REST API](/rest-api/rest-endpoints): For trading and general requests.
* [WebSocket API](/websocket-api/introduction): For real-time market data and account updates.
* [FIX API](/fix-api/fix): For higher-frequency trading and real-time market data.

{% hint style="info" %}
Our team is happy to assist you with your selection. Contact us at <support@sfox.com>.
{% endhint %}

## Examples

View examples of REST, WebSocket, an FIX APIs within the documentation.

Example code is included throughout this documentation. For example:

* [Create an Order (REST)](/rest-api/orders/create-order)
* [Stream an Order Book (WebSocket)](/websocket-api/market-data/order-book)
* [Request a Quote (FIX)](/fix-api/fix#requestforquote-r)


# Systems & Operations

## Production URLs

Use the following URLs to connect to sFOX production APIs. For testing, see Sandbox URLs.

<table><thead><tr><th width="281">API</th><th>URL</th></tr></thead><tbody><tr><td><strong>REST API</strong></td><td><strong><code>https://api.sfox.com</code></strong></td></tr><tr><td><strong>REST API</strong><br>(<a href="/pages/HoUS6l45i8X7tYKJBIbb">Candlestick / OHLCV </a>Data)</td><td><strong><code>https://chartdata.sfox.com</code></strong></td></tr><tr><td><strong>WebSocket API</strong></td><td><strong><code>wss://ws.sfox.com/ws</code></strong></td></tr><tr><td><strong>FIX API - Order Entry</strong></td><td><strong><code>fix.sfox.com:5001</code></strong></td></tr><tr><td><strong>FIX API – Market Data</strong></td><td><strong><code>fix-md.sfox.com:5001</code></strong></td></tr></tbody></table>

## Sandbox URLs

Use the following URLs to test your API connectivity.&#x20;

{% hint style="info" %}
API keys are separate from production. Sign in to the [sandbox interface](https://beta.sfox.com) to create an API key. Contact us at <support@sfox.com> for assistance configuring and funding your sandbox account.
{% endhint %}

{% hint style="warning" %}
Sandbox hosts a subset of order books and liquidity does not reflect production. Sandbox supports all functionality except transfers.
{% endhint %}

<table><thead><tr><th width="281">API</th><th>URL</th></tr></thead><tbody><tr><td><strong>REST API</strong></td><td><strong><code>https://api.staging.sfox.com</code></strong></td></tr><tr><td><strong>WebSocket API</strong></td><td><strong><code>wss://ws.staging.sfox.com/ws</code></strong></td></tr><tr><td><strong>FIX API - Order Entry</strong></td><td><strong><code>fix.staging.sfox.com:5001</code></strong></td></tr><tr><td><strong>FIX API – Market Data</strong></td><td><strong><code>fix-md.staging.sfox.com:5001</code></strong></td></tr></tbody></table>

## Availability Zones

The infrastructure for the sFOX platform is hosted in **US-EAST-1 (AWS)** within multiple availability zones:

* use1-az6
* use1-az1
* use1-az2


# Rate Limits

## [REST API Rate Limits](/rest-api/rate-limits)

The REST API rate limits requests by IP address **AND**, in some cases, by route.

* **IP Address:** 250 requests per 10 seconds.&#x20;
  * If you exceed this, a `429` error is thrown and you have to wait 60 seconds before resuming.
* **Route-specific limits:** Routes with unique rate limits are specified in the route details within this documentation. e.g. [Get All Done Orders](/rest-api/orders/get-all-done-orders).
  * If the route details do NOT specify a rate limit then the route does not have a specific rate limit.
  * If you exceed this, a `429` error is thrown and you have to wait 10 seconds before resuming **requests to this specific route.**

{% hint style="info" %}
sFOX recommends using the [**WebSocket API**](/websocket-api/introduction) for retrieving data as much as possible as this will not count towards the request limit.

**Note:** sFOX typically enforces route-specific rate limits on routes that return data that is available via the [**WebSocket API**](/websocket-api/introduction) e.g. account balances.
{% endhint %}

## [WebSocket API Rate Limits](/websocket-api/rate-limits)

The WebSocket API rate limits requests and connections by IP address. If you exceed a rate limit, an error is thrown and your requests will be blocked for 2 minutes. Rate limits for the WebSocket API are as follows:

<table><thead><tr><th width="147">Type</th><th>Limit</th></tr></thead><tbody><tr><td><strong>Connections</strong></td><td><strong>10 active connections</strong> per IP address.</td></tr><tr><td><strong>Requests</strong></td><td><strong>40 requests per 1 minute</strong> per IP address. Requests are counted, in total, across your active connections.</td></tr></tbody></table>


# REST Endpoints

Use the following URLs to connect to sFOX's REST API.

<table><thead><tr><th width="218">Endpoint</th><th>Description</th></tr></thead><tbody><tr><td><strong>Production</strong></td><td><strong><code>https://api.sfox.com</code></strong></td></tr><tr><td><a href="/pages/HoUS6l45i8X7tYKJBIbb"><strong>Candlestick / OHLCV</strong> </a><strong>Data</strong> (Production)</td><td><strong><code>https://chartdata.sfox.com</code></strong></td></tr><tr><td><strong>Sandbox</strong></td><td><p><strong><code>https://api.staging.sfox.com</code></strong><br></p><p> <a href="mailto:support@sfox.com"><em>Contact Support</em></a> <em>for access to the sandbox environment.</em></p></td></tr></tbody></table>


# Authentication

sFOX uses API keys to grant access. You can generate a new sFOX API key in the [developer portal](https://trade.sfox.com/account/api). &#x20;

{% hint style="info" %}
Please note the production and sandbox environments require separate API keys
{% endhint %}

The API key should be included in all API requests to the server in the `Authorization` header as a Bearer token:

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' 'https://api.sfox.com/v1/...'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/...',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/...",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}

## API Key Permissions

Your permissions as a user in your account define your API key permissions in your account.&#x20;

Any changes made to your permissions will change the permissions of both the API keys you previously created and new API keys you create.


# Rate Limits

The REST API rate limits requests by IP address **AND**, in some cases, by route.

* **IP Address:** 250 requests per 10 seconds.&#x20;
  * If you exceed this, a `429` error is thrown and you have to wait 60 seconds before resuming.
* **Route-specific limits:** Routes with unique rate limits are specified in the route details within this documentation. e.g. [Get All Done Orders](/rest-api/orders/get-all-done-orders).
  * If the route details do NOT specify a rate limit then the route does not have a specific rate limit.
  * If you exceed this, a `429` error is thrown and you have to wait 10 seconds before resuming **requests to this specific route.**

{% hint style="info" %}
sFOX recommends using the [**WebSocket API**](/websocket-api/introduction) for retrieving data as much as possible as this will not count towards the request limit.

**Note:** sFOX typically enforces route-specific rate limits on routes that return data that is available via the [**WebSocket API**](/websocket-api/introduction) e.g. account balances.
{% endhint %}


# Account Management

Account information including current balances, transactions, currencies, pairs, and fee rates.


# Get All Balances

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/user/balance`

Retrieve your account balances by currency. Results include an array of objects, each of which has details for a single currency.

{% hint style="info" %}
[**Rate Limit**](/rest-api/rate-limits)**: 5 requests per 10 seconds**

sFOX recommends using the [**Balances WebSocket feed**](/websocket-api/orders-and-account-data/balances) instead, which allows you to receive all balance changes in real-time, and does not count towards your request limit.
{% endhint %}

### Response Body

<table><thead><tr><th width="190.63141904239762">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong></td><td>The currency</td></tr><tr><td><strong><code>balance</code></strong></td><td>The total balance of this currency in your account across all wallets outlined below</td></tr><tr><td><strong><code>available</code></strong></td><td>The portion of the balance that is available for trading or withdrawals</td></tr><tr><td><strong><code>held</code></strong></td><td>Potion of the balance that is currently on hold and unavailable for trading or withdrawals (i.e. an ACH deposit that has yet to settle)</td></tr><tr><td><strong><code>borrow_wallet</code></strong></td><td>Amount of the currency , represented as the borrow wallet balance</td></tr><tr><td><strong><code>collateral_wallet</code></strong></td><td>Amount of the current being held as collateral in your collateral wallet</td></tr><tr><td><strong><code>lending_wallet</code></strong></td><td>Amount of the currency in your lending wallet</td></tr><tr><td><strong><code>trading_wallet</code></strong></td><td>Amount of the currency in your trading wallet</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
  {
    "currency":"btc",
    "balance": 1,
    "available": 1,
    "held": 0,
    "borrow_wallet": 0,
    "collateral_wallet": 0,
    "lending_wallet": 0,
    "trading_wallet": 1
  },
  {
    "currency":"usd",
    "balance": 100,
    "available": 90,
    "held": 10,
    "borrow_wallet": 0,
    "collateral_wallet": 0,
    "lending_wallet": 0,
    "trading_wallet": 100
  }
]
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' 
-H 'Content-Type: application/json' \
-X GET \
'https://api.sfox.com/v1/user/balance'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/user/balance',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/user/balance",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Currencies

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/currency`

Retrieve a list of currencies your account has access to. Currency settings are returned in the response.

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
    {
        "id": 1,
        "symbol": "usd",
        "name": "US Dollar",
        "is_fiat": 1,
        "is_lending_enabled": 0,
        "can_deposit": 1,
        "can_withdraw": 1,
        "min_withdrawal": 10,
        "confirmations_needed": null,
        "precision": 8,
        "ascii_sign": "$",
        "contract_address": null,
        "custody_enabled": 1,
        "trading_enabled": 1,
        "primary_network": null,
        "code": "usd",
        "currency": "usd"
    },
    {
        "id": 2,
        "symbol": "btc",
        "name": "Bitcoin",
        "is_fiat": 0,
        "is_lending_enabled": 0,
        "can_deposit": 1,
        "can_withdraw": 1,
        "min_withdrawal": 0.001,
        "confirmations_needed": 3,
        "precision": 8,
        "ascii_sign": "B",
        "contract_address": null,
        "custody_enabled": 1,
        "trading_enabled": 1,
        "primary_network": "Bitcoin",
        "code": "btc",
        "currency": "btc"
    }
]
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \ 
-H 'Content-Type: application/json' \
-X GET \
'https://api.sfox.com/v1/currency'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/currency',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/currency",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Currency Pairs

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/markets/currency-pairs`

Retrieve a list of currency pairs available to trade in your account.

### Response Body

Each trading pair is represented as a key-value object where the key is the lowercase concatenated symbol (e.g., "btcusd") and contains detailed information about the trading pair. Each trading pair object contains the following fields:

<table><thead><tr><th width="232.20396600566573">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>formatted_symbol</code></strong></td><td>A human-readable representation of the trading pair using standard notation (e.g., <code>"BTC/USD"</code>). <br>Format:  <code>"{BASE}/{QUOTE}"</code> with uppercase symbols.</td></tr><tr><td><strong><code>symbol</code></strong></td><td>The lowercase concatenated version of the trading pair used as an identifier (e.g., <code>"btcusd"</code>). <br>Format: lowercase <code>"{base}{quote}"</code>.</td></tr><tr><td><strong><code>base</code></strong></td><td>The base currency of the trading pair (e.g., <code>"btc"</code>).</td></tr><tr><td><strong><code>quote</code></strong></td><td>The quote currency of the trading pair (e.g., <code>"usd"</code>)</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "btcusd": {
        "formatted_symbol": "BTC/USD",
        "symbol": "btcusd",
        "base": "btc",
        "quote": "usd"
    },
    "ethbtc": {
        "formatted_symbol": "ETH/BTC",
        "symbol": "ethbtc",
        "base": "eth",
        "quote": "btc"
    },
    "ltcbtc": {
        "formatted_symbol": "LTC/BTC",
        "symbol": "ltcbtc",
        "base": "ltc",
        "quote": "btc"
    }
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \ 
-H 'Content-Type: application/json' \
-X GET \
'https://api.sfox.com/v1/markets/currency-pairs'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/markets/currency-pairs',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/markets/currency-pairs",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Transactions

Retrieve your transaction history

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/account/transactions`

Retrieve your transaction history, including trades and transfers. It returns an array of objects, each of which has details for each individual transaction.

{% hint style="info" %}
[**Rate Limit**](/rest-api/rate-limits)**: 1 request per 10 seconds**

Receive real-time [trade](/websocket-api/market-data/trades), [order](/websocket-api/orders-and-account-data/orders), and [balance](/websocket-api/orders-and-account-data/balances) updates using the sFOX WebSocket API. [Click here for details](/websocket-api/orders-and-account-data).
{% endhint %}

## Request

### Query Parameters

<table><thead><tr><th width="113.8203125">Name</th><th width="125">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>from</code></strong></td><td>timestamp</td><td>Start date for your query. Results will include transactions that occurred after this date. <strong>Unix timestamp in ms.</strong> Default: utcnow - 24hrs</td></tr><tr><td><strong><code>to</code></strong></td><td>timestamp</td><td>End date for your query. Results will include transactions that occurred before this date. <strong>Unix timestamp in ms.</strong> Default: utcnow</td></tr><tr><td><strong><code>limit</code></strong></td><td>int</td><td>Maximum number of results to be returned by the request. Default: 250. Maximum: 1000</td></tr><tr><td><strong><code>after</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred after (newer) than the specified ID (<code>id</code> from response body).<br><br>Use this parameter when you want to retrieve only new transactions from a previous request.</td></tr><tr><td><strong><code>offset</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred before (older) than the results from a previous request. <br><br>Specify the number of entries you've already had returned to you to get the next batch. e.g. If you retrieved <code>500</code> results in your previous request and you want the next <code>500</code>, set the offset to <code>501</code>.</td></tr><tr><td><strong><code>types</code></strong></td><td>string</td><td>Filter by transaction type. To filter by more than one type, separate each type with a comma. Possible values: <code>charge</code>, <code>deposit</code>, <code>withdraw</code>, <code>credit</code>, <code>buy</code>, <code>sell</code></td></tr><tr><td><strong><code>pending</code></strong></td><td>boolean</td><td>Specify whether the results should include transactions that are NOT completed (<code>Done</code>). e.g. pending deposits or withdrawals. <strong>Only applicable to</strong> <code>deposit</code> <strong>and</strong> <code>withdraw</code> <code>types</code>. Default: <code>false</code></td></tr></tbody></table>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \ 
https://api.sfox.com/v1/account/transactions?limit=50
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/account/transactions',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  params: {
   limit: 50
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});ja
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/account/transactions",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
  params={
   "limit": 50
  }
)
print(data)
```

{% endtab %}
{% endtabs %}

## Response

### Response Body

Response body is an array of objects. Each object represents a transaction and will include the following keys:

<table><thead><tr><th width="183.61764680221557">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong></td><td>sFOX-generated transaction ID. Use for <code>after</code> pagination.</td></tr><tr><td><strong><code>atxid</code></strong></td><td>Account transaction ID. An sFOX-generated ID specifically for deposit, withdrawal, credit, or charge transactions.</td></tr><tr><td><strong><code>order_id</code></strong></td><td>sFOX-generated ID of the order that this transaction is associated with, if applicable.</td></tr><tr><td><strong><code>client_order_id</code></strong></td><td>The optional ID that you specified when <a href="/pages/-Mkd5fv0VwgWbHGXHO7z"><mark style="color:blue;">placing an order</mark></a></td></tr><tr><td><strong><code>trade_id</code></strong></td><td>sFOX-generated ID of the trade, if applicable.</td></tr><tr><td><strong><code>day</code></strong></td><td>The timestamp of the transaction, in ISO8601 format</td></tr><tr><td><strong><code>action</code></strong></td><td>The action name of this transaction (“Deposit”, “Withdraw”, “Buy”, “Sell”, "Credit", "Charge")</td></tr><tr><td><strong><code>currency</code></strong></td><td>The base currency of the transaction </td></tr><tr><td><strong><code>memo</code></strong></td><td>The optional memo you specified for a withdrawal transaction</td></tr><tr><td><strong><code>amount</code></strong></td><td>The transacted amount of the <code>currency</code></td></tr><tr><td><strong><code>net_proceeds</code></strong></td><td>Net amount after fees</td></tr><tr><td><strong><code>price</code></strong></td><td>Price per unit of the <code>currency</code></td></tr><tr><td><strong><code>fees</code></strong></td><td>Fee paid in terms of the  <code>currency</code></td></tr><tr><td><strong><code>status</code></strong></td><td>The current transaction status</td></tr><tr><td><strong><code>hold_expires</code></strong></td><td>The expiration date of a hold on this transaction, if applicable</td></tr><tr><td><strong><code>tx_hash</code></strong></td><td>The transaction hash, if applicable (applicable to crypto deposits and withdrawals)</td></tr><tr><td><strong><code>algo_name</code></strong></td><td>The algorithm used to execute the transaction, if the transaction is an order</td></tr><tr><td><strong><code>algo_id</code></strong></td><td>The ID associated with the algorithm</td></tr><tr><td><strong><code>account_balance</code></strong></td><td>Your balance of the <code>currency</code> after the transaction</td></tr><tr><td><strong><code>AccountTransferFee</code></strong></td><td>Fee paid in terms of the  <code>currency</code> for deposit or withdrawal transactions</td></tr><tr><td><strong><code>description</code></strong></td><td>A description of the transaction. For crypto deposits, this is the sender address. For crypto withdrawals this is the destination address</td></tr><tr><td><strong><code>added_by_user_email</code></strong></td><td>The username/email address of the user who initiated this transaction</td></tr><tr><td><strong><code>symbol</code></strong></td><td>The currency pair of the transaction for trades (<code>action</code> = <code>Buy</code> or <code>Sell</code>)</td></tr><tr><td><strong><code>timestamp</code></strong></td><td>The UNIX timestamp of the transaction in milliseconds</td></tr></tbody></table>

### Transaction Statuses

The following table describes the possible Status Codes returned from this request.

{% hint style="info" %}
**These Status Codes are only applicable to deposit and withdrawal transactions.** Other transaction types will always be returned with status = Done
{% endhint %}

<table data-full-width="false"><thead><tr><th width="210.03515625">Status Code</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>Initiated</code></strong></td><td>Transaction initiated</td></tr><tr><td><strong><code>In Progress</code></strong></td><td>Transaction is in progress</td></tr><tr><td><strong><code>Approval Required</code></strong></td><td><ul><li><strong>Deposits:</strong> N/A</li><li><strong>Withdrawals:</strong> Approval is required before the transaction will be initiated</li></ul></td></tr><tr><td><strong><code>Processing Automatic withdrawal</code></strong></td><td><ul><li><strong>Deposits:</strong> N/A</li><li><strong>Withdrawals:</strong> Transaction is being broadcast</li></ul></td></tr><tr><td><strong><code>Confirmed</code></strong></td><td><ul><li><strong>Deposits:</strong> Transaction has been received. It is not available yet but will be shortly</li><li><strong>Withdrawals:</strong> Transaction has been approved. It has not been sent yet but will be shortly</li></ul></td></tr><tr><td><strong><code>Done</code></strong></td><td><ul><li><strong>Deposits:</strong> Transaction is complete and available to you</li><li><strong>Withdrawals:</strong> Transaction is complete</li></ul></td></tr><tr><td><strong><code>Canceled</code></strong></td><td>Transaction has been canceled</td></tr><tr><td><strong><code>Admin Hold, Pending Further Review</code></strong></td><td>Transaction was flagged for review. Contact support@sfox.com for more information</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
    {
        "id": 68029980111539,
        "AtxId": null,
        "order_id": "80000120662565",
        "client_order_id": "2013acd0-ea78-46c3-b2ac-ed4546f13182",
        "trade_id": "8848300113216138",
        "day": "2024-03-28T15:47:41.000Z",
        "action": "Sell",
        "currency": "usd",
        "memo": "",
        "amount": 71.26350189,
        "net_proceeds": 71.26350189,
        "price": 71299.1514729,
        "fees": 0.03564958,
        "status": "done",
        "hold_expires": "",
        "tx_hash": "",
        "algo_name": "Limit",
        "algo_id": "201",
        "account_balance": 3702.72950349,
        "AccountTransferFee": 0,
        "Description": "",
        "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000",
        "added_by_user_email": "example@sfox.com",
        "symbol": "btc/usd",
        "IdempotencyId": null,
        "timestamp": 1711640861000
    },
    {
        "id": 68029980111538,
        "AtxId": null,
        "order_id": "80000120662565",
        "client_order_id": "2013acd0-ea78-46c3-b2ac-ed4546f13182",
        "trade_id": "8848300113216138",
        "day": "2024-03-28T15:47:41.000Z",
        "action": "Sell",
        "currency": "btc",
        "memo": "",
        "amount": -0.001,
        "net_proceeds": -0.001,
        "price": 71299.1514729,
        "fees": 0.03564958,
        "status": "done",
        "hold_expires": "",
        "tx_hash": "",
        "algo_name": "Limit",
        "algo_id": "201",
        "account_balance": 10.00216189,
        "AccountTransferFee": 0,
        "Description": "",
        "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000",
        "added_by_user_email": "example@sfox.com",
        "symbol": "btc/usd",
        "IdempotencyId": null,
        "timestamp": 1711640861000
    },
    {
        "id": 68029980111501,
        "AtxId": 1670509823872833,
        "order_id": "",
        "client_order_id": "",
        "trade_id": "",
        "day": "2024-03-28T16:03:54.000Z",
        "action": "Credit",
        "currency": "dot",
        "memo": "",
        "amount": 0.0564958,
        "net_proceeds": 0.0564958,
        "price": 9.60559235,
        "fees": 0,
        "status": "done",
        "hold_expires": "",
        "tx_hash": "",
        "algo_name": "",
        "algo_id": "",
        "account_balance": 120.70980446,
        "AccountTransferFee": 0,
        "Description": "Staking Reward",
        "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000",
        "added_by_user_email": "example@sfox.com",
        "symbol": null,
        "IdempotencyId": null,
        "timestamp": 1711641834000
    }
]
```

</details>


# Get Fees

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/account/fee-rates`

Retrieve your account's current trading fee rates and trailing 14-day notional volume.&#x20;

Response your account's current taker fee rates, maker fee rate for trades in the sFOX Ox and Dark Pool order books, and your trailing 14-day notional trading volume used to determine your rates.

### Response Body

<table><thead><tr><th width="218.33333333333331">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>volume</code></strong></td><td>Your 14-day trailing volume in USD</td></tr><tr><td><strong><code>makerRate</code></strong></td><td>Your maker fee rate for trades executed as a maker in the Ox and Dark Pool order books</td></tr><tr><td><strong><code>nprRate</code></strong></td><td>Your taker fee rate when trading with routing type = <code>NetPrice</code> (NPR)</td></tr><tr><td><strong><code>nprOffRate</code></strong></td><td>Your taker fee rate when trading with routing type = <code>Smart</code> (NPR-Off)</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "volume": 2302868.809741,
    "makerRate": 0.00021,
    "nprRate": 0.00035,
    "nprOffRate": 0.00105
}
```

</details>

<details>

<summary><mark style="color:red;">401</mark>: Unauthorized</summary>

```json
{ 
    "error": "invalid token. check authorization header."
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \ 
-H 'Content-Type: application/json' \
-X GET \
'https://api.sfox.com/v1/account/fee-rates'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/account/fee-rates',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/account/fee-rates",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Orders

Create, cancel, amend, and manage orders

{% hint style="info" %}
sFOX recommends using our [WebSocket API](/websocket-api/orders-and-account-data) to receive order and/or trade updates where you can stream real-time order and/or trade updates and will avoid rate limits.
{% endhint %}

### Order Types & Algorithms

sFOX offers a wide range of order types and execution algorithms to optimize your order execution. Short descriptions are available in the page linked below. Further details can be found in the [sFOX Support Center](https://support.sfox.com/product-guides/trading/order-types). Or contact support to speak with an expert.&#x20;

{% content-ref url="/pages/-MksB3OWKUp0-RnwDoxN" %}
[Order Types](/rest-api/orders/algorithms-and-routing-types)
{% endcontent-ref %}

### Order Statuses

Orders may have any of the following statuses.

<table><thead><tr><th width="154">Status</th><th width="127" align="center">Status Code</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>Started</code></strong></td><td align="center"><strong><code>100</code></strong></td><td><ul><li>The order is open and active</li><li>Filled quantity may be >= 0</li><li>Filled quantity is &#x3C; the order quantity</li></ul></td></tr><tr><td><code>Filled</code></td><td align="center"><code>210</code></td><td><p></p><ul><li>The order has filled the entire order amount and is in the process of settling to final Done status</li><li>Filled quantity = order quantity</li><li>The order will not receive new fills</li></ul></td></tr><tr><td><strong><code>Done</code></strong></td><td align="center"><strong><code>300</code></strong></td><td><ul><li>The order was completed and is no longer active</li><li>Filled quantity = order quantity</li><li>The order will not receive new fills</li></ul></td></tr><tr><td><strong><code>Cancel Pending</code></strong></td><td align="center"><strong><code>90</code></strong></td><td><ul><li>The order is in the process of being canceled but cancelation has not been confirmed</li><li>The order may still receive fills</li></ul></td></tr><tr><td><strong><code>Canceled</code></strong></td><td align="center"><strong><code>10</code></strong></td><td><ul><li>The order was successfully canceled</li><li><strong>Order may have been partially filled prior to cancelation</strong></li></ul></td></tr></tbody></table>

### Order Object

Order updates received or retrieved via the sFOX APIs will include the following object per order:

<table data-full-width="false"><thead><tr><th width="224">Field</th><th width="120">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong></td><td>int</td><td>sFOX-generated order ID, assigned on order creation.</td></tr><tr><td><strong><code>side_id</code></strong></td><td>int</td><td>ID for the order side/action. Possible values: <code>500</code> (buy order), <code>600</code> (sell order).</td></tr><tr><td><strong><code>action</code></strong></td><td>string</td><td>Order side. Possible values: <code>buy</code> (buy order), <code>sell</code> (sell order)</td></tr><tr><td><strong><code>algorithm_id</code></strong></td><td>int</td><td>Order type / algorithm ID. Possible values: <a href="/pages/-MksB3OWKUp0-RnwDoxN">Order Types &#x26; Algorithms</a>.</td></tr><tr><td><strong><code>algorithm</code></strong></td><td>string</td><td>Order type / algorithm name. Possible values: <a href="/pages/-MksB3OWKUp0-RnwDoxN">Order Types &#x26; Algorithms</a>.</td></tr><tr><td><strong><code>type</code></strong></td><td>string</td><td>Order type / algorithm name. Possible values: <a href="/pages/-MksB3OWKUp0-RnwDoxN">Order Types &#x26; Algorithms</a>.</td></tr><tr><td><strong><code>pair</code></strong></td><td>string</td><td>Pair or product in the format <code>basequote</code> . e.g. <code>btcusd</code>, <code>ethbtc</code>, <code>ethusdc</code></td></tr><tr><td><strong><code>quantity</code></strong></td><td>number</td><td>Order size in base currency quantity.</td></tr><tr><td><strong><code>price</code></strong></td><td>number</td><td>Order limit price.</td></tr><tr><td><strong><code>amount</code></strong></td><td>number</td><td>Amount (quote currency) to spend when buying.</td></tr><tr><td><strong><code>net_market_amount</code></strong></td><td>number</td><td><code>amount</code> net fees for Market (<code>100</code>) orders.</td></tr><tr><td><strong><code>filled</code></strong></td><td>number</td><td>Unsigned, cumulative base currency quantity filled.</td></tr><tr><td><strong><code>vwap</code></strong></td><td>number</td><td>Cumulative volume-weighted average fill price of the order.</td></tr><tr><td><strong><code>filled_amount</code></strong></td><td>number</td><td>Unsigned, cumulative quote currency amount filled.</td></tr><tr><td><strong><code>fees</code></strong></td><td>number</td><td>Unsigned, cumulative quote currency fee amount accrued to this order.</td></tr><tr><td><strong><code>net_proceeds</code></strong></td><td>number</td><td>Signed, cumulative quote currency proceeds amount net fees.</td></tr><tr><td><strong><code>status</code></strong></td><td>string</td><td>Status name. Possible values: <a href="#order-statuses">Order Statuses</a>.</td></tr><tr><td><strong><code>status_code</code></strong></td><td>int</td><td>Status ID. Possible values: <a href="#order-statuses">Order Statuses</a>.</td></tr><tr><td><strong><code>routing_option</code></strong></td><td>string</td><td>Special order routing instructions. </td></tr><tr><td><strong><code>routing_type</code></strong></td><td>string</td><td>Order routing type.</td></tr><tr><td><strong><code>time_in_force</code></strong></td><td>string</td><td>Order time in force specified at order creation.</td></tr><tr><td><strong><code>expires</code></strong></td><td>datetime</td><td>Expiration date of the order (for <code>time_in_force</code> = <code>GTD</code> orders)</td></tr><tr><td><strong><code>dateupdated</code></strong></td><td>datetime</td><td>Date of the most recent update to this order.</td></tr><tr><td><strong><code>date_added</code></strong></td><td>datetime</td><td>Date the order was created.</td></tr><tr><td><strong><code>client_order_id</code></strong></td><td>string</td><td>User-specified ID for this order.</td></tr><tr><td><strong><code>user_tx_id</code></strong></td><td>string</td><td>Same as above.</td></tr><tr><td><strong><code>o_action</code></strong></td><td>string</td><td>Order side. Possible values: <code>Buy</code> (buy order), <code>Sell</code> (sell order)</td></tr><tr><td><strong><code>algo_id</code></strong></td><td>int</td><td>Order type / algorithm ID. Possible values: <a href="/pages/-MksB3OWKUp0-RnwDoxN">Order Types &#x26; Algorithms</a>.</td></tr><tr><td><strong><code>algorithm_options</code></strong></td><td>string[]</td><td>Additional object specifying special order parameters.</td></tr><tr><td><strong><code>destination</code></strong></td><td>string</td><td>Order destination.</td></tr></tbody></table>


# Order Types

## Order Types & Algorithms

sFOX offers a wide range of order types and execution algorithms to optimize your order execution. Further details can be found in the [sFOX Support Center](https://support.sfox.com/product-guides/trading/order-types). Or contact support to speak with an expert.&#x20;

<table data-full-width="false"><thead><tr><th width="124.53864668072796">ID</th><th width="158.90285789648493">Name</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>100</code></strong></td><td>Market</td><td>An order to buy or sell as quickly as possible, regardless of price</td></tr><tr><td><strong><code>200</code></strong></td><td>Smart Routing</td><td>An order to buy or sell at a specific price or better</td></tr><tr><td><strong><code>201</code></strong></td><td>Limit</td><td>An order to buy or sell at a specific price or better</td></tr><tr><td><strong><code>301</code></strong></td><td>Gorilla</td><td>Post-only maker order that places portions of your order on exchanges at a time to hide your order size from the market</td></tr><tr><td><strong><code>302</code></strong></td><td>Tortoise</td><td>Post-only maker order that places your order on the exchange with the best price</td></tr><tr><td><strong><code>303</code></strong></td><td>Hare</td><td>Post-only maker order that keeps you in the most competitive position in the order book at the price you want or better</td></tr><tr><td><strong><code>304</code></strong></td><td>Stop</td><td>An order to buy or sell an asset once the price of the asset reaches a specified price. When the trigger price is reached, a stop order becomes a market order (taker-only)</td></tr><tr><td><strong><code>305</code></strong></td><td>Polar Bear</td><td>An order that only takes from the best bid or ask until the order is completely filled (taker-only)</td></tr><tr><td><strong><code>306</code></strong></td><td>Sniper</td><td>Hides your order size in the SFOX Dark Pool but aggressively takes when bids or offers are available better than or equal to your limit price</td></tr><tr><td><strong><code>307</code></strong></td><td>TWAP</td><td>Execute evenly over a set amount of time at a price equal to or better than the order price, to achieve a time-weighted average price</td></tr><tr><td><strong><code>308</code></strong></td><td>Trailing Stop</td><td>An order where the stop price, set at a specific dollar or percentage interval above or below the current price, can adjust as the market does (sell order triggers follow the price up, but then stay the same as the price moves down and vice versa).</td></tr><tr><td><strong><code>309</code></strong></td><td>Immediate-or-Cancel (IOC)</td><td>An order to immediately buy or sell at the specified price or better and cancel any unfilled amount</td></tr></tbody></table>

### Routing Types <a href="#routing-types" id="routing-types"></a>

The routing type defines how sFOX prioritizes different sources of liquidity when executing your order. sFOX always attempts to execute your order at the best available price.

<table data-header-hidden><thead><tr><th width="218.51807228915658">Routing Type</th><th>Description</th></tr></thead><tbody><tr><td>Routing Type</td><td>Description</td></tr><tr><td><code>NetPrice</code></td><td>Routes orders to the best venues for execution by considering both the quoted prices and the fees charged by the trading venues. Additional details <a href="https://blog.sfox.com/sfox-pricing-crypto-trading-net-price-routing-8997fbc0520">here</a>.</td></tr></tbody></table>

{% hint style="info" %}
Contact <support@sfox.com> to learn more about additional routing options.
{% endhint %}


# Create Order

Create an order

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1/orders/:side`

Create an order.

{% hint style="info" %}
Create order requests are rate limited to **60 requests per second** per account.
{% endhint %}

### **Path Parameters**

<table><thead><tr><th width="240">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>side</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Possible values: <code>buy</code> (buy order), <code>sell</code> (sell order)</td></tr></tbody></table>

### Body Parameters

<table data-full-width="false"><thead><tr><th width="274">Parameter</th><th width="100">Type</th><th width="665">Description</th></tr></thead><tbody><tr><td><strong><code>currency_pair</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Pair or product to trade in the format <code>basequote</code> . e.g. <code>btcusd</code>, <code>ethbtc</code>, <code>ethusdc</code></td></tr><tr><td><strong><code>algorithm_id</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td><p>Order type / algorithm.</p><ul><li>For more info, see <a href="/pages/-MksB3OWKUp0-RnwDoxN"><strong>Order Types &#x26; Algorithms</strong></a></li><li>Default: Limit (<code>200</code>)</li></ul></td></tr><tr><td><strong><code>price</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td><p>Order limit price.</p><ul><li>NOT required for Market (<code>100</code>) orders</li><li><strong>Order fill price will always be better than or equal to this price.</strong> If market conditions do not allow it, the order will not execute.</li></ul></td></tr><tr><td><strong><code>quantity</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td><p>Order size in base currency quantity.</p><ul><li><strong>Required when placing SELL orders using</strong>: Market (<code>100</code>), Stop (<code>304</code>) or Trailing Stop (<code>308</code>).</li><li>Required for Smart (<code>200</code>), Limit (<code>201</code>), Gorilla (<code>301</code>), Tortoise (<code>302</code>), Hare (<code>303</code>), Polar Bear (<code>305</code>), Sniper (<code>306</code>), TWAP (<code>307</code>), and IOC (<code>309</code>).</li><li>For Market-type BUY orders, use amount.</li><li>NOT required for Market BUY (<code>100</code>) orders</li><li>Minimum order value: USD value must be >= $5 for supported spot pairs</li></ul></td></tr><tr><td><strong><code>amount</code></strong></td><td>string</td><td><p>The amount (quote currency) to spend when buying.</p><ul><li><strong>Required when placing BUY orders using:</strong> Market (<code>100</code>), Stop (<code>304</code>) or Trailing Stop (<code>308</code>) order types.</li><li>For standard non-Market spot orders, use quantity.</li><li>Minimum order value: USD value must be >= $5 for supported pairs</li><li>Exception: FOK and RFQ flows accept exactly one of quantity or amount.</li></ul></td></tr><tr><td><strong><code>client_order_id</code></strong></td><td>string</td><td><p>Optional field for a user-specified ID.</p><p><code>client_order_id</code> serves as an idempotency key. <strong>Orders will be rejected if the</strong> <code>client_order_id</code> <strong>has been specified in a previous order placed in the last 24 hours.</strong></p></td></tr><tr><td><strong><code>quote_id</code></strong></td><td>string</td><td>For executing on an <a href="/pages/nEOyHVWWrh7jJmuSU6Sx"><strong>RFQ</strong></a>, the <code>quote_id</code> received in the RFQ request.</td></tr><tr><td><strong><code>time_in_force</code></strong></td><td>string</td><td><p>Time in force (TIF) specifies how the lifetime of your order will be handled. Possible values:</p><ul><li><code>GTC</code>: Good 'til canceled orders remain open until canceled. This is the default TIF option. (Default)</li><li><code>IOC</code>: Immediate or cancel orders instantly cancel the remaining unfilled size of an order leaving it open. Smart (<code>200</code>) and Limit (<code>201</code>) orders only.</li><li><code>FOK</code>: Fill or kill orders are either instantly filled for the full order size or instantly rejected if the entire size cannot be matched. Market (<code>100</code>) and Limit (<code>201</code>) orders only.</li><li><code>GTD</code>: Good 'til date orders are automatically canceled at your specified <code>expires</code> date time.</li></ul></td></tr><tr><td><strong><code>max_slippage</code></strong></td><td>number</td><td>A risk management parameter that will limit the slippage of an order in basis points (e.g. setting <code>max_slippage</code> to <code>5</code> = 0.05%). Market (<code>100</code>), Stop (<code>304</code>), Trailing Stop (<code>308</code>) only.</td></tr><tr><td><strong><code>expires</code></strong></td><td>date-time</td><td><p>Specify the expiration date time of your order (UNIX timestamp in ms). </p><p><strong>Required for orders with</strong> <code>time_in_force</code> <strong>=</strong> <code>GTD</code></p></td></tr><tr><td><strong><code>destination</code></strong></td><td>string</td><td><p>Route the order to a specific destination.</p><p></p><p>Possible values:</p><ul><li><code>ox</code> for the sFOX Ox order book</li><li><code>darkpool</code> for the sFOX Dark Pool</li></ul></td></tr><tr><td><strong><code>total_time</code></strong></td><td>int</td><td>The time, in seconds, that a TWAP (<code>307</code>) order will stay active from the time the TWAP order is placed.</td></tr><tr><td><strong><code>interval</code></strong></td><td>int</td><td>The frequency, in seconds, that slices of a TWAP (<code>307</code>) order will be executed. Default: <code>900</code></td></tr><tr><td><strong><code>continuous</code></strong></td><td>boolean</td><td>TWAP (<code>307</code>) orders will execute slices as small as possible and frequently as possible over the <code>total_time</code>. <code>interval</code> will be ignored If <code>continuous</code> = <code>true.</code></td></tr><tr><td><strong><code>post_only</code></strong></td><td>boolean</td><td>TWAP (<code>307</code>) orders will execute in "post-only" mode. The order will not take and will only execute slices as make orders.<code>post_only</code> means <strong>it is possible the TWAP order will not fill completely</strong> by the end of the <code>total_time</code></td></tr><tr><td><strong><code>stop_amount</code></strong></td><td>number</td><td>Set the amount (quote currency) that the trigger price of a trailing stop order will trail the price of an asset. Trailing Stop (<code>308</code>) only.</td></tr><tr><td><strong><code>stop_percent</code></strong></td><td>number</td><td>Percentage that the trigger price of a trailing stop order will trail the price of an asset (e.g. <code>0.1</code> = 10%). Trailing Stop (<code>308</code>) only.</td></tr><tr><td><strong><code>stop_any_id</code></strong></td><td>int</td><td><p>Turn your order into an STO (Stop-Triggers-Other) or TSTO (Trailing-Stop-Triggers-Other) order: Trigger placement of an order type of your choosing at a certain price or based on a trailing amount/percent. e.g. when price reaches $100 trigger a 1-hour TWAP. Possible values:</p><ul><li><code>310</code> : STO (Stop-Triggers-Other)</li><li><code>311</code> : TSTO (Trailing-Stop-Triggers-Other)</li></ul></td></tr><tr><td><strong><code>stop_any_price</code></strong></td><td>number</td><td>Trigger price of an STO (Stop-Triggers-Other) order. <strong>Required if</strong> <code>stop_any_id</code> <strong>=</strong> <code>310</code>.</td></tr><tr><td><strong><code>stop_any_trail_amount</code></strong></td><td>number</td><td>Trailing amount (quote currency) of a TSTO (Trailing-Stop-Triggers-Other) order. <strong>Required if</strong> <code>stop_any_id</code> <strong>=</strong> <code>311</code> and <code>stop_any_trail_percent</code> <strong>is not used.</strong></td></tr><tr><td><strong><code>stop_any_trail_percent</code></strong></td><td>number</td><td>Specify the trailing percent of a TSTO (Trailing-Stop-Triggers-Other) order (e.g. <code>0.1</code> = 10%). <strong>Required if</strong> <code>stop_any_id</code> <strong>=</strong> <code>311</code> and <code>stop_any_trail_amount</code> <strong>is not used.</strong></td></tr><tr><td><strong><code>routing_option</code></strong></td><td>string</td><td><p>Specify how sFOX will trade your order. Routing Options: </p><ul><li><code>BestPrice</code>: Prioritize price improvement. Hare (<code>303</code>) and Gorilla (<code>301</code>) only.</li><li><code>Fast</code>: Prioritize speed of execution. Hare (<code>303</code>) and Gorilla (<code>301</code>) only.</li><li><code>WeightedExchange</code>: Prioritize routing based on the best combination of price and speed of execution. Smart (<code>200</code>), Limit (<code>201</code>) and Hare (<code>303</code>) only.</li></ul></td></tr><tr><td><strong><code>last_published</code></strong></td><td>date-time</td><td>Specify the last/latest order book update you are attempting to execute on for analysis purposes. Use the <a href="/pages/4CQgv3BxIh9W9BbKsZnF#order-book-message"><code>lastpublished</code> key from the order book message.</a> (UNIX timestamp in ms)</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">201</mark> Accepted &#x26; Created</summary>

```json
{
    "id": 2010135,
    "side_id": 500,
    "action": "Buy",
    "algorithm_id": 201,
    "algorithm": "Limit",
    "type": "Limit",
    "pair": "btcusd",
    "quantity": 0.1,
    "price": 36431,
    "amount": 0,
    "net_market_amount": 0,
    "filled": 0,
    "vwap": 0,
    "filled_amount": 0,
    "fees": 0,
    "net_proceeds": 0,
    "status": "Started",
    "status_code": 100,
    "routing_option": "WeightedExchange",
    "routing_type": "NetPrice",
    "time_in_force": "GTC",
    "expires": null,
    "dateupdated": "2023-11-17T20:52:40.000Z",
    "date_added": "2023-11-17T20:52:40.000Z",
    "client_order_id": "ea5c8afc-419a-447d-8188-659dce1a782a",
    "user_tx_id": "ea5c8afc-419a-447d-8188-659dce1a782a",
    "o_action": "Buy",
    "algo_id": 201,
    "algorithm_options": null,
    "destination": ""
}
```

</details>

<details>

<summary><mark style="color:red;">422</mark> Rejected</summary>

```json
// currency_pair not specified
{
    "error": "invalid currency_pair: undefined"
}

// currency_pair speficied but not supported or does not exist
{
    "error": "invalid currency_pair: btcusda"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

<pre class="language-bash"><code class="lang-bash"><strong>curl -X POST \
</strong>  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer &#x3C;API_TOKEN>' \
  --data '{ "quantity": 1,
            "currency_pair": "btcusd",
            "algorithm_id": 200,
            "price": 20000 }'  \
  'https://api.sfox.com/v1/orders/buy'
</code></pre>

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/orders/buy',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: {
   quantity: 1,
   currency_pair: 'btcusd',
   algorithm_id: 200,
   price: 20000
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/orders/buy",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "quantity": 1,
    "currency_pair":"btcusd",
    "algorithm_id": 200,
    "price": 20000
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Cancel Order

<mark style="color:red;">**`DELETE`**</mark> `https://api.sfox.com/v1/orders/:order_id`

Cancels a specified order. If the order has already been canceled or completed, the API will return an error.

### **Path Parameters**

<table><thead><tr><th width="240">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>order_id</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>The order ID generated by sFOX upon order creation.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark>: Cancelation Confirmed</summary>

```json
{ 
    "status": "canceled" 
}
```

</details>

<details>

<summary><mark style="color:green;">200</mark>: Cancelation In-Progress</summary>

<pre class="language-json"><code class="lang-json"><strong>{ 
</strong>    "status": "cancel pending" 
}
</code></pre>

</details>

<details>

<summary><mark style="color:green;">200</mark>: Order Completed – Could Not Be Canceled</summary>

```json
{
    "status": "order already finished"
}
```

</details>

<details>

<summary><mark style="color:red;">400</mark>: Bad Request</summary>

```json
//order_id does not exist in your account
{
    "error": "internal error"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X DELETE
  -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/orders/123'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'delete',
  url: 'https://api.sfox.com/v1/orders/123',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.delete(
  "https://api.sfox.com/v1/orders/123",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Cancel Multiple Orders

<mark style="color:red;">**`DELETE`**</mark> `https://api.sfox.com/v1/orders?ids=<order_id1>,<order_id2>,<...>`

Cancel a list of order IDs. sFOX will attempt to cancel each order included in the list and respond with the orders that were able to be canceled.

### **Query Parameters**

<table><thead><tr><th width="240">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>ids</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td><p>List of order IDs separated by a comma (,) </p><p>e.g. /orders?ids=123,456,789</p></td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

Responds with an array of all of the orders listed in the request that were able to begin cancelation (`Cancel Pending`) or were successfully canceled (`Canceled`)

```json
{ 
  "orders": [
    {"id": 2, "status": "Cancel pending"},
    {"id": 3, "status": "Canceled"}
  ]
}
```

</details>

<details>

<summary><mark style="color:red;">400</mark></summary>

If all of the provided order IDs were invalid, or were already in a `Done` or `Canceled` state, the response will contain an error.

{% code overflow="wrap" %}

```json
{ 
  "error": "the order ids provided were invalid or the orders were already done/canceled"
}
```

{% endcode %}

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X DELETE \
  -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/orders?ids=123,456'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'delete',
  url: 'https://api.sfox.com/v1/orders',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  params: {
    ids: '123,456'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.delete(
  "https://api.sfox.com/v1/orders",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  params={
   "ids": "123,456"
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Cancel All Orders

<mark style="color:red;">**`DELETE`**</mark> `https://api.sfox.com/v1/orders/open`

Cancel all open orders.

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

Responds with an array of all of the orders listed in the request that were able to begin cancelation (`Cancel Pending`) or were successfully canceled (`Canceled`)

```json
{ 
  "orders": [
    {"id": 2, "status": "Cancel pending"},
    {"id": 3, "status": "Canceled"}
  ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X DELETE \
  -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/orders/open'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'delete',
  url: 'https://api.sfox.com/v1/orders/open',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.delete(
  "https://api.sfox.com/v1/orders/open",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Amend Order

<mark style="color:orange;">**`PATCH`**</mark> `https://api.sfox.com/v1/orders/:order_id`

Make the following adjustments to the quantity or amount, price, and stop amount or stop percent parameters of an order without canceling the order.

### **Path Parameters**

<table><thead><tr><th width="240">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>order_id</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>The order ID generated by sFOX upon order creation.</td></tr></tbody></table>

### Body Parameters

<table><thead><tr><th width="183">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>quantity</code></strong></td><td>number</td><td><strong>Increase</strong> the quantity of an order.</td></tr><tr><td><strong><code>amount</code></strong></td><td>number</td><td><strong>Increase</strong> the quantity of an order. <code>amount</code> <strong>may only be increased for Stop</strong> (<code>304</code>) <strong>and Trailing Stop</strong> (<code>308</code>) <strong>orders</strong></td></tr><tr><td><strong><code>price</code></strong></td><td>number</td><td><ul><li>BUY Orders: <strong>Increase</strong> limit price</li><li>SELL Orders: <strong>Decrease</strong> limit price</li><li><strong>Price cannot be modified for Trailing Stop</strong> (<code>308</code>) <strong>order</strong></li></ul></td></tr><tr><td><strong><code>stop_amount</code></strong></td><td>number</td><td>Any modification is allowed</td></tr><tr><td><strong><code>stop_percent</code></strong></td><td>number</td><td>Any modification is allowed</td></tr></tbody></table>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X PATCH \
  -H 'Authorization: Bearer <API_TOKEN>' \
  --data '{ "quantity": 2 }'  \
  'https://api.sfox.com/v1/orders/123'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'patch',
  url: 'https://api.sfox.com/v1/orders/123',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: { quantity: 1 }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.patch(
  "https://api.sfox.com/v1/orders/123",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
   "quantity": 1
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get Single Order

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/orders/:order_id`

Retrieve the details of a single order.

{% hint style="info" %}
sFOX recommends using the [**Orders WebSocket feed**](/websocket-api/orders-and-account-data/orders) instead, which streams order updates in real-time and does not count towards your request limit.
{% endhint %}

### **Path Parameters**

<table><thead><tr><th width="240">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>order_id</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td><code>order_id</code> is either the order ID generated by sFOX upon order creation (<code>id</code>) or the client-assigned <code>client_order_id</code>.</td></tr></tbody></table>

### Order Statuses

<table><thead><tr><th width="151">Status</th><th width="128">Status Code</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>Started</code></strong></td><td><code>100</code></td><td><ul><li>The order is open and active</li><li>Filled quantity may be >= 0</li><li>Filled quantity is &#x3C; the order quantity</li></ul></td></tr><tr><td><code>Filled</code></td><td><code>210</code></td><td><p></p><ul><li>The order has filled the entire order amount and is in the process of settling to final Done status</li><li>Filled quantity = order quantity</li><li>The order will not receive new fills</li></ul></td></tr><tr><td><strong><code>Done</code></strong></td><td><code>300</code></td><td><ul><li>The order was completed and is no longer active</li><li>Filled quantity = order quantity</li><li>The order will not receive new fills</li></ul></td></tr><tr><td><strong><code>Cancel Pending</code></strong></td><td><code>90</code></td><td><ul><li>The order is in the process of being canceled but cancelation has not been completed</li><li>The order may still receive fills</li></ul></td></tr><tr><td><strong><code>Canceled</code></strong></td><td><code>10</code></td><td><ul><li>The order was successfully canceled</li><li><strong>Order may have been partially filled prior to cancelation</strong></li></ul></td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "id": 2010135,
    "side_id": 500,
    "action": "Buy",
    "algorithm_id": 201,
    "algorithm": "Limit",
    "type": "Limit",
    "pair": "btcusd",
    "quantity": 0.1,
    "price": 36431,
    "amount": 0,
    "net_market_amount": 0,
    "filled": 0,
    "vwap": 0,
    "filled_amount": 0,
    "fees": 0,
    "net_proceeds": 0,
    "status": "Started",
    "status_code": 100,
    "routing_option": "WeightedExchange",
    "routing_type": "NetPrice",
    "time_in_force": "GTC",
    "expires": null,
    "dateupdated": "2023-11-17T20:52:40.000Z",
    "date_added": "2023-11-17T20:52:40.000Z",
    "client_order_id": "ea5c8afc-419a-447d-8188-659dce1a782a",
    "user_tx_id": "ea5c8afc-419a-447d-8188-659dce1a782a",
    "o_action": "Buy",
    "algo_id": 201,
    "algorithm_options": null,
    "destination": ""
}
```

</details>

<details>

<summary><mark style="color:red;">401</mark>: Unauthorized</summary>

```json
//Invalid API key or insufficient user permissions
{
    "error": "user lookup failed"
}
```

</details>

<details>

<summary><mark style="color:red;">404</mark>: Not Found</summary>

```json
//The order_id specified in the request is invalid or does not exist
{
    "error": "the requested order was not found",
    "error_code": "ORDER_NOT_FOUND"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/orders/<ORDER_ID>'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/orders/<ORDER_ID>',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/orders/<ORDER_ID>",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Open Orders

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/orders`

Retrieve a list of all orders currently open in your account.

{% hint style="info" %}
[**Rate Limit**](/rest-api/rate-limits)**: 10 requests per 10 seconds**

sFOX recommends using the [**Orders WebSocket feed**](/websocket-api/orders-and-account-data/orders) instead, which streams order updates in real-time and does not count towards your request limit.
{% endhint %}

### Query Paramaters

<table><thead><tr><th width="211">Parameter</th><th width="133">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>limit</code></strong></td><td>int</td><td>Limit on the number of results to return. Default and maximum = <code>50</code>. Each response will include no more than 50 results.</td></tr><tr><td><strong><code>before</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred before (older) than the specified ID (<code>id</code> from response body).</td></tr><tr><td><strong><code>after</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred after (newer) than the specified ID (<code>id</code> from response body).</td></tr><tr><td><strong><code>action</code></strong></td><td>string</td><td>Filter response to only include orders with the specified action/side. Possible values: <code>buy</code> or <code>sell</code> (case sensitive).</td></tr><tr><td><strong><code>currency_pair</code></strong></td><td>string</td><td>Filter response to only include orders on the specified currency pair (<code>pair</code> from response body). Format: <code>&#x3C;basequote></code> e.g. <code>btcusd</code>.</td></tr><tr><td><strong><code>algorithm_id</code></strong></td><td>int</td><td>Filter response to only include orders with the specified <code>algorithm_id</code>/order type. Possible values: <a href="/pages/-MksB3OWKUp0-RnwDoxN">Order Types</a>.</td></tr><tr><td><strong><code>status</code></strong></td><td>string</td><td>Filter response to only include orders with the specified order status (<code>status</code> from response body). Possible values: <a href="/pages/-Mkd5fv0VwgWbHGXHO7z">Order Statuses</a> (case sensitive).</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
    {
        "id": 2008562,
        "side_id": 500,
        "action": "Buy",
        "algorithm_id": 201,
        "algorithm": "Limit",
        "type": "Limit",
        "pair": "ethusd",
        "quantity": 2.5,
        "price": 1750,
        "amount": 0,
        "net_market_amount": 0,
        "filled": 0,
        "vwap": 0,
        "filled_amount": 0,
        "fees": 0,
        "net_proceeds": 0,
        "status": "Started",
        "status_code": 100,
        "routing_option": "WeightedExchange",
        "routing_type": "NetPrice",
        "time_in_force": "GTC",
        "expires": null,
        "dateupdated": "2023-11-08T20:12:19.000Z",
        "date_added": "2022-11-07T20:52:40.000Z",
        "client_order_id": "d317e96a-0c26-4dc1-a4eb-b82b0e2a643c",
        "user_tx_id": "d317e96a-0c26-4dc1-a4eb-b82b0e2a643c",
        "o_action": "Buy",
        "algo_id": 201,
        "algorithm_options": null,
        "destination": ""
    },
    {
        "id": 2008561,
        "side_id": 600,
        "action": "Sell",
        "algorithm_id": 201,
        "algorithm": "Limit",
        "type": "Limit",
        "pair": "btcusd",
        "quantity": 1,
        "price": 38000,
        "amount": 0,
        "net_market_amount": 0,
        "filled": 0,
        "vwap": 0,
        "filled_amount": 0,
        "fees": 0,
        "net_proceeds": 0,
        "status": "Started",
        "status_code": 100,
        "routing_option": "WeightedExchange",
        "routing_type": "NetPrice",
        "time_in_force": "GTC",
        "expires": null,
        "dateupdated": "2023-11-08T20:11:58.000Z",
        "date_added": "2022-11-07T20:52:40.000Z",
        "client_order_id": "e6f9b6f3-5f01-444d-a83d-640dd67573ae",
        "user_tx_id": "e6f9b6f3-5f01-444d-a83d-640dd67573ae",
        "o_action": "Sell",
        "algo_id": 201,
        "algorithm_options": null,
        "destination": ""
    }
]
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/orders'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/orders',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/orders",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Done Orders

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/orders/done`

Retrieve a list of completed orders.

{% hint style="info" %}
[**Rate Limit**](/rest-api/rate-limits)**: 5 requests per 10 seconds**

sFOX recommends using the [**Orders WebSocket feed**](/websocket-api/orders-and-account-data/orders) instead, which streams order updates in real-time and does not count towards your request limit.
{% endhint %}

### **Query Parameters**

<table><thead><tr><th width="211">Parameter</th><th width="133">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>limit</code></strong></td><td>int</td><td>Limit on the number of results to return. Default and maximum = <code>50</code>. Each response will include no more than 50 results.</td></tr><tr><td><strong><code>before</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred before (older) than the specified ID (<code>id</code> from response body).</td></tr><tr><td><strong><code>after</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred after (newer) than the specified ID (<code>id</code> from response body).</td></tr><tr><td><strong><code>action</code></strong></td><td>string</td><td>Filter response to only include orders with the specified action/side. Possible values: <code>buy</code> or <code>sell</code> (case sensitive).</td></tr><tr><td><strong><code>currency_pair</code></strong></td><td>string</td><td>Filter response to only include orders on the specified currency pair (<code>pair</code> from response body). Format: <code>&#x3C;basequote></code> e.g. <code>btcusd</code>.</td></tr><tr><td><strong><code>algorithm_id</code></strong></td><td>int</td><td>Filter response to only include orders with the specified <code>algorithm_id</code>/order type. Possible values: <a href="/pages/-MksB3OWKUp0-RnwDoxN">Order Types</a>.</td></tr><tr><td><strong><code>status</code></strong></td><td>string</td><td>Filter response to only include orders with the specified order status (<code>status</code> from response body). Possible values: <a href="/pages/-Mkd5fv0VwgWbHGXHO7z">Order Statuses</a>.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
    {
        "id": 701968334,
        "side_id": 500,
        "action": "Buy",
        "algorithm_id": 200,
        "algorithm": "Smart",
        "type": "Smart",
        "pair": "btcusd",
        "quantity": 0.001,
        "price": 16900.6,
        "amount": 0,
        "net_market_amount": 0,
        "filled": 0.001,
        "vwap": 16900.6,
        "filled_amount": 16.9006,
        "fees": 0.0338012,
        "net_proceeds": -16.8667988,
        "status": "Done",
        "status_code": 300,
        "routing_option": "BestPrice",
        "routing_type": "NetPrice",
        "time_in_force": "GTC",
        "expires": null,
        "dateupdated": "2022-11-18T01:26:40.000Z",
        "date_added": "2022-11-17T20:52:40.000Z",
        "client_order_id": "94b0e7c4-0fa7-403d-a0d0-6c4ccec76630",
        "user_tx_id": "94b0e7c4-0fa7-403d-a0d0-6c4ccec76630",
        "o_action": "Buy",
        "algo_id": 200,
        "algorithm_options": null,
        "destination": ""
    },
    {
        "id": 701945645,
        "side_id": 500,
        "action": "Buy",
        "algorithm_id": 201,
        "algorithm": "Limit",
        "type": "Limit",
        "pair": "btcusd",
        "quantity": 0.01,
        "price": 16905,
        "amount": 0,
        "net_market_amount": 0,
        "filled": 0.01,
        "vwap": 16643,
        "filled_amount": 166.43,
        "fees": 0.16643,
        "net_proceeds": -166.26357,
        "status": "Done",
        "status_code": 300,
        "routing_option": "BestPrice",
        "routing_type": "NetPrice",
        "time_in_force": "GTC",
        "expires": null,
        "dateupdated": "2022-11-17T19:39:18.000Z",
        "date_added": "2022-11-17T18:52:40.000Z",
        "client_order_id": "",
        "user_tx_id": "",
        "o_action": "Buy",
        "algo_id": 201,
        "algorithm_options": null,
        "destination": ""
   }
]
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}
{% code overflow="wrap" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/orders/done?limit=20&after=711876817&currency_pair=btcusd'
```

{% endcode %}
{% endtab %}

{% tab title="NodeJS" %}
{% code overflow="wrap" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/orders/done?limit=20&after=711876817&currency_pair=btcusd',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/orders/done?limit=20&after=711876817&currency_pair=btcusd",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Get All Trades

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/account/trades`

Retrieve a list of completed trades (fills).

{% hint style="info" %}
[Stream trades real-time using the Trades WebSocket feed.](/websocket-api/orders-and-account-data/trades)
{% endhint %}

### **Path Parameters**

<table><thead><tr><th width="240">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>page_size</code></strong></td><td>number</td><td><p>The maximum number of trades to include in the response. </p><p></p><p>e.g. <code>page_size=20</code> will return a maximum of 20 trades in the response</p><p></p><p>Default <code>page_size</code> = <code>100</code></p></td></tr><tr><td><strong><code>last_seen_id</code></strong></td><td>number</td><td><p>The <code>cursor</code> of trade to paginate from. The response will contain trades completed after the <code>cursor</code>.</p><p></p><p>e.g. <code>last_seen_id=NjM1MjQ20c=</code> will return trades completed after the trade associated with this <code>cursor</code></p></td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
        {
            "cursor": "NjM1MzUwNzY=",
            "trade_id": 829106821,
            "order_id": 758399024,
            "date_updated": "2024-02-22T01:08:18.000Z",
            "action": "Sell",
            "currency_pair": "btcusd",
            "quantity": "0.01000000",
            "amount": "515.83628237",
            "price": "51583.62823740",
            "fees": "0.00000000",
            "net_amount": "515.83628237"
        },
        {
            "cursor": "NjM1MzUwNzQ=",
            "trade_id": 829106818,
            "order_id": 758319036,
            "date_updated": "2024-02-22T01:08:18.000Z",
            "action": "Buy",
            "currency_pair": "btcusd",
            "quantity": "0.01000000",
            "amount": "515.24440000",
            "price": "51524.44000000",
            "fees": "0.00000000",
            "net_amount": "515.24440000"
        },
        {
            "cursor": "NjM1MzUwNzI=",
            "trade_id": 829106817,
            "order_id": 758399024,
            "date_updated": "2024-02-22T01:08:18.000Z",
            "action": "Sell",
            "currency_pair": "btcusd",
            "quantity": "0.01000000",
            "amount": "515.79383311",
            "price": "51579.38331110",
            "fees": "0.00000000",
            "net_amount": "515.79383311"
        },
        {
            "cursor": "NjM1MzUwNjc=",
            "trade_id": 829105211,
            "order_id": 758399602,
            "date_updated": "2024-02-22T01:05:44.000Z",
            "action": "Sell",
            "currency_pair": "ltcusd",
            "quantity": "7.91515120",
            "amount": "542.39983445",
            "price": "68.52678120",
            "fees": "0.00000000",
            "net_amount": "542.39983445"
        },
        {
            "cursor": "NjM1MzUwNjU=",
            "trade_id": 829105212,
            "order_id": 758399603,
            "date_updated": "2024-02-22T01:05:44.000Z",
            "action": "Buy",
            "currency_pair": "ltcusd",
            "quantity": "7.91515120",
            "amount": "542.41023812",
            "price": "68.52809560",
            "fees": "0.00000000",
            "net_amount": "542.41023812"
        }
    ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/account/trades?page_size=<PAGE SIZE>&last_seen_id=
<CURSOR>'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/account/trades?page_size=<PAGE_SIZE>&last_seen_id=
<CURSOR>',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/account/trades?page_size=<PAGE SIZE>&last_seen_id=
<CURSOR>",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Request for Quote (RFQ)

Send Requests for Quotes

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1/quote`

Returns an actionable one-sided quote for the specified currency pair.

After sending an RFQ, the API will return a quote with a price at which a trade can be executed. If you agree with the price, you can request the execution of the trade using the [orders](/rest-api/orders#place-new-order) endpoint.

In the order request, you will need to specify the same:

* `currency_pair`
* `quote_id`
* exactly one of `quantity` or `amount`, matching the RFQ request
* and, if specified in the quote request, the `client_quote_id`

{% hint style="info" %}
Quote requests are rate limited to 10 requests per second.
{% endhint %}

### Request Body

<table><thead><tr><th width="247">Name</th><th width="123">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>pair</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>The currency pair for the quote. e.g. <code>btcusd</code></td></tr><tr><td><strong><code>side</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td><p>The side for the quote (whether you are buying or selling). Possible values:</p><ul><li><code>buy</code> : You want to buy</li><li><code>sell</code>: You want to sell</li></ul></td></tr><tr><td><strong><code>quantity</code></strong></td><td>number</td><td>The base currency quantity for the quote (e.g. <code>10</code> ). Provide exactly one of <code>quantity</code> or <code>amount</code>. <strong>Must be &#x3C;= the maximum quote quantity for the given pair.</strong></td></tr><tr><td><strong><code>amount</code></strong></td><td>number</td><td>The quote currency quantity for the quote (e.g. <code>300000.0000</code> ). Provide exactly one of <code>quantity</code> or <code>amount</code>.</td></tr><tr><td><strong><code>client_quote_id</code></strong></td><td>string</td><td>An optional idempotent identifier for your quote. <strong>If specified, you must specify the same value in the</strong> <code>client_order_id</code> <strong>field of your order request to execute on the quote.</strong></td></tr></tbody></table>

### Response Body

<table data-full-width="false"><thead><tr><th width="238.33333333333331">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>quote_id</code></strong></td><td>Unique identifier for the quote. <strong>Note</strong>: to execute an order on this quote you will specify this <code>quote_id</code> in your <a href="/pages/-Mkd5fv0VwgWbHGXHO7z#place-new-order">order request</a></td></tr><tr><td><strong><code>quantity</code></strong></td><td>The base currency quantity of the quote</td></tr><tr><td><strong><code>amount</code></strong></td><td>The quote currency amount of the quote</td></tr><tr><td><strong><code>pair</code></strong></td><td>The currency pair for the quote request</td></tr><tr><td><strong><code>side</code></strong></td><td>The quote side–whether you are buying or selling</td></tr><tr><td><strong><code>date_expiry</code></strong></td><td>The datetime the quote will expire</td></tr><tr><td><strong><code>date_quote</code></strong></td><td>The datetime the quote was generated</td></tr><tr><td><strong><code>buy_price</code></strong></td><td>The quote price–the price to buy this quantity. Returned if <code>side</code> = <code>buy</code>, else not included.</td></tr><tr><td><strong><code>sell_price</code></strong></td><td>The quote price–the price to sell this quantity. Returned if <code>side</code> = <code>sell</code>, else not included.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">201</mark></summary>

```json
{
    "quote_id": "165c404c-ffe9-11ed-b8ed-0a170e3de1bd",
    "pair": "btcusd",
    "side": "BUY",
    "date_expiry": "2023-05-31T19:26:58.595Z",
    "date_quote": "2023-05-31T19:26:48.595Z",
    "amount": 27044.7156,
    "quantity": 1,
    "buy_price": 27044.7156
}
```

</details>

<details>

<summary><mark style="color:red;">422</mark>: Unprocessable Entity</summary>

{% code overflow="wrap" %}

```json
//Requested quote size greater than maximum quote size for the currency pair
{
    "error": "request USD value <USD_VALUE_OF_REQUESTED_QUOTE_SIZE> greater than max USD value <MAX_USD_VALUE> for pair <CURRENCY_PAIR>"
}

//Currency pair not currently supported for RFQ
{
    "error": "<CURRENCY_PAIR> not currently supported for RFQ. please contact support for more information."
}
```

{% endcode %}

</details>

<details>

<summary><mark style="color:red;">503</mark>: Service Unavailable</summary>

{% code overflow="wrap" %}

```json
//RFQ requests are temporarily unavailable
{
    "error": "quotes temporarily unavailable. please try again later."
}

//RFQ requests are temporarily unavailable for this currency pair
{
    "error": "<CURRENCY_PAIR> quotes temporarily unavailable. please try again later."
}
```

{% endcode %}

</details>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer <API_TOKEN>' \
  --data '{ "pair": "btcusd",
            "side": "buy",
            "quantity": 1 }'  \
  'https://api.sfox.com/v1/quote'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/quote',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: {
   pair: 'btcusd',
   side: 'buy',
   quantity: 1
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/quote",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "pair": "btcusd",
    "side": "buy",
    "quantity": 1
  }
)
print(data)
```

{% endtab %}
{% endtabs %}

## End-to-End Example

The following example details the end-to-end process of requesting a quote from the RFQ endpoint and executing an order to trade on that quote. This example uses `quantity`. If your RFQ request used `amount`, submit the order with `amount` instead.

### RFQ

* **Request**: Requested a quote to purchase 1 BTC on the BTC/USD pair
* **Response**: Received a purchase price of `23243.49136824` for 1 BTC with Quote ID `cb436399-9db7-11ed-8ea6-0e5724aafd6b` which is later specified in the order

  request

<table data-header-hidden data-full-width="false"><thead><tr><th width="138"></th><th></th></tr></thead><tbody><tr><td><strong>Request</strong></td><td><pre class="language-bash" data-overflow="wrap"><code class="lang-bash">curl -X POST \
  -H 'Content-type: application/json' \ 
  -H 'Authorization: Bearer &#x3C;API_TOKEN>' \ 
  --data '{ "pair": “btcusd”,
            "side": "buy",
            “quantity”: 1 }' \ 
'https://api.sfox.com/v1/quote'
</code></pre></td></tr><tr><td><strong>Response</strong></td><td><pre class="language-json" data-overflow="wrap"><code class="lang-json">{
<strong>  "quote_id": "cb436399-9db7-11ed-8ea6-0e5724aafd6b", 
</strong>  "quantity": 1,
  "pair": "btcusd",
  "side": "BUY",
  "date_expiry": "2023-01-26T20:27:18.310Z", 
  "date_quote": "2023-01-26T20:27:03.310Z", 
  "buy_price": 23243.49136824
}
</code></pre></td></tr></tbody></table>

### Order Execution

* **Request**: Placed an order to buy 1 BTC on the BTC/USD pair and specified the previously received quote ID `cb436399-9db7-11ed-8ea6-0e5724aafd6b`
* **Response**: Received an “Order Filled” response, purchasing 1 BTC at the previously quoted unit price of `23243.49136824`

{% hint style="info" %}

* RFQ orders are Fill-or-Kill (FOK): Will be responded to with a “Done” (filled) or “Canceled” (rejected) order. The entire quantity will be filled or none at all
* Receive synchronous response: The response will reflect a terminal state of an order
* Are not guaranteed to be filled if placed within the quote expiry
* Only one order will be accepted per quote
* The order `quantity` or `amount` must be less than or equal to the corresponding quoted value
* Will settle immediately to your sFOX account if filled
  {% endhint %}

<table data-header-hidden data-full-width="false"><thead><tr><th width="173"></th><th></th></tr></thead><tbody><tr><td><strong>Request</strong></td><td><pre class="language-bash" data-overflow="wrap"><code class="lang-bash">curl -X POST \
  -H 'Content-type: application/json' \ 
  -H 'Authorization: Bearer &#x3C;API_TOKEN>' \ 
  --data '{ "currency_pair": “btcusd”,
            "quantity": 1,
            "quote_id": "cb436399-9db7-11ed-8ea6-0e5724aafd6b" }' \ 
      'https://api.sfox.com/v1/orders/buy'
</code></pre></td></tr><tr><td><strong>Response</strong></td><td><pre class="language-json" data-overflow="wrap"><code class="lang-json">{
  "id": 1754344,
  "side_id": 500,
  "action": "Buy",
  "algorithm_id": 150,
  "algorithm": "Instant",
  "type": "Instant",
  "pair": "btcusd",
<strong>  "quantity": 1,
</strong>  "price": 23243.49136824,
  "amount": 0,
  "net_market_amount": 0,
  "filled": 1,
  "vwap": 23243.49136824,
  "filled_amount": 23243.49136824,
  "fees": 0,
  "net_proceeds": -23243.49136824,
  "status": "Done",
  "status_code": 300,
  "routing_option": "BestPrice",
  "routing_type": "None",
  "time_in_force": "FOK",
  "expires": null,
  "dateupdated": "2023-01-26T20:27:06.000Z", "client_order_id": "",
  "user_tx_id": "",
  "o_action": "Buy",
  "algo_id": 150,
  "algorithm_options": null,
  "destination": "",
  "quote_id": "cb436399-9db7-11ed-8ea6-0e5724aafd6b"
}
</code></pre></td></tr></tbody></table>


# Post-Trade Settlement (PTS)

Manage positions, settlement, and risk


# Get Account Risk Metrics

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/post-trade-settlement`

Returns your account's current Post-Trade Settlement risk metrics

### Response Body

<table><thead><tr><th width="389.20396600566573">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>exposure</code></strong></td><td>Current USD value of credit used</td></tr><tr><td><strong><code>available_exposure</code></strong></td><td>USD value of credit available</td></tr><tr><td><strong><code>exposure_limit</code></strong></td><td>Credit limit</td></tr><tr><td><strong><code>equity</code></strong></td><td>Current USD value of your holdings</td></tr><tr><td><strong><code>equity_for_withdrawals</code></strong></td><td>The USD value of your portfolio that is available for withdrawals </td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "exposure": 1000378.13,
    "available_exposure":1999489.96,
    "exposure_limit":2000000.00,
    "equity": 100221.12,
    "equity_for_withdrawals":8000.42
}
```

</details>

<details>

<summary><mark style="color:red;">403</mark>: Forbidden</summary>

```json
//Your account does not have access to Post-Trade Settlement
{
    "error": "post trade settlement disabled"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/post-trade-settlement
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/post-trade-settlement',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/post-trade-settlement",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Positions

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/post-trade-settlement/positions`

Retrieve a list of your account's positions.

{% hint style="info" %}
[**Rate Limit**](/rest-api/rate-limits)**: 10 requests per 10 seconds**
{% endhint %}

### Query Parameters

<table><thead><tr><th width="243">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>status</code></strong></td><td>String</td><td><p>Filter response by position status</p><p><code>active</code> (default) = active positions</p><p><code>closed</code> = settlement history</p></td></tr><tr><td><strong><code>pair</code></strong></td><td>String</td><td>Filter response by currency pair associated with the position i.e. <code>btcusd</code></td></tr><tr><td><strong><code>loan_currency</code></strong></td><td>String</td><td>Filter response by loan currency i.e. <code>btc</code></td></tr><tr><td><strong><code>collateral_currency</code></strong></td><td>String</td><td>Filter response by collateral currency i.e. <code>btc</code></td></tr><tr><td><strong><code>margin_type</code></strong></td><td>String</td><td><p>Filter response by margin type</p><p><code>PTS_SHORT</code> = short positions</p><p><code>PTS_LONG</code> = long positions</p></td></tr><tr><td><strong><code>from</code></strong></td><td>String</td><td>Starting UNIX timestamp (in millis)<br></td></tr><tr><td><strong><code>to</code></strong></td><td>String</td><td>Ending UNIX timestamp (in millis)<br></td></tr><tr><td><strong><code>page_size</code></strong></td><td>String</td><td>The number of positions sent in the request. Default/Max = 100</td></tr><tr><td><strong><code>page_cursor</code></strong></td><td>String</td><td>The last Position Id of the previous page. The request will contain orders following the cursor.</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="254">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong></td><td>Position ID</td></tr><tr><td><strong><code>status</code></strong></td><td>The status of the position<br><code>ACTIVE</code> : Outstanding pending settlement<br><code>CLOSED</code> : Settled</td></tr><tr><td><strong><code>date_added</code></strong></td><td>Date and time the position was opened</td></tr><tr><td><strong><code>date_loan_closed</code></strong></td><td>The date and time the position was settled (<code>null</code> if position is active)</td></tr><tr><td><strong><code>loan_currency_symbol</code></strong></td><td>Currency borrowed</td></tr><tr><td><strong><code>current_loan_qty</code></strong></td><td>The amount currently awaiting settlement including interest if applicable</td></tr><tr><td><strong><code>collateral_currency</code></strong></td><td>Order proceeds currency</td></tr><tr><td><strong><code>pair</code></strong></td><td>Currency pair traded to open the position</td></tr><tr><td><strong><code>interest_rate</code></strong></td><td>The annualized interest rate of the borrowed currency</td></tr><tr><td><strong><code>interest_qty</code></strong></td><td>The amount of interest that has been charged to this position in terms of the currency borrowed</td></tr><tr><td><strong><code>margin_type</code></strong></td><td>Long or short</td></tr><tr><td><strong><code>order_id_open</code></strong></td><td>The ID of the order that opened the position</td></tr><tr><td><strong><code>order_id_close</code></strong></td><td>The ID of the order that closed/settled the position, if applicable (<code>null</code> if position is active or settled via transfer)</td></tr><tr><td><strong><code>proceeds</code></strong></td><td>Proceeds of the collateral currency as a result of this position</td></tr><tr><td><strong><code>vwap</code></strong></td><td>Open Price. The fill price of the order that opened the position</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "id": 3065,
    "status": "ACTIVE",
    "date_added": "2022-06-01T19:49:53.000Z",
    "date_loan_closed": null,
    "loan_currency_symbol": "btc",
    "current_loan_qty": 0.03349122,
    "collateral_currency": "usd",
    "pair": "btcusd",
    "interest_rate": 0.1,
    "interest_qty": 0.0000931,
    "margin_type": "PTS_SHORT",
    "order_id_open": 1117465,
    "order_id_close": null,
    "proceeds": 1003.651384,
    "vwap": 29967.597
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/post-trade-settlement/positions
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/post-trade-settlement/positions',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/post-trade-settlement/positions",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Funding Transactions

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/post-trade-settlement/interest/history`

Retrieve a list funding transactions that have accrued to positions in your account.

### Query Parameters

<table><thead><tr><th width="211">Name</th><th width="133">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>limit</code></strong></td><td>int</td><td>Limit on the number of results to return. Default: 100.</td></tr><tr><td><strong><code>before</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred before (older) than the specified ID (<code>id</code> from response body).</td></tr><tr><td><strong><code>after</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred after (newer) than the specified ID (<code>id</code> from response body).</td></tr><tr><td><strong><code>start_date</code></strong></td><td>timestamp</td><td>Search by minimum specified date time. Unix timestamp in ms.</td></tr><tr><td><strong><code>end_date</code></strong></td><td>timestamp</td><td>Search by maximum specified date time. Unix timestamp in ms.</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="211">Name</th><th width="133">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong></td><td>int</td><td>sFOX-generated ID for the transaction. Use for <code>before</code> / <code>after</code> pagination.</td></tr><tr><td><strong><code>currency</code></strong></td><td>string</td><td>The currency of the transaction.</td></tr><tr><td><strong><code>amount</code></strong></td><td>number</td><td>Amount of the currency charged.</td></tr><tr><td><strong><code>amount_usd</code></strong></td><td>number</td><td>USD value of the amount at the time of the transaction.</td></tr><tr><td><strong><code>date_added</code></strong></td><td>datetime</td><td>Date the transaction was created.</td></tr><tr><td><strong><code>date_updated</code></strong></td><td>datetime</td><td>Date the transaction was last updated.</td></tr><tr><td><strong><code>position_id</code></strong></td><td>int</td><td>sFOX-generated ID of the PTS position that this transaction accrued to.</td></tr><tr><td><strong><code>next_cursor</code></strong></td><td>int</td><td>Newest transaction <code>id</code> of the results. Paginate to the next, newer page of results specifying <code>after</code> = this value.</td></tr><tr><td><strong><code>prev_cursor</code></strong></td><td>int</td><td>Oldest transaction <code>id</code> of the results. Paginate to the next, older page of results specifying <code>before</code> = this value.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
        {
            "id": 2889941222331,
            "currency": "eth",
            "amount": 0.00011888,
            "amount_usd": 0.41202856,
            "date_added": "2024-03-21T20:39:00.000Z",
            "date_updated": "2024-03-21T20:39:00.000Z",
            "position_id": 253441111123
        },
        {
            "id": 2889941222330,
            "currency": "eth",
            "amount": 0.00011888,
            "amount_usd": 0.41218777,
            "date_added": "2024-03-21T19:37:00.000Z",
            "date_updated": "2024-03-21T19:37:00.000Z",
            "position_id": 253441111123
        }
    ],
    "page": {
        "next_cursor": 2889941222331,
        "prev_cursor": 2889941222330
    }
}
```

</details>

<details>

<summary><mark style="color:red;">400</mark>: Bad Request</summary>

```json
//specify only one of 'before' and 'after'
{
    "error": "before and after are mutually excusive parameters"
}

//start_date must be a valid Unix timestamp in ms
{
    "error": "start_date must be a valid timestamp"
}

//end_date must be a valid Unix timestamp in ms
{
    "error": "start_date must be a valid timestamp"
}
```

</details>

<details>

<summary><mark style="color:red;">401</mark>: Unauthorized</summary>

```json
//invalid API key
{
    "error": "user lookup failed"
}
```

</details>

<details>

<summary><mark style="color:red;">403</mark>: Forbidden</summary>

```json
//your account does not have post-trade settlement enabled
{
    "error": "post trade settlement disabled"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/post-trade-settlement/interest/history
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/post-trade-settlement/interest/history',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/post-trade-settlement/interest/history",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Funding Rates

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/post-trade-settlement/interest`

Retrieve the current PTS funding rates and terms per currency.

### Response Body

| Key                                 | Description                                                                                                  |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **`interest_rate`**                 | Annualized interest rate as decimal (i.e. `0.02` = 2%)                                                       |
| **`interest_grace_period_minutes`** | The amount of time in minutes after a position has been opened that interest will not accrue to the position |
| **`interest_frequency_minutes`**    | The frequency in minutes at which a position will accrue interest after the grace period has ended           |

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "usd": {
        "interest_rate":0.02,
        "interest_frequency_minutes":60,
        "interest_grace_period_minutes":1440
    },
    "btc": {
        "interest_rate":0.03,
        "interest_frequency_minutes":60,
        "interest_grace_period_minutes":1440
    }
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/post-trade-settlement/interest
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/post-trade-settlement/interest',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/post-trade-settlement/interest",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Risk Modes

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/post-trade-settlement/risk-modes`

Retrieve the current risk mode of each currency pair.

### Response Body

<table><thead><tr><th width="188">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency_pair</code></strong></td><td>The currency pair the risk mode is applied to.</td></tr><tr><td><strong><code>risk_mode</code></strong></td><td><p>The current risk mode setting of this currency pair. Possible values:</p><p><strong><code>Enabled</code></strong>: Credit may be used to open long or short positions.<br><strong><code>Long-Only</code></strong>: Credit may be used to open long positions.<br><strong><code>Short-Only</code></strong>: Credit may be used to open short positions.<br><strong><code>Reduce-Only</code></strong>: New positions may not be opened.</p></td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
        {
            "currency_pair": "btcusd",
            "risk_mode": "Enabled"
        },
        {
            "currency_pair": "btcpax",
            "risk_mode": "Reduce_Only"
        },
        {
            "currency_pair": "ltcbtc",
            "risk_mode": "Enabled"
        }}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```sh
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/post-trade-settlement/risk-modes
```

{% endtab %}

{% tab title="NodeJs" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/post-trade-settlement/risk-modes',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/post-trade-settlement/risk-modes",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Create Transfer

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1/account/transfer`

Transfer funds between your account's trading and collateral wallets.

{% hint style="info" %}
**Hedge long positions:** Transfer funds to your collateral wallet so you can open a short position on the same currency in your trading wallet.
{% endhint %}

{% hint style="warning" %}
Transfers from your collateral wallet to your trading wallet will automatically settle unsettled positions, if applicable, first. The remainder, if any, will be applied to your trading wallet.
{% endhint %}

### Body Parameters

<table><thead><tr><th width="244">Name</th><th width="95">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>String</td><td>Currency to be transferred</td></tr><tr><td><strong><code>quantity</code></strong> <mark style="color:red;">required</mark></td><td>String</td><td>Quantity to be transferred</td></tr><tr><td><strong><code>from_wallet</code></strong> <mark style="color:red;">required</mark></td><td>String</td><td>Wallet being transferred from. Possible values:<br><code>trading</code>: your account's trading wallet<br><code>collateral</code>: your account's collateral wallet</td></tr><tr><td><strong><code>to_wallet</code></strong> <mark style="color:red;">required</mark></td><td>String</td><td>Wallet being transferred to. Possible values:<br><code>trading</code>: your account's trading wallet<br><code>collateral</code>: your account's collateral wallet</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="254">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>from_transaction_id</code></strong></td><td>sFOX generated ID of the transaction debiting the source wallet of the transfer</td></tr><tr><td><strong><code>to_transaction_id</code></strong></td><td>sFOX generated ID of the transaction crediting the destination wallet of the transfer</td></tr><tr><td><strong><code>currency</code></strong></td><td>Currency that was transferred</td></tr><tr><td><strong><code>quantity</code></strong></td><td>Quantity of the currency that was transferred</td></tr><tr><td><strong><code>from_wallet</code></strong></td><td>Name of the source wallet (<code>trading</code> or <code>collateral</code>)</td></tr><tr><td><strong><code>to_wallet</code></strong></td><td>Name of the destination wallet (<code>trading</code> or <code>collateral</code>)</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "from_transaction_id": 5467771,
    "to_transaction_id": 5467772,
    "currency": "btc",
    "quantity": 1,
    "from_wallet": "trading",
    "to_wallet": "collateral"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
-X POST \
--data '{"currency": "btc", "quantity": "1", "from_wallet": "trading", "to_wallet": "collateral"}' \
https://api.sfox.com/v1/account/transfer
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/account/transfer',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: { 
    currency: 'btc',
    quantity: 1,
    from_wallet: 'trading',
    to_wallet: 'collateral'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/account/transfer",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "currency": "btc",
    "quantity": 1,
    "from_wallet": "trading",
    "to_wallet": "collateral"
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Shorting

Manage short positions, position settlement, and portfolio risk


# Get Account Risk Metrics

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/margin/account`

Returns your account's current risk metrics.

{% hint style="info" %}
Shorting is only available if your account is enabled for margin trading
{% endhint %}

### Response Body

<table><thead><tr><th width="339.33890664607196">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>account_value</code></strong></td><td>Your account's current value in USD</td></tr><tr><td><strong><code>equity</code></strong></td><td>Your account's USD balance - <code>position_notional</code></td></tr><tr><td><strong><code>position_notional</code></strong></td><td>The USD value of the active short positions in your account</td></tr><tr><td><strong><code>collateral</code></strong></td><td>The total amount of collateral you hold in your account (USD balance - USD proceeds from opening short positions)</td></tr><tr><td><strong><code>free_collateral</code></strong></td><td>The collateral available for opening new short positions</td></tr><tr><td><strong><code>margin_level</code></strong></td><td>Your account's current risk level (<code>equity</code> / <code>position_notional</code>). null if you have no active positions</td></tr><tr><td><strong><code>margin_call_level</code></strong></td><td>The <code>margin_level</code> at which you will receive a notification from sFOX to let you know that your <code>margin_level</code> is low and we suggest either closing positions or depositing additional collateral (USD) to avoid liquidation</td></tr><tr><td><strong><code>maintenance_margin_level</code></strong></td><td>The <code>margin_level</code> at which your position will be automatically liquidated</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "account_value": 100885.75696235,
    "equity": 97850.05595684,
    "position_notional": 88153.20356472,
    "collateral": 97850.05595684,
    "free_collateral": 97850.05595684,
    "margin_level": 1.11,
    "margin_call_level": 0.15,
    "maintenance_margin_level": 0.05
}
```

</details>

<details>

<summary><mark style="color:red;">403</mark>: Forbidden</summary>

```json
//Your account does not have Margin enabled
{
    "error": "account is not enabled for margin trading"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/margin/account
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/margin/account',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/margin/account",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Positions

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/margin/loans`

Retrieve a list of your account's positions.

{% hint style="info" %}
[**Rate Limit**](/rest-api/rate-limits)**: 10 requests per 10 seconds**
{% endhint %}

### Query Parameters

<table><thead><tr><th width="286">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>status</code></strong></td><td>string</td><td><p>Filter response by position status</p><p><code>active</code> (default) = active positions</p><p><code>closed</code> = settlement history</p></td></tr><tr><td><strong><code>pair</code></strong></td><td>string</td><td>Filter response by currency pair associated with the position i.e. <code>btcusd</code></td></tr><tr><td><strong><code>loan_currency</code></strong></td><td>string</td><td>Filter response by loan currency i.e. <code>btc</code></td></tr><tr><td><strong><code>collateral_currency</code></strong></td><td>string</td><td>Filter response by collateral currency i.e. <code>btc</code></td></tr><tr><td><strong><code>margin_type</code></strong></td><td>string</td><td><p>Filter response by margin type</p><p><code>PTS_SHORT</code> = short positions</p><p><code>PTS_LONG</code> = long positions</p></td></tr><tr><td><strong><code>from</code></strong></td><td>string</td><td>Starting UNIX timestamp (in millis)<br></td></tr><tr><td><strong><code>to</code></strong></td><td>string</td><td>Ending UNIX timestamp (in millis)<br></td></tr><tr><td><strong><code>page_size</code></strong></td><td>string</td><td>The number of positions sent in the request. Default/Max = 100</td></tr><tr><td><strong><code>page_cursor</code></strong></td><td>string</td><td>The last Position Id of the previous page. The request will contain orders following the cursor.</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="311">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong></td><td>Position ID</td></tr><tr><td><strong><code>status</code></strong></td><td>The status of the position<br><code>ACTIVE</code> : Outstanding pending settlement<br><code>CLOSED</code> : Settled</td></tr><tr><td><strong><code>date_added</code></strong></td><td>Date and time the position was opened</td></tr><tr><td><strong><code>date_loan_closed</code></strong></td><td>The date and time the position was settled (<code>null</code> if position is active)</td></tr><tr><td><strong><code>loan_currency</code></strong></td><td>Currency borrowed</td></tr><tr><td><strong><code>current_loan_qty</code></strong></td><td>The amount currently awaiting settlement including interest if applicable</td></tr><tr><td><strong><code>collateral_currency</code></strong></td><td>Order proceeds currency</td></tr><tr><td><strong><code>pair</code></strong></td><td>Currency pair traded to open the position</td></tr><tr><td><strong><code>interest_rate</code></strong></td><td>The annualized interest rate of the borrowed currency</td></tr><tr><td><strong><code>interest_qty</code></strong></td><td>The amount of interest that has been charged to this position in terms of the currency borrowed</td></tr><tr><td><strong><code>margin_type</code></strong></td><td>Long or short</td></tr><tr><td><strong><code>order_id</code></strong></td><td>The ID of the order that opened the position</td></tr><tr><td><strong><code>proceeds</code></strong></td><td>Proceeds of the collateral currency as a result of this position</td></tr><tr><td><strong><code>vwap</code></strong></td><td>Open Price. The fill price of the order that opened the position</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
        {
            "id": 3835,
            "status": "CLOSED",
            "date_added": "2022-06-30T01:01:55.000Z",
            "date_loan_closed": "2022-06-30T01:02:47.000Z",
            "loan_currency": "btc",
            "collateral_currency": "usd",
            "pair": "btcusd",
            "original_collateral_qty": 2101.94565,
            "current_collateral_qty": 0,
            "original_loan_qty": 0.1,
            "current_loan_qty": 0,
            "interest_qty": 0,
            "interest_rate": 0.1,
            "margin_type": "MARGIN_SHORT",
            "order_id": 1127584,
            "proceeds": 0
        },
        {
            "id": 3836,
            "status": "CLOSED",
            "date_added": "2022-06-30T02:46:57.000Z",
            "date_loan_closed": "2022-07-01T02:41:01.000Z",
            "loan_currency": "btc",
            "collateral_currency": "usd",
            "pair": "btcusd",
            "original_collateral_qty": 2107.60095,
            "current_collateral_qty": 0,
            "original_loan_qty": 0.1,
            "current_loan_qty": 0,
            "interest_qty": 0,
            "interest_rate": 0.1,
            "margin_type": "MARGIN_SHORT",
            "order_id": 1127591,
            "proceeds": 0
        }
    ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/margin/loans
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/margin/loans',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/margin/loans",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Transfers

Deposit to, withdraw from, and transfer within your sFOX account


# Get All Deposit Addresses

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/wallet-addresses`

Retrieve a list of crypto addresses for transferring funds to your sFOX account

### Response Body

<table><thead><tr><th width="242">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong></td><td>Crypto asset</td></tr><tr><td><strong><code>address</code></strong></td><td>Crypto address to use for deposits</td></tr><tr><td><strong><code>wallet_type</code></strong></td><td>Whether the address is for your trading account or Web3 wallet. Possible values:<br><code>Sfox Trading Wallet</code>: Your trading account<br><code>Web3 Wallet</code>: Your Web3 wallet</td></tr><tr><td><strong><code>primary_network</code></strong></td><td>The network supported for sending funds to this address</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "addresses": [
        {
            "currency": "eth",
            "address": "<ethereum_address>",
            "wallet_type": "Sfox Trading Wallet",
            "primary_network": "Ethereum"
        },
        {
            "currency": "sol",
            "address": "<solana_address>",
            "wallet_type": "Sfox Trading Wallet",
            "primary_network": "Solana"
        },
        {
            "currency": "btc",
            "address": "<bitcoin_address>",
            "wallet_type": "Sfox Trading Wallet",
            "primary_network": "Bitcoin"
        },
        {
            "currency": "eth",
            "address": "<ethereum_address>",
            "wallet_type": "Web3 Wallet",
            "primary_network": "Ethereum"
        }
    ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
https://api.sfox.com/v1/wallet-addresses
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/wallet-addresses',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/wallet-addresses",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get Single Deposit Address

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/user/deposit/address/:currency`

Retrieve your crypto deposit address(es) for a currency.

### Path Parameters

<table><thead><tr><th width="238">Name</th><th width="90">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Specify the currency you want to retrieve deposit address(es) for.</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="190">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong></td><td>Crypto asset</td></tr><tr><td><strong><code>address</code></strong></td><td>Crypto address to use for deposits</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
  {
    "address": "0x123456789",
    "currency": "eth"     
  }
]
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \ 
-H 'Content-Type: application/json' \
-X GET \
'https://api.sfox.com/v1/user/deposit/address/btc'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/user/deposit/address/eth',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/user/deposit/address/eth",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Create Deposit Address

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1/user/deposit/address/:currency`

Create a new deposit address for the crypto asset of your specified in your request.

### Path Parameters

<table><thead><tr><th width="238">Name</th><th width="90">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Create a deposit address for this currency e.g. <code>eth</code></td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="190">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong></td><td>Crypto asset</td></tr><tr><td><strong><code>address</code></strong></td><td>Crypto address to use for deposits</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "address":"<eth_address>",
    "currency":"eth"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
-X POST \
'https://api.sfox.com/v1/user/deposit/address/eth'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/user/deposit/address/eth',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/user/deposit/address/eth",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Deposit From Bank Account

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1/user/bank/deposit`

Initiate an ACH transfer from your linked bank account to your sFOX account.

### Body Parameters

<table><thead><tr><th width="227">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>amount</code></strong> <mark style="color:red;">required</mark></td><td>number</td><td>The amount of USD to send to your sFOX account.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
  "tx_status": 0000,
  "success": true
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
-X POST \
--data '{"amount": 100}' \
'https://api.sfox.com/v1/user/bank/deposit'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/user/bank/deposit',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: { 
    amount: 100
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/user/bank/deposit",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "amount": 100
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Withdraw From Account

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1/user/withdraw`

Initiate a withdrawal from your sFOX account to a crypto address or wire transfer to your linked bank account.

### Body Parameters

<table><thead><tr><th width="227">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>The currency to withdraw</td></tr><tr><td><strong><code>amount</code></strong> <mark style="color:red;">required</mark></td><td>number</td><td>The amount of the currency to withdraw</td></tr><tr><td><strong><code>address</code></strong></td><td>string</td><td>The crypto address to withdraw to. <strong>Required if</strong> <code>currency</code> <strong>is NOT</strong> <code>usd</code></td></tr><tr><td><strong><code>isWire</code></strong></td><td>boolean</td><td>Specify the bank withdrawal method. Possible values:<br><code>1</code>: Wire Transfer<br><code>0</code>: ACH Transfer (default)<br><br>Note, if <code>isWire</code> is not sent in the JSON body, the sFOX system will default to ACH Transfer.</td></tr><tr><td><strong><code>memo</code></strong></td><td>string</td><td>Optional description/memo field</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "success": true,
    "id": "5pauoj52osolwphwnioqxx2zcekikm23x2hyq2rkotockiysng3y5k245q",
    "atx_id": 1524562,
    "tx_status": 1100,
    "currency": "eth",
    "amount": 0.1,
    "address": "0x12345"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
-X POST \
--data '{"amount": 1, "currency": "eth", "address": "0x123456"}' \
'https://api.sfox.com/v1/user/withdraw'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/user/withdraw',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: { 
    currency: 'eth',
    address: '0x123456',
    amount: 1
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/user/withdraw",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  json={
    "currency": "eth",
    "address": "0x123456"
    "amount": 1
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get Single Withdrawal Fee

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/withdraw-fee/:currency`

Retrieve the withdrawal fee for a currency.

### Path Parameters

<table><thead><tr><th width="236">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Retrieve the withdrawal fee for this currency.</td></tr><tr><td><strong><code>channel</code></strong> </td><td>string</td><td>When <code>currency</code> = <code>usd</code>, the optional <code>channel</code> query parameter can be provided to request either <code>domestic</code> or <code>international</code> wire fees.</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="239">Key</th><th width="99"></th><th>Description</th></tr></thead><tbody><tr><td><strong><code>fee</code></strong></td><td>number</td><td>The withdrawal fee for this currency. Fee is the quantity of the currency.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
      "fee": 0.001
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell - BTC" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
-X GET \
'https://api.sfox.com/v1/withdraw-fee/btc'
```

{% endtab %}

{% tab title="Shell - USD" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
-X GET \
'https://api.sfox.com/v1/withdraw-fee/usd?channel=international'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/withdraw-fee/btc',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
})
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/withdraw-fee/btc",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Create Transfer

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1`**`/account/transfer`**

Transfer funds between your account's trading and collateral wallets.

{% hint style="info" %}
**Hedge long positions:** Transfer funds to your collateral wallet so you can open a short position on the same currency in your trading wallet.
{% endhint %}

{% hint style="warning" %}
Transfers from your collateral wallet to your trading wallet will automatically settle unsettled positions, if applicable, first. The remainder, if any, will be applied to your trading wallet.
{% endhint %}

### Body Parameters

<table><thead><tr><th width="244">Name</th><th width="95">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>String</td><td>Currency to be transferred</td></tr><tr><td><strong><code>quantity</code></strong> <mark style="color:red;">required</mark></td><td>Number</td><td>Quantity to be transferred</td></tr><tr><td><strong><code>from_wallet</code></strong> <mark style="color:red;">required</mark></td><td>String</td><td>Wallet being transferred from. Possible values:<br><code>trading</code>: your account's trading wallet<br><code>collateral</code>: your account's collateral wallet</td></tr><tr><td><strong><code>to_wallet</code></strong> <mark style="color:red;">required</mark></td><td>String</td><td>Wallet being transferred to. Possible values:<br><code>trading</code>: your account's trading wallet<br><code>collateral</code>: your account's collateral wallet</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="254">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>from_transaction_id</code></strong></td><td>sFOX generated ID of the transaction debiting the source wallet of the transfer</td></tr><tr><td><strong><code>to_transaction_id</code></strong></td><td>sFOX generated ID of the transaction crediting the destination wallet of the transfer</td></tr><tr><td><strong><code>currency</code></strong></td><td>Currency that was transferred</td></tr><tr><td><strong><code>quantity</code></strong></td><td>Quantity of the currency that was transferred</td></tr><tr><td><strong><code>from_wallet</code></strong></td><td>Name of the source wallet (<code>trading</code> or <code>collateral</code>)</td></tr><tr><td><strong><code>to_wallet</code></strong></td><td>Name of the destination wallet (<code>trading</code> or <code>collateral</code>)</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "from_transaction_id": 5467771,
    "to_transaction_id": 5467772,
    "currency": "btc",
    "quantity": 1,
    "from_wallet": "trading",
    "to_wallet": "collateral"
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
-X POST \
--data '{"currency": "btc", "quantity": "1", "from_wallet": "trading", "to_wallet": "collateral"}' \
https://api.sfox.com/v1/account/transfer
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/account/transfer',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: { 
    currency: 'btc',
    quantity: 1,
    from_wallet: 'trading',
    to_wallet: 'collateral'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/account/transfer",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "currency": "btc",
    "quantity": 1,
    "from_wallet": "trading",
    "to_wallet": "collateral"
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Custody (sFOX SAFE)

sFOX SAFE Custody is available all sFOX users. However, access is not granted by default. Contact support to request access.


# Get Whitelisted Addresses

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1`**`/whitelisted-addresses`**

Retrieve a list of the crypto withdrawal addresses you have whitelisted in your account.

### Response Body

<table><thead><tr><th width="240">Parameter</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>alias</code></strong></td><td>Custom alias you have assigned to the address</td></tr><tr><td><strong><code>address</code></strong></td><td>Whitelisted withdraw address</td></tr><tr><td><strong><code>currency_symbol</code></strong></td><td>Currency that can be withdrawn to the address</td></tr><tr><td><strong><code>date_created</code></strong></td><td>ISO date string</td></tr><tr><td><strong><code>date_updated</code></strong></td><td>ISO date string</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{ 
  "data": [ 
    { 
      "alias": "Satoshis Fund",
      "address": "1NLqQmwkGxxQmzS9uwtCGXxbxrcNW4FpYp",
      "currency_symbol": "btc",
      "date_created": "2021-09-15T15:12:13.000Z",
      "date_updated": "2021-09-15T15:12:13.000Z",
      "status":"Pending"
    }
  ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
'https://api.sfox.com/v1/whitelisted-addresses'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/whitelisted-addresses',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/whitelisted-addresses",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Add Whitelisted Address

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1`**`/whitelisted-addresses`**

Add a new crypto address to your account's whitelisted withdrawal addresses.

{% hint style="info" %}
If you have an approval rule for adding new whitelisted addresses, the address may not be immediately added to your whitelist as it may require approval from other users in your account.
{% endhint %}

### Body Parameters

<table><thead><tr><th width="281">Parameter</th><th width="91">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency_symbol</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Currency that can be withdrawn to this address</td></tr><tr><td><strong><code>address</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Crypto address to add to whitelist</td></tr><tr><td><strong><code>alias</code></strong></td><td>string</td><td>Custom alias to help identify your whitelisted withdrawal address</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
   "id":"4d90ee41-3b36-11ec-bdb0-0ab29ff926a1",
   "alias":"Satoshis Fund",
   "address":"1NLqQmwkGxxQmzS9uwtCGXxbxrcNW4FpYp",
   "currency_symbol":"btc",
   "date_created":"2021-11-01T17:08:15.000Z",
   "date_updated":"2021-11-01T17:08:15.000Z",
   "status":"Pending",
   "tag":null
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer < API_TOKEN >' \
  --data '{ "alias": "Satoshis Fund",
            "currency_symbol": "btc",
            "address": "1NLqQmwkGxxQmzS9uwtCGXxbxrcNW4FpYp" }' \
  'https://api.sfox.com/v1/whitelisted-addresses'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/whitelisted-addresses',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: {
    alias: 'Satoshis Fund',
    currency_symbol: 'btc',
    address: '1NLqQmwkGxxQmzS9uwtCGXxbxrcNW4FpYp'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/whitelisted-addresses",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "alias": "Satoshis Fund",
    "currency_symbol": "btc",
    "address": "1NLqQmwkGxxQmzS9uwtCGXxbxrcNW4FpYp"
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Delete Whitelisted Address

<mark style="color:red;">**`DELETE`**</mark>   `https://api.sfox.com/v1/whitelisted-addresses/:address_id`

Remove a crypto address from your account's whitelisted addresses.

### Path Parameters

<table><thead><tr><th width="240">Parameter</th><th width="92">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>address_id</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td>The address ID generated by sFOX upon adding the address to your whitelist.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark> OK</summary>

```
{}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X DELETE \
  -H 'Content-type: application/json' \
  -H "Authorization: Bearer ${API_TOKEN}" \
  "https://api.sfox.com/v1/whitelisted-addresses/${ADDRESS_ID}"
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'delete',
  url: `https://api.sfox.com/v1/whitelisted-addresses/${ADDRESS_ID}`,
  headers: {
    'Authorization': `Bearer ${API_KEY}`
  },
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

data = requests.delete(
  f"https://api.sfox.com/v1/whitelisted-addresses/{ADDRESS_ID}",
  headers={
    "Authorization": f"Bearer {os.environ['API_KEY']}",
  }
)
print(data.json())
```

{% endtab %}
{% endtabs %}


# Get Approval Rules

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1`**`/approval-rules`**

Retrieve a list of the approval rules you have created in your account.

{% hint style="info" %}
sFOX SAFE Custody is available all sFOX users. However, access is not granted by default. [Learn more and request access here](https://www.sfox.com/digital-asset-custody/).
{% endhint %}

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
      {
        "id": 3,
        "available_approver_count": 2,
        "date_added": "2021-03-17T16:19:47.000Z",
        "required_approvals": 2,
        "rule_type": "WITHDRAW",
        "status": "Pending Approval",
        "threshold": 20
      }
    ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
'https://api.sfox.com/v1/approval-rules'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/approval-rules',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/approval-rules",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Create Approval Rule

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1`**`/approval-rules`**

Add a new crypto address to your account's whitelisted withdrawal addresses.

{% hint style="info" %}
If you have an approval rule for altering SAFE settings, the new rule may not be immediately added to your account as it may require approval from other users in your account.
{% endhint %}

### Body Parameters

<table><thead><tr><th width="303">Parameter</th><th width="95">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>rule_type</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td><p>The type of approval rule to create. Possible values:</p><ul><li><code>WITHDRAW</code>: Approval rule for withdrawals.</li><li><code>ADD_ALTER_COLL</code>: Adding/editing users in your account.</li><li><code>ALTER_SAFE</code>: Adding/editing approval rules in your account.</li></ul></td></tr><tr><td><strong><code>required_approvals</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td>Number of approvals needed for the action to be approved.</td></tr><tr><td><strong><code>threshold</code></strong></td><td>number</td><td>The withdrawal amount (USD) required for the action to require approvals. <strong>Required if <code>rule_type</code> = <code>WITHDRAW</code></strong></td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
  id: 1,
  rule_type: "WITHDRAW",
  date_added: "2021-03-17T16:19:47.000Z",
  status: "Pending",
  available_approver_count: 2,
  required_approvals: 2,
  threshold: 0,
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer <API_TOKEN>' \
  --data '{ "rule_type":  "WITHDRAW", 
            "required_approvals":  2, 
            "threshold":  100 }'  \
  'https://api.sfox.com/v1/approval-rules'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/approval-rules',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: { 
    rule_type:  "WITHDRAW", 
    required_approvals:  2, 
    threshold:  100 
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/approval-rules",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
   "rule_type": "WITHDRAW",
   "required_approvals": 2,
   "threshold": 100
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Edit Approval Rule

<mark style="color:orange;">**`PATCH`**</mark> `https://api.sfox.com/v1`**`/approval-rules/:rule_id`**

Change an existing approval rule in your account.

{% hint style="info" %}
If you have an approval rule for altering SAFE settings, the change submitted may not be immediately processed as it may require approval from other users in your account.
{% endhint %}

### Path Parameters

<table><thead><tr><th width="190">Parameter</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>rule_id</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td>ID of the approval rule generated by sFOX you wish to edit</td></tr></tbody></table>

### Body Parameters

<table><thead><tr><th width="234">Parameter</th><th width="90"></th><th>Description</th></tr></thead><tbody><tr><td><strong><code>required_approvals</code></strong></td><td>int</td><td>Number of approvals needed for the action to be approved.</td></tr><tr><td><strong><code>threshold</code></strong></td><td>number</td><td>The withdrawal amount (USD) required for the action to require approvals.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
  id: 1,
  rule_type: "WITHDRAW",
  date_added: "2021-03-17T16:19:47.000Z",
  status: "Pending",
  available_approver_count: 2,
  required_approvals: 2,
  threshold: 100,
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X PATCH \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer <API_TOKEN>' \
  --data '{ "required_approvals":  3 , "threshold":  500 }'  \
  'https://api.sfox.com/v1/approval-rules/1'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'patch',
  url: 'https://api.sfox.com/v1/approval-rules/1',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: {
    required_approvals:  3 , 
    threshold:  500
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.patch(
  "https://api.sfox.com/v1/approval-rules/1",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
   "required_approvals": 3,
   "threshold": 500
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get Approval Requests

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1`**`/approvals`**

Retrieve a list of approval requests.

### Query Parameters

<table><thead><tr><th width="145">Parameter</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>pending</code></strong></td><td>boolean</td><td>When set to <code>true</code> will only return pending approvals, otherwise all approvals both completed and pending will be returned.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
      {
        "approval_id": 1,
        "requested_by_username": "example@email.com",
        "requested_by_uaid": "6ea3fb9e-7797-11eb-aa51-0242ac120002",
        "date_added": "2021-03-03T20:28:41.000Z",
        "status": "Pending",
        "approval_type": "WITHDRAW",
        "required_approvals": 2,
        "received_approvals": 0,
        "action_details": {
          "atx_currency_code": "btc",
          "atx_amount": 5,
          "atx_dest_address": "0x1232131223",
          "threshold": 1
        },
        "approval_responses": {
          "ua_display_id": "3fb9e6ea-7797-11eb-aa51-200020242ac1",
          "username": "collaborator@email.com",
          "approved": true
        }
    ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \
 'https://api.sfox.com/v1/approvals'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
import requests

data = requests.get(
  "https://api.sfox.com/v1/approvals",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/approval-rules",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Respond to Approval Request

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1`**`/approvals/:request_id`**

Approve or deny a request.

### Path Parameters

<table><thead><tr><th width="227">Parameter</th><th width="80">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>request_id</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td>ID of the approval request generated by sFOX you wish to respond to</td></tr></tbody></table>

### Body Parameters

<table><thead><tr><th width="191">Parameter</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>approve</code></strong> <mark style="color:red;">required</mark></td><td>boolean</td><td>Approves the request if true, denies the request if false</td></tr></tbody></table>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer <API_TOKEN>' \
  --data '{ "approve": true}'  \
  'https://api.sfox.com/v1/approvals/1'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
import requests

data = requests.post(
  "https://api.sfox.com/v1/approvals/1",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "approve": True
  }
)
print(data)
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.patch(
  "https://api.sfox.com/v1/approval-rules/1",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
   "required_approvals": 3,
   "threshold": 500
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Staking

Earn rewards on your holdings by staking supported digital assets. Once you have completed account verification, staking will be enabled for your account. Only certain assets are available to stake.


# Get Staking Currencies

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1`**`/staking/currencies`**

Retrieve a list staking-enabled assets along with the staking terms for that asset including the minimum amount, staking period, bonding, and unbonding period.

### Response Body

<table><thead><tr><th width="352">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong></td><td>The digital asset that may be staked</td></tr><tr><td><strong><code>min_stake_amount</code></strong></td><td>The minimum amount of this asset that may be staked in a given request</td></tr><tr><td><strong><code>min_stake_period_minutes</code></strong></td><td>The default period, in minutes, that the asset will be staking</td></tr><tr><td><strong><code>stake_bonding_period_minutes</code></strong></td><td>The amount of time, in minutes, after a staking request has been processed until the stake will begin accruing rewards</td></tr><tr><td><strong><code>stake_unbonding_period_minutes</code></strong></td><td>The amount of time, in minutes, that a completed stake of this asset will remain unavailable and not accruing rewards</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
        {
            "currency": "avax",
            "min_stake_amount": "25",
            "min_stake_period_minutes": 20160,
            "stake_bonding_period_minutes": 0,
            "stake_unbonding_period_minutes": 0
        }
    ]
}
```

</details>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' 
'https://api.sfox.com/v1/staking/currencies'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/staking/currencies',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/staking/currencies",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get All Staking Transactions

Staking and reward transaction history

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1`**`/staking/transactions`**

Retrieve a list of staking transactions from your account including stake and reward transactions.

### Query Parameters

<table><thead><tr><th width="152">Parameter</th><th width="118">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong></td><td>string</td><td>Retrieve transactions for a given asset or set of assets. <br>e.g. <code>?currency=avax%Cdot</code></td></tr><tr><td><strong><code>types</code></strong></td><td>string</td><td><p>Retrieve a specified type of transactions or set of transaction types. Possible values:</p><ul><li><code>STAKE</code>: Staking transactions</li><li><code>REWARD</code>: Reward transactions</li></ul></td></tr><tr><td><strong><code>from</code></strong></td><td>timestamp</td><td>Retrieve transactions that occurred after and including this timestamp (UNIX timestamp in ms).</td></tr><tr><td><strong><code>to</code></strong></td><td>timestamp</td><td>Retrieve transactions that occurred before and including this timestamp (UNIX timestamp in ms).</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="269">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>amount</code></strong></td><td>The transaction amount</td></tr><tr><td><strong><code>atx_id</code></strong></td><td>The associated ID of this transaction on your account ledger</td></tr><tr><td><strong><code>stake_start</code></strong></td><td>Time at which the staking period began for this request</td></tr><tr><td><strong><code>stake_end</code></strong></td><td>Time at which the staking period will or did end</td></tr><tr><td><strong><code>staked_reward_amount</code></strong></td><td>The rewards that were earned from this staking request</td></tr><tr><td><strong><code>staked_auto_restake</code></strong></td><td>Flag signifying whether you have enabled auto re-staking for this request</td></tr><tr><td><strong><code>date_added</code></strong></td><td>Time at which this transaction was recorded</td></tr><tr><td><strong><code>date_updated</code></strong></td><td>Time of the most recent update to this transaction</td></tr><tr><td><strong><code>currency_symbol</code></strong></td><td>Asset associated with this transaction</td></tr><tr><td><strong><code>status</code></strong></td><td>Status of this transaction</td></tr><tr><td><strong><code>type</code></strong></td><td>Type of transaction (either <code>stake</code> or <code>reward</code>)</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": [
        {
            "amount": 0.0670929,
            "atx_id": 1452808,
            "stake_start": null,
            "stake_end": null,
            "staked_reward_amount": null,
            "staked_auto_restake": null,
            "date_added": "2022-09-29T23:05:34.000Z",
            "date_updated": "2022-09-29T23:05:34.000Z",
            "currency_symbol": "avax",
            "status": "done",
            "type": "reward"
        },
        {
            "amount": 25,
            "atx_id": 1315723,
            "stake_start": "2022-09-15T23:04:27.000Z",
            "stake_end": "2022-09-29T23:04:27.000Z",
            "staked_reward_amount": 0.0670929,
            "staked_auto_restake": 0,
            "date_added": "2022-09-15T23:04:11.000Z",
            "date_updated": "2022-09-29T23:05:34.000Z",
            "currency_symbol": "avax",
            "status": "Unstaked",
            "type": "stake"
        }
    ]
}
```

</details>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' 
'https://api.sfox.com/v1/staking/transactions'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/staking/transactions',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/staking/transactions",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Create Stake

Submit a request to stake an asset

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1`**`/staking/stake`**

Create a stake transaction.

Submitting a staking request will transfer the specified quantity of the specified asset from your trading wallet to your staking wallet. At that point the request will begin processing. Once processed you can view and manage this request via the staking transactions endpoint.

{% hint style="info" %}
A successful stake request will transfer funds from your `trading_wallet` to your `staking_wallet.`Your request quantity must be greater than the `min_stake_amount` required for the asset your are staking.
{% endhint %}

### Body Parameters

<table><thead><tr><th width="232">Parameter</th><th width="95">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>The asset to stake e.g. <code>avax</code>.</td></tr><tr><td><strong><code>quantity</code></strong> <mark style="color:red;">required</mark></td><td>number</td><td>The amount of the <code>currency</code> to stake.</td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="153">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong></td><td>The sFOX-generated ID of this stake transaction.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
{
    "data": {
        "id":435
    }
}
```

</details>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer <API_TOKEN>' \
  --data '{ "currency": "avax",
            "quantity": 500 }'  \
  'https://api.sfox.com/v1/staking/stake'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/staking/stake',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: {
   currency: 'avax',
   quantity: 500
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/staking/stake",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "currency": "avax",
    "quantity": 500
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Cancel Stake

Submit a request to stake an asset

<mark style="color:red;">**`DELETE`**</mark> `https://api.sfox.com/v1`**`/staking/:id`**

Cancel a pending stake transaction.

{% hint style="info" %}
Only pending stakes (`status` = `PENDING`) may be canceled.
{% endhint %}

### Path Parameters

<table><thead><tr><th width="167">Parameter</th><th width="95">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td>The sFOX-generated ID of the pending stake transaction you wish to cancel.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">202</mark>: Successfully Canceled Stake</summary>

```json
//Response does not include a response body
```

</details>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X DELETE \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer <API_TOKEN>' \
  'https://api.sfox.com/v1/staking/123'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'delete',
  url: 'https://api.sfox.com/v1/staking/123',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.delete(
  "https://api.sfox.com/v1/staking/123",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Unstake

Submit a request to unstake an asset

<mark style="color:blue;">**`POST`**</mark> `https://api.sfox.com/v1`**`/staking/unstake`**

Submit a request to unstake an an active stake.

{% hint style="info" %}
Only active stakes (`status` = `STAKING`) may be unstaked. Only certain currencies may be unstaked on demand.
{% endhint %}

### Body Parameters

<table><thead><tr><th width="232">Parameter</th><th width="95">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td>The sFOX-generated ID of the active stake you wish to unstake.</td></tr><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>The currency of the active stake you wish to unstake.</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">204</mark>: Unstake Request Accepted</summary>

```json
//Success response does not include a response body
```

</details>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H 'Authorization: Bearer <API_TOKEN>' \
  --data '{ "currency": "avax",
            "id": 500 }'  \
  'https://api.sfox.com/v1/staking/unstake'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'post',
  url: 'https://api.sfox.com/v1/staking/unstake',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  data: {
   currency: 'avax',
   id: 500
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.post(
  "https://api.sfox.com/v1/staking/unstake",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  data={
    "currency": "avax",
    "id": 500
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Market Data

Retrieve market data from sFOX

{% content-ref url="/pages/HoUS6l45i8X7tYKJBIbb" %}
[Get Candlesticks](/rest-api/market-data/get-candlesticks)
{% endcontent-ref %}

{% content-ref url="/pages/D6vVmF5scUerC2HxTTDz" %}
[Get Volume Analytics](/rest-api/market-data/get-volume-analytics)
{% endcontent-ref %}

{% content-ref url="/pages/Gq6D9m1VngRjmOG7Hllm" %}
[Get Order Estimate](/rest-api/market-data/get-order-estimate)
{% endcontent-ref %}

{% content-ref url="/pages/XMkFODI8dLeWAgs780Sd" %}
[Get Order Book](/rest-api/market-data/get-order-book)
{% endcontent-ref %}


# Get Candlesticks

Historical candlestick data for a currency pair

<mark style="color:green;">**`GET`**</mark> `https://chartdata.sfox.com/candlesticks`

Retrieve historical candlestick / OHLCV (Open-High-Low-Close-Volume) data for a currency pair. Returns an array of objects, each representing a candle.

{% hint style="info" %}

* Data represents aggregated trades data from all of sFOX's supported liquidity providers. NOT representative of trades executed on sFOX.
* Data is not forward-filled and, therefore, may be incomplete. e.g. no data will be returned for an interval during which 0 trades were recorded.
  {% endhint %}

{% hint style="warning" %}
**Responses are limited to 500 candles.** If the requested `startTime` , `endTime` , and `period` will result in more than 500 data points, your request will be rejected. To retrieve data over a larger time range, you will need to make multiple requests with new `startTime` / `endTime` ranges. Candles may precede your specified `startTime` value.
{% endhint %}

### Query Parameters

<table><thead><tr><th width="244">Parameter</th><th width="145">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>pair</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>Specify the currency pair to retrieve data for. e.g. <code>btcusd</code></td></tr><tr><td><strong><code>startTime</code></strong> <mark style="color:red;">required</mark></td><td>timestamp</td><td>The unix timestamp (seconds) of the first datapoint returned</td></tr><tr><td><strong><code>endTime</code></strong> <mark style="color:red;">required</mark></td><td>timestamp</td><td>The unix timestamp (seconds) of the last datapoint you want returned</td></tr><tr><td><strong><code>period</code></strong></td><td>int</td><td><p>The duration or interval of each datapoint or candle in seconds (e.g. <code>period</code> = <code>60</code> would return 1-minute candles). Possible values:</p><ul><li><code>60</code> (1 minute) default if not specified</li><li><code>300</code> (5 minute)</li><li><code>900</code> (15 minute)</li><li><code>3600</code> (1 hour)</li><li><code>21600</code> (6 hour)</li><li><code>86400</code> (1 day)</li></ul></td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="218">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>open_price</code></strong></td><td>The price of the first trade recorded after the <code>start_time</code></td></tr><tr><td><strong><code>high_price</code></strong></td><td>The highest trade price during this period</td></tr><tr><td><strong><code>low_price</code></strong></td><td>The lowest trade price during this period</td></tr><tr><td><strong><code>close_price</code></strong></td><td>The price of the last trade executed in this period</td></tr><tr><td><strong><code>volume</code></strong></td><td>Total base currency volume traded during this period</td></tr><tr><td><strong><code>start_time</code></strong></td><td>The unix timestamp of the beginning of the period</td></tr><tr><td><strong><code>pair</code></strong></td><td>The trading pair / symbol</td></tr><tr><td><strong><code>candle_period</code></strong></td><td>The duration of each datapoint in seconds</td></tr><tr><td><strong><code>vwap</code></strong></td><td>The volume-weighted average price of the period</td></tr><tr><td><strong><code>trades</code></strong></td><td>The total number of trades executed across all liquidity providers during that period</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
  {
    "open_price":"9654",
    "high_price":"9662.37",
    "low_price":"9653.66",
    "close_price":"9655.73",
    "volume":"6.31945755",
    "start_time":1592939280,
    "pair":"btcusd",
    "candle_period":60,
    "vwap":"9655.70504211",
    "trades":53
  }
]
```

</details>

### Example Request

{% tabs %}
{% tab title="Shell" %}
{% code overflow="wrap" %}

```bash
curl 'https://chartdata.sfox.com/candlesticks?endTime=1665165809&pair=btcusd&period=86400&startTime=1657217002'
```

{% endcode %}
{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://chartdata.sfox.com/candlesticks',
  params: {
    pair: 'btcusd',
    startTime: 1657217002,
    endTime: 1665165809,
    period: 86400
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://chartdata.sfox.com/candlesticks",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  params={
   "pair":"btcusd",
   "startTime": 1657217002,
   "endTime": 1665165809,
   "period": 86400
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get Volume Analytics

Historical volume data by currency

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/analytics/volume`

Retrieve historical exchange volume analytics by currency.

{% hint style="info" %}
Data is not forward-filled and, therefore, may be incomplete. e.g. no data will be returned for an interval during which 0 trades were recorded.
{% endhint %}

{% hint style="warning" %}
**Responses are limited to 500 results.** If the requested `start_time` , `end_time` , and `interval` will result in more than 500 results, your request will be rejected. To retrieve data over a larger time range, you will need to make multiple requests with new `start_time` / `end_time` ranges. Results may precede your specified `start_time` value.
{% endhint %}

### Query Parameters

<table><thead><tr><th width="271">Name</th><th width="139">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>start_time</code></strong> <mark style="color:red;">required</mark></td><td>timestamp</td><td>Unix timestamp (ms) of the first datapoint to return</td></tr><tr><td><strong><code>end_time</code></strong></td><td>timestamp</td><td>Unix timestamp (ms) of the last datapoint to return</td></tr><tr><td><strong><code>interval</code></strong> <mark style="color:red;">required</mark></td><td>int</td><td><p>Duration of each datapoint in seconds (i.e. <code>interval</code> = <code>86400</code> = daily volume data)</p><p>(<code>60</code> | <code>3600</code> | <code>86400</code>)</p></td></tr><tr><td><strong><code>currency</code></strong> <mark style="color:red;">required</mark></td><td>string</td><td>The currency to retrieve data for (i.e. <code>eth</code>)</td></tr><tr><td><strong><code>net</code></strong></td><td>boolean</td><td><p>Retrieve "net volume" (net buy/sell volume) or "gross volume" (total traded volume)</p><p>(<code>true</code> | <code>false</code>)</p><p>default = <code>false</code></p></td></tr><tr><td><strong><code>by_exchange</code></strong></td><td>boolean</td><td><p>Retrieve total market volume or volume by exchange</p><p>(<code>true</code> | <code>false</code>)<br>default = <code>false</code></p></td></tr></tbody></table>

### Response Body

<table><thead><tr><th width="182">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>timstamp</code></strong></td><td>The Unix timestamp (ms) of the beginning of the interval</td></tr><tr><td><strong><code>exchange</code></strong></td><td>The exchange associated with the volume data (only returned if <code>by_exchange</code> = <code>true</code> in the request)</td></tr><tr><td><strong><code>volume</code></strong></td><td>The quantity of the specified currency traded during this interval</td></tr><tr><td><strong><code>usd_notional</code></strong></td><td>The USD value of the quantity of the specified currency traded during this interval</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark>: Gross Volume</summary>

<pre class="language-json"><code class="lang-json"><strong>//interval=86400&#x26;net=false&#x26;by_exchange=false
</strong><strong>{
</strong>    "data": [
        {
            "timestamp": 1689206400000,
            "volume": 324557.08579094,
            "usd_notional": 633266040.1379151
        },
        {
            "timestamp": 1689292800000,
            "volume": 244525.03601467,
            "usd_notional": 482590637.1359154
        },
        {
            "timestamp": 1689379200000,
            "volume": 54552.86708131,
            "usd_notional": 105565737.85291174
        },
        {
            "timestamp": 1689465600000,
            "volume": 59350.88216805,
            "usd_notional": 114595675.74899396
        },
        {
            "timestamp": 1689552000000,
            "volume": 174930.26792864,
            "usd_notional": 333229267.7529286
        }
    ]
}
</code></pre>

</details>

<details>

<summary><mark style="color:green;">200</mark>: Net Volume</summary>

```json
//interval=86400&net=true&by_exchange=false
{
    "data": [
        {
            "timestamp": 1689206400000,
            "volume": 23385.45910848,
            "usd_notional": 45629005.60418967
        },
        {
            "timestamp": 1689292800000,
            "volume": 487.77127065,
            "usd_notional": 962657.4526522362
        },
        {
            "timestamp": 1689379200000,
            "volume": 541.72807017,
            "usd_notional": 1048302.8024520231
        }
    ]
}
```

</details>

<details>

<summary><mark style="color:green;">200</mark>: Gross Volume by Exchange</summary>

```json
//interval=86400&net=false&by_exchange=true
{
    "data": [
        {
            "timestamp": 1689206400000,
            "volumes": [
                {
                    "exchange": "bitfinex",
                    "volume": 22064.11327313,
                    "usd_notional": 43050835.2870461
                },
                {
                    "exchange": "bitflyer",
                    "volume": 675.3754941,
                    "usd_notional": 1317772.3842097484
                },
                {
                    "exchange": "bitstamp",
                    "volume": 20403.74974212,
                    "usd_notional": 39811183.82200494
                },
                {
                    "exchange": "coinbase",
                    "volume": 256084.73824809,
                    "usd_notional": 499664851.6698304
                },
                {
                    "exchange": "gemini",
                    "volume": 2893.597955,
                    "usd_notional": 5645901.442109791
                },
                {
                    "exchange": "kraken",
                    "volume": 22435.5110785,
                    "usd_notional": 43775495.53271416
                }
            ]
        },
        {
            "timestamp": 1689292800000,
            "volumes": [
                {
                    "exchange": "bitfinex",
                    "volume": 16438.39032122,
                    "usd_notional": 32442539.986500576
                },
                {
                    "exchange": "bitflyer",
                    "volume": 282.4740891,
                    "usd_notional": 557486.2715692556
                },
                {
                    "exchange": "bitstamp",
                    "volume": 11499.07793533,
                    "usd_notional": 22694393.333832387
                },
                {
                    "exchange": "coinbase",
                    "volume": 194042.96600292,
                    "usd_notional": 382960044.1791732
                },
                {
                    "exchange": "gemini",
                    "volume": 1941.224533,
                    "usd_notional": 3831169.1901688813
                },
                {
                    "exchange": "kraken",
                    "volume": 20320.9031331,
                    "usd_notional": 40105004.17467113
                }
            ]
        }
    ]
}
```

</details>

<details>

<summary><mark style="color:green;">200</mark>: Net Volume by Exchange</summary>

```json
//interval=86400&net=true&by_exchange=true
{
    "data": [
        {
            "timestamp": 1689206400000,
            "volumes": [
                {
                    "exchange": "bitfinex",
                    "volume": -6825.69751025,
                    "usd_notional": -13318096.02295827
                },
                {
                    "exchange": "bitflyer",
                    "volume": 405.5878231,
                    "usd_notional": 791370.7816200266
                },
                {
                    "exchange": "bitstamp",
                    "volume": 2621.19358698,
                    "usd_notional": 5114394.218867672
                },
                {
                    "exchange": "coinbase",
                    "volume": 25602.95423207,
                    "usd_notional": 49955715.503370605
                },
                {
                    "exchange": "gemini",
                    "volume": 278.054287,
                    "usd_notional": 542531.1755026139
                },
                {
                    "exchange": "kraken",
                    "volume": 1303.36668958,
                    "usd_notional": 2543089.9477870227
                }
            ]
        },
        {
            "timestamp": 1689292800000,
            "volumes": [
                {
                    "exchange": "bitfinex",
                    "volume": -3128.46017994,
                    "usd_notional": -6174278.168395847
                },
                {
                    "exchange": "bitflyer",
                    "volume": 81.1377265,
                    "usd_notional": 160132.098396033
                },
                {
                    "exchange": "bitstamp",
                    "volume": 211.54172883,
                    "usd_notional": 417495.3181104044
                },
                {
                    "exchange": "coinbase",
                    "volume": 4753.17507186,
                    "usd_notional": 9380789.074742645
                },
                {
                    "exchange": "gemini",
                    "volume": -341.430339,
                    "usd_notional": -673841.3682337883
                },
                {
                    "exchange": "kraken",
                    "volume": -1088.1927376,
                    "usd_notional": -2147639.5019672103
                }
            ]
        }
    ]
}
```

</details>

<details>

<summary><mark style="color:red;">401</mark>: Unauthorized</summary>

```json
{
    "error": "invalid token. check authorization header."
}
```

</details>

<details>

<summary><mark style="color:red;">422</mark>: Unprocessable Entity</summary>

```json
{
    "error": "currency must be a non-blank string"
}
```

</details>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>'
'https://api.sfox.com/v1/analytics/volume?currency=btc&interval=86400&start_time=1689279127000&end_time=1689624727000&net=true'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/analytics/volume?currency=btc&interval=86400&start_time=1689279127000&end_time=1689624727000&net=true',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/analytics/volume?currency=btc&interval=86400&start_time=1689279127000&end_time=1689624727000&net=true",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get Order Estimate

Smart Routing Order Estimate

## Smart Routing Order Estimate

<mark style="color:blue;">`GET`</mark> `https://api.sfox.com/v1/offer/:side`

Get an estimated execution price for the specified quantity of a given asset using sFOX’s Smart Order Routing, as well as related information. **Only use this as an estimate – execution is not guaranteed.**

#### Path Parameters

| Name                                   | Type   | Description                                                                     |                       |
| -------------------------------------- | ------ | ------------------------------------------------------------------------------- | --------------------- |
| side<mark style="color:red;">\*</mark> | String | <p>Specifies your order side. </p><p><strong>Options</strong>: <code>buy</code> | <code>sell</code></p> |

#### Query Parameters

| Name                                       | Type   | Description                                                                                                                                  |                        |
| ------------------------------------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |
| pair                                       | String | <p>The pair or product to trade in the format: (i.e. "btcusd", "ethbtc", "usdteth")</p><p><strong>Default</strong> = <code>btcusd</code></p> |                        |
| quantity<mark style="color:red;">\*</mark> | Number | The base currency quantity to buy or sell. `quantity` **OR** `maxspend` are required.                                                        |                        |
| maxspend                                   | Number | The quote currency amount to spend (side = buy) or receive (side = sell). `quantity` **OR** `maxspend` are required.                         |                        |
| routing\_type                              | String | <p>The sFOX order book used for the estimate</p><p><strong>Options</strong>: <code>NetPrice</code>                                           | <code>Smart</code></p> |

{% tabs %}
{% tab title="200: OK Success" %}

```json
{
    "price": 19203.23787426,
    "subtotal": 19202.05116807,
    "fees": 6.72071791, 
    "total": 19208.77188598,
    "quantity": 1,
    "vwap": 19202.05116807,
    "currency_pair": "btcusd",
    "routing_type": "NetPrice"
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
This response is an estimate, not a quote. Prices fluctuate often, therefore, it is possible that an order submitted after receiving this estimate will execute differently. Real-time order book and ticker data is available through SFOX’s [Websocket API](https://www.sfox.com/developers/#websocket-feeds).
{% endhint %}

### Response Body

{% hint style="info" %}
VWAP, Price, Fees, and Total are in the quote currency (e.g. USD for a btcusd pair).
{% endhint %}

<table><thead><tr><th width="184">Key</th><th>Description</th><th width="167.1732854288847">Example</th></tr></thead><tbody><tr><td><code>price</code></td><td>Estimated order limit price to specify when placing this order to receive the estimated fill price at the time of this request. (Quote Currency)</td><td>19203.23787426</td></tr><tr><td><code>subtotal</code></td><td>If <code>side</code> = <code>buy</code>: Estimated cost before fees.<br>If <code>side</code> = <code>sell</code>: Estimated proceeds before fees.</td><td>19202.05116807</td></tr><tr><td><code>fees</code></td><td>Estimated fees you would pay in quote currency terms for this order. <strong>Note: Authentication required to receive a fees estimate</strong></td><td>6.72071791</td></tr><tr><td><code>total</code></td><td>If <code>side</code> = <code>buy</code>: Estimated cost net fees.<br>If <code>side</code> = <code>sell</code>: Estimated proceeds net fees.</td><td>19208.77188598</td></tr><tr><td><code>quantity</code></td><td>The base currency quantity applicable to the estimate. Equal to the <code>quantity</code> parameter in the request.</td><td>1</td></tr><tr><td><code>vwap</code></td><td>Estimated fill price you would receive at the time of this request. (Quote currency terms)</td><td>19202.05116807</td></tr><tr><td><code>currency_pair</code></td><td>Trading pair / symbol</td><td>"btcusd"</td></tr><tr><td><code>routing_type</code></td><td>sFOX order book used for this estimate</td><td>"NetPrice"</td></tr></tbody></table>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl 'https://api.sfox.com/v1/offer/buy?quantity=1&pair=btcusd'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/offer/buy',
  params: {
    quantity: 1,
    pair: 'btcusd' 
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/offer/buy",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  params={
    "quantity": 1,
    "pair": "btcusd"
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Get Order Book

Order book snapshot for a currency pair.

## Orderbook

<mark style="color:blue;">`GET`</mark> `https://api.sfox.com/v1/markets/orderbook/:pair`

Get the blended L2 orderbook data of our connected exchanges, including the top bids and asks and the location of those bids and asks

#### Path Parameters

| Name | Type   | Description                                                                                                  |
| ---- | ------ | ------------------------------------------------------------------------------------------------------------ |
| pair | string | <p>The pair or product to trade in the format: (i.e. "btcusd", "ethbtc", "usdteth")<br>Default: "btcusd"</p> |

{% tabs %}
{% tab title="200 " %}

```
{
  "bids": [
    [
      9458.12,
      1e-08,
      "gemini"
    ],
    [
      9456,
      1,
      "itbit"
    ],
    [
      9453,
      0.73553115,
      "itbit"
    ],
    // truncated
  "asks": [
    [
      9455.55,
      2.03782954,
      "market1"
    ],
    [
      9455.56,
      0.9908,
      "market1"
    ],
    [
      9455.59,
      0.60321264,
      "market1"
    ],
    // truncated
  "market_making": {
    "bids": [
      [
        9447.34,
        2,
        "bitstamp"
      ],
      [
        9452.01,
        0.60321264,
        "market1"
      ],
      [
        9452.31,
        0.47488688,
        "bittrex"
      ],
      [
        9456,
        1,
        "itbit"
      ],
      [
        9458.12,
        1e-08,
        "gemini"
      ]
    ],
    "asks": [
      [
        9458.13,
        2.07196048,
        "gemini"
      ],
      [
        9457.75,
        0.14748797,
        "itbit"
      ],
      [
        9456,
        0.1686167,
        "bittrex"
      ],
      [
        9455.68,
        0.742406,
        "bitstamp"
      ],
      [
        9455.55,
        2.03782954,
        "market1"
      ]
    ]
  },
  "timestamps": {
    "gemini": [
      1572903458537,
      1572903458538
    ],
    "bitstamp": [
      1572903458199,
      1572903458199
    ],
    "itbit": [
      1572903458414,
      1572903458416
    ],
    "bittrex": [
      1572903458517,
      1572903458517
    ],
    "market1": [
      1572903458071,
      1572903458071
    ]
  },
  "lastupdated": 1572903458756,
  "pair": "btcusd",
  "currency": "usd",
  "lastpublished": 1572903458798\}
```

{% endtab %}
{% endtabs %}

### Response Body

<table><thead><tr><th width="216">Key</th><th width="800">Description</th></tr></thead><tbody><tr><td><code>pair</code></td><td>The trading pair</td></tr><tr><td><code>currency</code></td><td>The quote currency</td></tr><tr><td><code>asks</code></td><td>List of asks, size, and exchange</td></tr><tr><td><code>bids</code></td><td>List of the bids, size, and exchange</td></tr><tr><td><code>market_making</code></td><td>List of the best bid and ask on each exchange</td></tr><tr><td><code>timestamp</code></td><td>A list of exchanges and the latest timestamps of the orderbook</td></tr><tr><td><code>lastupdated</code></td><td>Last update of the blended orderbook</td></tr><tr><td><code>lastpublished</code></td><td>Last time an orderbook update was published</td></tr></tbody></table>

### Example Request

{% tabs %}
{% tab title="Shell" %}

```bash
curl 'https://api.sfox.com/v1/markets/orderbook/btcusd'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/markets/orderbook/btcusd',
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/markets/orderbook/btcusd",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endtab %}
{% endtabs %}


# Reporting

Account transaction history and tax aid reports

**Generate an order-level report:**

{% content-ref url="/pages/h1q1JmGP5q1mxgilihgC" %}
[Get Orders Report](/rest-api/reporting/get-orders-report)
{% endcontent-ref %}

**Generate a monthly activity report by asset:**

{% content-ref url="/pages/eoiwhb1a83GUc04nVmBI" %}
[Get Monthly Summary](/rest-api/reporting/get-monthly-summary)
{% endcontent-ref %}

**Generate a portfolio valuation report:**

{% content-ref url="/pages/8P6wWonKkvnEoBNhuyzA" %}
[Get Portfolio Valuation](/rest-api/reporting/get-portfolio-valuation)
{% endcontent-ref %}

**Retrieve your account transaction history:**

{% content-ref url="/pages/Wm3b4sFrrvU9ZFElm0fL" %}
[Broken mention](broken://pages/Wm3b4sFrrvU9ZFElm0fL)
{% endcontent-ref %}


# Get Orders Report

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/users/reports/tax-order-summary`

Returns a list of order summaries from the specified time period.

## Request

### Headers

<table><thead><tr><th width="214.6171875">Name</th><th width="78.5703125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>Content-Type</code> <em><mark style="color:red;">required</mark></em></td><td>string</td><td><code>application/json</code></td></tr><tr><td><code>Authorization</code> <em><mark style="color:red;">required</mark></em></td><td>string</td><td>Bearer token</td></tr></tbody></table>

### Query Parameters

<table><thead><tr><th width="102.9609375">Name</th><th width="97.578125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>end</code></td><td>Number</td><td>The unix timestamp (seconds) of the last datapoint returned</td></tr><tr><td><code>start</code></td><td>Number</td><td>The unix timestamp (seconds) of the first datapoint returned</td></tr></tbody></table>

### Example Request

{% tabs %}
{% tab title="Curl" %}
{% code overflow="wrap" %}

```bash
curl 'https://api.sfox.com/v1/users/reports/tax-order-summary?end=1676102399999&start=1673337600000'
```

{% endcode %}
{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/users/reports/tax-order-summary',
  params: {
    startTime: 1657217002,
    endTime: 1665165809
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/users/reports/tax-order-summary",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  params={
   "startTime": 1657217002,
   "endTime": 1665165809
  }
)
print(data)
```

{% endtab %}
{% endtabs %}

## Response

CSV formatted response

{% tabs %}
{% tab title="200 " %}

```
OrderId,OrderDate,AddedByUserEmail,Action,AssetPair,Quantity,Asset,AssetUSDFXRate,UnitPrice,PriceCurrency,PrincipalAmount,PriceUSDFXRate,PrincipalAmountUSD,Fees,FeesUSD,Total,TotalUSD
703915618,Tue Jan 24 2023 01:44:00 GMT+0000 (Coordinated Universal Time),qmccarthy@sfox.com,Buy,xlmusd,106.35165019,xlm,0.09384001,0.09384001,usd,9.98003992,1,9.98003992,0.01996008,0.01996008,10,10
703915655,Tue Jan 24 2023 01:47:06 GMT+0000 (Coordinated Universal Time),qmccarthy@sfox.com,Sell,xlmusd,150.56406,xlm,0.09377324,0.09377324,usd,14.11887974,1,14.11887973,0.02823776,0.02823776,14.09064197,14.09064197
704255180,Fri Feb 10 2023 00:19:10 GMT+0000 (Coordinated Universal Time),qmccarthy@sfox.com,Buy,avaxusd,1,avax,17.94148758,17.94148758,usd,17.94148758,1,17.94148758,0.03588298,0.03588298,17.97737056,17.97737056
```

{% endtab %}
{% endtabs %}


# Get Monthly Summary

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/users/reports/tax-currency-summary`

Monthly summary of transactions for a selected currency

## Request

### Query Parameters

<table><thead><tr><th width="166.2890625">Name</th><th width="112.37890625">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>end</code> <em><mark style="color:red;">required</mark></em></td><td>timestamp</td><td>The unix timestamp (seconds) of the last datapoint returned</td></tr><tr><td><code>start</code> <em><mark style="color:red;">required</mark></em></td><td>timestamp</td><td>The unix timestamp (seconds) of the first datapoint returned</td></tr><tr><td><code>currency</code></td><td>string</td><td>Currency code for the requested report. If left blank, response will include all applicable currencies.</td></tr></tbody></table>

### Example Request

{% tabs %}
{% tab title="Curl" %}

```bash
curl 'https://api.sfox.com/v1/users/reports/tax-currency-summary?currency=usd&end=1676102399999&start=1673337600000'
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/users/reports/tax-currency-summary',
  params: {
    currency: 'btc',
    startTime: 1657217002,
    endTime: 1665165809
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/users/reports/tax-currency-summary",
  headers={
    "Authorization": "Bearer <API_KEY>",
  },
  params={
   "currency": "btc",
   "startTime": 1657217002,
   "endTime": 1665165809
  }
)
print(data)
```

{% endtab %}
{% endtabs %}

## Response

CSV formatted response

### Example Response

{% tabs %}
{% tab title="200 " %}

```
CurrencyYear,CurrencyMonth,Currency,Deposits,DepositsUSD,Credits,Withdrawals,WithdrawalsUSD,Charges,Buys,BuysTotalUSD,BuysTotalFeesUSD,Sells,SellsTotalUSD,SellsTotalFeesUSD,BuysForCrypto,BuysForCryptoUSD,SellsForCrypto,SellsForCryptoUSD
2023,1,usd,0,0,0,0,0,0,0,0,0,0,0,0,14.11887974,14.11887974,9.98003992,9.98003992
2023,2,usd,25,25,0,0,0,0,0,0,0,0,0,0,0,0,17.94148758,17.94148758
```

{% endtab %}
{% endtabs %}


# Get Portfolio Valuation

USD valuation of your portfolio over time

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/account/balance/history`

Retrieve a history of the USD value of your account's portfolio at hourly or daily intervals

## Request

### Query Parameters

<table><thead><tr><th width="136.453125">Name</th><th width="115.68359375" align="center">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>start_date</code> <em><mark style="color:red;">required</mark></em></td><td align="center">timestamp</td><td>Timestamp of the start of the query. Unix timestamp (ms)</td></tr><tr><td><code>end_date</code></td><td align="center">timestamp</td><td>Timestamp of the end of the query. Unix timestamp (ms)</td></tr><tr><td><code>interval</code></td><td align="center">int</td><td><p>Timeseries interval (sec). <br>Possible values: <code>3600</code> (hourly), <code>86400</code> (daily)</p><p>Default value: <code>86400</code></p></td></tr></tbody></table>

### Example Request

{% tabs %}
{% tab title="Shell" %}
{% code overflow="wrap" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>'
'https://api.sfox.com/v1/account/balance/history?interval=86400&start_date=1701475200000&end_date=1701734400000'
```

{% endcode %}
{% endtab %}

{% tab title="NodeJS" %}
{% code overflow="wrap" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/account/balance/history?interval=86400&start_date=1701475200000&end_date=1701734400000',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/account/balance/history?interval=86400&start_date=1701475200000&end_date=1701734400000",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
)
print(data)
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Response

### Response Body

<table><thead><tr><th width="156">Key</th><th width="113.375" align="center">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>data</code></td><td align="center">[object]</td><td>An array of portfolio value objects, each object with a <code>timestamp</code> and <code>usd_value</code></td></tr><tr><td><code>timestamp</code></td><td align="center">timestamp</td><td>Unix timestamp (ms) of the valuation</td></tr><tr><td><code>usd_value</code></td><td align="center">number</td><td>USD valuation of your portfolio as of the timestamp</td></tr></tbody></table>

### Responses

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "data": [
        {
            "timestamp": 1701475200000,
            "usd_value": 349515.64495392627
        },
        {
            "timestamp": 1701561600000,
            "usd_value": 349628.6458040236
        },
        {
            "timestamp": 1701648000000,
            "usd_value": 349653.452981625
        },
        {
            "timestamp": 1701734400000,
            "usd_value": 349301.02066800353
        },
        {
            "timestamp": 1701820800000,
            "usd_value": 350066.51819476683
        },
        {
            "timestamp": 1701907200000,
            "usd_value": 350761.96052562393
        }
    ]
}
```

{% endtab %}

{% tab title="422: Unprocessable Entity Invalid Request" %}

```json
//Invalid start_date
{
    "error": "start_date must be a valid unix timestamp in milliseconds"
}

//Invalid end_date
{
    "error": "end_date must be a valid unix timestamp in milliseconds"
}

// Invalid interval
{
    "error": "interval must be 3600 or 86400"
}
```

{% endtab %}
{% endtabs %}


# Get All Transactions

Retrieve your transaction history

<mark style="color:green;">**`GET`**</mark> `https://api.sfox.com/v1/account/transactions`

Retrieve your transaction history, including trades and transfers. It returns an array of objects, each of which has details for each individual transaction.

{% hint style="info" %}
[**Rate Limit**](/rest-api/rate-limits)**: 1 request per 10 seconds**

Receive real-time [trade](/websocket-api/market-data/trades), [order](/websocket-api/orders-and-account-data/orders), and [balance](/websocket-api/orders-and-account-data/balances) updates using the sFOX WebSocket API. [Click here for details](/websocket-api/orders-and-account-data).
{% endhint %}

## Request

### Query Parameters

<table><thead><tr><th width="113.8203125">Name</th><th width="125">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>from</code></strong></td><td>timestamp</td><td>Start date for your query. Results will include transactions that occurred after this date. <strong>Unix timestamp in ms.</strong> Default: utcnow - 24hrs</td></tr><tr><td><strong><code>to</code></strong></td><td>timestamp</td><td>End date for your query. Results will include transactions that occurred before this date. <strong>Unix timestamp in ms.</strong> Default: utcnow</td></tr><tr><td><strong><code>limit</code></strong></td><td>int</td><td>Maximum number of results to be returned by the request. Default: 250. Maximum: 1000</td></tr><tr><td><strong><code>after</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred after (newer) than the specified ID (<code>id</code> from response body).<br><br>Use this parameter when you want to retrieve only new transactions from a previous request.</td></tr><tr><td><strong><code>offset</code></strong></td><td>int</td><td>Pagination parameter. Return results that occurred before (older) than the results from a previous request. <br><br>Specify the number of entries you've already had returned to you to get the next batch. e.g. If you retrieved <code>500</code> results in your previous request and you want the next <code>500</code>, set the offset to <code>501</code>.</td></tr><tr><td><strong><code>types</code></strong></td><td>string</td><td>Filter by transaction type. To filter by more than one type, separate each type with a comma. Possible values: <code>charge</code>, <code>deposit</code>, <code>withdraw</code>, <code>credit</code>, <code>buy</code>, <code>sell</code></td></tr><tr><td><strong><code>pending</code></strong></td><td>boolean</td><td>Specify whether the results should include transactions that are NOT completed (<code>Done</code>). e.g. pending deposits or withdrawals. <strong>Only applicable to</strong> <code>deposit</code> <strong>and</strong> <code>withdraw</code> <code>types</code>. Default: <code>false</code></td></tr></tbody></table>

### Example Requests

{% tabs %}
{% tab title="Shell" %}

```bash
curl -H 'Authorization: Bearer <API_TOKEN>' \ 
https://api.sfox.com/v1/account/transactions?limit=50
```

{% endtab %}

{% tab title="NodeJS" %}

```javascript
const axios = require('axios');

axios({
  method: 'get',
  url: 'https://api.sfox.com/v1/account/transactions',
  headers: {
    'Authorization': 'Bearer <API_KEY>'
  },
  params: {
   limit: 50
  }
}).then(response => {
  console.log(response)
}).catch(err => {
  console.error(err)
});ja
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

data = requests.get(
  "https://api.sfox.com/v1/account/transactions",
  headers={
    "Authorization": "Bearer <API_KEY>",
  }
  params={
   "limit": 50
  }
)
print(data)
```

{% endtab %}
{% endtabs %}

## Response

### Response Body

Response body is an array of objects. Each object represents a transaction and will include the following keys:

<table><thead><tr><th width="183.61764680221557">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>id</code></strong></td><td>sFOX-generated transaction ID. Use for <code>after</code> pagination.</td></tr><tr><td><strong><code>AtxId</code></strong></td><td>Account transaction ID. An sFOX-generated ID specifically for deposit, withdrawal, credit, or charge transactions.</td></tr><tr><td><strong><code>order_id</code></strong></td><td>sFOX-generated ID of the order that this transaction is associated with, if applicable.</td></tr><tr><td><strong><code>client_order_id</code></strong></td><td>The optional ID that you specified when <a href="/pages/-Mkd5fv0VwgWbHGXHO7z"><mark style="color:blue;">placing an order</mark></a></td></tr><tr><td><strong><code>trade_id</code></strong></td><td>sFOX-generated ID of the trade, if applicable.</td></tr><tr><td><strong><code>day</code></strong></td><td>The timestamp of the transaction, in ISO8601 format</td></tr><tr><td><strong><code>action</code></strong></td><td>The action name of this transaction (“Deposit”, “Withdraw”, “Buy”, “Sell”, "Credit", "Charge")</td></tr><tr><td><strong><code>currency</code></strong></td><td>The base currency of the transaction </td></tr><tr><td><strong><code>memo</code></strong></td><td>The optional memo you specified for a withdrawal transaction</td></tr><tr><td><strong><code>amount</code></strong></td><td>The transacted amount of the <code>currency</code></td></tr><tr><td><strong><code>net_proceeds</code></strong></td><td>Net amount after fees</td></tr><tr><td><strong><code>price</code></strong></td><td>Price per unit of the <code>currency</code></td></tr><tr><td><strong><code>fees</code></strong></td><td>Fee paid in terms of the  <code>currency</code></td></tr><tr><td><strong><code>status</code></strong></td><td>The current transaction status</td></tr><tr><td><strong><code>hold_expires</code></strong></td><td>The expiration date of a hold on this transaction, if applicable</td></tr><tr><td><strong><code>tx_hash</code></strong></td><td>The transaction hash, if applicable (applicable to crypto deposits and withdrawals)</td></tr><tr><td><strong><code>algo_name</code></strong></td><td>The algorithm used to execute the transaction, if the transaction is an order</td></tr><tr><td><strong><code>algo_id</code></strong></td><td>The ID associated with the algorithm</td></tr><tr><td><strong><code>account_balance</code></strong></td><td>Your balance of the <code>currency</code> after the transaction</td></tr><tr><td><strong><code>AccountTransferFee</code></strong></td><td>Fee paid in terms of the  <code>currency</code> for deposit or withdrawal transactions</td></tr><tr><td><strong><code>Description</code></strong></td><td>A description of the transaction. For crypto deposits, this is the sender address. For crypto withdrawals this is the destination address</td></tr><tr><td><strong><code>added_by_user_email</code></strong></td><td>The username/email address of the user who initiated this transaction</td></tr><tr><td><strong><code>symbol</code></strong></td><td>The currency pair of the transaction for trades (<code>action</code> = <code>Buy</code> or <code>Sell</code>)</td></tr><tr><td><strong><code>timestamp</code></strong></td><td>The UNIX timestamp of the transaction in milliseconds</td></tr></tbody></table>

### Transaction Statuses

The following table describes the possible Status Codes returned from this request.

{% hint style="info" %}
**These Status Codes are only applicable to deposit and withdrawal transactions.** Other transaction types will always be returned with status = Done
{% endhint %}

<table data-full-width="false"><thead><tr><th width="210.03515625">Status Code</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>Started</code></strong></td><td>Transaction initiated</td></tr><tr><td><strong><code>Approval Required</code></strong></td><td><ul><li><strong>Deposits:</strong> N/A</li><li><strong>Withdrawals:</strong> Approval is required before the transaction will be initiated</li></ul></td></tr><tr><td><strong><code>Processing Automatic withdrawal</code></strong></td><td><ul><li><strong>Deposits:</strong> N/A</li><li><strong>Withdrawals:</strong> Transaction is being broadcast</li></ul></td></tr><tr><td><strong><code>Confirmed</code></strong></td><td><ul><li><strong>Deposits:</strong> Transaction has been received. It is not available yet but will be shortly</li><li><strong>Withdrawals:</strong> Transaction has been approved. It has not been sent yet but will be shortly</li></ul></td></tr><tr><td><strong><code>Done</code></strong></td><td><ul><li><strong>Deposits:</strong> Transaction is complete and available to you</li><li><strong>Withdrawals:</strong> Transaction is complete</li></ul></td></tr><tr><td><strong><code>Canceled</code></strong></td><td>Transaction has been canceled</td></tr><tr><td><strong><code>Admin Hold, Pending Further Review</code></strong></td><td>Transaction was flagged for review. Contact support@sfox.com for more information</td></tr></tbody></table>

### Responses

<details>

<summary><mark style="color:green;">200</mark></summary>

```json
[
    {
        "id": 68029980111539,
        "AtxId": null,
        "order_id": "80000120662565",
        "client_order_id": "2013acd0-ea78-46c3-b2ac-ed4546f13182",
        "trade_id": "8848300113216138",
        "day": "2024-03-28T15:47:41.000Z",
        "action": "Sell",
        "currency": "usd",
        "memo": "",
        "amount": 71.26350189,
        "net_proceeds": 71.26350189,
        "price": 71299.1514729,
        "fees": 0.03564958,
        "status": "done",
        "hold_expires": "",
        "tx_hash": "",
        "algo_name": "Limit",
        "algo_id": "201",
        "account_balance": 3702.72950349,
        "AccountTransferFee": 0,
        "Description": "",
        "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000",
        "added_by_user_email": "example@sfox.com",
        "symbol": "btc/usd",
        "IdempotencyId": null,
        "timestamp": 1711640861000
    },
    {
        "id": 68029980111538,
        "AtxId": null,
        "order_id": "80000120662565",
        "client_order_id": "2013acd0-ea78-46c3-b2ac-ed4546f13182",
        "trade_id": "8848300113216138",
        "day": "2024-03-28T15:47:41.000Z",
        "action": "Sell",
        "currency": "btc",
        "memo": "",
        "amount": -0.001,
        "net_proceeds": -0.001,
        "price": 71299.1514729,
        "fees": 0.03564958,
        "status": "done",
        "hold_expires": "",
        "tx_hash": "",
        "algo_name": "Limit",
        "algo_id": "201",
        "account_balance": 10.00216189,
        "AccountTransferFee": 0,
        "Description": "",
        "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000",
        "added_by_user_email": "example@sfox.com",
        "symbol": "btc/usd",
        "IdempotencyId": null,
        "timestamp": 1711640861000
    },
    {
        "id": 68029980111501,
        "AtxId": 1670509823872833,
        "order_id": "",
        "client_order_id": "",
        "trade_id": "",
        "day": "2024-03-28T16:03:54.000Z",
        "action": "Credit",
        "currency": "dot",
        "memo": "",
        "amount": 0.0564958,
        "net_proceeds": 0.0564958,
        "price": 9.60559235,
        "fees": 0,
        "status": "done",
        "hold_expires": "",
        "tx_hash": "",
        "algo_name": "",
        "algo_id": "",
        "account_balance": 120.70980446,
        "AccountTransferFee": 0,
        "Description": "Staking Reward",
        "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000",
        "added_by_user_email": "example@sfox.com",
        "symbol": null,
        "IdempotencyId": null,
        "timestamp": 1711641834000
    }
]
```

</details>


# Introduction

sFOX's WebSocket API offers a suite of WebSocket feeds, which enable you to stream market data such as [order books](/websocket-api/market-data/order-book) and [trades](/websocket-api/market-data/trades) as well as and account data including [orders](/websocket-api/orders-and-account-data/orders) and [balances](/websocket-api/orders-and-account-data/balances) in real-time.

{% hint style="info" %}
Utilizing WebSockets has a number of advantages including receiving updates in real-time, reducing latency, and reducing data transfer loads.
{% endhint %}


# Connecting

Connecting to the WebSocket API

Connecting to the sFOX WebSocket API gives you access to real-time market and/or account data.

## WebSocket API URLs

Use the following URLs to connect to sFOX WebSocket APIs.

<table><thead><tr><th width="178">Environment</th><th>Endpoint</th></tr></thead><tbody><tr><td><strong>Production</strong></td><td><strong><code>wss://ws.sfox.com/ws</code></strong></td></tr><tr><td><strong>Sandbox</strong></td><td><strong><code>wss://ws.staging.sfox.com/ws</code></strong><br><br><a href="mailto:support@sfox.com"><em>Contact support</em></a> <em>to access the sandbox environment.</em></td></tr></tbody></table>

## **Example Code**

Examples of establishing a WebSocket connection are shown below.

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws');

const ws = new WebSocket('wss://ws.sfox.com/ws');

// don't forget to subscribe (see below)
ws.on('message', function(data) {
    // Do something with data
    console.log(data);
});
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio

import websockets

async def main(uri):
    async with websockets.connect(uri) as ws:
        # don't forget to subscribe (see below)
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endtab %}
{% endtabs %}


# Rate Limits

Connecting to the WebSocket API

The WebSocket API rate limits requests and connections by IP address.&#x20;

If you exceed a rate limit, an error is thrown and your requests will be blocked for 2 minutes.

Rate limits for the WebSocket API are as follows:

<table><thead><tr><th width="147">Type</th><th>Limit</th></tr></thead><tbody><tr><td><strong>Connections</strong></td><td><strong>10 active connections</strong> per IP address.</td></tr><tr><td><strong>Requests</strong></td><td><strong>40 requests per 1 minute</strong> per IP address. Requests are counted, in total, across your active connections.</td></tr></tbody></table>

## Best Practices

To avoid rate limiting, sFOX recommends following these best practices:

#### 1. Consolidate feeds per [subscribe/unsubscribe request](/websocket-api/subscribing-and-unsubscribing)

Subscribe/unsubscribe to multiple WebSocket feeds in a single request rather than sending subscribe requests per WebSocket feed.

<pre class="language-json" data-overflow="wrap"><code class="lang-json"><strong>// Request -> Subscribe to feeds
</strong>{
    "type": "subscribe", 
    "feeds": ["&#x3C;feed 1>", "&#x3C;feed 2>", ...] //Subscribe to N feeds in 1 request
}
</code></pre>

For example, if you want to subscribe to both the [open orders](/websocket-api/orders-and-account-data/orders) and [balances](/websocket-api/orders-and-account-data/balances) feeds:

<pre class="language-json"><code class="lang-json"><strong>// Request -> Subscribe to open orders and balances feeds
</strong>{
    "type": "subscribe", 
    "feeds": ["private.user.open-orders", "private.user.balances"]
}
</code></pre>

#### 2. Consolidate WebSocket consumption by [connection](/websocket-api/connecting)

Consuming the same data across >1 connection will result in duplicate requests. For example, if you want consume the BTC/USD order book, do so in a single connection.

{% hint style="info" %}
Please note: To ensure optimal performance, sFOX recommends using a separate WebSocket connection for each feed "type" you subscribe to.&#x20;

For example, consume [market data](/websocket-api/market-data) and [orders/account data](/websocket-api/orders-and-account-data) in separate connections.

This segregation ensures that time-sensitive updates, such as [balances](/websocket-api/orders-and-account-data/balances) or [open-orders](/websocket-api/orders-and-account-data/orders) messages, are not impacted by high-frequency feeds like [order books](/websocket-api/market-data/order-book).
{% endhint %}


# Authentication

Authenticating to the WebSocket API

You must authenticate yourself when subscribing to any of the sFOX WebSocket feeds.

{% hint style="info" %}
All WebSocket feeds require authentication.
{% endhint %}

Authentication commands should be JSON with the following properties:

<table><thead><tr><th width="129">Property</th><th width="100">Type</th><th>Command</th></tr></thead><tbody><tr><td><strong><code>type</code></strong></td><td>string</td><td><code>"authenticate"</code></td></tr><tr><td><strong><code>apiKey</code></strong></td><td>string</td><td><code>"&#x3C;YOUR-API-KEY>"</code></td></tr></tbody></table>

### Authentication Message

To authenticate yourself to the WebSocket API, you must send an `authenticate` message to the server with an API key for your account. This message is mandatory as all WebSocket feeds require authentication.

#### Authenticate Message

```json
// Request -> Authenticate
{
    "type": "authenticate", 
    "apiKey": "<REPLACE WITH YOUR API KEY>"
}
```

Once a `authenticate` message is received the server responds with an `authenticate` message that specifies whether authentication succeeded or failed.

```json
// Response -> Authenticate
{
    "type": "success",
    "sequence": 1,
    "timestamp": 1727391983733911769,
    "payload": {
        "action": "authenticate"
    },
    "action": "authenticate"
}
```

### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const authMessage = {
   type: 'authenticate',
   apiKey: '<API_KEY>',
}
ws.send(JSON.stringify(authMessage))
```

{% endtab %}

{% tab title="Python" %}

```python
auth_message={
  "type": "authenticate",
  "apiKey": "<API KEY>"
}

await ws.send(json_dump(auth_message))
```

{% endtab %}
{% endtabs %}


# Subscribing & Unsubscribing

Subscribing or unsubscribing to WebSocket feeds

Once [connected](/websocket-api/connecting) to the WebSocket API you can subscribe to various feeds using the `subscribe` or `unsubscribe` commands.&#x20;

These commands should be JSON with the following properties:

<table><thead><tr><th width="116">Property</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Command you are sending to the WebSocket (<code>subscribe</code> or <code>unsubscribe</code>).</td></tr><tr><td><code>feeds</code></td><td>string[]</td><td>List of the feeds that should be subscribed/unsubscribed to/from, respectively.</td></tr></tbody></table>

### Subscribing

To begin receiving feed messages, you must send a `subscribe` message to the server indicating which feeds to receive. This message is mandatory—you may be disconnected if no `subscribe` has been received.

{% hint style="info" %}
To ensure optimal performance, we suggest maintaining a separate Websocket connection for market data subscriptions ([orderbooks](/websocket-api/market-data/order-book), [tickers](/websocket-api/market-data/ticker), [trades](/websocket-api/market-data/trades)) to ensure high-frequency market data doesn't impact the delivery of your time-sensitive account level updates, such as [balances](/websocket-api/orders-and-account-data/balances) or [open-orders](/websocket-api/orders-and-account-data/orders) messages.
{% endhint %}

#### Subscribe Message

```json
// Request -> Subscribe to feed(s)
{
    "type": "subscribe", 
    "feeds": ["<feed 1>", "<feed 2>", ...]
}
```

Once a `subscribe` message is received the server responds with a `subscribe` message that lists all feeds you are subscribed to. Subsequent subscribe messages add to the list of subscriptions.

```json
// Response -> Subscribe request
{
    "type": "success",
    "sequence": 2,
    "timestamp": 1727392002151355776,
    "payload": {
        "action": "subscribe",
        "feeds": [
            "<feed 1>",
            "<feed 2>",
            ...
        ]
    },
    "action": "subscribe"
}
```

#### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const subscribeMsg = {
  type: 'subscribe',
  feeds: ['ticker.sfox.btcusd']
}
ws.send(JSON.stringify(subscribeMsg));
```

{% endtab %}

{% tab title="Python" %}

```python
subscribe_msg = {
    "type": "subscribe",
    "feeds": ["ticker.sfox.btcusd"],
}

await ws.send(json.dumps(subscribe_msg))
```

{% endtab %}
{% endtabs %}

### Unsubscribing

To unsubscribe from a feed or feeds, send an `unsubscribe` message. The structure is equivalent to `subscribe` messages.

#### Unsubscribe Message

```json
// Request -> Unsubscribe to feed(s)
{
    "type": "unsubscribe", 
    "feeds": ["<feed 1>", "<feed 2>", ...]
}
```

Once a `unsubscribe` message is received the server responds with an `unsubscribe` message that lists all feeds you are unsubscribed from.

```json
// Response -> Subscribe request
{
    "type": "success",
    "sequence": 4,
    "timestamp": 1727394717752870042,
    "payload": {
        "action": "unsubscribe",
        "feeds": [
            "<feed 1>",
            "<feed 2>",
            ...
        ]
    },
    "action": "unsubscribe"
}
```

#### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const unsubscribeMsg = {
  type: 'unsubscribe',
  feeds: ['ticker.sfox.btcusd']
}
ws.send(JSON.stringify(unsubscribeMsg))
```

{% endtab %}

{% tab title="Python" %}

```python
unsubscribe_msg = {
    "type": "unsubscribe",
    "feeds": ["ticker.sfox.btcusd"],
}

await ws.send(json.dumps(unsubscribe_msg))
```

{% endtab %}
{% endtabs %}


# Message Format

WebSocket API message format

Messages received from the WebSocket API will be JSON objects with the following similar format:

<table><thead><tr><th width="162">Property</th><th width="118">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>sequence</code></strong></td><td>int</td><td>The sequence number that the message was sent in</td></tr><tr><td><strong><code>recipient</code></strong></td><td>string</td><td>The corresponding WebSocket feed that the message was sent to</td></tr><tr><td><strong><code>timestamp</code></strong></td><td>int</td><td>The UNIX timestamp (in nanoseconds)</td></tr><tr><td><strong><code>payload</code></strong></td><td>JSON</td><td>The payload parameter will be a JSON string that contains then data</td></tr></tbody></table>

{% hint style="info" %}
Please note that the `sequence` number sent by the WebSocket is not guaranteed to be in ascending order. If you detect any gaps or incorrect ordering you should reconnect.
{% endhint %}

**Example Message**

```json
{
  "sequence": 10,
  "recipient": "private.user.balances",
  "timestamp": 1649899310281716289,
  "payload": [{
    "currency": "aave",
    "balance": "0.17572419",
    "available": "0.17572419",
    "held": "0",
    "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000"
  }, {
    "currency": "ada",
    "balance": "42.32365721",
    "available": "42.32365721",
    "held": "0",
    "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000"
  }, {
    "currency": "atom",
    "balance": "0.40485184",
    "available": "0.40485184",
    "held": "0",
    "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000"
  }, {
    "currency": "avax",
    "balance": "0",
    "available": "0",
    "held": "0",
    "wallet_display_id": "5a3f1b1c-719d-11e9-b0be-0ea0e44d1000"
  }]
}
```


# Market Data

Receive real-time streaming market data from the sFOX WebSocket API

### Feeds

The sFOX WebSocket API offers the following Market Data feeds:

{% hint style="warning" %}
**Authentication required.** Please refer to the [WebSocket Authentication page here for more details.](/websocket-api/authentication)
{% endhint %}

<table data-column-title-hidden data-view="cards"><thead><tr><th>Feed</th><th>Description</th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Order Book</strong></td><td>Real-time streaming order book for a specified currency pair.</td><td><a href="/pages/4CQgv3BxIh9W9BbKsZnF">/pages/4CQgv3BxIh9W9BbKsZnF</a></td></tr><tr><td><strong>Trades</strong></td><td>Real-time tick data feed of all trades executed on SFOX’s supported liquidity providers</td><td><a href="/pages/OXAMdIJf07DyIT68P8IM">/pages/OXAMdIJf07DyIT68P8IM</a></td></tr><tr><td><strong>Ticker</strong></td><td>Aggregated 24-hour OHLCV data from all supported exchanges and the last price before each update</td><td><a href="/pages/NbNxoPL3jnDf6CiEawnl">/pages/NbNxoPL3jnDf6CiEawnl</a></td></tr></tbody></table>


# Order Book

Real-time streaming order book data

Real-time order books for a specified currency pair and order book variation.

### **Subscribing**

<table data-header-hidden><thead><tr><th width="100">Feed</th><th>Example</th></tr></thead><tbody><tr><td>Feed</td><td><strong><code>orderbook.&#x3C;order_book_type>.&#x3C;basequote></code></strong></td></tr><tr><td>Example</td><td><strong><code>orderbook.net.btcusd</code></strong></td></tr></tbody></table>

```json
// Request -> order book feed
{
    "type": "subscribe", 
    "feeds": ["orderbook.net.btcusd"]
}
```

### Order Book Types

sFOX provides the following order book variations:

<table><thead><tr><th width="100">Order Book</th><th width="430">Description</th><th>Example</th></tr></thead><tbody><tr><td><strong><code>net</code></strong></td><td>Fee-adjusted order book prioritizing the best net prices.</td><td><strong><code>orderbook.net.ethbtc</code></strong></td></tr><tr><td><strong><code>sfox</code></strong></td><td>Unadjusted order book prioritizing the best raw prices. <strong>Please note:</strong> trades on the <code>sfox</code> order book are assessed an additional 10bps fee.</td><td><strong><code>orderbook.sfox.btcusd</code></strong></td></tr></tbody></table>

### **Order Book Message**

{% hint style="info" %}
Order book messages are full order book snapshots for the given currency pair. sFOX does not support sending changes at this time.
{% endhint %}

#### Order Book Object

<table><thead><tr><th width="206">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>bids</code></strong></td><td><p>An array of the bids available in this order book. </p><p>Each bid is a price, quantity, and liquidity source.</p></td></tr><tr><td><strong><code>asks</code></strong></td><td><p>An array of the asks available in this order book. </p><p>Each ask is a price, quantity, and liquidity source.</p></td></tr><tr><td><strong><code>market_making</code></strong></td><td>The best bids and offers of the available destinations for maker orders placed on this pair.</td></tr><tr><td><strong><code>pair</code></strong></td><td>The currency pair of this order book.</td></tr><tr><td><strong><code>lastupdated</code></strong></td><td>The UNIX timestamp this order book was last updated.</td></tr><tr><td><strong><code>lastpublished</code></strong></td><td>The UNIX timestamp this order book was last published.</td></tr></tbody></table>

<details>

<summary>Order Book Message</summary>

<pre class="language-json"><code class="lang-json"><strong>// Order book message
</strong><strong>{
</strong>  "sequence": 18,
  "recipient": "orderbook.net.btcusd",
  "timestamp": 1649900198079450163,
  "payload": {
    "bids": [
      [41368.2, 0.3, "b2c2"],
      [41367.742812, 0.001963, "binance"],
      [41367.292857, 0.006878, "binance"],
      [41365.91428571, 0.7, "b2c2"],
      [41362.1, 2, "b2c2"],
      [41361.453441, 0.014505, "binance"],
      [41360.143572, 0.00869, "binance"],
      [41359.8561017, 0.2, "otc17"],
      [41358.613725, 1.20871, "otc19"],
      [41358.103776, 0.04, "binance"],
      [41358.073779, 0.028977, "binance"],
      [41357.873799, 0.012086, "binance"],
      [41357.113875, 1.20871, "otc19"],
      [41356.573929, 0.024173, "binance"],
      [41355.903996, 1.81307, "otc19"],
      [41355.8, 0.5, "otc23"],
      [41355.194067, 2.41733, "otc19"],
      [41353.994187, 0.017737, "binance"],
      [41353.974189, 0.19, "binance"],
      [41352.884298, 6.04332, "otc19"],
      [41352.4, 0.5, "otc23"],
      [41350.024584, 0.145041, "binance"],
      [41348.975, 4, "otc23"],
      [41348.96469, 0.003885, "binance"],
      [41348.17142857, 7, "b2c2"],
      [41346.76491, 0.05, "binance"],
      [41345.5071109, 1, "otc17"],
      [41344.76511, 8.46104, "otc19"],
      [41344.56513, 0.003885, "binance"],
      [41343.915195, 0.146232, "binance"],
      [41341.675419, 0.475, "binance"],
      [41340.77927, 0.39449605, "bitstamp"],
      [41340.615525, 0.035367, "binance"],
      [41339.06013, 0.00723432, "bitstamp"],
      [41338.770275, 0.15077458, "bitstamp"],
      [41338.525734, 12.08665, "otc19"],
      [41338.26053, 1.03596356, "bitstamp"],
      [41335.4205242, 5, "otc17"],
      [41335.272025, 0.12036964, "bitstamp"],
      [41335.06213, 0.13449116, "bitstamp"],
      [41333.60286, 0.12056821, "bitstamp"],
      [41333.516235, 0.241751, "binance"],
      [41333.4, 5, "otc23"],
      [41333.0256, 0.00331432, "kraken"],
      [41332.60336, 0.12087285, "bitstamp"],
      [41331.82375, 0.42, "bitstamp"],
      [41330.386548, 0.012, "binance"],
      [41330.376549, 0.142368, "binance"],
      [41330.306556, 12.08665, "otc19"],
      [41330.114605, 0.16802493, "bitstamp"],
      [41330.0286, 0.60222489, "kraken"],
      [41330.026584, 0.1, "binance"],
      [41328.776709, 0.036344, "binance"],
      [41328.63, 0.70524095, "kraken"],
      [41327.495915, 0.42, "bitstamp"],
      [41327.3313, 0.42197361, "kraken"],
      [41327.276025, 0.12088751, "bitstamp"],
      [41326.2324, 0.1, "kraken"],
      [41326.1325, 0.54830808, "kraken"],
      [41326.0326, 0.24161579, "kraken"],
      [41325.976989, 0.01, "binance"],
      [41325.96699, 0.1716, "binance"],
      [41325.3333, 0.12087016, "kraken"],
      [41325.257035, 1, "bitstamp"],
      [41324.68395, 0.0023, "gemini"],
      [41324.56713, 0.055, "binance"],
      [41324.553564, 1.27, "market1"],
      [41324.4342, 0.64773203, "kraken"],
      [41324.047182, 0.011, "binance"],
      [41324.037183, 0.1, "binance"],
      [41324.027184, 1, "binance"],
      [41323.84774, 0.1571347, "bitstamp"],
      [41323.5351, 3.62613745, "kraken"],
      [41323.34799, 0.42, "bitstamp"],
      [41322.497337, 0.09679, "binance"],
      [41322.484392, 0.01, "market1"],
      [41322.34849, 0.05, "bitstamp"],
      [41322.207366, 0.095, "binance"],
      [41322.157371, 1.007778, "binance"],
      [41321.14909, 0.03705224, "bitstamp"],
      [41321.1073014, 25, "otc17"],
      [41320.2384, 0.67345556, "kraken"],
      [41319.927594, 12.0873, "otc19"],
      [41319.8388, 0.0001, "kraken"],
      [41319.745488, 0.04009981, "market1"],
      [41319.735492, 0.0421593, "market1"],
      [41319.41922, 0.04865, "gemini"],
      [41319.1395, 0.003149, "kraken"],
      [41318.9397, 0.25, "kraken"],
      [41318.9397, 0.635, "gemini"],
      [41318.69032, 0.19340004, "bitstamp"],
      [41318.356044, 1.25, "market1"],
      [41318.31033, 0.02417329, "gemini"],
      [41317.5411, 0.6040736, "kraken"],
      [41317.45094, 0.42, "bitstamp"],
      [41316.52212, 0.0686, "market7"],
      [41315.8, 15, "b2c2"],
      [41314.898097, 3.583457, "binance"],
      [41314.888098, 0.095, "binance"],
      [41314.644, 0.12090144, "kraken"],
      [41314.46814, 0.133897, "binance"],
      [41314.2444, 0.01, "gemini"],
      [41314.16448, 0.42, "gemini"],
      [41313.37298, 0.1941, "bitstamp"],
      [41313.328254, 0.280266, "binance"],
      [41312.5461, 6.04332265, "kraken"],
      [41312.003665, 0.42, "bitstamp"],
      [41311.81683, 0.1274, "market7"],
      [41311.688418, 12.0873, "otc19"],
      [41311.65384, 0.0365641, "bitstamp"],
      [41311.4, 25, "b2c2"],
      [41311.324005, 0.61, "bitstamp"],
      [41311.0476, 0.37887065, "kraken"],
      [41310.7479, 0.2995721, "kraken"],
      [41310.744295, 0.05, "bitstamp"],
      [41310.648, 1, "gemini"],
      [41309.55909, 0.00121092, "gemini"],
      [41309.348652, 0.095, "binance"],
      [41309.21943, 0.04834911, "gemini"],
      [41309.15949, 0.60812, "gemini"]
    ],
    "asks": [
      [41364.5, 0.5, "otc23"],
      [41367.9, 0.5, "otc23"],
      [41371.325, 4, "otc23"],
      [41373.322712, 0.03838193, "market1"],
      [41373.332716, 0.01, "market1"],
      [41374.163048, 0.03712564, "market1"],
      [41374.173052, 0.1, "market1"],
      [41375.1855912, 0.2, "otc17"],
      [41375.39354, 0.1, "market1"],
      [41376.423952, 0.2, "market1"],
      [41377.417328, 1.2087, "otc19"],
      [41377.464368, 0.01, "market1"],
      [41378.317418, 1.20871, "otc19"],
      [41379.417528, 1.81307, "otc19"],
      [41379.427529, 0.01103, "binance"],
      [41379.43753, 0.006888, "binance"],
      [41379.535196, 0.01, "market1"],
      [41380.367623, 0.02579, "binance"],
      [41380.555604, 0.26, "market1"],
      [41381.03769, 0.024176, "binance"],
      [41381.43773, 0.001568, "binance"],
      [41381.857772, 2.41742, "otc19"],
      [41381.897776, 0.012086, "binance"],
      [41382.886536, 0.02943697, "market1"],
      [41384.2189484, 5, "otc17"],
      [41385.648151, 0.04, "binance"],
      [41385.658152, 0.035678, "binance"],
      [41385.728159, 6.04332, "otc19"],
      [41385.8, 0.3, "b2c2"],
      [41386.358222, 0.00869, "binance"],
      [41386.9, 5, "otc23"],
      [41387.2238233, 1, "otc17"],
      [41387.478372, 0.7, "market1"],
      [41387.858372, 0.145044, "binance"],
      [41388.08571429, 0.7, "b2c2"],
      [41388.872938, 0.2047, "market11"],
      [41388.968483, 0.095, "binance"],
      [41388.99898, 0.99, "market1"],
      [41389.1385, 0.05, "binance"],
      [41390.0494, 1.25, "market1"],
      [41390.308617, 0.095, "binance"],
      [41390.89974, 0.13, "market1"],
      [41390.933556, 0.0072, "market11"],
      [41391.188705, 0.000003, "binance"],
      [41391.198706, 0.00077, "binance"],
      [41391.55, 0.07250918, "bitfinex"],
      [41391.673778, 0.039, "market11"],
      [41391.898776, 8.46065, "otc19"],
      [41392.158802, 0.24179, "binance"],
      [41392.2, 2, "b2c2"],
      [41392.708857, 0.018085, "binance"],
      [41394.489035, 0.000545, "binance"],
      [41395.074798, 0.0112, "market11"],
      [41395.129099, 0.0081, "binance"],
      [41395.21484, 0.255, "market11"],
      [41395.63915, 0.001944, "binance"],
      [41395.799166, 0.001572, "binance"],
      [41396.25188, 1.25, "market1"],
      [41396.552, 0.5, "bitfinex"],
      [41397.749361, 0.036018, "binance"],
      [41398.5528, 0.19739821, "bitfinex"],
      [41398.93948, 0.1716, "binance"],
      [41399.5532, 0.00034227, "bitfinex"],
      [41400.089595, 12.08665, "otc19"],
      [41400.5536, 0.55271771, "bitfinex"],
      [41401.233872, 1, "market1"],
      [41401.31667, 0.2421, "market11"],
      [41401.99063, 0.0574, "market7"],
      [41402.180745, 0.12087124, "bitstamp"],
      [41402.5544, 0.61221032, "bitfinex"],
      [41402.919878, 0.000635, "binance"],
      [41403.347279, 0.5076, "market11"],
      [41403.5548, 0.07973682, "bitfinex"],
      [41403.81742, 0.51, "market11"],
      [41404.5552, 0.1662, "bitfinex"],
      [41404.962135, 0.23964408, "bitstamp"],
      [41404.97214, 0.12087406, "bitstamp"],
      [41405.100096, 0.000502, "binance"],
      [41405.5556, 0.38084686, "bitfinex"],
      [41406.02857143, 7, "b2c2"],
      [41406.28492, 0.0131, "market7"],
      [41406.482895, 0.15073263, "bitstamp"],
      [41406.556, 0.03624, "bitfinex"],
      [41406.89553, 0.1386, "market7"],
      [41407.488521, 0.4988, "market11"],
      [41407.74036, 0.1, "binance"],
      [41407.770363, 0.099338, "binance"],
      [41408.310417, 12.08665, "otc19"],
      [41408.5568, 0.060436, "bitfinex"],
      [41409.5572, 0.009672, "bitfinex"],
      [41409.8685, 0.01005354, "gemini"],
      [41410.330619, 0.012075, "binance"],
      [41410.464885, 0.42, "bitstamp"],
      [41410.5576, 0.0011, "bitfinex"],
      [41411.11521, 0.00122, "bitstamp"],
      [41411.125215, 0.0144676, "bitstamp"],
      [41411.1366896, 25, "otc17"],
      [41411.145225, 0.05, "bitstamp"],
      [41411.37, 0.0481, "market7"],
      [41411.445375, 0.1571276, "bitstamp"],
      [41411.558, 1.047576, "bitfinex"],
      [41411.629763, 0.4912, "market11"],
      [41412.5584, 0.39479641, "bitfinex"],
      [41413.15178, 0.0128, "market7"],
      [41413.206255, 0.25653181, "bitstamp"],
      [41413.5588, 0.8926, "bitfinex"],
      [41414.1728, 0.2814, "market7"],
      [41414.346825, 0.03670669, "bitstamp"],
      [41414.391025, 0.001, "binance"],
      [41414.5592, 0.20304, "bitfinex"],
      [41414.606955, 0.42, "bitstamp"],
      [41414.83707, 0.19339577, "bitstamp"],
      [41415.5596, 0.0121, "bitfinex"],
      [41415.771005, 0.4851, "market11"],
      [41415.8745, 2.0260228, "kraken"],
      [41416.25488, 0.2394, "market7"],
      [41416.2749, 3.62582685, "kraken"],
      [41416.311167, 0.0605, "market11"],
      [41416.53516, 0.291, "gemini"],
      [41416.54124, 12.08665, "otc19"]
    ],
    "market_making": {
      "bids": [
        [41345.224109, 1.27, "market1"],
        [41361.46, 0.39449605, "bitstamp"],
        [41366.05, 0.0023, "gemini"],
        [41371.88, 0.001963, "binance"],
        [41374, 0.69001372, "bitfinex"],
        [41374.4, 0.00331432, "kraken"]
      ],
      "asks": [
        [41381.49, 0.12087124, "bitstamp"],
        [41375.29, 0.01103, "binance"],
        [41374.5, 2.0260228, "kraken"],
        [41368.5, 0.01005354, "gemini"],
        [41352.644322, 0.03838193, "market1"]
      ]
    },
    "pair": "btcusd",
    "lastupdated": 1649900198016,
    "lastpublished": 1649900198017
  }
}
</code></pre>

</details>

### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws')

const ws = new WebSocket('wss://ws.sfox.com/ws')

ws.on('message', function(data) {
    console.log(data);
});

ws.on('open', function() {
  const subscribeMsg = {
    type: 'subscribe',
    feeds: ['orderbook.sfox.ethbtc']
  }
  ws.send(JSON.stringify(subscribeMsg));
});
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import json

import websockets


async def main(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "type": "subscribe",
            "feeds": [
                "orderbook.sfox.ethbtc",
            ],
        }))
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endtab %}
{% endtabs %}


# Trades

Real-time streaming tick data of publicly executed trades

Real-time tick data feed of any trade executed across all of sFOX’s integrated liquidity providers. Please note that this feed does not only represent trades executed on sFOX.

### **Subscribing**

<table data-header-hidden><thead><tr><th width="100">Feed</th><th>Example</th></tr></thead><tbody><tr><td>Feed</td><td><strong><code>trades.sfox.&#x3C;basequote></code></strong></td></tr><tr><td>Example</td><td><strong><code>trades.sfox.btcusd</code></strong></td></tr></tbody></table>

```json
// Request -> orders feed
{
    "type": "subscribe", 
    "feeds": ["trades.sfox.btcusd"]
}
```

### **Trades Message**

#### Trades Object

<table><thead><tr><th width="100">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>buyOrderId</code></strong></td><td>Order ID of the buy trade</td></tr><tr><td><strong><code>sellOrderId</code></strong></td><td>Order ID of the sell trade</td></tr><tr><td><strong><code>pair</code></strong></td><td>The currency pair of this trade</td></tr><tr><td><strong><code>price</code></strong></td><td>Price of this trade</td></tr><tr><td><strong><code>quantity</code></strong></td><td>Quantity traded</td></tr><tr><td><strong><code>side</code></strong></td><td>Side taken buy or sell</td></tr><tr><td><strong><code>exchange</code></strong></td><td>Location of the trade</td></tr><tr><td><strong><code>exchange_id</code></strong></td><td>ID of the trade location</td></tr><tr><td><strong><code>timestamp</code></strong></td><td>Time of the trade</td></tr></tbody></table>

#### Trades Message

```json
// Trades feed message
{
  "sequence": 24,
  "recipient": "trades.sfox.btcusd",
  "timestamp": 1649901441593380244,
  "payload": {
    "id": "1062696823",
    "quantity": "0.005",
    "price": "41492",
    "exchange": "bitfinex",
    "exchange_id": 2,
    "side": "buy",
    "pair": "btcusd",
    "pair_id": 1,
    "timestamp": "2022-04-14T01:57:21.521999872Z",
    "timeStamp": "2022-04-14T01:57:21.521",
    "buyOrderId": "",
    "sellOrderId": "",
    "is_decimal": true
  }
}
```

### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws')

const ws = new WebSocket('wss://ws.sfox.com/ws')

ws.on('message', function(data) {
    console.log(data);
});

ws.on('open', function() {
  const subscribeMsg = {
    type: 'subscribe',
    feeds: ['trades.sfox.btcusd']
  }
  ws.send(JSON.stringify(subscribeMsg));
});
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import json

import websockets


async def main(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "type": "subscribe",
            "feeds": [
                "trades.sfox.btcusd",
            ],
        }))
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endtab %}
{% endtabs %}


# Ticker

Real-time streaming day OHLCV data and last trade

Receive aggregated 24-hour OHLCV data from all supported exchanges and the last price before each update every 3 seconds. Subscriptions to the ticker feed will receive real-time trades that occur on any of the exchanges that are active on the sFOX platform.

### **Subscribing**

<table data-header-hidden><thead><tr><th width="100">Feed</th><th>Example</th></tr></thead><tbody><tr><td>Feed</td><td><strong><code>ticker.sfox.&#x3C;basequote></code></strong></td></tr><tr><td>Example</td><td><strong><code>ticker.sfox.btcusd</code></strong></td></tr></tbody></table>

```json
// Request -> ticker feed
{
    "type": "subscribe", 
    "feeds": ["ticker.sfox.btcusd"]
}
```

### **Ticker Message**

#### Ticker Object

<table><thead><tr><th width="178">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>amount</code></strong></td><td>Quantity of the most recent trade on this pair</td></tr><tr><td><strong><code>exchange</code></strong></td><td>Location of the most recent trade on this pair</td></tr><tr><td><strong><code>last</code></strong></td><td>Price of the most recent trade on this pair</td></tr><tr><td><strong><code>high</code></strong></td><td>High price since 00:00:00 GMT</td></tr><tr><td><strong><code>low</code></strong></td><td>Low price since 00:00:00 GMT</td></tr><tr><td><strong><code>open</code></strong></td><td>Open price at 00:00:00 GMT</td></tr><tr><td><strong><code>pair</code></strong></td><td>Currency pair</td></tr><tr><td><strong><code>source</code></strong></td><td>Data source</td></tr><tr><td><strong><code>timestamp</code></strong></td><td>Time of the trade</td></tr><tr><td><strong><code>volume</code></strong></td><td>Volume traded since 00:00:00 GMT (base currency)</td></tr><tr><td><strong><code>vwap</code></strong></td><td>Volume-weighted average price since 00:00:00 GMT</td></tr></tbody></table>

#### Ticker Message

```json
// Ticker feed message
{
  "sequence": 4,
  "recipient": "ticker.sfox.btcusd",
  "timestamp": 1649901842979345289,
  "payload": {
    "amount": 0.00005737,
    "exchange": "coinbase",
    "high": 41512.43,
    "last": 41420.58,
    "low": 41058.82,
    "open": 41141.31,
    "pair": "btcusd",
    "route": "Smart",
    "source": "ticker-info",
    "timestamp": "2022-04-14T02:04:02.481Z",
    "volume": 1387.77211046,
    "vwap": 41283.96339697249
  }
}
```

### Example Code & Ticker Message

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws')

const ws = new WebSocket('wss://ws.sfox.com/ws')

ws.on('message', function(data) {
    console.log(data);
});

ws.on('open', function() {
  const subscribeMsg = {
    type: 'subscribe',
    feeds: ['ticker.sfox.btcusd']
  }
  ws.send(JSON.stringify(subscribeMsg));
});
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import json

import websockets


async def main(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "type": "subscribe",
            "feeds": [
                "ticker.sfox.btcusd",
            ],
        }))
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endtab %}
{% endtabs %}


# Order Book Delta WebSocket API

Pre-release note: The delta feed and this documentation are subject to change before launch.

## Overview

The Order Book Delta feed provides real-time incremental updates for a specified currency pair. Use the first snapshot message as the authoritative starting state, then apply each sequential update message to maintain a synchronized local order book.

This feed uses the same WebSocket connection and subscription model as the [existing Order Book feed](https://docs.sfox.com/websocket-api/market-data/order-book)\*. The existing feed publishes full snapshots; the delta feed publishes both snapshot and update messages, with update messages containing only the levels that have changed.

## Subscribe

Subscribe using the feed name orderbook.delta.\<pair>, where \<pair> is the lowercase currency pair.

```
{
  "type": "subscribe",
  "feeds": ["orderbook.delta.btcusd"]
}
```

## Message format

| pair           | string  | Currency pair for the order book, for example btcusd.                  |
| -------------- | ------- | ---------------------------------------------------------------------- |
| type           | string  | Message type: snapshot or update.                                      |
| bids           | array   | Bid levels. Each level is \[price, quantity, liquidity\_source].       |
| asks           | array   | Ask levels. Each level is \[price, quantity, liquidity\_source].       |
| lu             | integer | UNIX timestamp in milliseconds when the order book was last updated.   |
| lp             | integer | UNIX timestamp in milliseconds when the order book was last published. |
| u              | integer | Incrementing update ID used to validate message order within the feed. |
| market\_making | object  | Separate top-of-book maker quotes, grouped into bids and asks.         |

### Order book level format

`[price, quantity, liquidity_source]`

Prices and quantities are represented as strings. For normal order book levels, maintain entries by the combination of side, price, and liquidity source.

## Snapshot message

A snapshot contains the complete normal and market-making state for the feed. Replace both local books in full and store its update ID for validation of the next update.

```
{
  "pair": "btcusd",
  "type": "snapshot",
  "bids": [
    ["92567.89", "2.34", "ox"],
    ["92566.12", "0.875", "ox"],
    ["92550.00", "15", "coinbase"]
  ],
  "asks": [
    ["92568.45", "1.12", "ox"],
    ["92570.00", "3.45", "ox"],
    ["92585.20", "0.5", "kraken"]
  ],
  "lu": 1737568923478,
  "lp": 1737568924001,
  "u": 10000,
  "market_making": {
    "bids": [
      ["92567.50", "2.34", "ox"],
      ["92549.80", "15", "coinbase"]
    ],
    "asks": [
      ["92568.80", "1.12", "ox"],
      ["92585.60", "0.5", "kraken"]
    ]
  }
}
```

## Update message

An update includes only levels that changed. Omitted levels and liquidity sources remain unchanged. A quantity of "0" removes the corresponding entry.

```
{
  "pair": "btcusd",
  "type": "update",
  "bids": [
    ["92567.89", "1.980", "ox"],
    ["92540.00", "0.420", "coinbase"],
    ["92566.12", "0", "ox"]
  ],
  "asks": [
    ["92568.45", "0.900", "ox"],
    ["92600.00", "2.000", "ox"]
  ],
  "lu": 1737568931123,
  "lp": 1737568931500,
  "u": 10001,
  "market_making": {
    "bids": [["92567.50", "1.980", "ox"]],
    "asks": [["92568.80", "0.900", "ox"]]
  }
}
```

### Apply normal order book updates

1. Locate the entry using side, price, and liquidity source.
2. If quantity is non-zero, insert the level or replace its current quantity.
3. If quantity is "0", remove the level.
4. Keep all levels omitted from the message unchanged.

## Synchronize with update IDs

Every message includes an update ID in u. Validate update IDs only against messages from the same feed, such as `orderbook.delta.btcusd`.

### When a snapshot is received

1. Replace the entire local normal order book with the message's bids and asks.
2. Replace the entire local market-making book with `market_making.bids` and `market_making.asks`.
3. Accept the snapshot regardless of whether its update ID is sequential from the preceding message.
4. Store the snapshot's update ID and use it to validate the next update.

### When an update is received

1. Confirm that the message's u equals the previously accepted u + 1.
2. If the update ID is sequential, apply the normal and market-making deltas.
3. If the update ID is not sequential, do not apply that message or any later updates from the feed.
4. Unsubscribe and subscribe again to start a new feed, then rebuild local state from a new snapshot.

**Important:** A gap, duplicate, or out-of-order update means local state can no longer be trusted. Resynchronize before applying further updates.

## Market-making book

`market_making` is a separate top-of-book view. It contains at most one maker bid and one maker ask per liquidity source and is independent from the normal bids and asks arrays.

Market-making prices are maker-fee-adjusted and may differ from the same source's levels in the normal order book.

| snapshot | Replace the full bids and asks state.  | Replace the full bids and asks maps.    |
| -------- | -------------------------------------- | --------------------------------------- |
| update   | Apply only the supplied level changes. | Apply only the supplied source changes. |

### Maintain market-making state

* Maintain separate bid and ask maps keyed by liquidity source, not by price.
* On a snapshot, replace both maps in full.
* On an update, upsert each supplied source on the indicated side.
* If quantity is "0", remove that source's quote on the indicated side.
* Sources omitted from an update remain unchanged.
* An empty bids or asks array means there were no changes on that side.

### Market-making removal example

```
{
  "pair": "btcusd",
  "type": "update",
  "bids": [],
  "asks": [],
  "lu": 1737568935000,
  "lp": 1737568935100,
  "u": 10002,
  "market_making": {
    "bids": [["92567.50", "0", "ox"]],
    "asks": []
  }
}
```

This update removes the ox market-making bid. The `coinbase` market-making bid and all market-making asks remain unchanged.

<br>


# Orders & Account Data

Receive real-time streaming account updates from the sFOX WebSocket API

### Feeds

The sFOX WebSocket API offers the following Orders & Account Data feeds:

{% hint style="warning" %}
**Authentication required.** Please refer to the [WebSocket Authentication page here for more details.](/websocket-api/authentication)
{% endhint %}

<table data-card-size="large" data-column-title-hidden data-view="cards"><thead><tr><th>Feed</th><th>Description</th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Orders</strong></td><td>Receive real-time streaming updates regarding open orders in your account. </td><td><a href="/pages/mLvBQA85lIokfQOiTdS1">/pages/mLvBQA85lIokfQOiTdS1</a></td></tr><tr><td><strong>Trades</strong></td><td>Receive real-time streaming updates regarding completed trades (fills) executed in your account. </td><td><a href="/pages/aOHfJ9hRv1zQLo4ouy2e">/pages/aOHfJ9hRv1zQLo4ouy2e</a></td></tr><tr><td><strong>Balances</strong></td><td>Real-time streaming updates to your account balances.</td><td><a href="/pages/iVOSvuFhBr5DdDK7xGHv">/pages/iVOSvuFhBr5DdDK7xGHv</a></td></tr><tr><td><strong>Post-Trade Settlement</strong></td><td>Real-time streaming account post-trade settlement credit and risk updates</td><td><a href="/pages/nzNxYDBDoFJOIRB2vs4p">/pages/nzNxYDBDoFJOIRB2vs4p</a></td></tr></tbody></table>


# Orders

Real-time streaming updates to your open orders

Receive real-time updates regarding open orders you've placed in your account.&#x20;

Updates include any change to an open order e.g. order creation, partial fills, status changes, amendments, etc.

### **Subscribing**

<table data-header-hidden><thead><tr><th width="100"></th><th>Feed Name</th></tr></thead><tbody><tr><td>Feed name</td><td><strong><code>private.user.open-orders</code></strong> </td></tr></tbody></table>

```json
// Request -> orders feed
{
    "type": "subscribe", 
    "feeds": ["private.user.open-orders"]
}
```

{% hint style="info" %}
The initial response payload will include all open orders in your account–a list of N order objects, each containing the latest order information.
{% endhint %}

### Orders Message

{% hint style="info" %}
Refer to [Orders reference](/rest-api/orders) page for payload details including order status descriptions.
{% endhint %}

```json
//Orders feed message
{
  "sequence": 5,
  "recipient": "private.user.open-orders",
  "timestamp": 1649903305545835513,
  "payload": [{
    "id": 693291242,
    "client_order_id": "577ab261-9dfc-415a-ba61-a54a18c1942c",
    "date_added": "2023-11-14T22:08:53.000Z",
    "status": "Started",
    "filled": "0.00035333",
    "filled_amount": "14.61628778",
    "vwap": "41367.24246455",
    "price": "37227.82",
    "quantity": "0.05",
    "pair": "btcusd",
    "action": "Sell",
    "type": "TWAP",
    "algorithm_id": 307,
    "fees": "0.02850176"
  }]
}
```

### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws')

const ws = new WebSocket('wss://ws.sfox.com/ws')

ws.on('open', function() {
  const authMessage = {
   type: 'authenticate',
   apiKey: '<API_KEY>',
  }
  
  ws.send(JSON.stringify(authMessage))
})

// After successful authentication, subscribe to open orders feed
const subscribeMsg = {
  type: 'subscribe',
  feeds: ['private.user.open-orders']
}

ws.send(JSON.stringify(subscribeMsg))
```

{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" %}

```python
import asyncio
import json

import websockets


async def main(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "type": "authenticate",
            "apiKey": "<API_KEY>"
        }))

        # After successful authentication message, subscribe to the open orders feed
        await ws.send(json.dumps({
            "type": "subscribe",
            "feeds": ["private.user.open-orders"]
        }))
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Trades

Real-time streaming updates of completed trades.

Receive real-time updates regarding completed trades in your account–fills on orders you've placed. Complete trade history can also be retrieved from the REST API. See [Get All Trades](/rest-api/orders/get-all-trades) for details.

### **Subscribing**&#x20;

<table data-header-hidden><thead><tr><th width="100"></th><th>Feed Name</th></tr></thead><tbody><tr><td>Feed name</td><td><strong><code>private.user.trades</code></strong> </td></tr></tbody></table>

```json
// Request -> trades feed
{
    "type": "subscribe", 
    "feeds": ["private.user.trades"]
}
```

### Trades Message

#### Trade Object

<table><thead><tr><th width="213">Value</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>trade_id</code></strong></td><td>The ID of the trade</td></tr><tr><td><strong><code>order_id</code></strong></td><td>The ID of the order that this trade is associated with</td></tr><tr><td><strong><code>date_updated</code></strong></td><td>The date and time the trade was completed</td></tr><tr><td><strong><code>action</code></strong></td><td>Buy or Sell</td></tr><tr><td><strong><code>currency_pair</code></strong></td><td>The currency pair this trade was executed on</td></tr><tr><td><strong><code>quantity</code></strong></td><td>The base currency quantity bought or sold in this trade</td></tr><tr><td><strong><code>amount</code></strong></td><td>The gross quote currency amount cost or proceeds from this trade</td></tr><tr><td><strong><code>price</code></strong></td><td>The fill price of this trade</td></tr><tr><td><strong><code>fees</code></strong></td><td>The fees charged on this trade (always in the quote currency)</td></tr><tr><td><strong><code>net_amount</code></strong></td><td>The net quote currency amount cost or proceeds from this trade (<code>amount</code> net fees)</td></tr></tbody></table>

#### Trades Message

{% hint style="info" %}
Payload will contain a list of one or more trade objects, each representing a unique, completed trade.
{% endhint %}

```json
// Trades feed message
{
    "sequence": 3,
    "recipient": "private.user.trades",
    "timestamp": 1708630086193678496,
    "payload": [
        {
            "trade_id": 830151520,
            "order_id": 759514460,
            "date_updated": "2024-02-22T19:28:06.000Z",
            "action": "Sell",
            "currency_pair": "compusd",
            "quantity": "1.65911629",
            "amount": "99.47066469",
            "price": "59.954004",
            "fees": "0.04973533",
            "net_amount": "99.42092936"
        }
    ]
}
```

### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws')

const ws = new WebSocket('wss://ws.sfox.com/ws')

ws.on('open', function() {
  const authMessage = {
   type: 'authenticate',
   apiKey: '<API_KEY>'
  }
  
  ws.send(JSON.stringify(authMessage))
})

// After successful authentication, subscribe to trades feed
const subscribeMsg = {
  type: 'subscribe',
  feeds: ['private.user.trades']
}

ws.send(JSON.stringify(subscribeMsg))
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import json

import websockets


async def main(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "type": "authenticate",
            "apiKey": "<API_KEY>"
        }))

        # After successful authentication message, subscribe to trades feed
        await ws.send(json.dumps({
            "type": "subscribe",
            "feeds": ["private.user.trades"]
        }))
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endtab %}
{% endtabs %}


# Balances

Real-time streaming updates to your account balances

The **`private.user.balances`** feed provides you with real-time updates on changes to your account balances, including Web3 wallet balances updates.

{% hint style="info" %}
Updates reflect your balances *inclusive of* completed, partially completed, or pending transactions, orders, and transfers. For example, a given balance update *does* reflect outstanding and/or partially filled orders.
{% endhint %}

### **Subscribing**

<table data-header-hidden><thead><tr><th width="100"></th><th>Feed Name</th></tr></thead><tbody><tr><td>Feed name</td><td><strong><code>private.user.balances</code></strong> </td></tr></tbody></table>

```json
// Request -> balances feed
{
    "type": "subscribe", 
    "feeds": ["private.user.balances"]
}
```

### **Balances Message**

{% hint style="info" %}
There are 2 types of balances message payloads:&#x20;

* **Account balances:** Your trading/custody account balances (Refer to [Get All Balances](/rest-api/account-management/get-all-balances) for payload and balance object details).
* **Web3 wallet balances:** Your account's Web3 wallet balances (see below for payload details). Web3 wallet messages can be identified by the **`type`** field.
  {% endhint %}

#### **Web3 Wallet Message**

<table><thead><tr><th width="174.71345029239765">Key</th><th>Description</th></tr></thead><tbody><tr><td><strong><code>address</code></strong></td><td>The web3 wallet address</td></tr><tr><td><strong><code>balance</code></strong></td><td>The total balance of this currency in your web3 wallet</td></tr><tr><td><strong><code>network</code></strong></td><td>The token network</td></tr><tr><td><strong><code>type</code></strong></td><td>Specifies that this is a Web3 balance message. (<code>web3</code>)</td></tr></tbody></table>

{% tabs %}
{% tab title="Account balances message" %}

```json
// Balances feed message (account balances)
{
  "sequence": 10,
  "recipient": "private.user.balances",
  "timestamp": 1649899310281716289,
  "payload": [{
    "currency": "btc",
    "balance": "0.17572419",
    "available": "0.17572419",
    "held": "0",
    "trading_wallet": "0.17572419",
    "collateral_wallet": "0",
    "borrow_wallet": "0",
    "lending_wallet": "0"
  }, {
    "currency": "usd",
    "balance": "100",
    "available": "100",
    "held": "0",
    "trading_wallet": "100",
    "collateral_wallet": "0",
    "borrow_wallet": "0",
    "lending_wallet": "0"
  }]
}
```

{% endtab %}

{% tab title="Web3 wallet balances message" %}

```json
// Balances feed message (web3 wallet balances)
{
  "sequence": 11,
  "recipient": "private.user.balances",
  "timestamp": 1649899310281716289,
  "payload": {
    "address": "0x0bCdB57ae247F434C91b1d4521fFd6601f7e8999",
    "balance": "250.5",
    "currency": "USDC",
    "network": "Ethereum",
    "type": "web3"
  }
}
```

{% endtab %}
{% endtabs %}

### Example Code

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws')

const ws = new WebSocket('wss://ws.sfox.com/ws')

ws.on('open', function() {
  const authMessage = {
   type: 'authenticate',
   apiKey: '<API_KEY>'
  }
  
  ws.send(JSON.stringify(authMessage))
})

// After successful authentication, subscribe to balances feed
const subscribeMsg = {
  type: 'subscribe',
  feeds: ['private.user.balances']
}

ws.send(JSON.stringify(subscribeMsg))
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import json

import websockets


async def main(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "type": "authenticate",
            "apiKey": "<API_KEY>"
        }))

        # After successful authentication message
        await ws.send(json.dumps({
            "type": "subscribe",
            "feeds": ["private.user.balances"]
        }))
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endtab %}
{% endtabs %}


# Post-Trade Settlement

Real-time streaming account post-trade settlement credit and risk updates

Receive real-time updates to your account's credit and risk metrics.

{% hint style="info" %}
Refer to the [Support Center](https://support.sfox.com/product-guides/trading/post-trade-settlement/risk-management#overview) for more information regarding risk management and risk metrics for Post-Trade Settlement (note: you may be asked to sign in to your sFOX account before being redirected to the support center)
{% endhint %}

### **Subscribing**

<table data-header-hidden><thead><tr><th width="100"></th><th>Feed Name</th></tr></thead><tbody><tr><td>Feed name</td><td><strong><code>private.user.post-trade-settlement</code></strong> </td></tr></tbody></table>

```json
// Request -> post-trade settlement feed
{
    "type": "subscribe", 
    "feeds": ["private.user.post-trade-settlement"]
}
```

{% hint style="info" %}
The initial response payload will include a snapshot of your account's current credit and risk metric data.
{% endhint %}

### **Post-Trade Settlement Message**

{% hint style="warning" %}
Messages are only sent when a transaction is executed. However, please note that asset price changes may impact your risk metrics.
{% endhint %}

#### Post-Trade Settlement Object

<table><thead><tr><th width="272">Key</th><th>Type</th><th width="442">Description</th></tr></thead><tbody><tr><td><strong><code>enabled</code></strong></td><td>boolean</td><td>Boolean whether post-trade settlement is enabled for your account</td></tr><tr><td><strong><code>equity</code></strong></td><td>string</td><td>Collateralization–The "liquidation value" of your portfolio–the USD value of your assets if all of your holdings were converted to USD.</td></tr><tr><td><strong><code>equity_for_withdrawals</code></strong></td><td>string</td><td>Your "Free Equity." The portion of your Equity that could be removed from your account (e.g. for a withdrawal) without triggering liquidation. </td></tr><tr><td><strong><code>exposure</code></strong></td><td>string</td><td>Your current total net open position (NOP) across currencies/markets–the USD value of your positions pending settlement.</td></tr><tr><td><strong><code>available_exposure</code></strong></td><td>string</td><td>Credit available before hitting your Exposure Limit.</td></tr><tr><td><strong><code>exposure_limit</code></strong></td><td>string</td><td>The maximum USD value of your total net open positions (NOPs) across currencies/markets.</td></tr><tr><td><strong><code>liquidation_level</code></strong></td><td>string</td><td>If your Equity Level drops below this level, your positions will be partially settled automatically.</td></tr></tbody></table>

#### Post-Trade Settlement Message

```json
// Post-trade settlement message
{
    "sequence": 3,
    "recipient": "private.user.post-trade-settlement",
    "timestamp": 1727392002153041890,
    "payload": {
        "enabled": true,
        "equity": "81306152.88083515",
        "equity_for_withdrawals": "81286273.68856692",
        "exposure": "0",
        "available_exposure": "250000",
        "exposure_limit": "250000",
        "liquidation_level": "0.1"
    }
}
```

### Example Code & Post-Trade Settlement Message

{% tabs %}
{% tab title="NodeJS" %}

```javascript
const WebSocket = require('ws')

const ws = new WebSocket('wss://ws.sfox.com/ws')

ws.on('open', function() {
  const authMessage = {
   type: 'authenticate',
   apiKey: '<API_KEY>',
  }
  
  ws.send(JSON.stringify(authMessage))
})

// After successful authentication, subscribe to balances feed
const subscribeMsg = {
  type: 'subscribe',
  feeds: ['private.user.post-trade-settlement']
}

ws.send(JSON.stringify(subscribeMsg))
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import json

import websockets


async def main(uri):
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "type": "authenticate",
            "apiKey": "<API_KEY>"
        }))

        # After successful authentication message
        await ws.send(json.dumps({
            "type": "subscribe",
            "feeds": ["private.user.post-trade-settlement"]
        }))
        async for msg in ws:
            print(msg)


asyncio.run(main("wss://ws.sfox.com/ws"))
```

{% endtab %}
{% endtabs %}


# FIX Order Entry

Use the FIX Order Entry session to submit, manage, and cancel orders.

For assistance or information regarding implementation of the FIX API, please contact <support@sfox.com>

{% hint style="info" %}
sFOX uses FIX 4.4
{% endhint %}

## Connectivity

Before logging onto a FIX session, you must establish a secure connection to the FIX gateway

### Endpoints <a href="#endpoints" id="endpoints"></a>

<table><thead><tr><th width="168.33333333333331">Environment</th><th width="437">Value</th><th>SSL Required</th></tr></thead><tbody><tr><td>Production</td><td><code>fix.sfox.com:5001</code></td><td>Y</td></tr><tr><td>Sandbox</td><td><code>fix.staging.sfox.com:5001</code> <br><br><a href="mailto:support@sfox.com">Contact support</a> <em>for access to the Sandbox environment.</em></td><td>Y</td></tr></tbody></table>

### TCP SSL

If your FIX implementation does not support establishing a native TCP SSL connection with SNI support, set up a local proxy such as [stunnel](https://www.stunnel.org/) to establish a secure connection to the FIX gateway. Refer to our [QuickFIX Integration Guide](/fix-api/quickfix-guide) for details and examples

## Standard Header

A standard header is required at the start of each message

{% hint style="info" %}
`SenderCompID`s must be provided by sFOX. Contact <support@sfox.com> to be provided with a `SenderCompID` for your session.
{% endhint %}

<table><thead><tr><th width="83">Tag</th><th width="200.99111900532864">Name</th><th width="466.5107282855374">Description</th></tr></thead><tbody><tr><td>108</td><td>HeartBtInt</td><td>Must be &#x3C;= <code>30</code> (seconds)</td></tr><tr><td>8</td><td>BeginString</td><td>Must be <code>FIX.4.4</code></td></tr><tr><td>49</td><td>SenderCompID</td><td>Value provided by sFOX. Must be unique per session</td></tr><tr><td>56</td><td>TargetCompID</td><td>Must be <code>SFOX</code></td></tr><tr><td></td><td>StartDay</td><td><code>Sunday</code></td></tr><tr><td></td><td>EndDay</td><td><code>Sunday</code></td></tr><tr><td></td><td>StartTime</td><td><code>00:00:01</code></td></tr><tr><td></td><td>EndTime</td><td><code>00:00:00</code></td></tr><tr><td></td><td>TimeZone</td><td>Must be <code>ETC</code> or <code>UTC</code></td></tr></tbody></table>

## Messages

### Logon – A <a href="#logon-a" id="logon-a"></a>

Sent by the client to initiate a session and by the server as an acknowledgement.

{% hint style="info" %}
Only one session may exist per SenderCompId. Attempting to logon using a SenderCompId of an active session will result in an error.
{% endhint %}

<table><thead><tr><th width="99">Tag</th><th width="200">Name</th><th width="105">Required</th><th width="358.71428571428567">Description</th></tr></thead><tbody><tr><td>554</td><td>Password</td><td>Y</td><td>Your API Key (generate one <a href="https://trade.sfox.com/account/api">here</a>)</td></tr><tr><td>20040</td><td>CancelOnDisconnect</td><td>N</td><td>String Field: Optionally cancel all orders on disconnect (logout or otherwise). <em>Note: this cancels orders on the entire account.</em><br><br><code>Y</code> - Cancel on Disconnect</td></tr></tbody></table>

{% hint style="warning" %}
**QuickFIX:** If you are implementing the FIX protocol using QuickFIX please refer to our [QuickFIX Integration Guide](/fix-api/quickfix-guide)
{% endhint %}

### NewOrderSingle – D <a href="#new-order-single-d" id="new-order-single-d"></a>

<table><thead><tr><th width="88" data-type="number">Tag</th><th width="159">Name</th><th width="186">Required</th><th>Description</th></tr></thead><tbody><tr><td>11</td><td>ClOrdID</td><td>Y</td><td>Client provided order ID, must be unique per-account. If placing an order on behalf of a quote, this value should match your QuoteReqID (see <a data-mention href="#order-status-request-h">#order-status-request-h</a>)</td></tr><tr><td>55</td><td>Symbol</td><td>Y</td><td><p>Trading pair in lowercase <code>basequote</code> format i.e. <code>btcusd</code></p><p>(see: <a href="#security-list-request-x">Security List</a>)</p></td></tr><tr><td>54</td><td>Side</td><td>Y</td><td><p><code>1</code>: Buy</p><p><code>2</code>: Sell</p></td></tr><tr><td>40</td><td>OrdType</td><td>Y</td><td><p><code>1</code>: Market</p><p><code>2</code>: Limit</p><p><code>3</code>: Stop</p><p>or one of our Algorithm IDs</p></td></tr><tr><td>44</td><td>Price</td><td>Y (excluding Market orders)</td><td>Limit Price</td></tr><tr><td>38</td><td>OrderQty</td><td>Y</td><td>For limit orders, this is the quantity to trade in the base currency. For Market Sell orders, this is the amount in the base currency.</td></tr><tr><td>152</td><td>CashOrderQty</td><td>Y (OrdType = <code>1</code> AND Side = <code>1</code> or OrdType = <code>3</code> (stop) AND Side = <code>1</code> (buy)</td><td>For market buy orders, this is the amount to spend in the quote currency</td></tr><tr><td>21</td><td>HandleInst (custom usage)</td><td>N</td><td>How to execute the order:<br><code>1</code>: Smart<br><code>2</code>: NetPrice (default)</td></tr><tr><td>59</td><td>TimeInForce</td><td>N</td><td>The lifetime of the order:<br><code>1</code>: good till cancel (default)<br><code>3</code>: immediate or cancel</td></tr><tr><td>20025</td><td>Destination (custom)</td><td>N</td><td>Specific destination:<br><code>ox</code><br><code>darkpool</code></td></tr><tr><td>117</td><td>QuoteID</td><td>N</td><td>QuoteID you'd like to place an order on behalf of (see <a data-mention href="#order-status-request-h">#order-status-request-h</a>)</td></tr></tbody></table>

<table><thead><tr><th width="125">Tag</th><th width="157">Name</th><th width="149">Algorithm</th><th width="105">Required</th><th width="297">Description</th><th>Default</th></tr></thead><tbody><tr><td>20000</td><td>StopAmount</td><td><code>308</code>: Trailing Stop</td><td>N</td><td>The fixed amount to trail the market price by</td><td></td></tr><tr><td>20001</td><td>StopPercent</td><td><code>308</code>: Trailing Stop</td><td>N</td><td>The percentage to trail the market price by (given as a decimal: 10% = 0.1)</td><td></td></tr><tr><td>20010</td><td>Interval</td><td><code>307</code>: TWAP</td><td>Y</td><td>The frequency at which TWAP trades are executed (in seconds)</td><td></td></tr><tr><td>20011</td><td>TotalTime</td><td><code>307</code>: TWAP</td><td>Y</td><td>The maximimum time a TWAP order will stay active (in seconds). Must be >= 15 minutes (900 seconds) and the interval (tag 20010)</td><td></td></tr><tr><td>20020</td><td>RoutingOption</td><td><p><code>301</code>: Gorilla</p><p><code>303</code>: Hare</p></td><td>Y</td><td>How SFOX will trade your order, <code>BestPrice</code> or <code>Fast</code></td><td></td></tr></tbody></table>

### RequestForQuote - R

<table><thead><tr><th width="88">Tag</th><th width="137">Name</th><th width="104">Required</th><th>Description</th></tr></thead><tbody><tr><td>131</td><td>QuoteReqID</td><td>Y</td><td>Client provided quote request ID. This identifier will also be used in any follow-up order placed on behalf of the returned quote as the ClOrdID</td></tr><tr><td>55</td><td>Symbol</td><td>Y</td><td><p>Trading pair in lowercase <code>basequote</code> format i.e. <code>btcusd</code></p><p>(see: <a href="#security-list-request-x">Security List</a>)</p></td></tr><tr><td>54</td><td>Side</td><td>Y</td><td><p><code>1</code>: Buy</p><p><code>2</code>: Sell</p></td></tr><tr><td>38</td><td>OrderQty</td><td>Y</td><td>Quantity of base currency you're interested in quoting a buy/sell order on</td></tr></tbody></table>

### OrderStatusRequest – H <a href="#order-status-request-h" id="order-status-request-h"></a>

<table><thead><tr><th width="96">Tag</th><th width="168">Name</th><th width="108">Required</th><th width="391.71428571428567">Description</th></tr></thead><tbody><tr><td>11</td><td>ClOrdID</td><td>Y</td><td>Original ClOrdID when creating the order</td></tr><tr><td>790</td><td>OrdStatusReqID</td><td>N</td><td>Optionally provided value that will be echoed in the response</td></tr></tbody></table>

### OrderCancelRequest – F <a href="#order-cancel-request-f" id="order-cancel-request-f"></a>

<table><thead><tr><th width="93.61538461538461">Tag</th><th width="150">Name</th><th width="106">Required</th><th>Description</th></tr></thead><tbody><tr><td>11</td><td>ClOrdID</td><td>Y</td><td>Unique ID of the cancel request</td></tr><tr><td>41</td><td>OrigClOrdID</td><td>Y</td><td>Original ClOrdID provided when creating the order</td></tr></tbody></table>

### OrderCancelReplaceRequest - G

<table><thead><tr><th width="120">Tag</th><th width="170">Name</th><th width="108">Required</th><th>Description</th></tr></thead><tbody><tr><td>11</td><td>ClOrdID</td><td>Y</td><td>Client Order ID of this request</td></tr><tr><td>41</td><td>OrigClOrdID</td><td>Y</td><td>Client Order ID of the original order</td></tr><tr><td>38</td><td>OrderQty</td><td>N</td><td></td></tr><tr><td>44</td><td>Price</td><td>N</td><td></td></tr><tr><td>152</td><td>CashOrderQty</td><td>N</td><td></td></tr><tr><td>20000</td><td>StopAmount</td><td>N</td><td></td></tr><tr><td>20001</td><td>StopPercent</td><td>N</td><td></td></tr></tbody></table>

### OrderMassCancelRequest - q

<table><thead><tr><th width="88.10122394971881">Tag</th><th width="232.84848484848487">Name</th><th width="108">Required</th><th>Description</th></tr></thead><tbody><tr><td>11</td><td>ClOrdID</td><td>N</td><td>Optional client order id, echoed back in the <code>OrderMassCancelReport</code></td></tr><tr><td>530</td><td>MassCancelRequestType</td><td>Y</td><td><code>7</code> - Cancel All Orders (this will attempt to cancel all open orders for the account)</td></tr></tbody></table>

### OrderMassCancelReport - r

<table><thead><tr><th width="94.52490473522084">Tag</th><th width="238.51028393699207">Name</th><th>Description</th></tr></thead><tbody><tr><td>37</td><td>OrderID</td><td>OrderID of this report</td></tr><tr><td>11</td><td>ClOrdID</td><td>ClOrdID provided in the <code>OrderMassCancelRequest</code>, if provided</td></tr><tr><td>530</td><td>MassCancelRequestType</td><td><code>7</code> - Cancel All Orders</td></tr><tr><td>531</td><td>MassCancelResponse</td><td><code>0</code> - Request Rejected<br><code>7</code> - Cancel All Orders</td></tr><tr><td>532</td><td>MassCancelRejectReason</td><td><code>99</code> - Other (if 531 = 0)</td></tr><tr><td>533</td><td>TotalAffectedOrders</td><td>Number of orders that are affected by the request (note: it is not guaranteed all of these orders are canceled, only that a cancel is requested)</td></tr><tr><td>58</td><td>Text</td><td>Optional text to describe the error (if 531 = 0)</td></tr></tbody></table>

### ExecutionReport – 8 <a href="#execution-report-8" id="execution-report-8"></a>

<table><thead><tr><th width="108.12655138722931">Tag</th><th width="160.69564222649527">Name</th><th>Description</th></tr></thead><tbody><tr><td>37</td><td>OrderID</td><td>SFOX Assigned Order ID, when rejected this will be 0.</td></tr><tr><td>17</td><td>ExecID</td><td>SFOX Assigned Trade ID, when rejected this will be 0.</td></tr><tr><td>11</td><td>ClOrdID</td><td>Client provided order ID</td></tr><tr><td>31</td><td>LastPx</td><td>Last fill price</td></tr><tr><td>32</td><td>LastQty</td><td>Last fill quantity</td></tr><tr><td>60</td><td>TransactTime</td><td></td></tr><tr><td>55</td><td>Symbol</td><td>Trading pair</td></tr><tr><td>54</td><td>Side</td><td><p><code>1</code>: Buy</p><p><code>2</code>: Sell</p></td></tr><tr><td>40</td><td>OrdType</td><td><p><code>1</code>: Market</p><p><code>2</code>: Limit</p></td></tr><tr><td>44</td><td>Price</td><td>Client provided limit price, only if OrdType = 2</td></tr><tr><td>150</td><td>ExecType</td><td><p>Execution type:</p><p><code>0</code>: New</p><p><code>4</code>: Canceled</p><p><code>8</code>: Rejected</p><p><code>F</code>: Trade</p><p><code>I</code>: Order Status Request</p></td></tr><tr><td>39</td><td>OrdStatus</td><td><p>Current status of the order:<br><code>0</code>: New</p><p><code>1</code>: Partially Filled</p><p><code>2</code>: Filled</p><p><code>3</code>: Done</p><p><code>4</code>: Canceled</p><p><code>8</code>: Rejected</p></td></tr><tr><td>151</td><td>LeavesQty</td><td>Amount remaining of the order</td></tr><tr><td>14</td><td>CumQty</td><td>Amount filled so far of the order</td></tr><tr><td>6</td><td>AvgPx</td><td>VWAP</td></tr><tr><td>136</td><td>NoMiscFees</td><td>Number of misc fees</td></tr><tr><td>=> 137</td><td>MiscFeeAmt</td><td>Amount of fees</td></tr><tr><td>=> 138</td><td>MiscFeeCurr</td><td>Fee Currency</td></tr></tbody></table>

### OrderCancelReject – 9 <a href="#ordercancelreject-9" id="ordercancelreject-9"></a>

<table><thead><tr><th width="100.24966622162881">Tag</th><th width="174">Name</th><th>Description</th></tr></thead><tbody><tr><td>37</td><td>OrderID</td><td>SFOX Order ID, unless the order is unknown (CxlRejReason = Unknown Order)</td></tr><tr><td>11</td><td>ClOrdID</td><td>Client provided order ID of the cancel request</td></tr><tr><td>41</td><td>OrigClOrdID</td><td>Client provided order ID of the original order (echoed back from the request)</td></tr><tr><td>39</td><td>OrdStatus</td><td>Existing status of the order that could not be canceled</td></tr><tr><td>102</td><td>CxlRejReason</td><td><code>0</code>: Too Late To Cancel<br><code>1</code>: Unknown Order<br><code>99</code>: Other (already canceled)</td></tr><tr><td>434</td><td>CxlRejResponseTo</td><td><code>1</code>: Order Cancel Request<br><code>2</code>: Order Cancel Replace Request</td></tr></tbody></table>

### Security List Request - x

<table><thead><tr><th width="88.28571428571428">Tag</th><th width="246">Name</th><th width="105">Required</th><th>Description</th></tr></thead><tbody><tr><td>320</td><td>SecurityReqID</td><td>Y</td><td></td></tr><tr><td>559</td><td>SecurityListRequestType</td><td>Y</td><td>Must be <code>4</code> - All Securities</td></tr></tbody></table>

### Security List - y

<table><thead><tr><th width="111">Tag</th><th width="204.23993144815768">Name</th><th>Description</th></tr></thead><tbody><tr><td>320</td><td>SecurityReqID</td><td>SecurityReqID from the SecurityListRequest</td></tr><tr><td>322</td><td>SecurityResponseID</td><td>Unique identifier of the response</td></tr><tr><td>560</td><td>SecurityRequestResult</td><td>This will always be <code>0</code> - Valid Request</td></tr><tr><td>146</td><td>NoRelatedSym</td><td></td></tr><tr><td>-> 55</td><td>Symbol</td><td>Underlying asset symbol in lowercase <code>basequote</code> format i.e. <code>btcusd</code></td></tr></tbody></table>


# FIX Market Data

Use the FIX Market Data session to receive market data from the FIX API

For assistance or information regarding implementation of the FIX API, please contact <support@sfox.com>

{% hint style="info" %}
sFOX uses FIX 4.4
{% endhint %}

## Connectivity

Before logging onto a FIX session, you must establish a secure connection to the FIX gateway

### Endpoints

<table><thead><tr><th width="157">Environment</th><th width="436">URL</th><th>SSL Required</th></tr></thead><tbody><tr><td>Production</td><td><code>fix-md.sfox.com:5001</code></td><td>Y</td></tr><tr><td>Sandbox</td><td><code>fix-md.staging.sfox.com:5001</code><br><a href="mailto:support@sfox.com">Contact support</a> to access the Sandbox environment</td><td>Y</td></tr></tbody></table>

### TCP SSL

If your FIX implementation does not support establishing a native TCP SSL connection with SNI support, set up a local proxy such as [stunnel](https://www.stunnel.org/) to establish a secure connection to the FIX gateway. Refer to our [QuickFIX Integration Guide](/fix-api/quickfix-guide) for details and examples

## Standard Header

{% hint style="info" %}
`SenderCompID`s must be provided by sFOX. Contact <support@sfox.com> to be provided with a `SenderCompID` for your session.
{% endhint %}

<table><thead><tr><th width="94">Tag</th><th width="175">Field</th><th>Description</th></tr></thead><tbody><tr><td>8</td><td>BeginString</td><td>Must be <code>FIX.4.4</code></td></tr><tr><td>108</td><td>HeartBtInt</td><td>Must be &#x3C;= <code>30</code> (seconds)</td></tr><tr><td>49</td><td>SenderCompID</td><td>Value provided by sFOX. Must be unique per session</td></tr><tr><td>56</td><td>TargetCompID</td><td>Must be <code>SFOX</code></td></tr><tr><td></td><td>StartDay</td><td><code>Sunday</code></td></tr><tr><td></td><td>EndDay</td><td><code>Sunday</code></td></tr><tr><td></td><td>StartTime</td><td><code>00:00:01</code></td></tr><tr><td></td><td>EndTime</td><td><code>00:00:00</code></td></tr><tr><td></td><td>TimeZone</td><td><code>ETC</code> / <code>UTC</code></td></tr></tbody></table>

## Messages

### Logon - A

{% hint style="info" %}
Only one session may exist per SenderCompId. Attempting to logon using a SenderCompId of an active session will result in an error.
{% endhint %}

<table><thead><tr><th width="92">Tag</th><th width="134">Name</th><th width="129">Required</th><th>Description</th></tr></thead><tbody><tr><td>554</td><td>Password</td><td>Y</td><td>Your API Key</td></tr></tbody></table>

{% hint style="warning" %}
**QuickFIX:** If you are implementing the FIX protocol using QuickFIX please refer to our [QuickFIX Integration Guide](/fix-api/quickfix-guide)
{% endhint %}

### Market Data Request – V <a href="#market-data-request-v" id="market-data-request-v"></a>

Subscribes the current session to Market Data

<table><thead><tr><th width="117">Tag</th><th width="231">Name</th><th width="111">Required</th><th>Description</th></tr></thead><tbody><tr><td>262</td><td>MDReqID</td><td>Y</td><td>Market data request ID, included in all MarketDataSnapshotFullRefresh updates</td></tr><tr><td>263</td><td>SubscriptionRequestType</td><td>Y</td><td><code>1</code>: Snapshot Plus Updates<br><code>2</code>: Disable Previous Snapshot Plus Updates</td></tr><tr><td>20030</td><td>FeedType</td><td>Y</td><td>Which marketdata feed:<br><code>net</code>: Net Price (default)<br><code>smart</code>: Smart</td></tr><tr><td>264</td><td>MarketDepth</td><td>N</td><td>Depth of the orderbook (per-side). The orderbook may be depth limited to a smaller number than the requested depth.</td></tr><tr><td>267</td><td>NoMDEntryType</td><td>N</td><td>Number of MDEntryTypes requested. If empty the default is to subscribe to the orderbook.</td></tr><tr><td>-> 269</td><td>MDEntryType</td><td>N</td><td><code>0</code>: Bid<br><code>1</code>: Offer<br><code>2</code>: Trade<br><br>Note: <code>0</code> and/or <code>1</code> will give both sides of the book.</td></tr><tr><td>146</td><td>NoRelatedSym</td><td>Y</td><td>Number of symbols in this request</td></tr><tr><td>-> 55</td><td>Symbol</td><td>Y</td><td>Pair to subscribe to, <code>basequote</code> format.</td></tr></tbody></table>

### Market Data Snapshot/Full Refresh - W

<table><thead><tr><th width="143">Tag</th><th width="174">Name</th><th>Description</th></tr></thead><tbody><tr><td>262</td><td>MDReqID</td><td>Original MDReqID that generated this refresh</td></tr><tr><td>55</td><td>Symbol</td><td>Symbol/currency pair of the market data entry</td></tr><tr><td>106</td><td>Issuer</td><td>The full feed recipient, e.g. <code>orderbook.net.btcusd</code></td></tr><tr><td>268</td><td>NoMDEntries</td><td>Number of market data entries in this message</td></tr><tr><td>-> 269</td><td>MDEntryType</td><td><code>0</code>: Bid<br><code>1</code>: Offer<br><code>2</code>: Trade</td></tr><tr><td>-> 270</td><td>MDEntryPx</td><td>Price of the market data entry</td></tr><tr><td>-> 271</td><td>MDEntrySize</td><td>Size/Quantity of the market data entry</td></tr><tr><td>-> 273</td><td>MDEntryTime</td><td>Only for trades</td></tr><tr><td>-> 37</td><td>OrderID</td><td>Only for trades</td></tr><tr><td>-> 275</td><td>MDMkt</td><td>Market of the entry, not applicable in the compact/enterprise feed</td></tr><tr><td>-> 2446</td><td>AggressorSide</td><td><code>1</code>: Buy<br><code>2</code>: Sell</td></tr></tbody></table>

### Security List Request - x

Returns a [Security List - y](#security-list-y) response containing supported symbols

<table><thead><tr><th width="113">Tag</th><th width="222">Name</th><th width="131">Required</th><th>Description</th></tr></thead><tbody><tr><td>320</td><td>SecurityReqID</td><td>Y</td><td></td></tr><tr><td>559</td><td>SecurityListRequestType</td><td>Y</td><td><code>4</code>: All Securities</td></tr></tbody></table>

### Security List - y

The response containing the list of symbols from a [Security List Request - x](#security-list-request-x) request

<table><thead><tr><th width="115">Tag</th><th width="225">Name</th><th>Description</th></tr></thead><tbody><tr><td>320</td><td>SecurityReqID</td><td>SecurityReqID from the SecurityListRequest</td></tr><tr><td>322</td><td>SecurityResponseID</td><td>Unique identifier of the response</td></tr><tr><td>560</td><td>SecurityRequestResult</td><td><code>0</code>: Valid Request</td></tr><tr><td>146</td><td>NoRelatedSym</td><td>Specifies the number of returned symbols</td></tr><tr><td>-> 55</td><td>Symbol</td><td>Underlying asset symbol in <code>basequote</code> format. i.e. <code>btcusd</code></td></tr></tbody></table>


# QuickFIX Guide

How to start integrating sFOX's FIX API using the QuickFIX FIX Engine Library

## About QuickFIX

QuickFIX Engine is an open source implementation of the FIX Protocol. To learn more, visit:

{% embed url="<https://quickfixengine.org/>" %}

## QuickFIX/C++

QuickFIX/C++ is a FIX implementation for C++, Python, and Ruby. Follow these steps to start using sFOX's FIX API with QuickFIX/C++:

1. Compile [QuickFIX/C++](https://github.com/quickfix/quickfix/tree/master/examples/tradeclient): `cmake` then `make` in the root directory
2. Use the [`stunnel` Configuration](#stunnel-configuration) below with `stunnel tunnel.conf`
3. Run the [Test Client](#undefined) `./bin/tradeclient <file_name>.cfg`

{% hint style="warning" %}
Make sure to add your API key to the application (recommended to so do in code). Following these steps without adding your API Key will result in failure to connect
{% endhint %}

#### stunnel Configuration

`tunnel.conf`

```
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1

sslVersionMin = TLSv1.2
sslVersionMax = TLSv1.3

debug = debug
client = yes
foreground = yes

[order]
accept = 5001
connect = fix.sfox.com:5001
sni = fix.sfox.com
```

#### Test Client

`<file_name>.cfg` (i.e. sfox.cfg)

{% hint style="warning" %}
Update the `SenderCompID` to the name of your choice
{% endhint %}

```ini
[DEFAULT]
ConnectionType=initiator
ReconnectInterval=60

[SESSION]
BeginString=FIX.4.4
SenderCompID=<your_sender_comp_id>
HeartBtInt=10
TargetCompID=SFOX
UseDataDictionary=N
SocketConnectPort=5001
SocketConnectHost=127.0.0.1
StartTime=00:00:00
EndTime=00:00:00
ResetOnLogon=Y
LogonTimeout=60
FileStorePath=./stores
```

## QuickFIX/J (Java)

{% hint style="warning" %}
LOGON responses will arrive after the heart beat interval, you will either need to set the heart beat interval low or set *LogonTimeout > HeartBtInt*&#x20;
{% endhint %}

{% hint style="warning" %}
UseSNI: You must set UseSNI=Y, which is supported in >=2.3.0
{% endhint %}

{% hint style="info" %}
`stunnel` is required for Java versions before 1.17
{% endhint %}

## Quickfix/N (C#)

Example Config

```
[DEFAULT]
ConnectionType=initiator
ReconnectInterval=60

[SESSION]
BeginString=FIX.4.4
SenderCompID=STG-USER-MD-01 # your assigned sender comp id
HeartBtInt=10
TargetCompID=SFOX
UseDataDictionary=N
StartTime=00:00:05
EndTime=00:00:00
StartDay=Sunday
EndDay=Sunday
ResetOnLogon=Y
LogonTimeout=60
FileStorePath=./stores
SSLEnable=Y
SocketConnectPort=5001
SocketConnectHost=fix-md.staging.sfox.com # or fix.staging.sfox.com for OE sessions
```


# Error Codes

## HTTP Status Codes

The sFOX API communicates error codes through HTTP status codes. The following are the error codes currently in use:

<table><thead><tr><th width="114" align="center">Code</th><th>Description</th></tr></thead><tbody><tr><td align="center"><strong><code>400</code></strong></td><td><strong>Bad Request</strong> — Your request was malformed in some way</td></tr><tr><td align="center"><strong><code>401</code></strong></td><td><strong>Unauthorized</strong> - Your API key is wrong</td></tr><tr><td align="center"><strong><code>403</code></strong></td><td><strong>Forbidden</strong> — The API key is not authorized for this endpoint</td></tr><tr><td align="center"><strong><code>404</code></strong></td><td><strong>Not Found</strong> — The specified endpoint could not be found</td></tr><tr><td align="center"><strong><code>405</code></strong></td><td><strong>Method Not Allowed</strong> — You tried to access a endpoint with an invalid method</td></tr><tr><td align="center"><strong><code>406</code></strong></td><td><strong>Not Acceptable</strong> — You requested a format that isn’t json</td></tr><tr><td align="center"><strong><code>422</code></strong></td><td><strong>Unprocessable Entity</strong> - Your request contained invalid input</td></tr><tr><td align="center"><strong><code>429</code></strong></td><td><strong>Too Many Requests</strong> — You have exceeded your request limit</td></tr><tr><td align="center"><strong><code>500</code></strong></td><td><strong>Internal Server Error</strong> — We had a problem with our server. Try again later.</td></tr><tr><td align="center"><strong><code>503</code></strong></td><td><strong>Service Unavailable</strong> — We’re temporarily offline for maintanance. Please try again later.</td></tr></tbody></table>


# Welcome

Welcome to the sFOX Connect API documentation.&#x20;

sFOX Connect is an API-first product for businesses launching or expanding digital asset products.  In a single integration Connect provides you with a compliant, secure, end-to-end digital asset solution across user onboarding, trading, custody and more.

Connect safely accelerates your time to market, unlocks new revenue streams with Monetization, enabling customizable fees for your users.

{% hint style="info" %}
Want to learn more? Contact us at <sales@sfox.com>.
{% endhint %}


# Getting Started

Connect API interactions originate from a "Partner" – your business and its master sFOX account. sFOX Connect enables Partners to automate onboarding and account verification process for your end users and interact with those end users' accounts without users having to leave your platform.

Connect integrations follow the following structure/hierarchy:

<div align="left" data-full-width="false"><figure><img src="/files/8vIXY8n7FTtlU6MjvW36" alt="" width="375"><figcaption></figcaption></figure></div>

## How it works

The sFOX Connect API provides a simple and secure method for you to instantly offer sFOX's suite of digital asset services to your users:

1. **Onboarding & Verification:** Create and verify an sFOX account for your user
   1. Send your user's KYC information to sFOX
   2. sFOX Connect will create and verify an sFOX account for your user
2. **Generate User Authentication Token:** Retrieve an authentication token to interact with this user's sFOX account
   1. You now have access to the user's sFOX account and your user has access to sFOX's products and features all from within your application


# Resources


# Terminology

<table><thead><tr><th width="196.4453125">Term</th><th>Description</th></tr></thead><tbody><tr><td><strong>Partner</strong></td><td>Term used to describe your enterprise within the context of Connect participants.</td></tr><tr><td><strong>End User</strong></td><td>A customer of your enterprise. This may be an individual (natural person) or a business. Sometimes abbreviated to 'User'</td></tr><tr><td><strong>Connect API Key</strong></td><td>The API key you will use to interact with the Connect API. <a href="/pages/G3R1xNlOWSjDGrCbywMc">Additional details here</a>.</td></tr><tr><td><strong>User Auth Token</strong></td><td>The API key for a specific end user account that you will use to interact with the sFOX API on behalf of that specific end user account. <a href="/pages/G3R1xNlOWSjDGrCbywMc">Additional details here</a>.</td></tr></tbody></table>


# Systems & Operations

## Production URLs

Use the following URLs to connect to sFOX production APIs. For testing, see Sandbox URLs.

<table><thead><tr><th width="281">API</th><th>URL</th></tr></thead><tbody><tr><td><strong>REST API</strong></td><td><strong><code>https://api.sfox.com</code></strong></td></tr><tr><td><strong>REST API</strong><br>(<a href="https://docs.sfox.com/rest-api/market-data/get-candlesticks">Candlestick / OHLCV </a>Data)</td><td><strong><code>https://chartdata.sfox.com</code></strong></td></tr><tr><td><strong>WebSocket API</strong></td><td><strong><code>wss://ws.sfox.com/ws</code></strong></td></tr></tbody></table>

## Sandbox URLs

Use the following URLs to test your API connectivity.&#x20;

{% hint style="warning" %}

1. API keys are separate from production. Sign in to the [sandbox interface](https://beta.sfox.com) to create an API key. Contact us at <support@sfox.com> for assistance configuring and funding your sandbox account.
2. Sandbox hosts a subset of order books and liquidity does not reflect production. Sandbox supports all functionality except transfers.
   {% endhint %}

<table><thead><tr><th width="281">API</th><th>URL</th></tr></thead><tbody><tr><td><strong>REST API</strong></td><td><strong><code>https://api.staging.sfox.com</code></strong></td></tr><tr><td><strong>WebSocket API</strong></td><td><strong><code>wss://ws.staging.sfox.com/ws</code></strong></td></tr></tbody></table>

## Availability Zones

The infrastructure for the sFOX platform is hosted in **US-EAST-1 (AWS)** within multiple availability zones:

* use1-az6
* use1-az1
* use1-az2


# Integration Options

Connect offers two options for streamlines flows.

## API (backend flow)

Automate all interactions with sFOX using the sFOX Connect API

{% content-ref url="/pages/uNE3QRhQ3rD6U6LaDQOV" %}
[REST API](/connect/rest-api/rest-endpoints)
{% endcontent-ref %}

{% content-ref url="/pages/X2NwSb3SpynHCChfDWeJ" %}
[WebSocket API](/connect/websocket-api/websocket-feeds)
{% endcontent-ref %}

## SSO (hybrid flow)

{% hint style="info" %}
SSO integrations are best used by partners aiming to utilize sFOX's front end.&#x20;

**However, please note that currently, the sFOX front end does not support co-branding.**
{% endhint %}

Embed an sFOX Connect iframe into your application and authenticate your users through IdP initiated SSO. Learn more about SSO integrations:

{% content-ref url="/pages/QIm8caaym7W6MQ1afBfj" %}
[Single Sign-On](/connect/single-sign-on/overview)
{% endcontent-ref %}


# Release Notes

#### 11 -December-2025

* The response schema for the [Get End User](/connect/rest-api/end-users/get-end-user) endpoint has been updated
* sFOX has released a new [Submit Documents API](/connect/rest-api/end-users/submit-documents/submit-documents-api)

#### 20-November-2025

As part of enhancing sFOX's KYC/KYB process, the [Create End User](/connect/rest-api/end-users/create-end-user) now accepts new, optional attributes to specify end users' expected use and employment information:&#x20;

* `intermediary_status`
* `expected_transfer_volume`
* `expected_trade_volume`
* `employment_status`
* `industry`
* `occupation`
* `job_title`

#### 24-June-2025

* As part of sFOX's KYC/KYB process, the [Create End User](/connect/rest-api/end-users/create-end-user) endpoint includes new attributes to collect source of funds information: `source_of_funds` and `source_of_funds_other`. &#x20;
* Similarly, `source_of_funds` will be returned in `GET` requests when calling End User endpoints.


# Guides


# End User Onboarding & KYC

## Overview

There are 3 main steps in the Onboarding & KYC process:

1. End User Account Creation
2. Account Verification
3. Enhanced Due Diligence (EDD), if applicable

These steps are described below.

### Step 1: Account Creation

At this step you will collect the required KYC information for account creation from your users within your application. Then send this information to sFOX to create an account.&#x20;

{% hint style="info" %}
KYC information required for account information varies by the type of account you are creating (individual or business account). Reference the account type-specific guides for details.
{% endhint %}

<div align="center"><figure><img src="/files/4tsjvXDPO1BDJplQPTrC" alt="" width="135"><figcaption></figcaption></figure></div>

### Step 2: Verification

Verifying an end user account is the second step in the sFOX Connect API onboarding flow. Upon successfully creating an account, sFOX will send a verification OTP code directly to the email of the account. You will collect this code from your user and send it to sFOX for verification.

{% hint style="info" %}
Individual accounts are required to complete SMS OTP code verification in addition to the above.
{% endhint %}

<figure><img src="/files/ohGPHz7ZJuOGtOkNQQnG" alt="" width="375"><figcaption></figcaption></figure>

API interactions include:

* [Request an SMS or email code](/connect/rest-api/end-users/create-verification-code)
* [Verify an SMS or email code](/connect/rest-api/end-users/confirm-verification-code)
* [Get the account's verification requirements](/connect/rest-api/end-users)

After verification, the account will be able to link a bank, deposit, and gain access to sFOX trading and crypto features.

{% hint style="info" %}
**Note:** Individual accounts will need to verify both phone and email. Business/Corporate accounts will only need to verify email.
{% endhint %}

### Interactive Demo

{% embed url="<https://www.figma.com/proto/6mXQsQSDCMuWXSfbPbvjzA/SMS%2FEMAIL-Verification-Prototype?mode=design&node-id=10-4588&page-id=0:1&scaling=contain&starting-point-node-id=10:4588&t=XQfcFTtVYcmMSuDK-1&type=design>" fullWidth="false" %}

### Step 3: Monitor for and Complete Enhanced Due Diligence (EDD) Requests

In some cases, sFOX will require additional information about a user of your app beyond the initial account creation KYC information.

In these cases, an [EDD request](/connect/rest-api/end-users/get-edd-requests) will be triggered, which will specify which user needs to complete the request and the information required.

To complete the EDD request, collect the requested information from your user and return it to sFOX as an [EDD response](/connect/rest-api/end-users/create-edd-responses).

## Onboarding Guides

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Individuals</strong></td><td>Create an verify accounts for individual users of your application</td><td><a href="/pages/rM48Z8edg8kULpdfpze3">/pages/rM48Z8edg8kULpdfpze3</a></td></tr><tr><td><strong>Businesses</strong></td><td>Create an verify accounts for individual users of your application</td><td><a href="/pages/9YeXrmJBbA5CFsbYiyov">/pages/9YeXrmJBbA5CFsbYiyov</a></td></tr><tr><td><strong>Enhanced Due Diligence (EDD)</strong></td><td>Monitoring applied to potentially high-risk customers or transactions</td><td><a href="/pages/Ly8mxalaLgavh6Tflzw4">/pages/Ly8mxalaLgavh6Tflzw4</a></td></tr></tbody></table>


# Quick Start: Individual Accounts

{% hint style="success" icon="rocket-launch" %}
sFOX aims to provide a clear and seamless onboarding experience for our partners and end users alike. &#x20;

This guide is designed to provide helpful information related to our **new and improved** onboarding flow; giving partners increased transparecy as to the exact items that must be acted upon in order for their customers to be onboarded onto the sFOX platform.
{% endhint %}

## Overview

The onboarding flow onto the sFOX platform centers around two concepts: **tiers** and **requirements**.  Let's define these terms for ease of communication:

* **Tier**: the degree to which an account can engage on the sFOX platform as it relates to funding and trading activity.  At the moment, sFOX has two tiers: Tier 1 and Tier 2.  A Tier 2 account has an elevated level of engagement compared to Tier 1.
* **Requirements**: the items that must be satisfied to achieve a tier, classified as either `completed`, `current`, or `future` .

## Interacting with Tiers and Requirements

Partners interact with the sFOX platform via REST API and websocket messages to create an account and understand an account's onboarding progress. &#x20;

At a high level, it is a 3-step process to onboard an `individual` end user account as defined below:

<figure><img src="/files/imt9YsYXh1FzmOFZqLST" alt=""><figcaption></figcaption></figure>

### Step 1: Create the End User Account

Like any financial platform, a new end user will access a partner's website or mobile app and submit personally identifiable information (PII) used for know-your-customer (KYC) purposes.

Once the partner captures PII information from the end user, it should be sent via API to [create the account](https://docs.sfox.com/connect/rest-api/end-users/create-end-user) in the sFOX platform.

Note, sFOX does have required information needed to create the end user's account which is defined in the hyperlink above.

### Step 2: Observe Requirements

Based on the information provided to sFOX upon creating the end user's account, requirements will be evaluated and classified into one of three categories:

* **Current**: one or more requirements that must be satisfied to obtain the very next tier.  Generally, brand new accounts start at Tier 0 and work towards Tier 1. &#x20;
* **Completed**: one or more requirements that have already been satisfied.
* **Future**: one or more requirements that are "next up" after the `current` requirements have been satisfied in order for the account to obtain the next tier (Tier 2), if so desired.

### Requirements Needed for Tier 1 + Tier 2

Below are the requirements that must be satisfied to obtain Tier 1 and subsequently Tier 2.

{% hint style="info" %}
While US and non-US accounts must satisfy the same set of requirements, *how* each requirement is satisfied is slightly different based on the citizenship of the end user.
{% endhint %}

#### Tier 1 Requirements

<table><thead><tr><th width="245.53369140625">Requirement</th><th>How to Satisfy</th></tr></thead><tbody><tr><td>Email verification</td><td><a href="https://docs.sfox.com/connect/rest-api/end-users/create-verification-code">Request</a> and <a href="https://docs.sfox.com/connect/rest-api/end-users/confirm-verification-code">submit</a> OTP code</td></tr><tr><td>Phone Number verification</td><td><a href="https://docs.sfox.com/connect/rest-api/end-users/create-verification-code">Request</a> and <a href="https://docs.sfox.com/connect/rest-api/end-users/confirm-verification-code">submit</a> OTP code</td></tr><tr><td>Identity Information</td><td><strong>US End User</strong>: sFOX will attempt automatic verification; if automation is not successful must provide a <a href="https://docs.sfox.com/connect/rest-api/end-users/submit-documents/submit-documents-api">document upload</a><br><br><strong>Non-US End User</strong>: must provide a document upload</td></tr><tr><td>Proof of address</td><td><strong>US End User</strong>: sFOX will attempt automatic verification; if automation is not successful must provide a <a href="https://docs.sfox.com/connect/rest-api/end-users/submit-documents/submit-documents-api">document upload</a><br><br><strong>Non-US End User</strong>: must provide a document upload</td></tr></tbody></table>

#### Tier 2 Requirements

To obtain Tier 2 for a given account, Tier 1 requirements must be satisfied and the below information must be provided:

<table><thead><tr><th width="245.53369140625">Requirement</th><th>How to Satisfy</th></tr></thead><tbody><tr><td>Source of Funds</td><td>Either on the POST during <a href="https://docs.sfox.com/connect/rest-api/end-users/create-end-user">initial account creation</a> or a PATCH to <a href="https://docs.sfox.com/connect/rest-api/end-users/update-end-user">update the account</a> after initial account creation</td></tr><tr><td>Expected Use</td><td>Either on the POST during <a href="https://docs.sfox.com/connect/rest-api/end-users/create-end-user">initial account creation</a> or a PATCH to <a href="https://docs.sfox.com/connect/rest-api/end-users/update-end-user">update the account</a> after initial account creation</td></tr></tbody></table>

#### What is Source of Funds and Expected Use Information?

* **Source of funds:** Primary source for the funds being transferred to the account
* **Employment status:** End user’s employment status
* **Occupation:** End user’s primary occupation
* **Intermediary Status:** Is the end user receiving or sending funds on behalf of someone other than themselves?

#### Expected Use

* **Expected Transfer Volume:** Expected monthly USD notional amount to be transferred (sent / received)
* **Expected Trade Volume:** Expected monthly USD notional amount to be traded

{% hint style="info" %}
As a reminder, these attributes can be provided during [initial account creation](https://docs.sfox.com/connect/rest-api/end-users/create-end-user) or subsequently via [update end user](https://docs.sfox.com/connect/rest-api/end-users/update-end-user)
{% endhint %}

### Step 3: Monitor for Updates

It is important that partners subscribe to the [onboarding](https://docs.sfox.com/connect/websocket-api/end-users/users) websocket feed.  This ensures asynchronous updates - especially for requirements that are satisfied via document upload - are observed by the partner in a timely fashion.

For context, when a document is uploaded for the purpose of satisfying a requirement, the sFOX team will review the document and either accept it or not. &#x20;

The act of accepting a document will trigger the sFOX system to update the end user's requirements and emit a websocket message, thereby informing the partner of the update - and in many cases, incrementing the account's tier as well.

### Example

#### Newly Created Account - No Requirements Satisfied

Below is the response from sFOX for a new end user account - the end user's PII could **not** be verified automatically. &#x20;

As such, the end user (partner) must upload two documents: one to satisfy the `proof_of_address` requirement and another for the `identity_info` requirement.

Note the `future` requirement for `identity_verification`.  This requirement represents an *image* of a identity document (passport, etc) compared to the `identity_info` requirement, which is simply the information contained in many identity-type documents, such as first name, last name, etc. &#x20;

{% hint style="warning" %}
Note, the `future` requirements are not absolutely needed to be acted upon unless this end user wishes to be Tier 2. &#x20;

However, it is advisable that partners ask for source of funds and expected use information during initial onboarding for a more streamlined experience in the event Tier 2 is desired.
{% endhint %}

```
 "data": {
        "user_id": "client_id_100",
        "status": "PENDING",
        "tier": 0,
        "requirements": {
            "email": true,
            "sms": true,
            "current": [
                "email",
                "phone_number",
                "proof_of_address",
                "identity_info"
            ],
            "future": [
                "identity_verification",
                "proof_of_source_of_funds",
                "expected_use"
            ],
            "completed": []
        }
    }
```

#### Requirements are Satisfied - Email and Phone Number

As the account's email and phone number are verified via OTP code, the corresponding requirements will become satisfied. &#x20;

This progression is reflected in the [GET End User](https://docs.sfox.com/connect/rest-api/end-users/get-end-user) endpoint:

```
{
    "data": {
        "account_type": "individual",
        "account_role": "Client",
        "user_id": "client_id_100",
        "advisor_user_id": null,
        "email": "client@email.com",
        "first_name": "Craig",
        "last_name": "sFOX",
        "phone_number": "+12243998561",
        "tier": 0,
        "requests": [],
        "account_purpose": "investing",
        "account_purpose_other": null,
        "source_of_funds": null,
        "source_of_funds_other": null,
        "id": "126c381a-2c6d-11f1-97c3-0251c71a6fcb",
        "phone_country_code": "US",
        "intermediary_status": false,
        "expected_transfer_volume": null,
        "expected_trade_volume": null,
        "individual": {
            "dob": "1988-10-01",
            "residential_country_code": "US",
            "residential_address": "1700 Main Ave",
            "residential_city": "Chicago",
            "residential_state": "IL",
            "residential_postal_code": "60622",
            "id_type": "ssn",
            "id_number": "*****6789",
            "id_country_code": "US",
            "employment_status": null,
            "industry": null,
            "occupation": null,
            "job_title": null
        },
        "status": "PENDING",
        "requirements": {
            "email": false,
            "sms": true,
            "current": [
                "proof_of_address",
                "identity_info"
            ],
            "future": [
                "identity_verification",
                "proof_of_source_of_funds",
                "expected_use"
            ],
            "completed": [
                "email",
                "phone_number"
            ]
        }
    }
}
```

### Wrapping Up

This quick start guide is not intended to be fully comprehensive, but rather demonstrate the paradigm of how `tiers` and `requirements` are used in-tandem to provide transparency and "next steps" for partners and end users alike.

For further questions, please do not hesitate to contact the sFOX team to get you up and running.


# Individuals

{% hint style="info" %}
This page is considered a "legacy" onboarding artifact.  For new partners, please see the [Quick Start: Individual Accounts](/connect/introduction/guides/onboarding/quick-start-individual-accounts) guide instead.
{% endhint %}

## Overview

The following steps are necessary to create an individual end user account and provide required documentation to enable transacting as quickly as possible.&#x20;

1. [Create an Individual End User](#create-individual-end-user)
2. [Complete OTP Code Verification](#otp-code-verification-if-applicable) (if applicable)
3. [Submit ID Documentation](#id-verification)

The above steps can be represented in a flowchart:

<figure><img src="/files/88odcpoSVlGBwTfiQPBg" alt=""><figcaption></figcaption></figure>

### Additional Requirements

While the above steps are sufficient to complete onboarding and enable transacting for a majority of end users, sFOX may require additional information for certain individuals in certain scenarios.  These scenarios are defined in the sections below:

* [High Risk Individuals](#high-risk-requirements)
* [Proof of Address](#proof-of-address-documentation)

### Best Practices

Finally, each partner will design their own unique and exciting experience for their end users.  In a general sense, sFOX is happy to provide best practices for integrating with the Connect platform.

[Recommended Best Practices](#best-practices-1)

***

## Onboard an Individual End User

{% stepper %}
{% step %}

### Create Individual End User

The following attributes are required when creating a new individual end user.

* **Name**: first name and last name
* **Address**: Primary residence (street address, city, postal code, state/province, country)
* **Email Address:** user's email address, used in the onboarding process while verifying OTP code
* **Phone Number:** user's phone number, used in the onboarding process while verifying OTP code
* **Date of Birth:** user's date of birth
* **National Identity Number**
  * U.S. Residents: Social Security Number (SSN)
  * Non-U.S. Residents: Passport number and issuing country
* **Account Purpose**: The primary intended use of the account

Create a new end user by submitting a [Create End User](/connect/rest-api/end-users/create-end-user) request.

{% tabs %}
{% tab title="U.S. End User" %}
{% code title="Request" overflow="wrap" lineNumbers="true" expandable="true" %}

```bash
curl --location 'https://api.sfox.com/v1/enterprise/register-account' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ${ENTERPRISE_API_KEY}' \
--data-raw '{
    "user_id": "<specify a unique id>",
    "account_type": "individual",
    "account_role": "client",
    "first_name": "John",
    "last_name": "Doe",
    "email": "email@example.com",
    "phone_country_code": "US",
    "phone_number": "+19171119999",
    "account_purpose": "investing",
    "source_of_funds": "employment",
    "source_of_funds_other": null,
    "advisor_user_id": null,
    "individual": {
        "dob": "1990-10-15",
        "residential_country_code": "US",
        "residential_address": "123 Main St",
        "residential_city": "Los Angeles",
        "residential_state": "CA",
        "residential_postal_code": "90403",
        "id_type": "ssn",
        "id_number": "XXXXXXXXX",
        "id_country_code": "US"
    }
}'
```

{% endcode %}
{% endtab %}

{% tab title="Non-U.S. End User" %}
{% code title="Request" overflow="wrap" lineNumbers="true" expandable="true" %}

```bash
curl --location 'https://api.sfox.com/v1/enterprise/register-account' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ${ENTERPRISE_API_KEY}' \
--data-raw '{
    "user_id": "<specify a unique id>",
    "account_type": "individual",
    "account_role": "client",
    "first_name": "John",
    "last_name": "Doe",
    "email": "email@example.com",
    "phone_country_code": "FR",
    "phone_number": "+339171119999",
    "account_purpose": "investing",
    "source_of_funds": "employment",
    "source_of_funds_other": null,
    "advisor_user_id": null,
    "individual": {
        "dob": "1990-10-15",
        "residential_country_code": "FR",
        "residential_address": "123 Main St",
        "residential_city": "Paris",
        "residential_state": "IDF",
        "residential_postal_code": "75006",
        "id_type": "passport",
        "id_number": "XXXXXXXXX",
        "id_country_code": "FR"
    }
}'
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### End User Status & Requirements

Upon end user creation, sFOX will return a status (`status`) and list of requirements (`requirements`).&#x20;

{% hint style="info" %}
End user `status` and `requirements` can be retrieved at any time with a [Get End User](/connect/rest-api/end-users/get-end-user) request.
{% endhint %}

The `requirements`  object specifically relates to OTP code verification for the end user's email address and phone number codes as part of the onboarding process.&#x20;

* You should interpret the `requirements` object as *"is OTP code verification for email and/or phone number outstanding?"* &#x20;
* If `email` or `sms` = `true`, then that means the requirement is **not** met.  If `false` that means the requirement is no longer outstanding.

{% hint style="success" %}
**If `status` = `VERIFIED` the end user is approved and able to deposit and trade on sFOX.** [**Continue to Step 4: ID Verification**](#id-verification) **to complete onboarding and enable withdrawals.**<br>

*sFOX continuously monitors transaction activity. If certain patterns are observed, the end user may only be able to transact a limited amount.  In this case, an sFOX team member will reach out to you.*
{% endhint %}

{% tabs %}
{% tab title="Verified" %}
Example of an end user who has been approved and onboarded to sFOX:

{% code title="Response" overflow="wrap" lineNumbers="true" expandable="true" %}

```json
{
    "data": {
        "user_id": "example_individual_123",
        "status": "VERIFIED",
        "requirements": {
            "email": false,
            "sms": false
        }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Pending" %}
Example of an end user who has not confirmed email or phone number. The end user must complete [Step 3: OTP code verification](#otp-code-verification-if-applicable) before reaching a terminal status (verified or unsupported)

{% code title="Response" overflow="wrap" lineNumbers="true" expandable="true" %}

```json
{
    "data": {
        "user_id": "example_individual_123",
        "status": "Pending",
        "requirements": {
            "email": true,
            "sms": true
        }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Unsupported" %}
Example of an end user who has been rejected due to residing in a location that sFOX does not currently support:

{% code title="Response" overflow="wrap" lineNumbers="true" expandable="true" %}

```json
{
    "data": {
        "user_id": "example_individual_123",
        "status": "UNSUPPORTED",
        "requirements": {
            "email": false,
            "sms": false
        }
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### OTP Code Verification (if applicable)

If the end user's status = `Pending` and `requirements` object lists `email` and/or `sms` = `true` , the end user must complete OTP code verification. Follow these steps to complete OTP code verification:

**Step 3A: Trigger OTP Code**

Initiate an OTP verification code to the end user via a [Create Verification Code](/connect/rest-api/end-users/create-verification-code) request.

{% tabs %}
{% tab title="Email" %}
Initiate an OTP verification code to the end user's email address

{% code title="Request" overflow="wrap" lineNumbers="true" expandable="true" %}

```bash
curl -X POST \
-H "Authorization: Bearer ${ENTERPRISE_API_KEY}" \
--data '{ "type": "email" }'  \
'https://api.sfox.com/v1/enterprise/users/send-verification/${USER_ID}'
```

{% endcode %}
{% endtab %}

{% tab title="SMS" %}
Initiate an OTP verification code to the end user's phone number via SMS

{% code title="Request" overflow="wrap" lineNumbers="true" expandable="true" %}

```bash
curl -X POST \
-H "Authorization: Bearer ${ENTERPRISE_API_KEY}" \
--data '{ "type": "sms" }'  \
'https://api.sfox.com/v1/enterprise/users/send-verification/${user_id}'
```

{% endcode %}
{% endtab %}
{% endtabs %}

**Step 3B: Collect OTP Code from End User**

Collect the OTP code directly from your end user.

**Step 3C: Verify OTP Code**

Confirm the OTP verification code and complete the requirement by submitting the code collected from your end user to sFOX via a [Confirm Verification Code](/connect/rest-api/end-users/confirm-verification-code) request.

{% tabs %}
{% tab title="Email" %}
Confirm an email OTP verification code:

{% code title="Request" overflow="wrap" lineNumbers="true" expandable="true" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H "Authorization: Bearer ${ENTERPRISE_API_KEY}" \
  --data '{ "type": "email", "otp": "12345" }'  \
  "https://api.sfox.com/v1/enterprise/users/verify/${USER_ID}"
```

{% endcode %}
{% endtab %}

{% tab title="SMS" %}
Confirm a SMS OTP verification code

{% code title="Request" overflow="wrap" lineNumbers="true" expandable="true" %}

```bash
curl -X POST \
  -H 'Content-type: application/json' \
  -H "Authorization: Bearer ${ENTERPRISE_API_KEY}" \
  --data '{ "type": "sms", "otp": "12345" }'  \
  "https://api.sfox.com/v1/enterprise/users/verify/${USER_ID}"
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### ID Verification

Submit a photo of a government-issued photo ID (e.g. driver’s license or passport) in a [Submit Document](/connect/rest-api/end-users/submit-documents) API request.

{% hint style="info" %}
sFOX recommends collecting and submitting IDs for each individual end user during **initial onboarding** in order to both maximize the verification rate and functionality available in the fewest steps.

If ID documentation is not submitted during initial onboarding, sFOX will request this information in the form of an EDD request for the end user. [Learn more about Enhanced Due Diligence (EDD) here](/connect/introduction/guides/onboarding/enhanced-due-diligence-edd).
{% endhint %}

{% code title="Request" overflow="wrap" lineNumbers="true" expandable="true" %}

```bash
curl --location 'https://api.sfox.com/v1/enterprise/ddq/upload' \
--header 'Authorization: Bearer ${ENTERPRISE_API_KEY}' \
--form 'files=@"${PATH_TO_FILE}"' \
--form 'user_id="${USER_ID}"' \
--form 'file_types="{\"${FILE_NAME}\":\"${DOCUMENT_TYPE}\"}"'
```

{% endcode %}
{% endstep %}
{% endstepper %}

***

## High-Risk Requirements

An end user may be considered "high risk" due to certain conditions.  Example of such conditions include, but are not limited to:

* Residing in a high-risk geographical region
* 65 years of age or older
* High-volume transactors

In these cases, sFOX will request some or all of the following information about the end user’s source of funds and expected use in the form of an EDD request for the end user. [Learn more about Enhanced Due Diligence (EDD) here](/connect/introduction/guides/onboarding/enhanced-due-diligence-edd).

#### Source of Funds

* **Source of funds:** Primary source of funds being transferred to the account
  * sFOX recommends specifying source of funds upon end user creation to minimize requests for additional information later on
* **Employment status:** End user’s employment status
* **Occupation:** End user’s primary occupation
* **Intermediary Status:** Is the end user receiving or sending funds on behalf of someone other than themselves?

#### Expected Use

* **Expected Monthly Transfer Volume:** Expected monthly USD notional amount to be transferred (sent / received)

{% hint style="info" %}
While an EDD request is in-flight, there is no loss of functionality for the end user
{% endhint %}

## Monitor for Additional Requirements

As noted above, sFOX may require additional information about an end user beyond the initial account creation information. &#x20;

{% hint style="warning" %}
It is important your application monitors for EDD requests.  For additional details regarding EDD and completing EDD requests, see our [Enhanced Due Diligence (EDD) guide](/connect/introduction/guides/onboarding/enhanced-due-diligence-edd).
{% endhint %}

## Proof of Address Documentation

Similar to the high-risk individual scenario, sFOX may require proof of address for certain end users; examples where Proof of Address will be requested include:

* Conflicting location data: ID and address in different regions
* Unable to validate location: sFOX was unable to validate the end user’s residential address
* As needed: when a high risk individual has not previously fulfilled this requirement

{% hint style="info" %}
Coming Soon: Improvements to enhance visibility into additional requirements and self-service options for fulfilling them.&#x20;
{% endhint %}

***

## Best Practices

How you onboard end users can have a significant impact on onboarding conversion:

* Rate: the percentage of end users who successfully complete onboarding
* Time: the amount of time required for an end user to successfully complete onboarding
* Steps: the number of steps your end user and application must complete before funding and trading

To that end, sFOX would like to provide a series of recommendations and best practices below:

### 1. Collecting KYC Information from End Users

In addition to the [basic information](#create-individual-end-user) required to create an end user, sFOX recommends collecting the following from individual end users during your onboarding process:

* [Source of Funds](#source-of-funds)
* [ID Documentation](#id-verification)

In doing so, you avoid having to collect additional information from the end user later on that may be required by sFOX is certain cases.&#x20;

### 2. Creating End Users

Include optional information such as the following when [creating an end user](#individual-end-user-example):

* Source of Funds (`source_of_funds`)

In doing so, you can reduce the likelihood of requests for additional information after the end user is created.&#x20;

### 3. Link a Bank Accounts via Plaid

After an end user has reached `status`=`VERIFIED`, we highly recommend directing the end user to [link a bank account via Plaid](/connect/rest-api/payments/create-bank-account-plaid) for the following reasons:

* Proof of Address: Linking a bank account via Plaid may fulfill the proof of address requirement for the end user resulting in faster onboarding in fewer steps and avoiding document collection requirements for fulfilling proof of address, which tends to be low conversion.
* Account Funding / ACH: U.S. bank accounts linked via Plaid instantly gain access to the ACH payment rail whereas bank accounts linked via API are required to complete micro-deposit verification before ACH may be enabled, which can take up to 5 business days to complete.

### 4. Submit ID Documents

After an end user has reached `status`=`VERIFIED`, we recommend collecting and [submitting ID documents](/connect/rest-api/end-users/submit-documents) rather than waiting for an EDD request for them.


# Businesses

## Step 1: Business Account Creation

At this step you will collect the required KYC information for account creation from your users within your application. Then send this information to sFOX to create an account.&#x20;

### Create Business Account

{% content-ref url="/pages/wkNmtRoP8TnEPRcONW4u" %}
[Create End User](/connect/rest-api/end-users/create-end-user)
{% endcontent-ref %}

## Step 2: Verification

Upon successfully creating an account, sFOX will send OTP codes directly to the email of the account. You will collect this code from your user and send it to sFOX for verification.

{% hint style="info" %}
Business accounts are only required to complete email OTP code verification.
{% endhint %}

### Step 2(a): Email Verification

#### Request Email OTP Code

Trigger sending an OTP verification code to the email of your user's account. Then collect this code from your user in your application.

{% content-ref url="/spaces/SqieKWDmfvEO9Y0sbJUb/pages/XNT45pXgriVUgj6rlFv5" %}
[Create Verification Code](/connect/rest-api/end-users/create-verification-code)
{% endcontent-ref %}

#### Verify Email OTP Code

Once you have collected the OTP code from your user, send it to sFOX to complete email verification.

{% content-ref url="/spaces/SqieKWDmfvEO9Y0sbJUb/pages/ikk27VB9fUmTgYG5FV3L" %}
[Confirm Verification Code](/connect/rest-api/end-users/confirm-verification-code)
{% endcontent-ref %}

### Step 3: Monitor for and Complete Enhanced Due Diligence (EDD) Requests

In some cases, sFOX will require additional information about a user of your app beyond the initial account creation KYC information.

In these cases, an EDD request will be triggered, which will specifiy which user needs to complete the request and the information required.

You will then share this information with sFOX to complete the EDD request




---

[Next Page](/llms-full.txt/1)

