NAV
curl javascript python

Change Log

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-07-08

2021-05-24

2021-05-21

2021-05-13

2021-05-12

2021-04-28

2021-04-21

2021-04-19

2021-03-31

2021-03-18

2021-03-10

2021-02-26

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
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 Balance) 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':
                await ws.send(json.dumps(place_order))
                print(data)
                break

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",
            "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
data DICTIONARY object Yes
clientOrderId INTEGER No Client assigned ID to help manage and identify orders
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",
            "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
data DICTIONARY object Yes
clientOrderId INTEGER No Client assigned ID to help manage and identify orders
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",
            "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",
            "quantity": "10",
            "timeInForce": "MAKER_ONLY_REPRICE",
            "stopPrice": "100",
            "limitPrice": "120",
            "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",
            "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
data DICTIONARY object Yes
clientOrderId INTEGER No Client assigned ID to help manage and identify orders
marketCode STRING Yes Market code e.g. ETH-USD-SWAP-LIN
orderType STRING Yes STOP 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",
            "source": 0
          }
}

AND

{
  "event": "placeorder",
  "submitted": True,
  "tag": "123",
  "timestamp": "1607639739136",
  "data": {
            "clientOrderId": "2",
            "marketCode": "BTC-USD",
            "side": "SELL",
            "orderType": "MARKET",
            "quantity": "0.2",
            "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
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",
            "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
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",
            "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
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
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
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",
              "quantityLastUpdated": "1599694369431"
            },
            {
              "total": "100000",
              "reserved": "0",
              "instrumentId": "FLEX",
              "available": "100000",
              "quantityLastUpdated": "1599694343242"
            }, 
            ........
          ]
}

Channel Update Frequency : 250ms

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

