OX.FUN
TradeSupport
  • 🏠OX.FUN
  • OX.FUN DOCS
    • πŸ“ˆPerps
    • πŸ“ŠStrategies
    • πŸ‚OX Coin
    • πŸ‚Seasons
    • πŸ“©Referral
  • Page
  • API
    • βš™οΈOX FUN API
    • πŸ”‘API Key Management
    • ☁️Websocket API
      • Authentication
      • Session Keep Alive
      • Order Commands
        • Place Limit Order
        • Place Market Order
        • Place Stop Limit Order
        • Place Stop Market Order
        • Place Batch Market Order
        • Cancel Order
        • Cancel Batch Order
        • Modify Order
        • Modify Batch Orders
      • Subscriptions - Private
        • Balance Channel
        • Position Channel
        • Order Channel
          • Order Opened
          • Order Closed
          • Order Closed Failure
          • Order Modified
          • Order Modified Failure
          • Order Matched
      • Subscriptions - Public
        • Fixed Size Order Book
        • Full Order Book
        • Incremental Order Book
        • Best Bid/Ask
        • Trade
        • Ticker
        • Candles
        • Liquidation RFQ
        • Market
      • Other Responses
      • Error Codes
        • Curl Error Codes
    • πŸ”ŒREST API V3
      • Account & Wallet - Private
      • Deposits & Withdrawals - Private
      • Market Data - Public
      • Orders - Private
      • Trades - Private
  • πŸ”—External
    • πŸ’§Aerodrome Pool
    • πŸ”΅Trade on Uniswap (Base)
    • Trade on Solana
    • 🦎CoinGecko
    • API Code Examples
  • πŸ”—SOCIALS
    • πŸ‚OX.FUN
    • Discord
    • Twitter
Powered by GitBook
On this page
  • GET /v3/orders/status
  • GET /v3/orders/working
  • POST /v3/orders/place
  • DELETE /v3/orders/cancel
  • DELETE /v3/orders/cancel-all
  1. API
  2. REST API V3

Orders - Private

GET /v3/orders/status

Get latest order status

CANCELED orders are not in the orderbook, the remainQuantity in the CANCELED orders is historical remaining quantity

Curl

Request

GET /v3/orders/status?orderId={orderId}&clientOrderId={clientOrderId}

Successful response format

{
    "success": true,
    "data": {
        "orderId": "1000387920513",
        "clientOrderId": "1612249737434",
        "marketCode": "OX-USDT",
        "status": "FILLED",
        "side": "BUY",
        "price": "0.0200",
        "isTriggered": false,
        "remainQuantity": "0",
        "totalQuantity": "12",
        "cumulativeMatchedQuantity": "12",
        "avgFillPrice": "0.0200",
        "orderType": "LIMIT",
        "timeInForce": "GTC",
        "source": "11",
        "createdAt": "1655980336520",
        "lastModifiedAt": "1655980393780",
        "lastMatchedAt": "1655980622848"
    }
}

Python
import os
import requests
import hmac
import hashlib
import base64
import time
from dotenv import load_dotenv

load_dotenv()

def fetch_order_status(order_id=None, client_order_id=None):
    if not order_id and not client_order_id:
        raise ValueError("Either orderId or clientOrderId must be provided.")

    api_key = os.getenv('API_KEY')
    secret_key = os.getenv('API_SECRET').encode('utf-8')
    ts = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())
    nonce = str(int(time.time() * 1000))
    method = "/v3/orders/status"
    api_url = "api.ox.fun"

    query_string = f"orderId={order_id}" if order_id else f"clientOrderId={client_order_id}"
    msg_string = f"{ts}\n{nonce}\nGET\n{api_url}\n{method}\n{query_string}"

    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:
        response = requests.get(f"https://{api_url}{method}?{query_string}", headers=headers)
        response.raise_for_status()
        data = response.json()
        if data.get('success'):
            return data
        else:
            print('Failed to fetch order status')
    except requests.exceptions.RequestException as error:
        print('Error fetching order status:', error)

# Example usage
order_status = fetch_order_status(order_id="111111111111")
print(order_status)
Javascript
const axios = require('axios');
const crypto = require('crypto');
require('dotenv').config();

