NAV
curl javascript python

Change Log

2022-06-28

Added new REST API GET /v3/orders/status to get latest order status

2022-05-25

2022-05-20

2022-05-10

2022-05-04

2022-04-18

2022-04-15

2022-04-12

2022-03-18

2022-03-11

2022-02-21

2022-01-05

2021-12-23

2021-12-21

2021-11-30

2021-11-22

2021-10-30

Here come the API V3!

2021-10-26

2021-09-23

2021-09-17

2021-08-23

2021-08-11

2021-08-09

2021-08-05

2021-08-03

2021-07-28

2021-05-24

2021-05-21

2021-05-13

2021-05-12

2021-04-28

2021-04-19

2021-03-31

2021-03-18

2021-03-10

2021-02-20

2021-02-05

2021-01-26

2021-01-18

2020-12-14

2020-12-10

2020-09-25

2020-07-25

2020-06-16

2020-06-15

Introduction

Welcome to CoinFLEX's v2 application programming interface (API). CoinFLEX's APIs provide clients programmatic access to control aspects of their accounts and to place orders on CoinFLEX's trading platform. CoinFLEX supports the following types of APIs:

Using these interfaces it is possible to place both authenticated and unauthenticated API commands for public and prvate commands respectively.

To get started please register for a TEST account at https://v2stg.coinflex.com/user-console/register

API Key Management

An API key is required to make an authenticated API command. API keys (public and corresponding secret key) can be generated via the CoinFLEX GUI within a clients account.

By default, API Keys are read-only and can only read basic account information, such as positions, orders, and trades. They cannot be used to trade such as placing, modifying or cancelling orders.

If you wish to execute orders with your API Key, clients must select the Can Trade permission upon API key creation.

API keys are also only bound to a single sub-account, defined upon creation. This means that an API key will only ever interact and return account information for a single sub-account.

Historical Data

CoinFLEX's historical L2 order book data (depth data), can be found at https://docs.tardis.dev/historical-data-details/coinflex (third party API), which includes historical market data details - instruments, data coverage and data collection specifics for all of our instruments since 2020-07-14.

Rate Limit

CoinFLEX's APIs allows our clients to access and control their accounts or view our market data using custom-written software. To protect the performance of the system, we impose certain limits:

Type Limit
Rest API 100 per second
Rest API 2500 per 5 mins
Rest POST v2.1/delivery/orders 2 per 10 seconds
Initialising Websocket Connection 200 per minute
Websocket API (Auth) 50 per second
Websocket API (No Auth) 1 per second

Websocket API

Subscription request format

{
  "op": "<value>",
  "tag": "<value>",
  "args": ["<value1>", "<value2>",.....]
}

Subscription success response format

{
  "event": "<opValue>",
  "success": True,
  "tag": "<value>",
  "channel": "<argsValue>",
  "timestamp": "1592491945368"
}

Subscription failure response format

{
  "event": "<opValue>",
  "success": False,
  "tag": "<value>",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592498745368"
}

Command request format

{
  "op": "<value>",
  "tag": "<value>",
  "data": {"<key1>": "<value1>",.....}
}

Command success response format

{
  "event": "<opValue>",
  "success": True
  "tag": "<value>",
  "timestamp": "1592498745368",
  "data": {"<key1>": "<value1>",.....}
}

Command failure response format

{
  "event": "<opValue>",
  "success": False,
  "message": "<errorMessage>",
  "code": "<codeCode>",
  "timestamp": "1592498745368",
  "data": {"<key1>": "<value1>",.....}
}

TEST site

LIVE site

CoinFLEX's application programming interface (API) provides our clients programmatic access to control aspects of their accounts and to place orders on the CoinFLEX trading platform. The API is accessible via WebSocket connection to the URIs listed above. Commands, replies, and notifications all traverse the WebSocket in text frames with JSON-formatted payloads.

Websocket commands can be sent in either of the following two formats:

For subscription based requests

{"op": "<value>", "args": ["<value1>", "<value2>",.....]}

op: can either be:

args: the value(s) will be the instrument ID(s) or asset ID(s), for example:

All other commands

{"op": "<command>", "data": {"<key1>":"<value1>",.....}}

op: can be:

data: JSON string of the request object containing the required parameters

Further information regarding the error codes and corresponding error messages from a failed subscription or order command request can be found in a later section of this documentation Error Codes.

WebSocket adapter

coinflex-ws is a websocket wrapper to easily connect to CoinFLEX's websockets.

Authentication

Request format

{
  "op": "login",
  "tag": "<value>",
  "data": {
            "apiKey": "<string>",
            "timestamp": "<string>",
            "signature": "<string>"
          }
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = 'API-KEY'
api_secret = 'API-SECRET'
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

msg_auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}

async def subscribe():
    async with websockets.connect('wss://v2stgapi.coinflex.com/v2/websocket') as ws:
        await ws.send(json.dumps(msg_auth))
        while ws.open:
            resp = await ws.recv()
            print(resp)

asyncio.get_event_loop().run_until_complete(subscribe())
const CryptoJS = require("crypto-js");
const WebSocket = require('ws');

var apiKey = "API-KEY";
var secretKey = "API-SECRET";
const ts = '' + Date.now();

var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(ts +'GET/auth/self/verify', secretKey));
var msg = JSON.stringify({  
                            "op": "login",
                            "tag": 1,
                            "data": {
                              "apiKey": apiKey,
                              "timestamp": ts,
                              "signature": sign
                            }
                          });

var ws = new WebSocket('wss://v2stgapi.coinflex.com/v2/websocket');

ws.onmessage = function (e) {
  console.log('websocket message from server : ', e.data);
};

ws.onopen = function () {
    ws.send(msg);
};

Success response format

{
  "event": "login",
  "success": true,
  "tag": "<value>",
  "timestamp": "1592491803978"
}
{
  "event": "login",
  "success": true,
  "tag": "1",
  "timestamp": "1592491808328"
}
{
  "event": "login",
  "success": true,
  "tag": "1",
  "timestamp": "1592491808329"
}

Failure response format

{
  "event": "login",
  "success": false,
  "code": "<errorCode>",
  "message": "<errorMessage>",
  "tag": "1",
  "timestamp": "1592492069732"
}
{
  "event": "login",
  "success": false,
  "code": "<errorCode>",
  "message": "<errorMessage>",
  "tag": "1",
  "timestamp": "1592492031972"
}
{
  "event": "login",
  "success": false,
  "code": "<errorCode>",
  "message": "<errorMessage>",
  "tag": "1",
  "timestamp": "1592492031982"
}

The Websocket API consists of public and private methods. The public methods do not require authentication. The private methods requires an authenticated websocket connection.

To autenticate a websocket connection a "login" message must be sent containing the clients signature.

The signature is constructed using a HMAC SHA256 operation to get a hash value, which in turn requires the clients API Secret as the key and a constructed message string as the value for the HMAC operation. This hash value is then encoded as a BASE-64 value which becomes the signature used for authentication.

API keys (public and corresponding secret key) can be generated via the GUI within the clients account.

The message string used in the HMAC SHA256 operation is constructed in the following way:

The signature can therefore be summarised by the following:

Request Parameters

Parameter Type Required Description
op STRING Yes 'login'
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
data DICTIONARY object Yes
apiKey STRING Yes Clients public API key, visible in the GUI when created
timestamp STRING Yes Current millisecond timestamp
signature STRING Yes Base64(HmacSHA256(current_ms_timestamp + 'GET/auth/self/verify', API-Secret))

Session Keep Alive

To maintain an active WebSocket connection it is imperative to either be subscribed to a channel that pushes data at least once per minute (Depth) or send a ping to the server once per minute.

Order Commands

Place Limit Order

Request format

{
  "op": "placeorder",
  "tag": 123,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "clientOrderId": 1,
            "marketCode": "BTC-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "LIMIT",
            "quantity": 1.5,
            "timeInForce": "GTC",
            "price": 9431.48
          }
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
place_order = \
{
  "op": "placeorder",
  "tag": 123,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "clientOrderId": 1,
            "marketCode": "BTC-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "LIMIT",
            "quantity": 1.5,
            "timeInForce": "GTC",
            "price": 9431.48
          }
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(place_order))
            elif 'event' in data and data['event'] == 'placeorder':
                continue

asyncio.get_event_loop().run_until_complete(subscribe())

Success response format


{
  "event": "placeorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1592491945248",
  "data": {
            "clientOrderId": 1,
            "marketCode": "BTC-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "LIMIT",
            "quantity": "1.5",
            "timeInForce": "GTC",
            "orderId": "1000000700008",
            "price": "9431.48",
            "source": 0
          }
}

Failure response format

{
  "event": "placeorder",
  "submitted": False,
  "tag": "123",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491945248",
  "data": {
            "clientOrderId": "1",
            "marketCode": "BTC-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "LIMIT",
            "quantity": "1.5",
            "timeInForce": "GTC",
            "price": "9431.48",
            "source": 0
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderOpened, OrderMatched etc......).

Request Parameters

Parameter Type Required Description
op STRING Yes placeorder
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
data DICTIONARY object Yes
clientOrderId ULONG No Client assigned ID to help manage and identify orders with max value 9223372036854775807
marketCode STRING Yes Market code e.g. BTC-USD-SWAP-LIN
orderType STRING Yes LIMIT
price FLOAT No Price
quantity FLOAT Yes Quantity (denominated by contractValCurrency)
side STRING Yes BUY or SELL
timeInForce ENUM No
  • 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)
timestamp 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.
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.

Place Market Order

Request format

{
  "op": "placeorder",
  "tag": 123,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "clientOrderId": 1,
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "SELL",
            "orderType": "MARKET",
            "quantity": 5
          }
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = '' 
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
place_order = \
{
  "op": "placeorder",
  "tag": 123,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "clientOrderId": 1,
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "SELL",
            "orderType": "MARKET",
            "quantity": 5
          }
}


url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)

            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(place_order))
            elif 'event' in data and data['event'] == 'placeorder':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "placeorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1592491945248",
  "data": {
            "clientOrderId": "1",
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "SELL",
            "orderType": "MARKET",
            "quantity": "5",
            "orderId": "1000000700008",
            "source": 0
          }
}

Failure response format

{
  "event": "placeorder",
  "submitted": False,
  "tag": "123",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491503359",
  "data": {
            "clientOrderId": "1",
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "SELL",
            "orderType": "MARKET",
            "quantity": "5",
            "source": 0
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderOpened, OrderMatched etc......).

Request Parameters

Parameter Type Required Description
op STRING Yes placeorder
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
data DICTIONARY object Yes
clientOrderId ULONG No Client assigned ID to help manage and identify orders with max value 9223372036854775807
marketCode STRING Yes Market code e.g. BTC-USD-SWAP-LIN
orderType STRING Yes MARKET
quantity FLOAT Yes Quantity (denominated by contractValCurrency)
side STRING Yes BUY or SELL
timestamp 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.
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.

Place Stop Limit Order

Request format

{
  "op": "placeorder",
  "tag": 123,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "clientOrderId": 1,
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "STOP_LIMIT",
            "quantity": 10,
            "timeInForce": "MAKER_ONLY_REPRICE",
            "stopPrice": 100,
            "limitPrice": 120
         }
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
place_order = \
{
  "op": "placeorder",
  "tag": 123,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "clientOrderId": 1,
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "STOP",
            "quantity": 10,
            "timeInForce": "MAKER_ONLY_REPRICE",
            "stopPrice": 100,
            "limitPrice": 120
         }
}


url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)

            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(place_order))
            elif 'event' in data and data['event'] == 'placeorder':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "placeorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1607639739098",
  "data": {
            "clientOrderId": "1",
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "STOP_LIMIT",
            "quantity": "10",
            "timeInForce": "MAKER_ONLY_REPRICE",
            "stopPrice": "100",
            "limitPrice": "120",
            "orderId": "1000000700008",
            "source": 0
          }
}

Failure response format

{
  "event": "placeorder",
  "submitted": False,
  "tag": "123",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491503359",
  "data": {
            "clientOrderId": "1",
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "STOP_LIMIT",
            "quantity": "10",
            "timeInForce": "MAKER_ONLY_REPRICE",
            "stopPrice": "100",
            "limitPrice": "120",
            "source": 0
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderOpened, OrderMatched etc......).

Request Parameters

Parameters Type Required Description
op STRING Yes placeorder
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
data DICTIONARY object Yes
clientOrderId ULONG No Client assigned ID to help manage and identify orders with max value 9223372036854775807
marketCode STRING Yes Market code e.g. ETH-USD-SWAP-LIN
orderType STRING Yes STOP_LIMIT for stop-limit orders (stop-market orders not supported)
quantity FLOAT Yes Quantity (denominated by contractValCurrency)
side STRING Yes BUY or SELL
limitPrice FLOAT Yes Limit price for the stop-limit order.

For BUY the limit price must be greater or equal to the stop price.

For SELL the limit price must be less or equal to the stop price.

stopPrice FLOAT Yes Stop price for the stop-limit order.

Triggered by the best bid price for the SELL stop-limit order.

Triggered by the best ask price for the BUY stop-limit order.

timeInForce ENUM No
  • 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)
timestamp 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.
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.

Place Batch Orders

Request format

{
  "op": "placeorders",
  "tag": 123,
  "dataArray": [{
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "clientOrderId": 1,
                  "marketCode": "ETH-USD-SWAP-LIN",
                  "side": "BUY",
                  "orderType": "LIMIT",
                  "quantity": 10,
                  "timeInForce": "MAKER_ONLY",
                  "price": 100
                }, 
                {
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "clientOrderId": 2,
                  "marketCode": "BTC-USD",
                  "side": "SELL",
                  "orderType": "MARKET",
                  "quantity": 0.2
                }]
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
place_batch_order =\
{
  "op": "placeorders",
  "tag": 123,
  "dataArray": [{
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "clientOrderId": 1,
                  "marketCode": "ETH-USD-SWAP-LIN",
                  "side": "BUY",
                  "orderType": "LIMIT",
                  "quantity": 10,
                  "timeInForce": "MAKER_ONLY",
                  "price": 100
                },
                {
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "clientOrderId": 2,
                  "marketCode": "BTC-USD",
                  "side": "SELL",
                  "orderType": "MARKET",
                  "quantity": 0.2
                }]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(place_batch_order))
            elif 'event' in data and data['event'] == 'placeorder':
                continue

asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "placeorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1607639739098",
  "data": {
            "clientOrderId": "1",
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "LIMIT",
            "quantity": "10",
            "timeInForce": "MAKER_ONLY",
            "price": "100",
            "orderId": "1000003700008",
            "source": 0
          }
}

AND

{
  "event": "placeorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1607639739136",
  "data": {
            "clientOrderId": "2",
            "marketCode": "BTC-USD",
            "side": "SELL",
            "orderType": "MARKET",
            "quantity": "0.2",
            "orderId": "1000004700009",
            "source": 0
          }
}

Failure response format

{
  "event": "placeorder",
  "submitted": False,
  "tag": "123",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491503359",
  "data": {
            "clientOrderId": "1",
            "marketCode": "ETH-USD-SWAP-LIN",
            "side": "BUY",
            "orderType": "LIMIT",
            "quantity": "10",
            "timeInForce": "MAKER_ONLY",
            "price": "100",
            "source": 0
          }
}

AND

{
  "event": "placeorder",
  "submitted": False,
  "tag": "123",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491503457",
  "data": {
            "clientOrderId": "2",
            "marketCode": "BTC-USD",
            "side": "SELL",
            "orderType": "MARKET",
            "quantity": "0.2",
            "source": 0
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderOpened, OrderMatched etc......).

All existing single order placement methods are supported:-

The websocket reply from the exchange will repond to each order in the batch separately, one order at a time, and has the same message format as the reponse for the single order placement method.

Request Parameters

Parameters Type Required Description
op STRING Yes placeorders
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
dataArray LIST of dictionaries Yes A list of orders with each order in JSON format, the same format/parameters as the request for placing a single order. The max number of orders is still limited by the message length validation so by default up to 20 orders can be placed in a batch, assuming that each order JSON has 200 characters.
timestamp 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.
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.

Cancel Order

Request format

{
  "op": "cancelorder",
  "tag": 456,
  "data": {
            "marketCode": "BTC-USD-SWAP-LIN",
            "orderId": 12
          }
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
cancel_order = \
{
  "op": "cancelorder",
  "tag": 456,
  "data": {
            "marketCode": "BTC-USD-SWAP-LIN",
            "orderId": 12
          }
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)

            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(cancel_order))
            elif 'event' in data and data['event'] == 'cancelorder':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "cancelorder",
  "submitted": True,
  "tag": "456",
  "timestamp": "1592491173964",
  "data": {
            "marketCode": "BTC-USD-SWAP-LIN",
            "clientOrderId": "1",
            "orderId": "12"
          }
}

Failure response format

{
  "event": "cancelorder",
  "submitted": False,
  "tag": "456",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491173964",
  "data": {
            "marketCode": "BTC-USD-SWAP-LIN",
            "orderId": "12"
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderClosed etc......).

This command can also be actioned via the trading GUI using the Cancel button next to an open order in the Open Orders blotter for both Spot and Derivative markets.

Request Parameters

Parameters Type Required Description
op STRING Yes cancelorder
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
data DICTIONARY object Yes
marketCode STRING Yes Market code e.g. BTC-USD-SWAP-LIN
orderId INTEGER Yes Unique order ID from the exchange

Cancel Batch Orders

Request format

{
  "op": "cancelorders",
  "tag": 456,
  "dataArray": [{
                  "marketCode": "BTC-USD-SWAP-LIN",
                  "orderId": 12
                },
                {
                  "marketCode": "BCH-USD",
                  "orderId": 34
                }]
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
cancel_batch_order = \
{
  "op": "cancelorders",
  "tag": 456,
  "dataArray": [{
                  "marketCode": "BTC-USD-SWAP-LIN",
                  "orderId": 12
                },
                {
                  "marketCode": "BCH-USD",
                  "orderId": 34
                }]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)

            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(cancel_batch_order))
            elif 'event' in data and data['event'] == 'cancelorder':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "cancelorder",
  "submitted": True,
  "tag": "456",
  "timestamp": "1592491173964",
  "data": {
            "marketCode": "BTC-USD-SWAP-LIN",
            "clientOrderId": "1",
            "orderId": "12"
          }
}

AND

{
  "event": "cancelorder",
  "submitted": True,
  "tag": "456",
  "timestamp": "1592491173978",
  "data": {
            "marketCode": "BCH-USD",
            "orderId": "34"
          }
}

Failure response format

{
  "event": "cancelorder",
  "submitted": False,
  "tag": "456",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491173964",
  "data": {
            "marketCode": "BTC-USD-SWAP-LIN",
            "orderId": "12"
          }
}

AND

{
  "event": "cancelorder",
  "submitted": False,
  "tag": "456",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491173989",
  "data": {
            "marketCode": "BCH-USD",
            "orderId": "12"
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderClosed etc......).

Request Parameters

Parameters Type Required Description
op STRING Yes cancelorders
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
dataArray LIST of dictionaries A list of orders with each order in JSON format, the same format/parameters as the request for cancelling a single order. The max number of orders is still limited by the message length validation so by default up to 20 orders can be placed in a batch, assuming that each order JSON has 200 characters.

Modify Order

Request format

{
  "op": "modifyorder",
  "tag": 1,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "marketCode": "BTC-USD-SWAP-LIN",
            "orderId": 888,
            "side": "BUY",
            "price": 9800,
            "quantity": 2
          }
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
modify_order = \
{
  "op": "modifyorder",
  "tag": 1,
  "data": {
            "timestamp": 1638237934061,
            "recvWindow": 500,
            "marketCode": "BTC-USD-SWAP-LIN",
            "orderId": 888,
            "side": "BUY",
            "price": 9800,
            "quantity": 2
          }
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(modify_order))
            elif 'event' in data and data['event'] == 'modifyorder':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "modifyorder",
  "submitted": True,
  "tag": "1",
  "timestamp": "1592491032427",
  "data":{
          "orderId": 888,
          "side": "BUY",
          "quantity": 2
          "price": 9800,
          "orderType": "LIMIT",
          "marketCode": "BTC-USD-SWAP-LIN"
         }
}

Failure response format

{
  "event": "modifyorder",
  "submitted": False,
  "tag": "1",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491032427",
  "data": {
            "orderId": 888,
            "side": "BUY",
            "quantity": 2,
            "price": 9800,
            "marketCode": "BTC-USD-SWAP-LIN"
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderModified etc......).

Currently only LIMIT orders are supported by the modify order command.

Please note that when a new order ID is issued the original order is actually closed and a new order with a new order ID is opened, replacing the original order. This is described in further detail in the section Order Channel - OrderModified.

Please be aware that modifying the side of an existing GTC LIMIT order from BUY to SELL or vice versa without modifying the price could result in the order matching immediately since its quite likely the new order will become an agressing taker order.

Request Parameters

Parameters Type Required Description
op STRING Yes modifyorder
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
data DICTIONARY object Yes
marketCode STRING Yes Market code e.g. BTC-USD-SWAP-LIN
orderId INTEGER Yes Unique order ID from the exchange
side STRING No BUY or SELL
price FLOAT No Price for limit orders
quantity FLOAT No Quantity (denominated by contractValCurrency)
timestamp 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.
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.

Modify Batch Orders

Request format

{
  "op": "modifyorders",
  "tag": 123,
  "dataArray": [{
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "marketCode": "ETH-USD-SWAP-LIN",
                  "side": "BUY",
                  "orderID": 304304315061932310,
                  "price": 101,
                }, 
                {
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "marketCode": "BTC-USD",
                  "orderID": 304304315061864646,
                  "price": 10001,
                  "quantity": 0.21
                }]
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
modify_batch_order = \
{
  "op": "modifyorders",
  "tag": 123,
  "dataArray": [{
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "marketCode": "ETH-USD-SWAP-LIN",
                  "side": "BUY",
                  "orderID": 304304315061932310,
                  "price": 101,
                }, 
                {
                  "timestamp": 1638237934061,
                  "recvWindow": 500,
                  "marketCode": "BTC-USD",
                  "orderID": 304304315061864646,
                  "price": 10001,
                  "quantity": 0.21
                }]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(modify_batch_order))
            elif 'event' in data and data['event'] == 'modifyorder':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "modifyorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1607639739098",
  "data": {
            "orderId": "304304315061932310",
            "side": "BUY",
            "quantity": "5"
            "price": "101",
            "orderType": "LIMIT",
            "marketCode": "ETH-USD-SWAP-LIN"
          }
}

AND

{
  "event": "modifyorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1607639739136",
  "data": {
            "orderId": "304304315061864646",
            "side": "SELL",
            "quantity": 0.21,
            "price": "10001",
            "orderType": "LIMIT",
            "marketCode": "BTC-USD"
          }
}

Failure response format

{
  "event": "placeorder",
  "submitted": False,
  "tag": "123",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491503359",
  "data": {
            "orderID": 304304315061932310,
            "side": "BUY",
            "price": 101,
            "marketCode": "ETH-USD-SWAP-LIN"
          }
}

AND

{
  "event": "placeorder",
  "submitted": False,
  "tag": "123",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "timestamp": "1592491503457",
  "data": {
            "orderID": 304304315061864646,
            "quantity": 0.21,
            "price": 10001,
            "marketCode": "BTC-USD"
          }
}

Requires an authenticated websocket connection. Please also subscribe to the User Order Channel to receive push notifications for all message updates in relation to an account or sub-account (e.g. OrderOpened, OrderMatched etc......).

The websocket reply from the exchange will repond to each order in the batch separately, one order at a time, and has the same message format as the reponse for the single order modify method.

Request Parameters

Parameters Type Required Description
op STRING Yes modifyorders
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
dataArray LIST of dictionaries Yes A list of orders with each order in JSON format, the same format/parameters as the request for modifying a single order. The max number of orders is still limited by the message length validation so by default up to 20 orders can be modified in a batch, assuming that each order JSON has 200 characters.
timestamp 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.
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.

Subscriptions - Private

All subscriptions to private account channels requires an authenticated websocket connection.

Multiple subscriptions to different channels both public and private can be made within a single subscription command:

{"op": "subscribe", "args": ["<value1>", "<value2>",.....]}

Balance Channel

Request format

{
  "op": "subscribe",
  "args": ["balance:all"],
  "tag": 101
}

OR

{
  "op": "subscribe", 
  "args": ["balance:USD", "balance:FLEX", ........], 
  "tag": 101
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
balance = \
{
  "op": "subscribe",
  "args": ["balance:all"],
  "tag": 101
}
url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(balance))
            elif 'event' in data and data['event'] == 'balance':
                 continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "success": True, 
  "tag": "101", 
  "event": "subscribe", 
  "channel": "<args value>", 
  "timestamp": "1607985371401"
}

