Account & Wallet - Private

GET /v3/account

Get account information

circle-info

Calling this endpoint using an API key pair linked to the parent account with the parameter "subAcc" allows the caller to include additional sub-accounts in the response. This feature does not work when using API key pairs linked to a sub-account.

chevron-rightCurehashtag

Request

GET v3/account?subAcc={subAcc},{subAcc}

Successful response format

{
    "success": true,
    "data": [
        {
            "accountId": "21213",
            "name": "main",
            "accountType": "PORTFOLIO",
            "balances": [
                {
                    "asset": "OX",
                    "total": "100000",
                    "available": "100000",
                    "reserved": "0",
                    "lastUpdatedAt": "1593627415234"
                },
                {
                    "asset": "USDT",
                    "total": "1585.890",
                    "available": "325.890",
                    "reserved": "1260.0",
                    "lastUpdatedAt": "1593627415123"
                }
            ],
            "positions": [
                {
                    "marketCode": "BTC-USD-SWAP-LIN", 
                    "baseAsset": "BTC", 
                    "counterAsset": "USD", 
                    "position": "0.00030", 
                    "entryPrice": "43976.700", 
                    "markPrice": "43788.1", 
                    "positionPnl": "-5.6580", 
                    "estLiquidationPrice": "2.59", 
                    "lastUpdatedAt": "1637876701404",
                }
            ],
            "collateral": "100000.0",
            "notionalPositionSize": "1313.643",
            "portfolioVarMargin": "131.3643",
            "maintenanceMargin": "65.68215",
            "marginRatio": "0.065682",
            "riskRatio": "761.241829",
            "liquidating": false,
            "feeTier": "2",
            "createdAt": "1611665624601"
        }
    ]
}}
chevron-rightPythonhashtag
import os
import requests
import hmac
import hashlib
import base64
from dotenv import load_dotenv
from datetime import datetime
import time

load_dotenv()