async function fetchOrderStatus(orderId = null, clientOrderId = null) {
    if (!orderId && !clientOrderId) {
        throw new Error("Either orderId or clientOrderId must be provided.");
    }

    const apiKey = process.env.API_KEY;
    const secretKey = process.env.API_SECRET;
    const ts = new Date().toISOString().split('.')[0] + 'Z';
    const nonce = Date.now().toString();
    const method = "/v3/orders/status";
    const apiUrl = "api.ox.fun";

    const queryString = orderId ? `orderId=${orderId}` : `clientOrderId=${clientOrderId}`;
    const msgString = `${ts}\n${nonce}\nGET\n${apiUrl}\n${method}\n${queryString}`;

    const sign = crypto.createHmac('sha256', secretKey)
        .update(msgString)
        .digest('base64');

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

    try {
        const response = await axios.get(`https://${apiUrl}${method}?${queryString}`, { headers });
        const data = response.data;
        if (data.success) {
            return data;
        } else {
            console.log('Failed to fetch order status');
        }
    } catch (error) {
        console.error('Error fetching order status:', error.response ? error.response.data : error.message);
    }
}

// Example usage
fetchOrderStatus(orderId="111111111111111111").then(status => console.log(status));
Request Parameter
Type
Required
Description

orderId

LONG

YES if no clientOrderId

Order ID

clientOrderId

LONG

YES if no orderId

Client assigned ID to help manage and identify orders with max value 9223372036854775807

Response Field
Type
Description

orderId

STRING

Order ID

clientOrderId

STRING

Client assigned ID to help manage and identify orders with max value 9223372036854775807

marketCode

STRING

Market code

status

STRING

Available values: CANCELED, OPEN, PARTIAL_FILL, FILLED

side

STRING

Side of the order, BUY or SELL

price

STRING

Price or limit price in the case of a STOP order

stopPrice

STRING

Trigger price for a STOP order

amount

STRING

Amount (only allow amount field when market is spot and direction is BUY)

displayQuantity

STRING

triggerType

STRING

isTriggered

BOOL

true for a STOP order

remainQuantity

STRING

Remaining quantity

totalQuantity

STRING

Total quantity

cumulativeMatchedQuantity

STRING

Cumulative quantity of the matches

avgFillPrice

STRING

Average of filled price

fees

LIST of dictionaries

Overall fees with instrument ID, if you don't hold enough OX to cover the fee then USDT will be charged instead

orderType

STRING

Type of the order, availabe values: MARKET, LIMIT, STOP_LIMIT,STOP_MARKET

timeInForce

STRING

Client submitted time in force.

  • GTC (Good-till-Cancel) - Default

  • IOC (Immediate or Cancel, i.e. Taker-only)

  • FOK (Fill or Kill, for full size)

  • MAKER_ONLY (i.e. Post-only)

  • MAKER_ONLY_REPRICE (Reprices order to the best maker only price if the specified price were to lead to a taker trade)

source

STRING

Source of the request, available values: 0, 2, 10, 11, 13, 22, 31, 32, 33, 101, 102, 103, 104, 108, 111, 150.

Enumeration: 0: GUI, 2: Borrow, 11: REST, 13: Websocket, 22: Delivery, 31: Physical settlement, 32: Cash settlement, 33: transfer, 101: Automatic borrow, 102: Borrow position liquidation, 103: Position liquidation, 104: Liquidation revert, 108: ADL, 111: Automatic repayment, 150: BLP assignment

createdAt

STRING

Millisecond timestamp of the order created time

lastModifiedAt

STRING

Millisecond timestamp of the order last modified time

lastMatchedAt

STRING

Millisecond timestamp of the order last matched time

canceledAt

STRING

Millisecond timestamp of the order canceled time

GET /v3/orders/working

Returns all the open orders of the account connected to the API key initiating the request.

Curl

Request

GET /v3/orders/working?marketCode={marketCode}&orderId={orderId}&clientOrderId={clientOrderId}

Successful response format

{
  "success": True,
  "data": [
      {
        "orderId": "1000026408953",
        "clientOrderId": "1",
        "marketCode": "BTC-USDT",
        "status": "OPEN",
        "side": "BUY",
        "price": "1000.0",
        "isTriggered": True,
        "quantity": "10.0",
        "remainQuantity": "10.0",
        "matchedQuantity": "0.0",
        "orderType": "LIMIT",
        "timeInForce": "GTC",
        "source": "11",
        "createdAt": "1680113440852",
        "lastModifiedAt": "1680113440875"
      }
  ]
}
Python
import os
import requests
import hmac
import hashlib
import base64
import time
from dotenv import load_dotenv

