NAV Navbar

Introduction

Apifiny Connect™ ’s institutional-grade REST and Websocket API gives Traders, OTC desks, Brokers, and Market Makers faster access to trade and easier reallocation of assets among a multitude of global exchanges using one consistent set of APIs.

There is also a FIX API for order management.

Change log

08/03/21

07/02/21

06/24/21

06/01/21

04/28/21

04/23/21

General

Professional traders can easily execute their strategies across all *crypto-to-crypto and other crypto fiat pairs. With one deposit and KYC process, traders can reallocate assets among exchanges and start trading.

An account must be obtained by clients and will be given an accountID, API_Key_ID and API_Secret_Key, API keys can be generated under menu "API Management" after signed in. https://clients.apifiny.com/admin/management.

avatar

Private requests must use JWT to generate a Signature and add the signature as a parameter to each request header.

Quick Start

We offer co-location services for the clients, support 6 exchanges, support for more exchanges will be coming soon. For the venues we offer co-lo, the base URL will be different each, make sure to use the right base URL accordingly. For the rest venues, the base URL is Other Venues URL

A “venue” is an exchange or a destination. “GBBO” is accessed by setting venue to GBBO: "venue": "GBBO". Get available "venue" by method. In the examples we use "VENUE1" or "VENUE2" instead of venue name,make sure to use the correct ones.

Base URLs

BINANCE

REST: https://apibn.apifiny.com/ac/v2

FIX: fixapibn.apifiny.com:1443

Server Location: AWS ap-northeast-1c

BINANCEUS

REST: https://apibnu.apifiny.com/ac/v2

FIX: fixapibnu.apifiny.com:1443

Server Location: AWS us-east-1a

COINBASEPRO

REST: https://apicb.apifiny.com/ac/v2

FIX: fixapicb.apifiny.com:1443

Server Location: AWS us-east-1a

HUOBI

REST: https://apihb.apifiny.com/ac/v2

FIX: fixapihb.apifiny.com:1443

Server Location: AWS ap-northeast-1c

KUCOIN

REST: https://apikc.apifiny.com/ac/v2

FIX: fixapikc.apifiny.com:1443

Server Location: AWS ap-northeast-1c

OKEX

REST: https://apiok.apifiny.com/ac/v2

FIX: fixapiok.apifiny.com:1443

Server Location: Ali Hong Kong, Ali B

Other Venues

The base URL is: https://api.apifiny.com/ac/v2/VENUE1

FIX: fix.api.apifiny.com:1443

Server Location: AWS us-east-1a

Authentication

Signature

REST API & Websocket Stream Signature:

// js
signature = JWT(payload={
    "accountId": "accountID",
    "secretKeyId": "API_Key_ID",
    "digest": hash256(RequestBody), // Websocket Stream remove digest
    "exp": 1535526941
}, key='API_Secret_Key', algorithm='HS256'

# python3
import hashlib
import jwt
import json

digest = hashlib.sha256(json.dumps(RequestBody).encode()).hexdigest()
signature = jwt.encode({
    'accountId': "accountID",
    'secretKeyId': "API_Key_ID",
    'digest': digest, # Websocket Stream remove digest
    'exp': 1535526941,
}, "API_Secret_Key", algorithm='HS256')

// Java
String digest = DigestUtils.sha256Hex(RequestBody);
public String jwtTest() {
        String accessKey = "API_Key_ID";
        String secretKey = "API_Secret_Key";
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("accountId", "accountID");
    claims.put("secretKeyId", accessKey);
    claims.put("digest", digest); // Websocket Stream remove digest
    claims.put("exp", exp);
        String signature = Jwts.builder().setClaims(claims)
                .signWith(Keys.hmacShaKeyFor(secretKey.getBytes()), SignatureAlgorithm.HS256).compact();
        return signature;
    }

Please use JWT to generate Signature for each private request. Please refer to jwt.io on how to use JWT.

Every private request, please use JWT and secretKey to generate Signature and add the signature as a parameter to each request header.

Query Account Info: /account/queryAccountInfo curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "$Base URL/account/queryAccountInfo?accountId=STA-00000001&venue=VENUE1"

Use parameters:

accountId=STA-00000001&venue=VENUE1

to generate Signature

Create a Withdraw Request: /asset/withdraw curl -X POST -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY*************lY1TyJ9.RrWnyheQs" "$Base URL/asset/withdraw" \ -d '{"accountId": "STA-00000001","venue":"VENUE1","coin": "BTC","amount": 10.0021,"address": "3Nxwena**********fp8v","ticket": "b2152827079***793d4bbe436f"}'

Use parameters:

{"accountId": "STA-00000001","venue":"VENUE1","coin": "BTC","amount": 10.0021,"address": "3Nxwena*************fp8v","ticket": "b2152827079***793d4bbe436f"}

to generate Signature

Payload in Signature includes the following content:

Parameter Description
accountId Account ID
secretKeyId API Access Key
key API Secret Key
digest hash value of the request body using sha256 hash(Websocket Stream remove digest)
exp expiration time of signature

Make Request

RESR API Market Data Request Example:

curl -X GET "https://api.apifiny.com/md/orderbook/v1/BTCUSD/VENUE1"

RESR API Others Request Example:

# Query Account Info: /account/queryAccountInfo
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/account/queryAccountInfo?accountId=STA-00000001&venue=VENUE1"

Use HTTP POST to make a request:

POST $Base URL/XXXX

The request end point is embedded in the signature.

Standard response

The structure of the response:

{
  "result": null,
  "error": {
    "code": 0x02002B,
    "message": "Account doesn't exist, please verify account ID"
  }
}

After making an API request, the server will send back a response in JSON format. The response includes:

Parameter Description
result when the request is successful, this key will include the result of the request. When the request is not successful, its value is null.
error when the request is not successful, the key will give the error message. Its value is null when the request is successful.
code Error code. Please refer to the error code explanation section.
message Error message.

Rate Limits

There are throttling limits, referred to as rate limits by Account ID. These are set at 20 requests per second and will result in an error message, “rate limit is exceeded”, if breached.

REST API

Base Information

There is a further set of API’s to discover basic information about venues and assets that Apifiny Connect™ supports.

Query List Venues

# URL: /utils/listVenueInfo
curl -X GET "https://api.apifiny.com/ac/v2/VENUE1/utils/listVenueInfo"

Response:

{
    "result": [{
            "exchange ": "VENUE1",
            "status": "enabled"
        },
        {
            "exchange ": "VENUE2",
            "status": "enabled"
        },
        // ... ...
        {
            "exchange ": "VENUE24",
            "status ": "disabled"
        }
    ],
    "error": null
}

HTTP Request:

GET https://api.apifiny.com/ac/v2/VENUE1/utils/listVenueInfo

Response:

Parameter Description
exchange name of the exchange
status exchange status, enabled or disabled

Query List Currencies

# URL: /utils/listCurrency
curl -X GET "https://api.apifiny.com/ac/v2/VENUE1/utils/listCurrency"

Response:

{
    "result": [{
            "currency": "BTC",
            "currencyPrecision": 9,
            "status": "NOT_DEPOSIT_WITHDRAW",
            "withdrawMaxAmount": 1000000,
            "withdrawMinAmount": 0.004,
            "withdrawMinFee": 0.0005,
            "nextStatus": null,
            "nextStatusAt": null,
            "coin": "BTC"
        },
        {
            "currency": "ETH",
            "currencyPrecision": 8,
            "status": "NOT_DEPOSIT_WITHDRAW",
            "withdrawMaxAmount": 10000,
            "withdrawMinAmount": 2,
            "withdrawMinFee": 0.001,
            "nextStatus": null,
            "nextStatusAt": null,
            "coin": "ETH"
        }
    ],
    "error": null
}

List known currencies.

HTTP Request:

GET https://api.apifiny.com/ac/v2/VENUE1/utils/listCurrency

Response:

Parameter Description
currency currency
currencyPrecision currency precision
status current status, DEPOSIT_WITHDRAW or NOT_DEPOSIT_WITHDRAW or DEPOSIT_NOT_WITHDRAW or NOT_DEPOSIT_NOT_WITHDRAW
withdrawMaxAmount max withdraw amount
withdrawMinAmount min withdraw amount
withdrawMinFee min withdraw fee
nextStatus next status
nextStatusAt next status time

currency status:

status explanation
DEPOSIT_WITHDRAW deposit and withdrawal are both allowed
NOT_DEPOSIT_WITHDRAW deposit is not allowed, withdrawal is allowed
DEPOSIT_NOT_WITHDRAW deposit is allowed, but withdrawal is not allowed
NOT_DEPOSIT_NOT_WITHDRAW deposit and withdrawal are both not allowed

Query List Symbols

# URL: /utils/listSymbolInfo
curl -X GET "https://api.apifiny.com/ac/v2/VENUE1/utils/listSymbolInfo"

Response:

{
    "result": [{
            "symbol": "EOSETH",
            "baseAsset": "EOS",
            "baseAssetPrecision": 8,
            "quoteAsset": "ETH",
            "quotePrecision": 8,
            "minPrice": 0.01,
            "maxPrice": 99999,
            "minQuantity": 0.01,
            "maxQuantity": 99999,
            "tickSize": 0.01,
            "stepSize": 0.0001,
            "minNotional": 1,
            "maxNotional": 1000,
            "status": "enabled"
        },
        {
            "symbol": "BCHUSDT",
            "baseAsset": "BCH",
            "baseAssetPrecision": 8,
            "quoteAsset": "USDT",
            "quotePrecision": 8,
            "minPrice": 0.01,
            "maxPrice": 99999,
            "minQuantity": 0.01,
            "maxQuantity": 99999,
            "tickSize": 0.01,
            "stepSize": 0.0001,
            "minNotional": 1,
            "maxNotional": 1000,
            "status": "enabled"
        }
    ],
    "error": null
}

Get a list of available trading pairs supported in this venue.

HTTP Request:

GET https://api.apifiny.com/ac/v2/VENUE1/utils/listSymbolInfo

Response:

Parameter Description
symbol symbol
baseAsset base asset
baseAssetPrecision baseAsset precision
quoteAsset quote asset,the right side of the symbol
quotePrecision quote precision
minPrice min price for the symbol
maxPrice max price for the symbol
minQuantity min quantity for the symbol
maxQuantity max quantity for the symbol
tickSize min price increment for the symbol
stepSize min quantity increment for the symbol
minNotional minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity
maxNotional maximum notional value allowed for an order on a symbol. An order's notional value is the price * quantity
status enabled or disabled

Query Current Timestamp of Server

# URL: /utils/currentTimeMillis
curl -X GET "https://api.apifiny.com/ac/v2/VENUE1/utils/currentTimeMillis"

Response:

{
    "result": 1552112542263,
    "error": null
}

Get the API server time.

HTTP Request:

GET https://api.apifiny.com/ac/v2/VENUE1/utils/currentTimeMillis

Response:

The server timestamp

Market Data

Rate Limit: We throttle public endpoints by Access Key 1 request per second.

Order book - REST API

The RESTFul interface endpoint is:

Request URL:

GET https://api.apifiny.com/md/orderbook/v1/{SYMBOL}/{VENUE}

curl -X GET "https://api.apifiny.com/md/orderbook/v1/BTCUSD/VENUE1"

The {SYMBOL} is the trading pairs. For example, ETHBTC.

The {VENUE} is the exchanges. For example, VENUE1.

Response:

{
    "symbol": "BTCUSD",
    "updatedAt": 1621840045855,
    "asks": [
        [36540.0700, 0.00466900]
        // [price, size]
        // ……
    ],
    "bids": [
        [36538.5700, 0.00000900],
        [36521.7900, 0.27496400]
    ]
}
# python3
res = requests.get("https://api.apifiny.com/md/orderbook/v1/{SYMBOL}/{VENUE}")
print(res.json())

Trades - REST API

Executed transactions data, also known as matched orders data or active data.

Request URL:

GET https://api.apifiny.com/md/trade/v1/{SYMBOL}/{VENUE1}

curl -X GET "https://api.apifiny.com/md/trade/v1/BTCUSD/VENUE1"

The {SYMBOL} is the trading pairs. For example, ETHBTC.

The {VENUE} is the exchanges. For example, VENUE1.

Response:

[{
    "symbol": "BTCUSD",
    "provider": "Venue1",
    "price": 36523.4600,
    "qty": 0.05913000,
    "side": "BUY",
    "tradeTime": 1621840043786,
    "exchangeID": "14150317",
    "updateTime": 1621840043788
}]

Response:

Parameter Description
symbol symbol
price filled price
qty filled size
side maker order side of this fill, BUY or SELL
tradeTime filled time
updateTime updated time

The trade side indicates the maker order side. The maker order is the order that was open on the order book. buy side indicates a down-tick because the maker was a buy order and their order was removed. Conversely, sell side indicates an up-tick.

OHLCV - REST API

OHLCV (Open, High, Low, Close, Volume) timeseries data. Each data point of this timeseries represents several indicators calculated from transactions activity inside a time range (period).

Request URL:

GET https://api.apifiny.com/md/kline/v1/{VENUE}/{BASE}/{QUOTE}/{PERIOD}

curl -X GET "https://api.apifiny.com/md/kline/v1/{VENUE}/{BASE}/{QUOTE}/{PERIOD}?startTime=1616923800000&endTime=1616937900000"
Parameter Description
VENUE Venue name
BASE Base asset
QUOTE Quote Asset
PERIOD The period of each candle, 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M
startTime The start time period
endTime The end time period

If startTime and endTime are not sent, the most recent klines are returned

Response:

[
    {
        "currencyPair":"BTC/USDT", 
        "period":"1m",
        "open":58053.69,
        "high":58053.69,
        "low":58053.69,
        "close":58053.69,
        "vol":0.027921,
        "count":1,
        "timestamp":1616140260000,
        "exchange":"Venue1"
    },
    {
        "currencyPair":"BTC/USDT",
        "period":"1m",
        "open":57865.28,
        "high":57885.08,
        "low":57865.28,
        "close":57885.08,
        "vol":0.068214,
        "count":2,
        "timestamp":1616140860000,
        "exchange":"Venue1"
    }]

Response:

Parameter Description
currencyPair symbol
period The period of each candle, 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M
open The opening price
high The closing price
low lowest price
close close price
vol Accumulated trading volume, in base asset
count The number of completed trades
timestamp The UNIX timestamp in seconds
exchange Venue name

Support 7 venues currently: BINANCE, BINANCEUS, COINBASEPRO, HUOBI, KUCOIN, OKEX, GATEIO. Others will result in an error message.

Ticker - REST API

24 hr stats for the trading pairs. volume is in base currency units. open, high, low are in quote currency units.

Request URL:

GET https://api.apifiny.com/md/ticker/v1/{SYMBOL}/{VENUE1}/

curl -X GET -H "https://api.apifiny.com/md/ticker/v1/BTCUSD/VENUE1"

The {SYMBOL} is the trading pairs. For example, BTCUSDT.

The {VENUE} is the exchanges. For example, VENUE1.

Response:

{
    "symbol": "BTCUSD",
    "open": 36720.9300,
    "high": 36815.0300,
    "low": 31120.0000,
    "close": 36501.1200,
    "vol": 5296.13216200,
    "amount": 180425575.4029,
    "count": 0,
    "provider": "Venue1",
    "tickerTime": 1621840042096,
    "updateAt": 1621840042192
}

Support 7 venues currently: BINANCE, BINANCEUS, COINBASEPRO, HUOBI, KUCOIN, OKEX, GATEIO. Others will result in an error message.

Account

The Account API has a number of calls to enable the user to get information about the account, to deposit and withdraw crypto from the account and interrogate the balances in the account. Only RESTful queries are supported for this set of functions.

Query Account Info

Requires authentication.

# Query Account Info: /account/queryAccountInfo
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/account/queryAccountInfo?accountId=STA-00000001&venue=VENUE1"

Response:

{
    "result": [{
        "accountId": "STA-00000001",
        "accountStatus": "OPENED",
        "createdAt": 1537857271784,
        "updatedAt": 1551956476878,
        "subAccountInfo": [{
            "accountId": "STA-VENUE1_00000001",
            "venue": "VENUE1",
            "accountStatus": "OPENED",
            "createdAt": 1584611383104,
            "updatedAt": 1584611383104
        }]
    }],
    "error": null
}

HTTP Request:

GET $Base URL/account/queryAccountInfo

signature={$signature}

Request:

Parameter Description
accountId account ID
venue venue name

Response:

Parameter Description
accountId account ID
venue venue name
accountStatus account status
createdAt creation time
updatedAt update time

Account Status:

Account Status Explanation
OPENED normal
RESTRICTED restricted. Cannot submit order or cancel order, but can query order.
SUSPENDED suspended, no operations are allowed

Query Account Asset

Requires authentication.

# Query Account Asset: /asset/listBalance
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/asset/listBalance?accountId=STA-00000001&venue=VENUE1"

Response:

{
    "result": [{
            "accountId": "STA-VENUE1_00000001",
            "venue": "VENUE1",
            "currency": "BTC",
            "amount": 51.95,
            "available": 51.95,
            "frozen": 0
        },
        {
            "accountId": "STA-VENUE1_00000001",
            "venue": "VENUE1",
            "currency": "USDT",
            "amount": 101.95,
            "available": 51.95,
            "frozen": 50
        }
    ],
    "error": null
}

HTTP Request:

GET $Base URL/asset/listBalance

signature={$signature}

Request:

Parameter Description
accountId account ID
venue venue name

Response:

Parameter Description
accountId account ID
venue venue name
currency symbol of asset
coin currency code in system, different from currency name if multiple chains are supported
amount amount
available available quantity
frozen frozen value
updatedAt update time

Get Deposit Address

Requires authentication.

# Get Deposit Address: /asset/queryAddress
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/asset/queryAddress?accountId=STA-00000001&venue=VENUE1&coin=USDT.ETH"

Response:

{
    "result": [{
        "venue": "VENUE1",
        "currency": "USDT",
        "coin": "USDT.ETH",
        "address": "3Nxwena****************fp8v",
        "expiredAt": 1584606409507
    }],
    "error": null
}
{
    "result": [{
        "venue": "VENUE1",
        "currency": "EOS",
        "coin": "EOS",
        "address": "acc******bnw",
        "memo": "10230001",
        "expiredAt": 1584606409507
    }],
    "error": null
}

HTTP Request:

GET $Base URL/asset/queryAddress

signature={$signature}

Request:

Parameter Description
accountId Account ID
venue venue name
coin currency code in system, different from currency name if multiple chains are supported

Response:

Parameter Description
venue venue name
currency currency name
address deposits address
memo memo information, some currencies are necessary, e.g. EOS
expiredAt expiration time

Create a Withdraw Ticket

Requires authentication.

# Create a Withdraw Ticket: /asset/createWithdrawTicket
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/asset/createWithdrawTicket?accountId=STA-00000001&venue=VENUE1"

Response:

{
    "result": [{
        "ticket": "b215282*************bbe436f",
        "expiredAt": 1584633883235
    }],
    "error": null
}

You need to get a ticket before you can withdraw. Also if your ID verification has not been approved, you will get rejection error message.

HTTP Request:

GET $Base URL/asset/createWithdrawTicket

signature={$signature}

Request:

Parameter Description
accountId account ID
venue venue name

Response:

Parameter Description
ticket withdraw ticket
expiredAt expired time

Create a Withdraw Request

Requires authentication.

# Create a Withdraw Request: /asset/withdraw
curl -X POST -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/asset/withdraw" \
-d '{"accountId": "STA-00000001","venue":"VENUE1","coin": "BTC","amount": 10.0021,"address": "3Nxwena****************fp8v","ticket": "b2152827079******793d4bbe436f"}'

Request:

{
  "accountId": "STA-0000001",
  "venue":"VENUE1",
  "coin": "BTC",
  "amount": 10.0021,
  "memo": "",
  "address": "3Nxwena****************fp8v",
  "ticket": "b2152827079******793d4bbe436f"
}

Response:

{
    "result": [{
        "accountId": "STA-VENUE1_00000001",
        "venue": "VENUE1",
        "currency": "BTC",
        "coin": "BTC",
        "amount": 10.0021,
        "fee": 0.0005,
        "fromAddress": null,
        "targetAddress": "3Nxwena****************fp8v",
        "type": "OUTGOING",
        "actionType": "ACCOUNT_CLIENT_WITHDRAW",
        "actionNote": "ACCOUNT_CLIENT_WITHDRAW",
        "logId": "STA-VENUE1_00000001.a93cdec7f3544ad89e2dd2a1515a7cba",
        "txId": "6af5256d5d3dd**********************************e1c31de",
        "status": "SUBMITTED",
        "logCreatedAt": 1584613315735,
        "logUpdatedAt": 1584613839359
    }],
    "error": null
}

HTTP Request:

POST $Base URL/asset/withdraw

signature={$signature}

Request:

Parameter Description
accountId Account ID
venue venue name
coin currency code in system, different from currency name if multiple chains are supported
amount the amount to withdraw
address a crypto address of the recipient
memo memo(Optional), It is usually necessary for EOS
ticket withdraw ticket

Response:

Parameter Description
accountId Account ID
venue venue name
currency currency name
coin internal coin name
amount the amount to withdraw
fee fee of withdrawal
fromAddress from address
targetAddress a crypto address of the recipient
type OUTGOING, INCOMING
actionType source of request
logId internal transfer ID
txId transaction ID
status SUBMITTED, COMPLETED, CANCELLED
logCreatedAt creation time
logUpdatedAt updated time

Transfer Between Venues

Requires authentication.

# Transfer Between Venues: /asset/transferToVenue
curl -X POST -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/asset/transferToVenue" \
-d '{"accountId": "STA-00000001","venue":"VENUE1","currency": "BTC","amount": 10.0,"targetVenue": "VENUE2"}'

Request:

{
  "accountId": "STA-0000001",
  "venue":"VENUE1",
  "currency": "BTC",
  "amount": 10.0,
  "targetVenue": "VENUE2"
}

Response:

{
    "result": [{
        "accountId": "STA-0000001",
        "venue": "FROM_VENUE",
        "currency": "BTC",
        "amount": 10.0,
        "fee": 0.0005,
        "targetVenue": "TO_VENUE",
        "logId": "STA-VENUE1_00000001.a93cdec7f3544ad89e2dd2a1515a7cba",
        "status": "SUBMITTED",
        "logCreatedAt": 1584613315735,
        "logUpdatedAt": 1584613839359
    }],
    "error": null
}

HTTP Request:

POST $Base URL/asset/transferToVenue

signature={$signature}

Request:

Parameter Description
accountId Account ID
venue venue name
currency currency name
amount the amount to withdraw
targetVenue name of target venue

Response:

Parameter Description
accountId Account ID
venue venue name
currency currency name
amount the amount to withdraw
fee fee of withdrawal
targetVenue target venue name
logId internal transfer ID
status SUBMITTED, COMPLETED, CANCELLED
logCreatedAt creation time
logUpdatedAt updated time

Query Account History

Requires authentication.

# Query Account History: /asset/queryAssetActivityList
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/asset/queryAssetActivityList" \
-d '{"accountId": "STA-00000001","startTimeDate": "1584355090628","endTimeDate": "1584614290628","limit": "10","page": "1"}'

Account activity either increases or decreases your account balance.

Request:

{
  "accountId": "STA-00000001",
  "startTimeDate": "1584355090628",
  "endTimeDate": "1584614290628",
  "limit": "10",  
  "page": "1"
}

Response:

{
    "result": [{
        "records": [{
            "accountId": "STA-VENUE1_00000001",
            "currency": "BTC",
            "status": "SUBMITTED",
            "type": "OUTGOING",
            "amount": 0.01,
            "fee": 0.003,
            "targetAddress": "",
            "coin": "BTC",
            "logId": "STA-VENUE1_00000001.8de7fc99b5064f288f8fb9608951fb69",
            "logCreatedAt": "1584355090628",
            "logUpdatedAt": "1584614290628",
            "actionType": "ACCOUNT_CLIENT_TRANSFER_OUTGOING",
            "actionNote": "ACCOUNT_CLIENT_TRANSFER_OUTGOING",
            "fromAccountId": "STA-VENUE1_00000001",
            "toAccountId": "STA-VENUE2_00000001"
        }, {
            "accountId": "STA-VENUE1_00000001",
            "currency": "BTC",
            "status": "SUBMITTED",
            "type": "OUTGOING",
            "amount": 0.01,
            "fee": 0.003,
            "targetAddress": "",
            "coin": "BTC",
            "logId": "STA-VENUE1_00000001.fde92d5bf570468e9e6b4a023d8080ce",
            "logCreatedAt": "1584355090628",
            "logUpdatedAt": "1584614290628",
            "actionType": "ACCOUNT_CLIENT_TRANSFER_OUTGOING",
            "actionNote": "ACCOUNT_CLIENT_TRANSFER_OUTGOING",
            "fromAccountId": "STA-VENUE1_00000001",
            "toAccountId": "STA-VENUE2_00000001"
        }],
        "total": 5,
        "size": 2,
        "current": 1,
        "orders": [],
        "hitCount": false,
        "searchCount": true,
        "pages": 3
    }],
    "error": null
}

HTTP Request:

POST $Base URL/asset/queryAssetActivityList

signature={$signature}

Request:

Parameter Description
accountId Account ID
startTimeDate start time
endTimeDate end time
limit records per page
page page number

Response:

Parameter Description
accountId Account ID
currency currency name
status status of this account activity, SUBMITTED, COMPLETED, CANCELLED
type IMCOMING for deposits, OUTGOING for withdrawals
amount amount of currency changed
fee fee occurs during this activity
fromAddress from address
targetAddress a crypto address of the recipient
txId transaction ID onchain
coin internal coin name
logId internal ID
logCreatedAt create time
logUpdatedAt update time
actionType source of request
actionNote note of request
fromAccountId the iniate sub-account transfer from
toAccountId the target sub-account transfer to
count total number of records
limit records per page
page page number
pages page count

Trading

Clients will typically be using the Websocket API to subscribe to the market data and RESTful API to submit orders. Clients can use the websocket API to subscribe to the order updates or use RESTful API to get order updates. A typical trade flow would be as follows:

Step 1: Subscribe to market data. The websocket endpoint used to subscribe and unsubscribe for market data is wss://api.apifiny.com/md/ws/v1 . Request and reply are in JSON format.

The RESTful endpoint is GET https://api.apifiny.com/md/orderbook/v1/{SYMBOL}/{VENUE}, where {SYMBOL} denotes the currency pair of interest and the {VENUE} denotes the exchange.

Step 2: Create order and send order using the RESTful API.

The method for creating an order is order.insertOrderLite, which enables an order to be created and submitted. Note that the orderId is optional, if requested, it should be composed of: account number+random number+13 digit timestamp+3 digit random number. Up to 64 digits.

for example:xxxxxxxxxxxxxx1614254993065992

Step 3: Subscribe to the order updates using websocket. A number of methods enable the querying of order(s) state.

The URL endpoints are /order/queryOrderInfo to find the state of a single submitted order; /order/listOpenOrder to get a list of all open orders; and /order/listCompletedOrder to get a list of all complete orders.

Step 4: Cancel Order (as needed). When an order that was submitted and is open needs to be canceled, The URL endpoint is /order/cancelOrder. Any order that has a status of PENDING_SUBMIT or has already been canceled, cannot be canceled. In addition, cancelledUpdatedAt must be null.

Further technical information and examples for all Trading API methods are as follows:

Create New Order

Requires authentication.

# Create New Order: order/newOrder
curl -X POST -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/newOrder" \
-d '{"accountId": "STA-00000001","venue":"VENUE1","orderId": "000000011584603011942221","orderInfo": {"symbol": "BTCUSD","orderType": "LIMIT","timeInForce": 1,"orderSide": "BUY","limitPrice": "100","quantity": "1.12"}
}'