If a subscription has been made to balance:all, the data array in the message from this balance channel will contain a JSON list. Each JSON will contain balance details for each spot asset. 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

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)
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": [ {
              "entryPrice": "1900.0",
              "lastUpdated": "1616053755423",
              "contractValCurrency": "ETH",
              "quantity" : "0.1",
              "instrumentId": "ETH-USD-SWAP-LIN",
              "positionPnl": "-5.6680",
              "estLiquidationPrice": "0"
            },
            {
              "entryPrice": "56934.8258",
              "lastUpdated": "1617099855968",
              "contractValCurrency": "BTC",
              "quantity" : "0.542000000",
              "instrumentId": "BTC-USD-SWAP-LIN",
              "positionPnl": "1220.9494164000000",
              "estLiquidationPrice": "53179.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 instrument. Otherwise the data array will contain a single JSON corresponding to one instrument per position channel subscription.

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

Channel Update Fields

Fields Type Description
table STRING position
accountId STRING Account identifier
timestamp STRING Current millisecond timestamp
data LIST of dictionaries
entryPrice STRING Average entry price of total position (Cost / Size)
lastUpdated STRING Millisecond timestamp
contractValCurrency STRING Base asset ID e.g. ETH
quantity STRING Position size (+/-)
instrumentId STRING e.g. ETH-USD-SWAP-LIN
positionPnl STRING Postion profit and lost
estLiquidationPrice STRING Estimated liquidation price, return 0 if it is negative(<0)

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(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"
}

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

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 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",
              "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
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
stopPrice STRING Stop price submitted (only applicable for STOP order types)
limitPrice STRING Limit price submitted (only applicable for STOP 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 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",
              "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
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 Remaining order quantity of closed order
stopPrice STRING Stop price of closed stop order (only applicable for STOP order types)
limitPrice STRING Limit price of closed stop order (only applicable for STOP order types)
ordertype STRING LIMIT or STOP
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
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

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
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
stopPrice STRING Stop price of modified order (only applicable for STOP order types)
limitPrice STRING Limit price of modified order (only applicable for STOP 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
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
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 order types)
limitPrice STRING Limit price submitted (only applicable for STOP 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 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
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)

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>",.....]}

Orderbook Depth

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

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

Orderbook depth channel format

{
  "table": "depth",
  "data": [ {
      "instrumentId": "BTC-USD-SWAP-LIN",
      "seqNum": 1608898592006137237,
      "timestamp": "1609350022785",
      "checksum": 1139901235, 
      "asks": [ [5556.82, 11, 0, 0],    //price, quantity, 0, 0
                [5556.84, 98.13, 0, 0],
                [5556.92, 1.582, 0, 0],
                [5557.6, 4.291, 0, 0],
                [5557.85, 2.54, 0, 0]
              ],
      "bids": [ [5556.81, 1.92, 0, 0],  //price, quantity, 0, 0
                [5556.8, 2.1, 0, 0],
                [5556.79, 1.9, 0, 0],
                [5556.19, 100, 0, 0],
                [5556.08, 2.972, 0, 0]
              ]
          } ]
}

Channel Update Frequency: 50ms

This orderbook depth channel sends a snapshot of the entire orderbook 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
args LIST Yes List of individual markets <depth>:<marketCode> e.g: [depthL10:BTC-USD-SWAP-LIN], the depth can be depthL5 depthL10 depthL25 depth(includes all)

Channel Update Fields

Fields Type Description
table STRING depth
data LIST of dictionary
instrumentId STRING Instrument ID
seqNum INTEGER Sequence number of the order book snapshot
timestamp STRING Millisecond timestamp
asks LIST of floats Sell side depth;
  1. price
  2. quantity
  3. 0
  4. 0
bids LIST of floats Buy side depth;
  1. price
  2. quantity
  3. 0
  4. 0

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",
              "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 orderbook.

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 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
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
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
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
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
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
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

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
    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
    
    # REST API method
    method = '/v2/accountinfo'
    
    # Not required for /v2/accountinfo
    body = urlencode({})
    
    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())
    

    Response

    {
      "event": "accountinfo",
      "timestamp": 1611665626191
      "accountId": "<Your Account ID>",
      "data": [ {
                  "accountId": "<Your Account ID>",
                  "tradeType": "LINEAR",
                  "marginCurrency": "USD",
                  "totalBalance": "10000",
                  "availableBalance": "10000",
                  "collateralBalance": "10000",
                  "portfolioVarMargin": "500",
                  "riskRatio": "20.0000",
                  "timestamp": "1611665624601"
              } ]
    }
    
    {
      "event": "accountinfo",
      "timestamp": 1611665626191
      "accountId": "<Your Account ID>",
      "data": [ {
                  "accountId": "<Your Account ID>",
                  "tradeType": "LINEAR",
                  "marginCurrency": "USD",
                  "totalBalance": "10000",
                  "availableBalance": "10000",
                  "collateralBalance": "10000",
                  "portfolioVarMargin": "500",
                  "riskRatio": "20.0000",
                  "timestamp": "1611665624601"
              } ]
    }
    

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

    Response Parameters

    Parameters Type Description
    event STRING accountinfo
    timestamp INTEGER 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
    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
    
    # REST API method
    method = '/v2/balances'
    
    # Not required for /v2/balances
    body = urlencode({})
    
    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())
    

    Response

    {
      "event": "balances",
      "timestamp": 1611665626191,
      "accountId": "<Your Account ID>",
      "tradeType": "LINEAR",
      "data": [ {   
                  "instrumentId": "BTC",
                  "total": "4468.823",              
                  "available": "4468.823",        
                  "reserved": "0",
                  "quantityLastUpdated": "1593627415234"
                },
                ...
                {
                  "instrumentId": "FLEX",
                  "total": "1585.890",              
                  "available": "325.890",         
                  "reserved": "1260",
                  "quantityLastUpdated": "1593627415123"
                }
              ]
    }
    
    {
      "event": "balances",
      "timestamp": 1611665626191,
      "accountId": "<Your Account ID>",
      "tradeType": "LINEAR",
      "data": [ {   
                  "instrumentId": "BTC",
                  "total": "4468.823",              
                  "available": "4468.823",        
                  "reserved": "0",
                  "quantityLastUpdated": "1593627415234"
                },
                ...
                {
                  "instrumentId": "FLEX",
                  "total": "1585.890",              
                  "available": "325.890",         
                  "reserved": "1260",
                  "quantityLastUpdated": "1593627415123"
                }
              ]
    }
    

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

    Response Parameters

    Parameters Type Description
    event STRING balances
    timestamp INTEGER 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
    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
    
    # REST API method, for example FLEX balances
    method = '/v2/balances/FLEX'
    
    # Not required for /v2/balances/{instrumentId}
    body = urlencode({})
    
    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())
    

    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": 1593627415293,
      "accountId": "<Your Account ID>",
      "tradeType": "LINEAR",
      "data": [ {   
                  "instrumentId": "FLEX",
                  "total": "4468.823",              
                  "available": "4468.823",        
                  "reserved": "0",
                  "quantityLastUpdated": "1593627415001"
                } ]
    }
    

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

    Response Parameters

    Parameters 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
    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
    
    # REST API method
    method = '/v2/positions'
    
    # Not required for /v2/positions
    body = urlencode({})
    
    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())
    

    Response

    {
      "event": "positions",
      "timestamp": 1593627415000,
      "accountId":"<Your Account ID>",
      "data": [ {
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "quantity": "0.542000000",
                  "lastUpdated": "1617099855966",
                  "contractValCurrency": "BTC",
                  "entryPrice": "56934.8258",
                  "positionPnl": "1212.0065",
                  "estLiquidationPrice": "52454.3592"
                },
                ...
              ]
    }
    
    {
      "event": "positions",
      "timestamp": 1593627415000,
      "accountId":"<Your Account ID>",
      "data": [ {
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "quantity": "0.542000000",
                  "lastUpdated": "1617099855966",
                  "contractValCurrency": "BTC",
                  "entryPrice": "56934.8258",
                  "positionPnl": "1212.0065",
                  "estLiquidationPrice": "52454.3592"
                },
                ...
              ]
    }
    

    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)

    GET /v2/positions/{instrumentId}

    Request

    GET /v2/positions/{instrumentId}
    
    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
    
    # REST API method, for example FLEX-USD-SWAP-LIN position
    method = '/v2/positions/FLEX-USD-SWAP-LIN'
    
    # Not required for /v2/positions/{instrumentId}
    body = urlencode({})
    
    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())
    

    Response

    {
      "event": "positionsById",
      "timestamp": 1593617005438,
      "accountId":"<Your Account ID>",
      "data": [ {
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "quantity": "0.542000000",
                  "lastUpdated": "1617099855966",
                  "contractValCurrency": "BTC",
                  "entryPrice": "56934.8258",
                  "positionPnl": "1216.6135",
                  "estLiquidationPrice": "53171.16"
              } ]
    }
    
    {
      "event": "positionsById",
      "timestamp": 1593617005438,
      "accountId":"<Your Account ID>",
      "data": [ {
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "quantity": "0.542000000",
                  "lastUpdated": "1617099855966",
                  "contractValCurrency": "BTC",
                  "entryPrice": "56934.8258",
                  "positionPnl": "1216.6135",
                  "estLiquidationPrice": "53171.16"
              } ]
    }
    

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

    Response Fields 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)

    GET /v2/trades/{marketCode}

    Request

    GET /v2/trades/{marketCode}?limit={limit}&startTime={startTime}&endTime={endTime}
    
    {
      "limit": {limit},
      "startTime": {startTime},
      "endTime": {endTime}
    }
    
    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
    
    # REST API method, for example FLEX-USD spot trades
    method = '/v2/trades/FLEX-USD'
    
    # Optional for /v2/trades/{marketCode}
    body = urlencode({'limit': 10, 'startTime': 1611850042397, 'endTime': 1611850059021})
    
    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())
    

    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": 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"
                },
                ...
              ]
    }
    

    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
    limit LONG NO Default 500, max 1000
    startTime LONG NO Millisecond timestamp
    endTime LONG NO Millisecond timestamp

    Response Parameters

    Parameters 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
    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
    
    # REST API method
    method = '/v2/orders'
    
    # Not required for /v2/orders
    body = urlencode({})
    
    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())
    

    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": "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"
                },
                ...
              ]
    }
    

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

    Response Parameters

    Parameters 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
    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}
    

    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"
                        }
                    }
                ]
            }
            ...
        ]
    }
    

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

    Request Parameters Type Required Description
    marketCode STRING NO
    orderId LONG NO
    clientOrderId LONG NO
    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
    orderId STRING Order ID which generated by the server
    clientOrderId STRING Client order ID which given by the user
    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 Remainning 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 Fees with instrument ID
    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
    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
    
    # REST API method
    method = '/v2/cancel/orders'
    
    # Not required for /v2/orders
    body = urlencode({})
    
    if body:
        path = method + '?' + body
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'DELETE', 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.delete(rest_url + path, headers=header)
    print(resp.json())
    

    Response

    {
      "event": "orders",
      "timestamp": 1594412077100,
      "accountId": "<AccountID>",
      "data": {
        "msg": "All open orders for the account have been queued for cancellation"
      }
    }
    
    {
      "event": "orders",
      "timestamp": 1594412077100,
      "accountId": "<AccountID>",
      "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
    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
    
    # REST API method, for example FLEX-USD spot market
    method = '/v2/cancel/orders/FLEX-USD' 
    
    # Not required for /v2/orders/{marketCode}
    body = urlencode({})
    
    if body:
        path = method + '?' + body
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'DELETE', 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.delete(rest_url + path, headers=header)
    print(resp.json())
    

    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": 1594412077100,
      "accountId": "<AccountID>",
      "data": {
                "marketCode": "FLEX-USD",
                "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.

    Response Parameters

    Parameters 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
    
    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
    
    # REST API method
    method = '/v2.1/delivery/orders' 
    
    # Not required for GET /v2.1/delivery/orders
    body = urlencode({})
    
    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())
    

    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": "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
                },
              ]
    }
    

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

    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 null
    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.1/delivery/orders

    Request

    POST /v2.1/delivery/orders?instrumentId={instrumentId}&qtyDeliver={qtyDeliver}
    
    {
      "instrumentId": {instrumentId},
      "qtyDeliver": {qtyDeliver}
    }
    
    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
    
    # REST API method
    method = '/v2.1/delivery/orders' 
    
    # Required for POST /v2.1/delivery/orders
    body = urlencode({"instrumentId": "BTC-USD-SWAP-LIN", "qtyDeliver": "1"})
    
    if body:
        path = method + '?' + body
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'POST', 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.post(rest_url + path, headers=header)
    print(resp.json())
    

    Response

    {
      "event": "delivery",
      "timestamp": "1599204123484",
      "accountId": "164",
      "data": [ {
                  "deliverOrderId": "586985384617312258",
                  "accountId": "164",
                  "clientOrderId": null,
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "deliverPrice": "10000.000000000",
                  "deliverPosition": "1.000",
                  "deliverType": "NEXT_CYCLE",
                  "instrumentIdDeliver": "BTC",
                  "deliverQty": "1.000",
                  "remainingQty": "1.000",
                  "remainingPosition": "1.000",
                  "transferAsset": "USD",
                  "transferQty": "1",
                  "auctionTime": "1599204122693",
                  "created": "1599204122693",
                  "lastUpdated": "1599204122693",
                  "status": "PENDING"
              } ]
    }
    
    {
      "event": "delivery",
      "timestamp": "1599204123484",
      "accountId": "164",
      "data": [ {
                  "deliverOrderId": "586985384617312258",
                  "accountId": "164",
                  "clientOrderId": null,
                  "instrumentId": "BTC-USD-SWAP-LIN",
                  "deliverPrice": "10000.000000000",
                  "deliverPosition": "1.000",
                  "deliverType": "NEXT_CYCLE",
                  "instrumentIdDeliver": "BTC",
                  "deliverQty": "1.000",
                  "remainingQty": "1.000",
                  "remainingPosition": "1.000",
                  "transferAsset": "USD",
                  "transferQty": "1",
                  "auctionTime": "1599204122693",
                  "created": "1599204122693",
                  "lastUpdated": "1599204122693",
                  "status": "PENDING"
              } ]
    }
    

    Submits a request for physical delivery for a specified perpetual swap instrument and quantity.

    Request Parameters

    Parameters Type Required Description
    instrumentId STRING YES Perpetual swap instrument intended for delivery
    qtyDeliver STRING YES Quantity intended for delivery

    Response Parameters

    Parameters Type Description
    event STRING delivery
    timestamp STRING Millisecond timestamp of the repsonse
    accountId STRING Account ID
    data LIST of dictionary
    deliverOrderId STRING Order id
    accountId STRING Account ID
    clientOrderId Null Type null
    instrumentId STRING Perpetual swap market code
    deliverPrice STRING Mark price at delivery
    deliverPosition STRING Delivered position size
    deliverType STRING ‘NEXT_CYCLE’: Queueing for the upcoming auction
    instrumentIdDeliver STRING Asset being received: long position = coin, short position = USD
    deliverQty STRING Quantity of the received asset
    remainingQty STRING Remaining quantity
    remainingPosition STRING Remaining position
    transferAsset STRING Asset being sent
    transferQty STRING Quantity being sent
    auctionTime STRING Millisecond timestamp of the next auction
    created STRING Millisecond timestamp
    lastUpdated STRING Millisecond timestamp
    status STRING Delivery status

    DELETE /v2.1/delivery/orders/{deliveryOrderId}

    Request

    DELETE /v2.1/delivery/orders/{deliveryOrderId}
    
    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
    
    # REST API method
    method = '/v2.1/delivery/orders/{deliveryOrderId}' 
    
    # Not required for DELETE /v2.1/delivery/orders/{deliveryOrderId}
    body = urlencode({})
    
    if body:
        path = method + '?' + body
    else:
        path = method
    
    msg_string = '{}\n{}\n{}\n{}\n{}\n{}'.format(ts, nonce, 'DELETE', 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.delete(rest_url + path, headers=header)
    print(resp.json())
    

    Success response

    {
      "event": "delivery",
      "timestamp": "1599204310297",
      "accountId": "164",
      "data": [
                "Cancel of user order was successful"
              ]
    }
    
    {
      "event": "delivery",
      "timestamp": "1599204310297",
      "accountId": "164",
      "data": [
                "Cancel of user order was successful"
              ]
    }
    

    Failure response

    {
      "event": "delivery",
      "timestamp": "1599204310297",
      "accountId": "164",
      "data": [
                "Cancel exception please try again"
              ]
    }
    
    {
      "event": "delivery",
      "timestamp": "1599204310297",
      "accountId": "164",
      "data": [
                "Cancel exception please try again"
              ]
    }
    

    Cancels a pending delivery.

    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"
            }
        ]
    }
    

    RESPONSE

    {
        "accountId": "13670827", 
        "event": "placeOrder", 
        "timestamp": "1615430915625", 
        "data": [
            {
                "success": "false", 
                "timestamp": "1615430915596", 
                "code": "710002", 
                "message": "FAILED sanity bound check as price (50007.0) <  lower bound (54767.0)", 
                "clientOrderId": "1612249737724", 
                "orderId": "0", 
                "price": "50007.0", 
                "quantity": "0.001", 
                "side": "SELL", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "timeInForce": "GTC", 
                "orderType": "LIMIT"
            }, 
            {
                "success": "true", 
                "timestamp": "1615430915602", 
                "clientOrderId": "1612249737724", 
                "orderId": "0", 
                "price": "54900.0", 
                "quantity": "0.002", 
                "side": "BUY", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "timeInForce": "GTC", 
                "orderType": "LIMIT"
            }, 
            {
                "success": "true", 
                "timestamp": "1615430915625", 
                "clientOrderId": "1612249737723", 
                "orderId": "0", 
                "price": "54901.0", 
                "quantity": "0.003", 
                "side": "SELL", 
                "marketCode": "BTC-USD-SWAP-LIN", 
                "timeInForce": "GTC", 
                "orderType": "LIMIT"
            }
        ]
    }
    

    Place orders.

    Request Parameters Type Required Description
    recvWindow LONG NO
    timestamp STRING NO
    responseType STRING YES FULL or ACK
    orders LIST YES
    clientOrderId STRING YES
    marketCode STRING YES
    side STRING YES
    quantity STRING YES
    timeInForce STRING NO Default GTC
    orderType STRING YES
    price STRING NO
    stopPrice STRING NO
    limitPrice STRING NO
    Response Parameters Type Description
    accountId STRING
    event STRING
    timestamp STRING
    data LIST
    success STRING Whether an order has been successfully placed
    timestamp STRING
    code STRING Error code
    message STRING Error message
    clientOrderId STRING
    orderId STRING
    price STRING
    quantity STRING
    side STRING SELL or BUY
    marketCode STRING
    timeInForce STRING
    orderType STRING

    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 STRING NO
    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
    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 STRING Either one of orderId or clientOrderId is required
    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
    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 STRING NO Millisecond timestamp, e.g. 1620977300, default 0
    endTime STRING NO Millisecond timestamp, e.g 1620977300, default time now
    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 STRING NO Millisecond timestamp, e.g. 1620977300, default 0
    endTime STRING NO Millisecond timestamp, e.g 1620977300, default time now
    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

    POST /v2/borrow

    Borrow.

    Request

    POST /v2/borrow
    
    {
        "borrowAsset": "USD",
        "collateralAsset": "BTC",
        "collateralAmount": "0.01"
    }
    

    SUCCESSFUL RESPONSE

    {
        "event": "borrow",
        "timestamp": "1626433827430",
        "accountId": "3123",
        "data": {
            "borrowAsset": "USD",
            "borrowedAmount": "296.21588287",
            "collateralAsset": "BTC",
            "collateralizedAmount": "0.01",
            "nonCollateralizedAmount": "0",
            "rateType": "FLOATING_RATE",
            "status": "COMPLETED",
            "borrowedAt": "1626433827616"
        }
    }
    
    Request Parameters Type Required Description
    borrowAsset STRING YES Borrow asset, can only be USD for now
    collateralAsset STRING YES Collateral asset
    collateralAmount STRING YES Collateral amount of the collateral asset
    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

    POST /v2/repay

    Repay.

    Request

    POST /v2/repay
    
    {
        "repayAsset": "USD",
        "regainAsset": "BTC",
        "regainAmount": "0.001"
    }
    

    SUCCESSFUL RESPONSE

    {
        "event": "repay",
        "timestamp": "1626433876060",
        "accountId": "3123",
        "data": {
            "repayAsset": "USD",
            "repaidAmount": "31.33109616",
            "regainAsset": "BTC",
            "regainedAmount": "0.001",
            "nonRegainedAmount": "0",
            "status": "COMPLETED",
            "repaidAt": "1626433876398"
        }
    }
    
    Request Parameters Type Required Description
    repayAsset STRING YES Repay asset, can only be USD for now
    regainAsset STRING YES Regain asset
    regainAmount STRING YES Regain amount of the regain asset
    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
    repaidAt STRING The time of repaid at

    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 STRING NO Millisecond timestamp, e.g. 1620977300, default 0
    endTime STRING NO Millisecond timestamp, e.g 1620977300, default time now
    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 STRING NO Millisecond timestamp, e.g. 1620977300, default 0
    endTime STRING NO Millisecond timestamp, e.g 1620977300, default time now
    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/borrowingSummary

    Get borrowing summary.

    Request

    GET v2/borrowingSummary
    

    SUCCESSFUL RESPONSE

    {
        "event": "borrowingSummary",
        "timestamp": "1626433981644",
        "accountId": "3123",
        "data": [
            {
                "borrowAsset": "USD",
                "borrowedAmount": "109031.8252978",
                "collateralAsset": "BTC",
                "collateralizedAmount": "3.65800000",
                "rateType": "FLOATING_RATE",
                "status": "To be repaid"
            },
            ...
        ]
    }
    
    Response Fields Type Description
    accountId STRING Account ID
    borrowAsset STRING Borrow asset, can only be USD for now
    borrowedAmount STRING Total borrowed amount of the borrow asset
    collateralAsset STRING Collateral asset
    collateralizedAmount STRING Total collateralized amount of the collateral asset
    rateType STRING FLOATING_RATE or FIXED_RATE
    status STRING To be repaid

    POST /v2/borrow/close

    Close borrow.

    Request

    POST /v2/borrow/close
    
    {
        "marketCode": "BTC-USD-SWAP-LIN",
        "price": "29633.5",
        "quantity": "1"
    }
    

    SUCCESSFUL RESPONSE

    {
        "event": "closeBorrow",
        "timestamp": "1626434069478",
        "accountId": "3123",
        "data": {
            "success": "true",
            "timestamp": "1626434069461",
            "clientOrderId": "1626434069478",
            "orderId": "1000018496331",
            "price": "29633.5",
            "quantity": "1.0",
            "side": "SELL",
            "status": "CANCELED_BY_FOK",
            "marketCode": "BTC-USD-SWAP-LIN",
            "timeInForce": "FOK",
            "notice": "OrderClosed",
            "orderType": "MARKET",
            "isTriggered": "false"
        }
    }
    
    Request Parameters Type Required Description
    marketCode STRING YES Borrow asset, can only be USD for now
    price STRING NO The price to close the borrow, default is the market price
    collateralAmount STRING NO The quantity to close the borrow, default is full position
    Response Fields Type Description
    accountId STRING Account ID
    clientOrderId STRING Client order ID which given by the user
    orderId STRING Order ID which generated by the server
    price STRING Price submitted
    quantity STRING Quantity submitted
    side STRING Side of the order, BUY or SELL
    status STRING Status of the order
    marketCode STRING Market code
    timeInForce STRING Time in force
    notice STRING OrderClosed or OrderMatched or OrderOpend
    orderType STRING Type of the order, LIMIT or STOP
    isTriggered STRING true(for stop order) or false

    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 YES 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
    endTime LONG NO
    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/delivery/public/funding

    Request

    GET /v2/delivery/public/funding?limit=20
    

    RESPONSE

    [
        {
            "timestamp": "2020-12-08 04:00:00",
            "instrumentId": "COMP-USD-SWAP-LIN",
            "fundingRate": "0.000000000"
        },
        {
            "timestamp": "2020-12-08 04:00:00",
            "instrumentId": "CRV-USD-SWAP-LIN",
            "fundingRate": "0.000000000"
        },
        ...
    ]
    

    Get funding rate

    Request Parameters Type Description
    column STRING limit size of results, e.g. 3
    instrumentId STRING e.g. UNI-USD-SWAP-LIN
    startTime STRING e.g. 2020-12-08 20:00:00
    limit STRING default 100, max 500
    Response Parameters Type Description
    timestamp STRING Timestamp of this response
    instrumentId STRING "BTC-USD-SWAP-LIN"
    fundingRate STRING e.g. 0.000060000

    GET /v2.1/deliver-auction/{instrumentId}

    Request

    GET /v2/deliver-auction
    
    GET /v2.1/deliver-auction/<instrumentId>
    

    RESPONSE

    {
        "event": "deliverAuction",
        "timestamp": "1596620815090",
        "data": [
            {
                "instrumentId": "BTC-USD-SWAP-LIN",
                "auctionTime": "1596620805000",
                "netDeliver": "-5.100000000",
                "estFundingRate": "0.0001"
            },
          ...
        ]
    }
    

    Requires authentication. Get entire delivery history.

    Response Parameters Type Description
    timestamp STRING UNIX Timestamp of the response
    instrumentId STRING Market code
    auctionTime STRING UNIX timestamp of the next auction
    netDeliver STRING Delivery imbalance (negative = more shorts than longs and vice versa)
    estFundingRate STRING Estimated funding rate a positive rate means longs pay shorts

    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/funding-rates/{marketCode}

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

    Request

    GET /v2/funding-rates/{marketCode}?startTime={startTime}&endTime={endTime}&limit={limit}
    
    Request Parameters Type Required Description
    marketCode STRING YES e.g. BTC-USD-REPO-LIN , available values: BTC-USD-REPO-LIN, ETH-USD-REPO-LIN
    limit LONG NO default is 50
    startTime LONG NO millisecond timestamp, e.g. 1579450778000, default is 7 days ago from time now
    endTime LONG NO millisecond timestamp, e.g. 1613978625000, default is time now

    SUCCESSFUL RESPONSE

    {
        "event": "fundingRates",
        "timestamp": "1611645666834",
        "data": [
            {
                "fundingRate": "0.00008",
                "index": "2.78222423",
                "markPrice": "33937.2848",
                "marketCode": "BTC-USD-REPO-LIN",
                "timestamp": "1606461774458"
            },
            ...
        ]
    }
    
    Response Fields Type Description
    timestamp STRING Timestamp of this response
    fundingRate STRING
    index STRING
    markPrice STRING
    marketCode STRING
    timestamp(in the data list) STRING

    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": "168.515000000",
                "available": "0.000000000",
                "reserved": "168.515",
                "quantityLastUpdated": "1621582933075"
            },
            {
                "instrumentId": "DOT",
                "total": "1923.80",
                "available": "0.00",
                "reserved": "1923.8",
                "quantityLastUpdated": "1621569724731"
            },
            {
                "instrumentId": "REVV",
                "total": "336.0",
                "available": "0.0",
                "reserved": "336.0",
                "quantityLastUpdated": "1621569725061"
            },
            ...
        ]
    }
    
    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
    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
    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 max 100, default 100, max 500
    startTime LONG NO e.g. 1579450778000, default 0
    endTime LONG NO e.g. 1613978625000, default time now
    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 max 100, default 100, max 500
    startTime LONG NO e.g. 1579450778000, default 0
    endTime LONG NO e.g. 1613978625000, default time now
    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 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.

    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

    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}

    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?asset={asset}&limit={limit}&startTime={startTime}&endTime={endTime}
    

    Successful response format

    {
        "success": true,
        "data": [
            {
                "asset": "flexUSD",
                "network": "SLP",
                "address": "simpleledger:qzlg6uvceehgzgtz6phmvy8gtdqyt6vf35fxqwx3p7",
                "quantity": "1000.0",
                "fee": "0.000000000",
                "id": "651573911056351237",
                "status": "COMPLETED",
                "txId": "38c09755bff75d33304a3cb6ee839fcb78bbb38b6e3e16586f20852cdec4886d",
                "requestedAt": "1617940800000",
                "completedAt": "16003243243242"
            }
        ]
    }
    
    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. 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
    asset STRING
    network STRING
    address STRING
    memo STRING Memo (tag) if applicable
    quantity STRING
    fee STRING
    id STRING
    status STRING COMPLETED, PROCESSING, PENDING, 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": {
            "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 main 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
    tfaType STRING NO GOOGLE, or AUTHY_SECRET, or YUBIKEY
    code STRING NO 2fa code if required by the account
    Response Field Type Description
    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

    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 Parameters 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

    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
    quantity STRING YES Quantity to mint
    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
    quantity STRING YES Quantity to redeem
    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

    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

    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
    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": [
            {
                "name": "FLEX",
                "canDeposit": true,
                "canWithdraw": true,
                "isCollateral": true,
                "loanToValue": "0.900000000",
                "minDeposit": "0.0001",
                "minWithdrawal": "0.0001",
                "network": [
                    "SLP",
                    "ERC20",
                    "SEP20"
                ]
            }
        ]
    }
    
    Request Parameter Type Required Description
    asset STRING NO Name of the asset
    Response Field Type Description
    name STRING Name of the asset
    canDeposit BOOL
    canWithdraw BOOL
    isCollateral BOOL
    loanToValue STRING Loan to value of the asset
    minDeposit STRING Minimum deposit amount
    minWithdrawal STRING Minimum withdrawal amount
    network LIST Available networks for deposits and withdrawals