load_dotenv()

def fetch_working_orders(market_code, order_id=None, client_order_id=None):
    api_key = os.getenv('API_KEY')
    secret_key = os.getenv('API_SECRET').encode('utf-8')
    ts = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())
    nonce = str(int(time.time() * 1000))
    method = "/v3/orders/working"
    api_url = "api.ox.fun"

    query_string = f"marketCode={market_code}"
    if order_id:
        query_string += f"&orderId={order_id}"
    if client_order_id:
        query_string += f"&clientOrderId={client_order_id}"

    msg_string = f"{ts}\n{nonce}\nGET\n{api_url}\n{method}\n{query_string}"

    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:
        response = requests.get(f"https://{api_url}{method}?{query_string}", headers=headers)
        response.raise_for_status()        
        data = response.json()
        if data.get('success'):
            return data
        else:
            print('Failed to fetch working orders')
    except requests.exceptions.RequestException as error:
        print('Error fetching working orders:', error)

# Example usage
orders = fetch_working_orders("BTC-USD-SWAP-LIN", order_id=None, client_order_id=None)
print(orders)
Javascript
const axios = require('axios');
const crypto = require('crypto');
require('dotenv').config();

async function fetchWorkingOrders(marketCode, orderId = null, clientOrderId = null) {
    const apiKey = process.env.API_KEY;
    const secretKey = process.env.API_SECRET;
    const ts = new Date().toISOString().split('.')[0] + 'Z';
    const nonce = Date.now().toString();
    const method = "/v3/orders/working";
    const apiUrl = "api.ox.fun";

    let queryString = `marketCode=${marketCode}`;
    if (orderId) {
        queryString += `&orderId=${orderId}`;
    }
    if (clientOrderId) {
        queryString += `&clientOrderId=${clientOrderId}`;
    }

    const msgString = `${ts}\n${nonce}\nGET\n${apiUrl}\n${method}\n${queryString}`;

    const sign = crypto.createHmac('sha256', secretKey)
        .update(msgString)
        .digest('base64');

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

    try {
        const response = await axios.get(`https://${apiUrl}${method}?${queryString}`, { headers });
        const data = response.data;
        if (data.success) {
            return data;
        } else {
            console.log('Failed to fetch working orders');
        }
    } catch (error) {
        console.log('Error fetching working orders:', error);
    }
}

// Example usage
fetchWorkingOrders("BTC-USD-SWAP-LIN").then(orders => console.log(orders));
Request Parameter
Type
Required
Description

marketCode

STRING

NO

default most recent orders first

orderId

LONG

NO

Client assigned ID to help manage and identify orders

clientOrderId

LONG

NO

Client assigned ID to help manage and identify orders with max value 9223372036854775807

Response Field
Type
Description

orderId

STRING

Order ID

clientOrderId

STRING

Client assigned ID to help manage and identify orders with max value 9223372036854775807

marketCode

STRING

Market code

status

STRING

Available values: OPEN, PARTIALLY_FILLED

side

STRING

Side of the order, BUY or SELL

price

STRING

Price or limit price in the case of a STOP order

stopPrice

STRING

Trigger price for a STOP order

isTriggered

BOOL

Returns true if a STOP order has been triggered

quantity

STRING

Quantity

remainQuantity

STRING

Remaining quantity

matchedQuantity

STRING

Matched Quantity

amount

STRING

Amount (only allow amount field when market is spot and direction is BUY)

displayQuantity

STRING

triggerType

STRING

orderType

STRING

Type of the order, availabe values: MARKET, LIMIT, STOP_LIMIT,STOP_MARKET

timeInForce

STRING

Client submitted time in force.

  • GTC (Good-till-Cancel) - Default

  • IOC (Immediate or Cancel, i.e. Taker-only)

  • FOK (Fill or Kill, for full size)

  • MAKER_ONLY (i.e. Post-only)

  • MAKER_ONLY_REPRICE (Reprices order to the best maker only price if the specified price were to lead to a taker trade)