Balance channel format

{
  "table": "balance",
  "accountId": "<Your account ID>",
  "timestamp": "1599693365059",
  "tradeType": "LINEAR",
  "data": [{
              "total": "10000",
              "reserved": "1000",
              "instrumentId": "USD",
              "available": "9000",
              "locked": "0"
              "quantityLastUpdated": "1599694369431",
            },
            {
              "total": "100000",
              "reserved": "0",
              "instrumentId": "FLEX",
              "available": "100000",
              "locked": "0"
              "quantityLastUpdated": "1599694343242",
            }
          ]
}

Channel Update Frequency : On update

The websocket will reply with the shown success response format for subscribed assets with changed balances.

If a subscription has been made to balance:all, the data array in the message from this balance channel will contain a JSON list, otherwise the data array will contain a single JSON corresponding to one spot asset per asset channel subscription.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
args LIST Yes balance:all or a list of individual assets balance:<assetId>
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32

Channel Update Fields

Fields Type Description
table STRING balance
accountId STRING Account identifier
timestamp STRING Current millisecond timestamp
tradeType STRING LINEAR
data LIST of dictionaries
total STRING Total spot asset balance
reserved STRING Reserved asset balance for working spot and repo orders
instrumentId STRING Base asset ID e.g. BTC
available STRING Remaining available asset balance (total - reserved)
locked STRING Temporarily locked asset balance
quantityLastUpdated STRING Millisecond timestamp

Position Channel

Request format

{
  "op": "subscribe", 
  "args": ["position:all"], 
  "tag": 102
}

OR

{
  "op": "subscribe",
  "args": ["position:BTC-USD-SWAP-LIN", "position:BCH-USD-SWAP-LIN", ........], 
  "tag": 102
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
position = \
{
  "op": "subscribe", 
  "args": ["position:all"], 
  "tag": 102
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(position))
            elif 'event' in data and data['event'] == 'position':
                 continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "success": True, 
  "tag": "102", 
  "event": "subscribe", 
  "channel": "<args value>", 
  "timestamp": "1607985371401"
}

Position channel format

{
  "table": "position",
  "accountId": "<Your account ID>",
  "timestamp": "1607985371481",
  "data": [ {
              "instrumentId": "ETH-USD-SWAP-LIN",
              "quantity" : "0.1",
              "lastUpdated": "1616053755423",
              "contractValCurrency": "ETH",
              "entryPrice": "1900.0",
              "positionPnl": "-5.6680",
              "estLiquidationPrice": "0",
              "margin": "0",
              "leverage": "0"
            },
            {
              "instrumentId": "WBTC-USD-SWAP-PER",
              "quantity" : "0.542",
              "lastUpdated": "1617099855968",
              "contractValCurrency": "WBTC",
              "entryPrice": "20000.0",
              "positionPnl": "1220.9494164000000",
              "estLiquidationPrice": "5317.2",
              "margin": "5420.0",
              "leverage": "2"
            },
            ...
          ]
}

Channel Update Frequency : real-time, on position update

The websocket will reply with the shown success response format for each position channel which has been successfully subscribed to.

If a subscription has been made to position:all, the data array in the message from this position channel will contain a JSON list. Each JSON will contain position details for a different instrument. Otherwise the data array will contain a single JSON corresponding to one instrument.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
args LIST Yes position:all or a list of individual instruments position:<instrumentId>
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32

Channel Update Fields

Fields Type Description
table STRING position
accountId STRING Account identifier
timestamp STRING Current millisecond timestamp
data LIST of dictionaries
instrumentId STRING e.g. ETH-USD-SWAP-LIN
quantity STRING Position size (+/-)
lastUpdated STRING Millisecond timestamp
contractValCurrency STRING Base asset ID e.g. ETH
entryPrice STRING Average entry price of total position (Cost / Size)
positionPnl STRING Postion profit and lost
estLiquidationPrice STRING Estimated liquidation price, return 0 if it is negative(<0)
margin STRING Used in permissionless perps to signify the amount of margin isolated by the position. Shows as 0 in non-permissionless markets
leverage STRING Used in permissionless perps to signify the selected leverage. Shows as 0 in non-permissionless markets

Order Channel

Request format

{
  "op": "subscribe", 
  "args": ["order:all"], 
  "tag": 102
}

OR

{
  "op": "subscribe", 
  "args": ["order:FLEX-USD", "order:ETH-USD-SWAP-LIN", .....], 
  "tag": 102
}
import websockets
import asyncio
import time
import hmac
import base64
import hashlib
import json

api_key = ''
api_secret = ''
ts = str(int(time.time() * 1000))
sig_payload = (ts+'GET/auth/self/verify').encode('utf-8')
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), sig_payload, hashlib.sha256).digest()).decode('utf-8')

auth = \
{
  "op": "login",
  "tag": 1,
  "data": {
           "apiKey": api_key,
           "timestamp": ts,
           "signature": signature
          }
}
order = \
{
  "op": "subscribe", 
  "args": ["order:all"], 
  "tag": 102
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                    await ws.send(json.dumps(auth))
            elif 'event' in data and data['event'] == 'login':
                if data['success'] == True:
                    await ws.send(json.dumps(order))
            elif 'event' in data and data['event'] == 'order':
                 continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "success": True, 
  "tag": "102", 
  "event": "subscribe", 
  "channel": "<args value>", 
  "timestamp": "1607985371401"
}

Channel Update Frequency : real-time, on order update

The websocket will reply with the shown success response format for EACH order channel which has been successfully subscribed to.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
args LIST Yes order:all or a list of individual markets order:<marketCode>
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32

OrderOpened

OrderOpened message format - LIMIT order

{
  "table": "order",
  "data": [ {
              "notice": "OrderOpened",
              "accountId": "<Your account ID>",
              "clientOrderId": "16",
              "orderId" : "123",
              "price": "9600",
              "quantity": "2" ,
              "side": "BUY",
              "status": "OPEN",
              "marketCode": "BTC-USD-SWAP-LIN",
              "timeInForce": "MAKER_ONLY",
              "timestamp": "1594943491077"
              "orderType": "LIMIT",
              "isTriggered": "False"
            } ]
}

OrderOpened message format - STOP LIMIT order

{
  "table": "order",
  "data": [ {
              "notice": "OrderOpened",
              "accountId": "<Your account ID>",
              "clientOrderId": "17",
              "orderId": "2245",
              "quantity": "2",
              "side": "BUY",
              "status": "OPEN",
              "marketCode": "USDT-USD-SWAP-LIN",
              "timeInForce": "IOC",
              "timestamp": "1594943491077",
              "stopPrice": "9280",
              "limitPrice": "9300",
              "orderType": "STOP_LIMIT",
              "isTriggered": "True"
            } ]
}

Channel Update Fields

Fields Type Description
table STRING order
data LIST of dictionary
notice STRING OrderOpened
accountId STRING Account identifier
clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
orderId STRING Unique order ID from the exchange
price STRING Limit price submitted (only applicable for LIMIT order types)
quantity STRING Quantity submitted
side STRING BUY or SELL
status STRING Order status
marketCode STRING Market code e.g. FLEX-USD
timeInForce STRING Client submitted time in force, GTC by default
timestamp STRING Current millisecond timestamp
orderType STRING LIMIT or STOP_LIMIT
stopPrice STRING Stop price submitted (only applicable for STOP LIMIT order types)
limitPrice STRING Limit price submitted (only applicable for STOP LIMIT order types)
isTriggered STRING False or True

OrderClosed

OrderClosed message format - LIMIT order

{
  "table": "order",
  "data": [ {
              "notice": "OrderClosed",
              "accountId": "<Your account ID>",
              "clientOrderId": "16",
              "orderId": "73",
              "price": "9600",
              "quantity": "2",
              "side": "BUY",
              "status": "<Canceled status>",
              "marketCode": "BTC-USD-SWAP-LIN",
              "timeInForce": "<Time in force>",
              "timestamp": "1594943491077",
              "remainQuantity": "1.5",
              "orderType": "LIMIT",
              "isTriggered": "False" 
            } ]
}

OrderClosed message format - STOP LIMIT order

{
  "table": "order",
  "data": [ {
              "notice": "OrderClosed",
              "accountId": "<Your account ID>",
              "clientOrderId": "16",
              "orderId": "13",
              "quantity": "2",
              "side": "BUY",
              "status": "CANCELED_BY_USER",
              "marketCode": "BTC-USD-SWAP-LIN",
              "timeInForce": "<Time in force>",
              "timestamp": "1594943491077",
              "remainQuantity": "1.5",
              "stopPrice": "9100",
              "limitPrice": "9120",
              "orderType": "STOP LIMIT",
              "isTriggered": "True" 
            } ]
}

There are multiple scenarios in which an order is closed as described by the status field in the OrderClosed message. In summary orders can be closed by:-

Channel Update Fields

Fields Type Description
table STRING order
data LIST of dictionary
notice STRING OrderClosed
accountId STRING Account identifier
clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
orderId STRING Unique order ID from the exchange
price STRING Limit price of closed order (only applicable for LIMIT order types)
quantity STRING Original order quantity of closed order
side STRING BUY or SELL
status STRING
  • CANCELED_BY_USER
  • CANCELED_BY_MAKER_ONLY
  • CANCELED_BY_FOK
  • CANCELED_ALL_BY_IOC
  • CANCELED_PARTIAL_BY_IOC
  • CANCELED_BY_AMEND
marketCode STRING Market code e.g. BTC-USD-SWAP-LIN
timeInForce STRING Time in force of closed order
timestamp STRING Current millisecond timestamp
remainQuantity STRING Historical remaining order quantity of closed order
stopPrice STRING Stop price of closed stop order (only applicable for STOP LIMIT order types)
limitPrice STRING Limit price of closed stop order (only applicable for STOP LIMIT order types)
ordertype STRING LIMIT or STOP_LIMIT
isTriggered STRING False or True

OrderClosed Failure

OrderClosed failure message format

{
  "event": "CANCEL", 
  "submitted": False, 
  "message": "Order request was rejected : REJECT_CANCEL_ORDER_ID_NOT_FOUND", 
  "code": "100004", 
  "timestamp": "0", 
  "data": {
            "clientOrderId": 3,
            "orderId": 3330802124194931673, 
            "displayQuantity": 0.0, 
            "lastMatchPrice": 0.0, 
            "lastMatchQuantity": 0.0, 
            "lastMatchedOrderId": 0, 
            "lastMatchedOrderId2": 0, 
            "matchedId": 0, 
            "matchedType": "MAKER", 
            "remainQuantity": 0.0, 
            "side": "BUY", 
            "status": "REJECT_CANCEL_ORDER_ID_NOT_FOUND", 
            "timeCondition": "GTC", 
            "marketCode": "BTC-USD-SWAP-LIN", 
            "timestampEpochMs": 1615377638518, 
            "orderType": "LIMIT",
            "price": 0.0, 
            "quantity": 0.0, 
            "isTriggered": False
          }
}

This order message can occur if:-

Channel Update Fields

Fields Type Description
event STRING
submitted BOOL
message STRING
code STRING
timestamp STRING
data LIST of dictionary
clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
orderId STRING Unique order ID from the exchange
displayQuantity DECIMAL
lastMatchPrice DECIMAL
lastMatchQuantity DECIMAL
lastMatchedOrderId DECIMAL
lastMatchedOrderId2 DECIMAL
matchedId DECIMAL
matchedType STRING
remainQuantity DECIMAL Historical remaining quantity of the closed order
side STRING
status STRING
timeCondition STRING
marketCode STRING
timestampEpochMs LONG
orderType STRING
price DECIMAL LIMIT or STOP_LIMIT
quantity DECIMAL
isTriggered BOOL False or True

OrderModified

OrderModified message format

{
  "table": "order",
  "data": [ {
              "notice": "OrderModified",
              "accountId": "<Your account ID>",
              "clientOrderId": "16",
              "orderId": "94335",
              "price": "9600",
              "quantity": "1",
              "side": "BUY",
              "status": "OPEN",
              "marketCode": "BTC-USD-SWAP-LIN",    
              "timeInForce": "GTC",
              "timestamp": "1594943491077"
              "orderType": "LIMIT",
              "isTriggered": "False" 
            } ]
}

As described in a previous section Order Commands - Modify Order, the Modify Order command can potentially affect the queue position of the order depending on which parameter of the original order has been modified.

If the orders queue position is unchanged because the orders quantity has been reduced and no other order parameter has been changed then this OrderModified message will be sent via the Order Channel giving the full details of the modified order. In this case the order ID is unchanged.

If however the order queue position has changed becuase the orders: (1) side was modified, (2) quantity was increased, (3) price was changed or any combination of these, then the exchange will close the orginal order with an OrderClosed message with status CANCELED_BY_AMEND, followed by the opening of a new order with an OrderOpened message containing a new order ID to reflect the orders new position in the order queue.

Channel Update Fields

Fields Type Description
table STRING order
data LIST of dictionary
notice STRING OrderModified
accountId STRING Account identifier
clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
orderId STRING Unique order ID from the exchange
price STRING Limit price of modified order (only applicable for LIMIT order types)
quantity STRING Quantity of modified order
side STRING BUY or SELL
status STRING Order status
marketCode STRING Market code e.g. BTC-USD-SWAP-LIN
timeInForce STRING Client submitted time in force, GTC by default
timestamp STRING Current millisecond timestamp
orderType STRING LIMIT or STOP_LIMIT
stopPrice STRING Stop price of modified order (only applicable for STOP LIMIT order types)
limitPrice STRING Limit price of modified order (only applicable for STOP LIMIT order types)
isTriggered STRING False or True

OrderModified Failure

OrderModified failure message format

{
  "event": "AMEND", 
  "submitted": False, 
  "message": "Order request was rejected : REJECT_AMEND_ORDER_ID_NOT_FOUND", 
  "code": "100004", 
  "timestamp": "0", 
  "data": {
            "clientOrderId": 3, 
            "orderId": 3330802124194931673, 
            "displayQuantity": 917.5, 
            "lastMatchPrice": 0.0, 
            "lastMatchQuantity": 0.0, 
            "lastMatchedOrderId": 0, 
            "lastMatchedOrderId2": 0, 
            "matchedId": 0, 
            "matchedType": "MAKER", 
            "remainQuantity": 0.0, 
            "side": "BUY", 
            "status": "REJECT_AMEND_ORDER_ID_NOT_FOUND", 
            "timeCondition": "GTC", 
            "marketCode": "SUSHI-USD-SWAP-LIN", 
            "timestampEpochMs": 1615377638518, 
            "orderType": "LIMIT", 
            "price": 22, 
            "quantity": 917.5, 
            "isTriggered": False
          }
}

This order message can occur if an order has already been matched by the time the modify order command is recieved and processed by the exchange which means this order is no longer active and therefore cannot be modified.

Channel Update Fields

Fields Type Description
event STRING
submitted BOOL
message STRING
code STRING
timestamp STRING
data LIST of dictionary
clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
orderId STRING Unique order ID from the exchange
displayQuantity DECIMAL
lastMatchPrice DECIMAL
lastMatchQuantity DECIMAL
lastMatchedOrderId DECIMAL
lastMatchedOrderId2 DECIMAL
matchedId DECIMAL
matchedType STRING
remainQuantity DECIMAL
side STRING
status STRING
timeCondition STRING
marketCode STRING
timestampEpochMs LONG
orderType STRING
price DECIMAL
quantity DECIMAL
isTriggered BOOL

OrderMatched

OrderMatched message format

{
  "table": "order",
  "data": [ {
              "notice": "OrderMatched",
              "accountId": "<Your account ID>",
              "clientOrderId": "16",
              "orderId": "567531657",
              "price": "9300",
              "quantity": "20",
              "side": "BUY",
              "status": "<Matched status>",
              "marketCode": "BTC-USD-SWAP-LIN",
              "timeInForce": "GTC",
              "timestamp": "1592490254168",
              "matchId": "11568123",
              "matchPrice": "9300",
              "matchQuantity": "20",
              "orderMatchType": "MAKER",
              "remainQuantity": "0",
              "orderType": "<Order type>", 
              "stopPrice": "9000",
              "limitPrice": "9050", 
              "fees": "3.7",
              "feeInstrumentId": "FLEX",   
              "isTriggered": "False"
        }
    ]
}

Channel Update Fields

Fields Type Required
table STRING order
data LIST of dictionary
notice STRING OrderMatched
accountId STRING Account identifier
clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
orderId STRING Unique order ID from the exchange
price STRING Limit price submitted (only applicable for LIMIT order types)
stopPrice STRING Stop price submitted (only applicable for STOP LIMIT order types)
limitPrice STRING Limit price submitted (only applicable for STOP LIMIT order types)
quantity STRING Order quantity submitted
side STRING BUY or SELL
status STRING FILLED or PARTIAL_FILL
marketCode STRING Market code i.e. BTC-USD-SWAP-LIN
timeInForce STRING Client submitted time in force (only applicable for LIMIT and STOP LIMIT order types)
timestamp STRING Millisecond timestamp of order match
matchID STRING Exchange match ID
matchPrice STRING Match price of order from this match ID
matchQuantity STRING Match quantity of order from this match ID
orderMatchType STRING MAKER or TAKER
remainQuantity STRING Remaining order quantity
orderType STRING
  • LIMIT
  • MARKET
  • STOP_LIMIT
fees STRING Amount of fees paid from this match ID
feeInstrumentId STRING Instrument ID of fees paid from this match ID
isTriggered STRING False (or True for STOP LIMIT order types)

Subscriptions - Public

All subscriptions to public channels do not require an authenticated websocket connection.

Multiple subscriptions to different channels both public and private can be made within a single subscription command:

{"op": "subscribe", "args": ["<value1>", "<value2>",.....]}

Fixed Size Order Book

Request format

{
  "op": "subscribe",
  "tag": 103,
  "args": ["depthL10:BTC-USD-SWAP-LIN"]
}
import websockets
import asyncio
import json

orderbook_depth = \
{
  "op": "subscribe",
  "tag": 103,
  "args": ["depthL10:BTC-USD-SWAP-LIN"]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                await ws.send(json.dumps(orderbook_depth))
            elif 'success' in data and data['success'] == 'True':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
    "success": true,
    "tag": "103",
    "event": "subscribe",
    "channel": "depthL10:BTC-USD-SWAP-LIN",
    "timestamp": "1665454814275"
}

Order Book depth channel format

{
    "table": "depthL10",
    "data": {
        "seqNum": 2166539633781384,
        "asks": [
            [
                19024.0,
                1.0
            ],
            [
                19205.0,
                4.207
            ],
            [
                19395.0,
                8.414
            ]
        ],
        "bids": [
            [
                18986.0,
                1.0
            ],
            [
                18824.0,
                4.207
            ],
            [
                18634.0,
                8.414
            ]
        ],
        "marketCode": "BTC-USD-SWAP-LIN",
        "timestamp": "1665454814328"
    },
    "action": "partial"
}

Channel Update Frequency: 100ms

This order book depth channel sends a snapshot of the entire order book every 50ms.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
args LIST Yes List of individual markets <depth>:<marketCode> e.g: [depthL10:BTC-USD-SWAP-LIN], valid book sizes are: depthL5 depthL10 depthL25

Channel Update Fields

Fields Type Description
table STRING depthL10
data DICTIONARY
seqNum INTEGER Sequence number of the order book snapshot
asks LIST of floats Sell side depth;
  1. price
  2. quantity
bids LIST of floats Buy side depth;
  1. price
  2. quantity
marketCode STRING marketCode
timestamp STRING Millisecond timestamp
action STRING

Full Order Book

Request format

{
  "op": "subscribe",
  "tag": 103,
  "args": ["depth:BTC-USD-SWAP-LIN"]
}
import websockets
import asyncio
import json

orderbook_depth = \
{
  "op": "subscribe",
  "tag": 103,
  "args": ["depth:BTC-USD-SWAP-LIN"]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                await ws.send(json.dumps(orderbook_depth))
            elif 'success' in data and data['success'] == 'True':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
    "success": true,
    "tag": "103",
    "event": "subscribe",
    "channel": "depth:BTC-USD-SWAP-LIN",
    "timestamp": "1665454814275"
}

Order book depth channel format

{
    "table": "depth",
    "data": {
        "seqNum": 2166539633781384,
        "asks": [
            [
                19024.0,
                1.0
            ],
            [
                19205.0,
                4.207
            ],
            [
                19395.0,
                8.414
            ]
        ],
        "bids": [
            [
                18986.0,
                1.0
            ],
            [
                18824.0,
                4.207
            ],
            [
                18634.0,
                8.414
            ]
        ],
        "checksum": 3475315026,
        "marketCode": "BTC-USD-SWAP-LIN",
        "timestamp": 1665454814328
    },
    "action": "partial"
}

Channel Update Frequency: 100ms

This order book depth channel sends a snapshot of the entire order book every 100ms.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
args LIST Yes List of individual markets <depth>:<marketCode> e.g: [depth:BTC-USD-SWAP-LIN]

Channel Update Fields

Fields Type Description
table STRING depth
data DICTIONARY
seqNum INTEGER Sequence number of the order book snapshot
asks LIST of floats Sell side depth;
  1. price
  2. quantity
bids LIST of floats Buy side depth;
  1. price
  2. quantity
checksum INTEGER marketCode
marketCode STRING marketCode
timestamp INTEGER Millisecond timestamp
action STRING

Incremental Order Book

Request format

{
    "op": "subscribe",
    "tag": "test1",
    "args": [
        "depthUpdate:BTC-USD-SWAP-LIN"
    ]
}

Success response format

{
    "success": true,
    "tag": "test1",
    "event": "subscribe",
    "channel": "depthUpdate:BTC-USD-SWAP-LIN",
    "timestamp": "1665456142779"
}

** depth update channel format**

{
    "table": "depthUpdate-diff",
    "data": {
        "seqNum": 2166539633794590,
        "asks": [],
        "bids": [],
        "checksum": 364462986,
        "marketCode": "BTC-USD-SWAP-LIN",
        "timestamp": "1665456142843"
    },
    "action": "increment"
}
{
    "table": "depthUpdate",
    "data": {
        "seqNum": 2166539633794591,
        "asks": [
            [
                19042.0,
                1.0
            ]
        ],
        "bids": [
            [
                19003.0,
                1.0
            ]
        ],
        "checksum": 2688268653,
        "marketCode": "BTC-USD-SWAP-LIN",
        "timestamp": "1665456142843"
    },
    "action": "partial"
}