Request:

{
  "accountId": "STA-00000001",
  "venue":"VENUE1",
  "orderId": "000000011584603011942221",
  "orderInfo": {
    "symbol": "BTCUSD",
    "orderType": "LIMIT",
    "timeInForce": 1,
    "orderSide": "BUY",
    "limitPrice": "100",
    "quantity": "1.12"
  }
}

Response:

{
    "result": [{
        "accountId": "STA-VENUE1_00000001",
        "venue": "VENUE1",
        "orderId": "000000011584603011942221",
        "symbol": "BTCUSD",
        "orderType": "LIMIT",
        "orderSide": "BUY",
        "limitPrice": 100,
        "quantity": 1.12,
        "filledAveragePrice": 0,
        "filledCumulativeQuantity": 0,
        "timeInForce": 1,
        "openQuantity": 1.12,
        "orderStatus": "PENDING_SUBMIT",
        "createdAt": 1584603012164,
        "updatedAt": 1584603012164
    }],
    "error": null
}

Make a new order request:

HTTP Request:

POST $Base URL/order/newOrder

signature={$signature}

Request:

Parameter Description
accountId account ID
venue venue name
orderId order ID(Optional)
symbol symbol
orderType order type, LIMIT or MARKET(only some venues support)
timeInForce specifies how long the order remains in effect, 1=GTC, 3=IOC=, 7=PostOnly
orderSide order side, BUY or SELL
limitPrice limit price
quantity quantity
total Amount of quote asset to spend, required when orderSide is BUY, orderType = MARKET