source

STRING

Source of the request, available values: 0, 2, 10, 11, 13, 22, 31, 32, 33, 101, 102, 103, 104, 108, 111, 150.

Enumeration: 0: GUI, 2: Borrow, 11: REST, 13: Websocket, 22: Delivery, 31: Physical settlement, 32: Cash settlement, 33: transfer, 101: Automatic borrow, 102: Borrow position liquidation, 103: Position liquidation, 104: Liquidation revert, 108: ADL, 111: Automatic repayment, 150: BLP assignment

createdAt

STRING

Millisecond timestamp of the order created time

lastModifiedAt

STRING

Millisecond timestamp of the order last modified time

lastMatchedAt

STRING

Millisecond timestamp of the order last matched time

POST /v3/orders/place

Place orders.

You can place up to 8 orders at a time in REST API

Curl

Request

POST /v3/orders/place
{
    "recvWindow": 20000, 
    "responseType": "FULL", 
    "timestamp": 1615430912440, 
    "orders": [
         {
             "clientOrderId": 1612249737724, 
             "marketCode": "BTC-USD-SWAP-LIN", 
             "side": "SELL", 
             "quantity": "0.001", 
             "timeInForce": "GTC", 
             "orderType": "LIMIT", 
             "price": "50007"
         }, 
         {
             "clientOrderId": 1612249737724, 
             "marketCode": "BTC-USD-SWAP-LIN", 
             "side": "BUY", 
             "quantity": "0.002", 
             "timeInForce": "GTC", 
             "orderType": "LIMIT", 
             "price": "54900"
         }
    ]
}

Successful response format

{
    "success": true,
    "data": [
       {
            "code": "710006",
            "message": "FAILED balance check as balance (0E-9) < value (0.001)",
            "submitted": false,
            "clientOrderId": "1612249737724",
            "marketCode": "BTC-USD-SWAP-LIN",
            "side": "SELL",
            "price": "52888.0",
            "quantity": "0.001",   
            "orderType": "LIMIT",
            "timeInForce": "GTC",
            "createdAt": "16122497377340",
            "source": "0"
        },
        {
            "notice": "OrderOpened", 
            "accountId": "1076", 
            "orderId": "1000132664173",
            "submitted": true,
            "clientOrderId": "1612249737724",
            "marketCode": "BTC-USD-SWAP-LIN",
            "status": "OPEN",
            "price": "23641.0",
            "stopPrice": null,
            "isTriggered": false,
            "quantity": "0.01",
            "amount": "0.0",
            "remainQuantity": null,
            "matchId": null,
            "matchPrice": null, 
            "matchQuantity": null, 
            "feeInstrumentId": null,
            "fees": null,
            "orderType": "LIMIT", 
            "timeInForce": "GTC", 
            "createdAt": "1629192975532",       
            "lastModifiedAt": null,         
            "lastMatchedAt": null   
        }
    ]
}

Python
import os
import requests
import hmac
import hashlib
import base64
import json
import time
from dotenv import load_dotenv

load_dotenv()

def place_orders(orders):
    api_key = os.getenv('API_KEY')
    secret_key = os.getenv('API_SECRET').encode('utf-8')
    ts = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())
    nonce = str(int(time.time() * 1000))
    method = "/v3/orders/place"
    api_url = "api.ox.fun"

    post_data = {
        "recvWindow": 20000,
        "responseType": "FULL",
        "timestamp": int(time.time() * 1000),
        "orders": orders
    }

    body = json.dumps(post_data)
    msg_string = f"{ts}\n{nonce}\nPOST\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:
        response = requests.post(f"https://{api_url}{method}", data=body, headers=headers)
        response.raise_for_status()
        print('Response:', response.json())
    except requests.exceptions.RequestException as error:
        print('Error placing orders:', error)

# Example usage
orders = [
    {
        "clientOrderId": 1612249737724,
        "marketCode": "BTC-USD-SWAP-LIN",
        "side": "SELL",
        "quantity": "0.001",
        "timeInForce": "GTC",
        "orderType": "LIMIT",
        "price": "50007"
    },
    {
        "clientOrderId": 1612249737724,
        "marketCode": "BTC-USD-SWAP-LIN",
        "side": "BUY",
        "quantity": "0.002",
        "timeInForce": "GTC",
        "orderType": "LIMIT",
        "price": "54900"
    }
]