def get_account_info(sub_accounts=None):
    api_key = os.getenv('API_KEY')
    secret_key = os.getenv('API_SECRET').encode('utf-8')
    ts = datetime.utcnow().isoformat()
    nonce = str(int(time.time() * 1000))
    method = "/v3/account"
    api_url = "api.ox.fun"
    
    # Prepare the subAcc parameter if sub_accounts are provided
    sub_acc_param = f'subAcc={",".join(sub_accounts)}' if sub_accounts else ''
    body = sub_acc_param

    msg_string = f'{ts}\n{nonce}\nGET\n{api_url}\n{method}\n{body}'
    sign = base64.b64encode(hmac.new(secret_key, msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')

    headers = {
        'Content-Type': 'application/json',
        'AccessKey': api_key,
        'Timestamp': ts,
        'Signature': sign,
        'Nonce': nonce
    }

    try:
        # Construct the URL with the subAcc parameter if it exists
        url = f'https://{api_url}{method}'
        if sub_acc_param:
            url += f'?{sub_acc_param}'
        
        response = requests.get(url, headers=headers)

        # Print the raw response content for debugging
        print("Raw Response Content:", response.content)

        # Check if the response is JSON
        if response.headers.get('Content-Type') == 'application/json':
            response_data = response.json()
            if response_data.get('success'):
                return response_data.get('data')
            else:
                print('Failed to fetch account data')
        else:
            print('Response is not in JSON format')

    except requests.exceptions.RequestException as error:
        print('Error making API request:', error)

# Example usage
response = get_account_info()

print(response)
chevron-rightJavascripthashtag
require('dotenv').config();
const axios = require('axios');
const CryptoJS = require("crypto-js");

async function getAccountInfo(subAccounts = []) {
  const apiKey = process.env.API_KEY;
  const secretKey = process.env.API_SECRET;
  const timestamp = new Date().toISOString();
  const nonce = Math.random().toString(36).substring(2);
  const verb = 'GET';
  const path = 'api.ox.fun';
  const method = '/v3/account';
  const subAccParam = subAccounts.length ? `subAcc=${subAccounts.join(',')}` : '';
  const body = subAccParam;

  const msgString = `${timestamp}\n${nonce}\n${verb}\n${path}\n${method}\n${body}`;
  const sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(msgString, secretKey));

  try {
    let url = `https://${path}${method}`;
    if (subAccParam) {
      url += `?${subAccParam}`;
    }

    const response = await axios.get(url, {
      headers: {
        'Content-Type': 'application/json',
        'AccessKey': apiKey,
        'Timestamp': timestamp,
        'Signature': sign,
        'Nonce': nonce
      }
    });

    console.log("Raw Response Content:", response.data);

    if (response.data.success) {      
      return response.data.data;
    } else {
      console.error('Failed to fetch account data');
    }
  } catch (error) {
    console.error('Error making API request:', error.response ? error.response.data : error.message);
  }
}

// Example usage
response = getAccountInfo();
console.log(response);
Request Parameter
Type
Required
Description

subAcc

STRING

NO

Name of sub account. If no subAcc is given, then the response contains only the account linked to the API-Key. Multiple subAccs can be separated with a comma, maximum of 10 subAccs, e.g. subone,subtwo

Response Field
Type
Description

accountId

STRING

Account ID

name

STRING

Account name

accountType

STRING

Account type LINEAR, STANDARD, PORTFOLIO

balances

LIST of dictionaries

asset

STRING

Asset name

total

STRING

Total balance

available

STRING

Available balance

reserved

STRING

Reserved balance

lastUpdatedAt

STRING

Last balance update timestamp

positions

LIST of dictionaries

Positions - only returned if the account has open positions

marketCode

STRING

Market code

baseAsset

STRING

Base asset

counterAsset

STRING

Counter asset

position

STRING

Position size

entryPrice

STRING

Entry price

markPrice

STRING

Mark price

positionPnl

STRING

Position PNL

estLiquidationPrice

STRING

Estimated liquidation price

lastUpdatedAt

STRING

Last position update timestamp

marginBalance

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin. Isolated margin + Unrealized position PnL

maintenanceMargin

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin

marginRatio

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin

leverage

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin

collateral

STRING

Total collateral balance

notionalPositionSize

STRING

Notional position size in OX

portfolioVarMargin

STRING

Initial margin

maintenanceMargin

STRING

Maintenance margin. The minimum amount of collateral required to avoid liquidation

marginRatio

STRING

Margin ratio. Orders are rejected/cancelled if the margin ratio reaches 50, and liquidation occurs if the margin ratio reaches 100

riskRatio

STRING

Ignore.

liquidating

BOOL

Available values: true and false

feeTier

STRING

Fee tier

createdAt

STRING

Timestamp indicating when the account was created

GET /v3/account/names

Get sub account information

circle-info

This endpoint can only be called using API keys paired with the parent account! Returns all active subaccounts.

chevron-rightCurlhashtag

Request

Successful response format

chevron-rightPythonhashtag
chevron-rightJavascripthashtag
Response Field
Type
Description

accountId

STRING

Account ID

name

STRING

Account name

GET /v3/wallet

Get account or sub-account wallet

circle-info

Calling this endpoint using an API key pair linked to the parent account with the parameter "subAcc" allows the caller to include additional sub-accounts in the response. This feature does not work when using API key pairs linked to a sub-account.

chevron-rightCurlhashtag

Request

Successful response format

chevron-rightPythonhashtag
chevron-rightJavascripthashtag
Request Parameter
Type
Required
Description

subAcc

STRING

NO

Max 5

type

STRING

NO

DEPOSIT, WITHDRAWAL, etc, default return all, most recent first

limit

LONG

NO

Default 200, max 500

startTime

LONG

NO

Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other. startTime is INCLUSIVE

endTime

LONG

NO

Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other. endTime is INCLUSIVE

Response Field
Type
Description

accountId

STRING

Account ID

name

STRING

Account name

walletHistory

LIST of dictionaries

id

STRING

A unique ID

amount

STRING

Amount

asset

STRING

Asset name

type

STRING

createdAt/lastUpdatedAt

STRING

Millisecond timestamp created time or updated time

POST /v3/transfer

Sub-account balance transfer β€” TODO

circle-info

Transferring funds between sub-accounts is restricted to API keys linked to the parent account.

chevron-rightCurlhashtag

Request

Successful response format

chevron-rightPythonhashtag
chevron-rightJavascripthashtag
Request Parameter
Type
Required
Description

asset

STRING

YES

quantity

STRING

YES

fromAccount

STRING

YES

toAccount

STRING

YES

Response Field
Type
Description

asset

STRING

quantity

STRING

fromAccount

STRING

toAccount

STRING

transferredAt

STRING

Millisecond timestamp

GET /v3/transfer

Sub-account balance transfer history

circle-info

API keys linked to the parent account can get all account transfers, while API keys linked to a sub-account can only see transfers where the sub-account is either the "fromAccount" or "toAccount".

chevron-rightCurlhashtag

Request

Successful response format

chevron-rightPythonhashtag
chevron-rightJavascripthashtag

Request Parameter
Type
Required
Description

asset

STRING

NO

Default all assets

limit

LONG

NO

Default 50, max 200

startTime

LONG

NO

Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other. startTime is INCLUSIVE

endTime

LONG

NO

Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other. endTime is INCLUSIVE

Response Field
Type
Description

asset

STRING

quantity

STRING

fromAccount

STRING

toAccount

STRING

id

STRING

status

STRING

transferredAt

STRING

Millisecond timestamp

GET /v3/balances

circle-info

Calling this endpoint using an API key pair linked to the parent account with the parameter "subAcc" allows the caller to include additional sub-accounts in the response. This feature does not work when using API key pairs linked to a sub-account.

chevron-rightCurlhashtag

Request

Successful response format

chevron-rightPythonhashtag
chevron-rightJavascripthashtag
Request Parameter
Type
Required
Description

asset

STRING

NO

Default all assets

subAcc

STRING

NO

Name of sub account. If no subAcc is given, then the response contains only the account linked to the API-Key. Multiple subAccs can be separated with a comma, maximum of 10 subAccs, e.g. subone,subtwo

Response Field
Type
Description

accountId

STRING

Account ID

name

STRING

The parent account is named "main" and comes first

balances

LIST of dictionaries

asset

STRING

Asset name

total

STRING

Total balance (available + reserved)

available

STRING

Available balance

reserved

STRING

Reserved balance

lastUpdatedAt

STRING

Timestamp of updated at

GET /v3/positions

Returns position data

chevron-rightCurlhashtag

Request

Successful response format

chevron-rightPythonhashtag
chevron-rightJavascripthashtag
circle-info

Calling this endpoint using an API key pair linked to the parent account with the parameter "subAcc" allows the caller to include additional sub-accounts in the response. This feature does not work when using API key pairs linked to a sub-account. Returns an empty array [] when no positions were found

Request Parameter
Type
Required
Description

marketCode

STRING

NO

Default all markets

subAcc

STRING

NO

Name of sub account. If no subAcc is given, then the response contains only the account linked to the API-Key. Multiple subAccs can be separated with a comma, maximum of 10 subAccs, e.g. subone,subtwo

Response Fields
Type
Description

accountId

STRING

Account ID

name

STRING

The parent account is named "main" and comes first

positions

LIST of dictionaries

marketCode

STRING

Contract symbol, e.g. 'BTC-oUSD-SWAP-LIN'

baseAsset

STRING

counterAsset

STRING

position

STRING

Position size, e.g. '0.94'

entryPrice

STRING

Average entry price

markPrice

STRING

positionPnl

STRING

Postion profit and lost

estLiquidationPrice

STRING

Estimated liquidation price, return 0 if it is negative(<0)

lastUpdated

STRING

Timestamp when position was last updated

marginBalance

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin. Isolated margin + Unrealized position PnL

maintenanceMargin

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin

marginRatio

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin

leverage

STRING

[Currently Unavailable] Appears in the position section only for positions using isolated margin

GET /v3/funding

Get funding payments by marketCode and sorted by time in descending order.

chevron-rightCurlhashtag

Request

SUCCESSFUL RESPONSE

chevron-rightPythonhashtag
chevron-rightJavascripthashtag

Request Parameters
Type
Required
Description

marketCode

STRING

NO

e.g. BTC-oUSD-SWAP-LIN

limit

LONG

NO

default is 200, max is 500

startTime

LONG

NO

Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other. startTime is INCLUSIVE

endTime

LONG

NO

Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other. endTime is EXCLUSIVE

Response Fields
Type
Description

id

STRING

A unique ID

marketCode

STRING

Market code

payment

STRING

Funding payment

fundingRate

STRING

Funding rate

position

STRING

Position

indexPrice

STRING

index price

createdAt

STRING

Timestamp of this response

Last updated