orderId if requested, should be composed of: **account number + random number + 13 digit timestamp+3 digit random number*. Up to 64 digits.

for example:xxxxxxxxxxxxxx1614254993065992

Response:

Parameter Description
accountId sub account ID
venue venue name
orderId order ID
symbol symbol
orderType order type, LIMIT or MARKET
orderSide order side, BUY or SELL
limitPrice limit price, not available for market order
quantity quantity
filledAveragePrice average fill price
filledCumulativeQuantity accumulated fill quantity
openQuantity open quantity to be filled
orderStatus order status
createdAt order creation timestamp
updatedAt order update timestamp
cancelledUpdatedAt if it is cancelled, cancellation timestamp
filledUpdatedAt last filled timestamp

Order Type:

Order Type Description
LIMIT Limit Order
MARKET Market Order*

*Only 6 exchanges support market order now, they are Binance, Binance(US), Coinbase(pro), Huobi, Kucoin, Okex, others will be coming soon.

Time In Force:

Time In Force Description
1 GTC (Good Till Canceled)
2 GTD (Good Till Date), temporarily not supported
3 IOC (Immediate Or Cancel)
7 Post Only (The order should only make liquidity)

Order Side:

Order Side Description
BUY buy order
SELL sell order

Order Status:

Order Status Explanation
PENDING_SUBMIT order has been sent but not confirmed
SUBMITTED order has been accepted and stay active
PART_FILLED final status, partially filled order
FILLED final status, completely filled order
CANCELLED final status, order has been cancelled
REJECTED final status, order has been rejected