place_orders(orders)
Javascript
const axios = require('axios');
const crypto = require('crypto');
require('dotenv').config();

async function placeOrders(orders) {
    const apiKey = process.env.API_KEY;
    const secretKey = process.env.API_SECRET;
    const ts = new Date().toISOString();
    const nonce = Math.random().toString(36).substring(2);
    const method = "/v3/orders/place";
    const apiUrl = "api.ox.fun";

    const postData = {
        recvWindow: 20000,
        responseType: "FULL",
        timestamp: Date.now(),
        orders: orders
    };

    const body = JSON.stringify(postData);
    const msgString = `${ts}\n${nonce}\nPOST\n${apiUrl}\n${method}\n${body}`;

    const sign = crypto.createHmac('sha256', secretKey)
        .update(msgString)
        .digest('base64');

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

    try {
        const response = await axios.post(`https://${apiUrl}${method}`, body, { headers });
        console.log('Response:', response.data);
    } catch (error) {
        console.error('Error placing orders:', error.response ? error.response.data : error.message);
    }
}

// Example usage
const orders = [
    {
        clientOrderId: 1612249737724,
        marketCode: "BTC-USD-SWAP-LIN",
        side: "SELL",
        quantity: "0.001",
        timeInForce: "GTC",
        orderType: "LIMIT",
        price: "50007"
    },
    {
        clientOrderId: 1612249737724,
        marketCode: "BTC-USD-SWAP-LIN",
        side: "BUY",
        quantity: "0.002",
        timeInForce: "GTC",
        orderType: "LIMIT",
        price: "54900"
    }
];

placeOrders(orders);
Request Parameters
Type
Required
Description

recvWindow

LONG

NO

In milliseconds. If an order reaches the matching engine and the current timestamp exceeds timestamp + recvWindow, then the order will be rejected. If timestamp is provided without recvWindow, then a default recvWindow of 1000ms is used. If recvWindow is provided with no timestamp, then the request will not be rejected. If neither timestamp nor recvWindow are provided, then the request will not be rejected

timestamp

STRING

YES

In milliseconds. If an order reaches the matching engine and the current timestamp exceeds timestamp + recvWindow, then the order will be rejected.

responseType

STRING

YES

FULL or ACK

orders

LIST

YES

clientOrderId

ULONG

YES

Client assigned ID to help manage and identify orders with max value 9223372036854775807

marketCode

STRING

YES

Market code

side

STRING

YES

BUY or SELL

quantity

STRING

YES

Quantity

amount

STRING

NO

Amount (only allow amount field when market is spot and direction is BUY)

displayQuantity

STRING

NO

displayQuantity (For an iceberg order, pass both quantity and displayQuantity fields in the order request.)

timeInForce

STRING

NO

Default GTC

orderType

STRING

YES

LIMIT or MARKET or STOP_LIMIT or STOP_MARKET

price

STRING

NO

Limit price for the limit order

stopPrice

STRING

NO

Stop price for the stop order

limitPrice

STRING

NO

Limit price for the stop limit order

selfTradePreventionMode

STRING

No

NONE, EXPIRE_MAKER, EXPIRE_TAKER, EXPIRE_BOTH

Response Fields
Type
Description

notice

STRING

OrderClosed or OrderMatched or OrderOpened

accountId

STRING

Account ID

code

STRING

Error code

message

STRING

Error message

submitted

BOOL

Denotes whether the order was submitted to the matching engine or not

orderId

STRING

clientOrderId

STRING

Client assigned ID to help manage and identify orders with max value 9223372036854775807

marketCode

STRING

status

STRING

Order status

side

STRING

SELL or BUY

price

STRING

stopPrice

STRING

isTriggered

BOOL

false (can be true for STOP order types)

quantity

STRING

amount

STRING

displayQuantity

STRING

remainQuantity

STRING

Remaining quantity

matchId

STRING

matchPrice

STRING

matchQuantity

STRING

Matched quantity

feeInstrumentId

STRING

Instrument ID of fees paid from this match ID

fees

STRING

Amount of fees paid from this match ID

orderType

STRING

MARKET or LIMIT or STOP_LIMIT or or STOP_MARKET

triggerType

STRING