Channel Update Frequency: 100ms

Incremental order book stream

Usage Instructions: 1. Connect to websocket wss://v2api.coinflex.com/v2/websocket 2. Subscribe to depthUpdate and you will get a message reply saying your subscription is successful 3. Afterwards you will get a snapshot of the book with table:depthUpdate 4. If you receive a reply with table:depthUpdate-diff first, keep it locally and wait for snapshot reply in step 3 5. The first incremental depthUpdate-diff message should have the same seqNum as the depthUpdate snapshot 6. After that, each new incremental update should have an incrementally larger seqNum to the previous update 7. The data in each event represents the absolute quantity for a price level. 8. If the quantity is 0, remove the price level.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply
args LIST Yes List of individual markets <depthUpdate>:<marketCode> e.g: ["depthUpdate:BTC-USD-SWAP-LIN"]

Channel Update Fields

Fields Type Description
table STRING depthUpdate-diff depthUpdate
data DICTIONARY
seqNum INTEGER Sequence number of the order book snapshot
asks LIST of floats Sell side depth;
  1. price
  2. quantity
bids LIST of floats Buy side depth;
  1. price
  2. quantity
marketCode STRING marketCode
checksum LONG
timestamp STRING Millisecond timestamp
action STRING partial increment

Best Bid/Ask

Request format

{
    "op": "subscribe",
    "tag": "test1",
    "args": [
        "bestBidAsk:BTC-USD-SWAP-LIN"
    ]
}

Success response format

{
    "success": true,
    "tag": "test1",
    "event": "subscribe",
    "channel": "bestBidAsk:BTC-USD-SWAP-LIN",
    "timestamp": "1665456882918"
}

** depth update channel format**

{
    "table": "bestBidAsk",
    "data": {
        "ask": [
            19045.0,
            1.0
        ],
        "checksum": 3790706311,
        "marketCode": "BTC-USD-SWAP-LIN",
        "bid": [
            19015.0,
            1.0
        ],
        "timestamp": "1665456882928"
    }
}

Channel Update Frequency: Real-time

This websocket subscription streams the best bid and ask in real-time. Messages are pushed on every best bid/ask update in real-time

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply
args LIST Yes List of individual markets <bestBidAsk>:<marketCode> e.g: ["bestBidAsk:BTC-USD-SWAP-LIN"]

Channel Update Fields

Fields Type Description
table STRING bestBidAsk
data DICTIONARY
asks LIST of floats Sell side depth;
  1. price
  2. quantity
bids LIST of floats Buy side depth;
  1. price
  2. quantity
checksum LONG
marketCode STRING marketCode
timestamp STRING Millisecond timestamp

Trade

Request format

{
  "op": "subscribe",
  "tag": 1,
  "args": ["trade:BTC-USD-SWAP-LIN"]
}
import websockets
import asyncio
import json

trade = \
{
  "op": "subscribe",
  "tag": 1,
  "args": ["trade:BTC-USD-SWAP-LIN"]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                await ws.send(json.dumps(trade))
            elif 'success' in data and data['success'] == 'True':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "subscribe", 
  "channel": ["trade:BTC-USD-SWAP-LIN"], 
  "success": True, 
  "tag": "1", 
  "timestamp": "1594299886880"
}

Trade channel format

{
  "table": "trade",
  "data": [ {
              "side": "buy",
              "tradeId": "2778148208082945",
              "price": "5556.91",
              "quantity": "5",
              "matchType": "MAKER",
              "marketCode": "BTC-USD-SWAP-LIN",
              "timestamp": "1594299886890"
            } ]
}

Channel Update Frequency: real-time, with every order matched event

This trade channel sends public trade information whenever an order is matched on the order book.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
args LIST Yes list of individual markets trade:<marketCode>

Channel Update Fields

Fields Type Description
table STRING trade
data LIST of dictionary
tradeId STRING Transaction Id
price STRING Matched price
quantity STRING Matched quantity
matchType STRING TAKER or MAKER
side STRING Matched side
timestamp STRING Matched timestamp
marketCode STRING Market code

Ticker

Request format

{
  "op": "subscribe", 
  "tag": 1,
  "args": ["ticker:all"]
}

OR

{
  "op": "subscribe", 
  "tag": 1,
  "args": ["ticker:FLEX-USD", ........]
}
import websockets
import asyncio
import json

ticker = \
{
  "op": "subscribe",
  "tag": 1,
  "args": ["ticker:all"]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                await ws.send(json.dumps(ticker))
            elif 'success' in data and data['success'] == 'True':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "subscribe", 
  "channel": "<args value>",
  "success": True,
  "tag": "1",
  "timestamp": "1594299886890"
}

Channel update format

{
    "table": "ticker",
    "data": [
        {
            "last": "0",
            "open24h": "2.80500000",
            "high24h": "3.39600000",
            "low24h": "2.53300000",
            "volume24h": "0",
            "currencyVolume24h": "0",
            "openInterest": "0",
            "marketCode": "1INCH-USD",
            "timestamp": "1622020931049",
            "lastQty": "0",
            "markPrice": "3.304",
            "lastMarkPrice": "3.304"
        },
        {
            "last": "0",
            "open24h": "2.80600000",
            "high24h": "3.39600000",
            "low24h": "2.53300000",
            "volume24h": "0",
            "currencyVolume24h": "0",
            "openInterest": "0",
            "marketCode": "1INCH-USD-SWAP-LIN",
            "timestamp": "1622020931046",
            "lastQty": "0",
            "markPrice": "3.304",
            "lastMarkPrice": "3.304"
        },
        ...
    ]
}

Channel Update Frequency: 500 ms

The ticker channel pushes live price and volume information about the contract.

The websocket will reply with the shown success response format for each ticker channel which has been successfully subscribed to.

The data array in the message from this ticker channel will contain a single JSON corresponding to one ticker subscription.

If you subcribe "ticker:all", you would get one whole message containing all markets.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
args LIST Yes ticker:all or a list of individual markets ticker:<marketCode>

Channel Update Fields

Fields Type Description
table STRING ticker
data LIST of dictionary
marketCode STRING Market code
last STRING Last traded price
markPrice STRING Mark price
open24h STRING 24 hour rolling opening price
volume24h STRING 24 hour rolling trading volume in counter currency
currencyVolume24h STRING 24 hour rolling trading volume in base currency
high24h STRING 24 hour highest price
low24h STRING 24 hour lowest price
openInterest STRING Open interest
lastQty STRING Last traded price amount
timestamp STRING Millisecond timestamp

Candles

Request format

{
  "op": "subscribe", 
  "tag": 1,
  "args": ["candles60s:BTC-USD-SWAP-LIN"]
}
import websockets
import asyncio
import json

candles = \
{
  "op": "subscribe",
  "tag": 1,
  "args": ["candles60s:BTC-USD-SWAP-LIN"]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                await ws.send(json.dumps(candles))
            elif 'success' in data and data['success'] == 'True':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "subscribe", 
  "channel": ["candles60s:BTC-USD-SWAP-LIN"], 
  "success": True, 
  "tag": "1", 
  "timestamp": "1594313762698"
}

Channel update format

{
  "table": "candle60s",
  "data": [ {
              "marketCode": "BTC-USD-SWAP-LIN",
              "candle": [
                "1594313762698", //timestamp
                "9633.1",        //open
                "9693.9",        //high
                "9238.1",        //low
                "9630.2",        //close
                "45247",         //volume in counter currency
                "5.3"            //volume in base currency
              ]
          } ]
}

Channel Update Frequency: 500ms

Granularity: 60s, 180s, 300s, 900s, 1800s, 3600s, 7200s, 14400s, 21600s, 43200s, 86400s

The candles channel pushes candlestick data for the current candle.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
args LIST Yes list of individual candle granularity and market candles<granularity>:<marketCode>

Channel Update Fields

Fields Type Description
table STRING candles<granularity>
data LIST of dictionary
marketCode STRING Market code
candle LIST of strings
  1. timestamp
  2. open
  3. high
  4. low
  5. close
  6. volume in counter currency
  7. volume in base currency

Liquidation RFQ

Request format

{
  "op": "subscribe", 
  "tag": 1,
  "args": ["liquidationRFQ"]
}
import websockets
import asyncio
import json

liquidation = \
{
  "op": "subscribe", 
  "tag": 1,
  "args": ["liquidationRFQ"]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                await ws.send(json.dumps(liquidation))
            elif 'success' in data and data['success'] == 'True':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "subscribe", 
  "channel": "liquidationRFQ", 
  "success": True, 
  "tag": "1", 
  "timestamp": "1613774604469"
}

Channel update format

{
  "table": "liquidationRFQ",
  "data": [ {
              "marketCode": "BTC-USD-SWAP-LIN"
              "timestamp": "1613774607889"
          } ]
}

Channel Update Frequency: real-time, whenever there is planned liquidation event of a clients position OR an auto-borrow OR an auto-borrow repayment

The liquidation RFQ (request for quotes) channel publishes a message 50ms before a liquidation event is due to occur. A liquidation event can be classed as one of the following:-

The message will contain the market code and is designed to give users an opportunity to make a 2 way market for the upcoming liquidation event.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
args Single element LIST Yes liquidationRFQ

Channel Update Fields

Fields Type Description
table STRING liquidationRFQ
data LIST of dictionary
marketCode STRING Market code of liquidation
timestamp STRING Millisecond timestamp

Market

Request format

{
  "op": "subscribe", 
  "tag": 1,
  "args": ["market:all"]
}

OR

{
  "op": "subscribe", 
  "tag": 1,
  "args": ["market:FLEX-USD", ........]
}
import websockets
import asyncio
import json

market = \
{
  "op": "subscribe",
  "tag": 1,
  "args": ["market:all"]
}

url= 'wss://v2stgapi.coinflex.com/v2/websocket'
async def subscribe():
    async with websockets.connect(url) as ws:
        while True:
            if not ws.open:
                print("websocket disconnected")
                ws = await websockets.connect(url)
            response = await ws.recv()
            data = json.loads(response)
            print(data)
            if 'nonce' in data:
                await ws.send(json.dumps(market))
            elif 'success' in data and data['success'] == 'True':
                continue
asyncio.get_event_loop().run_until_complete(subscribe())

Success response format

{
  "event": "subscribe", 
  "channel": "<args value>",
  "success": True,
  "tag": "1",
  "timestamp": "1594299886890"
}

Channel update format

{
  "table": "market",
  "data": [ {
              "marketPrice": "0.367",
              "listingDate": "1593288000000", 
              "qtyIncrement": "0.1", 
              "upperPriceBound": "0.417", 
              "lowerPriceBound": "0.317", 
              "counter": "USD", 
              "type": "SPOT", 
              "marketId": "3001000000000", 
              "referencePair": "FLEX/USD", 
              "tickSize": "0.001", 
              "marketPriceLastUpdated": "1613769981920", 
              "contractValCurrency": "FLEX", 
              "name": "FLEX/USD Spot", 
              "marketCode": "FLEX-USD", 
              "marginCurrency": "USD", 
              "base": "FLEX"
          }, 
          ........
        ]
}

Channel Update Frequency: 1s

The market channel pushes live information about the market such as the current market price and the lower & upper sanity bounds as well as reference data related to the market.

The websocket will reply with the shown success response format for each market which has been successfully subscribed to.

If a subscription has been made to market:all, the data array in the message from this channel will contain a JSON list of all markets. Each JSON will contain information for each market seperately. Otherwise the data array will contain a single JSON corresponding to one market per market channel subscription.

Request Parameters

Parameters Type Required Description
op STRING Yes subscribe
tag INTEGER or STRING No If given it will be echoed in the reply and the max size of tag is 32
args LIST Yes market:all or a list of individual markets market:<marketCode>

Channel Update Fields

Fields Type Description
table STRING market
data LIST of dictionaries
marketPrice STRING Mark price
listingDate STRING Millisecond timestamp
qtyIncrement STRING Quantity increment
upperPriceBound STRING Upper sanity price bound
lowerPriceBound STRING Lower sanity price bound
counter STRING
type STRING
marketId STRING
referencePair STRING
tickSize STRING Tick size
marketPriceLastUpdated STRING Millisecond timestamp
contractValCurrency STRING
name STRING
marketCode STRING
marginCurrency STRING
base STRING

Other Responses

By subscribing to an authenticated websocket there may be instances when a REST method will also generate a websocket reponse in addition to the REST reply. There are also some GUI commands which will generate a websocket reponse.

Cancel All Open Orders

Success response format

{
  "event": "CANCEL",
  "submitted": True,
  "timestamp": "1612476498953"
}

Documentation for the REST method for cancelling all open orders for an account can be found here Cancel All Orders.

Documentation for the REST method for cancelling all open orders by market for an account can be found here Cancel All Orders By Market.

In both these instances a successful action will generate the shown repsonse in an authenticated websocket.

This action can also be executed via the trading GUI using the Cancel All button on the Open Orders blotter for both Spot and Derivative markets.

Error Codes

Failure response format

{
  "event": "<opValue>",
  "message": "<errorMessage>",
  "code": "<errorCode>",
  "success": False
}

Both subscription and order command requests sent via websocket can be rejected and the failure response will return an error code and a corresponding error message explaining the reason for the rejection.

Code Error Message
05001 Your operation authority is invalid
20000 Signature is invalid
20001 Operation failed, please contact system administrator
20002 Unexpected error, please check if your request data complies with the specification.
20003 Unrecognized operation
20005 Already logged in
20006 Quantity must be greater than zero
20007 You are accessing server too rapidly
20008 clientOrderId must be greater than zero if provided
20009 JSON data format is invalid
20010 Either clientOrderId or orderId is required
20011 marketCode is required
20012 side is required
20013 orderType is required
20014 clientOrderId is not long type
20015 marketCode is invalid
20016 side is invalid
20017 orderType is invalid
20018 timeInForce is invalid
20019 orderId is invalid
20020 stopPrice or limitPrice is invalid
20021 price is invalid
20022 price is required for LIMIT order
20023 timestamp is required
20024 timestamp exceeds the threshold
20025 API key is invalid
20026 Token is invalid or expired
20027 The length of the message exceeds the maximum length
20028 price or stopPrice or limitPrice must be greater than zero
20029 stopPrice must be less than limitPrice for Buy Stop Order
20030 limitPrice must be less than stopPrice for Sell Stop Order
20031 The marketCode is closed for trading temporarily
20032 Failed to submit due to timeout in server side
20033 triggerType is invalid
20034 The size of tag must be less than 32
300011 Repo market orders are not allowed during the auction window
300012 Repo bids above 0 and offers below 0 are not allowed during the auction window
100005 Open order not found with id
100006 Open order does not match to the given account
200050 The market is not active
710002 FAILED sanity bound check as price (.....) < lower bound (.....)
710003 FAILED sanity bound check as price (.....) > upper bound (.....)
710004 FAILED net position check as position (.....) > threshold (.....)
710005 FAILED margin check as collateral (.....) < var (.....)
710006 FAILED balance check as balance (.....) < value (.....)

REST API V2

TEST site

LIVE site

For clients who do not wish to take advantage of CoinFLEX's native WebSocket API, CoinFLEX offers a RESTful API that implements much of the same functionality.

Authentication

Request

{
  "Content-Type": "application/json",
  "AccessKey": "<string>",
  "Timestamp": "<string>", 
  "Signature": "<string>", 
  "Nonce": "<string>"
}
import requests
import hmac
import base64
import hashlib
import datetime
from urllib.parse import urlencode

rest_url = 'https://v2stgapi.coinflex.com'
rest_path = 'v2stgapi.coinflex.com'

api_key = <API-KEY>
api_secret = <API-SECRET>

ts = datetime.datetime.utcnow().isoformat()
nonce = 123
method = <API-METHOD>

# Optional and can be omitted depending on the REST method being called 
body = urlencode({'key1': 'value1', 'key2': 'value2'})

if body:
    path = method + '?' + body
else:
    path = method

msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, body)
sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')