Cancel an Order

Requires authentication.

# Cancel an Order: /order/cancelOrder
curl -X POST -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/cancelOrder" \
-d '{"accountId": "STA-00000001","venue":"VENUE1","orderId": "000000011584603011942221"}'

Request:

{
  "accountId": "STA-00000001",
  "venue":"VENUE1",
  "orderId": "000000011584603011942221"
}

Response:

{
  //Same as new order response
}

Request Cancel an Order via the order ID.

HTTP Request:

POST $Base URL/order/cancelOrder

signature={$signature}

Request:

Parameter Description
accountId Account ID
venue Venue Name
orderId Order ID

Response:

Same as new order response.

Cancel Reject:

If the order could not be canceled (still pending submit, already filled or previously canceled, etc), then an error response will indicate the reason in the message field.

Cancel All

Requires authentication.

# Cancel All: /order/cancelAccountVenueAllOrder
curl -X POST -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/cancelAccountVenueAllOrder" \
-d '{"accountId": "STA-00000001","venue":"VENUE1","symbol": "BTCUSD"}'

Request:

{
  "accountId": "STA-00000001",
  "venue":"VENUE1",
  "symbol": "BTCUSD"
}

Response:

{
    "result": [
        "519e f355d9884e1f8e3d3ffc7caf13b5",
        "519e f355d9884e1f8e3d3ffc7caf13b3",
        "519e f355d9884e1f8e3d3ffc7caf14b5",
        "519e f355d9884e1f8e3d3ffc7caf13b6"
    ],
    "error": null
}

With best effort, Cancel all open orders. The response is a list of ids of the canceled orders.

HTTP Request:

POST $Base URL/order/cancelAccountVenueAllOrder

signature={$signature}

Request:

Parameter Description
accountId Account ID
venue venue name
symbol [Optional] Only cancel orders open for the specified trading pair

Response:

Parameter Description
orderId Order ID, unique identifier of an order.

Get an Order

Requires authentication.

# Get an Order: /order/queryOrderInfo
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/queryOrderInfo?accountId=STA-00000001&venue=VENUE1&orderId=000000011584603011942221"

Response:

{
  //Same as new order response
}

HTTP Request:

GET $Base URL/order/queryOrderInfo

signature={$signature}

Request:

Parameter Description
accountId account ID
venue venue name
orderId order ID

Response:

Same as new order response.

Query Multiple Orders by IDs

Requires authentication.

# Query Multiple Orders by IDs: /order/listMultipleOrderInfo
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/listMultipleOrderInfo?accountId=STA-00000001&orderIdList=000000121574697605570321,000000121574697754664817

Response:

[
  {
     //Same as new order response
  },
  {
     //Same as new order response
  }
]

HTTP Request:

GET $Base URL/order/listMultipleOrderInfo

signature={$signature}

Request:

Parameter Description
accountId account ID
orderIdList the total number of order ID cannot exceed 500

Response:

Same as new order response.

Query All Open Orders

Requires authentication.

# Query All Open Orders: /order/listOpenOrder
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/listOpenOrder?accountId=STA-00000001&venue=VENUE1"

Response:

{
    "result": [{
            "accountId": "STA-VENUE1_00000001",
            "venue": "VENUE1",
            "orderId": "000000011584603011942221",
            "symbol": "BTCUSD",
            "orderType": "LIMIT",
            "orderSide": "BUY",
            "limitPrice": 100,
            "quantity": 1.12,
            "filledAveragePrice": 0,
            "filledCumulativeQuantity": 0,
            "timeInForce": 1,
            "openQuantity": 1.12,
            "orderStatus": "PENDING_SUBMIT",
            "createdAt": 1584603012164,
            "updatedAt": 1584603012164
        },
        {
            "accountId": "STA-VENUE1_00000001",
            "venue": "VENUE1",
            "orderId": "000000011584603011942227",
            "symbol": "BTCUSD",
            "orderType": "LIMIT",
            "orderSide": "SELL",
            "limitPrice": 110,
            "quantity": 1.12,
            "filledAveragePrice": 0,
            "filledCumulativeQuantity": 0,
            "timeInForce": 1,
            "openQuantity": 1.12,
            "orderStatus": "SUBMITTED",
            "createdAt": 1584603012164,
            "updatedAt": 1584603012164
        }
    ],
    "error": null
}

HTTP Request:

GET /order/listOpenOrder

signature={$signature}

Request:

Parameter Description
accountId Account ID
venue Venue Name

Response:

Same as new order response.

Query All Completed Orders

Requires authentication.

# Query All Completed Orders: /order/listCompletedOrder
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/listCompletedOrder?accountId=STA-00000001&venue=VENUE1&startTime=1537857271784&endTime=1537857271784&limit=100&orderStatus="

Response:

[
  {
     //Same as new order response
  }
  {
     //Same as new order response
  }
]

Query all settled orders, including: filled, partially filled, canceled and rejected orders.

HTTP Request:

GET $Base URL/order/listCompletedOrder

signature={$signature}

Request:

Parameter Description
accountId account ID
venue venue name, use GBBO (optional)
startTime [Optional] Start Time
endTime [Optional] End Time
limit total number of orders, default is 500, Max 1000
orderStatus order status: PART_FILLED, FILLED, CANCELLED. (optional)

Response:

Same as new order response.

Query List Fills

Requires authentication.

# Query List Fills: /order/listFilledOrder
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/listFilledOrder?accountId=STA-00000001&venue=VENUE1"

Response:

{
    "result": [{
        "accountId": "STA-VENUE1_00000001",
        "venue": "VENUE1",
        "orderId": "000000011584603011942221",
        "symbol": "BTCUSD",
        "orderType": "LIMIT",
        "timeInForce": 3,
        "orderSide": "BUY",
        "limitPrice": 9000,
        "quantity": 0.01,
        "filledAveragePrice": 0,
        "filledCumulativeQuantity": 0,
        "openQuantity": 0,
        "orderStatus": "FILLED",
        "createdAt": 1584603012164,
        "updatedAt": 1584603012164,
        "cancelledUpdatedAt": null,
        "filledUpdatedAt": null,
        "lastCommission": 0.0450,
        "lastCommissionCurrency": "USD",
        "lastFilledQuantity": 0.01,
        "lastFilledPrice": 9000,
        "isTaker": true
    }],
    "error": null
}

HTTP Request:

GET $Base URL/order/listFilledOrder

signature={$signature}

Request:

Parameter Description
accountId [Required] Account ID
venue [Required] Venue name
symbol [Optional] Limit the list of fills to this symbol
orderId [Optional] Limit the list of fills to this order ID
limit Default 500; max 1000
startTime [Optional] Start Time
endTime [Optional] End Time

Data time range