timeInForce

STRING

source

STRING

Source of the request, available values: 0, 2, 10, 11, 13, 22, 101, 102, 103, 104, 111.

Enumeration: 0: GUI, 2: Borrow, 11: REST, 13: Websocket, 22: Delivery, 101: Automatic borrow, 102: Borrow position liquidation, 103: Contract liquidation, 104: Liquidation revert, 111: Automatic repayment

createdAt

STRING

Millisecond timestamp of the order created time

lastModifiedAt

STRING

Millisecond timestamp of the order last modified time

lastMatchedAt

STRING

Millisecond timestamp of the order last matched time

DELETE /v3/orders/cancel

Cancel orders.

You can cancel up to 8 orders at a time in REST API

Curl

Request

DELETE /v3/orders/cancel
{
    "recvWindow": 200000, 
    "responseType": "FULL", 
    "timestamp": 1615454880374, 
    "orders": [
        {
            "marketCode": "BTC-USD-SWAP-LIN", 
            "orderId": "304384250571714215", 
            "clientOrderId": 1615453494726
        }, 
        {
            "marketCode": "BTC-USD-SWAP-LIN", 
            "clientOrderId": 1612249737724
        }
    ]
}

Successful response format

{
    "success": true,
    "data": [
        {
            "notice": "OrderClosed", 
            "accountId": "12005486", 
            "orderId": "304384250571714215",
            "submitted": true,
            "clientOrderId": "1615453494726", 
            "marketCode": "BTC-USD-SWAP-LIN", 
            "status": "CANCELED_BY_USER", 
            "side": "BUY", 
            "price": "4870.0", 
            "stopPrice": null,
            "isTriggered": false,
            "quantity": "0.001",
            "amount": "0.0",
            "remainQuantity": "0.001",
            "orderType": "LIMIT",  
            "timeInForce": "GTC", 
            "closedAt": "1629712561919"
        },
        {
            "code": "40035",
            "message": "Open order not found with id",
            "submitted": false,
             "orderId": "204285250571714316",
             "clientOrderId": "1612249737724",
             "marketCode": "BTC-oUSD-SWAP-LIN",
             "closedAt": "1615454881433"
         }
    ]
}
Python
import os
import requests
import hmac
import hashlib
import base64
import json
import time
from dotenv import load_dotenv

load_dotenv()

def cancel_orders(orders):
    api_key = os.getenv('API_KEY')
    secret_key = os.getenv('API_SECRET').encode('utf-8')
    ts = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())
    nonce = str(int(time.time() * 1000))
    method = "/v3/orders/cancel"
    api_url = "api.ox.fun"

    post_data = {
        "recvWindow": 200000,
        "responseType": "FULL",
        "timestamp": int(time.time() * 1000),
        "orders": orders
    }

    body = json.dumps(post_data)
    msg_string = f"{ts}\n{nonce}\nDELETE\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:
        response = requests.delete(f"https://{api_url}{method}", data=body, headers=headers)
        response.raise_for_status()
        print('Response:', response.json())
    except requests.exceptions.RequestException as error:
        print('Error canceling orders:', error)

# Example usage
orders_to_cancel = [
    {
        "marketCode": "BTC-USD-SWAP-LIN",
        "orderId": "1111111111111",
        "clientOrderId": 11111111111111
    }
]

cancel_orders(orders_to_cancel)
Javascript
require('dotenv').config();
const axios = require('axios');
const crypto = require('crypto');

async function cancelOrders(orders) {
  const apiKey = process.env.API_KEY;
  const secretKey = process.env.API_SECRET;
  const ts = new Date().toISOString().split('.')[0] + 'Z';
  const nonce = Date.now().toString();
  const method = "/v3/orders/cancel";
  const apiUrl = "api.ox.fun";

  const postData = {
    recvWindow: 200000,
    responseType: "FULL",
    timestamp: Date.now(),
    orders: orders
  };

  const body = JSON.stringify(postData);
  const msgString = `${ts}\n${nonce}\nDELETE\n${apiUrl}\n${method}\n${body}`;

  const sign = crypto.createHmac('sha256', secretKey)
    .update(msgString)
    .digest('base64');

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

  try {
    const response = await axios.delete(`https://${apiUrl}${method}`, {
      data: body,
      headers: headers
    });
    console.log('Response:', response.data);
  } catch (error) {
    console.error('Error canceling orders:', error.response ? error.response.data : error.message);
  }
}