header = {'Content-Type': 'application/json', 'AccessKey': api_key,
          'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}

resp = requests.get(rest_url + path, headers=header)
print(resp.json())

Public market data methods do not require authentication, however private methods require a Signature to be sent in the header of the request. These private REST methods use HMAC SHA256 signatures.

The HMAC SHA256 signature is a keyed HMAC SHA256 operation using a clients API Secret as the key and a message string as the value for the HMAC operation.

The message string is constructed by the following formula:-

msgString = Timestamp + "\n" + Nonce + "\n" + Verb + "\n" + URL + "\n" + Path +"\n" + Body

Component Required Example Description
Timestamp Yes 2020-04-30T15:20:30 YYYY-MM-DDThh:mm:ss
Nonce Yes 123 User generated
Verb Yes 'GET' Uppercase
Path Yes 'v2stgapi.coinflex.com'
Method Yes '/v2/positions Available REST methods:
  • V2/positions
  • V2/orders
  • V2/balances
  • Body No instrumentID=BTC-USD-SWAP-LIN Optional and dependent on the REST method being called

    The constructed message string should look like:-

    2020-04-30T15:20:30\n 123\n GET\n v2stgapi.coinflex.com\n /v2/positions\n instrumentID=BTC-USD-SWAP-LIN

    Note the newline characters after each component in the message string. If Body is ommitted it's treated as an empty string.

    Finally you must use the HMAC SHA256 operation to get the hash value using the API Secret as the key and the constructed message string as the value for the HMAC operation. Then encode this hash value with BASE-64. This output becomes the signature for the specified authenticated REST API method.

    The signature must then be included in the header of the REST API call like so:

    header = {'Content-Type': 'application/json', 'AccessKey': API-KEY, 'Timestamp': TIME-STAMP, 'Signature': SIGNATURE, 'Nonce': NONCE}

    Methods - Private

    All private REST API methods require authentication using the approach explained above.

    GET /v2/accountinfo

    Request

    GET /v2/accountinfo
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/accountinfo'
    
    params = ""
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
        "event": "accountinfo",
        "timestamp": "1648800334773",
        "accountId": "677473",
        "data": [
            {
                "accountId": "677473",
                "tradeType": "LINEAR",
                "marginCurrency": "USD",
                "totalBalance": "33860283.6914636",
                "availableBalance": "33860283.6914636",
                "collateralBalance": "28661274.5806472",
                "portfolioVarMargin": "910198.2835522",
                "riskRatio": "31.4890",
                "timestamp": "1648800334761"
            }
        ]
    }
    
    {
        "event": "accountinfo",
        "timestamp": "1648800334773",
        "accountId": "677473",
        "data": [
            {
                "accountId": "677473",
                "tradeType": "LINEAR",
                "marginCurrency": "USD",
                "totalBalance": "33860283.6914636",
                "availableBalance": "33860283.6914636",
                "collateralBalance": "28661274.5806472",
                "portfolioVarMargin": "910198.2835522",
                "riskRatio": "31.4890",
                "timestamp": "1648800334761"
            }
        ]
    }
    

    Returns the account level information connected to the API key initiating the request.

    Response Fields

    Fields Type Description
    event STRING accountinfo
    timestamp STRING Millisecond timestamp
    accountId STRING Account ID
    data LIST of dictionary
    accountId STRING Account ID
    tradeType STRING Account type LINEAR
    marginCurrency STRING Asset USD
    totalBalance STRING Total balance denoted in marginCurrency
    collateralBalance STRING Collateral balance with LTV applied
    availableBalance STRING Available balance
    portfolioVarMargin STRING Portfolio margin
    riskRatio STRING collateralBalance / portfolioVarMargin, Orders are rejected/cancelled if the risk ratio drops below 1 and liquidation occurs if the risk ratio drops below 0.5
    timestamp STRING Millisecond timestamp

    GET /v2/balances

    Request

    GET /v2/balances
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/balances'
    
    params = ""
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
        "event": "balances",
        "timestamp": "1648800661246",
        "accountId": "677473",
        "tradeType": "LINEAR",
        "data": [
            {
                "instrumentId": "1INCH",
                "total": "100.00000000",
                "available": "100.00000000",
                "reserved": "0.00000000",
                "quantityLastUpdated": "1646413705113"
            },
            {
                "instrumentId": "AAVE",
                "total": "100.00000000",
                "available": "100.00000000",
                "reserved": "0.00000000",
                "quantityLastUpdated": "1646413705827"
            }
        ]
    }
    
    {
        "event": "balances",
        "timestamp": "1648800661246",
        "accountId": "677473",
        "tradeType": "LINEAR",
        "data": [
            {
                "instrumentId": "1INCH",
                "total": "100.00000000",
                "available": "100.00000000",
                "reserved": "0.00000000",
                "quantityLastUpdated": "1646413705113"
            },
            {
                "instrumentId": "AAVE",
                "total": "100.00000000",
                "available": "100.00000000",
                "reserved": "0.00000000",
                "quantityLastUpdated": "1646413705827"
            }
        ]
    }
    

    Returns all the coin balances of the account connected to the API key initiating the request.

    Response Fields

    Field Type Description
    event STRING balances
    timestamp STRING Millisecond timestamp
    accountId STRING Account ID
    tradeType STRING LINEAR
    data LIST of dictionaries
    instrumentId STRING Coin symbol, e.g. 'BTC'
    total STRING Total balance
    available STRING Available balance
    reserved STRING Reserved balance (unavailable) due to working spot orders
    quantityLastUpdated STRING Millisecond timestamp of when balance was last updated

    GET /v2/balances/{instrumentId}

    Request

    GET /v2/balances/{instrumentId}
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/balances/{instrumentId}'
    
    params = "limit=3"
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "balancesById",
      "timestamp": 1593627415293,
      "accountId": "<Your Account ID>",
      "tradeType": "LINEAR",
      "data": [ {   
                  "instrumentId": "FLEX",
                  "total": "4468.823",              
                  "available": "4468.823",        
                  "reserved": "0",
                  "quantityLastUpdated": "1593627415001"
                } ]
    }
    
    {
        "event": "balancesById",
        "timestamp": "1648813214792",
        "accountId": "677473",
        "tradeType": "LINEAR",
        "data": {
            "instrumentId": "FLEX",
            "total": "695180.143917630",
            "available": "695180.143917630",
            "reserved": "0",
            "quantityLastUpdated": "1648809926359"
        }
    }
    

    Returns the specified coin balance of the account connected to the API key initiating the request.

    Request Paramters

    Parameter Type Required Description
    instrumentId STRING YES Please place it in URL

    Response Fields

    Field Type Description
    event STRING balancesById
    timestamp INTEGER Millisecond timestamp
    accountId STRING Account ID
    tradeType STRING LINEAR
    data LIST of dictionary
    instrumentId STRING Coin symbol, e.g. 'FLEX'
    total STRING Total balance
    available STRING Available balance
    reserved STRING Reserved balance (unavailable) due to working spot orders
    quantityLastUpdated STRING Timestamp when was balance last updated

    GET /v2/positions

    Request

    GET /v2/positions
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/positions'
    
    params = "limit=3"
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "positions",
      "timestamp": 1593627415000,
      "accountId":"<Your Account ID>",
      "data": [ {
                  "instrumentId": "BTC-USD-SWAP-PER",
                  "quantity": "0.542000000",
                  "lastUpdated": "1617099855966",
                  "contractValCurrency": "BTC",
                  "entryPrice": "56934.8258",
                  "positionPnl": "1212.0065",
                  "estLiquidationPrice": "52454.3592",
                  "marginBalance": "1000.32",
                  "maintenanceMargin": "300.32",
                  "marginRatio": "0.4",
                  "leverage": "2"
                },
                ...
              ]
    }
    
    {
        "event": "positions", 
        "timestamp": "1648813006698", 
        "accountId": "677473", 
        "data": [
            {
                "instrumentId": "ETH-USD-SWAP-LIN", 
                "quantity": "-461.64", 
                "lastUpdated": "1648518794680", 
                "contractValCurrency": "ETH", 
                "entryPrice": "3405.16", 
                "positionPnl": "51675.9816", 
                "estLiquidationPrice": "64473.25"
            }, 
            {
                "instrumentId": "FLEX-USD-SWAP-LIN", 
                "quantity": "38742.4", 
                "lastUpdated": "1648174875502", 
                "contractValCurrency": "FLEX", 
                "entryPrice": "7.989", 
                "positionPnl": "-387.4240", 
                "estLiquidationPrice": "0",
            }, 
            {
                "instrumentId": "BTC-USD-SWAP-PER", 
                "quantity": "65.889", 
                "lastUpdated": "1648806900492", 
                "contractValCurrency": "BTC", 
                "entryPrice": "47642", 
                "positionPnl": "-441817.260", 
                "estLiquidationPrice": "0"
                "marginBalance": "1000.32",
                "maintenanceMargin": "300.32",
                "marginRatio": "0.4",
                "leverage": "2"
            }
        ]
    }
    

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

    Response Fields Type Description
    event STRING positions
    timestamp INTEGER Millisecond timestamp
    accountId STRING Account ID
    data LIST of dictionaries
    instrumentId STRING Contract symbol, e.g. 'BTC-USD-SWAP-LIN'
    quantity STRING Quantity of position, e.g. '0.94'
    lastUpdated STRING Timestamp when position was last updated
    contractValCurrency STRING Contract valuation currency
    entryPrice STRING Average entry price
    positionPnl STRING Postion profit and lost
    estLiquidationPrice STRING Estimated liquidation price, return 0 if it is negative(<0)
    marginBalance STRING Appears in the position section only for positions using isolated margin. Isolated margin + Unrealized position PnL
    maintenanceMargin STRING Appears in the position section only for positions using isolated margin
    marginRatio STRING Appears in the position section only for positions using isolated margin
    leverage STRING Appears in the position section only for positions using isolated margin

    GET /v2/positions/{instrumentId}

    Request

    GET /v2/positions/{instrumentId}
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/positions/{instrumentId}'
    
    params = "limit=3"
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "positionsById",
      "timestamp": 1593617005438,
      "accountId":"<Your Account ID>",
      "data": [ {
                  "instrumentId": "BTC-USD-SWAP-PER",
                  "quantity": "0.542000000",
                  "lastUpdated": "1617099855966",
                  "contractValCurrency": "BTC",
                  "entryPrice": "56934.8258",
                  "positionPnl": "1216.6135",
                  "estLiquidationPrice": "53171.16",
                  "marginBalance": "1000.32",
                  "maintenanceMargin": "300.32",
                  "marginRatio": "0.4",
                  "leverage": "2"
              } ]
    }
    
    {
        "event": "positionsById",
        "timestamp": "1648812534064",
        "accountId": "677473",
        "data": {
            "instrumentId": "FLEX-USD-SWAP-PER",
            "quantity": "38742.4",
            "lastUpdated": "1648174875502",
            "contractValCurrency": "FLEX",
            "entryPrice": "7.989",
            "positionPnl": "-387.4240",
            "estLiquidationPrice": "0",
            "marginBalance": "1000.32",
            "maintenanceMargin": "300.32",
            "marginRatio": "0.4",
            "leverage": "2"
        }
    }
    

    Returns the specified instrument ID position of the account connected to the API key initiating the request.

    Request Parameter Type Required Description
    instrumentId STRING YES Please place it in URL
    Response Field Type Description
    event STRING positionsById
    timestamp INTEGER Millisecond timestamp
    accountId STRING Account ID
    data LIST of dictionaries
    instrumentId STRING Contract symbol, e.g. 'FLEX-USD-SWAP-LIN'
    quantity STRING Quantity of position, e.g. '0.94'
    lastUpdated STRING Timestamp when position was last updated
    contractValCurrency STRING Contract valuation currency
    entryPrice STRING Average entry price
    positionPnl STRING Postion profit and lost
    estLiquidationPrice STRING Estimated liquidation price, return 0 if it is negative(<0)
    marginBalance STRING Appears in the position section only for positions using isolated margin. Isolated margin + Unrealized position PnL
    maintenanceMargin STRING Appears in the position section only for positions using isolated margin
    marginRatio STRING Appears in the position section only for positions using isolated margin
    leverage STRING Appears in the position section only for positions using isolated margin

    GET /v2/trades/{marketCode}

    Request

    GET /v2/trades/{marketCode}?limit={limit}&startTime={startTime}&endTime={endTime}
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/trades/{marketCode}'
    
    params = "limit=3"
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "trades", 
      "timestamp": 1595635101845, 
      "accountId": "<Your Account ID>", 
      "data": [ {
                  "matchId": "160067484555913077", 
                  "matchTimestamp": "1595514663626", 
                  "marketCode": "FLEX-USD", 
                  "matchQuantity": "0.1", 
                  "matchPrice": "0.065", 
                  "total": "0.0065", 
                  "orderMatchType": "TAKER", 
                  "fees": "0.0096", 
                  "feeInstrumentId": "FLEX", 
                  "orderId": "160067484555913076", 
                  "side": "SELL", 
                  "clientOrderId": "123"
                },
                ...
              ]
    }
    
    {
        "event": "trades",
        "timestamp": "1648812102411",
        "accountId": "677473",
        "data": [
            {
                "matchId": "448821476099870304",
                "matchTimestamp": "1648809926245",
                "marketCode": "FLEX-USD",
                "matchQuantity": "1",
                "matchPrice": "10",
                "total": "10",
                "orderMatchType": "MAKER",
                "fees": "0",
                "feeInstrumentId": null,
                "orderId": "1000200608142",
                "side": "SELL",
                "clientOrderId": "1612249737434"
            },
            {
                "matchId": "448821476099870303",
                "matchTimestamp": "1648809926245",
                "marketCode": "FLEX-USD",
                "matchQuantity": "1",
                "matchPrice": "10",
                "total": "10",
                "orderMatchType": "MAKER",
                "fees": "0",
                "feeInstrumentId": null,
                "orderId": "1000200608140",
                "side": "SELL",
                "clientOrderId": "1612249737434"
            },
            {
                "matchId": "448821476099861874",
                "matchTimestamp": "1648807731185",
                "marketCode": "FLEX-USD",
                "matchQuantity": "1",
                "matchPrice": "10",
                "total": "10",
                "orderMatchType": "MAKER",
                "fees": "0",
                "feeInstrumentId": null,
                "orderId": "1000200596577",
                "side": "SELL",
                "clientOrderId": "1612249737434"
            }
        ]
    }
    

    Returns the most recent trades of the account connected to the API key initiating the request.

    Request Parameters

    Parameters Type Required Description
    marketCode STRING YES Please place it in URL
    limit LONG NO Default 500, max 1000
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other

    Response Fields

    Field Type Description
    event STRING trades
    timestamp INTEGER Millisecond timestamp
    accountId STRING Account ID
    data LIST of dictionaries
    matchId STRING Match ID
    matchTimestamp STRING Order Matched timestamp
    marketCode STRING Market code
    matchQuantity STRING Match quantity
    matchPrice STRING Match price
    total STRING Total price
    side STRING Side of the match
    orderMatchType STRING TAKER or MAKER
    fees STRING Fees
    feeInstrumentId STRING Instrument ID of the fees
    orderId STRING Unique order ID from the exchange
    clientOrderID STRING Client assigned ID to help manage and identify orders

    GET /v2/orders

    Request

    GET /v2/orders
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/orders'
    
    params = ""
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "orders",
      "timestamp": "1593617005438",
      "accountId": "<Your Account ID>",
      "data": [ {
                  "orderId": "160039151345856176",
                  "marketCode": "BTC-USD-SWAP-LIN",
                  "clientOrderId": null|"<clientOrderId>",              
                  "side": "BUY",
                  "orderType": "LIMIT"|"STOP",
                  "quantity": "1.00",
                  "remainingQuantity": "1.00",
                  "price": "1.00"|null,               #for limit order, null for stop order
                  "stopPrice": "<stopPrice>"|null,    #for stop order, null for limit order 
                  "limitPrice": "<limitPrice>"|null,  #for stop order, null for limit order 
                  "orderCreated": 1593617008698,
                  "lastModified": 1593617008698,
                  "lastTradeTimestamp": 1593617008698,
                  "timeInForce": "GTC"
                },
                ...
              ]
    }
    
    {
        "event": "orders", 
        "timestamp": "1648809819657", 
        "accountId": "677473", 
        "data": [
            {
                "orderId": "1000200608142", 
                "marketCode": "FLEX-USD", 
                "clientOrderId": "1612249737434", 
                "side": "SELL", 
                "orderType": "LIMIT", 
                "quantity": "1.0", 
                "remainingQuantity": "1.0", 
                "price": "10.0", 
                "stopPrice": null, 
                "limitPrice": "10.0", 
                "orderCreated": 1648809816385, 
                "lastModified": 1648809816591, 
                "lastTradeTimestamp": 1648809816557, 
                "timeInForce": "GTC"
            }, 
            {
                "orderId": "1000200608140", 
                "marketCode": "FLEX-USD", 
                "clientOrderId": "1612249737434", 
                "side": "SELL", 
                "orderType": "LIMIT", 
                "quantity": "1.0", 
                "remainingQuantity": "1.0", 
                "price": "10.0", 
                "stopPrice": null, 
                "limitPrice": "10.0", 
                "orderCreated": 1648809812567, 
                "lastModified": 1648809812773, 
                "lastTradeTimestamp": 1648809812680, 
                "timeInForce": "GTC"
            }
        ]
    }
    

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

    Response Fields

    Fields Type Description
    event STRING orders
    timestamp STRING Millisecond timestamp
    accountId STRING Account ID
    data LIST of dictionaries
    orderId STRING Unique order ID from the exchange
    marketCode STRING Market code
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    side STRING BUY or SELL
    orderType STRING LIMIT or STOP
    quantity STRING Quantity submitted
    remainingQuantity STRING Remainning quantity
    price STRING Price submitted
    stopPrice STRING Stop price for the stop order
    limitPrice STRING Limit price for the stop limit order
    orderCreated INTEGER Timestamp when order was created
    lastModified INTEGER Timestamp when order was last mordified
    lastTradeTimestamp INTEGER Timestamp when order was last traded
    timeInForce STRING Time in force

    GET /v2.1/orders

    Request

    GET /v2.1/orders?marketCode={marketCode}&orderId={orderId}&clientOrderId={clientOrderId}&limit={limit}&startTime={startTime}&endTime={endTime}
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_key'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2.1/orders'
    
    params = "marketCode=FLEX-USD&limit=1"
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
        "event": "orders",
        "timestamp": "1619167719563",
        "accountId": "1076",
        "data": [
            {
                "status": "OrderClosed",
                "orderId": "304408197314577142",
                "clientOrderId": "1",
                "marketCode": "BTC-USD-SWAP-LIN",
                "side": "BUY",
                "orderType": "LIMIT",
                "price": "10006.0",
                "quantity": "0.001",
                "remainQuantity": "0.001",
                "timeInForce": "GTC",
                "orderClosedTimestamp": "1619131050779"
            },
            {
                "status": "OrderOpened",
                "orderId": "304408197314577143",
                "clientOrderId": "2",
                "marketCode": "BTC-USD-SWAP-LIN",
                "side": "SELL",
                "orderType": "LIMIT",
                "price": "60006.0",
                "quantity": "0.001",
                "remainQuantity": "0.001",
                "timeInForce": "GTC",
                "orderOpenedTimestamp": "1619131049574"
            },
            {
                "status": "OrderMatched",
                "orderId": "448528458527567629",
                "clientOrderId": "1618870087524",
                "marketCode": "FLEX-USD-SWAP-LIN",
                "side": "BUY",
                "orderType": "MARKET",
                "price": "0.194",
                "lastTradedPrice": "0.170",
                "avgFillPrice": "0.170",
                "quantity": "12.1",
                "filledQuantity": "12.1",
                "remainQuantity": "0",
                "matchIds": [
                    {
                        "448528458527567630": {
                            "matchQuantity": "12.1",
                            "matchPrice": "0.170",
                            "timestamp": "1618870088471",
                            "orderMatchType": "TAKER"
                        }
                    }
                ],
                "fees": {
                    "FLEX": "-0.00440786"
                },
                "timeInForce": "IOC",
                "isTriggered": "false"
            },
            {
                "status": "OrderPartiallyMatched",
                "orderId": "1000028616860",
                "clientOrderId": "1619090944648",
                "marketCode": "BTC-USD-SWAP-LIN",
                "side": "SELL",
                "orderType": "MARKET",
                "price": "42970.5",
                "lastTradedPrice": "43026.0",
                "avgFillPrice": "43026.0",
                "quantity": "0.112",
                "filledQuantity": "0.002",
                "remainQuantity": "0.11",
                "matchIds": [
                    {
                        "304515168532122149": {
                            "matchQuantity": "0.001",
                            "matchPrice": "43026.0",
                            "timestamp": "1628824216325",
                            "orderMatchType": "TAKER"
                        }
                    },
                    {
                        "304515168532122150": {
                            "matchQuantity": "0.001",
                            "matchPrice": "43026.0",
                            "timestamp": "1628824216326",
                            "orderMatchType": "TAKER"
                        }
                    }
                ]
            }
            ...
        ]
    }
    
    {
        "event": "orders",
        "timestamp": "1648809055324",
        "accountId": "677473",
        "data": [
            {
                "status": "OrderMatched",
                "orderId": "1000200596577",
                "clientOrderId": "1612249737434",
                "marketCode": "FLEX-USD",
                "side": "SELL",
                "orderType": "LIMIT",
                "price": "10.000",
                "lastTradedPrice": "10.000",
                "avgFillPrice": "10.000",
                "quantity": "1",
                "filledQuantity": "1",
                "remainQuantity": "0",
                "matchIds": [
                    {
                        "448821476099861874": {
                            "matchQuantity": "1",
                            "matchPrice": "10.000",
                            "timestamp": "1648807731185",
                            "orderMatchType": "MAKER"
                        }
                    }
                ],
                "timeInForce": "GTC",
                "isTriggered": "false"
            }
        ]
    }
    

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

    Request Parameters Type Required Description
    marketCode STRING NO Market code
    orderId LONG NO Client assigned ID to help manage and identify orders
    clientOrderId ULONG NO Client assigned ID to help manage and identify orders with max value 9223372036854775807
    limit LONG NO max 100, default 100
    startTime LONG NO e.g. 1579450778000, default 24 hours ago, the range between startTime and endTime should be less than or equal to 7 days(endTime - startTime <= 7days)
    endTime LONG NO e.g. 1613978625000, default time now, the range between startTime and endTime should be less than or equal to 7 days(endTime - startTime <= 7days)
    Response Fields Type Description
    accountId STRING Account ID
    timestamp STRING Timestamp of this response
    status STRING Status of the order, available values: OrderOpened, OrderPartiallyMatched, OrderMatched, OrderClosed
    orderId STRING Order ID which generated by the server
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    marketCode STRING Market code
    side STRING Side of the order, BUY or SELL
    orderType STRING Type of the order, LIMIT or STOP
    price STRING Price submitted
    lastTradedPrice STRING Price when order was last traded
    avgFillPrice STRING Average of filled price
    stopPrice STRING Stop price for the stop order
    limitPrice STRING Limit price for the stop limit order
    quantity STRING Quantity submitted
    remainQuantity STRING Remaining quantity
    filledQuantity STRING Filled quantity
    matchIds LIST of dictionaries Exchange matched IDs and information about matching orders
    matchQuantity STRING Matched quantity
    matchPrice STRING Matched price
    orderMatchType STRING MAKER or TAKER
    timestamp in matchIds STRING Time matched at
    leg1Price STRING
    leg2Price STRING
    fees LIST of dictionaries Overall fees with instrument ID, if FLEX is no enough to pay the fee then USD will be paid
    timeInForce STRING Time in force
    isTriggered STRING true(for stop order) or false
    orderOpenedTimestamp STRING Order opened at
    orderModifiedTimestamp STRING Order modified at
    orderClosedTimestamp STRING Order closed at

    DELETE /v2/cancel/orders

    Request

    DELETE /v2/cancel/orders 
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/cancel/orders'
    
    params = json.dumps({})
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'DELETE', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.delete(rest_url + method, headers=header, data=params)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "orders",
      "timestamp": 1594412077100,
      "accountId": "<AccountID>",
      "data": {
        "msg": "All open orders for the account have been queued for cancellation"
      }
    }
    
    {
        "event": "orders",
        "timestamp": "1648809641539",
        "accountId": "677473",
        "data": {
            "msg": "All open orders for the account have been queued for cancellation"
        }
    }
    

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

    If this REST method was sucessful it will also trigger a reponse message in an authenticated websocket of the account. This is documented here Cancel Open Orders.

    Response Parameters

    Parameters Type Description
    event STRING orders
    timestamp INTEGER Millisecond timestamp
    accountId STRING Account ID
    data Dictionary
    msg STRING Confirmation of action

    DELETE /v2/cancel/orders/{marketCode}

    Request

    DELETE /v2/cancel/orders/{marketCode}
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2/cancel/orders/{marketCode}'
    
    params = json.dumps({})
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'DELETE', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.delete(rest_url + method, headers=header, data=params)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "orders",
      "timestamp": 1594412077100,
      "accountId": "<AccountID>",
      "data": {
                "marketCode": "FLEX-USD",
                "msg": "All open orders for the specified market have been queued for cancellation"
              }
    }
    
    {
        "event": "orders",
        "timestamp": "1648807731741",
        "accountId": "3101",
        "data": {
            "marketCode": "BTC-USD-SWAP-LIN",
            "msg": "All open orders for the specified market have been queued for cancellation"
        }
    }
    

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

    If this REST method was sucessful it will also trigger a reponse message in an authenticated websocket of the account. This is documented here Cancel Open Orders.

    Request Parameter Type Required Description
    marketCode STRING YES Please place it in URL
    Response Fields Type Description
    event STRING orders
    timestamp INTEGER Millisecond timestamp
    accountId STRING Account ID
    data Dictionary
    marketCode STRING Market code
    msg STRING Confirmation of action

    GET /v2.1/delivery/orders

    Request

    GET /v2.1/delivery/orders?limit={limit}&startTime={startTime}&endTime={endTime}
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    # REST API method
    method = '/v2.1/delivery/orders'
    
    params = "limit=1"
    
    if params:
        path = method + '?' + params
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    Response

    {
      "event": "deliverOrders",
      "timestamp": "1596685339910",
      "data": [ {
                  "timestamp": "1595781719394",
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "status": "DELIVERED",
                  "quantity": null,
                  "deliverPrice": "9938.480000000",
                  "transferAsset": "USD",
                  "transferQty": "993.848000000",
                  "instrumentIdDeliver": "BTC",
                  "deliverQty": "0.100000000",
                  "deliverOrderId": "575770851486007299",
                  "clientOrderId": null
                },
                {
                  "timestamp": "1595786511155",
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "status": "CANCELLED",
                  "quantity": null,
                  "deliverPrice": "9911.470000000",
                  "transferAsset": "USD",
                  "transferQty": "0.000000000",
                  "instrumentIdDeliver": "BTC",
                  "deliverQty": "0.000000000",
                  "deliverOrderId": "575786553086246913",
                  "clientOrderId": null
                },
              ]
    }
    
    {
        "event": "deliverOrders",
        "timestamp": "1648806915444",
        "data": [
            {
                "timestamp": "1648806900463",
                "instrumentId": "BTC-USD-SWAP-LIN",
                "status": "PENDING",
                "quantity": "0.100000000",
                "deliverPrice": "45131.000000000",
                "transferAsset": "USD",
                "transferQty": "4513.100000000",
                "instrumentIdDeliver": "BTC",
                "deliverQty": "0.000000000",
                "deliverOrderId": "749523764730920963",
                "clientOrderId": null
            }
        ]
    }
    

    Returns the entire delivery history for the account connected to the API key initiating the request.

    Request Parameters

    Parameters Type Required Description
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other

    Response Parameters

    Parameters Type Description
    event STRING deliverOrders
    timestamp STRING Millisecond timestamp of the repsonse
    data LIST of dictionaries
    timestamp STRING Millisecond timestamp of the delivery action
    instrumentId STRING Perpetual swap market code
    status STRING Request status
    quantity Null Type Quantity
    deliverPrice STRING Mark price at delivery
    transferAsset STRING Asset being sent
    transferQty STRING Quantity being sent
    instrumentIdDeliver STRING Asset being received: long position = coin, short position = USD
    deliverQty STRING Quantity of the received asset
    deliverOrderId STRING Order id
    clientOrderId Null Type null

    POST /v2/orders/place

    Request

    POST /v2/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"
            }, 
            {
                "clientOrderId": 1612249737723, 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "side": "SELL", 
                "quantity": "0.003", 
                "timeInForce": "GTC", 
                "orderType": "LIMIT", 
                "price": "54901"
            }
        ]
    }
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = 'api_key'
    api_secret = 'api_secret'
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    
    method = '/v2/orders/place'
    
    params = json.dumps({"recvWindow":3000, "timestamp": 1737100050453, "responseType":"FULL","orders":[{"clientOrderId":1612249737434,"marketCode":"BTC-USD-SWAP-LIN","side":"SELL","quantity":"1","timeInForce":"GTC","orderType":"LIMIT","price":"49995"}]})
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'POST', rest_path, method, params)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.post(rest_url + method, headers=header, data=params)
    print(resp.url)
    print(resp.request.headers)
    print(resp.request.body)
    print(json.dumps(resp.json(), indent=4, separators=(', ', ': ')))
    

    RESPONSE

    {
        "accountId": "13670827", 
        "event": "placeOrder", 
        "timestamp": "1615430915625", 
        "data": [
            {
                "success": "false",
                "timestamp": "1641538345068",
                "code": "710006",
                "message": "FAILED balance check as balance (0E-9) < value (0.001)",
                "clientOrderId": "2619090944648",
                "price": "52888.0",
                "quantity": "0.001",
                "side": "SELL",
                "marketCode": "BTC-USD",
                "timeInForce": "GTC",
                "orderType": "LIMIT"
            },
            {
                "success": "true",
                "timestamp": "1641536720611",
                "clientOrderId": "3619090894340",
                "orderId": "1000132664173",
                "price": "23641.0",
                "quantity": "0.7",
                "side": "BUY",
                "status": "OPEN",
                "marketCode": "BTC-USD-SWAP-LIN",
                "timeInForce": "GTC",
                "matchId": "0",
                "notice": "OrderOpened",
                "orderType": "LIMIT",
                "isTriggered": "false"
            },
            {
                "success": "true",
                "timestamp": "1641538343028",
                "clientOrderId": "3619090894340",
                "orderId": "1000132688133",
                "price": "43000.0",
                "quantity": "0.1",
                "side": "BUY",
                "status": "PARTIAL_FILL",
                "marketCode": "BTC-USD-SWAP-LIN",
                "timeInForce": "GTC",
                "matchId": "304638880616112239",
                "lastTradedPrice": "42731.5",
                "matchQuantity": "0.001",
                "orderMatchType": "TAKER",
                "remainQuantity": "0.099",
                "notice": "OrderMatched",
                "orderType": "LIMIT",
                "fees": "0.00170064",
                "feeInstrumentId": "FLEX",
                "isTriggered": "false"
            }
        ]
    }
    
    {
        "event": "placeOrder", 
        "timestamp": "1648804490345", 
        "accountId": "677473", 
        "data": [
            {
                "success": "true", 
                "timestamp": "1648804490326", 
                "clientOrderId": "1612249737434", 
                "orderId": "1000200584643", 
                "price": "49995.0", 
                "quantity": "1.0", 
                "side": "SELL", 
                "status": "OPEN", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "timeInForce": "GTC", 
                "matchId": "0", 
                "notice": "OrderOpened", 
                "orderType": "LIMIT", 
                "isTriggered": "false"
            }
        ]
    }
    

    Place 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 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
    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
    timeInForce STRING NO Default GTC
    orderType STRING YES LIMIT or MARKET or STOP
    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
    Response Fields Type Description
    accountId STRING Account ID
    event STRING
    timestamp STRING Millisecond timestamp of the repsonse
    data LIST
    success STRING Whether an order has been successfully placed
    timestamp STRING
    code STRING Error code
    message STRING Error message
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    orderId STRING
    price STRING
    quantity STRING
    side STRING SELL or BUY
    marketCode STRING
    timeInForce STRING
    matchId STRING Exchange match ID
    lastTradedPrice STRING Price when order was last traded
    matchQuantity STRING Matched quantity
    orderMatchType STRING MAKER or TAKER
    remainQuantity STRING Remainning quantity
    notice STRING OrderClosed or OrderMatched or OrderOpend
    orderType STRING MARKET or LIMIT or STOP
    fees STRING Amount of fees paid from this match ID
    feeInstrumentId STRING Instrument ID of fees paid from this match ID
    isTriggered STRING false (or true for STOP order types)

    POST /v2/orders/modify

    Request

    POST /v2/orders/modify
    
    {
        "recvWindow": 13000, 
        "responseType": "FULL", 
        "timestamp": 1614331650143, 
        "orders": [
            {
                "clientOrderId": 1614330009059, 
                "orderId": "304369975621712260", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "side": "BUY", 
                "quantity": "0.007", 
                "price": "40001.0"
            }, 
            {
                "clientOrderId": 161224973777800, 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "side": "SELL", 
                "quantity": "0.002", 
                "price": "40003.0"
            }, 
            {
                "clientOrderId": 161224973777900, 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "side": "SELL", 
                "quantity": "0.003", 
                "price": "40004.0"
            }
        ]
    }
    

    RESPONSE

    {
        "accountId": "495", 
        "event": "modifyOrder", 
        "timestamp": "1614331651243", 
        "data": [
            {
                "success": "false", 
                "timestamp": "1614331651174", 
                "code": "40032", 
                "message": "Invalid request data", 
                "clientOrderId": "161224973777800", 
                "price": "40003.0", 
                "quantity": "0.002", 
                "side": "SELL", 
                "marketCode": "BTC-USD-SWAP-LIN"
            }, 
            {
                "success": "false", 
                "timestamp": "1614331651174", 
                "code": "40032", 
                "message": "Invalid request data", 
                "clientOrderId": "161224973777900", 
                "price": "40004.0", 
                "quantity": "0.003", 
                "side": "SELL", 
                "marketCode": "BTC-USD-SWAP-LIN"
            }, 
            {
                "success": "true", 
                "timestamp": "1614331651196", 
                "clientOrderId": "1614330009059", 
                "orderId": "304369975621712263", 
                "price": "40001.0", 
                "quantity": "0.007", 
                "side": "BUY", 
                "status": "OPEN", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "timeInForce": "GTC", 
                "notice": "OrderOpened", 
                "orderType": "LIMIT", 
                "isTriggered": "false"
            }
        ]
    }
    

    Modify orders.

    Request Parameters Type Required Description
    recvWindow LONG NO
    timestamp STRING NO
    responseType STRING YES FULL or ACK
    orders LIST YES
    clientOrderId ULONG NO Client assigned ID to help manage and identify orders with max value 9223372036854775807
    orderId STRING YES
    marketCode STRING YES
    side STRING NO
    quantity STRING NO
    price STRING NO
    stopPrice STRING NO
    limitPrice STRING NO
    Response Parameters Type Description
    accountId STRING
    event STRING
    timestamp STRING
    data LIST
    success STRING
    timestamp STRING
    code STRING Error code
    message STRING Error message
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    orderId STRING
    price STRING
    quantity STRING
    side STRING SELL or BUY
    status STRING Status of the order
    marketCode STRING
    timeInForce STRING
    notice STRING OrderClosed or OrderMatched or OrderOpend
    orderType STRING
    isTriggered STRING true or false

    DELETE /v2/orders/cancel

    Request

    DELETE /v2/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
            }
        ]
    }
    

    RESPONSE

    {
        "accountId": "495", 
        "event": "cancelOrder", 
        "timestamp": "1615454881391", 
        "data": [
            {
                "success": "true", 
                "timestamp": "1615454881383", 
                "clientOrderId": "1615453494726", 
                "orderId": "304384250571714215", 
                "price": "55006.0", 
                "quantity": "0.006", 
                "side": "SELL", 
                "status": "CANCELED_BY_USER", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "timeInForce": "GTC", 
                "remainQuantity": "0.006", 
                "notice": "OrderClosed", 
                "orderType": "LIMIT", 
                "isTriggered": "false"
            }, 
            {
                "success": "false", 
                "timestamp": "1615454881433", 
                "code": "40035", 
                "message": "Open order not found with id", 
                "clientOrderId": "1612249737724", 
                "marketCode": "BTC-USD-SWAP-LIN"
            }
        ]
    }
    

    Cancel orders.

    Request Parameters Type Required Description
    recvWindow LONG NO
    timestamp LONG NO
    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 Parameters Type Description
    accountId STRING
    event STRING
    timestamp STRING
    data LIST
    success STRING
    timestamp STRING
    code STRING Error code
    message STRING Error message
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    orderId STRING
    price STRING
    quantity STRING
    side STRING SELL or BUY
    status STRING Status of the order
    marketCode STRING
    timeInForce STRING
    notice STRING OrderClosed or OrderMatched or OrderOpend
    orderType STRING
    isTriggered STRING true or false

    POST /v2/mint

    Mint.

    Request

    POST /v2/mint
    
    {
    
        "asset": "flexUSD",
        "quantity": 1000
    
    }
    

    SUCCESSFUL RESPONSE

    {
        "event":"mint",
        "timestamp":"1620964317199",
        "accountId":"1532",
        "data":{
            "asset":"flexUSD",
            "quantity":"10"
        }
    }
    
    Request Parameters Type Required Description
    asset STRING YES Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    quantity STRING/DECIMAL YES Quantity of the asset
    Response Fields Type Description
    accountId STRING Account ID
    asset STRING Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    quantity STRING Quantity of the asset

    GET /v2/mint/{asset}

    Get mint history by asset and sorted by time in descending order.

    Request

    GET /v2/mint/{asset}?limit={limit}&startTime={startTime}&endTime={endTime}
    

    SUCCESSFUL RESPONSE

    {
        "event":"mintHistory",
        "timestamp":"1620964764692",
        "accountId":"1570",
        "data":[
            {
                "asset":"flexETH",
                "quantity":"0.100000000",
                "mintedAt":"1619779905495"
            },
            {
                "asset":"flexETH",
                "quantity":"97.800000000",
                "mintedAt":"1619779812468"
            },
            {
                "asset":"flexETH",
                "quantity":"0.100000000",
                "mintedAt":"1619779696705"
            },
            ...
        ]
    }
    
    Request Parameters Type Required Description
    asset STRING YES Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    limit STRING NO max 100, default 100
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Fields Type Description
    accountId STRING Account ID
    asset STRING Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    quantity STRING Quantity of the asset
    mintedAt STRING Minted time in millisecond timestamp

    POST /v2/redeem

    Redeem.

    Request

    POST /v2/redeem
    
    {
    
        "asset": "flexUSD",
        "quantity": 1000,
        "type": "Normal"
    
    }
    

    SUCCESSFUL RESPONSE

    {
        "event":"redeem",
        "timestamp":"1620964351508",
        "accountId":"1532",
        "data":{
            "asset":"flexUSD",
            "quantity":"10",
            "redeemAt":"1620964800000",
            "type":"NORMAL"
        }
    }
    
    Request Parameters Type Required Description
    asset STRING YES Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    quantity STRING/DECIMAL YES Quantity of the asset
    type STRING YES Redeem type, available types: Normal, Instant
    Response Fields Type Description
    accountId STRING Account ID
    asset STRING Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    quantity STRING Quantity of the asset
    redeemAt STRING Redeemed time
    type STRING Redeem type, available types: Normal, Instant

    GET /v2/redeem/{asset}

    Get redemption history by asset and sorted by time in descending order.

    Request

    GET /v2/redeem/{asset}?limit={limit}&startTime={startTime}&endTime={endTime}
    

    SUCCESSFUL RESPONSE

    {
      "event":"redemptionHistory",
      "timestamp":"1620964856842",
      "accountId":"1570",
      "data":[
        {
          "asset":"ETH",
          "quantity":"0.001000000",
          "requestedAt":"1619788358578",
          "redeemedAt":"1619788860219"
        },
        {
          "asset":"ETH",
          "quantity":"0.001000000",
          "requestedAt":"1619788328760",
          "redeemedAt":"1619788328963"
        },
        ...
      ]
    }
    
    Request Parameters Type Required Description
    asset STRING YES Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    limit STRING NO max 100, default 100
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Fields Type Description
    accountId STRING Account ID
    asset STRING Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    quantity STRING Quantity of the asset
    requestedAt STRING when the redeem request was made
    redeemedAt STRING when the redemption was actually processed

    GET v2/borrow/{asset}

    Get borrow history by asset and sorted by time in descending order.

    Request

    GET v2/borrow/{asset}?limit={limit}&startTime={startTime}&endTime={endTime}
    

    SUCCESSFUL RESPONSE

    {
        "event": "borrowHistory",
        "timestamp": "1626433904976",
        "accountId": "3123",
        "data": [
            {
                "borrowAsset": "USD",
                "borrowedAmount": "296.2158828",
                "collateralAsset": "BTC",
                "collateralizedAmount": "0.01000000",
                "nonCollateralizedAmount": "0",
                "rateType": "FLOATING_RATE",
                "status": "COMPLETED",
                "borrowedAt": "1626433827613"
            },
            {
                "borrowAsset": "USD",
                "borrowedAmount": "0.0000000",
                "collateralAsset": "BTC",
                "collateralizedAmount": "0.00000000",
                "nonCollateralizedAmount": "1",
                "rateType": "FLOATING_RATE",
                "status": "CANCELED",
                "borrowedAt": "1626432797124"
            },
            ...
        ]
    }
    
    Request Parameters Type Required Description
    asset STRING YES Collateral asset name
    limit STRING NO max 100, default 100
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Fields Type Description
    accountId STRING Account ID
    borrowAsset STRING Borrow asset, can only be USD for now
    borrowedAmount STRING Borrowed amount of the borrow asset
    collateralAsset STRING Collateral asset
    collateralizedAmount STRING Collateralized amount of the collateral asset
    nonCollateralizedAmount STRING nonCollateralizedAmount = collateralAmount - collateralizedAmount
    rateType STRING FLOATING_RATE or FIXED_RATE
    status STRING COMPLETED or PARTIAL or CANCELLED
    borrowedAt STRING The time of borrowed at

    GET v2/repay/{asset}

    Get repay history by asset and sorted by time in descending order.

    Request

    GET v2/repay/{asset}?limit={limit}&startTime={startTime}&endTime={endTime}
    

    SUCCESSFUL RESPONSE

    {
        "event": "repayHistory",
        "timestamp": "1626433953585",
        "accountId": "3123",
        "data": [
            {
                "repayAsset": "USD",
                "repaidAmount": "0",
                "regainAsset": "BTC",
                "regainedAmount": "0",
                "nonRegainedAmount": "0.001",
                "status": "CANCELLED",
                "repaidAt": "1626747403329"
            },
            {
                "repayAsset": "USD",
                "repaidAmount": "31863.01677",
                "regainAsset": "BTC",
                "regainedAmount": "1",
                "nonRegainedAmount": "0",
                "status": "COMPLETED",
                "repaidAt": "1626676776330"
            },
            ...
        ]
    }
    
    Request Parameters Type Required Description
    asset STRING YES Regain asset name
    limit STRING NO max 100, default 100
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Fields Type Description
    accountId STRING Account ID
    repayAsset STRING Repay asset, can only be USD for now
    repaidAmount STRING Repaid amount of the repay asset
    regainAsset STRING Regain asset
    regainedAmount STRING Already regained amount of the regain asset
    nonRegainedAmount STRING nonRegainedAmount = regainAmount - regainedAmount
    status STRING COMPLETED or PARTIAL or CANCELLED
    borrowedAt STRING The time of borrowed at
    repaidAt STRING The time of repaid at

    GET /v2/funding-payments

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

    Request

    GET v2/funding-payments?marketCode={marketCode}&limit={limit}&startTime={startTime}&endTime={endTime}
    
    Request Parameters Type Required Description
    marketCode STRING NO e.g. BTC-USD-REPO-LIN
    limit LONG NO default is 500, max is 500
    startTime LONG NO millisecond timestamp, e.g. 1579450778000, default is 500 hours ago
    endTime LONG NO millisecond timestamp, e.g. 1613978625000, default is time now

    SUCCESSFUL RESPONSE

    {
        "event": "fundingPayments",
        "timestamp": "1627626010074",
        "accountId": "276007",
        "data": [
            {
                "marketCode": "BTC-USD-SWAP-LIN",
                "payment": "-122.17530872",
                "rate": "-0.00005",
                "position": "-61.093",
                "markPrice": "39996.5",
                "timestamp": "1627617632190"
            },
            {
                "marketCode": "BTC-USD-SWAP-LIN",
                "payment": "98.71895684",
                "rate": "0.00005",
                "position": "-61.093",
                "markPrice": "32317.6",
                "timestamp": "1627041622046"
            },
            ...
        ]
    }
    
    Response Fields Type Description
    timestamp STRING Timestamp of this response
    marketCode STRING Market code
    payment STRING Funding payment
    rate STRING Funding rate
    position STRING Position
    markPrice STRING Mark price
    timestamp(in the data list) STRING Updated time

    POST /v2/AMM/create

    Create AMM

    Request

    POST /v2/AMM/create
    
    {
        "direction": "NEUTRAL",
        "marketCode": "BTC-USD-SWAP-LIN",
        "collateralAsset":"BTC",
        "assetQuantity":"0.1",
        "collateralCounterAsset":"USD",
        "counterAssetQuantity":"4000",
        "minPriceBound":"28000",
        "maxPriceBound":"52000"
    }
    

    SUCCESSFUL RESPONSE

    {
        "event": "createAMM",
        "timestamp": "1628491099751",
        "accountId": "3101",
        "data": {
            "hashToken": "CF-BTC-AMM-mz7WAOZc",
            "direction": "NEUTRAL",
            "marketCode": "BTC-USD-SWAP-LIN",
            "collateralAsset": "BTC",
            "assetQuantity": "0.1",
            "collateralCounterAsset": "USD",
            "counterAssetQuantity": "4000",
            "minPriceBound": "28000",
            "maxPriceBound": "52000"
        }
    }
    
    Request Parameters Type Required Description
    leverage STRING NO Maximum leverage, with USDT the range of leverage is 1 to 40X otherwise is 1 to 10X
    direction STRING YES Value can be BUY or SELL or NEUTRAL
    marketCode STRING YES Market code e.g. BCH-USD-SWAP-LIN
    collateralAsset STRING NO Required unless unleveraged and direction is BUY
    assetQuantity STRING NO Required unless unleveraged and direction is BUY. Minimum is $200 notional
    collateralCounterAsset STRING NO Required if unleveraged and direction is NEUTRAL or BUY
    counterAssetQuantity STRING NO Required if unleveraged and direction is NEUTRAL or BUY. Minimum is $200 notional
    minPriceBound STRING YES When unleveraged and direction is NEUTRAL, minPriceBound and maxPriceBound should be stuck to the formula mid = counterAssetQuantity/collateralAssetQuantity maxPriceBound - mid = mid - minPriceBound
    maxPriceBound STRING YES When unleveraged and direction is NEUTRAL, minPriceBound and maxPriceBound should be stuck to the formula mid = counterAssetQuantity/collateralAssetQuantity maxPriceBound - mid = mid - minPriceBound
    Response Fields Type Description
    hashToken STRING Identity of the AMM
    leverage STRING Leverage of the AMM
    direction STRING Value can be BUY or SELL or NEUTRAL
    marketCode STRING Market code e.g. BCH-USD-SWAP-LIN
    collateralAsset STRING Collateral asset
    assetQuantity STRING Quantity of the collateral asset
    collateralCounterAsset STRING Collateral counter asset
    counterAssetQuantity STRING Quantity of the collateral counter asset
    minPriceBound STRING Minimum price of the range
    maxPriceBound STRING Maximum price of the range

    POST /v2/AMM/redeem

    Redeem AMM

    Request

    POST /v2/AMM/redeem
    
    {
        "hashToken": "CF-BTC-AMM-WJRzxzb",
        "redeemType": "DELIVER"
    }
    

    SUCCESSFUL RESPONSE

    {
        "event": "redeemAMM",
        "timestamp": "1628502282362",
        "accountId": "3101",
        "data": {
            "hashToken": "CF-BTC-AMM-mz7WAOZc",
            "redeemType": "DELIVER"
        }
    }
    
    Request Parameters Type Required Description
    hashToken STRING YES Identity of the AMM
    redeemType STRING YES Value can be DELIVER or MANUAL
    Response Fields Type Description
    hashToken STRING Identity of the AMM
    redeemType STRING YES

    GET /v2/AMM

    Get AMMs.

    Request

    GET v2/AMM?hashToken=CF-BTC-AMM-RoBwokR&marketCode=BTC-USD-SWAP-LIN
    

    SUCCESSFUL RESPONSE

    {
        "event": "infoAMM",
        "timestamp": "1628508877030",
        "accountId": "3101",
        "data": [
            {
                "hashToken": "CF-BTC-AMM-RoBwokR",
                "direction": "NEUTRAL",
                "marketCode": "BTC-USD-SWAP-LIN",
                "status": "EXECUTING",
                "collateralAsset": "BTC",
                "assetQuantity": "0.4",
                "collateralCounterAsset": "USD",
                "counterAssetQuantity": "5000",
                "minPriceBound": "8750",
                "maxPriceBound": "16250",
                "assetBalance": "0",
                "counterAssetBalance": "19894.5719512",
                "position": "-0.433",
                "entryPrice": "37758.38",
                "usdEarned": "95",
                "flexReward": "675",
                "apr": "86.64",
                "createdAt": "1628066890178",
                "updatedAt": "1628476562875"
            }
        ]
    }
    
    Request Parameters Type Required Description
    hashToken STRING NO Multiple hashTokens can be separated by a comma
    marketCode STRING NO Market code e.g. BTC-USD-SWAP-LIN
    status STRING NO Value can be ENDED or EXECUTING or PENDING
    Response Fields Type Description
    hashToken STRING Identity of the AMM
    direction STRING Value can be BUY or SELL or NEUTRAL
    marketCode STRING Market code e.g. BTC-USD-SWAP-LIN
    status STRING Value can be ENDED or EXECUTING or PENDING
    collateralAsset STRING Collateral asset
    assetQuantity STRING Quantity of the collateral asset
    collateralCounterAsset STRING Collateral counter asset
    counterAssetQuantity STRING Quantity of the collateral counter asset
    minPriceBound STRING Minimum price of the range
    maxPriceBound STRING Maximum price of the range
    position STRING Current position
    usdEarned STRING USD already earned
    flexReward STRING Amount of FLEX reward
    apr STRING APR(annual percentage rate)
    createdAt STRING The time that AMM was created at
    updatedAt STRING The time that AMM was updated at

    Methods - Public

    GET /v2/all/markets

    Request

    GET/v2/all/markets`
    

    RESPONSE

    {
        "event": "markets",
        "timestamp": "1620810144786",
        "data": [
            {
                "marketId": "2001000000000",
                "marketCode": "BTC-USD",
                "name": "BTC/USD",
                "referencePair": "BTC/USD",
                "base": "BTC",
                "counter": "USD",
                "type": "SPOT",
                "tickSize": "0.1",
                "qtyIncrement": "0.001",
                "listingDate": 2208988800000,
                "endDate": 0,
                "marginCurrency": "USD",
                "contractValCurrency": "BTC",
                "upperPriceBound": "11000.00",
                "lowerPriceBound": "9000.00",
                "marketPrice": "10000.00",
                "marketPriceLastUpdated": "1620810131131"
            },
        ]
    }
    

    Get a list of all available markets on CoinFlex.

    Response Parameters Type Description
    timestamp STRING Timestamp of this response
    marketId STRING
    marketCode STRING Market Code
    name STRING Name of the contract
    referencePair STRING Reference pair
    base STRING Base asset
    counter STRING Counter asset
    type STRING Type of the contract
    tickSize STRING Tick size of the contract
    qtyIncrement STRING Minimum increamet quantity
    listingDate STRING Listing date of the contract
    endDate STRING Ending date of the contract
    marginCurrency STRING Margining currency
    contractValCurrency STRING Contract valuation currency
    upperPriceBound STRING Upper price bound
    lowerPriceBound STRING Lower price bound
    marketPrice STRING Market price
    marketPriceLastUpdated LONG The time that market price last updated at

    GET /v2/all/assets

    Request

    GET/v2/all/assets
    

    RESPONSE

    {
        "event": "assets",
        "timestamp":"1593617008698",
        "data": [
            {
                "instrumentId": "BTC-USD-200626-LIN",
                "name": "BTC/USD 20-06-26 Future (Linear)",
                "base": "BTC",
                "counter": "USD",
                "type": "FUTURE",
                "marginCurrency": "USD",
                "contractValCurrency": "BTC",
                "deliveryDate": null,
                "deliveryInstrument": null
            },
            {
                "instrumentId": "BTC",
                "name": "Bitcoin",
                "base": null,
                "counter": null,
                "type": "SPOT",
                "marginCurrency": null,
                "contractValCurrency": null,
                "deliveryDate": null,
                "deliveryInstrument": null
            }
        ]
    }
    

    Get a list of all assets available on CoinFLEX. These include coins and bookable contracts.

    Response Parameters Type Description
    timestamp STRING Timestamp of this response
    instrumentId STRING Instrument ID
    name STRING Name of the asset
    base STRING Base of the asset
    counter STRING Counter of the asset
    type STRING type of the asset
    marginCurrency STRING Margining currency
    contractValCurrency STRING Contract valuation currency
    deliveryDate STRING Delivery date
    deliveryInstrument STRING Delivery instrument

    GET /v2/publictrades/{marketCode}

    Request

    GET/v2/publictrades/{marketCode}?limit={limit}&startTime={startTime}&endTime{endTime}
    

    RESPONSE

    {
      "event": "publicTrades", 
      "timestamp": "1595636619410", 
      "marketCode": "BTC-USD-SWAP-LIN", 
      "data": [
        {
          "matchId": "160070803925856675", 
          "matchQuantity": "0.100000000", 
          "matchPrice": "9600.000000000", 
          "side": "BUY", 
          "matchTimestamp": "1595585860254"
          },
          ...
      ]
    }
    

    Get most recent trades.

    Request Parameters Type Required Description
    marketCode STRING YES
    limit LONG NO Default 100, max 300
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Parameters Type Description
    timestamp STRING Timestamp of this response
    marketCode STRING
    matchID STRING
    matchQuantity STRING
    matchPrice STRING
    side STRING
    matchTimestamp STRING

    GET /v2/ticker

    Request

    GET/v2/ticker
    

    RESPONSE

    {
      "event":"ticker",
      "timestamp":"123443563454",
      "data" :
      [
          {
                "marketCode": "BTC-USD-SWAP-LIN",
                "last": "43.259", 
                "markPrice": "11012.80409769",  
                "open24h": "49.375",
                "volume24h": "11295421",
                "currencyVolume24h": "1025.7",                       
                "high24h": "49.488",
                "low24h": "41.649",
                "openInterest": "1726003",
                "lastQty": "1"
          },
          ...
      ]
    }
    

    Get a list of all of the tickers.

    Response Parameters Type Description
    timestamp STRING Timestamp of this response
    marketCode STRING "BTC-USD-SWAP-LIN",
    last STRING Last traded price
    markPrice STRING Mark price
    open24h STRING Daily opening price
    volume24h STRING 24 hour volume (USD)
    currencyVolume24h STRING 24 hour volume (coin)
    high24h STRING 24 hour high
    low24h STRING 24 hour low
    openInterest STRING Current open interest
    lastQty STRING Last traded quantity

    GET /v2/candles/{marketCode}

    Get historical candles of active and expired markets.

    Request

    GET /v2/candles/{marketCode}?timeframe={timeframe}&limit={limit}&startTime={startTime}&endTime={endTime}
    
    Request Parameters Type Required Description
    marketCode STRING YES When marketCode is expired market like BTC-USD-201225-LIN, the startTime and the endTime should be explicitly set in 2020
    timeframe STRING NO e.g. 60s, 300s, 900s, 1800s, 3600s, 7200s, 14400s, 86400s, default 3600s
    limit LONG NO max 5000, default 500
    startTime LONG NO Millisecond timestamp, e.g. 1579450778000, default is limit times timeframe ago, if the limit is 300 and the timeframe is 3600s then the default startTime is time now - 300x3600s, if the limit is not present and the timeframe is 3600s then the default startTime is time now - 500x3600s
    endTime LONG NO Millisecond timestamp, e.g 1579450778000, default time now

    RESPONSE

    {
        "event": "candles",
        "timestamp": "1616743098781",
        "timeframe": "60s",
        "data": [
            {
                "timestamp": "1616713140000",
                "open": "51706.50000000",
                "high": "51758.50000000",
                "low": "51705.50000000",
                "close": "51754.00000000",
                "volume24h": "0",
                "currencyVolume24h": "0"
            },
            {
                "timestamp": "1616713200000",
                "open": "51755.50000000",
                "high": "51833.00000000",
                "low": "51748.00000000",
                "close": "51815.00000000",
                "volume24h": "0",
                "currencyVolume24h": "0"
            },
            ...
        ]
    }
    
    Response Fields Type Description
    timestamp(outer) STRING
    timeframe STRING Selected timeframe
    timestamp(inner) STRING Beginning of the candle
    open STRING
    high STRING
    low STRING
    close STRING
    volume24h STRING 24 hour rolling trading volume in counter currency
    currencyVolumn24h STRING 24 hour rolling trading volume in base currency

    GET /v2/depth/{marketCode}/{level}

    Get order book by marketCode and level.

    Request

    GET /v2/depth/BTC-USD-SWAP-LIN/5 
    

    SUCCESSFUL RESPONSE

    {
        "event": "depthL5", 
        "timestamp": "1615457834446", 
        "data": [
            {
                "asks": [
                    [
                        54792, 
                        0.001
                    ], 
                    [
                        54802.5, 
                        0.366
                    ], 
                    [
                        54803, 
                        0.75
                    ], 
                    [
                        54806, 
                        1.5
                    ], 
                    [
                        54830.5, 
                        0.687
                    ]
                ], 
                "bids": [
                    [
                        54786.5, 
                        0.1
                    ], 
                    [
                        54754.5, 
                        0.375
                    ], 
                    [
                        54752, 
                        0.394
                    ], 
                    [
                        54749.5, 
                        0.001
                    ], 
                    [
                        54745.5, 
                        0.339
                    ]
                ], 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "timestamp": "1615457834388"
            }
        ]
    }
    
    Response Fields Type Description
    event STRING
    timestamp STRING
    data LIST
    asks LIST of floats Sell side depth:
    1. price
    2. quantity
    bids LIST of floats Buy side depth:
    1. price
    2. quantity
    marketCode STRING
    timestamp STRING

    GET /v2/ping

    Get API service status.

    Request

    GET /v2/ping
    

    SUCCESSFUL RESPONSE

    {
        "success": "true"
    }
    
    Response Fields Type Description
    sucess STRING "true" indicates that the API service is OK otherwise it will be failed

    GET /v2/flex-protocol/balances/{flexProtocol}

    Get flexAsset balances.

    Request

    GET /v2/flex-protocol/balances/{flexProtocol}
    

    SUCCESSFUL RESPONSE

    {
        "event": "flexBalances",
        "timestamp": "1621582973071",
        "tradeType": "LINEAR",
        "flexProtocol": "flexUSD",
        "data": [
            {
                "instrumentId":"BTC",
                "total":"10.140668310000",
                "available":"10.140668310000",
                "reserved":"0",
                "markPrice":"39203",
                "quantityLastUpdated":"1645228442021"
            },
            {   "instrumentId":"USD",
                "total":"56.3903310956678000",
                "available":"56.3903310956678000",
                "reserved":"0",
                "markPrice":"1",
                "quantityLastUpdated":"1629525660717"
            }
        ]
    }
    
    Request Parameters Type Required Description
    flexProtocol STRING YES Available values flexUSD, flexBTC, flexETH, flexFLEX
    Response Fields Type Description
    tradeType STRING Trade type
    flexProtocol STRING Available values flexUSD, flexBTC, flexETH, flexFLEX
    instrumentId STRING Coin symbol, e.g. 'BTC'
    total STRING Total balance
    available STRING Available balance
    reserved STRING Reserved balance (unavailable) due to working spot orders
    markPrice STRING Mark price
    quantityLastUpdated STRING Millisecond timestamp of when balance was last updated

    GET /v2/flex-protocol/positions/{flexProtocol}

    Get flexAsset positions.

    Request

    GET /v2/flex-protocol/positions/{flexProtocol}
    

    SUCCESSFUL RESPONSE

    {
        "event": "flexPositions",
        "timestamp": "1621590427436",
        "flexProtocol": "flexUSD",
        "data": [
            {
                "instrumentId": "BTC-USD-SWAP-LIN",
                "quantity": "-169.048",
                "lastUpdated": "1621590364988",
                "contractValCurrency": "BTC",
                "entryPrice": "40766.3490",
                "positionPnl": "-23506.2934480"
            },
            {
                "instrumentId": "ETH-USD-SWAP-LIN",
                "quantity": "-1279.83",
                "lastUpdated": "1621587180441",
                "contractValCurrency": "ETH",
                "entryPrice": "2798.5100",
                "positionPnl": "53420.104200"
            },
            {
                "instrumentId": "LTC-USD-SWAP-LIN",
                "quantity": "-299.49",
                "lastUpdated": "1621585374591",
                "contractValCurrency": "LTC",
                "entryPrice": "207.9500",
                "positionPnl": "503.143200"
            },
            ...
        ]
    }
    
    Request Parameters Type Required Description
    flexProtocol STRING YES Available values flexUSD, flexBTC, flexETH, flexFLEX
    Response Fields Type Description
    flexProtocol STRING Available values flexUSD, flexBTC, flexETH, flexFLEX
    instrumentId STRING Contract symbol, e.g. FLEX-USD-SWAP-LIN
    quantity STRING Quantity of position, e.g. 0.94
    lastUpdated STRING Timestamp when position was last updated
    contractValCurrency STRING Contract valuation currency
    entryPrice STRING Average entry price
    positionPnl STRING Postion profit and lost

    GET /v2/flex-protocol/orders/{flexProtocol}

    Get flexAsset orders.

    Request

    GET /v2/flex-protocol/orders/{flexProtocol}
    

    SUCCESSFUL RESPONSE

    {
        "event": "flexOrders",
        "timestamp": "1621590953053",
        "data": [
            {
                "orderId": "1000085820424",
                "marketCode": "COMP-USD-REPO-LIN",
                "clientOrderId": "20",
                "side": "BUY",
                "orderType": "LIMIT",
                "quantity": "0.26",
                "remainingQuantity": "0.26",
                "price": "-0.0002",
                "stopPrice": null,
                "limitPrice": "-0.0002",
                "orderCreated": "1621590951780",
                "lastModified": "1621590951903",
                "lastTradeTimestamp": "1621590951828",
                "timeInForce": "GTC"
            },
            {
                "orderId": "1000085820409",
                "marketCode": "COMP-USD-REPO-LIN",
                "clientOrderId": "5",
                "side": "BUY",
                "orderType": "LIMIT",
                "quantity": "0.21",
                "remainingQuantity": "0.21",
                "price": "-0.00005",
                "stopPrice": null,
                "limitPrice": "-0.00005",
                "orderCreated": "1621590951510",
                "lastModified": "1621590951608",
                "lastTradeTimestamp": "1621590951543",
                "timeInForce": "GTC"
            },
            {
                "orderId": "1000085820408",
                "marketCode": "COMP-USD-REPO-LIN",
                "clientOrderId": "4",
                "side": "BUY",
                "orderType": "LIMIT",
                "quantity": "5.2",
                "remainingQuantity": "5.2",
                "price": "-0.00004",
                "stopPrice": null,
                "limitPrice": "-0.00004",
                "orderCreated": "1621590951381",
                "lastModified": "1621590951394",
                "lastTradeTimestamp": "1621590951392",
                "timeInForce": "GTC"
            },
            ...
        ]
    }
    
    Request Parameters Type Required Description
    flexProtocol STRING YES Available values flexUSD, flexBTC, flexETH, flexFLEX
    Response Fields Type Description
    flexProtocol STRING Available values flexUSD, flexBTC, flexETH, flexFLEX
    orderId STRING Unique order ID from the exchange
    marketCode STRING Market code
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    side STRING BUY or SELL
    orderType STRING LIMIT or STOP
    quantity STRING Quantity submitted
    remainingQuantity STRING Remainning quantity
    price STRING Price submitted
    stopPrice STRING Stop price for the stop order
    limitPrice STRING Limit price for the stop limit order
    orderCreated STRING Timestamp when order was created
    lastModified STRING Timestamp when order was last mordified
    lastTradeTimestamp STRING Timestamp when order was last traded
    timeInForce STRING Time in force

    GET /v2/flex-protocol/trades/{flexProtocol}/{marketCode}

    Get flexAsset trades.

    Request

    GET /v2/flex-protocol/trades/{flexProtocol}/{marketCode}?limit={limit}&startTime={startTime}&endTime={endTime}
    

    SUCCESSFUL RESPONSE

    {
        "event": "flexTrades",
        "timestamp": "1621591479201",
        "flexProtocol": "flexBTC",
        "data": [
            {
                "matchQuantity": "0.4",
                "total": "4.000000000",
                "fees": "0.788",
                "side": "BUY",
                "orderMatchType": "MAKER",
                "matchTimestamp": "1621483974496",
                "feeInstrumentId": "USD",
                "orderId": "1000009522024",
                "clientOrderId": "1621483945643",
                "marketCode": "BTC-USD-SWAP-LIN",
                "matchPrice": "39400",
                "matchId": "2001011000000"
            },
            {
                "matchQuantity": "0.4",
                "total": "4.400000000",
                "fees": "0.788",
                "side": "BUY",
                "orderMatchType": "MAKER",
                "matchTimestamp": "1621483973636",
                "feeInstrumentId": "USD",
                "orderId": "1000009522024",
                "clientOrderId": "1621483945643",
                "marketCode": "BTC-USD-SWAP-LIN",
                "matchPrice": "39400",
                "matchId": "2001011000000"
            },
            {
                "matchQuantity": "0.4",
                "total": "4.800000000",
                "fees": "0.788",
                "side": "BUY",
                "orderMatchType": "MAKER",
                "matchTimestamp": "1621483973476",
                "feeInstrumentId": "USD",
                "orderId": "1000009522024",
                "clientOrderId": "1621483945643",
                "marketCode": "BTC-USD-SWAP-LIN",
                "matchPrice": "39400",
                "matchId": "2001011000000"
            },
            ...
        ]
    }
    
    Request Parameters Type Required Description
    flexProtocol STRING YES Available values flexUSD, flexBTC, flexETH, flexFLEX
    marketCode STRING YES
    limit LONG NO default 100, max 500
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Fields Type Description
    flexProtocol STRING Available values flexUSD, flexBTC, flexETH, flexFLEX
    matchId STRING Match ID
    matchTimestamp STRING Order Matched timestamp
    marketCode STRING Market code
    matchQuantity STRING Match quantity
    matchPrice STRING Match price
    total STRING Total price
    side STRING Side of the match
    orderMatchType STRING TAKER or MAKER
    fees STRING Fees
    feeInstrumentId STRING Instrument ID of the fees
    orderId STRING Unique order ID from the exchange
    clientOrderID STRING Client assigned ID to help manage and identify orders

    GET /v2/flex-protocol/delivery/orders/{flexProtocol}

    Get flexAsset delivery orders.

    Request

    GET /v2/flex-protocol/delivery/orders/{flexProtocol}?limit={limit}&startTime={startTime}&endTime={endTime}
    

    SUCCESSFUL RESPONSE

    {
        "event": "flexDeliveryOrders",
        "timestamp": "1621592173494",
        "flexProtocol": "flexBTC",
        "data": [
            {
                "timestamp": "1621411380000",
                "instrumentId": "BTC-USD-SWAP-LIN",
                "status": "DELIVERED",
                "quantity": null,
                "deliverPrice": "40225.4",
                "transferAsset": "BTC",
                "transferQty": "0.001",
                "instrumentIdDeliver": "USD",
                "deliverQty": "40.2254",
                "deliverOrderId": "659754125496582148",
                "clientOrderId": null
            },
            {
                "timestamp": "1621411378000",
                "instrumentId": "BTC-USD-SWAP-LIN",
                "status": "DELIVERED",
                "quantity": null,
                "deliverPrice": "40217.8",
                "transferAsset": "BTC",
                "transferQty": "0.001",
                "instrumentIdDeliver": "USD",
                "deliverQty": "40.2178",
                "deliverOrderId": "659754119608827908",
                "clientOrderId": null
            },
            {
                "timestamp": "1621411376000",
                "instrumentId": "BTC-USD-SWAP-LIN",
                "status": "DELIVERED",
                "quantity": null,
                "deliverPrice": "40226.5",
                "transferAsset": "BTC",
                "transferQty": "0.001",
                "instrumentIdDeliver": "USD",
                "deliverQty": "40.2265",
                "deliverOrderId": "659754113236107267",
                "clientOrderId": null
            },
            ...
        ]
    }
    
    Request Parameters Type Required Description
    flexProtocol STRING YES Available values flexUSD, flexBTC, flexETH, flexFLEX
    limit LONG NO default 100, max 500
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Fields Type Description
    flexProtocol STRING Available values flexUSD, flexBTC, flexETH, flexFLEX
    instrumentId STRING Perpetual swap market code
    status STRING Request status
    quantity Null Type null
    deliverPrice STRING Mark price at delivery
    transferAsset STRING Asset being sent
    transferQty STRING Quantity being sent
    instrumentIdDeliver STRING Asset being received: long position is coin, short position is USD
    deliverQty STRING Quantity of the received asset
    deliverOrderId STRING Order id
    clientOrderId Null Type null

    REST API V3

    TEST

    LIVE site

    For clients who do not wish to take advantage of CoinFLEX's native WebSocket API, CoinFLEX offers a RESTful API that implements much of the same functionality.

    Error Codes

    Code Description
    429 Rate limit reached
    10001 General networking failure
    20001 Invalid parameter
    30001 Missing parameter
    40001 Alert from the server
    50001 Unknown server error
    20031 The marketCode is closed for trading temporarily

    Rate Limits

    Each IP is limited to:

    Certain endpoints have extra IP restrictions:

    Affected APIs:

    Authentication

    Request

    {
        "Content-Type": "application/json",
        "AccessKey": "<string>",
        "Timestamp": "<string>",
        "Signature": "<string>",
        "Nonce": "<string>"
    }
    
    import requests
    import hmac
    import base64
    import hashlib
    import datetime
    import json
    
    
    # rest_url = 'https://v2api.coinflex.com'
    # rest_path = 'v2api.coinflex.com'
    
    rest_url = 'https://v2stgapi.coinflex.com'
    rest_path = 'v2stgapi.coinflex.com'
    
    api_key = "API-KEY"
    api_secret = "API-SECRET"
    
    ts = datetime.datetime.utcnow().isoformat()
    nonce = 123
    method = "API-METHOD"
    
    # Optional and can be omitted depending on the REST method being called 
    body = json.dumps({'key1': 'value1', 'key2': 'value2'})
    
    if body:
        path = method + '?' + body
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'GET', rest_path, method, body)
    sig = base64.b64encode(hmac.new(api_secret.encode('utf-8'), msg_string.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8')
    
    header = {'Content-Type': 'application/json', 'AccessKey': api_key,
              'Timestamp': ts, 'Signature': sig, 'Nonce': str(nonce)}
    
    resp = requests.get(rest_url + path, headers=header)
    # When calling an endpoint that uses body
    # resp = requests.post(rest_url + method, data=body, headers=header)
    print(resp.json())
    

    Public market data methods do not require authentication, however private methods require a Signature to be sent in the header of the request. These private REST methods use HMAC SHA256 signatures.

    The HMAC SHA256 signature is a keyed HMAC SHA256 operation using a client's API Secret as the key and a message string as the value for the HMAC operation.

    The message string is constructed as follows:-

    msgString = f'{Timestamp}\n{Nonce}\n{Verb}\n{URL}\n{Path}\n{Body}'

    Component Required Example Description
    Timestamp Yes 2020-04-30T15:20:30 YYYY-MM-DDThh:mm:ss
    Nonce Yes 123 User generated
    Verb Yes GET Uppercase
    Path Yes v2stgapi.coinflex.com
    Method Yes /v3/positions Available REST methods
    Body No marketCode=BTC-USD-SWAP-LIN Optional and dependent on the REST method being called

    The constructed message string should look like:-

    2020-04-30T15:20:30\n 123\n GET\n v2stgapi.coinflex.com\n /v3/positions\n marketCode=BTC-USD-SWAP-LIN

    Note the newline characters after each component in the message string. If Body is omitted it's treated as an empty string.

    Finally, you must use the HMAC SHA256 operation to get the hash value using the API Secret as the key, and the constructed message string as the value for the HMAC operation. Then encode this hash value with BASE-64. This output becomes the signature for the specified authenticated REST API method.

    The signature must then be included in the header of the REST API call like so:

    header = {'Content-Type': 'application/json', 'AccessKey': API-KEY, 'Timestamp': TIME-STAMP, 'Signature': SIGNATURE, 'Nonce': NONCE}

    Account & Wallet - Private

    GET /v3/account

    Get account information

    Request

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

    Successful response format

    {
        "success": true,
        "data": [
            {
                "accountId": "21213",
                "name": "main",
                "accountType": "LINEAR",
                "balances": [
                    {
                        "asset": "BTC",
                        "total": "2.823",
                        "available": "2.823",
                        "reserved": "0",
                        "lastUpdatedAt": "1593627415234"
                    },
                    {
                        "asset": "FLEX",
                        "total": "1585.890",
                        "available": "325.890",
                        "reserved": "1260",
                        "lastUpdatedAt": "1593627415123"
                    }
                ],
                "positions": [
                    {
                        "marketCode": "FLEX-USD-SWAP-PER", 
                        "baseAsset": "FLEX", 
                        "counterAsset": "USD", 
                        "position": "11411.1", 
                        "entryPrice": "3.590", 
                        "markPrice": "6.360", 
                        "positionPnl": "31608.7470", 
                        "estLiquidationPrice": "2.59", 
                        "lastUpdatedAt": "1637876701404",
                        "marginBalance": "45264.03",
                        "maintenanceMargin": "10886.1894",
                        "marginRatio": "0.24",
                        "leverage": "3"
                    }
                ],
                "collateral": "1231231",
                "notionalPositionSize": "50000.0",
                "portfolioVarMargin": "500",
                "riskRatio": "20000.0000",
                "maintenanceMargin": "1231",
                "marginRatio": "12.3179",
                "liquidating": false,
                "feeTier": "6",
                "createdAt": "1611665624601"
            }
        ]
    }
    
    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
    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 if applicable
    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 Appears in the position section only for positions using isolated margin. Isolated margin + Unrealized position PnL
    maintenanceMargin STRING Appears in the position section only for positions using isolated margin
    marginRatio STRING Appears in the position section only for positions using isolated margin
    leverage STRING Appears in the position section only for positions using isolated margin
    notionalPositionSize STRING Notional position size
    portfolioVarMargin STRING Portfolio margin
    riskRatio STRING collateralBalance / portfolioVarMargin. Orders are rejected/cancelled if the risk ratio drops below 1, and liquidation occurs if the risk ratio drops below 0.5
    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
    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

    Request

    GET v3/account/names
    

    Successful response format

    {
        "success": true,
        "data":  [  {
                        "accountId": "21213",
                        "name": "Test 1"
                    }, 
                    {
                        "accountId": "21214",
                        "name": "Test 2"
                  }
              ] 
    }
    
    Response Field Type Description
    accountId STRING Account ID
    name STRING Account name

    GET /v3/wallet

    Get account or sub-account wallet

    Request

    GET v3/wallet?subAcc={name1},{name2}&type={type}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                 "accountId": "21213",
                 "name": "main",
                 "walletHistory": [
                      {
                        "id": "810583329159217160",
                        "asset": "USD",
                        "type": "DEPOSIT", 
                        "amount": "10",
                        "createdAt": "162131535213"  
                        }   
                            ]
            }
        ]
    }
    
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    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

    Request

    POST /v3/transfer
    
    {
        "asset": "flexUSD",
        "quantity": "1000",
        "fromAccount": "14320",
        "toAccount": "15343"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "asset": "flexUSD", 
            "quantity": "1000",
            "fromAccount": "14320",
            "toAccount": "15343",
            "transferredAt": "1635038730480"
        }
    }
    
    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

    Request

    GET /v3/transfer?asset={asset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "asset": "flexUSD", 
                "quantity": "1000",
                "fromAccount": "14320",
                "toAccount": "15343",
                "id": "703557273590071299",
                "status": "COMPLETED",
                "transferredAt": "1634779040611"
            }
        ]
    }
    
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    asset STRING
    quantity STRING
    fromAccount STRING
    toAccount STRING
    id STRING
    status STRING
    transferredAt STRING Millisecond timestamp

    GET /v3/balances

    Request

    GET /v3/balances?subAcc={name1},{name2}&asset={asset}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "accountId": "21213",
                "name": "main",
                "balances": [
                   {
                       "asset": "BTC",
                       "total": "4468.823",              
                       "available": "4468.823",        
                       "reserved": "0",
                       "lastUpdatedAt": "1593627415234"
                   },
                   {
                       "asset": "FLEX",
                       "total": "1585.890",              
                       "available": "325.890",         
                       "reserved": "1260",
                       "lastUpdatedAt": "1593627415123"
                   }
                           ]
            }
        ]
    }
    
    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 Parent account with the name “main” and take the first place
    balances LIST of dictionaries
    asset STRING Asset name
    available STRING Available balance
    reserved STRING Reserved balance
    lastUpdatedAt STRING Timestamp of updated at

    GET /v3/positions

    Request

    GET /v3/positions?subAcc={name1},{name2}&marketCode={marketCode}
    

    Successful response format

    {
      "success": True,
      "data": [
          {
            "accountId": "1234",
            "name": "PERMISSIONLESS_1234",
            "positions": [
                {
                  "marketCode": "XYZ-USD-SWAP-PER",
                  "baseAsset": "XYZ",
                  "counterAsset": "USD",
                  "position": "566.0",
                  "entryPrice": "7.3400",
                  "markPrice": "9.94984016",
                  "positionPnl": "1477.169530560",
                  "estLiquidationPrice": "0",
                  "lastUpdatedAt": "1673231134601",
                  "marginBalance": "61350.82873932",
                  "maintenanceMargin": "988.61",
                  "marginRatio": "0.01611209",
                  "leverage": "2"
                 }
            ]
          }
      ]
    }
    

    Returns position data

    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 Parent account with the name “main” and take the first place
    positions LIST of dictionaries
    marketCode STRING Contract symbol, e.g. 'BTC-USD-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 Appears in the position section only for positions using isolated margin. Isolated margin + Unrealized position PnL
    maintenanceMargin STRING Appears in the position section only for positions using isolated margin
    marginRatio STRING Appears in the position section only for positions using isolated margin
    leverage STRING Appears in the position section only for positions using isolated margin

    POST /v3/leverage

    Increase or decrease your leverage. This endpoint is used in markets that support isolated margin.

    Request

    POST /v3/leverage
    
    {
        "marketCode": "BTC-USD-SWAP-PER",
        "leverage": 3
    }
    

    Successful response format

    {
        "success": true,
        "data":{
            "marketCode": "BTC-USD-SWAP-PER",
            "leverage": 2,
            "maxPositionSize": "1000000"
        }
    }
    
    Request Parameter Type Required Description
    marketCode STRING YES
    leverage STRING YES
    Response Field Type Description
    marketCode STRING
    leverage STRING
    maxPositionSize STRING

    POST /v3/position/adjust

    Add to or reduce your margin balance when using isolated margin.

    Request

    POST /v3/position/adjust
    
    {
        "marketCode": "BTC-USD-SWAP-PER",
        "amount": "100",
        "type": "ADD"
    }
    

    Successful response format

    {     
    "success": true,     
    "data": { 
            "type": "ADD",       
            "amount": "100.0",       
            "marginBalance": "150.5"   
     }
    }
    
    Request Parameter Type Required Description
    marketCode STRING YES
    amount STRING YES Must be a positive value
    type STRING YES ADD, REDUCE
    Response Field Type Description
    type STRING
    amount STRING
    marginBalance STRING

    GET /v3/funding

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

    Request

    GET v3/funding?marketCode={marketCode}&limit={limit}&startTime={startTime}&endTime={endTime}
    
    Request Parameters Type Required Description
    marketCode STRING NO e.g. BTC-USD-REPO-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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other

    SUCCESSFUL RESPONSE

    {
        "success": true,
        "data": [
            {
                "id": "810583329213284361",
                "marketCode": "BTC-USD-SWAP-LIN",
                "payment": "-122.17530872",
                "fundingRate": "-0.00005",
                "position": "-61.093",
                "indexPrice": "39996.5",
                "createdAt": "1627617632190"
            }
        ]
    }
    
    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

    Deposits & Withdrawals - Private

    GET /v3/deposit-addresses

    Deposit addresses

    Request

    GET /v3/deposit-addresses?asset={asset}&network={network}
    

    Successful response format

    {
        "success": true,
        "data": {
            "address":"0xD25bCD2DBb6114d3BB29CE946a6356B49911358e"
        }
    }
    
    Request Parameter Type Required Description
    asset STRING YES
    network STRING YES
    Response Field Type Description
    address STRING Deposit address
    memo STRING Memo (tag) if applicable

    GET /v3/deposit

    Deposit history

    Request

    GET /v3/deposit?asset={asset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "asset": "flexUSD",
                "network": "SLP",
                "address": "simpleledger:qzlg6uvceehgzgtz6phmvy8gtdqyt6vf35fxqwx3p7",
                "quantity": "1000.0",
                "id": "651573911056351237",
                "status": "COMPLETED",
                "txId": "38c09755bff75d33304a3cb6ee839fcb78bbb38b6e3e16586f20852cdec4886d",
                "creditedAt": "1617940800000"
            }
        ]
    }
    
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    asset STRING
    network STRING
    address STRING Deposit address
    memo STRING Memo (tag) if applicable
    quantity STRING
    id STRING
    status STRING
    txId STRING
    creditedAt STRING Millisecond timestamp

    GET /v3/withdrawal-addresses

    Withdrawal addresses

    Request

    GET /v3/withdrawal-addresses?asset={asset}?network={network}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "asset": "FLEX",
                "network": "ERC20",
                "address": "0x047a13c759D9c3254B4548Fc7e784fBeB1B273g39",
                "label": "farming",
                "whitelisted": true
            }
        ]
    }
    

    Provides a list of all saved withdrawal addresses along with their respected labels, network, and whitelist status

    Request Parameter Type Required Description
    asset STRING NO Default all assets
    network STRING NO Default all networks
    Response Field Type Description
    asset STRING
    network STRING
    address STRING
    memo STRING Memo (tag) if applicable
    label STRING Withdrawal address label
    whitelisted BOOL

    GET /v3/withdrawal

    Withdrawal history

    Request

    GET /v3/withdrawal?id={id}&asset={asset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "id": "651573911056351237",
                "asset": "flexUSD",
                "network": "SLP",
                "address": "simpleledger:qzlg6uvceehgzgtz6phmvy8gtdqyt6vf35fxqwx3p7",
                "quantity": "1000.0",
                "fee": "0.000000000",
                "status": "COMPLETED",
                "txId": "38c09755bff75d33304a3cb6ee839fcb78bbb38b6e3e16586f20852cdec4886d",
                "requestedAt": "1617940800000",
                "completedAt": "16003243243242"
            }
        ]
    }
    
    Request Parameter Type Required Description
    id STRING NO
    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. This filter applies to "requestedAt"
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other. This filter applies to "requestedAt"
    Response Field Type Description
    id STRING
    asset STRING
    network STRING
    address STRING
    memo STRING Memo (tag) if applicable
    quantity STRING
    fee STRING
    status STRING COMPLETED, PROCESSING, PENDING, IN_SWEEPING, ON HOLD, CANCELED, or FAILED
    txId STRING
    requestedAt STRING Millisecond timestamp
    completedAt STRING Millisecond timestamp

    POST /v3/withdrawal

    Withdrawal request

    Request

    POST /v3/withdrawal
    
    {
        "asset": "flexUSD",
        "network": "SLP",
        "address": "simpleledger:qzlg6uvceehgzgtz6phmvy8gtdqyt6vf35fxqwx3p7",
        "quantity": "100",
        "externalFee": true,
        "tfaType": "GOOGLE",
        "code": "743249"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "id": "752907053614432259",
            "asset": "flexUSD",
            "network": "SLP",
            "address": "simpleledger:qzlg6uvceehgzgtz6phmvy8gtdqyt6vf35fxqwx3p7",
            "quantity": "1000.0",
            "externalFee": true,
            "fee": "0",
            "status": "PENDING",
            "requestedAt": "1617940800000"
        }
    }
    

    Withdrawals may only be initiated by API keys that are linked to the parent account and have withdrawals enabled. If the wrong 2fa code is provided the endpoint will block for 10 seconds.

    Request Parameter Type Required Description
    asset STRING YES
    network STRING YES
    address STRING YES
    memo STRING NO Memo is required for chains that support memo tags
    quantity STRING YES
    externalFee BOOL YES If false, then the fee is taken from the quantity, also with the burn fee for asset SOLO
    tfaType STRING NO GOOGLE, or AUTHY_SECRET, or YUBIKEY
    code STRING NO 2fa code if required by the account
    Response Field Type Description
    id STRING
    asset STRING
    network STRING
    address STRING
    memo STRING
    quantity STRING
    externalFee BOOL If false, then the fee is taken from the quantity
    fee STRING
    status STRING
    requestedAt STRING Millisecond timestamp

    GET /v3/withdrawal-fee

    Withdrawal fee estimate

    Request

    GET /v3/withdrawal-fee?asset={asset}&network={network}&address={address}&memo={memo}&quantity={quantity}&externalFee={externalFee}
    

    Successful response format

    {
        "success": true,
        "data": {
            "asset": "flexUSD",
            "network": "SLP",
            "address": "simpleledger:qzlg6uvceehgzgtz6phmvy8gtdqyt6vf35fxqwx3p7",
            "quantity": "1000.0",
            "externalFee": true,
            "estimatedFee": "0"
        }
    }
    
    Request Parameter Type Required Description
    asset STRING YES
    network STRING YES
    address STRING YES
    memo STRING NO Required only for 2 part addresses (tag or memo)
    quantity STRING YES
    externalFee BOOL NO Default false. If false, then the fee is taken from the quantity
    Response Field Type Description
    asset STRING
    network STRING
    address STRING
    memo STRING Memo (tag) if applicable
    quantity STRING
    externalFee BOOL If false, then the fee is taken from the quantity
    estimatedFee STRING

    Orders - Private

    GET /v3/orders/status

    Get latest order status

    Request

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

    Successful response format

    {
        "success": true,
        "data": {
            "orderId": "1000387920513",
            "clientOrderId": "1612249737434",
            "marketCode": "FLEX-USD",
            "status": "FILLED",
            "side": "BUY",
            "price": "5.200",
            "isTriggered": false,
            "remainQuantity": "0",
            "totalQuantity": "12",
            "cumulativeMatchedQuantity": "12",
            "avgFillPrice": "5.200",
            "orderType": "LIMIT",
            "timeInForce": "GTC",
            "source": "11",
            "createdAt": "1655980336520",
            "lastModifiedAt": "1655980393780",
            "lastMatchedAt": "1655980622848"
        }
    }
    
    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
    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
    avgLeg1Price STRING Average of leg1 price
    avgLeg2Price STRING Average of leg2 price
    fees LIST of dictionaries Overall fees with instrument ID, if FLEX is no enough to pay the fee then USD will be paid
    orderType STRING Type of the order, availabe values: MARKET, LIMIT, STOP_LIMIT
    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, 101, 102, 103, 111.

    Enumeration: 0: GUI, 2: Borrow, 10: AMM, 11: REST, 13: Websocket, 22: Delivery, 101: Automatic borrow, 102: Borrow position liquidation, 103: Contract liquidation, 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
    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.

    Request

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

    Successful response format

    {
        "success": true,
        "data":  [ {        
                    "orderId": "160067484555913076",
                    "clientOrderId": "123",
                    "marketCode": "BTC-USD-SWAP-LIN",
                    "status": "LIMIT"|"STOP",
                    "side": "SELL",
                    "price": "1.0",
                    "stopPrice": "0.9",
                    "isTriggered": true,
                    "quantity": "0.001",
                    "remainQuantity": "0.001",
                    "matchedQuantity": "0",
                    "orderType": "LIMIT", 
                    "timeInForce": "GTC",
                    "source": "0",
                    "createdAt": "1613089383656", 
                    "lastModifiedAt": null,
                    "lastMatchedAt": null
                   }]
    }
    
    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 true for a STOP order
    quantity STRING Quantity
    remainQuantity STRING Remaining quantity
    matchedQuantity STRING Matched Quantity
    orderType STRING Type of the order, availabe values: MARKET, LIMIT, STOP_LIMIT
    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, 101, 102, 103, 111.

    Enumeration: 0: GUI, 2: Borrow, 10: AMM, 11: REST, 13: Websocket, 22: Delivery, 101: Automatic borrow, 102: Borrow position liquidation, 103: Contract liquidation, 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

    POST /v3/orders/place

    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": false,
                        "clientOrderId": "1612249737724",
                        "marketCode": "BTC-USD-SWAP-LIN",
                        "status": "OPEN",
                        "price": "23641.0",
                        "stopPrice": null,
                        "isTriggered": "false",
                        "quantity": "0.01", 
                        "remainQuantity": "0.01",
                        "matchId": null,
                        "matchPrice": null, 
                        "matchQuantity": null, 
                        "feeInstrumentId": null,
                        "fees": null,
                        "orderType": "LIMIT", 
                        "timeInForce": "GTC", 
                        "createdAt": "1629192975532",       
                        "lastModifiedAt": null,         
                        "lastMatchedAt": null   
                    }
              ]
    }
    

    Place 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 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
    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
    timeInForce STRING NO Default GTC
    orderType STRING YES LIMIT or MARKET or STOP
    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
    Response Fields Type Description
    notice STRING OrderClosed or OrderMatched or OrderOpened
    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 STRING false (or true for STOP order types)
    quantity STRING
    remainQuantity STRING Remaining quantity
    matchId STRING
    matchPrice STRING
    matchQuantity 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
    timeInForce STRING
    source STRING Source of the request, available values: 0, 2, 10, 11, 13, 22, 101, 102, 103, 111.

    Enumeration: 0: GUI, 2: Borrow, 10: AMM, 11: REST, 13: Websocket, 22: Delivery, 101: Automatic borrow, 102: Borrow position liquidation, 103: Contract liquidation, 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

    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", 
                        "remainQuantity": "0.001",
                        "orderType": "LIMIT",  
                        "timeInForce": "GTC", 
                        "canceledAt": "1629712561919"
                     },
                     {
                        "code": "40035",
                        "message": "Open order not found with id",
                        "submitted": false,
                         "orderId": "204285250571714316",
                         "clientOrderId": "1612249737724",
                         "marketCode": "BTC-USD-SWAP-LIN",
                         "canceledAt": "1615454881433"
                     }
            ]
    
    }
    

    Cancel orders.

    Request Parameters Type Required Description
    recvWindow LONG NO
    timestamp LONG NO
    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
    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 STRING false (or true for STOP order types)
    quantity STRING
    remainQuantity STRING Remaining quantity
    orderType STRING MARKET or LIMIT or STOP
    timeInForce STRING
    canceledAt STRING Millisecond timestamp of the order cancel time

    DELETE /v3/orders/cancel-all

    Request

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

    Successful response format

    {
        "success": true,
        "data":  {
                       "notice": "Orders queued for cancelation"
                  }
    }
    

    Cancel orders.

    Request Parameters Type Required Description
    marketCode STRING NO
    Response Fields Type Description
    notice STRING Orders queued for cancelation or No working orders found”

    Trades - Private

    GET /v3/trades

    Returns the most recent trades of the account connected to the API key initiating the request.

    Request

    GET /v3/trades?marketCode={marketCode}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
                    {
                        "orderId": "160067484555913076",
                        "clientOrderId": "123",
                        "matchId": "160067484555913077",
                        "marketCode": "FLEX-USD",
                        "side": "SELL",
                        "matchedQuantity": "0.1",
                        "matchPrice": "0.065",
                        "total": "0.0065",  
                        "leg1Price'": "0.0065",         
                        "leg2Price": "0.0065",          
                        "orderMatchType": "TAKER",
                        "feeAsset": "FLEX",
                        "fee":"0.0096",
                        "source": "10",
                        "matchedAt": "1595514663626"
    
                   }
                ]
    }
    
    Request Parameter Type Required Description
    marketCode String default most recent trades first
    limit LONG NO max 500, default 200
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    orderId STRING Order ID
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    matchId STRING Match ID
    marketCode STRING Market code
    side STRING Side of the order, BUY or SELL
    matchedQuantity STRING Match quantity
    matchPrice STRING Match price
    total STRING Total price
    leg1Price STRING REPO & SPREAD
    leg2Price STRING REPO & SPREAD
    orderMatchType STRING TAKER,MAKER
    feeAsset STRING Instrument ID of the fees
    fee STRING Fees
    source STRING Source of the request, available values: 0, 2, 10, 11, 13, 22, 101, 102, 103, 111.

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

    matchedAt STRING Millisecond timestamp of the order matched time

    Flex Assets - Private

    POST /v3/flexasset/mint

    Mint

    Request

    POST /v3/flexasset/mint
    
    {
        "asset": "flexUSD",
        "quantity": "100"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "asset": "flexUSD",
            "quantity": "100"
        }
    }
    
    Request Parameter Type Required Description
    asset STRING YES Asset name, available assets e.g. flexUSD, flexBTC, flexETH, flexFLEX, flexAXS, flexBNB
    quantity STRING YES Quantity to mint, minimum quantity required: 10 flexUSD, 0.001 flexBTC, 0.1 flexETH, 100 flexFLEX, 1 flexAXS, 1 flexBNB
    Response Field Type Description
    asset STRING
    quantity STRING

    POST /v3/flexasset/redeem

    Redeem

    Request

    POST /v3/flexasset/redeem
    
    {
        "asset": "flexUSD",
        "quantity": "100",
        "type": "NORMAL"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "asset": "flexUSD",
            "quantity": "100",
            "type": "NORMAL",
            "redemptionAt": "1617940800000"
        }
    }
    
    Request Parameter Type Required Description
    asset STRING YES Asset name, available assets e.g. flexUSD, flexBTC, flexETH, flexFLEX, flexAXS, flexBNB
    quantity STRING YES Quantity to redeem, minimum quantity required: 10 flexUSD, 0.001 flexBTC, 0.1 flexETH, 100 flexFLEX, 1 flexAXS, 1 flexBNB
    type STRING YES NORMAL queues a redemption until the following interest payment and incurs no fee. INSTANT instantly redeems into the underlying asset and charges a fee equal to the sum of the two prior interest payments
    Response Field Type Description
    asset STRING
    quantity STRING
    type STRING Available types: NORMAL, INSTANT
    redemptionAt STRING Millisecond timestamp indicating when redemption will take place

    GET /v3/flexasset/mint

    Get mint history by asset and sorted by time in descending order.

    Request

    GET /v3/flexasset/mint?asset={asset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
              "asset": "flexUSD",
              "quantity": "1000.0",
              "mintedAt": "16003243243242"
            }
        ]
    }
    
    Request Parameter Type Required Description
    asset STRING NO Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    asset STRING
    quantity STRING
    mintedAt STRING

    GET /v3/flexasset/redeem

    Get redemption history by asset and sorted by time in descending order.

    Request

    GET /v3/flexasset/redeem?asset={asset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
              "asset": "flexUSD",
              "quantity": "1000.0",
              "requestedAt": "16003243243242",
              "redeemedAt": "16003243243242"
            }
        ]
    }
    
    Request Parameter Type Required Description
    asset STRING NO Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    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. Here startTime and endTime refer to the "requestedAt" timestamp
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other. Here startTime and endTime refer to the "requestedAt" timestamp
    Response Field Type Description
    asset STRING
    quantity STRING
    requestedAt STRING Millisecond timestamp indicating when redemption was requested
    redeemedAt STRING Millisecond timestamp indicating when the flexAssets were redeemed

    GET /v3/flexasset/earned

    Get earned history by asset and sorted by time in descending order.

    Request

    GET /v3/flexasset/earned?asset={asset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "asset": "flexUSD",
                "snapshotQuantity": "10000",
                "apr": "25",
                "rate": "0.00022831",
                "amount": "2.28310502",
                "paidAt": "1635822660847"
            }
        ]
    }
    
    Request Parameter Type Required Description
    asset STRING NO Asset name, available assets: flexUSD, flexBTC, flexETH, flexFLEX
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    asset STRING Asset name
    snapshotQuantity STRING
    apr STRING Annualized APR (%) = rate * 3 * 365 * 100
    rate STRING Period interest rate
    amount STRING
    paidAt STRING

    AMM - Private

    POST /v3/AMM/create

    Create AMM

    Request

    POST /v3/AMM/create
    

    Parameters to create a leveraged buy, sell, or neutral AMM

    {
        "leverage": "5",
        "direction": "BUY",
        "marketCode": "BCH-USD-SWAP-LIN",
        "collateralAsset": "BCH",
        "collateralQuantity": "50",
        "minPriceBound": "200",
        "maxPriceBound": "800"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "hashToken": "CF-BCH-AMM-ABCDE3iy",
            "leverage": "5",
            "direction": "BUY",
            "marketCode": "BCH-USD-SWAP-LIN",
            "collateralAsset": "BCH",    
            "collateralQuantity": "50",                
            "minPriceBound": "200",
            "maxPriceBound": "800"
        }
    }
    
    Request Parameter Type Required Description
    leverage STRING NO String from 1 to 10
    direction STRING YES Available values: BUY and SELL
    marketCode STRING YES Market code
    collateralAsset STRING NO Collateral asset, required when using leverage
    collateralQuantity STRING NO Collateral quantity, minimum notional $200, required when using leverage
    baseQuantity STRING NO Base asset quantity, required for unleveraged sell, and neutral AMMs.
    counterQuantity STRING NO Counter asset quantity, required for unleveraged buy, and neutral AMMs
    minPriceBound STRING YES Minimum price bound
    maxPriceBound STRING YES Maximum price bound
    Response Field Type Description
    hashToken STRING Hash token
    leverage STRING Leverage, string from 1 to 10
    direction STRING Available values: BUY and SELL
    marketCode STRING Market code
    collateralAsset STRING Collateral asset
    collateralQuantity STRING Collateral quantity, minimum notional $200
    baseAsset STRING Base asset
    baseQuantity STRING Base asset quantity, required for unleveraged sell, and neutral AMMs
    counterAsset STRING Counter asset
    counterQuantity STRING Counter asset quantity, required for unleveraged buy, and neutral AMMs
    minPriceBound STRING Minimum price bound
    maxPriceBound STRING Maximum price bound

    Unleveraged buy AMM

    {
        "direction": "BUY",
        "marketCode": "BCH-USD-SWAP-LIN",
        "counterQuantity": "250",
        "minPriceBound": "200",
        "maxPriceBound": "800"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "hashToken": "CF-BCH-AMM-ABCDE3iy",
            "direction": "BUY",
            "marketCode": "BCH-USD-SWAP-LIN",
            "counterAsset": "USD",
            "counterQuantity": "50",
            "minPriceBound": "200",
            "maxPriceBound": "800"
        }
    }
    

    For unleveraged neutral AMMs the mid point of the price bounds has to equal counterQuantity / baseQuantity.

    Unleveraged neutral AMM

    {
        "direction": "NEUTRAL",
        "marketCode": "BCH-USD-SWAP-LIN",
        "baseQuantity": "1",
        "counterQuantity": "500",
        "minPriceBound": "200",
        "maxPriceBound": "800"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "hashToken": "CF-BCH-AMM-ABCDE3iy",
            "direction": "BUY",
            "marketCode": "BCH-USD-SWAP-LIN",
            "baseAsset": "BCH",
            "counterAsset": "USD",
            "baseQuantity": "1",
            "counterQuantity": "500",
            "minPriceBound": "200",
            "maxPriceBound": "800"
        }
    }
    

    POST /v3/AMM/redeem

    Redeem AMM

    Request

    POST /v3/AMM/redeem
    
    {
        "hashToken": "CF-BCH-AMM-ABCDE3iy",
        "type":"DELIVER",
        "accountId": "9546"
    }
    

    Successful response format

    {
        "success": true,
        "data": {
            "hashToken": "CF-BCH-AMM-ABCDE3iy",
            "type":"DELIVER",
            "accountId": "9546"
        }
    }
    
    Request Parameter Type Required Description
    hashToken STRING YES Hash token
    type STRING YES Available values: DELIVER and MANUAL. DELIVER invokes physical delivery, the AMM must have the appropriate balance to trigger delivery. MANUAL cancels all working orders and creates a sub account that is accessible from the dashboard.
    accountId STRING NO Account ID
    Response Field Type Description
    hashToken STRING Hash token
    type STRING Available values: DELIVER and MANUAL
    accountId STRING Account ID

    GET /v3/AMM

    Get AMM information

    Request

    GET /v3/AMM?hashToken={hashToken},{hashToken}
    

    Successful response format

    {
        "success": true,
        "data": {
            "hashToken": "CF-BCH-AMM-ABCDE3iy",
            "leverage": "3",
            "direction": "BUY",
            "marketCode": "BCH-USD-SWAP-LIN",
            "initialCollateral": {
                "BCH": "123"
            },
            "minPriceBound": "200",
            "maxPriceBound": "800",
            "status": "ENDED",
            "positions": [
                {
                    "marketCode": "BTC-USD-SWAP-LIN",
                    "baseAsset": "BTC",
                    "counterAsset": "USD",
                    "position": "0.94",
                    "entryPrice": "7800.00",
                    "markPrice": "33000.00",
                    "positionPnl": "200.3",
                    "estLiquidationPrice": "12000.05",
                    "lastUpdatedAt": "1592486212218"
                }
            ],
            "balances": [
                {
                    "asset": "BTC",
                    "total": "4468.823",
                    "available": "4468.823",
                    "reserved": "0",
                    "lastUpdatedAt": "1593627415223"
                }
            ],
            "usdReward": "200",
            "flexReward": "200",
            "interestPaid": "123",
            "apr": "120",
            "volume": "2143324.342",
            "collateral": "1231231",
            "portfolioVarMargin": "500",
            "riskRatio": "20.0000",
            "maintenanceMargin": "1231",
            "marginRatio": "12.3179",
            "liquidating": false,
            "feeTier": "6",
            "createdAt": "1623042343252",
            "lastUpdatedAt": "1623142532134"
        }
    }
    
    Request Parameter Type Required Description
    hashToken STRING YES Multiple hashTokens can be separated with a comma, maximum of 5 hashTokens, e.g. CF-BCH-AMM-ABCDE3iy,CF-BCH-AMM-ABCDE4iy
    Response Field Type Description
    hashToken STRING Hash token
    leverage STRING Leverage if applicable
    direction STRING Direction
    marketCode STRING Market code
    initialCollateral JSON Initial collateral
    minPriceBound STRING Minimum price bound
    maxPriceBound STRING Maximum price bound
    status STRING Status
    positions LIST of dictionaries Positions
    baseAsset STRING Base asset
    counterAsset STRING Counter asset
    position STRING Position
    entryPrice STRING Entry price
    markPrice STRING Mark price
    positionPnl STRING Position PNL
    estLiquidationPrice STRING Estimated liquidation price
    lastUpdatedAt STRING Timestamp
    marginBalance STRING Appears in the position section only for positions using isolated margin. Isolated margin + Unrealized position PnL
    maintenanceMargin STRING Appears in the position section only for positions using isolated margin
    marginRatio STRING Appears in the position section only for positions using isolated margin
    leverage STRING Appears in the position section only for positions using isolated margin
    balances LIST of dictionaries Balances
    asset STRING Asset
    total STRING Total balance
    available STRING Available balance
    reserved STRING Reserved balance
    usdReward STRING USD reward from scalping
    flexReward STRING FLEX reward from fee rebates
    interestPaid STRING Interest paid, positive values imply interest was paid to the AMM, negative values imply interest was paid by the AMM
    apr STRING APR denotes annual percentage rate
    volume STRING Traded volume
    collateral STRING Collateral
    notionalPositionSize STRING Notional position size
    portfolioVarMargin STRING Portfolio margin
    riskRatio STRING collateralBalance / portfolioVarMargin, Orders are rejected/cancelled if the risk ratio drops below 1 and liquidation occurs if the risk ratio drops below 0.5
    maintenanceMargin STRING Maintenance margin
    marginRatio STRING Margin ratio
    liquidating BOOL Available values: true and false
    feeTier STRING Fee tier
    createdAt STRING AMM creation millisecond timestamp

    GET /v3/AMM/balances

    Get AMM balances

    Request

    GET /v3/AMM/balances?hashToken={hashToken},{hashToken}&asset={asset}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "hashToken": "CF-BCH-AMM-ABCDE3iy",
                "balances": [
                    {
                        "asset": "BTC",
                        "total": "4468.823",              
                        "available": "4468.823",        
                        "reserved": "0",
                        "lastUpdatedAt": "1593627415234"
                    },
                    {
                        "asset": "FLEX",
                        "total": "1585.890",              
                        "available": "325.890",         
                        "reserved": "1260",
                        "lastUpdatedAt": "1593627415123"
                    }
                ]
            }
        ]
    }
    
    Request Parameter Type Required Description
    hashToken STRING YES Multiple hashTokens can be separated with a comma, maximum of 5 hashTokens, e.g. CF-BCH-AMM-ABCDE3iy,CF-BCH-AMM-ABCDE4iy
    asset STRING NO
    Response Field Type Description
    hashToken STRING Hash token
    balances LIST of dictionaries Balances
    asset STRING Asset
    total STRING Total balance
    available STRING Available balance
    reserved STRING Reserved balance
    lastUpdatedAt STRING Millisecond timestamp of last updated at

    GET /v3/AMM/positions

    Get AMM positions

    Request

    GET /v3/AMM/positions?hashToken={hashToken},{hashToken}&marketCode={marketCode}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "hashToken": "CF-BCH-AMM-ABCDE3iy",
                "positions": [
                    {
                        "marketCode": "BTC-USD-SWAP-LIN",
                        "baseAsset": "BTC",
                        "counterAsset": "USD",
                        "position": "0.94",
                        "entryPrice": "7800.00", 
                        "markPrice": "33000.00", 
                        "positionPnl": "200.3",
                        "estLiquidationPrice": "12000.05",
                        "lastUpdatedAt": "1592486212218"
                    }
                ]
            }
        ]
    }
    
    Request Parameter Type Required Description
    hashToken STRING YES Multiple hashTokens can be separated with a comma, maximum of 5 hashTokens, e.g. CF-BCH-AMM-ABCDE3iy,CF-BCH-AMM-ABCDE4iy
    marketCode STRING NO Market code
    Response Field Type Description
    hashToken STRING Hash token
    positions LIST of dictionaries 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 Millisecond timestamp of last updated at

    GET /v3/AMM/orders

    Get AMM orders

    Request

    GET /v3/AMM/orders?hashToken={hashToken}
    
    

    Successful response format

    { 
        "success": true,
        "data": [
            {
                "orderId": "304354590153349202",
                "clientOrderId": "1",
                "marketCode": "BTC-USD-SWAP-LIN", 
                "status": "OPEN",
                "side": "BUY", 
                "price": "1.0",
                "quantity": "0.001",
                "remainQuantity": "0.001",
                "matchedQuantity": "0",
                "orderType": "LIMIT", 
                "timeInForce": "GTC",
                "createdAt": "1613089383656", 
                "lastModifiedAt": "1613089393622",
                "lastMatchedAt": "1613099383613"
            }
        ]
    }
    
    Request Parameter Type Required Description
    hashToken STRING YES Maximum 1 hashToken, e.g. CF-BCH-AMM-ABCDE3iy
    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: PARTIALLY_FILLED and OPEN
    side STRING Available values: BUY and SELL
    price STRING Limit price
    stopPrice STRING Stop price if applicable
    isTriggered BOOL Available values: true and false if applicable
    quantity STRING Quantity
    remainQuantity STRING Remaining order quantity
    matchedQuantity STRING Matched quantity
    orderType STRING Available values: LIMIT or STOP
    timeInForce STRING Time in force
    createdAt STRING Timestamp
    lastModifiedAt STRING Millisecond timestamp if applicable
    lastMatchedAt STRING Millisecond timestamp if applicable

    GET /v3/AMM/trades

    Get AMM trades. Trades are filtered in descending order (most recent first)

    Request

    GET /v3/AMM/trades?hashToken={hashToken}&marketCode={marketCode}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {    
        "success": true,
        "data": [
            {         
                "orderId": "1000099731323", 
                "clientOrderId": "16", 
                "matchId": "2001011000000", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "side": "SELL", 
                "matchedQuantity": "0.001", 
                "matchPrice": "50625", 
                "total": "50.625", 
                "orderMatchType": "MAKER", 
                "feeAsset": "FLEX",
                "fee": "-0.00307938", 
                "lastMatchedAt": "1639016502495"
            }
        ]
    }
    
    Request Parameter Type Required Description
    hashToken STRING YES Single hashToken e.g. CF-BCH-AMM-ABCDE3iy
    marketCode STRING NO Market code
    limit LONG NO Default 200, max 500, if the limit is reached and there are more trade records with the same millisecond timestamp as any of the included records, ignore the limit and return all of the additional trades that were recorded with that millisecond timestamp
    startTime LONG NO Millisecond timestamp. Default 24 hours ago. startTime and endTime must be within 7 days of each other
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    orderId STRING Order ID
    clientOrderId STRING Client assigned ID to help manage and identify orders with max value 9223372036854775807
    matchId STRING Match ID
    marketCode STRING Market code
    side STRING Available values: BUY and SELL
    matchedQuantity STRING Matched quantity
    matchPrice STRING Match price
    total STRING Total price
    leg1Price STRING
    leg2Price STRING
    orderMatchType STRING Available values: TAKER and MAKER
    feeAsset STRING Fee asset
    fee STRING Fee
    lastMatchedAt STRING Millisecond timestamp

    GET /v3/AMM/hash-token

    Get AMM hashTokens in descending order (most recent first)

    Request

    GET /v3/AMM/hash-token?status={status}&marketCode={marketCode}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "hashToken": "CF-ETH-AMM-607973",
                "direction": "BUY",
                "marketCode": "ETH-USD-SWAP-LIN",
                "minPriceBound": "3340",
                "maxPriceBound": "3380",
                "status": "EXECUTING",
                "createdAt": "1649630816578"
            },
            {
                "hashToken": "CF-BCH-AMM-607818",
                "direction": "SELL",
                "marketCode": "BCH-USD-SWAP-LIN",
                "minPriceBound": "300",
                "maxPriceBound": "1500",
                "status": "EXECUTING",
                "createdAt": "1649544662014"
            }
        ]
    }
    
    Request Parameter Type Required Description
    status STRING NO Available values: EXECUTING, ENDED, PENDING, LIQUIDATED
    marketCode STRING NO Market code
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    hashToken STRING hashToken e.g. CF-BCH-AMM-ABCDE3iy
    direction STRING Available values: BUY and SELL
    marketcode STRING Market code
    minPriceBound STRING Minimum price bound
    maxPriceBound STRING Maximum price bound
    status STRING Available values: EXECUTING, ENDED, PENDING, LIQUIDATED
    createdAt STRING Millisecond timestamp

    Market Data - Public

    GET /v3/markets

    Get a list of markets on CoinFlex.

    Request

    GET /v3/markets?marketCode={marketCode}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "marketCode": "BTC-USD",
                "name": "BTC/USD",
                "referencePair": "BTC/USD",
                "base": "BTC",
                "counter": "USD",
                "type": "SPOT",
                "tickSize": "0.1",
                "minSize": "0.001",
                "listedAt": "1593345600000",
                "upperPriceBound": "65950.5",
                "lowerPriceBound": "60877.3",
                "markPrice": "63413.9",
                "lastUpdatedAt": "1635848576163"
            }
        ]
    }
    
    Request Parameter Type Required Description
    marketCode STRING NO
    Response Field Type Description
    marketCode STRING Market Code
    name STRING Name of the contract
    referencePair STRING Reference pair
    base STRING Base asset
    counter STRING Counter asset
    type STRING Type of the contract
    tickSize STRING Tick size of the contract
    minSize STRING Minimum quantity
    listedAt STRING Listing date of the contract
    settlementAt STRING Timestamp of settlement if applicable i.e. Quarterlies and Spreads
    upperPriceBound STRING Sanity bound
    lowerPriceBound STRING Sanity bound
    markPrice STRING Mark price
    indexPrice STRING index price
    lastUpdatedAt STRING

    GET /v3/assets

    Get a list of assets supported on CoinFLEX

    Request

    GET /v3/assets?asset={asset}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "asset": "USD",
                "isCollateral": true,
                "loanToValue": "1.000000000",
                "networkList": [
                    {
                        "network": "ERC20",
                        "transactionPrecision": "6",
                        "isWithdrawalFeeChargedToUser": true,
                        "canDeposit": true,
                        "canWithdraw": true,
                        "minDeposit": "0.0001",
                        "minWithdrawal": "2"
                    }
                ]
            },
            {
                "asset": "LINK",
                "isCollateral": true,
                "loanToValue": "0.800000000",
                "networkList": [
                    {
                        "network": "ERC20",
                        "tokenId": "0x514910771af9ca656af840dff83e8264ecf986ca",
                        "transactionPrecision": "18",
                        "isWithdrawalFeeChargedToUser": true,
                        "canDeposit": true,
                        "canWithdraw": true,
                        "minDeposit": "0.0001",
                        "minWithdrawal": "0.0001"
                    }
                ]
            }
        ]
    }
    
    Request Parameter Type Required Description
    asset STRING NO Asset name
    Response Field Type Description
    asset STRING Asset name
    isCollateral BOOL Indicates it is collateral or not
    loanToValue STRING Loan to value of the asset
    networkList LIST List of dictionaries
    network STRING Network for deposit and withdrawal
    tokenId STRING Token ID
    transactionPrecision STRING Precision for the transaction
    isWithdrawalFeeChargedToUser BOOL Indicates the withdrawal fee is charged to user or not
    canDeposit BOOL Indicates can deposit or not
    canWithdraw BOOL Indicates can withdraw or not
    minDeposit STRING Minimum deposit amount
    minWithdrawal STRING Minimum withdrawal amount

    GET /v3/tickers

    Get tickers.

    Request

    GET /v3/tickers?marketCode={marketCode}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "marketCode": "BTC-USD-SWAP-LIN",
                "markPrice": "41512.4",
                "open24h": "41915.3",
                "high24h": "42662.2",
                "low24h": "41167.0",
                "volume24h": "114341.4550",
                "currencyVolume24h": "2.733",
                "openInterest": "3516.506000000",
                "lastTradedPrice": "41802.5",
                "lastTradedQuantity": "0.001",
                "lastUpdatedAt": "1642585256002"
            }
        ]
    }
    
    Request Parameter Type Required Description
    marketCode STRING NO Market code
    Response Field Type Description
    marketCode STRING Market code
    markPrice STRING Mark price
    open24h STRING Rolling 24 hour opening price
    high24h STRING Rolling 24 hour highest price
    low24h STRING Rolling 24 hour lowest price
    volume24h STRING Rolling 24 hour notional trading volume
    currencyVolume24h STRING Rolling 24 hour trading volume in base currency
    openInterest STRING Open interest
    lastTradedPrice STRING Last traded price
    lastTradedQuantity STRIN Last traded quantity
    lastUpdatedAt STRING Millisecond timestamp of lastest update

    GET /v3/funding/estimates

    Request

    GET /v3/funding/estimates?marketCode={marketCode}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "marketCode": "WBTC-USD-SWAP-PER",
                "fundingAt": "1667012400000",
                "estFundingRate": "0"
            },
            {
                "marketCode": "BTC-USD-SWAP-LIN",
                "fundingAt": "1667012400000",
                "estFundingRate": "0"
            }
        ]
    }
    
    Request Parameter Type Required Description
    marketCode STRING YES Market code
    Response Field Type Description
    marketCode STRING Market code
    estFundingRate STRING Estimates funding rate
    fundingAt STRING Millisecond timestamp

    GET /v3/candles

    Get candles.

    Request

    GET /v3/candles?marketCode={marketCode}&timeframe={timeframe}&limit={limit}
    &startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true, 
        "timeframe": "3600s", 
        "data": [
            {
                "open": "35888.80000000", 
                "high": "35925.30000000", 
                "low": "35717.00000000", 
                "close": "35923.40000000", 
                "volume": "0",
                "currencyVolume": "0",
                "openedAt": "1642932000000"
            },
            {
                "open": "35805.50000000", 
                "high": "36141.50000000", 
                "low": "35784.90000000", 
                "close": "35886.60000000", 
                "volume": "0",
                "currencyVolume": "0",
                "openedAt": "1642928400000"
            }
        ]
    }
    
    Request Parameter Type Required Description
    marketCode STRING YES Market code
    timeframe STRING NO Available values: 60s,300s,900s,1800s,3600s,7200s,14400s,86400s, default is 3600s
    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.
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other.
    Response Field Type Description
    timeframe STRING Available values: 60s,300s,900s,1800s,3600s,7200s,14400s,86400s
    open STRING Opening price
    high STRING Highest price
    low STRING Lowest price
    close STRING Closing price
    volume STRING Trading volume in counter currency
    currencyVolume STRING Trading volume in base currency
    openedAt STRING Millisecond timestamp of the candle open

    GET /v3/depth

    Get depth.

    Request

    GET /v3/depth?marketCode={marketCode}&level={level}
    

    Successful response format

    {
        "success": true, 
        "level": "5", 
        "data": {
            "marketCode": "BTC-USD-SWAP-LIN", 
            "lastUpdatedAt": "1643016065958", 
            "asks": [
                [
                    39400, 
                    0.261
                ], 
                [
                    41050.5, 
                    0.002
                ], 
                [
                    41051, 
                    0.094
                ], 
                [
                    41052.5, 
                    0.002
                ], 
                [
                    41054.5, 
                    0.002
                ]
            ], 
            "bids": [
                [
                    39382.5, 
                    0.593
                ], 
                [
                    39380.5, 
                    0.009
                ], 
                [
                    39378, 
                    0.009
                ], 
                [
                    39375.5, 
                    0.009
                ], 
                [
                    39373, 
                    0.009
                ]
            ]
        }
    }
    
    Request Parameter Type Required Description
    marketCode STRING YES Market code
    level LONG NO Default 5, max 100
    Response Field Type Description
    level LONG Level
    marketCode STRING Market code
    lastUpdatedAt STRING Millisecond timestamp of the lastest depth update
    asks LIST of floats Sell side depth: [price, quantity]
    bids LIST of floats Buy side depth: [price, quantity]

    GET /v3/markets/operational

    Get markets operational.

    Request

    GET /v3/markets/operational?marketCode={marketCode}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "marketCode": "BTC-USD",
                "operational": true 
            }
        ]
    }
    
    Request Parameter Type Required Description
    marketCode STRING YES Market code
    Response Field Type Description
    marketCode STRING Market code
    operational BOOL whether the market of the marketCode is operational

    GET /v3/exchange-trades

    Request

    GET /v3/exchange-trades?marketCode={marketCode}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "marketCode": "BTC-USD-SWAP-LIN",
                "matchPrice": "9600.00000" ,
                "matchQuantity": "0.100000" ,
                "side": "BUY" ,
                "matchType": "TAKER" ,
                "matchedAt": "1662207330439" 
            }
        ]
    }
    
    Request Parameter Type Required Description
    marketCode STRING YES Market code
    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
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other
    Response Field Type Description
    marketCode STRING
    matchPrice STRING
    matchQuantity STRING
    side STRING
    matchType STRING
    matchedAt STRING

    All Funding Rates - Public

    GET /v3/funding/rates

    Get all historical financing rates, including PLP

    Request

    GET /v3/funding/rates?marketCode={marketCode}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "marketCode": "BTC-USD-SWAP-LIN",
                "fundingRate": "0.0",
                "createdAt": "1628362803134"
            },
            {
                 "marketCode": "TKX-USD-SWAP-PER",
                 "fundingRate": "0.0",
                 "createdAt": "1628362803134"
            }
        ]
    }
    
    Request Parameter Type Required Description
    marketCode STRING NO Market code
    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.
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other.
    Response Field Type Description
    marketCode STRING Market code
    fundingRate STRING Funding rate
    createdAt STRING Millisecond timestamp

    Flex Assets - Public

    GET /v3/flexasset/balances

    Get flexAsset balances.

    Request

    GET /v3/flexasset/balances?flexasset={flexasset}
    

    Successful response format

    {
        "success": true, 
        "flexasset": "flexUSD", 
        "data": [
            {
                "asset": "USD", 
                "total": "110.78000000", 
                "available": "110.78000000", 
                "reserved": "0", 
                "lastUpdatedAt": "1642735371714"
            }
        ]
    }
    
    Request Parameter Type Required Description
    flexasset STRING YES FlexAsset name, available assets e.g. flexUSD, flexBTC, flexETH, flexFLEX
    Response Field Type Description
    asset STRING Asset name, e.g. 'BTC'
    total STRING Total balance
    available STRING Available balance
    reserved STRING Reserved balance (unavailable) due to working spot orders
    lastUpdatedAt STRING Millisecond timestamp of the latest balance update

    GET /v3/flexasset/positions

    Get flexAsset positions.

    Request

    GET /v3/flexasset/positions?flexasset={flexasset}
    

    Successful response format

    {
        "success": true,
        "flexasset": "flexUSD",
        "data": [
            {
                "marketCode": "BCH-USD-SWAP-LIN",
                "baseAsset": "BCH",
                "counterAsset": "USD",
                "quantity": "-4363.81",
                "entryPrice": "380.69",
                "markPrice": "297.74",
                "positionPnl": "-361978.0395",
                "estLiquidationPrice": "0",
                "lastUpdatedAt": "1643173228911"
            },
            {
                "marketCode": "BTC-USD-SWAP-LIN",
                "baseAsset": "BTC",
                "counterAsset": "USD",
                "quantity": "-28.931000000",
                "entryPrice": "43100.5",
                "markPrice": "37850.2",
                "positionPnl": "151896.4293000000",
                "estLiquidationPrice": "345678367498.5",
                "lastUpdatedAt": "1642666693674"
            }
        ]
    }
    
    Request Parameter Type Required Description
    flexasset STRING YES FlexAsset name, available assets e.g. flexUSD, flexBTC, flexETH, flexFLEX
    Response Field Type Description
    marketCode STRING Market code
    baseAsset STRING Base asset
    counterAsset STRING Counter asset
    quantity STRING Position size
    entryPrice STRING Average entry price
    markPrice STRING Mark price
    positionPnl STRING Postion profit and loss
    estLiquidationPrice STRING Estimated liquidation price, return 0 if it is negative (<0)
    lastUpdatedAt STRING Millisecond timestamp of the latest position update

    GET /v3/flexasset/yields

    Get flexasset yields.

    Request

    GET /v3/flexasset/yields?flexasset={flexasset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "flexasset": "flexBTC",
                "apr": "0",
                "yield": "0",
                "paidAt": "1643193000000"
            },
            {
                "flexasset": "flexUSD",
                "apr": "0",
                "yield": "0",
                "paidAt": "1643193000000"
            }
        ]
    }
    
    Request Parameter Type Required Description
    flexasset STRING NO FlexAsset name, available assets e.g. flexUSD, flexBTC, flexETH, flexFLEX
    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.
    endTime LONG NO Millisecond timestamp. Default time now. startTime and endTime must be within 7 days of each other.
    Response Field Type Description
    flexasset STRING Asset name, available assets e.g. flexUSD, flexBTC, flexETH, flexFLEX
    apr STRING Annualized APR (%) = yield * 3 * 365 * 100
    yield STRING Period yield
    paidAt STRING Millisecond timestamp of the interest payment