The system allows you to retrieve data up to three months (start from the last day by default). If you only specified the start time, the system will automatically calculate the end time (end time = start time + 3 months). On the contrary, if you only specified the end time, the system will calculate the start time (start time= end time - 3 months) the same way.

Response:

Same as new order response.

Parameter Description
lastCommission trading fees happen in this fill
lastCommissionCurrency the currency of the trading fee
isTaker this field indicates if the fill was the result of a liquidity provider or liquidity taker. TRUE indicates Taker and FALSE indicates Maker

Query Current Fee Rate

Requires authentication.

# Query Current Fee Rate: /order/getCommissionRate
curl -X GET -H "Content-Type: application/json" -H "signature: eyJhbI1NiJ9.eyJhY**************lY1TyJ9.RrWnyheQs" "https://api.apifiny.com/ac/v2/VENUE1/order/getCommissionRate?accountId=STA-00000001&venue=VENUE1&symbol=BTCUSDT"

Response:

{
    "result": [{
        "accountId": "STA-VENUE1_00000001",
        "tradingVolume": 121.1001,
        "takeFee": 0.003,
        "makeFee": 0,
        "specialRate": 0
    }],
    "error": null
}

HTTP Request:

GET $Base URL/order/getCommissionRate

signature={$signature}

Request:

Parameter Description
accountId account ID
venue VENUE1
symbol symbol

Response:

Parameter Description
accountId account ID
tradingVolume cumulative trading volume within 30 days
takeFee taker fee
makeFee maker fee
specialRate special discount of trading fee

Websocket API

Market Data

Heartbeat and Connection

After connected to Websocket server, the server will send heartbeat periodically (currently at 30s interval). The heartbeat message will have an integer in it, e.g.

{"ping": 1492420473027}

When client receives this heartbeat message, it should respond with a matching "pong" message which has the same integer in it, e.g.

{"pong": 1492420473027} 

Rate Limit: We throttle public endpoints by Access Key 1 request per second.

Request (subscription):

{
  "channel":"ChannelName",
  "symbol":"BTCUSD",
  "venues":["VENUE1","VENUE2"],
  "action":"sub"
}

Request (unsubscribing):

{
  "channel":"ChannelName",
  "symbol":"BTCUSD",
  "venues":["VENUE1","VENUE2"],
  "action":"unsub"
}
# python3
def get_md_signature(accessKey, secretKey):
    claims = {'accessKey': accessKey}
    signature = jwt.encode(claims, secretKey, algorithm='HS256')
    return str(signature, encoding='utf-8')

headers = {'signature': get_md_signature('API_Key_ID', 'API_Secret_Key')}
msg = {"channel": "trade", "symbol": 'symbol', "venues": 'VENUES', "action": "sub"}
def sub_md(message):
    from websocket import create_connection
    import ssl
    sslopt = {"cert_reqs": ssl.CERT_NONE}
    con = create_connection('wss://api.apifiny.com/md/ws/v1', sslopt=sslopt, header=headers)
    con.send(json.dumps(message))
    while True:
        response = con.recv()
        if 'ping' in response:
            pong = response.replace('ping', 'pong')
            con.send(pong)
        print(response)
sub_md(msg)

The websocket end point is

URL:

wss://api.apifiny.com/md/ws/v1

Parameter Description
channel channel name, orderbook or trade or kline_<period> or ticker
symbol symbol
venues venue name list
action subscription or unsubscribing

The request for subscription/unsubscribe must be in JSON format.

Listed below are all allowed values for channel variables:

Channel Name Description
orderbook The current order book of a specific pair.
trade The most recent trades with their price, volume, and direction.
kline_<period> OHLCV, the Kline/Candlestick Stream push updates to the current klines/candlestick every second.
ticker 24hr rolling window ticker statistics for all symbols that changed in an array.

** For trade, kline_<period> and ticker we support 6 venues currently: BINANCE, BINANCEUS, COINBASEPRO, HUOBI, KUCOIN, OKEX. Others will result in an error message.*

Order Book Payload:

{
    "venues": ["VENUE1"],
    "channel": "orderbook",
    "symbol": "BTCUSDT",
    "orderbook": {
        "symbol": "BTCUSDT",
        "updatedAt": 1621839607399,
        "asks": [
            [36179.76000000, 0.01311800],
            // [price, size]
            // ……
        ],
        "bids": [
            [36165.88000000, 0.01426800],
            [36153.40000000, 0.05641000]
        ]
    }
}
// ....
{
  "venues":["VENUE1"],
    "channel": "orderbook",
    "symbol": "BTCUSDT",
    "orderbook": {
        "symbol": "BTCUSDT",
        "updatedAt": 1621839607399,
        "asks": [
            [36179.76000000, 0.01311800],
            // [price, size]
            // ……
        ],
        "bids": [
            [36165.88000000, 0.01426800],
            [36153.40000000, 0.05641000]
        ]
    }
}

Recent Trades Payload:

{
    "venues": ["VENUE1"],
    "channel": "trade",
    "symbol": "BTCUSDT",
    "trade": {
        "trades": [{
            "symbol": "BTCUSDT",
            "provider": "VENUE1",
            "price": 36271.52000000,
            "qty": 0.00034500,
            "side": "BUY",
            "tradeTime": 1621839791084,
            "exchangeID": "5093303",
            "updateTime": 1621839791086
        }, {
            "symbol": "BTCUSDT",
            "provider": "VENUE1",
            "price": 36289.07000000,
            "qty": 0.00000700,
            "side": "SELL",
            "tradeTime": 1621839787668,
            "exchangeID": "5093301",
            "updateTime": 1621839787671
        }]
    }
}

OHLCV Request (subscription):

{
  "channel":"kline_1m",
  "symbol":"BTC/USD",
  "venues":["VENUE1","VENUE2"],
  "action":"sub"
}

OHLCV Payload:

{
    "venues": ["VENUE1"],
    "channel": "kline_1m",
    "symbol": "BTC/USD",
    "kline_1m": {
        "currencyPair": "BTC/USD",
        "period": "1m",
        "open": 36536.1900,
        "high": 36536.1900,
        "low": 36464.6200,
        "close": 36464.6200,
        "vol": 2.46849600,
        "count": 65,
        "timestamp": 1621841040000,
        "exchange": "VENUE1"
    }
}

Ticker Payload:

{
    "venues": ["VENUE1"],
    "channel": "ticker",
    "symbol": "BTCUSDT",
    "ticker": {
        "symbol": "BTCUSDT",
        "open": 36631.84000000,
        "high": 36785.32000000,
        "low": 31109.00000000,
        "close": 36198.03000000,
        "vol": 2984.41975300,
        "amount": 101489083.47069713,
        "count": 0,
        "provider": "VENUE1",
        "tickerTime": 1621839608737,
        "updateAt": 1621839608835
    }
}

User Data Stream

Requires authentication.

Websocket API will receive a stream of order update or account update. URLs are:

BINANCE

order update url:

wss://apibn.apifiny.com/ac/ws/v2/order

account update url:

wss://apibn.apifiny.com/ac/ws/v2/asset

BINANCEUS

order update url:

wss://apibnu.apifiny.com/ac/ws/v2/order

account update url:

wss://apibnu.apifiny.com/ac/ws/v2/asset

COINBASEPRO

order update url:

wss://apicb.apifiny.com/ac/ws/v2/order

account update url:

wss://apicb.apifiny.com/ac/ws/v2/asset

HUOBI

order update url:

wss://apihb.apifiny.com/ac/ws/v2/order

account update url:

wss://apihb.apifiny.com/ac/ws/v2/asset

KUCOIN

order update url:

wss://apikc.apifiny.com/ac/ws/v2/order