// Example usage
const ordersToCancel = [
  {
    marketCode: "BTC-USD-SWAP-LIN",
    orderId: "1111111111",
    clientOrderId: 11111111111111
  }
];

cancelOrders(ordersToCancel);
Request Parameters
Type
Required
Description

recvWindow

LONG

NO

timestamp

LONG

YES

responseType

STRING

YES

FULL or ACK

orders

LIST

YES

marketCode

STRING

YES

orderId

STRING

Either one of orderId or clientOrderId is required

clientOrderId

ULONG

Either one of orderId or clientOrderId is required

Client assigned ID to help manage and identify orders with max value 9223372036854775807

Response Fields
Type
Description

submitted

BOOL

Denotes if the cancel request was submitted to the matching engine or not

notice

STRING

OrderClosed

accountId

STRING

Account ID

code

STRING

Error code

message

STRING

Error message

orderId

STRING

clientOrderId

STRING

Client assigned ID to help manage and identify orders with max value 9223372036854775807

marketCode

STRING

side

STRING

SELL or BUY

price

STRING

stopPrice

STRING

isTriggered

BOOL

false (can be true for STOP order types)

quantity

STRING

amount

STRING

displayQuantity

STRING

remainQuantity

STRING

Remaining quantity

orderType

STRING

MARKET or LIMIT or STOP or STOP_MARKET

triggerType

STRING

timeInForce

STRING

closedAt

STRING

Millisecond timestamp of the order close time

DELETE /v3/orders/cancel-all

Cancel orders

Cancels all open orders for the specified market for the account connected to the API key initiating the request.

Curl

Request

DELETE  /v3/orders/cancel-all
{
    "marketCode": "BTC-USD-SWAP-LIN"
}

Successful response format

{
    "success": true,
    "data":  
        {
            "notice": "Orders queued for cancelation"
        }
}
Python
import os
import requests
import hmac
import hashlib
import base64
import json
import time
from dotenv import load_dotenv

load_dotenv()

def cancel_all_orders(market_code):
    api_key = os.getenv('API_KEY')
    secret_key = os.getenv('API_SECRET').encode('utf-8')
    ts = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())
    nonce = str(int(time.time() * 1000))
    method = "/v3/orders/cancel-all"
    api_url = "api.ox.fun"

    post_data = {
        "marketCode": market_code
    }

    body = json.dumps(post_data)
    msg_string = f"{ts}\n{nonce}\nDELETE\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:
        response = requests.delete(f"https://{api_url}{method}", data=body, headers=headers)
        response.raise_for_status()
        print('Response:', response.json())
    except requests.exceptions.RequestException as error:
        print('Error canceling all orders:', error)

# Example usage
cancel_all_orders("BTC-USD-SWAP-LIN")
Javascript
require('dotenv').config();
const axios = require('axios');
const crypto = require('crypto');

async function cancelAllOrders(marketCode) {
  const apiKey = process.env.API_KEY;
  const secretKey = process.env.API_SECRET;
  const ts = new Date().toISOString().split('.')[0] + 'Z';
  const nonce = Date.now().toString();
  const method = "/v3/orders/cancel-all";
  const apiUrl = "api.ox.fun";

  const postData = {
    marketCode: marketCode
  };

  const body = JSON.stringify(postData);
  const msgString = `${ts}\n${nonce}\nDELETE\n${apiUrl}\n${method}\n${body}`;

  const sign = crypto.createHmac('sha256', secretKey)
    .update(msgString)
    .digest('base64');

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

  try {
    const response = await axios.delete(`https://${apiUrl}${method}`, {
      data: body,
      headers: headers
    });
    console.log('Response:', response.data);
  } catch (error) {
    console.error('Error canceling all orders:', error.response ? error.response.data : error.message);
  }
}

// Example usage
cancelAllOrders("BTC-USD-SWAP-LIN");

Request Parameters
Type
Required
Description

marketCode

STRING

NO

Response Fields
Type
Description

notice

STRING

Orders queued for cancelation or No working orders found”

PreviousMarket Data - PublicNextTrades - Private

Last updated 3 months ago

πŸ”Œ