wss://apikc.apifiny.com/ac/ws/v2/asset

OKEX

order update url:

wss://apiok.apifiny.com/ac/ws/v2/order

account update url:

wss://apiok.apifiny.com/ac/ws/v2/asset

Other Venues

order update url:

wss://api.apifiny.com/ac/ws/v2/VENUE1/order

account update url:

wss://api.apifiny.com/ac/ws/v2/VENUE1/asset

# python3
import hashlib
import json
import time
from urllib.parse import urlencode
import jwt

def ws_client():
    millis = int(round(time.time() * 1000)) + 30000
    signature = jwt.encode({
        'accountId': "You accountId",
        'secretKeyId': 'You API_Key_ID',
        'exp': millis,
    }, "You API_Secret_Key", algorithm='HS256')
    headers = {'signature': signature}
    url = "`wss://api.apifiny.com/gx/ws/v2/VENUE1/order"
    //url = "`wss://api.apifiny.com/gx/ws/v2/VENUE1/asset"
    from websocket import create_connection
    import ssl
    sslopt = {"cert_reqs": ssl.CERT_NONE}
    con = create_connection(url, sslopt=sslopt, header=headers)
    while True:
        response = con.recv()
        if 'ping' in response:
            pong = response.replace('ping', 'pong')
            con.send(pong)
        print(response)

ws_client()

Order Update

Order Update Payload:

{
    "logTimestamp": 1552116459536,
    "payload": {
        "accountId": "ST-00000001",
        "venue": "VENUE1",
        "orderId": "000000121574697605570321",
        "symbol": "BTCUSD",
        "orderType": "LIMIT",
        "timeInForce": 1,
        "orderSide": "BUY",
        "limitPrice": 100.0,
        "quantity": 1.12,
        "filledAveragePrice": 100.0,
        "filledCumulativeQuantity": 1.12,
        "openQuantity": 0,
        "orderStatus": "FILLED",
        "createdAt": 1552116459467,
        "updatedAt": 1552116459467,
        "cancelledUpdatedAt": null,
        "filledUpdatedAt": 1552116459467,
        "lastCommission": 0.112,
        "lastCommissionCurrency": "USD",
        "lastFilledQuantity": 1.12,
        "lastFilledPrice": 100.0,
        "lastFilledCreatedAt": 1552116459467,
        "isTaker": true
    }
}

Orders are updated with the order status change event.

Signature method see Authentication.

Path: /order

Parameter Description:

Parameter Description
lastFilledQuantity last filled quantity
lastFilledPrice last filled price
lastFilledCreatedAt last filled time
lastCommission trading fees happen in this fill
lastCommissionCurrency the currency of the trading fee
isTaker this field indicates if the fill was the result of a liquidity provider or liquidity taker. TRUE indicates Taker and FALSE indicates Maker

Account Update

Account Update Payload:

{
  "result" : {
    "logTimestamp" : 1625036845606,
    "payload" : [ {
      "accountId" : "ST-00000001",
      "amount" : 0,
      "available" : 0,
      "currency" : "UNI",
      "frozen" : 0,
      "venue" : "VENUE1"
    }, {
      "accountId" : "ST-00000001",
      "amount" : 0.00512281,
      "available" : 0.00512281,
      "currency" : "BTC",
      "frozen" : 0,
      "venue" : "VENUE1"
    }]
  },
  "error" : null
}

Account update is sent any time an account balance has changed. Update occurs during the following:

Signature method see Authentication.

Path: /asset

Response Description:

Parameter Description
accountId account ID
amount amount of currency changed
available available quantity
currency currency name
frozen frozen value
venue Venue name

FIX API

FIX (Financial Information exchange) is a standard protocol which can be used to enter orders, submit cancel requests, and receive fills. Users of the FIX API will typically have existing software using FIX for order management. Users who are not familiar with FIX should first consider using the REST API.

FIX API can be implemented using QuickFIX with the following language support:

Configuration information are as follows:

Configuration for quickfix

FIX API ENDPOINT URL

For the venues we offer co-location, the FIX API endpoint URL will be different each, make sure to use the right base URL accordingly.

BINANCE

fixapibn.apifiny.com:1443

BINANCEUS

fixapibnu.apifiny.com:1443

COINBASEPRO

fixapicb.apifiny.com:1443

HUOBI

fixapihb.apifiny.com:1443

KUCOIN

fixapikc.apifiny.com:1443

OKEX

fixapiok.apifiny.com:1443

Other Venues

fix.api.apifiny.com:1443

Quickfix Configuration

Quickfix configuration sample codes:

[default]
ConnectionType=initiator
SenderCompID=STA-00000001
TargetCompID=APIFINY
SocketConnectHost=fix.api.apifiny.com
StartTime=00:00:00
EndTime=00:00:00
HeartBtInt=30
ReconnectInterval=5
UseDataDictionary=Y
ResetSeqNumFlag=Y
ResetOnLogon=Y
ResetOnLogout=Y
ResetOnDisconnect=Y

[session]
BeginString=FIX.4.2
SocketConnectPort=1443

Here is an optional Python3 sample codes for login using quickfix:

Logon

 def toAdmin(self, message, sessionID):
        if message.getHeader().getField(35) is "A":
            API_Secret_Key = 'API_Secret_Key'
            signature = get_signature('Fix', 'STA-00000015', 'API_Key_ID','STA-00000015', API_Secret_Key)
            message.setField(fix.RawDataLength(len(signature)))
            message.setField(fix.RawData(signature))
        ...

get_signature is as following:

# python3
def get_signature(method, account_id, API_Key_ID, params, API_Secret_Key):
    now = datetime.datetime.now()
    expect_time = now + datetime.timedelta(seconds=30)
    params_json_string = json.dumps(params) if isinstance(params, dict) else params
    digest = hashlib.sha256(params_json_string.encode()).hexdigest()
    signature = jwt.encode({
        'accountId': account_id,
        'secretKeyId': API_Key_ID,
        'digest': digest,
        'method': method,
        'exp': int(expect_time.timestamp()),
    }, API_Secret_Key)
    return str(signature, encoding='utf-8')

Requires authentication.Add JWT Signature token in toAdmin.

Method: Fix

Digest: hash value of account_id using sha256 hash.

Request:

Tag Name Description
35 MsgType A
95 RawDataLength Length of signature data
96 RawData Signature data

Response:

If successfully message MsgType(35)=A,otherwise MsgType(35)=5 will be returned.

New Order

    msg = quickfix42.NewOrderSingle()
    msg.setField(fix.ClOrdID(order_id)) # generated order id:the last 16 bits are a 13-bit timestamp + three random numbers up to 64 characters.
    msg.setField(fix.Symbol(symbol)) # symbol:BTCUSDT
    msg.setField(fix.HandlInst('1'))
    msg.setField(fix.OrdType(fix.OrdType_LIMIT)) # OrdType:limit
    order.setField(fix.TimeInForce_IMMEDIATE_OR_CANCEL)
    msg.setField(fix.TransactTime())
    msg.setField(fix.Side(side))
    msg.setField(fix.Price(price))
    msg.setField(fix.Account(account_id))
    msg.setField(fix.OrderQty(qty))
    msg.setField(fix.SecurityExchange("VENUE1"))
    msg.setField(fix.Text("new Order"))
    quickfix.Session.sendToTarget(msg, application.sessionID)

Request:

Tag Name Description
11 ClOrdID Only present on order acknowledgements, ExecType=New (150=0)
55 Symbol Symbol of the original order
21 HandlInst Instructions for order handling on Broker trading floor
40 OrdType 1 = Market(only some venues support); 2 = Limit
59 TimeInForce Specifies how long the order remains in effect, 1=GTC, 3=IOC=, 7=PostOnly
60 TransactTime Time the event occurred
54 Side Must be 1 to buy or 2 to sell
44 Price Price of the fill if ExecType indicates a fill, otherwise the order price
1 Account Account id
38 OrderQty OrderQty as accepted
207 SecurityExchange VENUE
58 Text Free format text string

Response:

If the order is accepted, an ExecutionReport (8) will be returned. Otherwise, an ExecutionReport with ExecType=8 (Rejected) will be returned.

Cancel Order

    msg = quickfix42.OrderCancelRequest()
    msg.setField(fix.ClOrdID(order_id))
    msg.setField(fix.Account(account_id))
    msg.setField(fix.SecurityExchange("VENUE1"))
    msg.setField(fix.Text("Cancel Order"))

Request:

Tag Name Description
11 ClOrdID Only present on order acknowledgements, ExecType=New (150=0)
1 Account account id
207 SecurityExchange VENUE
58 Text Free format text string

Response:

If the order is successfully cancelled, an ExecutionReport (8) with ExecType=4 (Canceled) will be returned. Otherwise, an OrderCancelReject (9) will be returned.

Execution Report

Execution Report message Sent by the broker/gateway when an order is accepted, rejected, partially filled, or canceled.

Tag Name Description
11 ClOrdID Only present on order acknowledgements, ExecType=New (150=0)
37 OrderID OrderID from the ExecutionReport with ExecType=New (150=0)
17 ExecId Unique identifier of execution message
55 Symbol Symbol of the original order
54 Side Must be 1 to buy or 2 to sell
32 LastShares Amount filled (if ExecType=1). Also called LastQty as of FIX 4.3
44 Price Price of the fill if ExecType indicates a fill, otherwise the order price
38 OrderQty OrderQty as accepted
60 TransactTime Time the event occurred
150 ExecType 1 for Partially fill and 2 for fill
39 OrdStatus Order status as of the current message

ExecType VALUES

ExecType Description
0 NEW, ACK
1 PARTIAL_FILL
2 FILL
4 CANCELED
8 REJECTED

Query order status

    msg = quickfix42.OrderStatusRequest()
    msg.setField(fix.ClOrdID(order_id))
    msg.setField(fix.Account(account_id))
    msg.setField(fix.SecurityExchange("VENUE1"))

Request:

Tag Name Description
11 ClOrdID Only present on order acknowledgements, ExecType=New (150=0)
1 Account account id
207 SecurityExchange VENUE

Response:

The response to an Order Status Request is an ExecutionReport (8) .

Status/Error Codes

There are two categories of error codes, one set generated by HTTP, typically by a server for a client request, and the other category is a set of Apifiny Connect application status/error codes.

HTTP Error code

HTTP status codes are divided into 5 ranges as follows:

Some of the most common HTTP error codes include:

HTTP 403 - too many errors and IP is blocked

HTTP 502 - service is not available

Apifiny Connect Status/Error Codes

Apifiny Connect status/error codes are returned as a hexadecimal number. The number on the farthest right delineates client side errors (designated by the hexadecimal number A) from server side errors (designated by the hexadecimal number B).

Client side errors should be corrected at the client and the request resubmitted. Server side errors will have a max retry count as well as a resubmit interval of 50 ms. Persistent resubmissions will result in suspension of the submitting IP.

Error Code Explanation Hexadecimal Error Code
65548 common error 0x01000C
65562 general request error, please check if the parameters in request are correct. 0x01001A
65579 general server side error, retry or contact customer service. 0x01002B
65595 server busy please wait 0x01003B
65658 IP is not in the white list 0x01007A
131098 Account Session Stopped 0x02001A
131099 create account error 0x02001B
131114 Request too often, please try later 0x02002A
131115 Account doesn't exist, please verify account ID. 0x02002B
131130 Sorry, the venue does not match the request url, please check the base url. 0x02003A
131162 Account status doesn't satisfy request, please verify account status. 0x02005A
131178 SQL execution error, duplicate primary key 0x02006A
196634 token error 0x03001A
196650 session error 0x03002A
196666 session extension validation Error 0x03003A
196682 sso token error 0x03004A
196698 session type error 0x03005A
262170 withdraw address not exist 0x04001A
262186 the number of withdraw addresses reaches limit 0x04002A
262202 Util_Unknown_Symbol 0x04003A
262218 Util_Unknown_Currency 0x04004A
262250 Util_Unknown_CoinType 0x04006A
262266 Util_Unknown_Coin 0x04007A
262299 Util_Create_Withdraw_Address_Error 0x04009B
262427 A connection issue encountered, please try again 0x04011B
262443 You have reach your daily withdrawal limit, please try next day 0x04012B
5243242 Order doesn't exist, please change order ID, Execute Fail 0x050016A
327706 Order ID doesn't exist, please recreate order id. 0x05001A
327722 Order_OriginalOrderIdDuplicate 0x05002A
327723 New order failure,retry or contact customer service. 0x05002B
327738 Order_OpenOrderNotExist 0x05003B
327738 Order doesn't exist, please change order ID. 0x05003A
327741 This exchange is currently under maitenance or not supported yet. 0x05003D
327754 Order_CancelPendingSubmitWait 0x05004A
327755 cancel order error, need to contact customer service. 0x05004B
327786 timeout for new order or other request, please wait and retry. 0x05005A
327786 orderSide parameter error 0x05006B
327786 too many open orders, cannot create new order, need to delete some orders and retry. 0x05006A
327802 order id repeat 0x05007B
327802 cannot cancel order under current order status, need confirm order status and retry or abandon request. 0x05007A
327818 Order create failed, incorrect timestamp format 0x05008A
327818 timeout for cancel order operation, need wait and retry. 0x05008A
327834 Order create failed, timestamp error 0x05009A
327836 Order_Detail_Not_Exist 0x05009C
327946 Order_Status_Not_Pending_Submit_Cancel 0x05010A
327948 Order_Log_Not_Exist order 0x05010C
327962 the number of new order within 24 hours exceed limit, please contact customer service. 0x05011A
327978 order id rule error 0x05012A
328010 the order is being cancelled, please verify order status. 0x05014A
328026 order cannot be canceled when in Pending_Submit status,please wait for status changed to submitted to cancel order.( if order status is still pending submit after 10 minutes, please contact customer service. ) 0x05015A
328042 Order_GBBO_Error 0x05016A
328058 SOM_Request_Error 0x05017A
328074 Your account has reached the trade amount limitation 0x05018A
393242 Asset_AvailableNotEnough. 0x06001A
393242 withdraw ticket error, please check or create a withdraw ticket first. 0x06001B
393258 Not enough asset available. Please verify if there is enough asset in account. 0x06002A
393274 asset free frozen not enough 0x06003A
393290 asset reduce frozen not enough 0x06004A
393306 Order_Cancel_TimeOut_Error 0x06005A
393322 Asset_Activity_Submitted_Not_Exist 0x06006A
393338 Asset_Query_Deposit_Address_Error 0x06007A
393354 Assets in this currency are insufficient or non-existent 0x06008A
393355 Asset_Activity_Completed_TxId_Error 0x06008B
393372 Asset_Log_Not_Exist 0x06009C
393482 Order_Create_TimeOut_Error 0x06010A
393514 Asset_Activity_Id_Exist 0x06012A
393530 Conversion between two currencies is not supported 0x06013A
2097162 Signature Error 0x20000A
2097163 Permission denied. Invalid API key or permissions for action. 0x20000B
2097178 No matching market 0x20001A

Download Demo

Click Python Sample to download demo Codes.

Contact Us