Api бинанс на русском руководство

Вступление

Биржа binance, как и многие другие биржи, предоставляет API — программный интерфейс для автоматизации торговли. В этой статье рассмотрены методы и приведены примеры кода для работы с ними.
Официальное описание API (на английском) — здесь. Бот для Binance — здесь. Как получить API ключи — тут.

Вводная информация

В отличии от многих других бирж, Binance лимитирует не только количество запросов к API, но и «вес» запросов. Причем, это не какие-то фиксированные единицы, но целый комплекс (как они заявляют, англ). Например, если вы постоянно запрашиваете свечи но не торгуете, то ваш вес накапливается и вас могут забанить. И вообще они суровые — если вы постоянно перебиваете лучшую цену на минимальную ставку, или создаете/отменяете ордера но не покупаете и продаете и т.п. то вас настигнут санкции. Так что будьте аккуратны при тестировании ботов. Впрочем, пока я тестировал, ничего плохого не случилось, хотя я порой и жестил.

Если биржа захочет вам намекнуть, что пора бы снизить пыл, она вернет 429 ответ сервера. Если вы будете игнорировать этот ответ и ломиться в закрытую дверь, то вас забанят по IP на срок от 2 минут до 3 дней.

Подключение к API биржи идет через https://api.binance.com, для авторизованных запросов нужно отправлять ключ в заголовке X-MBX-APIKEY, и подписывать тело запроса SHA256.

Что бы вы не заморачивались с этим, я написал код, который позволяет все указанные запросы выполнять. Для его работы нужно установить Python версии 3.6+ с официального сайта, потом в командной строке выполнить pip install requests. Создайте папку (для удобства), создайте новый файл binance_api.py, и вставьте туда этот код:

import ssl
import time
import json
import urllib
import hmac, hashlib
import requests

from urllib.parse import urlparse, urlencode
from urllib.request import Request, urlopen

class Binance():

    methods = {
            # public methods
            'ping':             {'url':'api/v1/ping', 'method': 'GET', 'private': False},
            'time':             {'url':'api/v1/time', 'method': 'GET', 'private': False},
            'exchangeInfo':     {'url':'api/v1/exchangeInfo', 'method': 'GET', 'private': False},
            'depth':            {'url': 'api/v1/depth', 'method': 'GET', 'private': False},
            'trades':           {'url': 'api/v1/trades', 'method': 'GET', 'private': False},
            'historicalTrades': {'url': 'api/v1/historicalTrades', 'method': 'GET', 'private': False},
            'aggTrades':        {'url': 'api/v1/aggTrades', 'method': 'GET', 'private': False},
            'klines':           {'url': 'api/v1/klines', 'method': 'GET', 'private': False},
            'ticker24hr':       {'url': 'api/v1/ticker/24hr', 'method': 'GET', 'private': False},
            'tickerPrice':      {'url': 'api/v3/ticker/price', 'method': 'GET', 'private': False},
            'tickerBookTicker': {'url': 'api/v3/ticker/bookTicker', 'method': 'GET', 'private': False},
            # private methods
            'createOrder':      {'url': 'api/v3/order', 'method': 'POST', 'private': True},
            'testOrder':        {'url': 'api/v3/order/test', 'method': 'POST', 'private': True},
            'orderInfo':        {'url': 'api/v3/order', 'method': 'GET', 'private': True},
            'cancelOrder':      {'url': 'api/v3/order', 'method': 'DELETE', 'private': True},
            'openOrders':       {'url': 'api/v3/openOrders', 'method': 'GET', 'private': True},
            'allOrders':        {'url': 'api/v3/allOrders', 'method': 'GET', 'private': True},
            'account':          {'url': 'api/v3/account', 'method': 'GET', 'private': True},
            'myTrades':         {'url': 'api/v3/myTrades', 'method': 'GET', 'private': True},
            # wapi
            'depositAddress':   {'url': 'wapi/v3/depositAddress.html', 'method':'GET', 'private':True},
            'withdraw':   {'url': 'wapi/v3/withdraw.html', 'method':'POST', 'private':True},
            'depositHistory': {'url': 'wapi/v3/depositHistory.html', 'method':'GET', 'private':True},
            'withdrawHistory': {'url': 'wapi/v3/withdrawHistory.html', 'method':'GET', 'private':True},
            'assetDetail': {'url': 'wapi/v3/assetDetail.html', 'method':'GET', 'private':True},
            'tradeFee': {'url': 'wapi/v3/tradeFee.html', 'method':'GET', 'private':True},
            'accountStatus': {'url': 'wapi/v3/accountStatus.html', 'method':'GET', 'private':True},
            'systemStatus': {'url': 'wapi/v3/systemStatus.html', 'method':'GET', 'private':True},
            'assetDust': {'url': 'sapi/v1/asset/dust', 'method':'POST', 'private':True},
            'dustLog': {'url': 'wapi/v3/userAssetDribbletLog.html', 'method':'GET', 'private':True},
            'assetAssetDividend': {'url': 'sapi/v1/asset/assetDividend', 'method':'GET', 'private':True},
            #sapi
            'marginTransfer': {'url': 'sapi/v1/margin/transfer', 'method': 'POST', 'private':True},
            'marginLoan': {'url': 'sapi/v1/margin/loan', 'method': 'POST', 'private': True},
            'marginLoanGet': {'url': 'sapi/v1/margin/loan', 'method': 'GET', 'private': True},
            'marginRepay': {'url': 'sapi/v1/margin/repay', 'method': 'POST', 'private': True},
            'marginRepayGet': {'url': 'sapi/v1/margin/repay', 'method': 'GET', 'private': True},
            'marginCreateOrder': {'url': 'sapi/v1/margin/order', 'method': 'POST', 'private':True},
            'marginCancelOrder': {'url': 'sapi/v1/margin/order', 'method': 'DELETE', 'private':True},
            'marginOrderInfo': {'url': 'sapi/v1/margin/order', 'method': 'GET', 'private':True},
            'marginAccount': {'url': 'sapi/v1/margin/account', 'method': 'POST', 'private':True},
            'marginOpenOrders': {'url': 'sapi/v1/margin/openOrders', 'method': 'GET', 'private':True},
            'marginAllOrders': {'url': 'sapi/v1/margin/allOrders', 'method': 'GET', 'private':True},
            'marginAsset': {'url': 'sapi/v1/margin/asset', 'method': 'POST', 'private':True},
            'marginPair': {'url': 'sapi/v1/margin/pair', 'method': 'POST', 'private':True},
            'marginPriceIndex': {'url': 'sapi/v1/margin/priceIndex', 'method': 'POST', 'private':True},
            'marginMyTrades': {'url': 'sapi/v1/margin/myTrades', 'method': 'GET', 'private':True},
            'marginMaxBorrowable': {'url': 'sapi/v1/margin/maxBorrowable', 'method': 'GET', 'private':True},
            'marginmaxTransferable': {'url': 'sapi/v1/margin/maxTransferable', 'method': 'GET', 'private':True},
            #futures
            'futuresExchangeInfo': {'url': 'fapi/v1/exchangeInfo', 'method': 'GET', 'private': False, 'futures': True},
            'futuresKlines': {'url': 'fapi/v1/klines', 'method': 'GET', 'private': False, 'futures': True},
            'futuresCreateOrder':      {'url': 'fapi/v1/order', 'method': 'POST', 'private': True, 'futures': True},
            'futuresAccount':      {'url': 'fapi/v1/account', 'method': 'POST', 'private': True, 'futures': True},
            'futuresBalance':      {'url': 'fapi/v1/balance', 'method': 'GET', 'private': True, 'futures': True},
            'futuresSymbolPriceTicker': {'url': 'fapi/v1/ticker/price', 'method': 'GET', 'private': True, 'futures': True},
            'futuresOrderInfo': {'url': 'fapi/v1/order', 'method': 'GET', 'private': True, 'futures': True},
            'futuresCancelOrder':      {'url': 'fapi/v1/order', 'method': 'DELETE', 'private': True, 'futures': True},
   }
    
    def __init__(self, API_KEY, API_SECRET):
        self.API_KEY = API_KEY
        self.API_SECRET = bytearray(API_SECRET, encoding='utf-8')
        self.shift_seconds = 0

    def __getattr__(self, name):
        def wrapper(*args, **kwargs):
            kwargs.update(command=name)
            return self.call_api(**kwargs)
        return wrapper

    def set_shift_seconds(self, seconds):
        self.shift_seconds = seconds
        
    def call_api(self, **kwargs):

        command = kwargs.pop('command')

        base_url ='https://api.binance.com/' 
        if self.methods[command].get('futures'):
            base_url = 'https://fapi.binance.com/' 
        api_url = base_url  + self.methods[command]['url']

        payload = kwargs
        headers = {}
        
        payload_str = urllib.parse.urlencode(payload)
        if self.methods[command]['private']:
            payload.update({'timestamp': int(time.time() + self.shift_seconds - 1) * 1000})
            payload_str = urllib.parse.urlencode(payload).encode('utf-8')
            sign = hmac.new(
                key=self.API_SECRET,
                msg=payload_str,
                digestmod=hashlib.sha256
            ).hexdigest()

            payload_str = payload_str.decode("utf-8") + "&signature="+str(sign) 
            headers = {"X-MBX-APIKEY": self.API_KEY, "Content-Type":"application/x-www-form-urlencoded"}

        if self.methods[command]['method'] == 'GET' or self.methods[command]['url'].startswith('sapi'):
            api_url += '?' + payload_str

        response = requests.request(method=self.methods[command]['method'], url=api_url, data="" if self.methods[command]['method'] == 'GET' else payload_str, headers=headers)
            
        if 'code' in response.text:
            raise Exception(response.text)

        return response.json()

Для тестирования методов, создайте в этой же папке второй файл, например, binance_test.py, туда вставьте вот такой код (подставьте свои API ключи):

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('account', bot.account())

(Или возьмите с гитхаба)

После этого код можно запускать. К примеру, если вы только установили Python и не знаете, что делать, найдите редактор Idle (он устанавливается вместе с питоном), в нем File -> Open, откройте файл binance_test.py и нажмите F5. Код, представленный выше, вернет информацию по вашему аккаунту — подробности ниже.

Еще немного общей информации: практически во всех подписанных запросах необходимо указывать параметр timestamp — это текущее unix-время в милиосекундах. Но, так как некоторые сети бывают перегружены, то ваш запрос может заблудиться и придти позже. Поэтому биржа предоставляет вам временное окно (по умолчанию 5000 милисекунд). Если у вас запросы не успевают придти в это окно, вы можете его расширить с помощью параметра recvWindow. Но, думаю, это мало кому понадобится.


Реклама



Публичные запросы


Проверка связи — /api/v1/ping 

Метод для проверки работы API. 
Возвращает пустой словарь

Ссылка для просмотра в браузере https://api.binance.com/api/v1/ping.
Вес — 1
Код для проверки:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print(bot.ping())

Получение времени биржи — /api/v1/time

Ссылка для просмотра в браузере https://api.binance.com/api/v1/time
Вес — 1
Возвращает словарь с текущим временем:

{
  "serverTime": 1499827319559
}

Код для проверки:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print(bot.time())

Настройки и лимиты биржи — /api/v1/exchangeInfo

Ссылка для просмотра в браузере https://api.binance.com/api/v1/exchangeInfo
Вес — 1
Возвращает структуру данных:

{
  "timezone": "UTC",
  "serverTime": 1508631584636,
  "rateLimits": [{
      "rateLimitType": "REQUESTS",
      "interval": "MINUTE",
      "limit": 1200
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "SECOND",
      "limit": 10
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "DAY",
      "limit": 100000
    }
  ],
  "exchangeFilters": [],
  "symbols": [{
    "symbol": "ETHBTC",
    "status": "TRADING",
    "baseAsset": "ETH",
    "baseAssetPrecision": 8,
    "quoteAsset": "BTC",
    "quotePrecision": 8,
    "orderTypes": ["LIMIT", "MARKET"],
    "icebergAllowed": false,
    "filters": [{
      "filterType": "PRICE_FILTER",
      "minPrice": "0.00000100",
      "maxPrice": "100000.00000000",
      "tickSize": "0.00000100"
    }, {
      "filterType": "LOT_SIZE",
      "minQty": "0.00100000",
      "maxQty": "100000.00000000",
      "stepSize": "0.00100000"
    }, {
      "filterType": "MIN_NOTIONAL",
      "minNotional": "0.00100000"
    }]
  }]
}

Ключ rateLimits ведет на массив с лимитами — сколько запросов в секунду/минуту/день можно делать. 
Ключ symbols содержит настройки для каждой пары — рассмотрим одну, ETHBTC

{
  "symbol": "ETHBTC",
  "status": "TRADING",
  "baseAsset": "ETH",
  "baseAssetPrecision": 8,
  "quoteAsset": "BTC",
  "quotePrecision": 8,
  "orderTypes": [
    "LIMIT",
    "LIMIT_MAKER",
    "MARKET",
    "STOP_LOSS_LIMIT",
    "TAKE_PROFIT_LIMIT"
  ],
  "icebergAllowed": true,
  "filters": [
    {
      "filterType": "PRICE_FILTER",
      "minPrice": "0.00000100",
      "maxPrice": "100000.00000000",
      "tickSize": "0.00000100"
    },
    {
      "filterType": "LOT_SIZE",
      "minQty": "0.00100000",
      "maxQty": "100000.00000000",
      "stepSize": "0.00100000"
    },
    {
      "filterType": "MIN_NOTIONAL",
      "minNotional": "0.00100000"
    }
  ]
}

symbol — непосредственно пара
status — TRADING  -разрешена торговля
baseAsset — базовая валюта
baseAssetPrecision — требуемое количество символов базовой валюты после запятой при создании ордера (для цены и количества)
quoteAsset — квотируемая валюта
quotePrecision — требуемое количество символов квотируемой валюты после запятой при создании ордера (для цены и количества)
«orderTypes»: [
    «LIMIT»,
    «LIMIT_MAKER»,
    «MARKET»,
    «STOP_LOSS_LIMIT»,
    «TAKE_PROFIT_LIMIT»
  ] — допустимые виды ордеров по паре
icebergAllowed — разрешено ли создание айсбергов (ордеров с невидимой частью)
filters — ограничение ордеров
    PRICE_FILTER — ограничение цены создаваемого ордера. Цена ордера должна быть в диапазоне min_price и max_price, и шаг торговли должен быть кратен tickSize. Да да, тут нельзя ставить ордера с произвольной ценой.
    LOT_SIZE — ограничение объема создаваемого ордера. Объем должен быть в диапазоне minQty и maxQty, и быть кратен stepSize.
    MIN_NOTIONAL — итоговая сумма ордера (объем*цена) должна быть выше minNotional.
Код для проверки:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print(bot.exchangeInfo())

Открытые ордера на бирже — /api/v1/depth

Метод позволяет получить книгу ордеров. 
Принимает параметры:
Обязательные:
symbol — пара 
Необязательные:
limit — кол-во возвращаемых записей от 5 до 1000 (по умолчанию 100). Допустимые значения: 5, 10, 20, 50, 100, 500, 1000. Еще можно указать 0, но он может вернуть большое кол-во данных.
Вес зависит от параметра limit. При лимите от 5 до 100 вес будет равен 1. Для параметра 500 вес составит 5. Для параметра 1000 вес будет 10.
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/depth?symbol=ETHBTC
Возвращает значения:

{
  "lastUpdateId": 1027024,
  "bids": [
    [
      "4.00000000",     // PRICE
      "431.00000000",   // QTY
      []                // Ignore.
    ]
  ],
  "asks": [
    [
      "4.00000200",
      "12.00000000",
      []
    ]
  ]
}

bids — это списки цен/объемов на покупку, asks — на продажу.
Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('depth', bot.depth(
    symbol='BNBBTC',
    limit=5
))

Последние (чужие) сделки — /api/v1/trades

Принимает параметры:
Обязательные:
symbol — пара 
Необязательные:
limit — кол-во возвращаемых записей (максимум 500, по умолчанию 500).
Вес — 1
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/trades?symbol=ETHBTC
Пример ответа:

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "time": 1499865549590,
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]

id — id сделки
price — цена
qty — количество
time — время сделки
isBuyerMaker — была ли покупка по указанной покупателем цене, 
isBestMatch — была ли встречная сделка
Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('trades', bot.trades(
    symbol='BNBBTC',
    limit=1
))

Сжатая история сделок — /api/v1/aggTrades

Метод позволяет получить суммарную историю сделок. Сделки, выполненные в одно время по одному ордеру и по одной цене будут представлены одной строкой с объединенным количеством.
Вес — 1
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/aggTrades?symbol=ETHBTC
Принимает параметры:
Обязательные:
symbol — пара
Необязательные:
fromID — показывать начиная со сделки № (включительно)
startTime — начиная с какого времени (включительно)
endTime — заканчивая каким временем (включительно)
limit — Кол-во записей (максимум 500, по умолчанию 500)
Возвращает данные:

[
  {
    "a": 26129,         //  tradeId строки
    "p": "0.01633102",  // Цена
    "q": "4.70443515",  // Количество
    "f": 27781,         // Первая tradeId
    "l": 27781,         // Последняя tradeId
    "T": 1498793709153, // Время
    "m": true,          // Was the buyer the maker?
    "M": true           // Was the trade the best price match?
  }
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('aggTrades', bot.aggTrades(
    symbol='BNBBTC',
    limit=1
))

Данные по свечам – /api/v1/klines

Вес – 1
Ссылка для просмотра в браузере https://api.binance.com/api/v1/klines?symbol=LTCBTC&interval=5m
Параметры:
Обязательные:
symbol – пара
interval – период свечи
    Допустимые интервалы:
    •    1m     // 1 минута
    •    3m     // 3 минуты
    •    5m    // 5 минут
    •    15m  // 15 минут
    •    30m    // 30 минут
    •    1h    // 1 час
    •    2h    // 2 часа
    •    4h    // 4 часа
    •    6h    // 6 часов
    •    8h    // 8 часов
    •    12h    // 12 часов
    •    1d    // 1 день
    •    3d    // 3 дня
    •    1w    // 1 неделя
    •    1M    // 1 месяц

Необязательные:
limit – кол-во свечей (максимум 500, по умолчанию 500)
startTime – время начала построения
endTime – окончание периода
Если не указаны параметры startTime и endTime, то возвращаются самые последние свечи.
Пример ответа:

[
  [
    1499040000000,      // Время открытия
    "0.01634790",       // Цена открытия (Open)
    "0.80000000",       // Максимальная цена (High)
    "0.01575800",       // Минимальная цена (Low)
    "0.01577100",       // Цена закрытия (Close)
    "148976.11427815",  // Объем
    1499644799999,      // Время закрытия
    "2434.19055334",    // Объем квотируемой валюты
    308,                // Кол-во сделок
    "1756.87402397",    // Taker buy base asset volume
    "28.46694368",      // Taker buy quote asset volume
    "17928899.62484339" // Ignore
  ]
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('klines', bot.klines(
    symbol='BNBBTC',
    interval='5m',
    limit=1
))

Статистика за 24 часа — /api/v1/ticker/24hr

Вес – 1, если указана пара, иначе вес равен (количеству всех торгуемых пар)/2.
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/ticker/24hr?symbol=BNBBTC
Параметры:
Необязательные:
symbol – пара
Если symbol не указан, возвращаются данные по всем парам. В этом случае, считается, что вы сделали столько запросов к бирже, сколько вернулось пар.
Пример ответа:

{
  "symbol": "BNBBTC", // пара
  "priceChange": "-94.99999800", // изменение цены за сутки 
  "priceChangePercent": "-95.960", // изменение цены за сутки %
  "weightedAvgPrice": "0.29628482", //Средневзвешенная цена
  "prevClosePrice": "0.10002000", // Предыдущая цена закрытия
  "lastPrice": "4.00000200",     // Последняя цена
  "lastQty": "200.00000000",    // Последний объем
  "bidPrice": "4.00000000",    // Цена покупки
  "askPrice": "4.00000200",    // Цена продажи
  "openPrice": "99.00000000",    // Цена открытия
  "highPrice": "100.00000000",    // Самая высокая цена
  "lowPrice": "0.10000000",    // Самая низкая цена
  "volume": "8913.30000000",    // Объем торгов базовой валюты
  "quoteVolume": "15.30000000",    // Объем торгов квотируемой
  "openTime": 1499783499040,    // Время открытия
  "closeTime": 1499869899040,    // Время закрытия
  "fristId": 28385,   // Id первой сделки
  "lastId": 28460,    // Id последней сделки
  "count": 76         // Кол-во сделок
}

Если пар несколько, то такие словари вкладываются в массив, вот так:

[
  {
    "symbol": "BNBBTC",
    
  },
  {
    "symbol": "LTCBTC",
    
  },
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('ticker/24hr', bot.ticker24hr(
    symbol='BNBBTC'
))

Последняя цена по паре (или парам) — /api/v3/ticker/price

Вес — 1
Параметры:
Необязательные:
symbol – пара
Если параметр symbol не указан, то возвращаются цены по всем парам.
Ссылка для просмотра в браузере: https://api.binance.com/api/v3/ticker/price?symbol=BNBBTC
Пример ответа:

{
  "symbol": "LTCBTC",
  "price": "4.00000200"
}

Или (если не указан параметр)

[
  {
    "symbol": "LTCBTC",
    "price": "4.00000200"
  },
  {
    "symbol": "ETHBTC",
    "price": "0.07946600"
  }
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('ticker/price', bot.tickerPrice(
    symbol='BNBBTC'
))

Лучшие цены покупки/продажи — /api/v3/ticker/bookTicker

Вес 1
Параметры:
Необязательные:
symbol – пара
Если параметр symbol не указан, возвращаются данные по всем парам.
Ссылка для просмотра в браузере: https://api.binance.com/api/v3/ticker/bookTicker?symbol=BNBBTC
Пример ответа:

{
  "symbol": "LTCBTC",
  "bidPrice": "4.00000000", //Лучшая цена покупки
  "bidQty": "431.00000000", // Кол-во к покупке
  "askPrice": "4.00000200", // Лучшая цена продажи
  "askQty": "9.00000000"       // Кол-во к продаже    
}

Или (если не указан параметр):

[
  {
    "symbol": "LTCBTC",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000"
  },
  {
    "symbol": "ETHBTC",
    "bidPrice": "0.07946700",
    "bidQty": "9.00000000",
    "askPrice": "100000.00000000",
    "askQty": "1000.00000000"
  }
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('ticker/bookTicker', bot.tickerBookTicker(
    symbol='BNBBTC'
))

Реклама




Реклама



Авторизованные запросы:


Создание ордера — /api/v3/order

Для тех, кто будет писать свою библиотеку – обратите внимание, что адрес один и тот же /api/v3/order, но отличается метод – если отправлять данные через POST, это будет создание ордера, через GET – получение информации об ордере, DELETE – отмена ордера. Параметры, соответственно, разные.

Вес – 1
Метод: POST
Параметры:
Обязательные:
symbol – пара
side – тип ордера (BUY либо SELL)
type – тип ордера (LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER) 
quantity – количество к покупке
timestamp – текущее время в миллисекундах (в коде, выложенном здесь, проставляется автоматически, указывать не надо. 
Необязательные:
timeInForce – (GTC, IOC, FOK). По умолчанию GTC. Расшифрую.
    GTC (Good Till Cancelled) – ордер будет висеть до тех пор, пока его не отменят.
    IOC (Immediate Or Cancel) – Будет куплено то количество, которое можно купить немедленно. Все, что не удалось купить, будет отменено.
   FOK (Fill-Or-Kill) – Либо будет куплено все указанное количество немедленно, либо не будет куплено вообще ничего, ордер отменится.

price – цена
newClientOrderId – Идентификатор ордера, который вы сами придумаете (строка). Если не указан, генерится автоматически.
stopPrice – стоп-цена, можно указывать если тип ордера STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, или TAKE_PROFIT_LIMIT.
icebergQty – кол-во для ордера-айсберга, можно указывать, если тип ордера LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT
recvWindow – кол-во миллисекунд, которое прибавляется к timestamp и формирует окно действия запроса (см. выше). По умолчанию 5000.
newOrderRespType –какую информацию возвращать, если удалось создать ордер. Допустимые значения ACK, RESULT, или FULL, по умолчанию RESULT. Подробности ниже.

В зависимости от типа ордера, некоторые поля становятся обязательными:

Тип ордера                    Обязательные поля
LIMIT                         timeInForce, quantity, price
MARKET                        quantity
STOP_LOSS                     quantity, stopPrice
STOP_LOSS_LIMIT               timeInForce, quantity, price, stopPrice
TAKE_PROFIT                   quantity, stopPrice
TAKE_PROFIT_LIMIT             timeInForce, quantity, price, stopPrice
LIMIT_MAKER                   quantity, price

Ордера типа LIMIT_MAKER – это ордера типа обычного LIMIT, но они отклонятся, если ордер при выставлении может выполниться по рынку. Другими словами, вы никогда не будете тейкером, ордер либо выставится выше/ниже рынка, либо не выставится вовсе.
Ордера типа STOP_LOSS и TAKE_PROFIT исполнятся по рынку (ордер типа MARKET), как только будет достигнута цена stopPrice.
Любые ордера LIMIT или LIMIT_MAKER могут формировать ордер-айсберг, установив параметр icebergQty.
Если установлен параметр icebergQty, то параметр timeInForce ОБЯЗАТЕЛЬНО должен иметь значение GTC.

Для того, что бы выставлять цены, противоположные текущим для ордеров типов MARKET и LIMIT:
Цена выше рыночной: STOP_LOSS BUY, TAKE_PROFIT SELL
Цена ниже рыночной: STOP_LOSS SELL, TAKE_PROFIT BUY

При создании ордера вернется ответ, в зависимости от параметра newOrderRespType:

newOrderRespType == ACK:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595
}

newOrderRespType == RESULT:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "0.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL"
}

newOrderRespType == FULL:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "0.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "fills": [
    {
      "price": "4000.00000000",
      "qty": "1.00000000",
      "commission": "4.00000000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3999.00000000",
      "qty": "5.00000000",
      "commission": "19.99500000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3998.00000000",
      "qty": "2.00000000",
      "commission": "7.99600000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3997.00000000",
      "qty": "1.00000000",
      "commission": "3.99700000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3995.00000000",
      "qty": "1.00000000",
      "commission": "3.99500000",
      "commissionAsset": "USDT"
    }
  ]
}

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
# Создать отложенный ордер на покупку 0.1 LTC за BTC
# По курсу 0.1
print('createOrder', bot.createOrder(
    symbol='LTCBTC',
    recvWindow=5000,
    side='BUY',
    type='LIMIT',
    timeInForce='GTC',
    quantity=0.1,
    price=0.1
))

Тестирование создания ордера: /api/v3/order/test

Вес: 1
Метод: POST
Метод позволяет протестировать создание ордера – например, проверить, правильно ли настроены временные рамки. По факту такой ордер никогда не будет исполнен, и средства на его создание затрачены не будут.
Параметры такие же, как при создании ордера.
Возвращает пустой словарь:

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
# Протестировать отложенный ордер на покупку 0.1 LTC за BTC
# По курсу 0.1
print('testOrder', bot.testOrder(
    symbol='LTCBTC',
    recvWindow=5000,
    side='BUY',
    type='LIMIT',
    timeInForce='GTC',
    quantity=0.1,
    price=0.1
))

Получить информацию по созданному ордеру — /api/v3/order

Вес – 1
Метод – GET
Параметры:
Обязательные:
symbol – пара
orderId – ID ордера, назначенный биржей
ИЛИ origClientOrderId – ID ордера, назначенный пользователем или сгенерированный (см. создание ордера)
Либо orderId либо origClientOrderId необходимо предоставить.
timestamp – текущее время (в представленном коде проставляется автоматически, указывать не надо)
Необязательные:
recvWindow – окно валидности запроса.

Возвращаемое значение:

{
  "symbol": "LTCBTC",
  "orderId": 1,
  "clientOrderId": "myOrder1",
  "price": "0.1",
  "origQty": "1.0",     // исходное указанное кол-во на покупку/продажу
  "executedQty": "0.0",  // текущее исполненное кол-во
  "status": "NEW",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "BUY",
  "stopPrice": "0.0",
  "icebergQty": "0.0",
  "time": 1499827319559,
  "isWorking": true
}

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('orderInfo', bot.orderInfo(
    orderId=123123,
    symbol='LTCBTC',
))

Отмена ордера — /api/v3/order

Вес – 1
Метод – DELETE
Параметры:
Обязательные:
symbol – пара

orderId – ID ордера, назначенный биржей
ИЛИ origClientOrderId – ID ордера, назначенный пользователем или сгенерированный (см. создание ордера)
Либо orderId либо origClientOrderId необходимо предоставить.

timestamp – текущее время (в представленном коде проставляется автоматически, указывать не надо)
Не обязательные:

 
newClientOrderId – позволяет однозначно определить отмену, если не указано, генерируется автоматически
recvWindow – окно валидности запроса.
Возвращает:

{
  "symbol": "LTCBTC",
  "origClientOrderId": "myOrder1",
  "orderId": 1,
  "clientOrderId": "cancelMyOrder1"
}

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)
print('cancelOrder', bot.cancelOrder(
    orderId=123123,
    symbol='LTCBTC',
))

Текущие открытые пользователем ордера — /api/v3/openOrders

Вес – 1 если указана пара, либо (количество всех открытых для торгов пар) / 2.
Метод – GET
Параметры:
Обязательные:
timestamp – текущее время (в представленном коде проставляется автоматически, указывать не надо)
Не обязательные:
Не обязательные:
symbol – пара
recvWindow – окно валидности запроса.

Если параметр symbol не указан, возвращаются все открытые ордера по всем парам в массиве. В этом случае количество запросов к API считается равным количеству открытых для торговли пар.
Возвращает:

[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "isWorking": trueO
  }
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)

# Все открытые ордера по паре
print('openOrders', bot.openOrders(
    symbol='LTCBTC',
))

# Все открытые ордера по всем парам
print('openOrders', bot.openOrders())

Все ордера пользователя вообще — /api/v3/allOrders

Метод позволяет получить вообще все ордера пользователя – открытые, исполненные или отмененные.
Вес – 5
Метод – GET
Параметры:
Обязательные:
symbol – пара
timestamp – текущее время (в представленном коде проставляется автоматически, указывать не надо)
Не обязательные:
orderId – Если указан, то вернутся все ордера, которые >= указанному. Если не указан, вернутся самые последние.
limit – кол-во возвращаемых ордеров (максимум 500, по умолчанию 500)
recvWindow – окно валидности запроса.
Возвращает:

[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "isWorking": true
  }
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)

# Все ордера по паре
print('allOrders', bot.allOrders(
    symbol='LTCBTC',
))

Информация по аккаунту — /api/v3/account

Вес – 5
Метод – GET
Параметры:
Обязательные:
timestamp – текущее время (в представленном коде проставляется автоматически, указывать не надо)
Не обязательные:
recvWindow – окно валидности запроса.
Возвращает:

{
  "makerCommission": 15,
  "takerCommission": 15,
  "buyerCommission": 0,
  "sellerCommission": 0,
  "canTrade": true,
  "canWithdraw": true,
  "canDeposit": true,
  "updateTime": 123456789,
  "balances": [
    {
      "asset": "BTC",
      "free": "4723846.89208129",
      "locked": "0.00000000"
    },
    {
      "asset": "LTC",
      "free": "4763368.68006011",
      "locked": "0.00000000"
    }
  ]
}

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)

print('account', bot.account())

Список сделок пользователя — /api/v3/myTrades

Метод позволяет получить историю торгов авторизованного пользователя по указанной паре.
Вес – 5.
Параметры:
Обязательные:
symbol – пара
timestamp – текущее время (в представленном коде проставляется автоматически, указывать не надо)
Не обязательные:
limit – кол-во возвращаемых сделок (максимум 500, по умолчанию 500)
fromId – с какой сделки начинать вывод. По умолчанию выводятся самые последние.
recvWindow – окно валидности запроса.
Возвращает:

[
  {
    "id": 28457,
    "orderId": 100234,
    "price": "4.00000100",
    "qty": "12.00000000",
    "commission": "10.10000000",
    "commissionAsset": "BNB",
    "time": 1499865549590,
    "isBuyer": true,
    "isMaker": false,
    "isBestMatch": true
  }
]

Пример кода:

from binance_api import Binance
bot = Binance(
    API_KEY='D7...Ejj',
    API_SECRET='gwQ...u3A'
)

print('myTrades', bot.myTrades(
    symbol='LTCBTC'
))

Реклама



WAPI

Ввод и вывод средств

Подробное описание будет чуть позже, пока что примеры с комментариями

from binance_api import Binance
bot = Binance(
    API_KEY='D7F...Ejj',
    API_SECRET='gwQ...u3A'
)

# Получение адреса для депозита
print(bot.depositAddress(asset='BTC'))

# Вывод средств
print(bot.withdraw(asset='XRP', address='1wsdsr234234242', amount=12))

# История пополнений
print(bot.depositHistory(asset='BTC'))
print(bot.depositHistory())

# История выводов
print(bot.withdrawHistory())
print(bot.withdrawHistory(asset='ETH'))

# Узнать комиссию за вывод
print(bot.withdrawFee(asset='BTC'))

# Состояние аккаунта
print(bot.accountStatus())

# Состояние биржи
print(bot.systemStatus())

Table of Contents generated with DocToc

  • General API Information
  • HTTP Return Codes
  • Error Codes
  • General Information on Endpoints
  • LIMITS
    • General Info on Limits
    • IP Limits
    • Order Rate Limits
  • Data Sources
  • Endpoint security type
  • SIGNED (TRADE and USER_DATA) Endpoint security
    • Timing security
    • SIGNED Endpoint Examples for POST /api/v3/order
      • HMAC Keys
        • Example 1: As a request body
        • Example 2: As a query string
        • Example 3: Mixed query string and request body
      • RSA Keys
  • Public API Endpoints
    • Terminology
    • ENUM definitions
    • General endpoints
      • Test connectivity
      • Check server time
      • Exchange information
    • Market Data endpoints
      • Order book
      • Recent trades list
      • Old trade lookup (MARKET_DATA)
      • Compressed/Aggregate trades list
      • Kline/Candlestick data
      • UIKlines
      • Current average price
      • 24hr ticker price change statistics
      • Symbol price ticker
      • Symbol order book ticker
      • Rolling window price change statistics
    • Account endpoints
      • New order (TRADE)
        • Conditional fields in Order Responses
      • Test new order (TRADE)
      • Query order (USER_DATA)
      • Cancel order (TRADE)
        • Regarding cancelRestrictions
      • Cancel All Open Orders on a Symbol (TRADE)
      • Cancel an Existing Order and Send a New Order (TRADE)
      • Current open orders (USER_DATA)
      • All orders (USER_DATA)
      • New OCO (TRADE)
      • Cancel OCO (TRADE)
      • Query OCO (USER_DATA)
      • Query all OCO (USER_DATA)
      • Query Open OCO (USER_DATA)
      • Account information (USER_DATA)
      • Account trade list (USER_DATA)
      • Query Current Order Count Usage (TRADE)
      • Query Prevented Matches (USER_DATA)
    • User data stream endpoints
      • Start user data stream (USER_STREAM)
      • Keepalive user data stream (USER_STREAM)
      • Close user data stream (USER_STREAM)

Public Rest API for Binance (2023-03-13)

General API Information

  • The following base endpoints are available:
    • https://api.binance.com
    • https://api1.binance.com
    • https://api2.binance.com
    • https://api3.binance.com
    • https://api4.binance.com
  • All endpoints are equal in functionality.
    Performance may vary between the base endpoints and can be freely switched between them to find which one works best for one’s setup.
  • All endpoints return either a JSON object or array.
  • Data is returned in ascending order. Oldest first, newest last.
  • All time and timestamp related fields are in milliseconds.
  • The base endpoint https://data.binance.com can be used to access the following API endpoints that have NONE as security type:
    • GET /api/v3/aggTrades
    • GET /api/v3/avgPrice
    • GET /api/v3/depth
    • GET /api/v3/exchangeInfo
    • GET /api/v3/klines
    • GET /api/v3/ping
    • GET /api/v3/ticker
    • GET /api/v3/ticker/24hr
    • GET /api/v3/ticker/bookTicker
    • GET /api/v3/ticker/price
    • GET /api/v3/time
    • GET /api/v3/trades
    • GET /api/v3/uiKlines

HTTP Return Codes

  • HTTP 4XX return codes are used for malformed requests; the issue is on the sender’s side.
  • HTTP 403 return code is used when the WAF Limit (Web Application Firewall) has been violated.
  • HTTP 409 return code is used when a cancelReplace order partially succeeds. (i.e. if the cancellation of the order fails but the new order placement succeeds.)
  • HTTP 429 return code is used when breaking a request rate limit.
  • HTTP 418 return code is used when an IP has been auto-banned for continuing to send requests after receiving 429 codes.
  • HTTP 5XX return codes are used for internal errors; the issue is on Binance’s side.
    It is important to NOT treat this as a failure operation; the execution status is
    UNKNOWN and could have been a success.

Error Codes

  • Any endpoint can return an ERROR

Sample Payload below:

{
  "code": -1121,
  "msg": "Invalid symbol."
}
  • Specific error codes and messages are defined in Errors Codes.

General Information on Endpoints

  • For GET endpoints, parameters must be sent as a query string.
  • For POST, PUT, and DELETE endpoints, the parameters may be sent as a
    query string or in the request body with content type
    application/x-www-form-urlencoded. You may mix parameters between both the
    query string and request body if you wish to do so.
  • Parameters may be sent in any order.
  • If a parameter sent in both the query string and request body, the
    query string parameter will be used.

LIMITS

General Info on Limits

  • The following intervalLetter values for headers:
    • SECOND => S
    • MINUTE => M
    • HOUR => H
    • DAY => D
  • intervalNum describes the amount of the interval. For example, intervalNum 5 with intervalLetter M means «Every 5 minutes».
  • The /api/v3/exchangeInfo rateLimits array contains objects related to the exchange’s RAW_REQUESTS, REQUEST_WEIGHT, and ORDERS rate limits. These are further defined in the ENUM definitions section under Rate limiters (rateLimitType).
  • A 429 will be returned when either request rate limit or order rate limit is violated.

IP Limits

  • Every request will contain X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) in the response headers which has the current used weight for the IP for all request rate limiters defined.
  • Each route has a weight which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier weight.
  • When a 429 is received, it’s your obligation as an API to back off and not spam the API.
  • Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).
  • IP bans are tracked and scale in duration for repeat offenders, from 2 minutes to 3 days.
  • A Retry-After header is sent with a 418 or 429 responses and will give the number of seconds required to wait, in the case of a 429, to prevent a ban, or, in the case of a 418, until the ban is over.
  • The limits on the API are based on the IPs, not the API keys.

Order Rate Limits

  • Every successful order response will contain a X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter) header which has the current order count for the account for all order rate limiters defined. To monitor order count usage, refer to GET api/v3/rateLimit/order.
  • When the order count exceeds the limit, you will receive a 429 error without the Retry-After header. Please check the Order Rate Limit rules using GET api/v3/exchangeInfo and wait for reactivation accordingly.
  • Rejected/unsuccessful orders are not guaranteed to have X-MBX-ORDER-COUNT-** headers in the response.
  • The order rate limit is counted against each account.

Data Sources

  • The API system is asynchronous, so some delay in the response is normal and expected.
  • Each endpoint has a data source indicating where the data is being retrieved, and thus which endpoints have the most up-to-date response.

These are the three sources, ordered by which is has the most up-to-date response to the one with potential delays in updates.

  • Matching Engine — the data is from the matching Engine
  • Memory — the data is from a server’s local or external memory
  • Database — the data is taken directly from a database

Some endpoints can have more than 1 data source. (e.g. Memory => Database)
This means that the endpoint will check the first Data Source, and if it cannot find the value it’s looking for it will check the next one.

Endpoint security type

  • Each endpoint has a security type that determines how you will
    interact with it. This is stated next to the NAME of the endpoint.
  • If no security type is stated, assume the security type is NONE.
  • API-keys are passed into the Rest API via the X-MBX-APIKEY
    header.
  • API-keys and secret-keys are case sensitive.
  • API-keys can be configured to only access certain types of secure endpoints.
    For example, one API-key could be used for TRADE only, while another API-key
    can access everything except for TRADE routes.
  • By default, API-keys can access all secure routes.
Security Type Description
NONE Endpoint can be accessed freely.
TRADE Endpoint requires sending a valid API-Key and signature.
USER_DATA Endpoint requires sending a valid API-Key and signature.
USER_STREAM Endpoint requires sending a valid API-Key.
MARKET_DATA Endpoint requires sending a valid API-Key.
  • TRADE and USER_DATA endpoints are SIGNED endpoints.

SIGNED (TRADE and USER_DATA) Endpoint security

  • SIGNED endpoints require an additional parameter, signature, to be
    sent in the query string or request body.
  • Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation.
    Use your secretKey as the key and totalParams as the value for the HMAC operation.
  • The signature is not case sensitive.
  • totalParams is defined as the query string concatenated with the
    request body.

Timing security

  • A SIGNED endpoint also requires a parameter, timestamp, to be sent which
    should be the millisecond timestamp of when the request was created and sent.

  • An additional parameter, recvWindow, may be sent to specify the number of
    milliseconds after timestamp the request is valid for. If recvWindow
    is not sent, it defaults to 5000.

  • The logic is as follows:

    if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) {
      // process request
    } else {
      // reject request
    }

Serious trading is about timing. Networks can be unstable and unreliable,
which can lead to requests taking varying amounts of time to reach the
servers. With recvWindow, you can specify that the request must be
processed within a certain number of milliseconds or be rejected by the
server.

It is recommended to use a small recvWindow of 5000 or less! The max cannot go beyond 60,000!

SIGNED Endpoint Examples for POST /api/v3/order

HMAC Keys

Here is a step-by-step example of how to send a valid signed payload from the
Linux command line using echo, openssl, and curl.

Key Value
apiKey vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A
secretKey NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j
Parameter Value
symbol LTCBTC
side BUY
type LIMIT
timeInForce GTC
quantity 1
price 0.1
recvWindow 5000
timestamp 1499827319559

Example 1: As a request body

  • requestBody: symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559

  • HMAC SHA256 signature:

    [linux]$ echo -n "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559" | openssl dgst -sha256 -hmac "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    (stdin)= c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71
    
  • curl command:

    (HMAC SHA256)
    [linux]$ curl -H "X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" -X POST 'https://api.binance.com/api/v3/order' -d 'symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71'
    

Example 2: As a query string

  • queryString: symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559

  • HMAC SHA256 signature:

    [linux]$ echo -n "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559" | openssl dgst -sha256 -hmac "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    (stdin)= c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71
    
  • curl command:

    (HMAC SHA256)
    [linux]$ curl -H "X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" -X POST 'https://api.binance.com/api/v3/order?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71'
    

Example 3: Mixed query string and request body

  • queryString: symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC

  • requestBody: quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559

  • HMAC SHA256 signature:

    [linux]$ echo -n "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTCquantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559" | openssl dgst -sha256 -hmac "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    (stdin)= 0fd168b8ddb4876a0358a8d14d0c9f3da0e9b20c5d52b2a00fcf7d1c602f9a77
    
  • curl command:

    (HMAC SHA256)
    [linux]$ curl -H "X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" -X POST 'https://api.binance.com/api/v3/order?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC' -d 'quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=0fd168b8ddb4876a0358a8d14d0c9f3da0e9b20c5d52b2a00fcf7d1c602f9a77'
    

Note that the signature is different in example 3.
There is no & between «GTC» and «quantity=1».

RSA Keys

This will be a step by step process how to create the signature payload to send a valid signed payload.

We support PKCS#8 currently.

To get your API key, you need to upload your RSA Public Key to your account and a corresponding API key will be provided for you.

For this example, the private key will be referenced as ./test-prv-key.pem

Key Value
apiKey CAvIjXy3F44yW6Pou5k8Dy1swsYDWJZLeoK2r8G4cFDnE9nosRppc2eKc1T8TRTQ
Parameter Value
symbol BTCUSDT
side SELL
type LIMIT
timeInForce GTC
quantity 1
price 0.2
timestamp 1668481559918
recvWindow 5000

Step 1: Construct the payload

Arrange the list of parameters into a string. Separate each parameter with a &.

For the parameters above, the signature payload would look like this:

symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918&recvWindow=5000

Step 2: Compute the signature:

  1. Encode signature payload as ASCII data.
  2. Sign payload using RSASSA-PKCS1-v1_5 algorithm with SHA-256 hash function.
$ echo -n 'symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918&recvWindow=5000' | openssl dgst -sha256 -sign ./test-prv-key.pem
  1. Encode output as base64 string.
$  echo -n 'symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918&recvWindow=5000' | openssl dgst -sha256 -sign ./test-prv-key.pem | openssl enc -base64 -A
HZ8HOjiJ1s/igS9JA+n7+7Ti/ihtkRF5BIWcPIEluJP6tlbFM/Bf44LfZka/iemtahZAZzcO9TnI5uaXh3++lrqtNonCwp6/245UFWkiW1elpgtVAmJPbogcAv6rSlokztAfWk296ZJXzRDYAtzGH0gq7CgSJKfH+XxaCmR0WcvlKjNQnp12/eKXJYO4tDap8UCBLuyxDnR7oJKLHQHJLP0r0EAVOOSIbrFang/1WOq+Jaq4Efc4XpnTgnwlBbWTmhWDR1pvS9iVEzcSYLHT/fNnMRxFc7u+j3qI//5yuGuu14KR0MuQKKCSpViieD+fIti46sxPTsjSemoUKp0oXA==
  1. Since the signature may contain / and =, this could cause issues with sending the request. So the signature has to be URL encoded.
HZ8HOjiJ1s%2FigS9JA%2Bn7%2B7Ti%2FihtkRF5BIWcPIEluJP6tlbFM%2FBf44LfZka%2FiemtahZAZzcO9TnI5uaXh3%2B%2BlrqtNonCwp6%2F245UFWkiW1elpgtVAmJPbogcAv6rSlokztAfWk296ZJXzRDYAtzGH0gq7CgSJKfH%2BXxaCmR0WcvlKjNQnp12%2FeKXJYO4tDap8UCBLuyxDnR7oJKLHQHJLP0r0EAVOOSIbrFang%2F1WOq%2BJaq4Efc4XpnTgnwlBbWTmhWDR1pvS9iVEzcSYLHT%2FfNnMRxFc7u%2Bj3qI%2F%2F5yuGuu14KR0MuQKKCSpViieD%2BfIti46sxPTsjSemoUKp0oXA%3D%3D
  1. The curl command:
curl -H "X-MBX-APIKEY: CAvIjXy3F44yW6Pou5k8Dy1swsYDWJZLeoK2r8G4cFDnE9nosRppc2eKc1T8TRTQ" -X POST 'https://api.binance.com/api/v3/order?symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918&recvWindow=5000&signature=HZ8HOjiJ1s%2FigS9JA%2Bn7%2B7Ti%2FihtkRF5BIWcPIEluJP6tlbFM%2FBf44LfZka%2FiemtahZAZzcO9TnI5uaXh3%2B%2BlrqtNonCwp6%2F245UFWkiW1elpgtVAmJPbogcAv6rSlokztAfWk296ZJXzRDYAtzGH0gq7CgSJKfH%2BXxaCmR0WcvlKjNQnp12%2FeKXJYO4tDap8UCBLuyxDnR7oJKLHQHJLP0r0EAVOOSIbrFang%2F1WOq%2BJaq4Efc4XpnTgnwlBbWTmhWDR1pvS9iVEzcSYLHT%2FfNnMRxFc7u%2Bj3qI%2F%2F5yuGuu14KR0MuQKKCSpViieD%2BfIti46sxPTsjSemoUKp0oXA%3D%3D'

A sample Bash script below does the similar steps said above.

API_KEY="put your own API Key here"
PRIVATE_KEY_PATH="test-prv-key.pem"
# Set up the request:
API_METHOD="POST"
API_CALL="api/v3/order"
API_PARAMS="symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2"
# Sign the request:
timestamp=$(date +%s000)
api_params_with_timestamp="$API_PARAMS&timestamp=$timestamp"
signature=$(echo -n "$api_params_with_timestamp" 
            | openssl dgst -sha256 -sign "$PRIVATE_KEY_PATH" 
            | openssl enc -base64 -A)
# Send the request:
curl -H "X-MBX-APIKEY: $API_KEY" -X "$API_METHOD" 
    "https://api.binance.com/$API_CALL?$api_params_with_timestamp" 
    --data-urlencode "signature=$signature"

Public API Endpoints

Terminology

These terms will be used throughout the documentation, so it is recommended especially for new users to read to help their understanding of the API.

  • base asset refers to the asset that is the quantity of a symbol. For the symbol BTCUSDT, BTC would be the base asset.
  • quote asset refers to the asset that is the price of a symbol. For the symbol BTCUSDT, USDT would be the quote asset.

ENUM definitions

Symbol status (status):

  • PRE_TRADING
  • TRADING
  • POST_TRADING
  • END_OF_DAY
  • HALT
  • AUCTION_MATCH
  • BREAK

Account and Symbol Permissions (permissions):

  • SPOT
  • MARGIN
  • LEVERAGED
  • TRD_GRP_002
  • TRD_GRP_003
  • TRD_GRP_004
  • TRD_GRP_005
  • TRD_GRP_006
  • TRD_GRP_007

Order status (status):

Status Description
NEW The order has been accepted by the engine.
PARTIALLY_FILLED A part of the order has been filled.
FILLED The order has been completed.
CANCELED The order has been canceled by the user.
PENDING_CANCEL Currently unused
REJECTED The order was not accepted by the engine and not processed.
EXPIRED The order was canceled according to the order type’s rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill)
or by the exchange, (e.g. orders canceled during liquidation, orders canceled during maintenance)
EXPIRED_IN_MATCH The order was expired by the exchange due to STP. (e.g. an order with EXPIRE_TAKER will match with existing orders on the book with the same account or same tradeGroupId)

OCO Status (listStatusType):

Status Description
RESPONSE This is used when the ListStatus is responding to a failed action. (E.g. Orderlist placement or cancellation)
EXEC_STARTED The order list has been placed or there is an update to the order list status.
ALL_DONE The order list has finished executing and thus no longer active.

OCO Order Status (listOrderStatus):

Status Description
EXECUTING Either an order list has been placed or there is an update to the status of the list.
ALL_DONE An order list has completed execution and thus no longer active.
REJECT The List Status is responding to a failed action either during order placement or order canceled

ContingencyType

  • OCO

Order types (orderTypes, type):

  • LIMIT
  • MARKET
  • STOP_LOSS
  • STOP_LOSS_LIMIT
  • TAKE_PROFIT
  • TAKE_PROFIT_LIMIT
  • LIMIT_MAKER

Order Response Type (newOrderRespType):

  • ACK
  • RESULT
  • FULL

Order side (side):

  • BUY
  • SELL

Time in force (timeInForce):

This sets how long an order will be active before expiration.

Status Description
GTC Good Til Canceled
An order will be on the book unless the order is canceled.
IOC Immediate Or Cancel
An order will try to fill the order as much as it can before the order expires.
FOK Fill or Kill
An order will expire if the full order cannot be filled upon execution.

Kline/Candlestick chart intervals:

s-> seconds; m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

  • 1s
  • 1m
  • 3m
  • 5m
  • 15m
  • 30m
  • 1h
  • 2h
  • 4h
  • 6h
  • 8h
  • 12h
  • 1d
  • 3d
  • 1w
  • 1M

Rate limiters (rateLimitType)

  • REQUEST_WEIGHT

    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 1200
    }
  • ORDERS

    {
      "rateLimitType": "ORDERS",
      "interval": "SECOND",
      "intervalNum": 1,
      "limit": 10
    }
  • RAW_REQUESTS

    {
      "rateLimitType": "RAW_REQUESTS",
      "interval": "MINUTE",
      "intervalNum": 5,
      "limit": 5000
    }

Rate limit intervals (interval)

  • SECOND
  • MINUTE
  • DAY

General endpoints

Test connectivity

Test connectivity to the Rest API.

Weight:
1

Parameters:
NONE

Data Source:
Memory

Response:

Check server time

Test connectivity to the Rest API and get the current server time.

Weight:
1

Parameters:
NONE

Data Source:
Memory

Response:

{
  "serverTime": 1499827319559
}

Exchange information

Current exchange trading rules and symbol information

Weight:
10

Parameters:

There are 4 possible options:

Options Example
No parameter curl -X GET «https://api.binance.com/api/v3/exchangeInfo»
symbol curl -X GET «https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC»
symbols curl -X GET «https://api.binance.com/api/v3/exchangeInfo?symbols=%5B%22BNBBTC%22,%22BTCUSDT%22%5D»
or
curl -g -X GET ‘https://api.binance.com/api/v3/exchangeInfo?symbols=[«BTCUSDT»,»BNBBTC»]’
permissions curl -X GET «https://api.binance.com/api/v3/exchangeInfo?permissions=SPOT»
or
curl -X GET «https://api.binance.com/api/v3/exchangeInfo?permissions=%5B%22MARGIN%22%2C%22LEVERAGED%22%5D»
or
curl -g -X GET ‘https://api.binance.com/api/v3/exchangeInfo?permissions=[«MARGIN»,»LEVERAGED»]’

Notes:

  • If the value provided to symbol or symbols do not exist, the endpoint will throw an error saying the symbol is invalid.
  • All parameters are optional.
  • permissions can support single or multiple values (e.g. SPOT, ["MARGIN","LEVERAGED"])
  • If permissions parameter not provided, the default values will be ["SPOT","MARGIN","LEVERAGED"].
    • If one wants to view all symbols on GET /api/v3/exchangeInfo, then one has to search with all permissions explicitly specified
      (i.e. permissions=["SPOT","MARGIN","LEVERAGED","TRD_GRP_002","TRD_GRP_003","TRD_GRP_004","TRD_GRP_005","TRD_GRP_006","TRD_GRP_007"])

Data Source:
Memory

Response:

{
  "timezone": "UTC",
  "serverTime": 1565246363776,
  "rateLimits": [
    {
      //These are defined in the `ENUM definitions` section under `Rate Limiters (rateLimitType)`.
      //All limits are optional
    }
  ],
  "exchangeFilters": [
    //These are the defined filters in the `Filters` section.
    //All filters are optional.
  ],
  "symbols": [
    {
      "symbol": "ETHBTC",
      "status": "TRADING",
      "baseAsset": "ETH",
      "baseAssetPrecision": 8,
      "quoteAsset": "BTC",
      "quotePrecision": 8, // will be removed in future api versions (v4+)
      "quoteAssetPrecision": 8,
      "baseCommissionPrecision": 8,
      "quoteCommissionPrecision": 8,
      "orderTypes": [
        "LIMIT",
        "LIMIT_MAKER",
        "MARKET",
        "STOP_LOSS",
        "STOP_LOSS_LIMIT",
        "TAKE_PROFIT",
        "TAKE_PROFIT_LIMIT"
      ],
      "icebergAllowed": true,
      "ocoAllowed": true,
      "quoteOrderQtyMarketAllowed": true,
      "allowTrailingStop": false,
      "cancelReplaceAllowed":false,
      "isSpotTradingAllowed": true,
      "isMarginTradingAllowed": true,
      "filters": [
        //These are defined in the Filters section.
        //All filters are optional
      ],
      "permissions": [
        "SPOT",
        "MARGIN"
      ],
      "defaultSelfTradePreventionMode": "NONE",
      "allowedSelfTradePreventionModes": [
        "NONE"
      ]
    }
  ]
}

Market Data endpoints

Order book

Weight:
Adjusted based on the limit:

Limit Request Weight
1-100 1
101-500 5
501-1000 10
1001-5000 50

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 100; max 5000.
If limit > 5000. then the response will truncate to 5000.

Data Source:
Memory

Response:

{
  "lastUpdateId": 1027024,
  "bids": [
    [
      "4.00000000",     // PRICE
      "431.00000000"    // QTY
    ]
  ],
  "asks": [
    [
      "4.00000200",
      "12.00000000"
    ]
  ]
}

Recent trades list

Get recent trades.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 500; max 1000.

Data Source:
Memory

Response:

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590,
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]

Old trade lookup (MARKET_DATA)

GET /api/v3/historicalTrades

Get older trades.

Weight:
5

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 500; max 1000.
fromId LONG NO TradeId to fetch from. Default gets most recent trades.

Data Source:
Database

Response:

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590,
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]

Compressed/Aggregate trades list

Get compressed, aggregate trades. Trades that fill at the time, from the same taker order, with the same price will have the quantity aggregated.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
fromId LONG NO ID to get aggregate trades from INCLUSIVE.
startTime LONG NO Timestamp in ms to get aggregate trades from INCLUSIVE.
endTime LONG NO Timestamp in ms to get aggregate trades until INCLUSIVE.
limit INT NO Default 500; max 1000.
  • If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.

Data Source:
Database

Response:

[
  {
    "a": 26129,         // Aggregate tradeId
    "p": "0.01633102",  // Price
    "q": "4.70443515",  // Quantity
    "f": 27781,         // First tradeId
    "l": 27781,         // Last tradeId
    "T": 1498793709153, // Timestamp
    "m": true,          // Was the buyer the maker?
    "M": true           // Was the trade the best price match?
  }
]

Kline/Candlestick data

Kline/candlestick bars for a symbol.
Klines are uniquely identified by their open time.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
interval ENUM YES
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
  • If startTime and endTime are not sent, the most recent klines are returned.

Data Source:
Database

Response:

[
  [
    1499040000000,      // Kline open time
    "0.01634790",       // Open price
    "0.80000000",       // High price
    "0.01575800",       // Low price
    "0.01577100",       // Close price
    "148976.11427815",  // Volume
    1499644799999,      // Kline Close time
    "2434.19055334",    // Quote asset volume
    308,                // Number of trades
    "1756.87402397",    // Taker buy base asset volume
    "28.46694368",      // Taker buy quote asset volume
    "0"                 // Unused field, ignore.
  ]
]

UIKlines

The request is similar to klines having the same parameters and response.

uiKlines return modified kline data, optimized for presentation of candlestick charts.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
interval ENUM YES
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
  • If startTime and endTime are not sent, the most recent klines are returned.

Data Source:
Database

Response:

[
  [
    1499040000000,      // Kline open time
    "0.01634790",       // Open price
    "0.80000000",       // High price
    "0.01575800",       // Low price
    "0.01577100",       // Close price
    "148976.11427815",  // Volume
    1499644799999,      // Kline close time
    "2434.19055334",    // Quote asset volume
    308,                // Number of trades
    "1756.87402397",    // Taker buy base asset volume
    "28.46694368",      // Taker buy quote asset volume
    "0"                 // Unused field. Ignore.
  ]
]

Current average price

Current average price for a symbol.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES

Data Source:
Memory

Response:

{
  "mins": 5,
  "price": "9.35751834"
}

24hr ticker price change statistics

24 hour rolling window price change statistics. Careful when accessing this with no symbol.

Weight:

Parameter Symbols Provided Weight
symbol 1 1
symbol parameter is omitted 40
symbols 1-20 1
21-100 20
101 or more 40
symbols parameter is omitted 40

Parameters:

Name Type Mandatory Description
symbol STRING NO Parameter symbol and symbols cannot be used in combination.
If neither parameter is sent, tickers for all symbols will be returned in an array.

Examples of accepted format for the symbols parameter:
[«BTCUSDT»,»BNBUSDT»]
or
%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

symbols STRING NO
type ENUM NO Supported values: FULL or MINI.
If none provided, the default is FULL

Data Source:
Memory

Response — FULL:

{
  "symbol": "BNBBTC",
  "priceChange": "-94.99999800",
  "priceChangePercent": "-95.960",
  "weightedAvgPrice": "0.29628482",
  "prevClosePrice": "0.10002000",
  "lastPrice": "4.00000200",
  "lastQty": "200.00000000",
  "bidPrice": "4.00000000",
  "bidQty": "100.00000000",
  "askPrice": "4.00000200",
  "askQty": "100.00000000",
  "openPrice": "99.00000000",
  "highPrice": "100.00000000",
  "lowPrice": "0.10000000",
  "volume": "8913.30000000",
  "quoteVolume": "15.30000000",
  "openTime": 1499783499040,
  "closeTime": 1499869899040,
  "firstId": 28385,   // First tradeId
  "lastId": 28460,    // Last tradeId
  "count": 76         // Trade count
}

OR

[
  {
    "symbol": "BNBBTC",
    "priceChange": "-94.99999800",
    "priceChangePercent": "-95.960",
    "weightedAvgPrice": "0.29628482",
    "prevClosePrice": "0.10002000",
    "lastPrice": "4.00000200",
    "lastQty": "200.00000000",
    "bidPrice": "4.00000000",
    "bidQty": "100.00000000",
    "askPrice": "4.00000200",
    "askQty": "100.00000000",
    "openPrice": "99.00000000",
    "highPrice": "100.00000000",
    "lowPrice": "0.10000000",
    "volume": "8913.30000000",
    "quoteVolume": "15.30000000",
    "openTime": 1499783499040,
    "closeTime": 1499869899040,
    "firstId": 28385,   // First tradeId
    "lastId": 28460,    // Last tradeId
    "count": 76         // Trade count
  }
]

Response — MINI

{
  "symbol":      "BNBBTC",          // Symbol Name
  "openPrice":   "99.00000000",     // Opening price of the Interval
  "highPrice":   "100.00000000",    // Highest price in the interval
  "lowPrice":    "0.10000000",      // Lowest  price in the interval
  "lastPrice":   "4.00000200",      // Closing price of the interval
  "volume":      "8913.30000000",   // Total trade volume (in base asset)
  "quoteVolume": "15.30000000",     // Total trade volume (in quote asset)
  "openTime":    1499783499040,     // Start of the ticker interval
  "closeTime":   1499869899040,     // End of the ticker interval
  "firstId":     28385,             // First tradeId considered
  "lastId":      28460,             // Last tradeId considered
  "count":       76                 // Total trade count
}

OR

[
  {
    "symbol": "BNBBTC",
    "openPrice": "99.00000000",
    "highPrice": "100.00000000",
    "lowPrice": "0.10000000",
    "lastPrice": "4.00000200",
    "volume": "8913.30000000",
    "quoteVolume": "15.30000000",
    "openTime": 1499783499040,
    "closeTime": 1499869899040,
    "firstId": 28385,
    "lastId": 28460,
    "count": 76
  },
  {
    "symbol": "LTCBTC",
    "openPrice": "0.07000000",
    "highPrice": "0.07000000",
    "lowPrice": "0.07000000",
    "lastPrice": "0.07000000",
    "volume": "11.00000000",
    "quoteVolume": "0.77000000",
    "openTime": 1656908192899,
    "closeTime": 1656994592899,
    "firstId": 0,
    "lastId": 10,
    "count": 11
  }
]

Symbol price ticker

Latest price for a symbol or symbols.

Weight:

Parameter Symbols Provided Weight
symbol 1 1
symbol parameter is omitted 2
symbols Any 2

Parameters:

Name Type Mandatory Description
symbol STRING NO Parameter symbol and symbols cannot be used in combination.
If neither parameter is sent, prices for all symbols will be returned in an array.

Examples of accepted format for the symbols parameter:
[«BTCUSDT»,»BNBUSDT»]
or
%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

symbols STRING NO

Data Source:
Memory

Response:

{
  "symbol": "LTCBTC",
  "price": "4.00000200"
}

OR

[
  {
    "symbol": "LTCBTC",
    "price": "4.00000200"
  },
  {
    "symbol": "ETHBTC",
    "price": "0.07946600"
  }
]

Symbol order book ticker

GET /api/v3/ticker/bookTicker

Best price/qty on the order book for a symbol or symbols.

Weight:

Parameter Symbols Provided Weight
symbol 1 1
symbol parameter is omitted 2
symbols Any 2

Parameters:

Name Type Mandatory Description
symbol STRING NO Parameter symbol and symbols cannot be used in combination.
If neither parameter is sent, bookTickers for all symbols will be returned in an array.

Examples of accepted format for the symbols parameter:
[«BTCUSDT»,»BNBUSDT»]
or
%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

symbols STRING NO

Data Source:
Memory

Response:

{
  "symbol": "LTCBTC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}

OR

[
  {
    "symbol": "LTCBTC",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000"
  },
  {
    "symbol": "ETHBTC",
    "bidPrice": "0.07946700",
    "bidQty": "9.00000000",
    "askPrice": "100000.00000000",
    "askQty": "1000.00000000"
  }
]

Rolling window price change statistics

Note: This endpoint is different from the GET /api/v3/ticker/24hr endpoint.

The window used to compute statistics will be no more than 59999ms from the requested windowSize.

openTime for /api/v3/ticker always starts on a minute, while the closeTime is the current time of the request.
As such, the effective window will be up to 59999ms wider than windowSize.

E.g. If the closeTime is 1641287867099 (January 04, 2022 09:17:47:099 UTC) , and the windowSize is 1d. the openTime will be: 1641201420000 (January 3, 2022, 09:17:00)

Weight:

2 for each requested

symbol

regardless of

windowSize

.

The weight for this request will cap at 100 once the number of symbols in the request is more than 50.

Parameters

Name Type Mandatory Description
symbol STRING YES Either symbol or symbols must be provided

Examples of accepted format for the

symbols parameter:
[«BTCUSDT»,»BNBUSDT»]
or
%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

The maximum number of

symbols allowed in a request is 100.

symbols
windowSize ENUM NO Defaults to 1d if no parameter provided
Supported windowSize values:
1m,2m….59m for minutes
1h, 2h….23h — for hours
1d…7d — for days

Units cannot be combined (e.g.

1d2h is not allowed)

type ENUM NO Supported values: FULL or MINI.
If none provided, the default is FULL

Data Source:
Database

Response — FULL

When using symbol:

{
  "symbol":             "BNBBTC",
  "priceChange":        "-8.00000000",  // Absolute price change
  "priceChangePercent": "-88.889",      // Relative price change in percent
  "weightedAvgPrice":   "2.60427807",   // QuoteVolume / Volume
  "openPrice":          "9.00000000",
  "highPrice":          "9.00000000",
  "lowPrice":           "1.00000000",
  "lastPrice":          "1.00000000",
  "volume":             "187.00000000",
  "quoteVolume":        "487.00000000", // Sum of (price * volume) for all trades
  "openTime":           1641859200000,  // Open time for ticker window
  "closeTime":          1642031999999,  // Close time for ticker window
  "firstId":            0,              // Trade IDs
  "lastId":             60,
  "count":              61              // Number of trades in the interval
}

or

When using symbols:

[
  {
    "symbol": "BTCUSDT",
    "priceChange": "-154.13000000",        // Absolute price change
    "priceChangePercent": "-0.740",        // Relative price change in percent
    "weightedAvgPrice": "20677.46305250",  // QuoteVolume / Volume
    "openPrice": "20825.27000000",
    "highPrice": "20972.46000000",
    "lowPrice": "20327.92000000",
    "lastPrice": "20671.14000000",
    "volume": "72.65112300",
    "quoteVolume": "1502240.91155513",     // Sum of (price * volume) for all trades
    "openTime": 1655432400000,             // Open time for ticker window
    "closeTime": 1655446835460,            // Close time for ticker window
    "firstId": 11147809,                   // Trade IDs
    "lastId": 11149775,
    "count": 1967                          // Number of trades in the interval
  },
  {
    "symbol": "BNBBTC",
    "priceChange": "0.00008530",
    "priceChangePercent": "0.823",
    "weightedAvgPrice": "0.01043129",
    "openPrice": "0.01036170",
    "highPrice": "0.01049850",
    "lowPrice": "0.01033870",
    "lastPrice": "0.01044700",
    "volume": "166.67000000",
    "quoteVolume": "1.73858301",
    "openTime": 1655432400000,
    "closeTime": 1655446835460,
    "firstId": 2351674,
    "lastId": 2352034,
    "count": 361
  }
]

Response — MINI

When using symbol:

{
    "symbol": "LTCBTC",
    "openPrice": "0.10000000",
    "highPrice": "2.00000000",
    "lowPrice": "0.10000000",
    "lastPrice": "2.00000000",
    "volume": "39.00000000",
    "quoteVolume": "13.40000000",  // Sum of (price * volume) for all trades
    "openTime": 1656986580000,     // Open time for ticker window
    "closeTime": 1657001016795,    // Close time for ticker window
    "firstId": 0,                  // Trade IDs
    "lastId": 34,
    "count": 35                    // Number of trades in the interval
}

OR

When using symbols:

[
    {
        "symbol": "BNBBTC",
        "openPrice": "0.10000000",
        "highPrice": "2.00000000",
        "lowPrice": "0.10000000",
        "lastPrice": "2.00000000",
        "volume": "39.00000000",
        "quoteVolume": "13.40000000", // Sum of (price * volume) for all trades
        "openTime": 1656986880000,    // Open time for ticker window
        "closeTime": 1657001297799,   // Close time for ticker window
        "firstId": 0,                 // Trade IDs
        "lastId": 34,
        "count": 35                   // Number of trades in the interval
    },
    {
        "symbol": "LTCBTC",
        "openPrice": "0.07000000",
        "highPrice": "0.07000000",
        "lowPrice": "0.07000000",
        "lastPrice": "0.07000000",
        "volume": "33.00000000",
        "quoteVolume": "2.31000000",
        "openTime": 1656986880000,
        "closeTime": 1657001297799,
        "firstId": 0,
        "lastId": 32,
        "count": 33
    }
]

Account endpoints

New order (TRADE)

POST /api/v3/order  (HMAC SHA256)

Send in a new order.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
side ENUM YES
type ENUM YES
timeInForce ENUM NO
quantity DECIMAL NO
quoteOrderQty DECIMAL NO
price DECIMAL NO
newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent.
Orders with the same newClientOrderID can be accepted only when the previous one is filled, otherwise the order will be rejected.
strategyId INT NO
strategyType INT NO The value cannot be less than 1000000.
stopPrice DECIMAL NO Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
trailingDelta LONG NO Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
icebergQty DECIMAL NO Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
newOrderRespType ENUM NO Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
selfTradePreventionMode ENUM NO The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Some additional mandatory parameters based on order type:

Type Additional mandatory parameters Additional Information
LIMIT timeInForce, quantity, price
MARKET quantity or quoteOrderQty MARKET orders using the quantity field specifies the amount of the base asset the user wants to buy or sell at the market price.
E.g. MARKET order on BTCUSDT will specify how much BTC the user is buying or selling.

MARKET orders using quoteOrderQty specifies the amount the user wants to spend (when buying) or receive (when selling) the quote asset; the correct quantity will be determined based on the market liquidity and quoteOrderQty.
E.g. Using the symbol BTCUSDT:
BUY side, the order will buy as many BTC as quoteOrderQty USDT can.
SELL side, the order will sell as much BTC needed to receive quoteOrderQty USDT.

STOP_LOSS quantity, stopPrice or trailingDelta This will execute a MARKET order when the conditions are met. (e.g. stopPrice is met or trailingDelta is activated)
STOP_LOSS_LIMIT timeInForce, quantity, price, stopPrice or trailingDelta
TAKE_PROFIT quantity, stopPrice or trailingDelta This will execute a MARKET order when the conditions are met. (e.g. stopPrice is met or trailingDelta is activated)
TAKE_PROFIT_LIMIT timeInForce, quantity, price, stopPrice or trailingDelta
LIMIT_MAKER quantity, price This is a LIMIT order that will be rejected if the order immediately matches and trades as a taker.
This is also known as a POST-ONLY order.

Other info:

  • Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty.

  • Any order with an icebergQty MUST have timeInForce set to GTC.

  • For STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT_LIMIT and TAKE_PROFIT orders, trailingDelta can be combined with stopPrice.

  • MARKET orders using quoteOrderQty will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty.
    Trigger order price rules against market price for both MARKET and LIMIT versions:

  • Price above market price: STOP_LOSS BUY, TAKE_PROFIT SELL

  • Price below market price: STOP_LOSS SELL, TAKE_PROFIT BUY

Data Source:
Matching Engine

Response ACK:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "orderListId": -1, //Unless OCO, value will be -1
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595
}

Response RESULT:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "orderListId": -1, //Unless OCO, value will be -1
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "0.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "workingTime": 1507725176595,
  "selfTradePreventionMode": "NONE"
}

Response FULL:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "orderListId": -1, //Unless OCO, value will be -1
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "0.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "workingTime": 1507725176595,
  "selfTradePreventionMode": "NONE",
  "fills": [
    {
      "price": "4000.00000000",
      "qty": "1.00000000",
      "commission": "4.00000000",
      "commissionAsset": "USDT",
      "tradeId": 56
    },
    {
      "price": "3999.00000000",
      "qty": "5.00000000",
      "commission": "19.99500000",
      "commissionAsset": "USDT",
      "tradeId": 57
    },
    {
      "price": "3998.00000000",
      "qty": "2.00000000",
      "commission": "7.99600000",
      "commissionAsset": "USDT",
      "tradeId": 58
    },
    {
      "price": "3997.00000000",
      "qty": "1.00000000",
      "commission": "3.99700000",
      "commissionAsset": "USDT",
      "tradeId": 59
    },
    {
      "price": "3995.00000000",
      "qty": "1.00000000",
      "commission": "3.99500000",
      "commissionAsset": "USDT",
      "tradeId": 60
    }
  ]
}

Conditional fields in Order Responses

There are fields in the order responses (e.g. order placement, order query, order cancellation) that appear only if certain conditions are met.

These fields can apply to OCO Orders.

The fields are listed below:

Field Description Visibility conditions Examples
icebergQty Quantity for the iceberg order Appears only if the parameter icebergQty was sent in the request. "icebergQty": "0.00000000"
preventedMatchId When used in combination with symbol, can be used to query a prevented match. Appears only if the order expired due to STP. "preventedMatchId": 0
preventedQuantity Order quantity that expired due to STP Appears only if the order expired due to STP. "preventedQuantity": "1.200000"
stopPrice Price when the algorithmic order will be triggered Appears for STOP_LOSS. TAKE_PROFIT, STOP_LOSS_LIMIT and TAKE_PROFIT_LIMIT orders. "stopPrice": "23500.00000000"
strategyId Can be used to label an order that’s part of an order strategy. Appears if the parameter was populated in the request. "strategyId": 37463720
strategyType Can be used to label an order that is using an order strategy. Appears if the parameter was populated in the request. "strategyType": 1000000
trailingDelta Delta price change required before order activation Appears for Trailing Stop Orders. "trailingDelta": 10
trailingTime Time when the trailing order is now active and tracking price changes Appears only for Trailing Stop Orders. "trailingTime": -1

Test new order (TRADE)

POST /api/v3/order/test (HMAC SHA256)

Test new order creation and signature/recvWindow long.
Creates and validates a new order but does not send it into the matching engine.

Weight:
1

Parameters:

Same as POST /api/v3/order

Data Source:
Memory

Response:

Query order (USER_DATA)

GET /api/v3/order (HMAC SHA256)

Check an order’s status.

Weight:
2

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO
origClientOrderId STRING NO
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Notes:

  • Either orderId or origClientOrderId must be sent.
  • For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.

Data Source:
Memory => Database

Response:

{
  "symbol": "LTCBTC",
  "orderId": 1,
  "orderListId": -1                 // This field will always have a value of -1 if not an OCO.
  "clientOrderId": "myOrder1",
  "price": "0.1",
  "origQty": "1.0",
  "executedQty": "0.0",
  "cummulativeQuoteQty": "0.0",
  "status": "NEW",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "BUY",
  "stopPrice": "0.0",
  "icebergQty": "0.0",
  "time": 1499827319559,
  "updateTime": 1499827319559,
  "isWorking": true,
  "workingTime":1499827319559,
  "origQuoteOrderQty": "0.000000",
  "selfTradePreventionMode": "NONE"
}

Note: The payload above does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

Cancel order (TRADE)

DELETE /api/v3/order  (HMAC SHA256)

Cancel an active order.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO
origClientOrderId STRING NO
newClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default.
cancelRestrictions ENUM NO Supported values:
ONLY_NEW — Cancel will succeed if the order status is NEW.
ONLY_PARTIALLY_FILLED — Cancel will succeed if order status is PARTIALLY_FILLED.
recvWindow LONG NO The value cannot be greater than 60000.
timestamp LONG YES

Either orderId or origClientOrderId must be sent.
If both parameters are sent, orderId takes precedence.

Data Source:
Matching Engine

Response:

{
  "symbol": "LTCBTC",
  "origClientOrderId": "myOrder1",
  "orderId": 4,
  "orderListId": -1, //Unless part of an OCO, the value will always be -1.
  "clientOrderId": "cancelMyOrder1",
  "price": "2.00000000",
  "origQty": "1.00000000",
  "executedQty": "0.00000000",
  "cummulativeQuoteQty": "0.00000000",
  "status": "CANCELED",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "BUY",
  "selfTradePreventionMode": "NONE"
}

Note: The payload above does not show all fields that can appear in the order response. Please refer to Conditional fields in Order Responses.

Regarding cancelRestrictions

  • If the cancelRestrictions value is not any of the supported values, the error will be:
{
    "code": -1145,
    "msg": "Invalid cancelRestrictions"
}
  • If the order did not pass the conditions for cancelRestrictions, the error will be:
{
    "code": -2011,
    "msg": "Order was not canceled due to cancel restrictions."
}

Cancel All Open Orders on a Symbol (TRADE)

DELETE /api/v3/openOrders (HMAC SHA256)

Cancels all active orders on a symbol.
This includes OCO orders.

Weight
1

Name Type Mandatory Description
symbol STRING YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Matching Engine

Response

[
  {
    "symbol": "BTCUSDT",
    "origClientOrderId": "E6APeyTJvkMvLMYMqu1KQ4",
    "orderId": 11,
    "orderListId": -1,
    "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
    "price": "0.089853",
    "origQty": "0.178622",
    "executedQty": "0.000000",
    "cummulativeQuoteQty": "0.000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "selfTradePreventionMode": "NONE"
  },
  {
    "symbol": "BTCUSDT",
    "origClientOrderId": "A3EF2HCwxgZPFMrfwbgrhv",
    "orderId": 13,
    "orderListId": -1,
    "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
    "price": "0.090430",
    "origQty": "0.178622",
    "executedQty": "0.000000",
    "cummulativeQuoteQty": "0.000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "selfTradePreventionMode": "NONE"
  },
  {
    "orderListId": 1929,
    "contingencyType": "OCO",
    "listStatusType": "ALL_DONE",
    "listOrderStatus": "ALL_DONE",
    "listClientOrderId": "2inzWQdDvZLHbbAmAozX2N",
    "transactionTime": 1585230948299,
    "symbol": "BTCUSDT",
    "orders": [
      {
        "symbol": "BTCUSDT",
        "orderId": 20,
        "clientOrderId": "CwOOIPHSmYywx6jZX77TdL"
      },
      {
        "symbol": "BTCUSDT",
        "orderId": 21,
        "clientOrderId": "461cPg51vQjV3zIMOXNz39"
      }
    ],
    "orderReports": [
      {
        "symbol": "BTCUSDT",
        "origClientOrderId": "CwOOIPHSmYywx6jZX77TdL",
        "orderId": 20,
        "orderListId": 1929,
        "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
        "price": "0.668611",
        "origQty": "0.690354",
        "executedQty": "0.000000",
        "cummulativeQuoteQty": "0.000000",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "STOP_LOSS_LIMIT",
        "side": "BUY",
        "stopPrice": "0.378131",
        "icebergQty": "0.017083",
        "selfTradePreventionMode": "NONE"
      },
      {
        "symbol": "BTCUSDT",
        "origClientOrderId": "461cPg51vQjV3zIMOXNz39",
        "orderId": 21,
        "orderListId": 1929,
        "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
        "price": "0.008791",
        "origQty": "0.690354",
        "executedQty": "0.000000",
        "cummulativeQuoteQty": "0.000000",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "LIMIT_MAKER",
        "side": "BUY",
        "icebergQty": "0.639962",
        "selfTradePreventionMode": "NONE"
      }
    ]
  }
]

Cancel an Existing Order and Send a New Order (TRADE)

POST /api/v3/order/cancelReplace

Cancels an existing order and places a new order on the same symbol.

Filters and Order Count are evaluated before the processing of the cancellation and order placement occurs.

A new order that was not attempted (i.e. when newOrderResult: NOT_ATTEMPTED ), will still increase the order count by 1.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
side ENUM YES
type ENUM YES
cancelReplaceMode ENUM YES The allowed values are:
STOP_ON_FAILURE — If the cancel request fails, the new order placement will not be attempted.
ALLOW_FAILURE — new order placement will be attempted even if cancel request fails.
timeInForce ENUM NO
quantity DECIMAL NO
quoteOrderQty DECIMAL NO
price DECIMAL NO
cancelNewClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default.
cancelOrigClientOrderId STRING NO Either the cancelOrigClientOrderId or cancelOrderId must be provided. If both are provided, cancelOrderId takes precedence.
cancelOrderId LONG NO Either the cancelOrigClientOrderId or cancelOrderId must be provided. If both are provided, cancelOrderId takes precedence.
newClientOrderId STRING NO Used to identify the new order.
strategyId INT NO
strategyType INT NO The value cannot be less than 1000000.
stopPrice DECIMAL NO
trailingDelta LONG NO
icebergQty DECIMAL NO
newOrderRespType ENUM NO Allowed values:
ACK, RESULT, FULL
MARKET and LIMIT orders types default to FULL; all other orders default to ACK
selfTradePreventionMode ENUM NO The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.
cancelRestrictions ENUM NO Supported values:
ONLY_NEW — Cancel will succeed if the order status is NEW.
ONLY_PARTIALLY_FILLED — Cancel will succeed if order status is ONLY_PARTIALLY_FILLED. For more information please refer to Regarding cancelRestrictions
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Similar to POST /api/v3/order, additional mandatory parameters are determined by type.

Response format varies depending on whether the processing of the message succeeded, partially succeeded, or failed.

Data Source:
Matching Engine

Response SUCCESS:

//Both the cancel order placement and new order placement succeeded.
{
  "cancelResult": "SUCCESS",
  "newOrderResult": "SUCCESS",
  "cancelResponse": {
    "symbol": "BTCUSDT",
    "origClientOrderId": "DnLo3vTAQcjha43lAZhZ0y",
    "orderId": 9,
    "orderListId": -1,
    "clientOrderId": "osxN3JXAtJvKvCqGeMWMVR",
    "price": "0.01000000",
    "origQty": "0.000100",
    "executedQty": "0.00000000",
    "cummulativeQuoteQty": "0.00000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "SELL",
    "selfTradePreventionMode": "NONE"
  },
  "newOrderResponse": {
    "symbol": "BTCUSDT",
    "orderId": 10,
    "orderListId": -1,
    "clientOrderId": "wOceeeOzNORyLiQfw7jd8S",
    "transactTime": 1652928801803,
    "price": "0.02000000",
    "origQty": "0.040000",
    "executedQty": "0.00000000",
    "cummulativeQuoteQty": "0.00000000",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "workingTime": 1669277163808,
    "fills": [],
    "selfTradePreventionMode": "NONE"
  }
}

Response when Cancel Order Fails with STOP_ON FAILURE:

{
  "code": -2022,
  "msg": "Order cancel-replace failed.",
  "data": {
    "cancelResult": "FAILURE",
    "newOrderResult": "NOT_ATTEMPTED",
    "cancelResponse": {
      "code": -2011,
      "msg": "Unknown order sent."
    },
    "newOrderResponse": null
  }
}

Response when Cancel Order Succeeds but New Order Placement Fails:

{
  "code": -2021,
  "msg": "Order cancel-replace partially failed.",
  "data": {
    "cancelResult": "SUCCESS",
    "newOrderResult": "FAILURE",
    "cancelResponse": {
      "symbol": "BTCUSDT",
      "origClientOrderId": "86M8erehfExV8z2RC8Zo8k",
      "orderId": 3,
      "orderListId": -1,
      "clientOrderId": "G1kLo6aDv2KGNTFcjfTSFq",
      "price": "0.006123",
      "origQty": "10000.000000",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "SELL",
      "selfTradePreventionMode": "NONE"
    },
    "newOrderResponse": {
      "code": -2010,
      "msg": "Order would immediately match and take."
    }
  }
}

Response when Cancel Order fails with ALLOW_FAILURE:

{
  "code": -2021,
  "msg": "Order cancel-replace partially failed.",
  "data": {
    "cancelResult": "FAILURE",
    "newOrderResult": "SUCCESS",
    "cancelResponse": {
      "code": -2011,
      "msg": "Unknown order sent."
    },
    "newOrderResponse": {
      "symbol": "BTCUSDT",
      "orderId": 11,
      "orderListId": -1,
      "clientOrderId": "pfojJMg6IMNDKuJqDxvoxN",
      "transactTime": 1648540168818
    }
  }
}

Response when both Cancel Order and New Order Placement fail:

{
  "code": -2022,
  "msg": "Order cancel-replace failed.",
  "data": {
    "cancelResult": "FAILURE",
    "newOrderResult": "FAILURE",
    "cancelResponse": {
      "code": -2011,
      "msg": "Unknown order sent."
    },
    "newOrderResponse": {
      "code": -2010,
      "msg": "Order would immediately match and take."
    }
  }
}

Note: The payload above does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

Current open orders (USER_DATA)

GET /api/v3/openOrders  (HMAC SHA256)

Get all open orders on a symbol. Careful when accessing this with no symbol.

Weight:
3 for a single symbol; 40 when the symbol parameter is omitted

Parameters:

Name Type Mandatory Description
symbol STRING NO
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If the symbol is not sent, orders for all symbols will be returned in an array.

Data Source:
Memory => Database

Response:

[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "orderListId": -1, //Unless OCO, the value will always be -1
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true,
    "origQuoteOrderQty": "0.000000",
    "workingTime": 1499827319559,
    "selfTradePreventionMode": "NONE"
  }
]

Note: The payload above does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

All orders (USER_DATA)

GET /api/v3/allOrders (HMAC SHA256)

Get all account orders; active, canceled, or filled.

Weight:
10 with symbol

Data Source:
Database

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Notes:

  • If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.
  • For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.
  • If startTime and/or endTime provided, orderId is not required.

Response:

[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "orderListId": -1, //Unless OCO, the value will always be -1
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true,
    "origQuoteOrderQty": "0.000000",
    "workingTime": 1499827319559,
    "selfTradePreventionMode": "NONE",
  }
]

Note: The payload above does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

New OCO (TRADE)

POST /api/v3/order/oco (HMAC SHA256)

Weight: 1

Send in a new OCO

Parameters:

Name Type Mandatory Description
symbol STRING YES
listClientOrderId STRING NO A unique Id for the entire orderList
side ENUM YES
quantity DECIMAL YES
limitClientOrderId STRING NO A unique Id for the limit order
price DECIMAL YES
limitStrategyId INT NO
limitStrategyType INT NO The value cannot be less than 1000000.
limitIcebergQty DECIMAL NO Used to make the LIMIT_MAKER leg an iceberg order.
trailingDelta LONG NO
stopClientOrderId STRING NO A unique Id for the stop loss/stop loss limit leg
stopPrice DECIMAL YES
stopStrategyId INT NO
stopStrategyType INT NO The value cannot be less than 1000000.
stopLimitPrice DECIMAL NO If provided, stopLimitTimeInForce is required.
stopIcebergQty DECIMAL NO Used with STOP_LOSS_LIMIT leg to make an iceberg order.
stopLimitTimeInForce ENUM NO Valid values are GTC/FOK/IOC
newOrderRespType ENUM NO Set the response JSON.
selfTradePreventionMode ENUM NO The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Additional Info:

  • Price Restrictions:
    • SELL: Limit Price > Last Price > Stop Price
    • BUY: Limit Price < Last Price < Stop Price
  • Quantity Restrictions:
    • Both legs must have the same quantity.
    • ICEBERG quantities however do not have to be the same
  • Order Rate Limit
    • OCO counts as 2 orders against the order rate limit.

Data Source:
Matching Engine

Response:

{
  "orderListId": 0,
  "contingencyType": "OCO",
  "listStatusType": "EXEC_STARTED",
  "listOrderStatus": "EXECUTING",
  "listClientOrderId": "JYVpp3F0f5CAG15DhtrqLp",
  "transactionTime": 1563417480525,
  "symbol": "LTCBTC",
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "clientOrderId": "Kk7sqHb9J6mJWTMDVW7Vos"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "clientOrderId": "xTXKaGYd4bluPVp78IVRvl"
    }
  ],
  "orderReports": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "orderListId": 0,
      "clientOrderId": "Kk7sqHb9J6mJWTMDVW7Vos",
      "transactTime": 1563417480525,
      "price": "0.000000",
      "origQty": "0.624363",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "STOP_LOSS",
      "side": "BUY",
      "stopPrice": "0.960664",
      "workingTime": -1,
      "selfTradePreventionMode": "NONE"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "orderListId": 0,
      "clientOrderId": "xTXKaGYd4bluPVp78IVRvl",
      "transactTime": 1563417480525,
      "price": "0.036435",
      "origQty": "0.624363",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "BUY",
      "workingTime": 1563417480525,
      "selfTradePreventionMode": "NONE"
    }
  ]
}

Cancel OCO (TRADE)

DELETE /api/v3/orderList (HMAC SHA256)

Weight: 1

Cancel an entire Order List

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderListId LONG NO Either orderListId or listClientOrderId must be provided
listClientOrderId STRING NO Either orderListId or listClientOrderId must be provided
newClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Additional notes:

  • Canceling an individual leg will cancel the entire OCO
  • If both orderListId and listClientOrderId are sent, orderListId takes precedence.

Data Source:
Matching Engine

Response

{
  "orderListId": 0,
  "contingencyType": "OCO",
  "listStatusType": "ALL_DONE",
  "listOrderStatus": "ALL_DONE",
  "listClientOrderId": "C3wyj4WVEktd7u9aVBRXcN",
  "transactionTime": 1574040868128,
  "symbol": "LTCBTC",
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "clientOrderId": "pO9ufTiFGg3nw2fOdgeOXa"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "clientOrderId": "TXOvglzXuaubXAaENpaRCB"
    }
  ],
  "orderReports": [
    {
      "symbol": "LTCBTC",
      "origClientOrderId": "pO9ufTiFGg3nw2fOdgeOXa",
      "orderId": 2,
      "orderListId": 0,
      "clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
      "price": "1.00000000",
      "origQty": "10.00000000",
      "executedQty": "0.00000000",
      "cummulativeQuoteQty": "0.00000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "STOP_LOSS_LIMIT",
      "side": "SELL",
      "stopPrice": "1.00000000",
      "selfTradePreventionMode": "NONE"
    },
    {
      "symbol": "LTCBTC",
      "origClientOrderId": "TXOvglzXuaubXAaENpaRCB",
      "orderId": 3,
      "orderListId": 0,
      "clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
      "price": "3.00000000",
      "origQty": "10.00000000",
      "executedQty": "0.00000000",
      "cummulativeQuoteQty": "0.00000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "SELL",
      "selfTradePreventionMode": "NONE"
    }
  ]
}

Query OCO (USER_DATA)

GET /api/v3/orderList (HMAC SHA256)

Weight: 2

Retrieves a specific OCO based on provided optional parameters

Parameters:

Name Type Mandatory Description
orderListId LONG NO Either orderListId or listClientOrderId must be provided
origClientOrderId STRING NO Either orderListId or listClientOrderId must be provided
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Database

Response:

{
  "orderListId": 27,
  "contingencyType": "OCO",
  "listStatusType": "EXEC_STARTED",
  "listOrderStatus": "EXECUTING",
  "listClientOrderId": "h2USkA5YQpaXHPIrkd96xE",
  "transactionTime": 1565245656253,
  "symbol": "LTCBTC",
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 4,
      "clientOrderId": "qD1gy3kc3Gx0rihm9Y3xwS"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 5,
      "clientOrderId": "ARzZ9I00CPM8i3NhmU9Ega"
    }
  ]
}

Query all OCO (USER_DATA)

GET /api/v3/allOrderList (HMAC SHA256)

Weight: 10

Retrieves all OCO based on provided optional parameters

Parameters

Name Type Mandatory Description
fromId LONG NO If supplied, neither startTime or endTime can be provided
startTime LONG NO
endTime LONG NO
limit INT NO Default Value: 500; Max Value: 1000
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Database

Response:

[
  {
    "orderListId": 29,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "amEEAXryFzFwYF1FeRpUoZ",
    "transactionTime": 1565245913483,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 4,
        "clientOrderId": "oD7aesZqjEGlZrbtRpy5zB"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 5,
        "clientOrderId": "Jr1h6xirOxgeJOUuYQS7V3"
      }
    ]
  },
  {
    "orderListId": 28,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "hG7hFNxJV6cZy3Ze4AUT4d",
    "transactionTime": 1565245913407,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 2,
        "clientOrderId": "j6lFOfbmFMRjTYA7rRJ0LP"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 3,
        "clientOrderId": "z0KCjOdditiLS5ekAFtK81"
      }
    ]
  }
]

Query Open OCO (USER_DATA)

GET /api/v3/openOrderList (HMAC SHA256)

Weight: 3

Parameters

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Database

Response:

[
  {
    "orderListId": 31,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "wuB13fmulKj3YjdqWEcsnp",
    "transactionTime": 1565246080644,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 4,
        "clientOrderId": "r3EH2N76dHfLoSZWIUw1bT"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 5,
        "clientOrderId": "Cv1SnyPD3qhqpbjpYEHbd2"
      }
    ]
  }
]

Account information (USER_DATA)

GET /api/v3/account (HMAC SHA256)

Get current account information.

Weight:
10

Parameters:

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Memory => Database

Response:

{
  "makerCommission": 15,
  "takerCommission": 15,
  "buyerCommission": 0,
  "sellerCommission": 0,
  "commissionRates": {
    "maker": "0.00150000",
    "taker": "0.00150000",
    "buyer": "0.00000000",
    "seller": "0.00000000"
  },
  "canTrade": true,
  "canWithdraw": true,
  "canDeposit": true,
  "brokered":false,
  "requireSelfTradePrevention": false,
  "updateTime": 123456789,
  "accountType": "SPOT",
  "balances": [
    {
      "asset": "BTC",
      "free": "4723846.89208129",
      "locked": "0.00000000"
    },
    {
      "asset": "LTC",
      "free": "4763368.68006011",
      "locked": "0.00000000"
    }
  ],
    "permissions": [
    "SPOT"
  ]
}

Account trade list (USER_DATA)

GET /api/v3/myTrades  (HMAC SHA256)

Get trades for a specific account and symbol.

Weight:
10 with symbol

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO This can only be used in combination with symbol.
startTime LONG NO
endTime LONG NO
fromId LONG NO TradeId to fetch from. Default gets most recent trades.
limit INT NO Default 500; max 1000.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Notes:

  • If fromId is set, it will get trades >= that fromId.
    Otherwise most recent trades are returned.
  • The time between startTime and endTime can’t be longer than 24 hours.
  • These are the supported combinations of all parameters:
    • symbol
    • symbol + orderId
    • symbol + startTime
    • symbol + endTime
    • symbol + fromId
    • symbol + startTime + endTime
    • symbol+ orderId + fromId

Data Source:
Memory => Database

Response:

[
  {
    "symbol": "BNBBTC",
    "id": 28457,
    "orderId": 100234,
    "orderListId": -1,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "commission": "10.10000000",
    "commissionAsset": "BNB",
    "time": 1499865549590,
    "isBuyer": true,
    "isMaker": false,
    "isBestMatch": true
  }
]

Query Current Order Count Usage (TRADE)

GET /api/v3/rateLimit/order

Displays the user’s current order count usage for all intervals.

Weight:
20

Parameters:

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Memory

Response:

[

  {
    "rateLimitType": "ORDERS",
    "interval": "SECOND",
    "intervalNum": 10,
    "limit": 50,
    "count": 0
  },
  {
    "rateLimitType": "ORDERS",
    "interval": "DAY",
    "intervalNum": 1,
    "limit": 160000,
    "count": 0
  }
]

Query Prevented Matches (USER_DATA)

GET /api/v3/myPreventedMatches

Displays the list of orders that were expired due to STP.

These are the combinations supported:

  • symbol + preventedMatchId
  • symbol + orderId
  • symbol + orderId + fromPreventedMatchId (limit will default to 500)
  • symbol + orderId + fromPreventedMatchId + limit

Parameters:

Name Type Mandatory Description
symbol STRING YES
preventedMatchId LONG NO
orderId LONG NO
fromPreventedMatchId LONG NO
limit INT NO Default: 500; Max: 1000
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Weight

Case Weight
If symbol is invalid 1
Querying by preventedMatchId 1
Querying by orderId 10

Data Source:

Database

Response:

[
  {
    "symbol": "BTCUSDT",
    "preventedMatchId": 1,
    "takerOrderId": 5,
    "makerOrderId": 3,
    "tradeGroupId": 1,
    "selfTradePreventionMode": "EXPIRE_MAKER",
    "price": "1.100000",
    "makerPreventedQuantity": "1.300000",
    "transactTime": 1669101687094
  }
]

User data stream endpoints

Specifics on how user data streams work can be found here.

Start user data stream (USER_STREAM)

POST /api/v3/userDataStream

Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent.

Weight:
1

Parameters:
NONE

Data Source:
Memory

Response:

{
  "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}

Keepalive user data stream (USER_STREAM)

PUT /api/v3/userDataStream

Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It’s recommended to send a ping about every 30 minutes.

Weight:
1

Data Source»
Memory

Parameters:

Name Type Mandatory Description
listenKey STRING YES

Response:

Close user data stream (USER_STREAM)

DELETE /api/v3/userDataStream

Close out a user data stream.

Weight:
1

Parameters:

Name Type Mandatory Description
listenKey STRING YES

Data Source:
Memory

Response:

Цель этого руководства — мягко познакомить вас с Binance API без написания ни единой строчки кода

Binance API — Спотовая торговля с помощью Postman.

Понимание и использование API для торговли криптовалютой может открыть целый мир возможностей, когда дело доходит до входа и выхода из позиций. Обладая некоторыми простыми знаниями в области написания кода, вы можете подключиться к серверной части биржи, чтобы автоматизировать свои торговые стратегии.

Обойдя через API веб-сайт, вы можете гораздо быстрее найти соответствующий движок для высокопроизводительных приложений.

Цель этой серии руководств — познакомить вас с REST API Binance и научить, как с ним взаимодействовать.

К концу ознакомления с руководством вы должны быть уверены в своей способности запрашивать через API информацию о рынках и вашей позиции и размещать ряд различных типов ордеров.

В этой статье мы будем использовать Postman для связи с биржей. Не волнуйтесь — мы не будем рисковать реальными деньгами.

Информация для начинающих пользователей биржи Бинанс / Binance

Бинанс является одной из самых известных финансовых платформ во всем мире. Миллионы пользователей торгуют на ней фиатом и криптовалютами ежедневно. Как правило, эта биржа показывает самый большой 24-часовой торговый объем среди конкурентов, так что — поздравляем! Завести аккаунт именно на Бинансе было хорошей идеей!
Чтобы следить за динамикой своего кошелька на этой площадке и выставлять такие заказы, как стоп лосс, тейк профит или трейлинг стоп лосс, давайте добавим ваш Бинанс аккаунт к приложению Good Crypto. Для этого нам понадобится создать API ключ — однако, секундочку. А что же такое этот самый API ключ?

Что такое API ключ?

API используется не только в криптовалютах, но и в любых других приложениях. Это аббревиатура английского application programming interface

означает
интерфейс взаимодействия приложений.
API позволяет двум приложениям “видеть” и “взаимодействовать” друг с другом. API ключ — это “визитная карточка”, которая позволяет двум приложениям “узнавать” друг друга. Связать два приложения через API ключ — это как познакомить двух ваших друзей друг с другом. После того, как вы их представили — они смогут общаться дальше уже без вас.

Бинанс и Good Crypto — это два отдельных приложения, поэтому их нужно связать друг с другом, чтобы приложение Good Crypto могло импортировать заказы и балансы с Бинанса, а также отправлять заказы на Бинанс.

Чтобы связать одно приложение с другим, вам как раз понадобится API ключ. Кстати, если у вас еще нет аккаунта на Бинансе, вы можете использовать нашу реферальную ссылку при его создании, чтобы получать 20% кэшбэка от всех комиссий на Бинансе пожизненно!

Итак, вы наверняка слышали про публичные и приватные ключи, когда речь заходила про блокчейн-кошельки. API ключи, которые вы создаете на бирже, это как раз те самые два ключа. Да и функциональность у них тоже очень похожа.

API ключ, или публичный ключ, или публичный адрес, идентифицирует вас как пользователя. Это что-то сродни email-адресу, который вы используете для создания аккаунта.

А вот секретный ключ, видимый только вам, подписывает запросы, которые генерируются с помощью публичного API ключа, и доказывает, что этот ключ принадлежит именно вам и никому другому с помощью математической логики асимметричного шифрования.

Безопасность

Так безопасно или нет добавлять API ключ с Бинанса в Good Crypto?

В целом, тот факт, что вы генерируете API ключ, создает хоть и маленький, но все же потенциальный риск для вашего аккаунта — но без паники, наша команда позаботилась о вашей безопасности.

Когда вы добавляете биржевой API ключ в наше приложение, этот ключ мгновенно шифруется на вашем устройстве и отправляется к нам на сервер в зашифрованном виде по безопасному каналу. После, ключ остается на хранении в нашей зашифрованной базе, к которой ни у кого нет доступа. Каналы взаимодействия между нашим приложением и нашими серверами всегда шифруются, и передаваемая информация не может быть перехвачена. Когда вы отсылаете свой заказ на биржу, вы даете приложению соответствующее указание, и мы отправляем запрос к нам на сервер. Через мгновение сервер размещает ваш заказ на бирже.

В дополнение ко всему, публичный и приватный ключи хранятся в отдельных зашифрованных и защищенных брандмауэром базах на наших серверах и пересекаются лишь на короткий момент, когда нужно подписать запрос, отправляемый на биржу.

Таким образом, API ключ максимально защищен, когда лежит внутри нашего приложения. Ваша главная задача — сделать так, чтобы никто другой не получил к нему доступа в другом месте. Поэтому критически важно НИКОГДА не пересылать его по незашифрованному каналу, а это значит — никаких email’ов с API ключом. Самый безопасный способ — отсканировать ключ в форме QR-кода своим телефоном с сайта биржи и забыть о нем (подробнее об этом — ниже).

Существует еще один уровень обеспечения безопасности, которым управляете вы, да, вы. Так как вы — тот самый человек, который определяет набор разрешенных действий для этого ключа, они называются permissions

или
разрешения
. Звучит сложно — но на деле это просто… Взгляните.

Для того, чтобы использовать Good Crypto, обычно требуется два типа разрешений: разрешение на импорт и отслеживание балансов (Read) и разрешение на отправку заказов на биржу (Write). Чтобы обеспечить полноценную работу нашего приложения, просто отметьте галочкой Read и Write в процессе создания ключа.

Но, пожалуйста, обратите внимание на то, что мы вам настоятельно НЕ рекомендуем отмечать галочкой графу Withdrawal (Вывод Средств). Нашему приложению не нужна эта опция, чтобы полноценно функционировать.

Процесс генерирования и добавления API ключа

WAPI

Ввод и вывод средств

Подробное описание будет чуть позже, пока что примеры с комментариями

from binance_api import Binance bot = Binance( API_KEY=’D7F…Ejj’, API_SECRET=’gwQ…u3A’ ) # Получение адреса для депозита print(bot.depositAddress(asset=’BTC’)) # Вывод средств print(bot.withdraw(asset=’XRP’, address=’1wsdsr234234242′, amount=12)) # История пополнений print(bot.depositHistory(asset=’BTC’)) print(bot.depositHistory()) # История выводов print(bot.withdrawHistory()) print(bot.withdrawHistory(asset=’ETH’)) # Узнать комиссию за вывод print(bot.withdrawFee(asset=’BTC’)) # Состояние аккаунта print(bot.accountStatus()) # Состояние биржи print(bot.systemStatus())

Тех. поддержка Бинанс фьючерс

Связаться с технической поддержкой можно, отправив запрос на этой странице https://www.binance.com/ru/support/requests/new

Многие вопросы рассмотрены в справочном центре https://www.binance.com/ru/support

Также представительства есть во многих социальных сетях, туда тоже можно обращаться:

https://www.facebook.com/binance

https://www.binance.com/ru/community

Tweets by binance

https://www.instagram.com/Binance/

https://vk.com/binance

Как торговать фьючерсами

Два основных направления при фьючерсной торговле:

  • Лонг позиция, когда трейдер покупает контракт с расчетом на будущий рост.
  • Шорт позиция, когда ставка делается на снижение цены.

Можно открывать длинные или короткие позиции с кредитным плечом, чтобы получить дополнительную прибыль на рынках с высокой волатильностью (риски также увеличиваются).

Руководство по началу торгов:

  • Пополнить счет фьючерсного аккаунта биржи (как это сделать, расскажем далее). Данная сумма будет выступать в качестве маржи.
  • Указать подходящее кредитное плечо (от 1 до 125 для Биткоина, до 75 — для альткоинов).
  • Выбрать нужный тип ордера, на продажу или на покупку.
  • Указать желаемое количество контрактов.

История транзакций, произведенных трейдером, расположена в нижней части торгового терминала.

Обзор биржи и инструкций по торговле:

Подробный обзор биржи Binance (Futures)

Binance Futures — площадка для торговли фьючерсными контрактами, запущенная криптобиржей Бинанс в 2019 году. Предоставляет возможность работы с фьючерсами и бессрочными контрактами и использования кредитного плеча до 125х. Есть демо-счет (тестнет) для пробной торговли без риска реальными активами.

Получите скидку на торговую комиссию в 10% на бирже Binance по коду «CRYPTOSLIVA» или по регистрации по этой ссылке

Отзывы Binance

Binance Futures имеет сугубо положительные отзывы. Пользователи отмечают высокий уровень безопасности, большой выбор контрактов для торговли, подробные руководства для новичков, достаточно широкий торговый функционал для создания лонг и шорт позиций, разные типы ордеров (маркет, лимитный, стоп-лимит).

Однако можно найти и отрицательные мнения. К примеру, на форумах упоминают ситуации с рыночными манипуляциями:

И еще:

Открытие большого количества сделок.

Открытие большого количества сделок, зачастую в разные стороны по коррелирующим активам, с последующей фиксацией только положительных сделок.

Например, покупка Биткоина и продажа Эфира. При любом раскладе одна из сделок выходит в плюс, ее трейдер закрывает и забирает свою долю прибыли. А убыточная сделка остается на счету. Это повторяется много раз, затем счет уже не выдерживает убытков и наступает ликвидация.

Признак такой схемы- на счету много сделок, открытых длительное время, а трейдер требует распределения прибыли после каждой положительной сделки.

Комиссии Binance Futures

Описание всех существующих комиссий для Binance Futures:

Тип действия Комиссионные сборы
Ввод Без комиссии
Вывод с фьючерсного счета на обычный Без комиссии
Вывод со спотового счета на внешний кошелек Зависит от валюты или способа вывода https://www.binance.com/ru/fee/depositFee
Трейдинг фьючерсами USDT-M Мейкер — от 0,02% до 0, тейкер — от 0,018% до 0 (уменьшается при помощи BNB)
Трейдинг фьючерсами COIN-M Мейкер — от 0,015% до -0,009%, тейкер — от 0,04% до 0,024% (уменьшается при помощи BNB)

Скачивание и установка Postman

Postman — это платформа для совместной работы API. Для нас это идеальная отправная точка — у нас будет доступ к коллекциям запросов Binance, которые мы будем тестировать без необходимости писать ни одной строчки кода.

Программа доступна для Mac, Windows и Linux. Перейдите на страницу загрузок Postman и загрузите .zip файл.

После этого найдите его в проводнике и установите. Запустите приложение, и все готово! Обратите внимание, что вы можете создать учетную запись для входа в систему, но это не обязательно. Если вы хотите пропустить этот шаг, просто выберите соответствующую опцию внизу окна.

Отличия от основной Binance

На фьючерсном рынке, в отличие от спотового, расчеты не закрываются моментально. Контрагенты, совершая сделку, заключают договор, по которому расчет должен осуществиться позже, в момент заранее заданной ликвидации позиции по цене исполнения. Трейдеры, оперируя контрактами, не владеют активом, торговля осуществляется только его стоимостью.

Другой важный нюанс — использование начальной и поддерживающей маржи для совершения сделки. Таким образом, на момент открытия позиции пользователь должен иметь обеспечение больше, чем указанная начальная маржа (индивидуальная для каждого контракта). Поддерживающая маржа — это уровень, ниже которого не может упасть сумма обеспечения и нереализованной прибыли. Если такое случится, то позиция автоматически ликвидируется.

Актуальные данные по начальной и поддерживающей маржи для разных контрактов можно посмотреть здесь: https://www.binance.com/ru/support/faq/360033161972

За автоматическую иквидацию взимается штраф (комиссия):

При этом пользователь имеет право в любой момент сам закрыть позицию, тогда штрафов не будет.

Еще одно ключевое отличие спотовой биржи от фьючерсной заключается в разнице цен. Цены на фьючерсы включают в себя дополнительные затраты на хранение, поэтому заметно отличаются от курсов спота. При помощи ставок финансирования Бинанс стремится сблизить эти уровни в долгосрочной перспективе. Ставки финансирования представляют собой регулярные выплаты трейдерам, торгующими с короткими или длинными позициями, исходя из разницы цен между деривативным и спотовым рынками. Финансирование осуществляется раз в 8 часов, в 3:00; 11:00 и 24:00.

Текущие ставки:

Токен BNB: обзор, как работает

Основной токен Binance Futures, как и основной площадки — криптовалюта BNB. Здесь точно так же можно использовать его основную функцию, то есть оплачивать с его помощью долю комиссионных сборов. Так, стандартная комиссия для мейкера составляет 0,02%, для тейкера 0,018%, а с помощью BNB можно снизить их до 0,016% и 0,0144% соответственно, и дальше по мере повышения VIP-уровня. На уровне VIP 9 комиссия нулевая.

Токен BNB торгуется, помимо Binance, на некоторых крупных криптовалютных биржах: KuCoin, HitBTC, BitForex, Gate и пр.

Как создать криптовалютный дашборд с помощью Plotly и API Binance

Упрощаем отслеживание активов

Binance предоставляет два типа доступа к API: реальный и тестовый.

Настраиваем реальный API Binance

Реальный API обеспечивает прямой доступ к аккаунту. В нем будут отражены любые сделки, совершенные через этот API. Поэтому использовать его следует с осторожностью.

Для начала нужно зарегистрироваться на Binance.

После регистрации вам будет предложено установить двухфакторную аутентификацию (2FA). Вы также можете подключить ее самостоятельно в настройках безопасности.

Затем переходим во вкладку API Management в настройках. Вам будет предложено установить метки для ключей API. Эта функция пригодится тем, у кого есть несколько ключей, связанных с одним аккаунтом.

Указываем метки и нажимаем Create API. После этого нужно пройти аутентификацию еще раз. Затем отобразятся API Key и Secret Key. Скопируйте их в безопасное место. По умолчанию получить доступ к ключам можно следующим способом, который можно изменить:

Мы будем использовать ключи как реального, так и тестового API, чтобы понять, как с ними работать. С целью не засорять реальный аккаунт установим доступ только для чтения для ключей реального API:

Сохранять ключи реального API мы будем в файл secret.cfg, как показано ниже. Не забывайте, что нельзя ни с кем делиться этим файлом.

[BINANCE]
ACTUAL_API_KEY = <your-actual-api-key>
ACTUAL_SECRET_KEY = <your-actual-secret-key>

Настраиваем тестовый API Binance

Тестовый API Binance полностью имитирует взаимодействие с реальным API. Рекомендуем для начала повзаимодействовать с ним, чтобы убедиться в корректности работы приложения.

Для начала необходимо войти в систему: https://testnet.binance.vision/ (на данный момент вход поддерживается только с GitHub).

Затем нажмите на Generate HMAC_SHA256 Key (Сгенерировать ключ HMAC_SHA256) и снова укажите метки для ключей. Отобразившиеся после создания ключи также скопируйте в безопасное место. Все подробности о тестовом API можно прочитать на главной странице.

Теперь добавим ключи тестового API в файл secret.cfg, как показано ниже:

[BINANCE]
ACTUAL_API_KEY = <your-actual-api-key>
ACTUAL_SECRET_KEY = <your-actual-secret-key>
TEST_API_KEY = <your-test-api-key>
TEST_SECRET_KEY = <your-test-secret-key>

Мы успешно настроили ключи реального и тестового API и сохранили их в файле secret.cfg. Теперь можно переходить к получению данных.

Как получить данные с помощью API Binance

Устанавливаем библиотеку python-binance

Binance не предоставляет библиотеку Python для взаимодействия с API. Поэтому мы воспользуемся популярным сторонним инструментом под названием python-binance.

Устанавливаем python-binance с помощью следующей команды:

$ pip install python-binance

Получаем информацию об аккаунте

В этом разделе мы воспользуемся тестовым аккаунтом. По умолчанию в нем будет отображаться баланс различных криптовалют. У python-binance нет доступа к тестовому API, поэтому мы поменяем URL-адрес конечной точки.

Код ниже предоставляет информацию о тестовом аккаунте:

# Импорт библиотек 
from binance.client import Client
import configparser

# Загрузка ключей из файла config
config = configparser.ConfigParser()
config.read_file(open('<path-to-your-config-file>'))
test_api_key = config.get('BINANCE', 'TEST_API_KEY')
test_secret_key = config.get('BINANCE', 'TEST_SECRET_KEY')

client = Client(test_api_key, test_secret_key)

client.API_URL = 'https://testnet.binance.vision/api'  # Это нужно, чтобы изменить URL-адрес конечной точки тестового аккаунта  

info = client.get_account()  # Получение информации об аккаунте

print(info)

Мы получаем такие важные данные, как тип аккаунта (accountType), баланс, разрешение и прочие.

Теперь получим баланс ETH:

balance = client.get_asset_balance(asset='ETH')

print(balance)

Библиотека python-binance предоставляет много возможностей. Подробную информацию о ней можно найти в документации.

Получаем архивные данные

Тестовый API выдает фиктивные архивные данные. Поэтому мы воспользуемся реальным API и его ключами.

Ниже показано, как получить стоимость ETH на Binance с самой ранней даты до текущего дня:

# Импорт библиотек 
from binance.client import Client
import configparser
import pandas as pd

# Загрузка ключей из файла config
config = configparser.ConfigParser()
config.read_file(open('<path-to-your-config-file>'))
actual_api_key = config.get('BINANCE', 'ACTUAL_API_KEY')
actual_secret_key = config.get('BINANCE', 'ACTUAL_SECRET_KEY')

client = Client(actual_api_key, actual_secret_key)

# Получение самой ранней доступной даты на Binance
earliest_timestamp = client._get_earliest_valid_timestamp('ETHUSDT', '1d')  # Здесь "ETHUSDT" - валютная пара, а "1d" - временной интервал
print(earliest_timestamp)

# Получение архивных данных (Candle data или Kline)
candle = client.get_historical_klines("ETHUSDT", "1d", earliest_timestamp, limit=1000)

print(candle[1])

Вывод выше представляет следующие параметры, упомянутые в документации Binance API:

Преобразовываем полученные данные в датафрейм и сохраняем его как файл CSV:

eth_df = pd.DataFrame(candle, columns=['dateTime', 'open', 'high', 'low', 'close', 'volume', 'closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol', 'takerBuyQuoteVol', 'ignore'])
eth_df.dateTime = pd.to_datetime(eth_df.dateTime, unit='ms')
eth_df.closeTime = pd.to_datetime(eth_df.closeTime, unit='ms')
eth_df.set_index('dateTime', inplace=True)
eth_df.to_csv('eth_candle.csv')

print(eth_df.tail(10))

Получаем данные в реальном времени

Чтобы передавать данные в реальном времени, можно воспользоваться WebSocket Binance. Вот как это сделать:

# Импорт библиотек 
from binance.client import Client
import configparser
from binance.websockets import BinanceSocketManager
from twisted.internet import reactor 

# Загрузка ключей из файла config
config = configparser.ConfigParser()
config.read_file(open('<path-to-your-config-file>'))
actual_api_key = config.get('BINANCE', 'ACTUAL_API_KEY')
actual_secret_key = config.get('BINANCE', 'ACTUAL_SECRET_KEY')

client = Client(actual_api_key, actual_secret_key)


def streaming_data_process(msg):
    """
    Function to process the received messages
    param msg: input message
    """
    print(f"message type: {msg['e']}")
    print(f"close price: {msg['c']}")
    print(f"best ask price: {msg['a']}")
    print(f"best bid price: {msg['b']}")
    print("---------------------------")
    
# Запуск WebSocket
bm = BinanceSocketManager(client)
conn_key = bm.start_symbol_ticker_socket('ETHUSDT', streaming_data_process)
bm.start()

Ниже показано, как остановить потоковую передачу данных и закрыть WebSocket:

# Остановка websocket
bm.stop_socket(conn_key)

# Websocket использует цикл reactor из библиотеки Twisted. Метод выше
# остановит соединение с веб-сокетом, но не цикл reactor, поэтому код может 
# выйти не сразу.

# Поэтому нужно указать
reactor.stop()

Итак, мы научились получать данные несколькими способами. Теперь можно переходить к созданию дашборда Plotly.

Как создать дашборд с помощью Plotly

В этом разделе мы создадим дашборд с помощью Plotly, который будет отслеживать криптовалютный портфель тестового аккаунта в реальном времени и изменять его общую стоимость в зависимости от получаемых данных.

Вот как будет выглядеть финальная версия дашборда. Детали внешнего вида можно изменить позднее:

В дашборд включены следующие функции:

  • Индикатор: общая стоимость портфеля в USDT.
  • Индикатор: общая стоимость портфеля в BTC.
  • Индикатор: конвертация BNB/USDT.
  • Круговая диаграмма: распределение портфеля (в USDT).
  • Столбчатая диаграмма: распределение токенов.

Теперь рассмотрим код.

  1. Импортируем все необходимые библиотеки:
# Импорт библиотек
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from binance.client import Client
import configparser
from binance.websockets import BinanceSocketManager
import time

2. Прочитываем все ключи, устанавливаем соединение и получаем информацию об аккаунте:

# Загрузка ключей из файла config
config = configparser.ConfigParser()
config.read_file(open(
    '/home/venom/GitHub/blog_code/building_cryptocurrency_dashboard_plotly_binanceAPI/secret.cfg'))
test_api_key = config.get('BINANCE', 'TEST_API_KEY')
test_secret_key = config.get('BINANCE', 'TEST_SECRET_KEY')

# Установка соединения
client = Client(test_api_key, test_secret_key)
client.API_URL = 'https://testnet.binance.vision/api'  # Это нужно, чтобы изменить URL-адрес конечной точки тестового аккаунт

# Получение информации об аккаунте для проверки баланса
info = client.get_account()  # Получение информации об аккаунте

# Сохранение различных токенов и соответствующих величин в списках
assets = []
values = []
for index in range(len(info['balances'])):
    for key in info['balances'][index]:
        if key == 'asset':
            assets.append(info['balances'][index][key])
        if key == 'free':
            values.append(info['balances'][index][key])


token_usdt = {}  # Словарь для хранения стоимости валютной пары в USDT
token_pairs = []  # Список для хранения различных пар токенов

# Создание пар токенов и сохранение их в список
for token in assets:
    if token != 'USDT':
        token_pairs.append(token + 'USDT')

3. Определяем функции, которые будут обрабатывать потоковые данные и рассчитывать показатели на их основе:

def streaming_data_process(msg):
    """
    Function to process the received messages and add latest token pair price
    into the token_usdt dictionary
    :param msg: input message
    """
    global token_usdt
    token_usdt[msg['s']] = msg['c']


def total_amount_usdt(assets, values, token_usdt):
    """
    Function to calculate total portfolio value in USDT
    :param assets: Assets list
    :param values: Assets quantity
    :param token_usdt: Token pair price dict
    :return: total value in USDT
    """
    total_amount = 0
    for i, token in enumerate(assets):
        if token != 'USDT':
            total_amount += float(values[i]) * float(
                token_usdt[token + 'USDT'])
        else:
            total_amount += float(values[i]) * 1
    return total_amount


def total_amount_btc(assets, values, token_usdt):
    """
    Function to calculate total portfolio value in BTC
    :param assets: Assets list
    :param values: Assets quantity
    :param token_usdt: Token pair price dict
    :return: total value in BTC
    """
    total_amount = 0
    for i, token in enumerate(assets):
        if token != 'BTC' and token != 'USDT':
            total_amount += float(values[i]) 
                            * float(token_usdt[token + 'USDT']) 
                            / float(token_usdt['BTCUSDT'])
        if token == 'BTC':
            total_amount += float(values[i]) * 1
        else:
            total_amount += float(values[i]) 
                            / float(token_usdt['BTCUSDT'])
    return total_amount


def assets_usdt(assets, values, token_usdt):
    """
    Function to convert all assets into equivalent USDT value
    :param assets: Assets list
    :param values: Assets quantity
    :param token_usdt: Token pair price dict
    :return: list of asset values in USDT
    """
    assets_in_usdt = []
    for i, token in enumerate(assets):
        if token != 'USDT':
            assets_in_usdt.append(
                float(values[i]) * float(token_usdt[token + 'USDT'])
            )
        else:
            assets_in_usdt.append(float(values[i]) * 1)
    return assets_in_usdt

4. Начинаем передавать данные в реальном времени:

# Потоковая передача данных для токенов в портфолио
bm = BinanceSocketManager(client)
for tokenpair in token_pairs:
    conn_key = bm.start_symbol_ticker_socket(tokenpair, streaming_data_process)
bm.start()
time.sleep(5)  # Это дает всем парам токенов достаточно времени, чтобы установить соединение

5. Определяем макет, графики и хостинг:

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.FLATLY])
server = app.server

app.layout = html.Div([
    html.Div([
        html.Div([
            dcc.Graph(
                id='figure-1',
                figure={
                    'data': [
                        go.Indicator(
                            mode="number",
                            value=total_amount_usdt(assets, values, token_usdt),
                        )
                    ],
                    'layout':
                        go.Layout(
                            title="Portfolio Value (USDT)"
                        )
                }
            )], style={'width': '30%', 'height': '300px',
                       'display': 'inline-block'}),
        html.Div([
            dcc.Graph(
                id='figure-2',
                figure={
                    'data': [
                        go.Indicator(
                            mode="number",
                            value=total_amount_btc(assets, values, token_usdt),
                            number={'valueformat': 'g'}
                        )
                    ],
                    'layout':
                        go.Layout(
                            title="Portfolio Value (BTC)"
                        )
                }
            )], style={'width': '30%', 'height': '300px',
                       'display': 'inline-block'}),
        html.Div([
            dcc.Graph(
                id='figure-3',
                figure={
                    'data': [
                        go.Indicator(
                            mode="number",
                            value=float(token_usdt['BNBUSDT']),
                            number={'valueformat': 'g'}
                        )
                    ],
                    'layout':
                        go.Layout(
                            title="BNB/USDT"
                        )
                }
            )],
            style={'width': '30%', 'height': '300px', 'display': 'inline-block'})
    ]),
    html.Div([
        html.Div([
            dcc.Graph(
                id='figure-4',
                figure={
                    'data': [
                        go.Pie(
                            labels=assets,
                            values=assets_usdt(assets, values, token_usdt),
                            hoverinfo="label+percent"
                        )
                    ],
                    'layout':
                        go.Layout(
                            title="Portfolio Distribution (in USDT)"
                        )
                }
            )], style={'width': '50%', 'display': 'inline-block'}),
        html.Div([
            dcc.Graph(
                id='figure-5',
                figure={
                    'data': [
                        go.Bar(
                            x=assets,
                            y=values,
                            name="Token Quantities For Different Assets",
                        )
                    ],
                    'layout':
                        go.Layout(
                            showlegend=False,
                            title="Tokens distribution"
                        )
                }
            )], style={'width': '50%', 'display': 'inline-block'}),
        dcc.Interval(
            id='1-second-interval',
            interval=1000,  # 1000 milliseconds
            n_intervals=0
        )
    ]),
])


@app.callback(Output('figure-1', 'figure'),
              Output('figure-2', 'figure'),
              Output('figure-3', 'figure'),
              Output('figure-4', 'figure'),
              Output('figure-5', 'figure'),
              Input('1-second-interval', 'n_intervals'))
def update_layout(n):
    figure1 = {
        'data': [
            go.Indicator(
                mode="number",
                value=total_amount_usdt(assets, values, token_usdt),
            )
        ],
        'layout':
            go.Layout(
                title="Portfolio Value (USDT)"
            )
    }
    figure2 = {
        'data': [
            go.Indicator(
                mode="number",
                value=total_amount_btc(assets, values, token_usdt),
                number={'valueformat': 'g'}
            )
        ],
        'layout':
            go.Layout(
                title="Portfolio Value (BTC)"
            )
    }
    figure3 = {
        'data': [
            go.Indicator(
                mode="number",
                value=float(token_usdt['BNBUSDT']),
                number={'valueformat': 'g'}
            )
        ],
        'layout':
            go.Layout(
                title="BNB/USDT"
            )
    }
    figure4 = {
        'data': [
            go.Pie(
                labels=assets,
                values=assets_usdt(assets, values, token_usdt),
                hoverinfo="label+percent"
            )
        ],
        'layout':
            go.Layout(
                title="Portfolio Distribution (in USDT)"
            )
    }
    figure5 = {
        'data': [
            go.Bar(
                x=assets,
                y=values,
                name="Token Quantities For Different Assets",
            )
        ],
        'layout':
            go.Layout(
                showlegend=False,
                title="Tokens distribution"
            )
    }

    return figure1, figure2, figure3, figure4, figure5


if __name__ == '__main__':
    app.run_server(host='127.0.0.1', port='8050', debug=True)

Вот и все! Этот код позволяет отслеживать криптовалютный портфель тестового аккаунта. Его можно с легкостью настроить и для реального аккаунта без изменения URL-адреса конечной точки.

Весь код можно найти в репозитории на GitHub.

Читайте также:

  • Разработка инфраструктуры и торговых ботов для ИИ-трейдинга
  • 4 принципа успешной поисковой системы и не только
  • Введение в блокчейн  -  основу криптовалют

Читайте нас в Telegram, VK и Яндекс.Дзен


Перевод статьи Mayank Vadsola: Building a cryptocurrency dashboard using Plotly and Binance API

Change Log

2023-05-18

  • New endpoints for Wallet:
    • POST /sapi/v1/capital/deposit/credit-apply: apply deposit credit for expired address

2023-05-09

  • New endpoints for Portfolio Margin:
    • GET /sapi/v1/portfolio/asset-index-price: query portfolio margin asset index price
  • Update endpoints for Wallet:
    • POST /sapi/v1/asset/transfer: add enum MAIN_PORTFOLIO_MARGIN and PORTFOLIO_MARGIN_MAIN

2023-04-20

  • New endpoints for Sub-Account:
    • GET /sapi/v1/managed-subaccount/deposit/address: get managed sub-account deposit address
  • Update endpoints for VIP Loans:
    • GET /sapi/v1/loan/vip/ongoing/orders: add fields totalCollateralValueAfterHaircut and lockedCollateralValue

2023-04-18

  • New endpoints for Spot Algo:
    • POST /sapi/v1/algo/spot/newOrderTwap to support new order
    • DELETE /sapi/v1/algo/spot/order to support cancel Algo order
    • GET /sapi/v1/algo/spot/openOrders to support query Algo open orders
    • GET /sapi/v1/algo/spot/historicalOrders to support query Algo historical orders
    • GET /sapi/v1/algo/spot/subOrders to support query Algo sub orders for a specified algoId

2023-03-23

  • Update endpoints for Sub-Account:
    • GET /sapi/v1/managed-subaccount/queryTransLogForInvestor: Add response field tranId
    • GET /sapi/v1/managed-subaccount/queryTransLogForTradeParent: Add response field tranId
  • New endpoints for Sub-Account:
    • GET /sapi/v1/managed-subaccount/info: query investor’s managed sub-account list
    • GET /sapi/v1/sub-account/transaction-statistics: Query sub-account transaction tatistics

2023-03-13

Notice: All changes are being rolled out gradually to all our servers, and may take a week to complete.

GENERAL CHANGES

  • The error messages for certain issues have been improved for easier troubleshooting.
Situation Old Error Message New Error Message
An account cannot place or cancel an order, due to trading ability disabled. This action is disabled on this account. This account may not place or cancel orders.
When the permissions configured on the symbol do not match the permissions on the account. This symbol is not permitted for this account.
When the account tries to place an order on a symbol it has no permissions for. This symbol is restricted for this account.
Placing an order when symbol is not TRADING. Unsupported order combination. This order type is not possible in this trading phase.
Placing an order with timeinForce=IOC or FOK on a trading phase that does not support it. Limit orders require GTC for this phase.
  • Fixed error message for querying archived orders:
    • Previously, If an archived order (i.e. order with status CANCELED or EXPIRED where executedQty == 0 that occurred more than 90 days in the past.) is queried, the error message would be:
      • {"code": -2013,"msg": "Order does not exist."}
    • Now, the error message is:
      • {"code": -2026,"msg": "Order was canceled or expired with no executed qty over 90 days ago and has been archived."}
  • Behavior for API requests with startTime and endTime:
    • Previously some requests failed if the startTime == endTime.
    • Now, all API requests that accept startTime and endTime allow the parameters to be equal. This applies to the following requests:
      • Rest API
        • GET /api/v3/aggTrades
        • GET /api/v3/klines
        • GET /api/v3/allOrderList
        • GET /api/v3/allOrders
        • GET /api/v3/myTrades

The following changes will take effect approximately a week from the release date, but the rest of the documentation has been updated to reflect the future changes:

  • Changes to Filter Evaluation:
    • Previous behavior: LOT_SIZE and MARKET_LOT_SIZE required that (quantityminQty) % stepSize == 0.
    • New behavior: This has now been changed to (quantity % stepSize) == 0.
  • Bug fix with reverse MARKET orders (i.e., MARKET using quoteOrderQty):
    • Previous behavior: Reverse market orders would always have the status FILLED even if the order did not fully fill due to low liquidity.
    • New behavior: If the reverse market order did not fully fill due to low liquidity the order status will be EXPIRED, and FILLED only if the order was completely filled.

SPOT API

  • Changes to DELETE /api/v3/order and POST /api/v3/order/cancelReplace:
    • A new optional parameter cancelRestrictions that determines whether the cancel will succeed if the order status is NEW or PARTIALLY_FILLED.
    • If the order cancellation fails due to cancelRestrictions, the error will be:
      • {"code": -2011,"msg": "Order was not canceled due to cancel restrictions."}

2023-02-27

  • New endpoints for Margin:
    • /sapi/v1/margin/next-hourly-interest-rate: Get user the next hourly estimate interest
  • New endpoints for Porfolio Margin:
    • GET /sapi/v1/portfolio/interest-history: get user’s portfolio margin interest history
    • GET /sapi/v1/portfolio/interest-rate: get portfolio margin interest rate

2023-02-21

  • Adjusted endpoints for Crypto Loan:
    • POST /sapi/v1/loan/borrow: paramater loanTerm is restricted to 7 or 30

2023-02-17

The Websocket Stream now only allows 300 connections requests every 5 minutes.

This limit is per IP address.

Please be careful when trying to open multiple connections or reconnecting to the Websocket API.


2023-02-13

  • New endpoints for Sub-Account:
    • GET /sapi/v4/sub-account/assets: Fetch sub-account assets

2023-02-02

  • New endpoints for Margin:
    • GET /sapi/v1/margin/exchange-small-liability: Query the coins which can be small liability exchange
    • POST /sapi/v1/margin/exchange-small-liability: Cross Margin Small Liability Exchange
    • GET /sapi/v1/margin/exchange-small-liability-history: Get Small liability Exchange History
  • Update endpoints for Wallet:
    • Universal Transfer POST /sapi/v1/asset/transfer support option transfer

2023-01-26

As per the announcement, Self Trade Prevention will be enabled at 2023-01-26 08:00 UTC.

Please refer to GET /api/v3/exchangeInfo from the Rest API or exchangeInfo from the Websocket API on the default and allowed modes.


2023-01-23

New API cluster has been added. Note that all endpoints are functionally equal, but may vary in performance.

  • https://api4.binance.com

2023-01-19

ACTUAL RELEASE DATE TBD

SPOT API

New Feature: Self-Trade Prevention (aka STP) will be added to the system at a later date. This will prevent orders from matching with orders from the same account, or accounts under the same tradeGroupId.

Please refer to GET /api/v3/exchangeInfo from the SPOT API or exchangeInfo from the Websocket API on the status.

"defaultSelfTradePreventionMode": "NONE",   //If selfTradePreventionMode not provided, this will be the value passed to the engine
"allowedSelfTradePreventionModes": [        //What the allowed modes of selfTradePrevention are
    "NONE",
    "EXPIRE_TAKER",
    "EXPIRE_BOTH",
    "EXPIRE_MAKER"
]
  • New order status: EXPIRED_IN_MATCH — This means that the order expired due to STP being triggered.
  • New endpoint:
    • GET /api/v3/myPreventedMatches — This queries the orders that expired due to STP being triggered.
  • New optional parameter selfTradePreventionMode has been added to the following endpoints:
    • POST /api/v3/order
    • POST /api/v3/order/oco
    • POST /api/v3/cancelReplace
  • New responses that will appear for all order placement endpoints if there was a prevented match (i.e. if an order could have matched with an order of the same account, or the accounts are in the same tradeGroupId):
    • tradeGroupId — This will only appear if account is configured to a tradeGroupId and if there was a prevented match.
    • preventedQuantity — Only appears if there was a prevented match.
    • An array preventedMatches with the following fields:
      • preventedMatchId
      • makerOrderId
      • price
      • takerPreventedQuantity — This will only appear if selfTradePreventionMode set is EXPIRE_TAKER or EXPIRE_BOTH.
      • makerPreventedQuantity — This will only appear if selfTradePreventionMode set is EXPIRE_MAKER or EXPIRE_BOTH.
  • New fields preventedMatchId and preventedQuantity that can appear in the order query endpoints if the order had expired due to an STP trigger:
    • GET /api/v3/order
    • GET /api/v3/openOrders
    • GET /api/v3/allOrders

USER DATA STREAM

  • New execution Type: TRADE_PREVENTION
  • New fields for executionReport (These fields will only appear if the order has expired due to STP trigger)
    • utradeGroupId
    • vpreventedMatchId
    • UcounterOrderId
    • ApreventedQuantity
    • BlastPreventedQuantity

2023-01-13

  • The following endpoints will be discontinued on January 13, 2023 6:00 AM UTC:
    • POST /sapi/v1/sub-account/subAccountApi/ipRestriction to support master account enable and disable IP restriction for a sub-account API Key
    • POST /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList to support master account add IP list for a sub-account API Key
  • New endpoints for Sub-Account:
    • GET /sapi/v1/managed-subaccount/fetch-future-asset: Investor can use this api to query managed sub account futures asset details
    • GET /sapi/v1/managed-subaccount/marginAsset: Investor can use this api to query managed sub account margin asset details
  • New endpoin for Margin:
    • GET /sapi/v1/margin/crossMarginCollateralRatio: Get cross margin collateral ratio

2023-01-05

  • New endpoints for Sub-Account:
    • GET /sapi/v1/managed-subaccount/queryTransLogForInvestor: Investor can use this api to query managed sub account transfer log
    • GET /sapi/v1/managed-subaccount/queryTransLogForTradeParent: Trading team can use this api to query managed sub account transfer log

2022-12-26

  • New endpoints for wallet:
    • GET /sapi/v1/capital/contract/convertible-coins: Get a user’s auto-conversion settings in deposit/withdrawal
    • POST /sapi/v1/capital/contract/convertible-coins: User can use it to turn on or turn off the BUSD auto-conversion from/to a specific stable coin.

2022-12-15

  • New RSA signature
    • Documentation has been updated to show how to sign a request using an RSA key.
    • For security reasons, we recommend to use RSA keys instead of HMAC keys when generating an API key.
    • We accept PKCS#8 (BEGIN PUBLIC KEY).
    • More details on how to upload your RSA public key will be added at a later date.

2022-12-13

REST API

Some error messages on error code -1003 have changed:

  • Previous error message:

Too much request weight used; current limit is %s request weight per %s %s. Please use the websocket for live updates to avoid polling the API.

has been updated to:

Too much request weight used; current limit is %s request weight per %s. Please use WebSocket Streams for live updates to avoid polling the API.

  • Previous error message

Way too much request weight used; IP banned until %s. Please use the websocket for live updates to avoid bans.

has been updated to:

Way too much request weight used; IP banned until %s. Please use WebSocket Streams for live updates to avoid bans.


2022-12-05

Notice: These changes are being rolled out gradually to all our servers, and will take approximately a week to complete.

WEBSOCKET

  • !bookTicker will be removed by December 7, 2022. Please use the Individual Book Ticker Streams instead. (<symbol>@bookTicker).
    • Multiple <symbol>@bookTicker streams can be subscribed to over one connection. (E.g. wss://stream.binance.com:9443/stream?streams=btcusdt@bookTicker/bnbbtc@bookTicker)

SPOT API

  • New error code -1135
    • This error code will occur if a parameter requiring a JSON object is invalid.
  • New error code -1108
    • This error will occur if a value to a parameter being sent was too large, potentially causing overflow.
    • This error code can occur in the following endpoints:
      • POST /api/v3/order
      • POST /api/v3/order/cancelReplace
      • POST /api/v3/order/oco
  • Changes to GET /api/v3/aggTrades
    • Previous behavior: startTime and endTime had to be used in combination and could only be an hour apart.
    • New behavior: startTime and endTime can be used individually and the 1 hour limit has been removed.
      • When using startTime only, this will return trades from that time, up to the limit provided.
      • When using endTime only, this will return trades starting from the endTime including all trades before that time, up to the limit provided.
      • If limit not provided, regardless of used in combination or sent individually, the endpoint will use the default limit.
  • Changes to GET /api/v3/myTrades

    • Fixed a bug where symbol + orderId combination would return all trades even if the number of trades went beyond the 500 default limit.
    • Previous behavior: The API would send specific error messages depending on the combination of parameters sent. E.g:


      {
      "code": -1106,
      "msg": "Parameter X was sent when not required."
      }

    • New behavior: If the combinations of optional parameters to the endpoint were not supported, then the endpoint will respond with the generic error:


      {
      "code": -1128,
      "msg": "Combination of optional parameters invalid."
      }

    • Added a new combination of supported parameters: symbol + orderId + fromId.

    • The following combinations of parameters were previously supported but no longer accepted, as these combinations were only taking fromId into consideration, ignoring startTime and endTime:

      • symbol + fromId + startTime
      • symbol + fromId + endTime
      • symbol + fromId + startTime + endTime
    • Thus, these are the supported combinations of parameters:

      • symbol
      • symbol + orderId
      • symbol + startTime
      • symbol + endTime
      • symbol + fromId
      • symbol + startTime + endTime
      • symbol+ orderId + fromId

Note: These new fields will appear approximately a week from the release date.

  • Changes to GET /api/v3/exchangeInfo
    • New fields defaultSelfTradePreventionMode and allowedSelfTradePreventionModes
  • Changes to the Order Placement Endpoints/Order Query/Order Cancellation Endpoints:
    • New field selfTradePreventionMode will appear in the response.
    • Affects the following endpoints:
      • POST /api/v3/order
      • POST /api/v3/order/oco
      • POST /api/v3/order/cancelReplace
      • GET /api/v3/order
      • DELETE /api/v3/order
      • DELETE /api/v3/orderList
  • Changes to GET /api/v3/account
    • New field requireSelfTradePrevention will appear in the response.
  • New field workingTime, indicating when the order started working on the order book, will appear in the following endpoints:
    • POST /api/v3/order
    • GET /api/v3/order
    • POST /api/v3/order/cancelReplace
    • POST /api/v3/order/oco
    • GET /api/v3/order
    • GET /api/v3/openOrders
    • GET /api/v3/allOrders
  • Field trailingTime, indicating the time when the trailing order is active and tracking price changes, will appear for the following order types (TAKE_PROFIT, TAKE_PROFIT_LIMIT, STOP_LOSS, STOP_LOSS_LIMIT if trailingDelta parameter was provided) for the following endpoints:
    • POST /api/v3/order
    • GET /api/v3/order
    • GET /api/v3/openOrders
    • GET /api/v3/allOrders
    • POST /api/v3/order/cancelReplace
    • DELETE /api/v3/order
  • Field commissionRates will appear in the GET /api/v3/acccount response

USER DATA STREAM

  • eventType executionReport has new fields
    • VselfTradePreventionMode
    • Dtrailing_time (Appears if the trailing stop order is active)
    • WworkingTime (Appears if isWorking=true)

2022-12-02

  • Added a new market data base URL https://data.binance.com.
  • Added a new WebSocket URL wss://data-stream.binance.com.

2022-11-29

  • New endpoint for VIP Loan:
    • `GET /sapi/v1/loan/vip/collateral/account: Check Locked Value of VIP Collateral Account

2022-11-22

  • New endpoints for Convert:
    • GET /sapi/v1/convert/exchangeInfo: Query for all convertible token pairs and the tokens’ respective upper/lower limits
    • GET /sapi/v1/convert/assetInfo: Query for supported asset’s precision information
    • POST /sapi/v1/convert/getQuote: Request a quote for the requested token pairs
    • POST /sapi/v1/convert/acceptQuote: Accept the offered quote by quote ID.
    • GET /sapi/v1/convert/orderStatus: Query order status by order ID.

2022-11-18

  • New endpoint for Wallet:
    • GET /sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage: The query of Cloud-Mining payment and refund history
  • New endpoints for Sub-account:
    • GET /sapi/v1/sub-account/apiRestrictions/ipRestriction/thirdPartyList: To query Sub-Account API key Third Party IP whitelist
    • POST /sapi/v2/sub-account/subAccountApi/ipRestriction: To support master account update IP Restriction for Sub-Account API key

2022-11-14

  • New endpoints for VIP Loan:
    • GET /sapi/v1/loan/vip/ongoing/orders: Get VIP Loan Ongoing Orders
    • POST /sapi/v1/loan/vip/repay: VIP Loan Repay
    • GET /sapi/v1/loan/vip/repay/history: Get VIP Loan Repayment History

2022-11-02

  • Update endpoints for Wallet:
    • POST /sapi/v1/capital/withdraw/apply: Weight changed to Weight(UID): 600

2022-11-01

  • New endpoints for Crypto Loan:
    • GET /sapi/v1/loan/loanable/data: Get interest rate and borrow limit of loanable assets. The borrow limit is shown in USD value.
    • GET /sapi/v1/loan/collateral/data: Get LTV information and collateral limit of collateral assets. The collateral limit is shown in USD value.
    • GET /sapi/v1/loan/repay/collateral/rate: Get the the rate of collateral coin / loan coin when using collateral repay, the rate will be valid within 8 second.
    • POST /sapi/v1/loan/customize/margin_call: Customize margin call for ongoing orders only.

2022-10-28

  • Update endpoints for Wallet:
    • POST /sapi/v1/asset/convert-transfer: New parameter accountType
    • POST /sapi/v1/asset/convert-transfer/queryByPage: request method is changed to GET, new parameter clientTranId

2022-10-15

  • New endpoints for Binance Code:
    • POST /sapi/v1/giftcard/buyCode: For buying a fixed-value Binance Code.
    • GET /sapi/v1/giftcard/buyCode/token-limit: To verify which tokens are available for you to purchase fixed-value gift cards as mentioned in section 2 and its’ limitation.

2022-09-30

  • Delete endpoints for Futures Cross Collateral:
    • POST /sapi/v1/futures/loan/borrow
    • POST /sapi/v1/futures/loan/repay
    • GET /sapi/v1/futures/loan/configs
    • GET /sapi/v2/futures/loan/configs
    • GET /sapi/v1/futures/loan/calcAdjustLevel
    • GET /sapi/v2/futures/loan/calcAdjustLevel
    • GET /sapi/v1/futures/loan/calcMaxAdjustAmount
    • GET /sapi/v2/futures/loan/calcMaxAdjustAmount
    • POST /sapi/v1/futures/loan/adjustCollateral
    • POST /sapi/v2/futures/loan/adjustCollateral
    • GET /sapi/v1/futures/loan/collateralRepayLimit
    • GET /sapi/v1/futures/loan/collateralRepay
    • POST /sapi/v1/futures/loan/collateralRepay
    • GET /sapi/v1/futures/loan/collateralRepayResult

2022-09-30

Scheduled changes to the removal of !bookTicker around November 2022.

  • The All Book Tickers stream (!bookTicker) is set to be removed in November 2022
  • More details of the actual removal date will be announced at a later time.
  • Please use the Individual Book Ticker Streams instead. (<symbol>@bookTicker).
  • Multiple <symbol>@bookTicker streams can be subscribed to over one connection.
    • Example: wss://stream.binance.com:9443/stream?streams=btcusdt@bookTicker/bnbbtc@bookTicker

2022-09-29

  • New endpoints for Wallet:
    • POST /sapi/v1/asset/convert-transfer: Convert transfer, convert between BUSD and stablecoins.
    • POST /sapi/v1/asset/convert-transfer/queryByPage: Query convert transfer

2022-09-22

  • Update endpoint for Sub-Account:
    • POST /sapi/v1/sub-account/subAccountApi/ipRestriction: Add new param thirdParty
    • POST /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList: Add new param thirdPartyName
    • DELETE /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList: Add new param thirdPartyName
  • Add Rate Limit for following endpoints:
    • GET /sapi/v1/bswap/liquidity: 3/1s per account and per pool
    • GET /sapi/v1/bswap/quote: 3/1s per account and per pool
    • POST /sapi/v1/lending/daily/purchase: 1/3s per account
    • POST /sapi/v1/lending/customizedFixed/purchase: 1/3s per account
    • POST /sapi/v1/staking/purchase: 1/3s per account

2022-09-16

  • New endpoint for Margin:
    • GET /sapi/v1/margin/tradeCoeff: Get personal margin level information

2022-09-15

  • New endpoints for Crypto Loan
    • POST /sapi/v1/loan/borrow: Borrow — Crypto Loan Borrow
    • GET /sapi/v1/loan/borrow/history: Borrow — Get Loan Borrow History
    • GET/sapi/v1/loan/ongoing/orders: Borrow — Get Loan Ongoing Orders
    • POST/sapi/v1/loan/repay: Repay — Crypto Loan Repay
    • GET/sapi/v1/loan/repay/history: Repay — Get Loan Repayment History
    • POST/sapi/v1/loan/adjust/ltv: Adjust LTV — Crypto Loan Adjust LTV
    • GET/sapi/v1/loan/ltv/adjustment/history: Adjust LTV — Get Loan LTV Adjustment History

2022-09-15

Note that these are rolling changes, so it may take a few days for it to rollout to all our servers.

  • Changes to GET /api/v3/exchangeInfo
    • New optional parameter permissions added to display all symbols with the permissions matching the parameter provided. (eg.SPOT, MARGIN, LEVERAGED)
    • If not provided, the default value will be ["SPOT","MARGIN", "LEVERAGED"].
      • This means the request GET /api/v3/exchangeInfo without any parameters will show all symbols that can be used for SPOT,MARGIN and/or LEVERAGED trading.
      • To search for symbols that can be traded on other permissions (e.g. TRD_GRP_004, etc), then this needs to be searched for explicitly. (e.g.permissions=TRD_GRP_004)
    • Cannot be combined with symbol or symbols

2022-09-12

  • Update endpoint for Sub-account:
    • GET /sapi/v1/sub-account/subAccountApi/ipRestriction:
      To support master account query Third party IP list name for a sub account API key

2022-09-05

  • Delete endpoint for Futures:
    • GET /sapi/v1/futures/loan/wallet

2022-08-23

SPOT API

Note that these are rolling changes, so it may take a few days for it to rollout to all our servers.

  • Changes to GET /api/v3/ticker and GET /api/v3/ticker/24hr
    • New optional parameter type added
    • Supported values for parameter type are FULL and MINI
      • FULL is the default value and the response that is currently being returned from the endpoint
      • MINI omits the following fields from the response: priceChangePercent, weightedAvgPrice, bidPrice, bidQty, askPrice, askQty, and lastQty
  • New error code -1008
    • This is sent whenever the servers are overloaded with requests.
    • This error code only appears for the SPOT API.
  • New field brokered has been added to GET /api/v3/account
  • New endpoint: GET /api/v3/uiKlines
  • New kline interval: 1s

2022-08-18

  • Update endpoint for Convert:
    • GET /sapi/v1/convert/tradeFlow: Update weight from Weight(IP) 3000 to Weight(UID) 3000.

2022-08-08

SPOT API

  • Changes to POST /api/v3/order and POST /api/v3/order/cancelReplace
    • New optional field strategyId is a parameter used to identify an order as part of a strategy.
    • New optional field strategyType is a parameter used to identify what strategy was running. (E.g. If all the orders are part of spot grid strategy, it can be set to strategyType=1000000)
    • Note: strategyType cannot be less than 1000000.
  • Changes to POST /api/v3/order/oco
    • New optional fields limitStrategyId, limitStrategyType. stopStrategyId, stopStrategyType
    • These are the strategy metadata parameters for both legs of the OCO orders.
    • limitStrategyType and stopStrategyType both cannot be less than 1000000.
  • Changes to GET /api/v3/order, GET /api/v3/openOrders, and GET /api/v3/allOrders
    • New fields strategyId and strategyType will appear in the response JSON for orders that had these fields populated upon order placement.
  • Changes to DELETE /api/v3/order and DELETE /api/v3/openOrders
    • New fields strategyId and strategyType will appear in the response JSON for cancelled orders that had these fields populated upon order placement.

USER DATA STREAM

  • New fields to eventType executionReport
    • j for strategyId
    • J for strategyType
    • Note that these fields only appear if these were populated upon order placement.

2022-08-05

  • Update endpoint for Convert:
    • GET /sapi/v1/convert/tradeFlow: Update weight from Weight(IP) 100 to Weight(IP) 3000.

2022-07-21

  • New endpoint for Portfolio Margin:
    • GET /sapi/v1/portfolio/pmLoan Query Portfolio Margin Bankruptcy Loan Record
    • POST /sapi/v1/portfolio/repay Portfolio Margin Bankruptcy Loan Repay

2022-07-18

  • New endpoint for Portfolio Margin:
    • GET /sapi/v1/portfolio/collateralRate to get Portfolio Margin Collateral Rate.

2022-07-01

  • New endpoint for Wallet:
    • POST /sapi/v3/asset/getUserAsset to get user assets.
  • New endpoint for Margin:
    • GET /sapi/v1/margin/dribblet to query the historical information of user’s margin account small-value asset conversion BNB.
  • Update endpoint for Convert:
    • GET /sapi/v1/convert/tradeFlow: Update weight from 3000 to 100.
  • Update endpoint for Margin:
    • GET /sapi/v1/margin/repay: Add response field rawAsset.

2022-06-20

SPOT API: Changes to GET /api/v3/ticker

  • Weight has been reduced from 5 to 2 per symbol, regardless of windowSize.
  • The max number of symbols that can be processed in a request is 100.
    • If the number of symbols sent is more than 100, the error will be as follows:
    {
     "code": -1101,
     "msg": "Too many values sent for parameter 'symbols', maximum allowed up to 100." 
    }
  • The max Weight(IP) for this endpoint will cap at 100.
    • I.e. If the request has more than 50 symbols, the Weight will still be 100, regardless of windowSize.

2022-06-15

Note: The update is being rolled out over the next few days, so these changes may not be visible right away.

  • GET /api/v3/ticker added
    • Rolling window price change statistics based on windowSize provided.
    • Contrary to GET /api/v3/ticker/24hr the list of symbols cannot be omitted.
    • If windowSize not specified, the value will default to 1d.
    • Response is similar to GET /api/v3/ticker/24hr, minus the following fields: prevClosePrice, lastQty, bidPrice, bidQty, askPrice, askQty
  • POST /api/v3/order/cancelReplace added
    • Cancels an existing order and places a new order on the same symbol.
    • The filters are evaluated before the cancel order is placed.
      • e.g. If the MAX_NUM_ORDERS filter is 10, and the total number of open orders on the account is also 10, when using POST /api/v3/order/cancelReplace both the cancel order placement and new order will fail because of the filter.
    • The change is being rolled out in the next few days, thus this feature will be enabled once the upgrade is completed.
  • GET /api/v3/exchangeInfo returns new field cancelReplaceAllowed in symbols list.
  • New filter NOTIONAL has been added.
    • Defines the allowed notional value (price * quantity) based on a configured minNotional and maxNotional
  • New exchange filter EXCHANGE_MAX_NUM_ICEBERG_ORDERS has been added.
    • Defines the limit of open iceberg orders on an account

WEBSOCKETS

  • New symbol ticker streams with 1h and 4h windows:
    • Individual symbol ticker streams
      • <symbol>@ticker_<window-size>
    • All market ticker streams
      • !ticker_<window-size>@arr

2022-06-02

  • Update endpoint for Subaccount:
    • GET /sapi/v1/sub-account/sub/transfer/history: fromEmail and toEmail can be master email.

2022-05-31

  • Update endpoint for Fiat:
    • GET /sapi/v1/fiat/orders: Weight changes from UID(3000) to UID(90000)
  • Update endpoint for Pay:
    • GET /sapi/v1/pay/transactions: Param names changed: startTimestamp -> startTime; endTimestamp -> endTime.

2022-05-26

  • Update endpoint for Fiat:
    • GET /sapi/v1/fiat/orders: Weight changes from IP(1) to UID(3000)
  • Update info for the following margin account endpoints: The max interval between startTime and endTime is 30 days.:
    • GET /sapi/v1/margin/transfer
    • GET /sapi/v1/margin/loan
    • GET /sapi/v1/margin/repay
    • GET /sapi/v1/margin/isolated/transfer
    • GET /sapi/v1/margin/interestHistory

2022-05-23

  • Changes to Order Book Depth Levels
    • Quantities in the Depth levels were returning negative values in situations where they were exceeding the max value, resulting in an overflow.
    • Going forward depth levels will not overflow, but will be capped at the max value based on the precision of the base asset. This means that the depth level is at max value or more.
      • E.g. If the precision is 8, then the max value for quantity will be at 92,233,720,368.54775807.
    • When the fix has been applied, a change in the order book at the affected price level is required for the changes to be visible.
  • What does this affect?

    • SPOT API
      • GET /api/v3/depth
    • Websocket Streams
      • <symbol>@depth
      • <symbol>@depth@100ms
      • <symbol>@depth<levels>
      • <symbol>@depth<levels>@100ms
  • Updates to MAX_POSITION

    • If an order’s quantity can cause the position to overflow, this will now fail the MAX_POSITION filter.

2022-05-19

  • Update endpoint for Mining:
    • GET /sapi/v1/mining/pub/algoList and GET /sapi/v1/mining/pub/coinList: Need no paramter.
  • Add error codes (21xxx) for Portfolio Margin Account: -21001, -21002, -21003

2022-05-17

SPOT API

  • Changes to GET api/v3/aggTrades
    • When providing startTime and endTime, the oldest items are returned.
  • Changed error messaging on GET /api/v3/myTrades where parameter symbol is not provided:
{
"code": -1102,
"msg": "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed." 
}
  • The following endpoints now support multi-symbol querying using the parameter symbols.
    • GET /api/v3/ticker/24hr
    • GET /api/v3/ticker/price
    • GET /api/v3/ticker/bookTicker
  • In the above, the request weight will depend on the number of symbols provided in symbols.

    Please refer to the table below:

Endpoint Number of Symbols Weight
GET /api/v3/ticker/price Any 2
GET /api/v3/ticker/bookTicker Any 2
GET /api/v3/ticker/24hr 1-20 1
GET /api/v3/ticker/24hr 21-100 20
GET /api/v3/ticker/24hr 101 or more 40

2022-05-05

  • New endpoint for Binance Code:
    • GET /sapi/v1/giftcard/cryptography/rsa-public-key to fetch RSA public key.
  • Update endpoint for Binance Code:
    • POST /sapi/v1/giftcard/redeemCode: new optional parameter externalUid. Each external unique ID represents a unique user on the partner platform. The function helps you to identify the redemption behavior of different users.

2022-04-28

  • New endpoints for Staking:
    • GET /sapi/v1/staking/productList to get Staking product list
    • POST /sapi/v1/staking/purchase to stake product
    • POST /sapi/v1/staking/redeem to redeem product
    • GET /sapi/v1/staking/position to get Staking product holding position
    • GET /sapi/v1/staking/stakingRecord to inquiry Staking history records
    • POST /sapi/v1/staking/setAutoStaking to set Auto Staking function
    • GET /sapi/v1/staking/personalLeftQuota to inquiry Staking left quota

2022-04-27

  • New endpoint for Futures Algo:
    • POST /sapi/v1/algo/futures/newOrderTwap to support Twap new order

FAQ: Time-Weighted Average Price(Twap) Introduction


2022-04-26

  • GET /sapi/v1/margin/rateLimit/order added
    • The endpoint will display the user’s current margin order count usage for all intervals.

2022-04-20

  • New endpoint for Portfolio Margin:
    • GET /sapi/v1/portfolio/account to support query portfolio margin account info

FAQ: Portfolio Margin Program

Only Portfolio Margin Account is accessible to this endpoint. To enroll, kindly refer to: How to Enroll into the Binance Portfolio Margin Program


2022-04-13

  • New endpoints for Futures Algo:
    • POST /sapi/v1/algo/futures/newOrderVp to support VP new order
    • DELETE /sapi/v1/algo/futures/order to support cancel Algo order
    • GET /sapi/v1/algo/futures/openOrders to support query Algo open orders
    • GET /sapi/v1/algo/futures/historicalOrders to support query Algo historical orders
    • GET /sapi/v1/algo/futures/subOrders to support query Algo sub orders for a specified algoId

FAQ: Volume Participation(VP) Introduction


2022-04-13

Information on Trailing Stops

SPOT API

  • Trailing Stops have been enabled.
    • This is a type of algo order where the activation is based on a percentage of a price change in the market using the new parameter trailingDelta.
    • This can only used with any of the following order types: STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT.
    • The trailingDelta parameter will be done in Basis Points or BIPS.
      • For example: a STOP_LOSS SELL order with a trailingDelta of 100 will trigger after a price decrease of 1%. (100 / 10,000 => 0.01 => 1%)
    • When used in combination with OCO Orders, the trailingDelta will determine when the contingent leg of the OCO will trigger.
    • When trailingDelta is used in combination with stopPrice, once the stopPrice condition is met, the trailing stop starts tracking the price change from the stopPrice based on the trailingDelta provided.
    • When no stopPrice is sent, the trailing stop starts tracking the price changes from the last price based on the trailingDelta provided.
  • Changes to POST /api/v3/order
    • New optional field trailingDelta
  • Changes to POST /api/v3/order/test
    • New optional field trailingDelta
  • Changes to POST /api/v3/order/oco
    • New optional field trailingDelta
  • A new filter TRAILING_DELTA has been added.
    • This filter is defined by the minimum and maximum values for the trailingDelta value.

USER DATA STREAM

  • New field in executionReport
    • «d» for trailingDelta

2022-04-12

Note: The changes are being rolled out during the next few days, so these will not appear right away.

  • Error message changed on GET api/v3/allOrders where symbol is not provided:


    {
    "code": -1102,
    "msg": "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed."
    }

  • Fixed a typo with an error message when an account has disabled permissions (e.g. to withdraw, to trade, etc)


    "This action is disabled on this account."

  • During a market data audit, we detected some issues with the Spot aggregate trade data.
    • Missing aggregate trades were recovered.
    • Duplicated records were marked invalid with the following values:
      • p = ‘0’ // price
      • q = ‘0’ // qty
      • f = -1 // first_trade_id
      • l = -1 // last_trade_id

2022-04-08

  • Update WEBSOCKET for BLVT:
    • Base url changed to wss://nbstream.binance.com/lvt-p for BLVT streams <tokenName>@tokenNav and <tokenName>@nav_Kline_<interval>
      More details: Websocket BLVT Info Streams and Websocket BLVT NAV Kline/Candlestick Streams

2022-3-29

The following updates will take effect on March 31, 2022 08:00 AM UTC

  • Update endpoint for Sub-account:
    • GET /sapi/v1/sub-account/universalTransfer

The query time period must be less then 30 days; If startTime and endTime not sent, return records of the last 30 days by default


2022-03-25

  • Update endpoint for Sub-Account:
    • New endpointGET /sapi/v1/managed-subaccount/accountSnapshot to support investor master account query asset snapshot of managed sub-account

2022-03-08

  • Update endpoint for Sub-Account:
    • New transfer typesMARGIN,ISOLATED_MARGIN and parametersymboladded inPOST /sapi/v1/sub-account/universalTransfer to support transfer to sub-account cross margin account and isolated margin account

2022-02-28

  • New field allowTrailingStop has been added to GET /api/v3/exchangeInfo

2022-02-22

SPOT API

  • (price-minPrice) % tickSize == 0 rule in PRICE_FILTER has been changed to price % tickSize == 0.
  • A new filter PERCENT_PRICE_BY_SIDE has been added.
  • Changes to GET api/v3/depth
    • The limit value can be outside of the previous values (i.e. 5, 10, 20, 50, 100, 500, 1000,5000) and will return the correct limit. (i.e. if limit=3 then the response will be the top 3 bids and asks)
    • The limit still cannot exceed 5000. If the limit provided is greater than 5000, then the response will be truncated to 5000.
    • Due to the changes, these are the updated request weights based on the limit value provided:
Limit Request Weight
1-100 1
101-500 5
501-1000 10
1001-5000 50
  • Changes to GET api/v3/aggTrades
    • When providing startTime and endTime, the oldest items are returned.

2022-2-18

  • Update endpoint for Sub-Account:
    • New fields isManagedSubAccountand isAssetManagementSubAccount added inGET /sapi/v1/sub-account/listto support query whether the sub-account is a managed sub-account or a asset management sub-account

2022-2-17

The following updates will take effect on February 24, 2022 08:00 AM UTC

  • Update endpoint for Wallet:
    • GET /sapi/v1/accountSnapshot

The time limit of this endpoint is shortened to only support querying the data of the latest month


2022-2-09

  • New endpoint for Wallet:
    • POST /sapi/v1/asset/dust-btc to get assets that can be converted into BNB

2022-1-25

  • From January 28, 2022 4:00 AM UTC, You need to openEnable Spot & Margin Tradingpermission for the API key which requests these endpoints as following:
    • POST /sapi/v1/asset/dust Dust transfer
    • POST /sapi/v1/lending/daily/purchase Purchase Savings flexible product
    • POST /sapi/v1/lending/daily/redeem Redeem Savings flexible product
    • POST /sapi/v1/lending/customizedFixed/purchase Purchase Savings Fixed/Activity project
    • POST /sapi/v1/lending/positionChanged Change Savings Fixed/Activity position to Daily position
    • POST /sapi/v1/bswap/liquidityAdd Bswap add liquidity
    • POST /sapi/v1/bswap/liquidityRemove Bswap remove liquidity
    • POST /sapi/v1/bswap/swap Bswap swap
    • POST /sapi/v1/bswap/claimRewards Bswap claim rewards

2022-1-21

  • New endpoints for Binance Code:
    • POST /sapi/v1/giftcard/createCode to create a Binance Code.
    • POST /sapi/v1/giftcard/redeemCode to redeem a Binance Code.
    • GET /sapi/v1/giftcard/verify to verify a Binance Code.

2022-1-4

  • New endpoint for Mining:

    • GET /sapi/v1/mining/payment/uid to get Mining account earning.
  • New endpoints for BSwap:

    • GET /sapi/v1/bswap/unclaimedRewards to get unclaimed rewards record.
    • POST /sapi/v1/bswap/claimRewards to claim swap rewards or liquidity rewards.
    • GET /sapi/v1/bswap/claimedHistory to get history of claimed rewards.

2021-12-30

  • Update endpoint for Margin:

    • Removed out limit fromGET /sapi/v1/margin/interestRateHistory; The max interval between startTime and endTime is 30 days.
  • Update endpoint for Wallet:

    • As the Mining account is merged into Funding account, transfer types MAIN_MINING, MINING_MAIN, MINING_UMFUTURE, MARGIN_MINING, and MINING_MARGIN will be discontinued in Universal Transfer endpoint POST /sapi/v1/asset/transfer on January 05, 2022 08:00 AM UTC

2021-12-29

  • Removed out dated «Symbol Type» enum; added «Permissions» enum.

2021-12-24

  • Update endpoints for Sub-Account:
    • New parameterclientTranIdadded inPOST /sapi/v1/sub-account/universalTransfer and GET /sapi/v1/sub-account/universalTransfer to support custom transfer id

2021-12-03

  • New endpoints for Margin:

    • GET /sapi/v1/margin/crossMarginData to get cross margin fee data collection
    • GET /sapi/v1/margin/isolatedMarginData to get isolated margin fee data collection
    • GET /sapi/v1/margin/isolatedMarginTier to get isolated margin tier data collection
  • New endpoints for NFT:

    • GET /sapi/v1/nft/history/transactions to get NFT transaction history
    • GET /sapi/v1/nft/history/deposit to get NFT deposit history
    • GET /sapi/v1/nft/history/withdraw to get NFT withdraw history
    • GET /sapi/v1/nft/user/getAsset to get NFT asset

2021-11-30

  • New endpoint for Convert:

    • GET /sapi/v1/convert/tradeFlow to support user query convert trade history records
  • New endpoint for Rebate:

    • GET /sapi/v1/rebate/taxQuery to support user query spot rebate history records

2021-11-19

  • New endpoint for Pay:

    • GET /sapi/v1/pay/transactionsto support user query Pay trade history
  • Update endpoint for Wallet:

    • New fieldinfoadded inGET /sapi/v1/capital/withdraw/historyto show the reason for withdrawal failure

2021-11-18

The following updates will take effect on November 25, 2021 08:00 AM UTC

  • Update endpoint for Wallet:
    • GET /sapi/v1/accountSnapshot

The query time range of both endpoints are shortened to support data query within the last 6 months only, where startTime does not support selecting a timestamp beyond 6 months.
If you do not specify startTime and endTime, the data of the last 7 days will be returned by default.


2021-11-17

  • The following endpoints will be discontinued on November 17, 2021 13:00 PM UTC:
    • POST /sapi/v1/account/apiRestrictions/ipRestriction to support user enable and disable IP restriction for an API Key
    • POST /sapi/v1/account/apiRestrictions/ipRestriction/ipList to support user add IP list for an API Key
    • GET /sapi/v1/account/apiRestrictions/ipRestriction to support user query IP restriction for an API Key
    • DELETE /sapi/v1/account/apiRestrictions/ipRestriction/ipList to support user delete IP list for an API Key

2021-11-16

  • New endpoints for Sub-Account:
    • POST /sapi/v1/sub-account/subAccountApi/ipRestriction to support master account enable and disable IP restriction for a sub-account API Key
    • POST /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList to support master account add IP list for a sub-account API Key
    • GET /sapi/v1/sub-account/subAccountApi/ipRestriction to support master account query IP restriction for a sub-account API Key
    • DELETE /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList to support master account delete IP list for a sub-account API Key

2021-11-09

  • New endpoints for Wallet:
    • POST /sapi/v1/account/apiRestrictions/ipRestriction to support user enable and disable IP restriction for an API Key
    • POST /sapi/v1/account/apiRestrictions/ipRestriction/ipList to support user add IP list for an API Key
    • GET /sapi/v1/account/apiRestrictions/ipRestriction to support user query IP restriction for an API Key
    • DELETE /sapi/v1/account/apiRestrictions/ipRestriction/ipList to support user delete IP list for an API Key

2021-11-08

  • New endpoint for Crypto Loans:
    • New endpointGET /sapi/v1/loan/incometo support user query crypto loans income history

2021-11-05

  • Update endpoint for Wallet:
    • New parameter walletTypeadded in POST /sapi/v1/capital/withdraw/apply to support user choose wallet type spot wallet and funding wallet when withdraw crypto.

2021-11-04

The following updates will take effect on November 11, 2021 08:00 AM UTC

  • Update endpoints for Wallet and Futures:
    • GET /sapi/v1/asset/transfer
    • GET /sapi/v1/futures/transfer

The query time range of both endpoints are shortened to support data query within the last 6 months only, where startTime does not support selecting a timestamp beyond 6 months.
If you do not specify startTime and endTime, the data of the last 7 days will be returned by default.


2021-11-01

  • GET /api/v3/rateLimit/order added
    • The endpoint will display the user’s current order count usage for all intervals.
    • This endpoint will have a request weight of 20.

2021-10-22

  • Update endpoint for Wallet:
    • New transfer types MAIN_FUNDING,FUNDING_MAIN,FUNDING_UMFUTURE,UMFUTURE_FUNDING,MARGIN_FUNDING,FUNDING_MARGIN,FUNDING_CMFUTUREand CMFUTURE_FUNDING added in Universal Transfer endpoint POST /sapi/v1/asset/transfer and GET /sapi/v1/asset/transfer to support transfer assets among funding account and other accounts
    • As the C2C account, Binance Payment, Binance Card and other business account are merged into a Funding account, transfer types MAIN_C2C,C2C_MAIN,C2C_UMFUTURE,C2C_MINING,UMFUTURE_C2C,MINING_C2C,MARGIN_C2C,C2C_MARGIN,MAIN_PAYand PAY_MAIN will be discontinued in Universal Transfer endpoint POST /sapi/v1/asset/transfer and GET /sapi/v1/asset/transfer on November 04, 2021 08:00 AM UTC

2021-10-14

  • Update the time range of the response data for the following margin account endpoints, startTime and endTime time span will not exceed 30 days, without time parameter sent the system will return the last 7 days of data by default, while the archived parameter is true, the system will return the last 7 days of data 6 months ago by default:
    • GET /sapi/v1/margin/transfer
    • GET /sapi/v1/margin/loan
    • GET /sapi/v1/margin/repay
    • GET /sapi/v1/margin/isolated/transfer
    • GET /sapi/v1/margin/interestHistory

2021-09-18

  • New endpoints for BSwap:
    • GET /sapi/v1/bswap/poolConfigure to get pool configure
    • GET /sapi/v1/bswap/addLiquidityPreview to get add liquidity preview
    • GET /sapi/v1/bswap/removeLiquidityPreview to get remove liquidity preview

2021-09-17

  • Add/api/*and/sapi/* limit introduction in General Info

2021-09-08

  • Add endpoints for enabled isolated margin account limit:

    • DELETE /sapi/v1/margin/isolated/account to disable isolated margin account for a specific symbol
    • POST /sapi/v1/margin/isolated/account to enable isolated margin account for a specific symbol
    • GET /sapi/v1/margin/isolated/accountLimit to query enabled isolated margin account limit
  • New field «enabled» in response of GET /sapi/v1/margin/isolated/account to check if the isolated margin account is enabled


2021-09-03

  • Update endpoint for Wallet:
    • New fields sameAddress,depositDust and specialWithdrawTipsadded in GET /sapi/v1/capital/config/getall
      sameAddress means if the coin needs to provide memo to withdraw
      depositDust means minimum creditable amount
      specialWithdrawTips means special tips for withdraw
    • New field confirmNoadded in GET /sapi/v1/capital/withdraw/history to support query confirm times for withdraw history

2021-08-27

  • Update endpoint for Wallet:
    • New parameter withdrawOrderIdadded in GET /sapi/v1/capital/withdraw/history to support user query withdraw history by withdrawOrderId
    • New field unlockConfirmadded in GET /sapi/v1/capital/deposit/hisrec to support query network confirm times for unlocking

2021-08-23

  • New endpoints for Margin Account OCO:
    • POST /sapi/v1/margin/order/oco
    • DELETE /sapi/v1/margin/orderList
    • GET /sapi/v1/margin/orderList
    • GET /sapi/v1/margin/allOrderList
    • GET /sapi/v1/margin/openOrderList

Same usage as spot account OCO


2021-08-20

  • Update endpoint for Wallet:
    • New parametersfromSymbol,toSymboland new transfer types ISOLATEDMARGIN_MARGIN, MARGIN_ISOLATEDMARGINand ISOLATEDMARGIN_ISOLATEDMARGIN added in POST /sapi/v1/asset/transfer and GET /sapi/v1/asset/transfer to support user transfer assets between Margin(cross) account and Margin(isolated) account

2021-08-12

  • GET api/v3/myTrades has a new optional field orderId

2021-08-05

  • New endpoint for C2C:
    • GET /sapi/v1/c2c/orderMatch/listUserOrderHistory to query user C2C trade history

2021-08-05

  • Update endpoints for Savings:
    • GET /sapi/v1/lending/union/purchaseRecord
    • GET /sapi/v1/lending/union/redemptionRecord
    • GET /sapi/v1/lending/union/interestHistory

The time between startTime and endTime cannot be longer than 30 days. If startTime and endTime are both not sent, then the last 30 days’ data will be returned


2021-07-29

  • Update endpoint for Sub-Account:
    • GET /sapi/v1/sub-account/transfer/subUserHistory if startTimeandendTimeare not sent, the recent 30-day data will be returned by default

2021-07-27

  • New endpoint for Fiat:
    • GET /sapi/v1/fiat/orders to query user fiat deposit and withdraw history
    • GET /sapi/v1/fiat/payments to query user fiat payments history

2021-07-16

  • New endpoint for Wallet:
    • GET /sapi/v1/account/apiRestrictions to query user API Key permission

2021-07-09

  • New endpoint for Wallet:
    • POST /sapi/v1/asset/get-funding-asset to query funding wallet, includes Binance Pay, Binance Card, Binance Gift Card, Stock Token

2021-06-24

  • Update endpoints for Wallet:
    • GET /sapi/v1/capital/withdraw/history added default value 1000, max value 1000 for the parameterlimit
    • GET /sapi/v1/capital/deposit/hisrec added default value 1000, max value 1000 for the parameterlimit

2021-06-17

  • Update endpoint for Savings:
    • GET /sapi/v1/lending/daily/product/list to include new parameters current and size

2021-06-15

  • New endpoints for Sub-Account:
    • POST /sapi/v1/managed-subaccount/deposit to deposit assets into the managed sub-account (only for investor master account)
    • GET /sapi/v1/managed-subaccount/asset to query managed sub-account asset details (only for investor master account)
    • POST /sapi/v1/managed-subaccount/withdraw to withdrawal assets from the managed sub-account (only for investor master account)

2021-06-04

On August 01, 2021 02:00 AM UTC the WAPI endpoints will be discontinued:

  • GET /wapi/v3/systemStatus.html
  • POST /wapi/v3/withdraw.html
  • GET /wapi/v3/depositHistory.html
  • GET /wapi/v3/withdrawHistory.html
  • GET /wapi/v3/depositAddress.html
  • GET /wapi/v3/accountStatus.html
  • GET /wapi/v3/apiTradingStatus.html
  • GET /wapi/v3/userAssetDribbletLog.html
  • GET /wapi/v3/assetDetail.html
  • GET /wapi/v3/tradeFee.html
  • GET /wapi/v3/sub-account/list.html
  • GET /wapi/v3/sub-account/transfer/history.html
  • POST /wapi/v3/sub-account/transfer.html
  • GET /wapi/v3/sub-account/assets.html

The WAPI endpoints have been removed from Binance API Documentation.To ensure your trading strategies are not affected, all API users are encouraged to upgrade trading bots to SAPI endpoints as soon as possible.


2021-05-26

  • Update endpoint for Wallet:
    • New transfer types MAIN_PAY ,PAY_MAIN added in Universal Transfer endpoint POST /sapi/v1/asset/transfer and GET /sapi/v1/asset/transfer to support trasnfer assets between spot account and pay account

2021-05-12

  • Added Data Source in the documentation to explain where each endpoint is retrieving its data
  • Added field Data Source to each Spot API endpoint in the documentation
  • GET api/v3/exchangeInfo now supports single or multi-symbol query

2021-04-28

On May 15, 2021 08:00 UTC the SAPI Create Margin Account endpoint will be discontinued:

  • POST /sapi/v1/margin/isolated/create

Isolated Margin account creation and trade preparation can be completed directly through Isolated Margin funds transfer POST /sapi/v1/margin/isolated/transfer


2021-04-26

On April 28, 2021 00:00 UTC the weights to the following endpoints will be adjusted:

  • GET /api/v3/order weight increased to 2
  • GET /api/v3/openOrders weight increased to 3
  • GET /api/v3/allOrders weight increased to 10
  • GET /api/v3/orderList weight increased to 2
  • GET /api/v3/openOrderList weight increased to 3
  • GET /api/v3/account weight increased to 10
  • GET /api/v3/myTrades weight increased to 10
  • GET /api/v3/exchangeInfo weight increased to 10

2021-04-08

  • Update endpoint for Sub-Account:
    • GET /sapi/v1/sub-account/futures/accountSummary and GET /sapi/v2/sub-account/futures/accountSummary the unit of field asset changed to USD valued summary of sub-account assets

2021-04-02

  • New endpoints for Wallet:
    • GET /sapi/v1/system/status to query system status
    • GET /sapi/v1/account/status to query account status
    • GET /sapi/v1/account/apiTradingStatus to query account API trading status
    • GET /sapi/v1/asset/dribblet to query dust log
    • GET /sapi/v1/asset/assetDetail to query asset detail
    • GET /sapi/v1/asset/tradeFee to query trade fee
  • New endpoint for Sub-Account:
    • GET /sapi/v3/sub-account/assets to query sub-account assets

2021-04-01

  • Update endpoint for Sub-Account:
    • GET /sapi/v1/sub-account/transfer/subUserHistory new fields fromAccountType and toAccountType added in response

2021-03-31

  • Update endpoint for Sub-Account:
    • GET /wapi/v3/sub-account/transfer/history.html added new parameters fromEmail and toEmail, the original parameteremail is equal tofromEmailby default

2021-03-08

  • New endpoint for Sub-Account:
    • POST /sapi/v1/sub-account/virtualSubAccount to support create a virtual sub-account
    • GET /sapi/v1/sub-account/list to support query sub-account list
    • POST /sapi/v1/sub-account/blvt/enable to support enable blvt for sub-account

2021-03-05

  • New endpoints for Margin:
    • GET /sapi/v1/margin/interestRateHistory to support margin interest rate history query

2021-02-08

  • New endpoints for Futures:
    • GET /sapi/v2/futures/loan/wallet to support BUSD loan query
    • GET /sapi/v2/futures/loan/configs to support BUSD loan query
    • GET /sapi/v2/futures/loan/calcAdjustLevel to support BUSD loan
    • GET /sapi/v2/futures/loan/calcMaxAdjustAmount to support adjustment of BUSD loan
    • POST /sapi/v2/futures/loan/adjustCollateral to support adjustment of BUSD loan
  • Update endpoints for Futures
    • GET /sapi/v1/futures/loan/adjustCollateral/history new parameter and fields in response loanCoin for BUSD loan
    • GET /sapi/v1/futures/loan/liquidationHistory new parameter and fields in response loanCoin for BUSD loan

2021-02-04

  • New transfer types MARGIN_MINING ,MINING_MARGIN, MARGIN_C2C ,C2C_MARGIN, MARGIN_CMFUTURE, CMFUTURE_MARGIN added in Universal Transfer endpoint POST /sapi/v1/asset/transfer and GET /sapi/v1/asset/transfer.

2021-01-15

  • New endpoint DELETE /sapi/v1/margin/openOrders for Margin Trade
    • This will allow a user to cancel all open orders on a single symbol for margin account.
    • This endpoint will cancel all open orders including OCO orders for margin account.

2021-01-10

  • New parameter pageSize for Mining endpoint GET /sapi/v1/mining/payment/list
  • New fields in response to Mining endpoint GET /sapi/v1/mining/payment/list:

    • «type» for income type
    • «hashTransfer» for resale Hashrate
    • «transferAmount» for transferred Income
  • New Mining endpoints:

    • GET /sapi/v1/mining/payment/other
    • GET /sapi/v1/mining/hash-transfer/config/details
    • GET /sapi/v1/mining/hash-transfer/config/details/list
    • GET /sapi/v1/mining/hash-transfer/profit/details
    • POST /sapi/v1/mining/hash-transfer/config
    • POST /sapi/v1/mining/hash-transfer/config/cancel

2021-01-01

USER DATA STREAM

  • outboundAccountInfo has been removed.

2020-12-30

  • New endpoint for Wallet:
    • POST /sapi/v1/asset/transfer to support user universal transfer among Spot, Margin, Futures, C2C, MINING accounts.
    • GET /sapi/v1/asset/transfer to get user universal transfer history.

2020-12-22

  • New endpoint for Sub-Account:
    • GET /sapi/v1/sub-account/sub/transfer/history to get spot asset transfer history.

2020-12-11

  • Update endpoints for Futures Cross-Collateral:
    • GET /sapi/v1/futures/loan/wallet new fields in response interestFreeLimit for total interest free limit, interestFreeLimitUsed for interest free limit used.
    • GET /sapi/v1/futures/loan/interestHistory new fields in response interestFreeLimitUsed for interest free limit used.

2020-12-04

  • Update endpoint for BLVT:

    • GET /sapi/v1/blvt/tokenInfo new fields in response currentBaskets(include symbol, amount , notionalValue ),purchaseFeePct,dailyPurchaseLimit,redeemFeePct,dailyRedeemLimit.
  • New endpoint for BLVT:

    • GET /sapi/v1/blvt/userLimit to get BLVT user limit info.

2020-12-02

  • New endpoints for Sub-Account:
    • GET /sapi/v2/sub-account/futures/account to get detail on sub-account’s USDT margined futures account and COIN margined futures account.
    • GET /sapi/v2/sub-account/futures/accountSummary to get summary of sub-account’s USDT margined futures account and COIN margined futures account.
    • GET /sapi/v2/sub-account/futures/positionRisk to get position risk of sub-account’s USDT margined futures account and COIN margined futures account.

2020-12-01

  • Update Margin Trade Endpoint:
    • POST /sapi/v1/margin/order new parameter quoteOrderQty allow a user to specify the total quoteOrderQty spent or received in the MARKET order.

2020-11-27

New API clusters have been added in order to improve performance.

Users can access any of the following API clusters, in addition to api.binance.com

If there are any performance issues with accessing api.binance.com please try any of the following instead:

  • https://api1.binance.com/api/v3/*
  • https://api2.binance.com/api/v3/*
  • https://api3.binance.com/api/v3/*

2020-11-16

  • Updated endpoints for Margin, new parameter archived to query data from 6 months ago:
    • GET /sapi/v1/margin/loan
    • GET /sapi/v1/margin/repay
    • GET /sapi/v1/margin/interestHistory

2020-11-13

  • New endpoints for Sub-Account:
    • POST /sapi/v1/sub-account/universalTransfer to transfer spot and futures asset between master account and sub accounts.
    • GET /sapi/v1/sub-account/universalTransfer to search transfer records.

2020-11-10

  • New endpoint to toggle BNB Burn:
    • POST /sapi/v1/bnbBurn to toggle BNB Burn on spot trade and margin interest.
    • GET /sapi/v1/bnbBurn to get BNB Burn status.

2020-11-09

  • New field tranId is available from endpoints:
    • GET /sapi/v1/sub-account/futures/internalTransfer
    • GET /sapi/v1/sub-account/transfer/subUserHistory

2020-11-03

  • Update endpoints for Futures Cross-Collateral:

    • GET /sapi/v1/futures/loan/repay/history new fields in response repayType(NORMAL for normal repayment, COLLATERAL for collateral repayment), price (collateral repayment rate), repayCollateral(collateral amount for collateral repayment).
    • GET /sapi/v1/futures/loan/wallet new fields in response totalInterest (total interest for cross-collateral), principalForInterest(cross-collateral principal for interest), interest(cross-collateral interest).
    • GET /sapi/v1/futures/loan/configs new fields in response interestRate (interest rate for cross-collateral), interestGracePeriod (interest grace period for cross-collateral).
  • New endpoints for Futures Cross-Collateral:

    • GET /sapi/v1/futures/loan/collateralRepayLimit to check the maximum and minimum limit when repay with collateral.
    • GET /sapi/v1/futures/loan/collateralRepay to get quote for collateral repayment.
    • POST /sapi/v1/futures/loan/collateralRepay to repay with collateral.
    • GET /sapi/v1/futures/loan/collateralRepayResult to check collateral repayment result.
    • GET /sapi/v1/futures/loan/interestHistory to get cross-collateral interest history.

2020-10-14

  • Update endpoints for Futures Cross-Collateral:
    • POST /sapi/v1/futures/loan/borrow and GET /sapi/v1/futures/loan/borrow/history new field borrowId in response for ID of Cross-Collateral borrow operation.
    • POST /sapi/v1/futures/loan/repay and GET /sapi/v1/futures/loan/repay/history new field repayId in response for ID of Cross-Collateral repay operation.

2020-10-10

  • New type added in the endpoint POST /sapi/v1/sub-account/futures/transferto support transfer asset from subaccount’s spot account to its COIN-margined futures account and transfer asset from subaccount’s COIN-margined futures account to its spot account.

2020-09-30

  • Update endpoints for Margin Account:
    • GET /sapi/v1/margin/maxBorrowable new field borrowLimit in response for account borrow limit.

2020-09-28

  • New endpoints for Binance Savings:
    • POST /sapi/v1/lending/positionChanged to change fixed/activity position to daily position.
  • New parameter ACTIVITY replace REGULARin the following Binance Savings endpoints:
    • GET /sapi/v1/lending/project/list
    • POST /sapi/v1/lending/customizedFixed/purchase
    • GET /sapi/v1/lending/project/position/list
    • GET /sapi/v1/lending/union/purchaseRecord
    • GET /sapi/v1/lending/union/interestHistory

2020-09-23

  • New SAPI endpoints for BSwap:
    • GET /sapi/v1/bswap/pools to list all swap pools.
    • GET /sapi/v1/bswap/liquidity to get liquidity information of a pool.
    • POST /sapi/v1/bswap/liquidityAdd to add liquidity.
    • POST /sapi/v1/bswap/liquidityRemove to remove liquidity.
    • GET /sapi/v1/bswap/liquidityOps to get liquidity operation record.
    • GET /sapi/v1/bswap/quote to request quotes.
    • POST /sapi/v1/bswap/swap to swap.
    • GET /sapi/v1/bswap/swap to get swap history.

2020-09-16

  • New SAPI endpoints for BLVT:

    • GET /sapi/v1/blvt/tokenInfo to get BLVT info.
    • POST /sapi/v1/blvt/subscribe (HMAC SHA256) to subscribe BLVT.
    • GET /sapi/v1/blvt/subscribe/record (HMAC SHA256) to get subscription record。
    • POST /sapi/v1/blvt/redeem (HMAC SHA256) to redeem BLVT.
    • GET /sapi/v1/blvt/redeem/record (HMAC SHA256 to get redemption record.
  • The BLVT NAV system is working relatively with Binance Futures, so some endpoints are based on futures system:

    • New endpoint to get historical BLVT Kline.
    • New WebSocket streams for BLVT Info and BLVT NAV Kline:

2020-09-09

USER DATA STREAM

  • outboundAccountInfo has been deprecated.
  • outboundAccountInfo will be removed in the future. (Exact date unknown) Please use outboundAccountPosition instead.
  • outboundAccountInfo will now only show the balance of non-zero assets and assets that have been reduced to 0.

2020-09-03

  • New endpoint POST /sapi/v1/sub-account/futures/internalTransfer to transfer futures asset between master account and subaccount.
  • New endpointGET /sapi/v1/sub-account/futures/internalTransfer to get futures transfer history of subaccount.

2020-09-01

  • New parameter masterAccountTotalAsset added in the endpoint GET /sapi/v1/sub-account/spotSummary to get BTC valued asset summary of master account.

2020-08-27

  • New endpoint GET /sapi/v1/sub-account/spotSummary to get BTC valued asset summary of subaccout.

2020-08-26

  • New parameter symbols added in the endpoint GET /sapi/v1/margin/isolated/account.

2020-07-28

ISOLATED MARGIN

  • New parameters «isIsolated» and «symbol» added for isolated margin in the following endpoints:

    • POST /sapi/v1/margin/loan
    • POST /sapi/v1/margin/repay
  • New parameter «isIsolated» and new response field «isIsolated» added for isolated margin in the following endpoints:

    • POST /sapi/v1/margin/order
    • DELETE /sapi/v1/margin/order
    • GET /sapi/v1/margin/order
    • GET /sapi/v1/margin/openOrders
    • GET /sapi/v1/margin/allOrders
    • GET /sapi/v1/margin/myTrades
  • New parameter «isolatedSymbol» and new response field «isolatedSymbol» added for isolated margin in the following endpoints:

    • GET /sapi/v1/margin/loan
    • GET /sapi/v1/margin/repay
    • GET /sapi/v1/margin/interestHistory
  • New parameter «isolatedSymbol» and new response field «isIsolated» added for isolated margin in the following endpoint GET /sapi/v1/margin/forceLiquidationRec

  • New parameter «isolatedSymbol» added for isolated margin in the following endpoints:

    • GET /sapi/v1/margin/maxBorrowable
    • GET /sapi/v1/margin/maxTransferable
  • New endpoints for isolated margin:

    • POST /sapi/v1/margin/isolated/create
    • POST /sapi/v1/margin/isolated/transfer
    • GET /sapi/v1/margin/isolated/transfer
    • GET /sapi/v1/margin/isolated/account
    • GET /sapi/v1/margin/isolated/pair
    • GET /sapi/v1/margin/isolated/allPairs
  • New endpoints for listenKey management of isolated margin account:

    • POST /sapi/v1/userDataStream/isolated
    • PUT /sapi/v1/userDataStream/isolated
    • DELETE /sapi/v1/userDataStream/isolated

2020-07-20

  • The max value of parameter «limit» in GET /sapi/v1/margin/allOrders has been changed as 500.

2020-07-17

  • There is now a request limit specifically for the sapi/v1/margin/allOrders endpoint at 60 raw requests per minute for a single IP address.

2020-07-13

  • New SAPI Endpoints for futures Cross-Collateral:
    • POST /sapi/v1/futures/loan/borrow
    • GET /sapi/v1/futures/loan/borrow/history
    • POST /sapi/v1/futures/loan/repay
    • GET /sapi/v1/futures/loan/repay/history
    • GET /sapi/v1/futures/loan/wallet
    • GET /sapi/v1/futures/loan/configs
    • GET /sapi/v1/futures/loan/calcAdjustLevel
    • GET /sapi/v1/futures/loan/calcMaxAdjustAmount
    • POST /sapi/v1/futures/loan/adjustCollateral
    • GET /sapi/v1/futures/loan/adjustCollateral/history
    • GET /sapi/v1/futures/loan/liquidationHistory

2020-06-28

  • SAPI Endpoints for futures:
    • POST /sapi/v1/futures/transfer
    • GET /sapi/v1/futures/transfer

2020-05-06

  • New endpoints for Mining:
    • GET /sapi/v1/mining/pub/algoList
    • GET /sapi/v1/mining/pub/coinList
    • GET /sapi/v1/mining/worker/detail
    • GET /sapi/v1/mining/worker/list
    • GET /sapi/v1/mining/payment/list
    • GET /sapi/v1/mining/statistics/user/status
    • GET /sapi/v1/mining/statistics/user/list

2020-05-01

  • From 2020-05-01 UTC 00:00, all symbols will have a limit of 200 open orders using the MAX_NUM_ORDERS filter.
    • No existing orders will be removed or canceled.
    • Accounts that have 200 or more open orders on a symbol will not be able to place new orders on that symbol until the open order count is below 200.
    • OCO orders count as 2 open orders before the LIMIT order is touched or the STOP_LOSS (or STOP_LOSS_LIMIT) order is triggered; once this happens the other order is canceled and will no longer count as an open order.

2020-04-25

SPOT API

  • New field permissions
    • Defines the trading permissions that are allowed on accounts and symbols.
    • permissions is an enum array; values:
      • SPOT
      • MARGIN
    • permissions will replace isSpotTradingAllowed and isMarginTradingAllowed on GET api/v3/exchangeInfo in future API versions (v4+).
    • For an account to trade on a symbol, the account and symbol must share at least 1 permission in common.
  • Updates to GET api/v3/exchangeInfo
    • New field permissions added.
    • New field quoteAssetPrecision added; a duplicate of the quotePrecision field. quotePrecision will be removed in future API versions (v4+).
  • Updates to GET api/v3/account
    • New field permissions added.
  • New endpoint DELETE api/v3/openOrders
    • This will allow a user to cancel all open orders on a single symbol.
    • This endpoint will cancel all open orders including OCO orders.
  • Orders can be canceled via the API on symbols in the BREAK or HALT status.

USER DATA STREAM

  • OutboundAccountInfo has new field P which shows the trading permissions of the account.

2020-04-23

WEB SOCKET STREAM

  • WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
    • A PING frame
    • A PONG frame
    • A JSON control message (e.g. subscribe, unsubscribe)
  • A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
  • A single connection can listen to a maximum of 1024 streams.

2020-04-16

  • New fields in response to endpointGET /sapi/v1/lending/daily/token/position

    • todayPurchasedAmount for user’s purchased amount today
  • New lending endpoints for customized fixed projects:

    • GET /sapi/v1/lending/project/list
    • POST /sapi/v1/lending/customizedFixed/purchase
    • GET /sapi/v1/lending/project/position/list

2020-04-02

  • New fields in response to endpointGET /sapi/v1/capital/config/getall
    • minConfirm for min number for balance confirmation
    • unLockConfirm for confirmation number for balance unlock

2020-03-24

  • MAX_POSITION filter added.

    • This filter defines the allowed maximum position an account can have on the base asset of a symbol. An account’s position defined as the sum of the account’s:
      • free balance of the base asset
      • locked balance of the base asset
      • sum of the qty of all open BUY orders
    • BUY orders will be rejected if the account’s position is greater than the maximum position allowed.

2020-03-13

  • New parameter transactionFeeFlag is available in endpoint:
    • POST /sapi/v1/capital/withdraw/apply and
    • POST /wapi/v3/withdraw.html

2020-02-05

  • New sub account endpoints:
    • POST /sapi/v1/sub-account/futures/transfer to transfer between futures and spot accout of sub-account.
    • POST /sapi/v1/sub-account/margin/transfer to transfer between margin and spot accout of sub-account.
    • POST /sapi/v1/sub-account/transfer/subToSub to transfer to another account by sub-account.
    • POST /sapi/v1/sub-account/transfer/subToMaster to transfer to same master by sub-account.
    • GET /sapi/v1/sub-account/transfer/subUserHistory to get transfer history of sub-account.

2020-01-15

  • New parameter withdrawOrderId for client customized withdraw id for endpoint POST /wapi/v3/withdraw.html.

  • New field withdrawOrderId in response to GET /wapi/v3/withdrawHistory.html


2019-12-25

  • New endpoints for Binance Savings:

    • GET /sapi/v1/lending/daily/product/list
    • GET /sapi/v1/lending/daily/userLeftQuota
    • POST /sapi/v1/lending/daily/purchase
    • GET /sapi/v1/lending/daily/userRedemptionQuota
    • POST /sapi/v1/lending/daily/redeem
    • GET /sapi/v1/lending/daily/token/position
    • GET /sapi/v1/lending/union/account
    • GET /sapi/v1/lending/union/purchaseRecord
    • GET /sapi/v1/lending/union/redemptionRecord
    • GET /sapi/v1/lending/union/interestHistory
  • Added time interval limit in
    GET /sapi/v1/capital/withdraw/history,
    GET /wapi/v3/withdrawHistory.html,
    GET /sapi/v1/capital/deposit/hisrec and
    GET /wapi/v3/depositHistory.html:

    • The default startTime is 90 days from current time, and the default endTime is current time.
    • Please notice the default startTime and endTime to make sure that time interval is within 0-90 days.
    • If both startTime and endTime are sent, time between startTime and endTime must be less than 90 days.

2019-12-18

  • New endpoint to get daily snapshot of account:
    GET /sapi/v1/accountSnapshot

2019-11-30

  • Added parameter sideEffectType in POST /sapi/v1/margin/order (HMAC SHA256) with enums:

    • NO_SIDE_EFFECT for normal trade order;
    • MARGIN_BUY for margin trade order;
    • AUTO_REPAY for making auto repayment after order filled.
  • New field marginBuyBorrowAmount and marginBuyBorrowAsset in FULL response to POST /sapi/v1/margin/order (HMAC SHA256)


2019-11-28

  • New SAPI endpont to disable fast withdraw switch:

    POST /sapi/v1/account/disableFastWithdrawSwitch (HMAC SHA256)
  • New SAPI endpont to enable fast withdraw switch:

    POST /sapi/v1/account/enableFastWithdrawSwitch (HMAC SHA256)

2019-11-22

  • Quote Order Qty Market orders have been enabled on all symbols.
    • Quote Order Qty MARKET orders allow a user to specify the total quoteOrderQty spent or received in the MARKET order.
    • Quote Order Qty MARKET orders will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty.
    • Using BNBBTC as an example:
      • On the BUY side, the order will buy as many BNB as quoteOrderQty BTC can.
      • On the SELL side, the order will sell as much BNB as needed to receive quoteOrderQty BTC.

2019-11-19

  • GET /sapi/v1/sub-account/margin/account has new field:
    marginTradeCoeffVo which contains

    • forceLiquidationBar for liquidation margin ratio
    • marginCallBar for margin call margin ratio
    • normalBar for initial margin ratio

2019-11-13

Rest API

  • api/v3/exchangeInfo has new fields:
    • quoteOrderQtyMarketAllowed
    • baseCommissionPrecision
    • quoteCommissionPrecision
  • MARKET orders have a new optional field: quoteOrderQty used to specify the quote quantity to BUY or SELL. This cannot be used in combination with quantity.
    • The exact timing that quoteOrderQty MARKET orders will be enabled is TBD. There will be a separate announcement and further details at that time.
  • All order query endpoints will return a new field origQuoteOrderQty in the JSON payload. (e.g. GET api/v3/allOrders)
    {
      "code": -1128,
      "msg": "Combination of optional parameters invalid. Recommendation: 'stopLimitTimeInForce' should also be sent."
    }
  • Updated error messages for -1128

    • Sending an OCO with a stopLimitPrice but without a stopLimitTimeInForce will return the error:
  • Updated error messages for -1003 to specify the limit is referring to the request weight, not to the number of requests.

Deprecation of v1 endpoints:

By end of Q1 2020, the following endpoints will be removed from the API. The documentation has been updated to use the v3 versions of these endpoints.

  • GET api/v1/depth
  • GET api/v1/historicalTrades
  • GET api/v1/aggTrades
  • GET api/v1/klines
  • GET api/v1/ticker/24hr
  • GET api/v1/ticker/price
  • GET api/v1/exchangeInfo
  • POST api/v1/userDataStream
  • PUT api/v1/userDataStream
  • GET api/v1/ping
  • GET api/v1/time
  • GET api/v1/ticker/bookTicker

These endpoints however, will NOT be migrated to v3. Please use the following endpoints instead moving forward.

Old V1 Endpoints New V3 Endpoints
GET api/v1/ticker/allPrices GET api/v3/ticker/price
GET api/v1/ticker/allBookTickers GET api/v3/ticker/bookTicker

USER DATA STREAM

  • Changes toexecutionReport event

    • If the C field is empty, it will now properly return null, instead of "null".
    • New field Q which represents the quoteOrderQty.
  • balanceUpdate event type added

    • This event occurs when funds are deposited or withdrawn from your account.

WEB SOCKET STREAM

  • WSS now supports live subscribing/unsubscribing to streams.

2019-11-08

  • New sapi for subaccount management on margin and futures:
    • GET /sapi/v1/sub-account/status (HMAC SHA256)
    • POST /sapi/v1/sub-account/margin/enable (HMAC SHA256)
    • GET /sapi/v1/sub-account/margin/account (HMAC SHA256)
    • GET /sapi/v1/sub-account/margin/accountSummary (HMAC SHA256)
    • POST /sapi/v1/sub-account/futures/enable (HMAC SHA256)
    • GET /sapi/v1/sub-account/futures/account (HMAC SHA256)
    • GET /sapi/v1/sub-account/futures/accountSummary (HMAC SHA256)
    • GET /sapi/v1/sub-account/futures/positionRisk (HMAC SHA256)

2019-11-04

  • New sapi endpoints for subaccount wallet.
    • GET /sapi/v1/capital/deposit/subAddress (HMAC SHA256)): fetch subaccount deposit address.
    • GET /sapi/v1/capital/deposit/subHisrec (HMAC SHA256)): fetch subaccount deposit history.

2019-10-29

  • New sapi endpoints for wallet.
    • POST /sapi/v1/capital/withdraw/apply (HMAC SHA256): withdraw.
    • Get /sapi/v1/capital/withdraw/history (HMAC SHA256): fetch withdraw history with network.

2019-10-14

  • New sapi endpoints for wallet.
    • GET /sapi/v1/capital/config/getall (HMAC SHA256): get all coins’ information for user.
    • GET /sapi/v1/capital/deposit/hisrec (HMAC SHA256): fetch deposit history with network.
    • GET /sapi/v1/capital/deposit/address (HMAC SHA256): fetch deposit address with network.

2019-10-11

  • Added parameter network in POST /wapi/v3/withdraw.html so that asset can be withdrawed with specific network.

2019-09-09

  • New WebSocket streams for bookTickers added: <symbol>@bookTicker and !bookTicker.

2019-09-03

  • Faster order book data with 100ms updates: <symbol>@depth@100ms and <symbol>@depth#@100ms
  • Added «Update Speed:» to Websocket Market Streams
  • Removed deprecated v1 endpoints as per previous announcement:
    • GET api/v1/order
    • GET api/v1/openOrders
    • POST api/v1/order
    • DELETE api/v1/order
    • GET api/v1/allOrders
    • GET api/v1/account
    • GET api/v1/myTrades

2019-08-16

  • GET api/v1/depth limit of 10000 has been temporarily removed

  • In Q4 2017, the following endpoints were deprecated and removed from the API documentation. They have been permanently removed from the API as of this version. We apologize for the omission from the original changelog:

    • GET api/v1/order
    • GET api/v1/openOrders
    • POST api/v1/order
    • DELETE api/v1/order
    • GET api/v1/allOrders
    • GET api/v1/account
    • GET api/v1/myTrades
  • Streams, endpoints, parameters, payloads, etc. described in the documents in this repository are considered official and supported. The use of any other streams, endpoints, parameters, or payloads, etc. is not supported; use them at your own risk and with no guarantees.


2019-09-15

Rest API

  • New order type: OCO («One Cancels the Other»)

    • An OCO has 2 orders: (also known as legs in financial terms)
      • STOP_LOSS or STOP_LOSS_LIMIT leg
      • LIMIT_MAKER leg
    • Price Restrictions:
      • SELL Orders : Limit Price > Last Price > Stop Price
      • BUY Orders : Limit Price < Last Price < Stop Price
      • As stated, the prices must «straddle» the last traded price on the symbol. EX: If the last price is 10:
        • A SELL OCO must have the limit price greater than 10, and the stop price less than 10.
        • A BUY OCO must have a limit price less than 10, and the stop price greater than 10.
    • Quantity Restrictions:
      • Both legs must have the same quantity.
      • ICEBERG quantities however, do not have to be the same.
    • Execution Order:
      • If the LIMIT_MAKER is touched, the limit maker leg will be executed first BEFORE canceling the Stop Loss Leg.
      • if the Market Price moves such that the STOP_LOSS or STOP_LOSS_LIMIT will trigger, the Limit Maker leg will be cancelled BEFORE executing the STOP_LOSS Leg.
    • Cancelling an OCO
      • Cancelling either order leg will cancel the entire OCO.
      • The entire OCO can be canceled via the orderListId or the listClientOrderId.
    • New Enums for OCO:
      1. ListStatusType
        • RESPONSE — used when ListStatus is responding to a failed action. (either order list placement or cancellation)
        • EXEC_STARTED — used when an order list has been placed or there is an update to a list’s status.
        • ALL_DONE — used when an order list has finished executing and is no longer active.
      2. ListOrderStatus
        • EXECUTING — used when an order list has been placed or there is an update to a list’s status.
        • ALL_DONE — used when an order list has finished executing and is no longer active.
        • REJECT — used when ListStatus is responding to a failed action. (either order list placement or cancellation)
      3. ContingencyType
        • OCO — specifies the type of order list.
    • New Endpoints:
      • POST api/v3/order/oco
      • DELETE api/v3/orderList
      • GET api/v3/orderList
  • recvWindow cannot exceed 60000.

  • New intervalLetter values for headers:

    • SECOND => S
    • MINUTE => M
    • HOUR => H
    • DAY => D
  • New Headers X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) will give your current used request weight for the (intervalNum)(intervalLetter) rate limiter. For example, if there is a one minute request rate weight limiter set, you will get a X-MBX-USED-WEIGHT-1M header in the response. The legacy header X-MBX-USED-WEIGHT will still be returned and will represent the current used weight for the one minute request rate weight limit.

  • New Header X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)that is updated on any valid order placement and tracks your current order count for the interval; rejected/unsuccessful orders are not guaranteed to have X-MBX-ORDER-COUNT-** headers in the response.

    • Eg. X-MBX-ORDER-COUNT-1S for «orders per 1 second» and X-MBX-ORDER-COUNT-1D for orders per «one day»
  • GET api/v1/depth now supports limit 5000 and 10000; weights are 50 and 100 respectively.

  • GET api/v1/exchangeInfo has a new parameter ocoAllowed.

USER DATA STREAM

  • executionReport event now contains «g» which has the orderListId; it will be set to -1 for non-OCO orders.
  • New Event Type listStatus; listStatus is sent on an update to any OCO order.
  • New Event Type outboundAccountPosition; outboundAccountPosition is sent any time an account’s balance changes and contains the assets that could have changed by the event that generated the balance change (a deposit, withdrawal, trade, order placement, or cancelation).

NEW ERRORS

  • -1131 BAD_RECV_WINDOW
    • recvWindow must be less than 60000
  • -1099 Not found, authenticated, or authorized
    • This replaces error code -1999

NEW -2011 ERRORS

  • OCO_BAD_ORDER_PARAMS
    • A parameter for one of the orders is incorrect.
  • OCO_BAD_PRICES
    • The relationship of the prices for the orders is not correct.
  • UNSUPPORTED_ORD_OCO
    • OCO orders are not supported for this symbol.

2019-03-12

Rest API

  • X-MBX-USED-WEIGHT header added to Rest API responses.
  • Retry-After header added to Rest API 418 and 429 responses.
  • When canceling the Rest API can now return errorCode -1013 OR -2011 if the symbol’s status isn’t TRADING.
  • api/v1/depth no longer has the ignored and empty [].
  • api/v3/myTrades now returns quoteQty; the price * qty of for the trade.

Websocket streams

  • <symbol>@depth and <symbol>@depthX streams no longer have the ignored and empty [].

System improvements

  • Matching Engine stability/reliability improvements.
  • Rest API performance improvements.

2018-11-13

Rest API

  • Can now cancel orders through the Rest API during a trading ban.
  • New filters: PERCENT_PRICE, MARKET_LOT_SIZE, MAX_NUM_ICEBERG_ORDERS.
  • Added RAW_REQUESTS rate limit. Limits based on the number of requests over X minutes regardless of weight.
  • /api/v3/ticker/price increased to weight of 2 for a no symbol query.
  • /api/v3/ticker/bookTicker increased weight of 2 for a no symbol query.
  • DELETE /api/v3/order will now return an execution report of the final state of the order.
  • MIN_NOTIONAL filter has two new parameters: applyToMarket (whether or not the filter is applied to MARKET orders) and avgPriceMins (the number of minutes over which the price averaged for the notional estimation).
  • intervalNum added to /api/v1/exchangeInfo limits. intervalNum describes the amount of the interval. For example: intervalNum 5, with interval minute, means «every 5 minutes».

Explanation for the average price calculation:

  1. (qty * price) of all trades / sum of qty of all trades over previous 5 minutes.

  2. If there is no trade in the last 5 minutes, it takes the first trade that happened outside of the 5min window.
    For example if the last trade was 20 minutes ago, that trade’s price is the 5 min average.

  3. If there is no trade on the symbol, there is no average price and market orders cannot be placed.
    On a new symbol with applyToMarket enabled on the MIN_NOTIONAL filter, market orders cannot be placed until there is at least 1 trade.

  4. The current average price can be checked here: https://api.binance.com/api/v3/avgPrice?symbol=<symbol>
    For example:
    https://api.binance.com/api/v3/avgPrice?symbol=BNBUSDT

User data stream

  • Last quote asset transacted quantity (as variable Y) added to execution reports. Represents the lastPrice * lastQty (L * l).

2018-07-18

Rest API

  • New filter: ICEBERG_PARTS
  • POST api/v3/order new defaults for newOrderRespType. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
  • POST api/v3/order RESULT and FULL responses now have cummulativeQuoteQty
  • GET api/v3/openOrders with no symbol weight reduced to 40.
  • GET api/v3/ticker/24hr with no symbol weight reduced to 40.
  • Max amount of trades from GET /api/v1/trades increased to 1000.
  • Max amount of trades from GET /api/v1/historicalTrades increased to 1000.
  • Max amount of aggregate trades from GET /api/v1/aggTrades increased to 1000.
  • Max amount of aggregate trades from GET /api/v1/klines increased to 1000.
  • Rest API Order lookups now return updateTime which represents the last time the order was updated; time is the order creation time.
  • Order lookup endpoints will now return cummulativeQuoteQty. If cummulativeQuoteQty is < 0, it means the data isn’t available for this order at this time.
  • REQUESTS rate limit type changed to REQUEST_WEIGHT. This limit was always logically request weight and the previous name for it caused confusion.

User data stream

  • cummulativeQuoteQty field added to order responses and execution reports (as variable Z). Represents the cummulative amount of the quote that has been spent (with a BUY order) or received (with a SELL order). Historical orders will have a value < 0 in this field indicating the data is not available at this time. cummulativeQuoteQty divided by cummulativeQty will give the average price for an order.
  • O (order creation time) added to execution reports

2018-01-23

  • GET /api/v1/historicalTrades weight decreased to 5
  • GET /api/v1/aggTrades weight decreased to 1
  • GET /api/v1/klines weight decreased to 1
  • GET /api/v1/ticker/24hr all symbols weight decreased to number of trading symbols / 2
  • GET /api/v3/allOrders weight decreased to 5
  • GET /api/v3/myTrades weight decreased to 5
  • GET /api/v3/account weight decreased to 5
  • GET /api/v1/depth limit=500 weight decreased to 5
  • GET /api/v1/depth limit=1000 weight decreased to 10
  • -1003 error message updated to direct users to websockets

2018-01-20

  • GET /api/v1/ticker/24hr single symbol weight decreased to 1
  • GET /api/v3/openOrders all symbols weight decreased to number of trading symbols / 2
  • GET /api/v3/allOrders weight decreased to 15
  • GET /api/v3/myTrades weight decreased to 15
  • GET /api/v3/order weight decreased to 1
  • myTrades will now return both sides of a self-trade/wash-trade

2018-01-14

  • GET /api/v1/aggTrades weight changed to 2
  • GET /api/v1/klines weight changed to 2
  • GET /api/v3/order weight changed to 2
  • GET /api/v3/allOrders weight changed to 20
  • GET /api/v3/account weight changed to 20
  • GET /api/v3/myTrades weight changed to 20
  • GET /api/v3/historicalTrades weight changed to 20

Introduction

API Key Setup

  • Some endpoints will require an API Key. Please refer to this page regarding API key creation.
  • Once API key is created, it is recommended to set IP restrictions on the key for security reasons.
  • Never share your API key/secret key to ANYONE.

API Key Restrictions

  • After creating the API key, the default restrictions is Enable Reading.
  • To enable withdrawals via the API, the API key restriction needs to be modified through the Binance UI.

Enabling Accounts

Spot Account

A SPOT account is provided by default upon creation of a Binance Account.

Margin Account

To enable a MARGIN account for Margin Trading, please refer to the Margin Trading Guide

Spot Testnet

Users can use the SPOT Testnet to practice SPOT trading.

Currently, this is only available via the API.

Please refer to the SPOT Testnet page for more information and how to set up the Testnet API key.

API Library

Python connector

This is a lightweight library that works as a connector to Binance public API, written in Python.

https://github.com/binance/binance-connector-python

Node.js connector

This is a lightweight library that works as a connector to Binance public API, written for Node.js users.

https://github.com/binance/binance-connector-node

Ruby connector

This is a lightweight library that works as a connector to Binance public API, written for Ruby users.

https://github.com/binance/binance-connector-ruby

DotNET connector

This is a lightweight library that works as a connector to Binance public API, written for C# users.

https://github.com/binance/binance-connector-dotnet

Java connector

This is a lightweight library that works as a connector to Binance public API, written for Java users.

https://github.com/binance/binance-connector-java

Postman Collections

There is now a Postman collection containing the API endpoints for quick and easy use.

This is recommended for new users who want to get a quick-start into using the API.

For more information please refer to this page: Binance API Postman

Swagger

A YAML file with OpenAPI specification on the RESTful API is available to be used, as well as a Swagger UI page for the consulting.

https://github.com/binance/binance-api-swagger

  • Binance API Telegram Group
    • For any questions in sudden drop in performance with the API and/or Websockets.
    • For any general questions about the API not covered in the documentation.
  • Binance Developers
    • For any questions on your code implementation with the API and/or Websockets.
  • Binance Customer Support
    • For cases such as missing funds, help with 2FA, etc.

General Info

General API Information

  • The following base endpoints are available:
    • https://api.binance.com
    • https://api1.binance.com
    • https://api2.binance.com
    • https://api3.binance.com
    • https://api4.binance.com
  • All endpoints are equal in functionality.
    Performance may vary between the base endpoints and can be freely switched between them to find which one works best for one’s setup.
  • All endpoints return either a JSON object or array.
  • Data is returned in ascending order. Oldest first, newest last.
  • All time and timestamp related fields are in milliseconds.
  • The base endpoint https://data.binance.com can be used to access the following API endpoints that have NONE as security type:
    • GET /api/v3/aggTrades
    • GET /api/v3/avgPrice
    • GET /api/v3/depth
    • GET /api/v3/exchangeInfo
    • GET /api/v3/klines
    • GET /api/v3/ping
    • GET /api/v3/ticker
    • GET /api/v3/ticker/24hr
    • GET /api/v3/ticker/bookTicker
    • GET /api/v3/ticker/price
    • GET /api/v3/time
    • GET /api/v3/trades
    • GET /api/v3/uiKlines

HTTP Return Codes

  • HTTP 4XX return codes are used for malformed requests;
    the issue is on the sender’s side.
  • HTTP 403 return code is used when the WAF Limit (Web Application Firewall) has been violated.
  • HTTP 409 return code is used when a cancelReplace order partially succeeds. (e.g. if the cancellation of the order fails but the new order placement succeeds.)
  • HTTP 429 return code is used when breaking a request rate limit.
  • HTTP 418 return code is used when an IP has been auto-banned for continuing to send requests after receiving 429 codes.
  • HTTP 5XX return codes are used for internal errors; the issue is on
    Binance’s side.
    It is important to NOT treat this as a failure operation; the execution status is
    UNKNOWN and could have been a success.

Error Codes and Messages

  • If there is an error, the API will return an error with a message of the reason.

The error payload on API and SAPI is as follows:

{
  "code": -1121,
  "msg": "Invalid symbol."
}
  • Specific error codes and messages defined in Error Codes.

General Information on Endpoints

  • For GET endpoints, parameters must be sent as a query string.
  • For POST, PUT, and DELETE endpoints, the parameters may be sent as a
    query string or in the request body with content type
    application/x-www-form-urlencoded. You may mix parameters between both the
    query string and request body if you wish to do so.
  • Parameters may be sent in any order.
  • If a parameter sent in both the query string and request body, the
    query string parameter will be used.

LIMITS

General Info on Limits

  • The following intervalLetter values for headers:
    • SECOND => S
    • MINUTE => M
    • HOUR => H
    • DAY => D
  • intervalNum describes the amount of the interval. For example, intervalNum 5 with intervalLetter M means «Every 5 minutes».
  • The /api/v3/exchangeInfo rateLimits array contains objects related to the exchange’s RAW_REQUESTS, REQUEST_WEIGHT, and ORDERS rate limits. These are further defined in the ENUM definitions section under Rate limiters (rateLimitType).
  • A 429 will be returned when either request rate limit or order rate limit is violated.

IP Limits

  • Every request will contain X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) in the response headers which has the current used weight for the IP for all request rate limiters defined.
  • Each route has a weight which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier weight.
  • When a 429 is received, it’s your obligation as an API to back off and not spam the API.
  • Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).
  • IP bans are tracked and scale in duration for repeat offenders, from 2 minutes to 3 days.
  • A Retry-After header is sent with a 418 or 429 responses and will give the number of seconds required to wait, in the case of a 429, to prevent a ban, or, in the case of a 418, until the ban is over.
  • The limits on the API are based on the IPs, not the API keys.

Order Rate Limits

  • Every successful order response will contain a X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter) header which has the current order count for the account for all order rate limiters defined.

  • When the order count exceeds the limit, you will receive a 429 error without the Retry-After header. Please check the Order Rate Limit rules using GET api/v3/exchangeInfo and wait for reactivation accordingly.

  • Rejected/unsuccessful orders are not guaranteed to have X-MBX-ORDER-COUNT-** headers in the response.

  • The order rate limit is counted against each account.

  • To monitor order count usage, refer to GET api/v3/rateLimit/order

Websocket Limits

  • WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
    • A PING frame
    • A PONG frame
    • A JSON controlled message (e.g. subscribe, unsubscribe)
  • A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
  • A single connection can listen to a maximum of 1024 streams.
  • There is a limit of 300 connections per attempt every 5 minutes per IP.

/api/ and /sapi/ Limit Introduction

The /api/* and /sapi/* endpoints adopt either of two access limiting rules, IP limits or UID (account) limits.

  • Endpoints related to /api/*:

    • According to the two modes of IP and UID (account) limit, each are independent.
    • Endpoints share the 1200 per minute limit based on IP.
    • Responses contain the header X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter), defining the weight used by the current IP.
    • Successful order responses contain the header X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter), defining the order limit used by the UID.
  • Endpoints related to /sapi/*:

    • Endpoints are marked according to IP or UID limit and their corresponding weight value.
    • Each endpoint with IP limits has an independent 12000 per minute limit.
    • Each endpoint with UID limits has an independent 180000 per minute limit.
    • Responses from endpoints with IP limits contain the header X-SAPI-USED-IP-WEIGHT-1M, defining the weight used by the current IP.
    • Responses from endpoints with UID limits contain the header X-SAPI-USED-UID-WEIGHT-1M, defining the weight used by the current UID.

Data Sources

  • The API system is asynchronous, so some delay in the response is normal and expected.
  • Each endpoint has a data source indicating where the data is being retrieved, and thus which endpoints have the most up-to-date response.

These are the three sources, ordered by which is has the most up-to-date response to the one with potential delays in updates.

  • Matching Engine — the data is from the matching Engine
  • Memory — the data is from a server’s local or external memory
  • Database — the data is taken directly from a database

Endpoint security type

  • Each endpoint has a security type that determines how you will
    interact with it. This is stated next to the NAME of the endpoint.

    • If no security type is stated, assume the security type is NONE.
  • API-keys are passed into the Rest API via the X-MBX-APIKEY
    header.
  • API-keys and secret-keys are case sensitive.
  • API-keys can be configured to only access certain types of secure endpoints.
    For example, one API-key could be used for TRADE only, while another API-key
    can access everything except for TRADE routes.
  • By default, API-keys can access all secure routes.
Security Type Description
NONE Endpoint can be accessed freely.
TRADE Endpoint requires sending a valid API-Key and signature.
MARGIN Endpoint requires sending a valid API-Key and signature.
USER_DATA Endpoint requires sending a valid API-Key and signature.
USER_STREAM Endpoint requires sending a valid API-Key.
MARKET_DATA Endpoint requires sending a valid API-Key.
  • TRADE, MARGIN and USER_DATA endpoints are SIGNED endpoints.

SIGNED (TRADE, USER_DATA, AND MARGIN) Endpoint security

  • SIGNED endpoints require an additional parameter, signature, to be
    sent in the query string or request body.
  • Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation.
    Use your secretKey as the key and totalParams as the value for the HMAC operation.
  • The signature is not case sensitive.
  • totalParams is defined as the query string concatenated with the
    request body.

Timing security

  • A SIGNED endpoint also requires a parameter, timestamp, to be sent which
    should be the millisecond timestamp of when the request was created and sent.
  • An additional parameter, recvWindow, may be sent to specify the number of
    milliseconds after timestamp the request is valid for. If recvWindow
    is not sent, it defaults to 5000.

The logic is as follows:

  if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow)
  {
    // process request
  } 
  else 
  {
    // reject request
  }

Serious trading is about timing. Networks can be unstable and unreliable,
which can lead to requests taking varying amounts of time to reach the
servers. With recvWindow, you can specify that the request must be
processed within a certain number of milliseconds or be rejected by the
server.

SIGNED Endpoint Examples for POST /api/v3/order — HMAC Keys

Here is a step-by-step example of how to send a vaild signed payload from the
Linux command line using echo, openssl, and curl.

Key Value
apiKey vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A
secretKey NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j
Parameter Value
symbol LTCBTC
side BUY
type LIMIT
timeInForce GTC
quantity 1
price 0.1
recvWindow 5000
timestamp 1499827319559

Example 1: As a request body

Example 1

HMAC SHA256 signature:

    $ echo -n "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559" | openssl dgst -sha256 -hmac "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    (stdin)= c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71

curl command:

    (HMAC SHA256)
    $ curl -H "X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" -X POST 'https://api.binance.com/api/v3/order' -d 'symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71'

  • requestBody:

symbol=LTCBTC
&side=BUY
&type=LIMIT
&timeInForce=GTC
&quantity=1
&price=0.1
&recvWindow=5000
&timestamp=1499827319559

Example 2: As a query string

Example 2

HMAC SHA256 signature:

    $ echo -n "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559" | openssl dgst -sha256 -hmac "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    (stdin)= c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71

curl command:

    (HMAC SHA256)
   $ curl -H "X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" -X POST 'https://api.binance.com/api/v3/order?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71'

  • queryString:

symbol=LTCBTC
&side=BUY
&type=LIMIT
&timeInForce=GTC
&quantity=1
&price=0.1
&recvWindow=5000
&timestamp=1499827319559

Example 3: Mixed query string and request body

Example 3

HMAC SHA256 signature:

   $ echo -n "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTCquantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559" | openssl dgst -sha256 -hmac "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
    (stdin)= 0fd168b8ddb4876a0358a8d14d0c9f3da0e9b20c5d52b2a00fcf7d1c602f9a77

curl command:

    (HMAC SHA256)
    $ curl -H "X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" -X POST 'https://api.binance.com/api/v3/order?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC' -d 'quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=0fd168b8ddb4876a0358a8d14d0c9f3da0e9b20c5d52b2a00fcf7d1c602f9a77'
  • queryString:

symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC

  • requestBody:

quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559

Note that the signature is different in example 3.
There is no & between «GTC» and «quantity=1».

SIGNED Endpoint Example for POST /api/v3/order — RSA Keys

  • This will be a step by step process how to create the signature payload to send a valid signed payload.
  • We support PKCS#8 currently.
  • To get your API key, you need to upload your RSA Public Key to your account and a corresponding API key will be provided for you.

For this example, the private key will be referenced as test-prv-key.pem

Key Value
apiKey CAvIjXy3F44yW6Pou5k8Dy1swsYDWJZLeoK2r8G4cFDnE9nosRppc2eKc1T8TRTQ
Parameter Value
symbol BTCUSDT
side SELL
type LIMIT
timeInForce GTC
quantity 1
price 0.2
recvWindow 5000
timestamp 1668481559918

Signature payload (with the listed parameters):

symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918&recvWindow=5000

Step 1: Construct the payload

Arrange the list of parameters into a string. Separate each parameter with a &.

Step 2: Compute the signature:

2.1 — Encode signature payload as ASCII data.

Step 2.2

 $ echo -n 'symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918&recvWindow=5000' | openssl dgst -sha256 -sign ./test-prv-key.pem

2.2 — Sign payload using RSASSA-PKCS1-v1_5 algorithm with SHA-256 hash function.

Step 2.3

$  echo -n 'symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918&recvWindow=5000' | openssl dgst -sha256 -sign ./test-prv-key.pem | openssl enc -base64 -A
HZ8HOjiJ1s/igS9JA+n7+7Ti/ihtkRF5BIWcPIEluJP6tlbFM/Bf44LfZka/iemtahZAZzcO9TnI5uaXh3++lrqtNonCwp6/245UFWkiW1elpgtVAmJPbogcAv6rSlokztAfWk296ZJXzRDYAtzGH0gq7CgSJKfH+XxaCmR0WcvlKjNQnp12/eKXJYO4tDap8UCBLuyxDnR7oJKLHQHJLP0r0EAVOOSIbrFang/1WOq+Jaq4Efc4XpnTgnwlBbWTmhWDR1pvS9iVEzcSYLHT/fNnMRxFc7u+j3qI//5yuGuu14KR0MuQKKCSpViieD+fIti46sxPTsjSemoUKp0oXA==

2.3 — Encode output as base64 string.

Step 2.4

HZ8HOjiJ1s%2FigS9JA%2Bn7%2B7Ti%2FihtkRF5BIWcPIEluJP6tlbFM%2FBf44LfZka%2FiemtahZAZzcO9TnI5uaXh3%2B%2BlrqtNonCwp6%2F245UFWkiW1elpgtVAmJPbogcAv6rSlokztAfWk296ZJXzRDYAtzGH0gq7CgSJKfH%2BXxaCmR0WcvlKjNQnp12%2FeKXJYO4tDap8UCBLuyxDnR7oJKLHQHJLP0r0EAVOOSIbrFang%2F1WOq%2BJaq4Efc4XpnTgnwlBbWTmhWDR1pvS9iVEzcSYLHT%2FfNnMRxFc7u%2Bj3qI%2F%2F5yuGuu14KR0MuQKKCSpViieD%2BfIti46sxPTsjSemoUKp0oXA%3D%3D

2.4 — Since the signature may contain / and =, this could cause issues with sending the request. So the signature has to be URL encoded.

Step 2.5

 curl -H "X-MBX-APIKEY: CAvIjXy3F44yW6Pou5k8Dy1swsYDWJZLeoK2r8G4cFDnE9nosRppc2eKc1T8TRTQ" -X POST 'https://api.binance.com/api/v3/order?symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2&timestamp=1668481559918recvWindow=5000&signature=HZ8HOjiJ1s%2FigS9JA%2Bn7%2B7Ti%2FihtkRF5BIWcPIEluJP6tlbFM%2FBf44LfZka%2FiemtahZAZzcO9TnI5uaXh3%2B%2BlrqtNonCwp6%2F245UFWkiW1elpgtVAmJPbogcAv6rSlokztAfWk296ZJXzRDYAtzGH0gq7CgSJKfH%2BXxaCmR0WcvlKjNQnp12%2FeKXJYO4tDap8UCBLuyxDnR7oJKLHQHJLP0r0EAVOOSIbrFang%2F1WOq%2BJaq4Efc4XpnTgnwlBbWTmhWDR1pvS9iVEzcSYLHT%2FfNnMRxFc7u%2Bj3qI%2F%2F5yuGuu14KR0MuQKKCSpViieD%2BfIti46sxPTsjSemoUKp0oXA%3D%3D'

2.5 — curl command

Bash script

#!/usr/bin/env bash

# Set up authentication:
API_KEY="put your own API Key here"
PRIVATE_KEY_PATH="test-prv-key.pem"

# Set up the request:
API_METHOD="POST"
API_CALL="api/v3/order"
API_PARAMS="symbol=BTCUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1&price=0.2"

# Sign the request:
timestamp=$(date +%s000)
api_params_with_timestamp="$API_PARAMS&timestamp=$timestamp"
signature=$(echo -n "$api_params_with_timestamp" 
            | openssl dgst -sha256 -sign "$PRIVATE_KEY_PATH" 
            | openssl enc -base64 -A)

# Send the request:
curl -H "X-MBX-APIKEY: $API_KEY" -X "$API_METHOD" 
    "https://api.binance.com/$API_CALL?$api_params_with_timestamp" 
    --data-urlencode "signature=$signature"

A sample Bash script containing similar steps is available in the right side.


Public API Definitions

Terminology

These terms will be used throughout the documentation, so it is recommended especially for new users to read to help their understanding of the API.

  • base asset refers to the asset that is the quantity of a symbol. For the symbol BTCUSDT, BTC would be the base asset.
  • quote asset refers to the asset that is the price of a symbol. For the symbol BTCUSDT, USDT would be the quote asset.

ENUM definitions

Symbol status (status):

  • PRE_TRADING
  • TRADING
  • POST_TRADING
  • END_OF_DAY
  • HALT
  • AUCTION_MATCH
  • BREAK

Account and Symbol Permissions (permissions):

  • SPOT
  • MARGIN
  • LEVERAGED
  • TRD_GRP_002
  • TRD_GRP_003
  • TRD_GRP_004
  • TRD_GRP_005
  • TRD_GRP_006
  • TRD_GRP_007

Order status (status):

Status Description
NEW The order has been accepted by the engine.
PARTIALLY_FILLED A part of the order has been filled.
FILLED The order has been completed.
CANCELED The order has been canceled by the user.
PENDING_CANCEL Currently unused
REJECTED The order was not accepted by the engine and not processed.
EXPIRED The order was canceled according to the order type’s rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during liquidation, orders canceled during maintenance)
EXPIRED_IN_MATCH The order was canceled by the exchange due to STP trigger. (e.g. an order with EXPIRE_TAKER will match with existing orders on the book with the same account or same tradeGroupId)

OCO Status (listStatusType):

Status Description
RESPONSE This is used when the ListStatus is responding to a failed action. (E.g. Orderlist placement or cancellation)
EXEC_STARTED The order list has been placed or there is an update to the order list status.
ALL_DONE The order list has finished executing and thus no longer active.

OCO Order Status (listOrderStatus):

Status Description
EXECUTING Either an order list has been placed or there is an update to the status of the list.
ALL_DONE An order list has completed execution and thus no longer active.
REJECT The List Status is responding to a failed action either during order placement or order canceled.)

ContingencyType

  • OCO

Order types (orderTypes, type):

  • LIMIT
  • MARKET
  • STOP_LOSS
  • STOP_LOSS_LIMIT
  • TAKE_PROFIT
  • TAKE_PROFIT_LIMIT
  • LIMIT_MAKER

Order Response Type (newOrderRespType):

  • ACK
  • RESULT
  • FULL

Order side (side):

  • BUY
  • SELL

Time in force (timeInForce):

This sets how long an order will be active before expiration.

Status Description
GTC Good Til Canceled

An order will be on the book unless the order is canceled.

IOC Immediate Or Cancel

An order will try to fill the order as much as it can before the order expires.

FOK Fill or Kill

An order will expire if the full order cannot be filled upon execution.

Kline/Candlestick chart intervals:

s-> seconds; m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

  • 1s
  • 1m
  • 3m
  • 5m
  • 15m
  • 30m
  • 1h
  • 2h
  • 4h
  • 6h
  • 8h
  • 12h
  • 1d
  • 3d
  • 1w
  • 1M

Rate limiters (rateLimitType)

REQUEST_WEIGHT

    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 1200
    }

ORDERS

    {
      "rateLimitType": "ORDERS",
      "interval": "SECOND",
      "intervalNum": 10,
      "limit": 100
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "DAY",
      "intervalNum": 1,
      "limit": 200000
    }

RAW_REQUESTS

    {
      "rateLimitType": "RAW_REQUESTS",
      "interval": "MINUTE",
      "intervalNum": 5,
      "limit": 5000
    }
  • REQUEST_WEIGHT

  • ORDERS

  • RAW_REQUESTS

Rate limit intervals (interval)

  • SECOND
  • MINUTE
  • DAY

Filters

Filters define trading rules on a symbol or an exchange.
Filters come in two forms: symbol filters and exchange filters.

Symbol Filters

PRICE_FILTER

ExchangeInfo format:

  {
    "filterType": "PRICE_FILTER",
    "minPrice": "0.00000100",
    "maxPrice": "100000.00000000",
    "tickSize": "0.00000100"
  }

The PRICE_FILTER defines the price rules for a symbol. There are 3 parts:

  • minPrice defines the minimum price/stopPrice allowed; disabled on minPrice == 0.
  • maxPrice defines the maximum price/stopPrice allowed; disabled on maxPrice == 0.
  • tickSize defines the intervals that a price/stopPrice can be increased/decreased by; disabled on tickSize == 0.

Any of the above variables can be set to 0, which disables that rule in the price filter. In order to pass the price filter, the following must be true for price/stopPrice of the enabled rules:

  • price >= minPrice
  • price <= maxPrice
  • price % tickSize == 0

PERCENT_PRICE

ExchangeInfo format:

  {
    "filterType": "PERCENT_PRICE",
    "multiplierUp": "1.3000",
    "multiplierDown": "0.7000",
    "avgPriceMins": 5
  }

The PERCENT_PRICE filter defines the valid range for the price based on the average of the previous trades.
avgPriceMins is the number of minutes the average price is calculated over. 0 means the last price is used.

In order to pass the percent price, the following must be true for price:

  • price <= weightedAveragePrice * multiplierUp
  • price >= weightedAveragePrice * multiplierDown

PERCENT_PRICE_BY_SIDE

ExchangeInfo format:

    {
          "filterType": "PERCENT_PRICE_BY_SIDE",
          "bidMultiplierUp": "1.2",
          "bidMultiplierDown": "0.2",
          "askMultiplierUp": "5",
          "askMultiplierDown": "0.8",
          "avgPriceMins": 1
    }

The PERCENT_PRICE_BY_SIDE filter defines the valid range for the price based on the average of the previous trades.

avgPriceMins is the number of minutes the average price is calculated over. 0 means the last price is used.

There is a different range depending on whether the order is placed on the BUY side or the SELL side.

Buy orders will succeed on this filter if:

  • Order price <= weightedAveragePrice * bidMultiplierUp
  • Order price >= weightedAveragePrice * bidMultiplierDown

Sell orders will succeed on this filter if:

  • Order Price <= weightedAveragePrice * askMultiplierUp
  • Order Price >= weightedAveragePrice * askMultiplierDown

LOT_SIZE

ExchangeInfo format:

  {
    "filterType": "LOT_SIZE",
    "minQty": "0.00100000",
    "maxQty": "100000.00000000",
    "stepSize": "0.00100000"
  }

The LOT_SIZE filter defines the quantity (aka «lots» in auction terms) rules for a symbol. There are 3 parts:

  • minQty defines the minimum quantity/icebergQty allowed.
  • maxQty defines the maximum quantity/icebergQty allowed.
  • stepSize defines the intervals that a quantity/icebergQty can be increased/decreased by.

In order to pass the lot size, the following must be true for quantity/icebergQty:

  • quantity >= minQty
  • quantity <= maxQty
  • quantity % stepSize == 0

MIN_NOTIONAL

ExchangeInfo format:

  {
    "filterType": "MIN_NOTIONAL",
    "minNotional": "0.00100000",
    "applyToMarket": true,
    "avgPriceMins": 5
  }

The MIN_NOTIONAL filter defines the minimum notional value allowed for an order on a symbol.
An order’s notional value is the price * quantity.
If the order is an Algo order (e.g. STOP_LOSS_LIMIT), then the notional value of the stopPrice * quantity will also be evaluated.
If the order is an Iceberg Order, then the notional value of the price * icebergQty will also be evaluated.
applyToMarket determines whether or not the MIN_NOTIONAL filter will also be applied to MARKET orders.
Since MARKET orders have no price, the average price is used over the last avgPriceMins minutes.
avgPriceMins is the number of minutes the average price is calculated over. 0 means the last price is used.

NOTIONAL

ExchangeInfo format:

{
   "filterType": "NOTIONAL",
   "minNotional": "10.00000000",
   "applyMinToMarket": false,
   "maxNotional": "10000.00000000",
   "applyMaxToMarket": false,
   "avgPriceMins": 5
}

The NOTIONAL filter defines the acceptable notional range allowed for an order on a symbol.

applyMinToMarket determines whether the minNotional will be applied to MARKET orders.

applyMaxToMarket determines whether the maxNotional will be applied to MARKET orders.

In order to pass this filter, the notional (price * quantity) has to pass the following conditions:

  • price * quantity <= maxNotional
  • price * quantity >= minNotional

For MARKET orders, the average price used over the last avgPriceMins minutes will be used for calculation.

If the avgPriceMins is 0, then the last price will be used.

ICEBERG_PARTS

ExchangeInfo format:

  {
    "filterType": "ICEBERG_PARTS",
    "limit": 10
  }

The ICEBERG_PARTS filter defines the maximum parts an iceberg order can have. The number of ICEBERG_PARTS is defined as CEIL(qty / icebergQty).

MARKET_LOT_SIZE

ExchangeInfo format:

  {
    "filterType": "MARKET_LOT_SIZE",
    "minQty": "0.00100000",
    "maxQty": "100000.00000000",
    "stepSize": "0.00100000"
  }

The MARKET_LOT_SIZE filter defines the quantity (aka «lots» in auction terms) rules for MARKET orders on a symbol. There are 3 parts:

  • minQty defines the minimum quantity allowed.
  • maxQty defines the maximum quantity allowed.
  • stepSize defines the intervals that a quantity can be increased/decreased by.

In order to pass the market lot size, the following must be true for quantity:

  • quantity >= minQty
  • quantity <= maxQty
  • quantity % stepSize == 0

MAX_NUM_ORDERS

ExchangeInfo format:

  {
    "filterType": "MAX_NUM_ORDERS",
    "maxNumOrders": 25
  }

The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol.
Note that both «algo» orders and normal orders are counted for this filter.

MAX_NUM_ALGO_ORDERS

ExchangeInfo format:

  {
    "filterType": "MAX_NUM_ALGO_ORDERS",
    "maxNumAlgoOrders": 5
  }

The MAX_NUM_ALGO_ORDERS filter defines the maximum number of «algo» orders an account is allowed to have open on a symbol.
«Algo» orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.

MAX_NUM_ICEBERG_ORDERS

The MAX_NUM_ICEBERG_ORDERS filter defines the maximum number of ICEBERG orders an account is allowed to have open on a symbol.
An ICEBERG order is any order where the icebergQty is > 0.

ExchangeInfo format:

  {
    "filterType": "MAX_NUM_ICEBERG_ORDERS",
    "maxNumIcebergOrders": 5
  }

MAX_POSITION

The MAX_POSITION filter defines the allowed maximum position an account can have on the base asset of a symbol.
An account’s position defined as the sum of the account’s:

  1. free balance of the base asset
  2. locked balance of the base asset
  3. sum of the qty of all open BUY orders

BUY orders will be rejected if the account’s position is greater than the maximum position allowed.

If an order’s quantity can cause the position to overflow, this will also fail the MAX_POSITION filter.

ExchangeInfo format:

{
  "filterType":"MAX_POSITION",
  "maxPosition":"10.00000000"
}

TRAILING_DELTA

ExchangeInfo format:

    {
          "filterType": "TRAILING_DELTA",
          "minTrailingAboveDelta": 10,
          "maxTrailingAboveDelta": 2000,
          "minTrailingBelowDelta": 10,
          "maxTrailingBelowDelta": 2000
   }

The TRAILING_DELTA filter defines the minimum and maximum value for the parameter trailingDelta.

In order for a trailing stop order to pass this filter, the following must be true:

For STOP_LOSS BUY, STOP_LOSS_LIMIT_BUY,TAKE_PROFIT SELL and TAKE_PROFIT_LIMIT SELL orders:

  • trailingDelta >= minTrailingAboveDelta
  • trailingDelta <= maxTrailingAboveDelta

For STOP_LOSS SELL, STOP_LOSS_LIMIT SELL, TAKE_PROFIT BUY, and TAKE_PROFIT_LIMIT BUY orders:

  • trailingDelta >= minTrailingBelowDelta
  • trailingDelta <= maxTrailingBelowDelta

Exchange Filters

EXCHANGE_MAX_NUM_ORDERS

ExchangeInfo format:

  {
    "filterType": "EXCHANGE_MAX_NUM_ORDERS",
    "maxNumOrders": 1000
  }

The EXCHANGE_MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on the exchange.
Note that both «algo» orders and normal orders are counted for this filter.

EXCHANGE_MAX_NUM_ALGO_ORDERS

ExchangeInfo format:

  {
    "filterType": "EXCHANGE_MAX_NUM_ALGO_ORDERS",
    "maxNumAlgoOrders": 200
  }

The EXCHANGE_MAX_NUM_ALGO_ORDERS filter defines the maximum number of «algo» orders an account is allowed to have open on the exchange.
«Algo» orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.

EXCHANGE_MAX_NUM_ICEBERG_ORDERS

The EXCHANGE_MAX_NUM_ICEBERG_ORDERS filter defines the maximum number of iceberg orders an account is allowed to have open on the exchange.

ExchangeInfo format:

{
  "filterType": "EXCHANGE_MAX_NUM_ICEBERG_ORDERS",
  "maxNumIcebergOrders": 10000
}

Wallet Endpoints

System Status (System)

Response

{ 
    "status": 0,              // 0: normal,1:system maintenance
    "msg": "normal"           // "normal", "system_maintenance"
}


GET /sapi/v1/system/status

Fetch system status.

Weight(IP):
1

All Coins’ Information (USER_DATA)

Get information of coins (available for deposit and withdraw) for user.

Response:

[
    {
        "coin": "BTC",
        "depositAllEnable": true,
        "free": "0.08074558",
        "freeze": "0.00000000",
        "ipoable": "0.00000000",
        "ipoing": "0.00000000",
        "isLegalMoney": false,
        "locked": "0.00000000",
        "name": "Bitcoin",
        "networkList": [
            {
                "addressRegex": "^(bnb1)[0-9a-z]{38}$",
                "coin": "BTC",
                "depositDesc": "Wallet Maintenance, Deposit Suspended", // shown only when "depositEnable" is false.
                "depositEnable": false,
                "isDefault": false,        
                "memoRegex": "^[0-9A-Za-z\-_]{1,120}$",
                "minConfirm": 1,  // min number for balance confirmation
                "name": "BEP2",
                "network": "BNB",            
                "resetAddressStatus": false,
                "specialTips": "Both a MEMO and an Address are required to successfully deposit your BEP2-BTCB tokens to Binance.",
                "unLockConfirm": 0,  // confirmation number for balance unlock 
                "withdrawDesc": "Wallet Maintenance, Withdrawal Suspended", // shown only when "withdrawEnable" is false.
                "withdrawEnable": false,
                "withdrawFee": "0.00000220",
                "withdrawIntegerMultiple": "0.00000001",
                "withdrawMax": "9999999999.99999999",
                "withdrawMin": "0.00000440",
                "sameAddress": true,  // If the coin needs to provide memo to withdraw
                "estimatedArrivalTime": 25,
                "busy": false
            },
            {
                "addressRegex": "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^(bc1)[0-9A-Za-z]{39,59}$",
                "coin": "BTC",
                "depositEnable": true,
                "isDefault": true,
                "memoRegex": "",
                "minConfirm": 1, 
                "name": "BTC",
                "network": "BTC",
                "resetAddressStatus": false,
                "specialTips": "",
                "unLockConfirm": 2,
                "withdrawEnable": true,
                "withdrawFee": "0.00050000",
                "withdrawIntegerMultiple": "0.00000001",
                "withdrawMax": "750",
                "withdrawMin": "0.00100000",
                "sameAddress": false,
                "estimatedArrivalTime": 25,
                "busy": false
            }
        ],
        "storage": "0.00000000",
        "trading": true,
        "withdrawAllEnable": true,
        "withdrawing": "0.00000000"
    }
]


GET /sapi/v1/capital/config/getall (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Daily Account Snapshot (USER_DATA)

Response:

{
   "code":200, // 200 for success; others are error codes
   "msg":"", // error message
   "snapshotVos":[
      {
         "data":{
            "balances":[
               {
                  "asset":"BTC",
                  "free":"0.09905021",
                  "locked":"0.00000000"
               },
               {
                  "asset":"USDT",
                  "free":"1.89109409",
                  "locked":"0.00000000"
               }
            ],
            "totalAssetOfBtc":"0.09942700"
         },
         "type":"spot",
         "updateTime":1576281599000
      }
   ]
}

OR

{
   "code":200, // 200 for success; others are error codes
   "msg":"", // error message
   "snapshotVos":[
      {
         "data":{
            "marginLevel":"2748.02909813",
            "totalAssetOfBtc":"0.00274803",
            "totalLiabilityOfBtc":"0.00000100",
            "totalNetAssetOfBtc":"0.00274750",
            "userAssets":[
               {
                  "asset":"XRP",
                  "borrowed":"0.00000000",
                  "free":"1.00000000",
                  "interest":"0.00000000",
                  "locked":"0.00000000",
                  "netAsset":"1.00000000"
               }
            ]
         },
         "type":"margin",
         "updateTime":1576281599000
      }
   ]
}

OR

{
   "code":200, // 200 for success; others are error codes
   "msg":"", // error message
   "snapshotVos":[
      {
         "data":{
            "assets":[
               {
                  "asset":"USDT",
                  "marginBalance":"118.99782335", // Not real-time data, can ignore
                  "walletBalance":"120.23811389"
               }
            ],
            "position":[
               {
                  "entryPrice":"7130.41000000",
                  "markPrice":"7257.66239673",
                  "positionAmt":"0.01000000",
                  "symbol":"BTCUSDT",
                  "unRealizedProfit":"1.24029054"  // Only show the value at the time of opening the position
               }
            ]
         },
         "type":"futures",
         "updateTime":1576281599000
      }
   ]
}


GET /sapi/v1/accountSnapshot (HMAC SHA256)

Weight(IP):
2400

Parameters:

Name Type Mandatory Description
type STRING YES «SPOT», «MARGIN», «FUTURES»
startTime LONG NO
endTime LONG NO
limit INT NO min 7, max 30, default 7
recvWindow LONG NO
timestamp LONG YES
  • The query time period must be less then 30 days
  • Support query within the last one month only
  • If startTimeand endTime not sent, return records of the last 7 days by default

Disable Fast Withdraw Switch (USER_DATA)

Response:

{}


POST /sapi/v1/account/disableFastWithdrawSwitch (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES
  • Caution:

    This request will disable fastwithdraw switch under your account.

    You need to enable «trade» option for the api key which requests this endpoint.

Enable Fast Withdraw Switch (USER_DATA)

Response:

{}


POST /sapi/v1/account/enableFastWithdrawSwitch (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES
  • This request will enable fastwithdraw switch under your account.

    You need to enable «trade» option for the api key which requests this endpoint.

  • When Fast Withdraw Switch is on, transferring funds to a Binance account will be done instantly. There is no on-chain transaction, no transaction ID and no withdrawal fee.

Withdraw(USER_DATA)

Response:

{
    "id":"7213fea8e94b4a5593d507237e5a555b"
}


POST /sapi/v1/capital/withdraw/apply (HMAC SHA256)

Submit a withdraw request.

Weight(UID):
600

Parameters:

Name Type Mandatory Description
coin STRING YES
withdrawOrderId STRING NO client id for withdraw
network STRING NO
address STRING YES
addressTag STRING NO Secondary address identifier for coins like XRP,XMR etc.
amount DECIMAL YES
transactionFeeFlag BOOLEAN NO When making internal transfer, true for returning the fee to the destination account; false for returning the fee back to the departure account. Default false.
name STRING NO Description of the address. Space in name should be encoded into %20.
walletType INTEGER NO The wallet type for withdraw,0-spot wallet ,1-funding wallet. Default walletType is the current «selected wallet» under wallet->Fiat and Spot/Funding->Deposit
recvWindow LONG NO
timestamp LONG YES
  • If network not send, return with default network of the coin.
  • You can get network and isDefault in networkList of a coin in the response of Get /sapi/v1/capital/config/getall (HMAC SHA256).

Deposit History (supporting network) (USER_DATA)

Response:

[
    {
        "id": "769800519366885376",
        "amount": "0.001",
        "coin": "BNB",
        "network": "BNB",
        "status": 0,
        "address": "bnb136ns6lfw4zs5hg4n85vdthaad7hq5m4gtkgf23",
        "addressTag": "101764890",
        "txId": "98A3EA560C6B3336D348B6C83F0F95ECE4F1F5919E94BD006E5BF3BF264FACFC",
        "insertTime": 1661493146000,
        "transferType": 0,
        "confirmTimes": "1/1",
        "unlockConfirm": 0,
        "walletType": 0
    },
    {
        "id": "769754833590042625",
        "amount":"0.50000000",
        "coin":"IOTA",
        "network":"IOTA",
        "status":1,
        "address":"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW",
        "addressTag":"",
        "txId":"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999",
        "insertTime":1599620082000,
        "transferType":0,
        "confirmTimes": "1/1",
        "unlockConfirm": 0,
        "walletType": 0
    }
]


GET /sapi/v1/capital/deposit/hisrec (HMAC SHA256)

Fetch deposit history.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
coin STRING NO
status INT NO 0(0:pending,6: credited but cannot withdraw, 7=Wrong Deposit,8=Waiting User confirm, 1:success)
startTime LONG NO Default: 90 days from current timestamp
endTime LONG NO Default: present timestamp
offset INT NO Default:0
limit INT NO Default:1000, Max:1000
recvWindow LONG NO
timestamp LONG YES
txId STRING NO
  • Please notice the default startTime and endTime to make sure that time interval is within 0-90 days.
  • If both startTime and endTime are sent, time between startTime and endTime must be less than 90 days.

Withdraw History (supporting network) (USER_DATA)

Response:

[
  {
    "id": "b6ae22b3aa844210a7041aee7589627c",  // Withdrawal id in Binance
    "amount": "8.91000000",   // withdrawal amount
    "transactionFee": "0.004", // transaction fee
    "coin": "USDT",
    "status": 6,
    "address": "0x94df8b352de7f46f64b01d3666bf6e936e44ce60",
    "txId": "0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268"   // withdrawal transaction id
    "applyTime": "2019-10-12 11:12:02",  // UTC time
    "network": "ETH",
    "transferType": 0 // 1 for internal transfer, 0 for external transfer   
    "withdrawOrderId": "WITHDRAWtest123", // // will not be returned if there's no withdrawOrderId for this withdraw.
    "info": "The address is not valid. Please confirm with the recipient",  // reason for withdrawal failure
    "confirmNo":3,  // confirm times for withdraw
    "walletType": 1,  //1: Funding Wallet 0:Spot Wallet
    "txKey": "",
    "completeTime": "2023-03-23 16:52:41" // complete UTC time when user's asset is deduct from withdrawing, only if status =  6(success)
  },
  {
    "id": "156ec387f49b41df8724fa744fa82719",
    "amount": "0.00150000",
    "transactionFee": "0.004",
    "coin": "BTC",
    "status": 6,
    "address": "1FZdVHtiBqMrWdjPyRPULCUceZPJ2WLCsB",
    "txId": "60fd9007ebfddc753455f95fafa808c4302c836e4d1eebc5a132c36c1d8ac354"
    "applyTime": "2019-09-24 12:43:45",
    "network": "BTC",
    "transferType": 0, 
    "info": "",
    "confirmNo": 2,
    "walletType": 1,
    "txKey": "",
    "completeTime": "2023-03-23 16:52:41" 
  }
]


GET /sapi/v1/capital/withdraw/history (HMAC SHA256)

Fetch withdraw history.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
coin STRING NO
withdrawOrderId STRING NO
status INT NO 0(0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6:Completed)
offset INT NO
limit INT NO Default: 1000, Max: 1000
startTime LONG NO Default: 90 days from current timestamp
endTime LONG NO Default: present timestamp
recvWindow LONG NO
timestamp LONG YES
  • network may not be in the response for old withdraw.
  • Please notice the default startTime and endTime to make sure that time interval is within 0-90 days.
  • If both startTime and endTimeare sent, time between startTimeand endTimemust be less than 90 days.
  • If withdrawOrderId is sent, time between startTime and endTime must be less than 7 days.
  • If withdrawOrderId is sent, startTime and endTime are not sent, will return last 7 days records by default.

Deposit Address (supporting network) (USER_DATA)

Response:

{
    "address": "1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv",
    "coin": "BTC",
    "tag": "",
    "url": "https://btc.com/1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv"
}


GET /sapi/v1/capital/deposit/address (HMAC SHA256)

Fetch deposit address with network.

Weight(IP):
10

Parameters:

Name Type Mandatory Description
coin STRING YES
network STRING NO
recvWindow LONG NO
timestamp LONG YES
  • If network is not send, return with default network of the coin.
  • You can get network and isDefault in networkList in the response of Get /sapi/v1/capital/config/getall (HMAC SHA256).

Account Status (USER_DATA)

Response:

{
    "data": "Normal"
}


GET /sapi/v1/account/status

Fetch account status detail.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Account API Trading Status (USER_DATA)

Response:

{
    "data": {          // API trading status detail
            "isLocked": false,   // API trading function is locked or not
            "plannedRecoverTime": 0,  // If API trading function is locked, this is the planned recover time
            "triggerCondition": { 
                    "GCR": 150,  // Number of GTC orders
                    "IFER": 150, // Number of FOK/IOC orders
                    "UFR": 300   // Number of orders
            },
            "updateTime": 1547630471725   
    }
}


GET /sapi/v1/account/apiTradingStatus (HMAC SHA256)

Fetch account api trading status detail.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

DustLog(USER_DATA)

Response

{
        "total": 8,   //Total counts of exchange
        "userAssetDribblets": [
            {
                "operateTime": 1615985535000,
                "totalTransferedAmount": "0.00132256",   // Total transfered BNB amount for this exchange.
                "totalServiceChargeAmount": "0.00002699",    //Total service charge amount for this exchange.
                "transId": 45178372831,
                "userAssetDribbletDetails": [           //Details of  this exchange.
                    {
                        "transId": 4359321,
                        "serviceChargeAmount": "0.000009",
                        "amount": "0.0009",
                        "operateTime": 1615985535000,
                        "transferedAmount": "0.000441",
                        "fromAsset": "USDT"
                    },
                    {
                        "transId": 4359321,
                        "serviceChargeAmount": "0.00001799",
                        "amount": "0.0009",
                        "operateTime": 1615985535000,
                        "transferedAmount": "0.00088156",
                        "fromAsset": "ETH"
                    }
                ]
            },
            {
                "operateTime":1616203180000,
                "totalTransferedAmount": "0.00058795",
                "totalServiceChargeAmount": "0.000012",
                "transId": 4357015,
                "userAssetDribbletDetails": [       
                    {
                        "transId": 4357015,
                        "serviceChargeAmount": "0.00001",
                        "amount": "0.001",
                        "operateTime": 1616203180000,
                        "transferedAmount": "0.00049",
                        "fromAsset": "USDT"
                    },
                    {
                        "transId": 4357015,
                        "serviceChargeAmount": "0.000002",         
                        "amount": "0.0001",
                        "operateTime": 1616203180000,
                        "transferedAmount": "0.00009795",
                        "fromAsset": "ETH"
                    }
                ]
            }
        ]
    }
}


GET /sapi/v1/asset/dribblet (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
startTime LONG NO
endTime LONG NO
recvWindow LONG NO
timestamp LONG YES
  • Only return last 100 records
  • Only return records after 2020/12/01

Get Assets That Can Be Converted Into BNB (USER_DATA)

Response

{
    "details": [
        {
            "asset": "ADA",         
            "assetFullName": "ADA", 
            "amountFree": "6.21",   //Convertible amount
            "toBTC": "0.00016848",  //BTC amount
            "toBNB": "0.01777302",  //BNB amount(Not deducted commission fee)
            "toBNBOffExchange": "0.01741756", //BNB amount(Deducted commission fee)
            "exchange": "0.00035546" //Commission fee
        }
    ],
    "totalTransferBtc": "0.00016848",
    "totalTransferBNB": "0.01777302",
    "dribbletPercentage": "0.02"     //Commission fee
}  


POST /sapi/v1/asset/dust-btc (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Dust Transfer (USER_DATA)

Response:

{
    "totalServiceCharge":"0.02102542",
    "totalTransfered":"1.05127099",
    "transferResult":[
        {
            "amount":"0.03000000",
            "fromAsset":"ETH",
            "operateTime":1563368549307,
            "serviceChargeAmount":"0.00500000",
            "tranId":2970932918,
            "transferedAmount":"0.25000000"
        },
        {
            "amount":"0.09000000",
            "fromAsset":"LTC",
            "operateTime":1563368549404,
            "serviceChargeAmount":"0.01548000",
            "tranId":2970932918,
            "transferedAmount":"0.77400000"
        },
        {
            "amount":"248.61878453",
            "fromAsset":"TRX",
            "operateTime":1563368549489,
            "serviceChargeAmount":"0.00054542",
            "tranId":2970932918,
            "transferedAmount":"0.02727099"
        }
    ]
}


POST /sapi/v1/asset/dust (HMAC SHA256)

Convert dust assets to BNB.

Weight(UID):
10

Parameters:

Name Type Mandatory Description
asset ARRAY YES The asset being converted. For example: asset=BTC,USDT
recvWindow LONG NO
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Asset Dividend Record (USER_DATA)

Response:

{
    "rows":[
        {
            "id":1637366104,
            "amount":"10.00000000",
            "asset":"BHFT",
            "divTime":1563189166000,
            "enInfo":"BHFT distribution",
            "tranId":2968885920
        },
        {
            "id":1631750237,
            "amount":"10.00000000",
            "asset":"BHFT",
            "divTime":1563189165000,
            "enInfo":"BHFT distribution",
            "tranId":2968885920
        }
    ],
    "total":2
}


GET /sapi/v1/asset/assetDividend (HMAC SHA256)

Query asset dividend record.

Weight(IP):
10

Parameters:

Name Type Mandatory Description
asset STRING NO
startTime LONG NO
endTime LONG NO
limit INT NO Default 20, max 500
recvWindow LONG NO
timestamp LONG YES
  • There cannot be more than 180 days between parameter startTime and endTime.

Asset Detail (USER_DATA)

Response:

{
        "CTR": {
            "minWithdrawAmount": "70.00000000", //min withdraw amount
            "depositStatus": false,//deposit status (false if ALL of networks' are false)
            "withdrawFee": 35, // withdraw fee
            "withdrawStatus": true, //withdraw status (false if ALL of networks' are false)
            "depositTip": "Delisted, Deposit Suspended" //reason
        },
        "SKY": {
            "minWithdrawAmount": "0.02000000",
            "depositStatus": true,
            "withdrawFee": 0.01,
            "withdrawStatus": true
        }   
}


GET /sapi/v1/asset/assetDetail (HMAC SHA256)

Fetch details of assets supported on Binance.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
recvWindow LONG NO
timestamp LONG YES
  • Please get network and other deposit or withdraw details from GET /sapi/v1/capital/config/getall.

Trade Fee (USER_DATA)

Response:

[
    {
        "symbol": "ADABNB",
        "makerCommission": "0.001",
        "takerCommission": "0.001"
    },
    {
        "symbol": "BNBBTC",
        "makerCommission": "0.001",
        "takerCommission": "0.001"
    }
]


GET /sapi/v1/asset/tradeFee (HMAC SHA256)

Fetch trade fee

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING NO
recvWindow LONG NO
timestamp LONG YES

User Universal Transfer (USER_DATA)

Response:

{
    "tranId":13526853623
}


POST /sapi/v1/asset/transfer (HMAC SHA256)

You need to enable Permits Universal Transfer option for the API Key which requests this endpoint.

Weight(UID):
900

Parameters:

Name Type Mandatory Description
type ENUM YES
asset STRING YES
amount DECIMAL YES
fromSymbol STRING NO
toSymbol STRING NO
recvWindow LONG NO
timestamp LONG YES
  • fromSymbol must be sent when type are ISOLATEDMARGIN_MARGIN and ISOLATEDMARGIN_ISOLATEDMARGIN
  • toSymbol must be sent when type are MARGIN_ISOLATEDMARGIN and ISOLATEDMARGIN_ISOLATEDMARGIN

  • ENUM of transfer types:

    • MAIN_UMFUTURE Spot account transfer to USDⓈ-M Futures account
    • MAIN_CMFUTURE Spot account transfer to COIN-M Futures account
    • MAIN_MARGIN Spot account transfer to Margin(cross)account
    • UMFUTURE_MAIN USDⓈ-M Futures account transfer to Spot account
    • UMFUTURE_MARGIN USDⓈ-M Futures account transfer to Margin(cross)account
    • CMFUTURE_MAIN COIN-M Futures account transfer to Spot account
    • CMFUTURE_MARGIN COIN-M Futures account transfer to Margin(cross) account
    • MARGIN_MAIN Margin(cross)account transfer to Spot account
    • MARGIN_UMFUTURE Margin(cross)account transfer to USDⓈ-M Futures
    • MARGIN_CMFUTURE Margin(cross)account transfer to COIN-M Futures
    • ISOLATEDMARGIN_MARGIN Isolated margin account transfer to Margin(cross) account
    • MARGIN_ISOLATEDMARGIN Margin(cross) account transfer to Isolated margin account
    • ISOLATEDMARGIN_ISOLATEDMARGIN Isolated margin account transfer to Isolated margin account
    • MAIN_FUNDING Spot account transfer to Funding account
    • FUNDING_MAIN Funding account transfer to Spot account
    • FUNDING_UMFUTURE Funding account transfer to UMFUTURE account
    • UMFUTURE_FUNDING UMFUTURE account transfer to Funding account
    • MARGIN_FUNDING MARGIN account transfer to Funding account
    • FUNDING_MARGIN Funding account transfer to Margin account
    • FUNDING_CMFUTURE Funding account transfer to CMFUTURE account
    • CMFUTURE_FUNDING CMFUTURE account transfer to Funding account
    • MAIN_OPTION Spot account transfer to Options account
    • OPTION_MAIN Options account transfer to Spot account
    • UMFUTURE_OPTION USDⓈ-M Futures account transfer to Options account
    • OPTION_UMFUTURE Options account transfer to USDⓈ-M Futures account
    • MARGIN_OPTION Margin(cross)account transfer to Options account
    • OPTION_MARGIN Options account transfer to Margin(cross)account
    • FUNDING_OPTION Funding account transfer to Options account
    • OPTION_FUNDING Options account transfer to Funding account
    • MAIN_PORTFOLIO_MARGIN Spot account transfer to Portfolio Margin account
    • PORTFOLIO_MARGIN_MAIN Portfolio Margin account transfer to Spot account

Query User Universal Transfer History (USER_DATA)

Response:

{
    "total":2,
    "rows":[
        {
            "asset":"USDT",
            "amount":"1",
            "type":"MAIN_UMFUTURE",
            "status": "CONFIRMED", // status: CONFIRMED / FAILED / PENDING
            "tranId": 11415955596,
            "timestamp":1544433328000
        },
        {
            "asset":"USDT",
            "amount":"2",
            "type":"MAIN_UMFUTURE",
            "status": "CONFIRMED",
            "tranId": 11366865406,
            "timestamp":1544433328000
        }
    ]
}


GET /sapi/v1/asset/transfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
type ENUM YES
startTime LONG NO
endTime LONG NO
current INT NO Default 1
size INT NO Default 10, Max 100
fromSymbol STRING NO
toSymbol STRING NO
recvWindow LONG NO
timestamp LONG YES
  • fromSymbol must be sent when type are ISOLATEDMARGIN_MARGIN and ISOLATEDMARGIN_ISOLATEDMARGIN
  • toSymbol must be sent when type are MARGIN_ISOLATEDMARGIN and ISOLATEDMARGIN_ISOLATEDMARGIN
  • Support query within the last 6 months only
  • If startTimeand endTime not sent, return records of the last 7 days by default

Funding Wallet (USER_DATA)

Response

[
    {
        "asset": "USDT",
        "free": "1",    // avalible balance
        "locked": "0",  // locked asset
        "freeze": "0",  // freeze asset
        "withdrawing": "0",  
        "btcValuation": "0.00000091"  
    }
]


POST /sapi/v1/asset/get-funding-asset (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
needBtcValuation STRING NO true or false
recvWindow LONG NO
timestamp LONG YES
  • Currently supports querying the following business assets:Binance Pay, Binance Card, Binance Gift Card, Stock Token

User Asset (USER_DATA)

Response

[
  {
    "asset": "AVAX",
    "free": "1",
    "locked": "0",
    "freeze": "0",
    "withdrawing": "0",
    "ipoable": "0",
    "btcValuation": "0"
  },
  {
    "asset": "BCH",
    "free": "0.9",
    "locked": "0",
    "freeze": "0",
    "withdrawing": "0",
    "ipoable": "0",
    "btcValuation": "0"
  },
  {
    "asset": "BNB",
    "free": "887.47061626",
    "locked": "0",
    "freeze": "10.52",
    "withdrawing": "0.1",
    "ipoable": "0",
    "btcValuation": "0"
  },
  {
    "asset": "BUSD",
    "free": "9999.7",
    "locked": "0",
    "freeze": "0",
    "withdrawing": "0",
    "ipoable": "0",
    "btcValuation": "0"
  },
  {
    "asset": "SHIB",
    "free": "532.32",
    "locked": "0",
    "freeze": "0",
    "withdrawing": "0",
    "ipoable": "0",
    "btcValuation": "0"
  },
  {
    "asset": "USDT",
    "free": "50300000001.44911105",
    "locked": "0",
    "freeze": "0",
    "withdrawing": "0",
    "ipoable": "0",
    "btcValuation": "0"
  },
  {
    "asset": "WRZ",
    "free": "1",
    "locked": "0",
    "freeze": "0",
    "withdrawing": "0",
    "ipoable": "0",
    "btcValuation": "0"
  }
]


POST /sapi/v3/asset/getUserAsset

Get user assets, just for positive data.

Weight(IP):
5

Parameters:

Name Type Mandatory Description
asset STRING NO If asset is blank, then query all positive assets user have.
needBtcValuation BOOLEAN NO Whether need btc valuation or not.
recvWindow LONG NO
timestamp LONG YES
  • If asset is set, then return this asset, otherwise return all assets positive.
  • If needBtcValuation is set, then return btcValudation.

BUSD Convert (TRADE)

Response

{
  "tranId": 118263407119,
  "status": "S"
}


POST /sapi/v1/asset/convert-transfer

Convert transfer, convert between BUSD and stablecoins.

Weight(UID):
5

Parameters:

Name Type Mandatory Description
clientTranId STRING YES The unique user-defined transaction id, min length 20
asset STRING YES The current asset
amount BigDecimal YES The amount must be positive number
targetAsset String YES Target asset you want to convert
accountType String NO Only MAIN and CARD, default MAIN
  • If the clientTranId has been used before, will not do the convert transfer, the original transfer will be returned.

BUSD Convert History (USER_DATA)

Response

{
  "total":3,
  "rows":
  [
    {
      "tranId":118263615991,
      "type":244,
      "time":1664442078000,
      "deductedAsset":"BUSD",
      "deductedAmount":"1",
      "targetAsset":"USDC",
      "targetAmount":"1",
      "status":"S",
      "accountType":"MAIN"
    },{
      "tranId":118263598801,
      "type":244,
      "time":1664442061000,
      "deductedAsset":"BUSD",
      "deductedAmount":"1",
      "targetAsset":"USDC",
      "targetAmount":"1",
      "status":"S",
      "accountType":"MAIN"
    },{
      "tranId":118263407119,
      "type":244,
      "time":1664441820000,
      "deductedAsset":"BUSD",
      "deductedAmount":"1",
      "targetAsset":"USDC",
      "targetAmount":"1",
      "status":"S",
      "accountType":"MAIN"
    }
  ]
}


GET /sapi/v1/asset/convert-transfer/queryByPage

Weight(UID):
5

Parameters:

Name Type Mandatory Description
tranId LONG NO The transaction id
clientTranId STRING NO The user-defined transaction id
asset STRING NO If it is blank, we will match deducted asset and target asset.
startTime LONG YES inclusive, unit: ms
endTime LONG YES exclusive, unit: ms
accountType STRING NO MAIN: main account. CARD: funding account. If it is blank, we will query spot and card wallet, otherwise, we just query the corresponding wallet
current INTEGER NO current page, default 1, the min value is 1
size INTEGER NO page size, default 10, the max value is 100
  • ENUM of types:
    • 244 convert via sapi call
    • 11 auto convert when deposit
    • 32 auto convert when withdraw
    • 34 in case withdraw failed
    • 254 busd auto convert job

Get Cloud-Mining payment and refund history (USER_DATA)

Response

{
  "total":5,
  "rows":[
    {"createTime":1667880112000,"tranId":121230610120,"type":248,"asset":"USDT","amount":"25.0068","status":"S"},
    {"createTime":1666776366000,"tranId":119991507468,"type":249,"asset":"USDT","amount":"0.027","status":"S"},
    {"createTime":1666764505000,"tranId":119977966327,"type":248,"asset":"USDT","amount":"0.027","status":"S"},
    {"createTime":1666758189000,"tranId":119973601721,"type":248,"asset":"USDT","amount":"0.018","status":"S"},
    {"createTime":1666757278000,"tranId":119973028551,"type":248,"asset":"USDT","amount":"0.018","status":"S"}
  ]
}


GET /sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage

The query of Cloud-Mining payment and refund history

Weight(UID):
600

Parameters:

Name Type Mandatory Description
tranId LONG NO The transaction id
clientTranId STRING NO The unique flag
asset STRING NO If it is blank, we will query all assets
startTime LONG YES inclusive, unit: ms
endTime LONG YES exclusive, unit: ms
current INTEGER NO current page, default 1, the min value is 1
size INTEGER NO page size, default 10, the max value is 100
  • Just return the SUCCESS records of payment and refund.
  • For response, type = 248 means payment, type = 249 means refund, status =S means SUCCESS.

Get API Key Permission (USER_DATA)

Response

{
   "ipRestrict": false,
   "createTime": 1623840271000,   
   "enableWithdrawals": false,   // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals
   "enableInternalTransfer": true,  // This option authorizes this key to transfer funds between your master account and your sub account instantly
   "permitsUniversalTransfer": true,  // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization
   "enableVanillaOptions": false,  //  Authorizes this key to Vanilla options trading
   "enableReading": true,
   "enableFutures": false,  //  API Key created before your futures account opened does not support futures API service
   "enableMargin": false,   //  This option can be adjusted after the Cross Margin account transfer is completed
   "enableSpotAndMarginTrading": false, // Spot and margin trading
   "tradingAuthorityExpirationTime": 1628985600000  // Expiration time for spot and margin trading permission
}


GET /sapi/v1/account/apiRestrictions (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Query auto-converting stable coins (USER_DATA)

Response:

{
  "convertEnabled": true,
  "coins": [
    "USDC",
    "USDP",
    "TUSD"
  ],
  "exchangeRates": {
    "USDC": "1",
    "TUSD": "1",
    "USDP": "1"
  }
}


GET /sapi/v1/capital/contract/convertible-coins

Get a user’s auto-conversion settings in deposit/withdrawal

Weight(UID):
600

Parameters:
None

Switch on/off BUSD and stable coins conversion (USER_DATA)

Response:
Returns code 200 on success without body.


POST /sapi/v1/capital/contract/convertible-coins

User can use it to turn on or turn off the BUSD auto-conversion from/to a specific stable coin.

Weight(UID):
600

Parameters:

Name Type Mandatory Description
coin STRING YES Must be USDC, USDP or TUSD
enable BOOLEAN YES true: turn on the auto-conversion. false: turn off the auto-conversion
  • Params need to be in the POST body

One click arrival deposit apply (for expired address deposit) (USER_DATA)

Response:

{
    "code": "000000",
    "message": "success",
    "data":true,
    "success": true
}


POST /sapi/v1/capital/deposit/credit-apply (HMAC SHA256)

Apply deposit credit for expired address (One click arrival)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
depositId LONG NO Deposit record Id, priority use
txId STRING NO Deposit txId, used when depositId is not specified
subAccountId LONG NO Sub-accountId of Cloud user
subUserId LONG NO Sub-userId of parent user
  • Params need to be in the POST body

Sub-Account Endpoints

  • The endpoints documented in this section are for Corporate Accounts.
  • To become a corporate account, please refer to this document: Corporate Account Application

Create a Virtual Sub-account(For Master Account)

Response:

{
    "email":"addsdd_virtual@aasaixwqnoemail.com"
}


POST /sapi/v1/sub-account/virtualSubAccount (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
subAccountString STRING YES Please input a string. We will create a virtual email using that string for you to register
recvWindow LONG NO
timestamp LONG YES
  • This request will generate a virtual sub account under your master account.
  • You need to enable «trade» option for the API Key which requests this endpoint.

Query Sub-account List (For Master Account)

Response:

{
    "subAccounts":[
        {
            "email":"testsub@gmail.com",
            "isFreeze":false,
            "createTime":1544433328000,
            "isManagedSubAccount": false,
            "isAssetManagementSubAccount": false
        },
        {
            "email":"virtual@oxebmvfonoemail.com",
            "isFreeze":false,
            "createTime":1544433328000,
            "isManagedSubAccount": false,
            "isAssetManagementSubAccount": false
        }
    ]
}


GET /sapi/v1/sub-account/list (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING NO Sub-account email
isFreeze STRING NO true or false
page INT NO Default value: 1
limit INT NO Default value: 1, Max value: 200
recvWindow LONG NO
timestamp LONG YES

Query Sub-account Spot Asset Transfer History (For Master Account)

Response:

[
    {
        "from":"aaa@test.com",
        "to":"bbb@test.com",
        "asset":"BTC",
        "qty":"10",
        "status": "SUCCESS",
        "tranId": 6489943656,
        "time":1544433328000
    },
    {
        "from":"bbb@test.com",
        "to":"ccc@test.com",
        "asset":"ETH",
        "qty":"2",
        "status": "SUCCESS",
        "tranId": 6489938713,
        "time":1544433328000
    }
]


GET /sapi/v1/sub-account/sub/transfer/history (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
fromEmail STRING NO
toEmail STRING NO
startTime LONG NO
endTime LONG NO
page INT NO Default value: 1
limit INT NO Default value: 500
recvWindow LONG NO
timestamp LONG YES
  • fromEmail and toEmail cannot be sent at the same time.
  • Return fromEmail equal master account email by default.

Query Sub-account Futures Asset Transfer History (For Master Account)

Response

{
    "success":true,
    "futuresType": 2,
    "transfers":[
        {
            "from":"aaa@test.com",
            "to":"bbb@test.com",
            "asset":"BTC",
            "qty":"1",
            "tranId":11897001102,
            "time":1544433328000
        },
        {
            "from":"bbb@test.com",
            "to":"ccc@test.com",
            "asset":"ETH",
            "qty":"2",
            "tranId":11631474902,
            "time":1544433328000
        }
    ]
}


GET /sapi/v1/sub-account/futures/internalTransfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
futuresType LONG YES 1:USDT-margined Futures,2: Coin-margined Futures
startTime LONG NO Default return the history with in 100 days
endTime LONG NO Default return the history with in 100 days
page INT NO Default value: 1
limit INT NO Default value: 50, Max value: 500
recvWindow LONG NO
timestamp LONG YES

Sub-account Futures Asset Transfer (For Master Account)

Response

{
    "success":true,
    "txnId":"2934662589"
}


POST /sapi/v1/sub-account/futures/internalTransfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
fromEmail STRING YES Sender email
toEmail STRING YES Recipient email
futuresType LONG YES 1:USDT-margined Futures,2: Coin-margined Futures
asset STRING YES
amount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • Master account can transfer max 2000 times a minute
  • There must be sufficient margin balance in futures wallet to execute transferring.

Query Sub-account Assets (For Master Account)

Response:

{
    "balances":[
        {
            "asset":"ADA",
            "free":10000,
            "locked":0
        },
        {
            "asset":"BNB",
            "free":10003,
            "locked":0
        },
        {
            "asset":"BTC",
            "free":11467.6399,
            "locked":0
        },
        {
            "asset":"ETH",
            "free":10004.995,
            "locked":0
        },
        {
            "asset":"USDT",
            "free":11652.14213,
            "locked":0
        }
    ]
}


GET /sapi/v3/sub-account/assets (HMAC SHA256)

Fetch sub-account assets

Weight(UID):
60

Parameters:

Name Type Mandatory Description
email STRING YES Sub account email
recvWindow LONG NO
timestamp LONG YES

Query Sub-account Spot Assets Summary (For Master Account)

Response:

{
    "totalCount":2,
    "masterAccountTotalAsset": "0.23231201",
    "spotSubUserAssetBtcVoList":[
        {
            "email":"sub123@test.com",
            "totalAsset":"9999.00000000"
        },
        {
            "email":"test456@test.com",
            "totalAsset":"0.00000000"
        }
    ]
}

Get BTC valued asset summary of subaccounts.

GET /sapi/v1/sub-account/spotSummary (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING NO Sub account email
page LONG NO default 1
size LONG NO default 10, max 20
recvWindow LONG NO
timestamp LONG YES

Get Sub-account Deposit Address (For Master Account)

Response:

{
    "address":"TDunhSa7jkTNuKrusUTU1MUHtqXoBPKETV",
    "coin":"USDT",
    "tag":"",
    "url":"https://tronscan.org/#/address/TDunhSa7jkTNuKrusUTU1MUHtqXoBPKETV"
}


GET /sapi/v1/capital/deposit/subAddress (HMAC SHA256)

Fetch sub-account deposit address

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub account email
coin STRING YES
network STRING NO
recvWindow LONG NO
timestamp LONG YES

Get Sub-account Deposit History (For Master Account)

Response:

[
    {
        "id": "769800519366885376",
        "amount": "0.001",
        "coin": "BNB",
        "network": "BNB",
        "status": 0,
        "address": "bnb136ns6lfw4zs5hg4n85vdthaad7hq5m4gtkgf23",
        "addressTag": "101764890",
        "txId": "98A3EA560C6B3336D348B6C83F0F95ECE4F1F5919E94BD006E5BF3BF264FACFC",
        "insertTime": 1661493146000,
        "transferType": 0,
        "confirmTimes": "1/1",
        "unlockConfirm": 0,
        "walletType": 0
    },
    {
        "id": "769754833590042625",
        "amount":"0.50000000",
        "coin":"IOTA",
        "network":"IOTA",
        "status":1,
        "address":"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW",
        "addressTag":"",
        "txId":"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999",
        "insertTime":1599620082000,
        "transferType":0,
        "confirmTimes": "1/1",
        "unlockConfirm": 0,
        "walletType": 0
    }
]


GET /sapi/v1/capital/deposit/subHisrec (HMAC SHA256)

Fetch sub-account deposit history

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub account email
coin STRING NO
status INT NO 0(0:pending,6: credited but cannot withdraw,7:Wrong Deposit,8:Waiting User confirm,1:success)
startTime LONG NO
endTime LONG NO
limit INT NO
offset INT NO default:0
recvWindow LONG NO
timestamp LONG YES
txId STRING NO

Get Sub-account’s Status on Margin/Futures (For Master Account)

Response

[
    {
        "email":"123@test.com",      // user email
        "isSubUserEnabled": true,    // true or false
        "isUserActive": true,        // true or false
        "insertTime": 1570791523523,  // sub account create time
        "isMarginEnabled": true,     // true or false for margin
        "isFutureEnabled": true,      // true or false for futures.
        "mobile": 1570791523523      // user mobile number
    }
]


GET /sapi/v1/sub-account/status (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
email STRING NO Sub-account email
recvWindow LONG NO
timestamp LONG YES
  • If no email sent, all sub-accounts’ information will be returned.

Enable Margin for Sub-account (For Master Account)

Response

{

    "email":"123@test.com",
    "isMarginEnabled": true

}


POST /sapi/v1/sub-account/margin/enable (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
recvWindow LONG NO
timestamp LONG YES

Get Detail on Sub-account’s Margin Account (For Master Account)

Response

{
      "email":"123@test.com",
      "marginLevel": "11.64405625",
      "totalAssetOfBtc": "6.82728457",
      "totalLiabilityOfBtc": "0.58633215",
      "totalNetAssetOfBtc": "6.24095242",
      "marginTradeCoeffVo": 
            {
                "forceLiquidationBar": "1.10000000",  // Liquidation margin ratio
                "marginCallBar": "1.50000000",        // Margin call margin ratio
                "normalBar": "2.00000000"             // Initial margin ratio
            },
      "marginUserAssetVoList": [
          {
              "asset": "BTC",
              "borrowed": "0.00000000",
              "free": "0.00499500",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00499500"
          },
          {
              "asset": "BNB",
              "borrowed": "201.66666672",
              "free": "2346.50000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "2144.83333328"
          },
          {
              "asset": "ETH",
              "borrowed": "0.00000000",
              "free": "0.00000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00000000"
          },
          {
              "asset": "USDT",
              "borrowed": "0.00000000",
              "free": "0.00000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00000000"
          }
      ]
}


GET /sapi/v1/sub-account/margin/account (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
recvWindow LONG NO
timestamp LONG YES

Get Summary of Sub-account’s Margin Account (For Master Account)

Response

{
    "totalAssetOfBtc": "4.33333333", 
    "totalLiabilityOfBtc": "2.11111112", 
    "totalNetAssetOfBtc": "2.22222221",
    "subAccountList":[
        {
            "email":"123@test.com",
            "totalAssetOfBtc": "2.11111111",
            "totalLiabilityOfBtc": "1.11111111",
            "totalNetAssetOfBtc": "1.00000000"
        },
        { 
            "email":"345@test.com",
            "totalAssetOfBtc": "2.22222222", 
            "totalLiabilityOfBtc": "1.00000001", 
            "totalNetAssetOfBtc": "1.22222221"
        }
    ]
}

GET /sapi/v1/sub-account/margin/accountSummary (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Enable Futures for Sub-account (For Master Account)

Response

{

    "email":"123@test.com",
    "isFuturesEnabled": true  // true or false

}


POST /sapi/v1/sub-account/futures/enable (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
recvWindow LONG NO
timestamp LONG YES

Get Detail on Sub-account’s Futures Account (For Master Account)

Response


{
    "email": "abc@test.com",
    "asset": "USDT",
    "assets":[
        {
            "asset": "USDT",
            "initialMargin": "0.00000000",
            "maintenanceMargin": "0.00000000",
            "marginBalance": "0.88308000",
            "maxWithdrawAmount": "0.88308000",
            "openOrderInitialMargin": "0.00000000",
            "positionInitialMargin": "0.00000000",
            "unrealizedProfit": "0.00000000",
            "walletBalance": "0.88308000"
         }
    ],
    "canDeposit": true,
    "canTrade": true,
    "canWithdraw": true,
    "feeTier": 2,
    "maxWithdrawAmount": "0.88308000",
    "totalInitialMargin": "0.00000000",
    "totalMaintenanceMargin": "0.00000000",
    "totalMarginBalance": "0.88308000",
    "totalOpenOrderInitialMargin": "0.00000000",
    "totalPositionInitialMargin": "0.00000000",
    "totalUnrealizedProfit": "0.00000000",
    "totalWalletBalance": "0.88308000",
    "updateTime": 1576756674610
 }

GET /sapi/v1/sub-account/futures/account (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
recvWindow LONG NO
timestamp LONG YES

Get Summary of Sub-account’s Futures Account (For Master Account)

Response

{
    "totalInitialMargin": "9.83137400", 
    "totalMaintenanceMargin": "0.41568700", 
    "totalMarginBalance": "23.03235621", 
    "totalOpenOrderInitialMargin": "9.00000000",
    "totalPositionInitialMargin": "0.83137400",
    "totalUnrealizedProfit": "0.03219710",
    "totalWalletBalance": "22.15879444",
    "asset": "USD",  // The sum of BUSD and USDT
    "subAccountList":[
        {
            "email": "123@test.com",
            "totalInitialMargin": "9.00000000", 
            "totalMaintenanceMargin": "0.00000000", 
            "totalMarginBalance": "22.12659734", 
            "totalOpenOrderInitialMargin": "9.00000000",
            "totalPositionInitialMargin": "0.00000000",
            "totalUnrealizedProfit": "0.00000000",
            "totalWalletBalance": "22.12659734",
            "asset": "USD" //The sum of BUSD and USDT
        },
        { 
            "email": "345@test.com",
            "totalInitialMargin": "0.83137400", 
            "totalMaintenanceMargin": "0.41568700", 
            "totalMarginBalance": "0.90575887", 
            "totalOpenOrderInitialMargin": "0.00000000",
            "totalPositionInitialMargin": "0.83137400",
            "totalUnrealizedProfit": "0.03219710",
            "totalWalletBalance": "0.87356177",
            "asset": "USD"
        }
    ]
}

GET /sapi/v1/sub-account/futures/accountSummary (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Get Futures Position-Risk of Sub-account (For Master Account)

Response

[
    {
        "entryPrice": "9975.12000",
        "leverage": "50",              // current initial leverage
        "maxNotional": "1000000",      // notional value limit of current initial leverage
        "liquidationPrice": "7963.54",
        "markPrice": "9973.50770517",
        "positionAmount": "0.010",
        "symbol": "BTCUSDT",
        "unrealizedProfit": "-0.01612295"
    }
]

GET /sapi/v1/sub-account/futures/positionRisk (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
recvWindow LONG NO
timestamp LONG YES

Futures Transfer for Sub-account (For Master Account)

Response

{
    "txnId":"2966662589"
}

POST /sapi/v1/sub-account/futures/transfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
asset STRING YES The asset being transferred, e.g., USDT
amount DECIMAL YES The amount to be transferred
type INT YES 1: transfer from subaccount’s spot account to its USDT-margined futures account 2: transfer from subaccount’s USDT-margined futures account to its spot account 3: transfer from subaccount’s spot account to its COIN-margined futures account 4:transfer from subaccount’s COIN-margined futures account to its spot account
recvWindow LONG NO
timestamp LONG YES
  • You need to open Enable Spot & Margin Trading permission for the API Key which requests this endpoint.

Margin Transfer for Sub-account (For Master Account)

Response

{
    "txnId":"2966662589"
}

POST /sapi/v1/sub-account/margin/transfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
asset STRING YES The asset being transferred, e.g., BTC
amount DECIMAL YES The amount to be transferred
type INT YES 1: transfer from subaccount’s spot account to margin account 2: transfer from subaccount’s margin account to its spot account
recvWindow LONG NO
timestamp LONG YES
  • You need to open Enable Spot & Margin Trading permission for the API Key which requests this endpoint.

Transfer to Sub-account of Same Master (For Sub-account)

Response

{
    "txnId":"2966662589"
}

POST /sapi/v1/sub-account/transfer/subToSub (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
toEmail STRING YES Sub-account email
asset STRING YES
amount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to open Enable Spot & Margin Trading permission for the API Key which requests this endpoint.

Transfer to Master (For Sub-account)

Response

{
    "txnId":"2966662589"
}

POST /sapi/v1/sub-account/transfer/subToMaster (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING YES
amount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to open Enable Spot & Margin Trading permission for the API Key which requests this endpoint.

Sub-account Transfer History (For Sub-account)

Response

[
  {
    "counterParty":"master",
    "email":"master@test.com",
    "type":1,  // 1 for transfer in, 2 for transfer out
    "asset":"BTC",
    "qty":"1",
    "fromAccountType":"SPOT",
    "toAccountType":"SPOT",
    "status":"SUCCESS", // status: PROCESS / SUCCESS / FAILURE
    "tranId":11798835829,
    "time":1544433325000
  },
  {
    "counterParty":"subAccount",
    "email":"sub2@test.com",
    "type":1,                                 
    "asset":"ETH",
    "qty":"2",
    "fromAccountType":"SPOT",
    "toAccountType":"SPOT",
    "status":"SUCCESS",
    "tranId":11798829519,
    "time":1544433326000
  }
]

GET /sapi/v1/sub-account/transfer/subUserHistory (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO If not sent, result of all assets will be returned
type INT NO 1: transfer in, 2: transfer out
startTime LONG NO
endTime LONG NO
limit INT NO Default 500
recvWindow LONG NO
timestamp LONG YES
  • If type is not sent, the records of type 2: transfer out will be returned by default.
  • If startTime and endTime are not sent, the recent 30-day data will be returned.

Universal Transfer (For Master Account)

Response

{
    "tranId":11945860693,
    "clientTranId":"test"
}

POST /sapi/v1/sub-account/universalTransfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
fromEmail STRING NO
toEmail STRING NO
fromAccountType STRING YES «SPOT»,»USDT_FUTURE»,»COIN_FUTURE»,»MARGIN»(Cross),»ISOLATED_MARGIN»
toAccountType STRING YES «SPOT»,»USDT_FUTURE»,»COIN_FUTURE»,»MARGIN»(Cross),»ISOLATED_MARGIN»
clientTranId STRING NO Must be unique
symbol STRING NO Only supported under ISOLATED_MARGIN type
asset STRING YES
amount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to enable «internal transfer» option for the api key which requests this endpoint.
  • Transfer from master account by default if fromEmail is not sent.
  • Transfer to master account by default if toEmail is not sent.
  • At least either fromEmail or toEmail need to be sent when the fromAccountType and the toAccountType are the same.
  • Supported transfer scenarios:
    • SPOT transfer to SPOT, USDT_FUTURE, COIN_FUTURE (regardless of master or sub)
    • SPOT, USDT_FUTURE, COIN_FUTURE transfer to SPOT (regardless of master or sub)
    • Master account SPOT transfer to sub-account MARGIN(Cross), ISOLATED_MARGIN
    • Sub-account MARGIN(Cross), ISOLATED_MARGIN transfer to master account SPOT

Query Universal Transfer History (For Master Account)

Response

{
    "result": [
        {
            "tranId": 92275823339,
            "fromEmail": "abctest@gmail.com",
            "toEmail": "deftest@gmail.com",
            "asset": "BNB",
            "amount": "0.01",
            "createTimeStamp": 1640317374000,
            "fromAccountType": "USDT_FUTURE",
            "toAccountType": "SPOT",
            "status": "SUCCESS",
            "clientTranId": "test"
        }
    ],
    "totalCount": 1
}

GET /sapi/v1/sub-account/universalTransfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
fromEmail STRING NO
toEmail STRING NO
clientTranId STRING NO
startTime LONG NO
endTime LONG NO
page INT NO Default 1
limit INT NO Default 500, Max 500
recvWindow LONG NO
timestamp LONG YES
  • fromEmail and toEmail cannot be sent at the same time.
  • Return fromEmail equal master account email by default.
  • The query time period must be less then 30 days.
  • If startTime and endTime not sent, return records of the last 30 days by default.

Get Detail on Sub-account’s Futures Account V2 (For Master Account)

Response

USDT Margined Futures:


{
    "futureAccountResp": {
    "email": "abc@test.com",
    "assets":[
        {
            "asset": "USDT",
            "initialMargin": "0.00000000",
            "maintenanceMargin": "0.00000000",
            "marginBalance": "0.88308000",
            "maxWithdrawAmount": "0.88308000",
            "openOrderInitialMargin": "0.00000000",
            "positionInitialMargin": "0.00000000",
            "unrealizedProfit": "0.00000000",
            "walletBalance": "0.88308000"
         }
    ],
    "canDeposit": true,
    "canTrade": true,
    "canWithdraw": true,
    "feeTier": 2,
    "maxWithdrawAmount": "0.88308000",
    "totalInitialMargin": "0.00000000",
    "totalMaintenanceMargin": "0.00000000",
    "totalMarginBalance": "0.88308000",
    "totalOpenOrderInitialMargin": "0.00000000",
    "totalPositionInitialMargin": "0.00000000",
    "totalUnrealizedProfit": "0.00000000",
    "totalWalletBalance": "0.88308000",
    "updateTime": 1576756674610
 }
}

COIN Margined Futures:


{
    "deliveryAccountResp": {
        "email": "abc@test.com",
        "assets":[
            {
                "asset": "BTC",
                "initialMargin": "0.00000000",
                "maintenanceMargin": "0.00000000",
                "marginBalance": "0.88308000",
                "maxWithdrawAmount": "0.88308000",
                "openOrderInitialMargin": "0.00000000",
                "positionInitialMargin": "0.00000000",
                "unrealizedProfit": "0.00000000",
                "walletBalance": "0.88308000"
             }
        ],
        "canDeposit": true,
        "canTrade": true,
        "canWithdraw": true,
        "feeTier": 2,
        "updateTime": 1598959682001
    }
 }

GET /sapi/v2/sub-account/futures/account (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
futuresType INT YES 1:USDT Margined Futures, 2:COIN Margined Futures
recvWindow LONG NO
timestamp LONG YES

Get Summary of Sub-account’s Futures Account V2 (For Master Account)

Response

USDT Margined Futures:

{
  "futureAccountSummaryResp": {
    "totalInitialMargin": "9.83137400", 
    "totalMaintenanceMargin": "0.41568700", 
    "totalMarginBalance": "23.03235621", 
    "totalOpenOrderInitialMargin": "9.00000000",
    "totalPositionInitialMargin": "0.83137400",
    "totalUnrealizedProfit": "0.03219710",
    "totalWalletBalance": "22.15879444",
    "asset": "USD",  //The sum of BUSD and USDT
    "subAccountList":[
        {
            "email": "123@test.com",
            "totalInitialMargin": "9.00000000", 
            "totalMaintenanceMargin": "0.00000000", 
            "totalMarginBalance": "22.12659734", 
            "totalOpenOrderInitialMargin": "9.00000000",
            "totalPositionInitialMargin": "0.00000000",
            "totalUnrealizedProfit": "0.00000000",
            "totalWalletBalance": "22.12659734",
            "asset": "USD"  //The sum of BUSD and USDT
        },
        { 
            "email": "345@test.com",
            "totalInitialMargin": "0.83137400", 
            "totalMaintenanceMargin": "0.41568700",
            "totalMarginBalance": "0.90575887",
            "totalOpenOrderInitialMargin": "0.00000000",
            "totalPositionInitialMargin": "0.83137400",
            "totalUnrealizedProfit": "0.03219710",
            "totalWalletBalance": "0.87356177",
            "asset": "USD"
        }
    ]
  }
}

COIN Margined Futures:

{
  "deliveryAccountSummaryResp": {
    "totalMarginBalanceOfBTC": "25.03221121", 
    "totalUnrealizedProfitOfBTC": "0.12233410",
    "totalWalletBalanceOfBTC": "22.15879444",
    "asset": "BTC",
    "subAccountList":[
        {
            "email": "123@test.com",
            "totalMarginBalance": "22.12659734", 
            "totalUnrealizedProfit": "0.00000000",
            "totalWalletBalance": "22.12659734",
            "asset": "BTC"
        },
        { 
            "email": "345@test.com",
            "totalMarginBalance": "0.90575887",
            "totalUnrealizedProfit": "0.03219710",
            "totalWalletBalance": "0.87356177",
            "asset": "BTC"
        }
    ]
  }
}

GET /sapi/v2/sub-account/futures/accountSummary (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
futuresType INT YES 1:USDT Margined Futures, 2:COIN Margined Futures
page INT NO default:1
limit INT NO default:10, max:20
recvWindow LONG NO
timestamp LONG YES

Get Futures Position-Risk of Sub-account V2 (For Master Account)

Response

USDT Margined Futures:

{
  "futurePositionRiskVos": [
     {
        "entryPrice": "9975.12000",
        "leverage": "50",              // current initial leverage
        "maxNotional": "1000000",      // notional value limit of current initial leverage
        "liquidationPrice": "7963.54",
        "markPrice": "9973.50770517",
        "positionAmount": "0.010",
        "symbol": "BTCUSDT",
        "unrealizedProfit": "-0.01612295"
     }
   ]
}

COIN Margined Futures:

{
  "deliveryPositionRiskVos": [
     {
        "entryPrice": "9975.12000",
        "markPrice": "9973.50770517",
        "leverage": "20",          
        "isolated": "false",                
        "isolatedWallet": "9973.50770517",
        "isolatedMargin": "0.00000000",
        "isAutoAddMargin": "false",
        "positionSide": "BOTH",
        "positionAmount": "1.230",
        "symbol": "BTCUSD_201225",
        "unrealizedProfit": "-0.01612295"
     }
   ]
}

GET /sapi/v2/sub-account/futures/positionRisk (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
futuresType INT YES 1:USDT Margined Futures, 2:COIN Margined Futures
recvWindow LONG NO
timestamp LONG YES

Enable Leverage Token for Sub-account (For Master Account)

Response

{
    "email":"123@test.com",
    "enableBlvt":true
}

POST /sapi/v1/sub-account/blvt/enable (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
enableBlvt BOOLEAN YES Only true for now
recvWindow LONG NO
timestamp LONG YES

Get IP Restriction for a Sub-account API Key (For Master Account)

Response:

{
    "ipRestrict": "true",
    "ipList": [
        "69.210.67.14",
        "8.34.21.10"
    ],
    "updateTime": 1636371437000,
    "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf"
}


GET /sapi/v1/sub-account/subAccountApi/ipRestriction (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
subAccountApiKey STRING YES
recvWindow LONG NO
timestamp LONG YES

Delete IP List For a Sub-account API Key (For Master Account)

Response:

{
  "ipRestrict": "true",
  "ipList": [
    "69.210.67.14",
    "8.34.21.10"
  ],
  "updateTime": 1636371437000,
  "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf"
}


DELETE /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
subAccountApiKey STRING YES
ipAddress STRING NO Can be added in batches, separated by commas
recvWindow LONG NO
timestamp LONG YES
  • You need to enable Enable Spot & Margin Trading option for the api key which requests this endpoint

Update IP Restriction for Sub-Account API key (For Master Account)

Response:

{
  "status": "2", 
  "ipList": [
    "69.210.67.14",
    "8.34.21.10",  //only return if you open IP restriction and input IP address.
  ],
  "updateTime": 1636371437000,
  "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf"
}


POST /sapi/v2/sub-account/subAccountApi/ipRestriction (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
email STRING YES Sub-account email
subAccountApiKey STRING YES
status STRING YES IP Restriction status. 1 = IP Unrestricted. 2 = Restrict access to trusted IPs only.
ipAddress STRING NO Insert static IP in batch, separated by commas.
recvWindow LONG NO
timestamp LONG YES
  • You need to enable Enable Spot & Margin Trading option for the api key which requests this endpoint

Deposit Assets Into The Managed Sub-account(For Investor Master Account)

Response

{
    "tranId":66157362489
}

POST /sapi/v1/managed-subaccount/deposit (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
toEmail STRING YES
asset STRING YES
amount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to enable Enable Spot & Margin Trading option for the api key which requests this endpoint

Query Managed Sub-account Asset Details(For Investor Master Account)

Response

[
  {
     "coin": "INJ",                
     "name": "Injective Protocol", 
     "totalBalance": "0",          
     "availableBalance": "0",      
     "inOrder": "0",                
     "btcValue": "0"               
  },
  {
     "coin": "FILDOWN",
     "name": "FILDOWN",
     "totalBalance": "0",
     "availableBalance": "0",
     "inOrder": "0",
     "btcValue": "0"
  }
]

GET /sapi/v1/managed-subaccount/asset (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES
recvWindow LONG NO
timestamp LONG YES

Withdrawl Assets From The Managed Sub-account(For Investor Master Account)

Response

{
    "tranId":66157362489
}

POST /sapi/v1/managed-subaccount/withdraw (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
fromEmail STRING YES
asset STRING YES
amount DECIMAL YES
transferDate LONG NO Withdrawals is automatically occur on the transfer date(UTC0). If a date is not selected, the withdrawal occurs right now
recvWindow LONG NO
timestamp LONG YES
  • You need to enable Enable Spot & Margin Trading option for the api key which requests this endpoint

Query Managed Sub-account Snapshot(For Investor Master Account)

Response:

{
   "code":200, // 200 for success; others are error codes
   "msg":"", // error message
   "snapshotVos":[
      {
         "data":{
            "balances":[
               {
                  "asset":"BTC",
                  "free":"0.09905021",
                  "locked":"0.00000000"
               },
               {
                  "asset":"USDT",
                  "free":"1.89109409",
                  "locked":"0.00000000"
               }
            ],
            "totalAssetOfBtc":"0.09942700"
         },
         "type":"spot",
         "updateTime":1576281599000
      }
   ]
}

OR

{
   "code":200, // 200 for success; others are error codes
   "msg":"", // error message
   "snapshotVos":[
      {
         "data":{
            "marginLevel":"2748.02909813",
            "totalAssetOfBtc":"0.00274803",
            "totalLiabilityOfBtc":"0.00000100",
            "totalNetAssetOfBtc":"0.00274750",
            "userAssets":[
               {
                  "asset":"XRP",
                  "borrowed":"0.00000000",
                  "free":"1.00000000",
                  "interest":"0.00000000",
                  "locked":"0.00000000",
                  "netAsset":"1.00000000"
               }
            ]
         },
         "type":"margin",
         "updateTime":1576281599000
      }
   ]
}

OR

{
   "code":200, // 200 for success; others are error codes
   "msg":"", // error message
   "snapshotVos":[
      {
         "data":{
            "assets":[
               {
                  "asset":"USDT",
                  "marginBalance":"118.99782335",
                  "walletBalance":"120.23811389"
               }
            ],
            "position":[
               {
                  "entryPrice":"7130.41000000",
                  "markPrice":"7257.66239673",
                  "positionAmt":"0.01000000",
                  "symbol":"BTCUSDT",
                  "unRealizedProfit":"1.24029054"  // Only show the value at the time of opening the position
               }
            ]
         },
         "type":"futures",
         "updateTime":1576281599000
      }
   ]
}


GET /sapi/v1/managed-subaccount/accountSnapshot (HMAC SHA256)

Weight(IP):
2400

Parameters:

Name Type Mandatory Description
email STRING YES
type STRING YES «SPOT», «MARGIN»(cross), «FUTURES»(UM)
startTime LONG NO
endTime LONG NO
limit INT NO min 7, max 30, default 7
recvWindow LONG NO
timestamp LONG YES
  • The query time period must be less then 30 days
  • Support query within the last one month only
  • If startTimeand endTime not sent, return records of the last 7 days by default

Query Managed Sub Account Transfer Log (For Investor Master Account) (USER_DATA)

Response

{
    managerSubTransferHistoryVos: [
        0: {
            fromEmail: "test_0_virtual@kq3kno9imanagedsub.com"
            fromAccountType: "SPOT"
            toEmail: "wdywl0lddakh@test.com"
            toAccountType: "SPOT"
            asset: "BNB"
            amount: "0.01"
            scheduledData: 1679416673000
            createTime: 1679416673000
            status: "SUCCESS"
            tranId: 91077779
        }
        1: {
            fromEmail: "wdywl0lddakh@test.com"
            fromAccountType: "SPOT"
            toEmail: "test_0_virtual@kq3kno9imanagedsub.com"
            toAccountType: "SPOT"
            asset: "BNB"
            amount: "1"
            scheduledData: 1679416616000
            createTime: 1679416616000
            status: "SUCCESS"
            tranId: 91077676
        }
    ]
    count: 2
}

GET /sapi/v1/managed-subaccount/queryTransLogForInvestor (HMAC SHA256)

Investor can use this api to query managed sub account transfer log. This endpoint is available for investor of Managed Sub-Account. A Managed Sub-Account is an account type for investors who value flexibility in asset allocation and account application, while delegating trades to a professional trading team.
Please refer to link

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Managed Sub Account Email
startTime LONG YES Start Time
endTime LONG YES End Time (The start time and end time interval cannot exceed half a year)
page INT YES Page
limit INT YES Limit (Max: 500)
transfers STRING NO Transfer Direction (FROM/TO)
transferFunctionAccountType STRING NO Transfer function account type (SPOT/MARGIN/ISOLATED_MARGIN/USDT_FUTURE/COIN_FUTURE)

Query Managed Sub Account Transfer Log (For Trading Team Master Account) (USER_DATA)

Response

{
    managerSubTransferHistoryVos: [
        0: {
            fromEmail: "test_0_virtual@kq3kno9imanagedsub.com"
            fromAccountType: "SPOT"
            toEmail: "wdywl0lddakh@test.com"
            toAccountType: "SPOT"
            asset: "BNB"
            amount: "0.01"
            scheduledData: 1679416673000
            createTime: 1679416673000
            status: "SUCCESS"
            tranId: 91077779
        }
        1: {
            fromEmail: "wdywl0lddakh@test.com"
            fromAccountType: "SPOT"
            toEmail: "test_0_virtual@kq3kno9imanagedsub.com"
            toAccountType: "SPOT"
            asset: "BNB"
            amount: "1"
            scheduledData: 1679416616000
            createTime: 1679416616000
            status: "SUCCESS"
            tranId: 91077676
        }
    ]
    count: 2
}

GET /sapi/v1/managed-subaccount/queryTransLogForTradeParent (HMAC SHA256)

Trading team can use this api to query managed sub account transfer log. This endpoint is available for trading team of Managed Sub-Account. A Managed Sub-Account is an account type for investors who value flexibility in asset allocation and account application, while delegating trades to a professional trading team.
Please refer to link

Weight(UID):
60

Parameters:

Name Type Mandatory Description
email STRING YES Managed Sub Account Email
startTime LONG YES Start Time
endTime LONG YES End Time (The start time and end time interval cannot exceed half a year)
page INT YES Page
limit INT YES Limit (Max: 500)
transfers STRING NO Transfer Direction (FROM/TO)
transferFunctionAccountType STRING NO Transfer function account type (SPOT/MARGIN/ISOLATED_MARGIN/USDT_FUTURE/COIN_FUTURE)

Query Managed Sub-account Futures Asset Details(For Investor Master Account)(USER_DATA)

Response

{
  "code": "200",
  "message": "OK",
  "snapshotVos": [
    {
      "type": "FUTURES",
      "updateTime": 1672893855394,
      "data": {
        "assets": [
          {
            "asset": "USDT",
            "marginBalance": 100,
            "walletBalance": 120
          }
        ],
        "position": [
          {
            "symbol": "BTCUSDT",
            "entryPrice": 17000,
            "markPrice": 17000,
            "positionAmt": 0.0001
          }
        ]
      }
    }
  ]
}

GET /sapi/v1/managed-subaccount/fetch-future-asset (HMAC SHA256)

Investor can use this api to query managed sub account futures asset details

Weight(UID):
60

Parameters:

Name Type Mandatory Description
email STRING YES Managed Sub Account Email

Query Managed Sub-account Margin Asset Details (For Investor Master Account) (USER_DATA)

Response

{
  marginLevel:"999"
  totalAssetOfBtc:"0"
  totalLiabilityOfBtc:"0"
  totalNetAssetOfBtc:"0"
  userAssets:[
    0:{
    asset:"MATIC"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    1:{
    asset:"VET"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    2:{
    asset:"BAKE"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    3:{
    asset:"SHIB"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    4:{
    asset:"USDT"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    5:{
    asset:"DOGE"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    6:{
    asset:"AAVE"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    7:{
    asset:"ONT"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    8:{
    asset:"XRP"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    9:{
    asset:"XLM"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    10:{
    asset:"LINK"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    11:{
    asset:"QTUM"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    12:{
    asset:"ETHW"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    13:{
    asset:"XTZ"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    14:{
    asset:"LUNA"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    15:{
    asset:"EUR"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    16:{
    asset:"IOST"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    17:{
    asset:"BCH"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    18:{
    asset:"BTC"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    19:{
    asset:"IOTA"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    20:{
    asset:"CREAM"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    21:{
    asset:"BAT"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    22:{
    asset:"BNB"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    23:{
    asset:"ETH"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    24:{
    asset:"ZEC"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    25:{
    asset:"USDC"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    26:{
    asset:"LTC"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    27:{
    asset:"BUSD"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    28:{
    asset:"ZIL"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
    29:{
    asset:"THETA"
    borrowed:"0"
    free:"0"
    interest:"0"
    locked:"0"
    netAsset:"0"
    }
  ]
}

GET /sapi/v1/managed-subaccount/marginAsset (HMAC SHA256)

Investor can use this api to query managed sub account margin asset details

Weight(IP):
1

Parameters:

Name Type Mandatory Description
email STRING YES Managed Sub Account Email

Query Sub-account Assets (For Master Account)(USER_DATA)

Response

{
    "balances":[
        {
            "asset":"ADA",
            "free":"10000",
            "locked":"0"
        },
        {
            "asset":"BNB",
            "free":"10003",
            "locked":"0"
        },
        {
            "asset":"BTC",
            "free":"11467.6399",
            "locked":"0"
        }
    ]
}

GET /sapi/v4/sub-account/assets (HMAC SHA256)

Fetch sub-account assets

Weight(UID):
60

Parameters:

Name Type Mandatory Description
email STRING YES Managed Sub Account Email
recvWindow LONG NO
timestamp LONG YES

Query Managed Sub-account List (For Investor)(USER_DATA)

Response

{
    total: 3
    managerSubUserInfoVoList: [
        0: {
            rootUserId: 1000138475670
            managersubUserId: 1000137842513
            bindParentUserId: 1000138475669
            email: "test_0_virtual@kq3kno9imanagedsub.com"
            insertTimeStamp: 1678435149000
            bindParentEmail: "wdyw8xsh8pey@test.com"
            isSubUserEnabled: true
            isUserActive: true
            isMarginEnabled: false
            isFutureEnabled: false
            isSignedLVTRiskAgreement: false
        }
        1: {
            rootUserId: 1000138475670
            managersubUserId: 1000137842514
            bindParentUserId: 1000138475669
            email: "test_1_virtual@4qd2u7zxmanagedsub.com"
            insertTimeStamp: 1678435152000
            bindParentEmail: "wdyw8xsh8pey@test.com"
            isSubUserEnabled: true
            isUserActive: true
            isMarginEnabled: false
            isFutureEnabled: false
            isSignedLVTRiskAgreement: false
        }
        2: {
            rootUserId: 1000138475670
            managersubUserId: 1000137842515
            bindParentUserId: 1000138475669
            email: "test_2_virtual@akc05o8hmanagedsub.com"
            insertTimeStamp: 1678435153000
            bindParentEmail: "wdyw8xsh8pey@test.com"
            isSubUserEnabled: true
            isUserActive: true
            isMarginEnabled: false
            isFutureEnabled: false
            isSignedLVTRiskAgreement: false
        }
    ]
}

GET /sapi/v1/managed-subaccount/info (HMAC SHA256)

Get investor’s managed sub-account list.

Weight(UID):
60

Parameters:

Name Type Mandatory Description
email STRING NO Managed sub-account email
page INT NO Default value: 1
limit INT NO Default value: 20, Max value: 20
recvWindow LONG NO
timestamp LONG YES

Query Sub-account Transaction Statistics (For Master Account) (USER_DATA)

Response example:

{
    "recent30BtcTotal": "0",
    "recent30BtcFuturesTotal": "0",
    "recent30BtcMarginTotal": "0",
    "recent30BusdTotal": "0",
    "recent30BusdFuturesTotal": "0",
    "recent30BusdMarginTotal": "0",
    "tradeInfoVos": []
}

OR

{
    "recent30BtcTotal": "0",
    "recent30BtcFuturesTotal": "0",
    "recent30BtcMarginTotal": "0",
    "recent30BusdTotal": "0",
    "recent30BusdFuturesTotal": "0",
    "recent30BusdMarginTotal": "0",
    "tradeInfoVos": [
        {
            "userId": 1000138138384,
            "btc": 0,
            "btcFutures": 0,
            "btcMargin": 0,
            "busd": 0,
            "busdFutures": 0,
            "busdMargin": 0,
            "date": 1676851200000
        },
        {
            "userId": 1000138138384,
            "btc": 0,
            "btcFutures": 0,
            "btcMargin": 0,
            "busd": 0,
            "busdFutures": 0,
            "busdMargin": 0,
            "date": 1677110400000
        },
        {
            "userId": 1000138138384,
            "btc": 0,
            "btcFutures": 0,
            "btcMargin": 0,
            "busd": 0,
            "busdFutures": 0,
            "busdMargin": 0,
            "date": 1677369600000
        }
    ]
}

GET /sapi/v1/sub-account/transaction-statistics (HMAC SHA256)

Query Sub-account Transaction Tatistics (For Master Account).

Weight(UID): 60

Parameters:

Name Type Mandatory Description
email STRING YES Sub user email
recvWindow LONG NO
timestamp LONG YES

Get Managed Sub-account Deposit Address (For Investor Master Account) (USER_DATA)

Response:

{
    "coin": "USDT",
    "address": "0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d",
    "tag": "",
    "url": "https://etherscan.io/address/0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d"
}

GET /sapi/v1/managed-subaccount/deposit/address (HMAC SHA256)

Get investor’s managed sub-account deposit address.

Weight(UID):
1

Parameters:

Name Type Mandatory Description
email STRING YES Sub user email
coin STRING YES
network STRING NO networks can be found in GET /sapi/v1/capital/deposit/address
recvWindow LONG NO
timestamp LONG YES
  • If network is not send, return with default network of the coin.

Market Data Endpoints

Test Connectivity

Response:

{}


GET /api/v3/ping

Test connectivity to the Rest API.

Weight(IP):
1

Parameters:

NONE

Data Source: Memory

Check Server Time

Response:

{
  "serverTime": 1499827319559
}


GET /api/v3/time

Test connectivity to the Rest API and get the current server time.

Weight(IP):
1

Parameters:

NONE

Data Source:
Memory

Exchange Information

Response:

{
  "timezone": "UTC",
  "serverTime": 1565246363776,
  "rateLimits": [
    {
      //These are defined in the `ENUM definitions` section under `Rate Limiters (rateLimitType)`.
      //All limits are optional
    }
  ],
  "exchangeFilters": [
    //These are the defined filters in the `Filters` section.
    //All filters are optional.
  ],
  "symbols": [
    {
      "symbol": "ETHBTC",
      "status": "TRADING",
      "baseAsset": "ETH",
      "baseAssetPrecision": 8,
      "quoteAsset": "BTC",
      "quotePrecision": 8,
      "quoteAssetPrecision": 8,
      "orderTypes": [
        "LIMIT",
        "LIMIT_MAKER",
        "MARKET",
        "STOP_LOSS",
        "STOP_LOSS_LIMIT",
        "TAKE_PROFIT",
        "TAKE_PROFIT_LIMIT"
      ],
      "icebergAllowed": true,
      "ocoAllowed": true,
      "quoteOrderQtyMarketAllowed": true,
      "allowTrailingStop": false,
      "cancelReplaceAllowed": false,
      "isSpotTradingAllowed": true,
      "isMarginTradingAllowed": true,
      "filters": [
        //These are defined in the Filters section.
        //All filters are optional
      ],
      "permissions": [
         "SPOT",
         "MARGIN"
      ],
      "defaultSelfTradePreventionMode": "NONE",
      "allowedSelfTradePreventionModes": [
        "NONE"
      ]
    }
  ]
}


GET /api/v3/exchangeInfo

Current exchange trading rules and symbol information

Weight(IP):
10

Parameters:

There are 4 possible options:

Options Example
No parameter curl -X GET «https://api.binance.com/api/v3/exchangeInfo»
symbol curl -X GET «https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC»
symbols curl -X GET «https://api.binance.com/api/v3/exchangeInfo?symbols=%5B%22BNBBTC%22,%22BTCUSDT%22%5D»

or

curl -g -X GET ‘https://api.binance.com/api/v3/exchangeInfo?symbols=[«BTCUSDT»,»BNBBTC»]’

permissions curl -X GET «https://api.binance.com/api/v3/exchangeInfo?permissions=SPOT»

or

curl -X GET «https://api.binance.com/api/v3/exchangeInfo?permissions=%5B%22MARGIN%22%2C%22LEVERAGED%22%5D»

or

curl -g -X GET ‘https://api.binance.com/api/v3/exchangeInfo?permissions=[«MARGIN»,»LEVERAGED»]’

Notes:

  • If the value provided to symbol or symbols do not exist, the endpoint will throw an error saying the symbol is invalid.
  • All parameters are optional.
  • permissions can support single or multiple values (e.g. SPOT, ["MARGIN","LEVERAGED"])
  • If permissions parameter not provided, the default values will be ["SPOT","MARGIN","LEVERAGED"].
    • If one wants to view all symbols on GET /api/v3/exchangeInfo, then one has to search with all permissions explicitly specified
      (i.e. permissions=["SPOT","MARGIN","LEVERAGED","TRD_GRP_002","TRD_GRP_003","TRD_GRP_004","TRD_GRP_005","TRD_GRP_006","TRD_GRP_007"])

Data Source:
Memory

Order Book

Response:

{
  "lastUpdateId": 1027024,
  "bids": [
    [
      "4.00000000",     // PRICE
      "431.00000000"    // QTY
    ]
  ],
  "asks": [
    [
      "4.00000200",
      "12.00000000"
    ]
  ]
}


GET /api/v3/depth

Weight(IP):

Adjusted based on the limit:

Limit Weight
1-100 1
101-500 5
501-1000 10
1001-5000 50

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 100; max 5000.

If limit > 5000, then the response will truncate to 5000.

Data Source:
Memory

Recent Trades List

Response:

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590,
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]


GET /api/v3/trades

Get recent trades.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 500; max 1000.

Data Source:
Memory

Old Trade Lookup (MARKET_DATA)

Response:

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590, // Trade executed timestamp, as same as `T` in the stream
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]


GET /api/v3/historicalTrades

Get older market trades.

Weight(IP):
5

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 500; max 1000.
fromId LONG NO Trade id to fetch from. Default gets most recent trades.

Data Source:
Database

Compressed/Aggregate Trades List

Response:

[
  {
    "a": 26129,         // Aggregate tradeId
    "p": "0.01633102",  // Price
    "q": "4.70443515",  // Quantity
    "f": 27781,         // First tradeId
    "l": 27781,         // Last tradeId
    "T": 1498793709153, // Timestamp
    "m": true,          // Was the buyer the maker?
    "M": true           // Was the trade the best price match?
  }
]


GET /api/v3/aggTrades

Get compressed, aggregate trades. Trades that fill at the time, from the same
order, with the same price will have the quantity aggregated.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
fromId LONG NO id to get aggregate trades from INCLUSIVE.
startTime LONG NO Timestamp in ms to get aggregate trades from INCLUSIVE.
endTime LONG NO Timestamp in ms to get aggregate trades until INCLUSIVE.
limit INT NO Default 500; max 1000.
  • If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.
  • Note that if a trade has the following values, this was a duplicate aggregate trade and marked as invalid:
    • p = ‘0’ // price
    • q = ‘0’ // qty
    • f = -1 // first_trade_id
    • l = -1 // last_trade_id

Data Source:
Database

Kline/Candlestick Data

Response:

[
  [
    1499040000000,      // Kline open time
    "0.01634790",       // Open price
    "0.80000000",       // High price
    "0.01575800",       // Low price
    "0.01577100",       // Close price
    "148976.11427815",  // Volume
    1499644799999,      // Kline Close time
    "2434.19055334",    // Quote asset volume
    308,                // Number of trades
    "1756.87402397",    // Taker buy base asset volume
    "28.46694368",      // Taker buy quote asset volume
    "0"                 // Unused field, ignore.
  ]
]


GET /api/v3/klines

Kline/candlestick bars for a symbol.
Klines are uniquely identified by their open time.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
interval ENUM YES
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
  • If startTime and endTime are not sent, the most recent klines are returned.

Data Source:
Database

UIKlines

Response:

[
  [
    1499040000000,      // Kline open time
    "0.01634790",       // Open price
    "0.80000000",       // High price
    "0.01575800",       // Low price
    "0.01577100",       // Close price
    "148976.11427815",  // Volume
    1499644799999,      // Kline close time
    "2434.19055334",    // Quote asset volume
    308,                // Number of trades
    "1756.87402397",    // Taker buy base asset volume
    "28.46694368",      // Taker buy quote asset volume
    "0"                 // Unused field. Ignore.
  ]
]


GET /api/v3/uiKlines

The request is similar to klines having the same parameters and response.

uiKlines return modified kline data, optimized for presentation of candlestick charts.

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
interval ENUM YES
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
  • If startTime and endTime are not sent, the most recent klines are returned.

Data Source:
Database

Current Average Price

Response:

{
  "mins": 5,
  "price": "9.35751834"
}


GET /api/v3/avgPrice

Current average price for a symbol.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING YES

Data Source:
Memory

24hr Ticker Price Change Statistics

Response: — FULL

{
  "symbol": "BNBBTC",
  "priceChange": "-94.99999800",
  "priceChangePercent": "-95.960",
  "weightedAvgPrice": "0.29628482",
  "prevClosePrice": "0.10002000",
  "lastPrice": "4.00000200",
  "lastQty": "200.00000000",
  "bidPrice": "4.00000000",
  "bidQty": "100.00000000",
  "askPrice": "4.00000200",
  "askQty": "100.00000000",
  "openPrice": "99.00000000",
  "highPrice": "100.00000000",
  "lowPrice": "0.10000000",
  "volume": "8913.30000000",
  "quoteVolume": "15.30000000",
  "openTime": 1499783499040,
  "closeTime": 1499869899040,
  "firstId": 28385,   // First tradeId
  "lastId": 28460,    // Last tradeId
  "count": 76         // Trade count
}

OR

[
  {
    "symbol": "BNBBTC",
    "priceChange": "-94.99999800",
    "priceChangePercent": "-95.960",
    "weightedAvgPrice": "0.29628482",
    "prevClosePrice": "0.10002000",
    "lastPrice": "4.00000200",
    "lastQty": "200.00000000",
    "bidPrice": "4.00000000",
    "bidQty": "100.00000000",
    "askPrice": "4.00000200",
    "askQty": "100.00000000",
    "openPrice": "99.00000000",
    "highPrice": "100.00000000",
    "lowPrice": "0.10000000",
    "volume": "8913.30000000",
    "quoteVolume": "15.30000000",
    "openTime": 1499783499040,
    "closeTime": 1499869899040,
    "firstId": 28385,   // First tradeId
    "lastId": 28460,    // Last tradeId
    "count": 76         // Trade count
  }
]

Response — MINI

{
  "symbol":      "BNBBTC",          // Symbol Name
  "openPrice":   "99.00000000",     // Opening price of the Interval
  "highPrice":   "100.00000000",    // Highest price in the interval
  "lowPrice":    "0.10000000",      // Lowest  price in the interval
  "lastPrice":   "4.00000200",      // Closing price of the interval
  "volume":      "8913.30000000",   // Total trade volume (in base asset)
  "quoteVolume": "15.30000000",     // Total trade volume (in quote asset)
  "openTime":    1499783499040,     // Start of the ticker interval
  "closeTime":   1499869899040,     // End of the ticker interval
  "firstId":     28385,             // First tradeId considered
  "lastId":      28460,             // Last tradeId considered
  "count":       76                 // Total trade count
}

OR

[
  {
    "symbol": "BNBBTC",
    "openPrice": "99.00000000",
    "highPrice": "100.00000000",
    "lowPrice": "0.10000000",
    "lastPrice": "4.00000200",
    "volume": "8913.30000000",
    "quoteVolume": "15.30000000",
    "openTime": 1499783499040,
    "closeTime": 1499869899040,
    "firstId": 28385,
    "lastId": 28460,
    "count": 76
  },
  {
    "symbol": "LTCBTC",
    "openPrice": "0.07000000",
    "highPrice": "0.07000000",
    "lowPrice": "0.07000000",
    "lastPrice": "0.07000000",
    "volume": "11.00000000",
    "quoteVolume": "0.77000000",
    "openTime": 1656908192899,
    "closeTime": 1656994592899,
    "firstId": 0,
    "lastId": 10,
    "count": 11
  }
]


GET /api/v3/ticker/24hr

24 hour rolling window price change statistics. Careful when accessing this with no symbol.

Weight(IP):

Parameter Symbols Provided Weight
symbol 1 1
symbol parameter is omitted 40
symbols 1-20 1
21-100 20
101 or more 40
symbols parameter is omitted 40

Parameters:

Name Type Mandatory Description
symbol STRING NO Parameter symbol and symbols cannot be used in combination.

If neither parameter is sent, tickers for all symbols will be returned in an array.

Examples of accepted format for the symbols parameter:
[«BTCUSDT»,»BNBUSDT»]

or

%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

symbols STRING NO
type ENUM NO Supported values: FULL or MINI.

If none provided, the default is

FULL

Data Source:
Memory

Symbol Price Ticker

Response:

{
  "symbol": "LTCBTC",
  "price": "4.00000200"
}

OR

[
  {
    "symbol": "LTCBTC",
    "price": "4.00000200"
  },
  {
    "symbol": "ETHBTC",
    "price": "0.07946600"
  }
]


GET /api/v3/ticker/price

Latest price for a symbol or symbols.

Weight(IP):

Parameter Symbols Provided Weight
symbol 1 1
symbol parameter is omitted 2
symbols Any 2

Parameters:

Name Type Mandatory Description
symbol STRING NO Parameter symbol and symbols cannot be used in combination.

If neither parameter is sent, prices for all symbols will be returned in an array.

Examples of accepted format for the symbols parameter:
[«BTCUSDT»,»BNBUSDT»]

or

%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

symbols STRING NO

Data Source:
Memory

Symbol Order Book Ticker

Response:

{
  "symbol": "LTCBTC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}

OR

[
  {
    "symbol": "LTCBTC",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000"
  },
  {
    "symbol": "ETHBTC",
    "bidPrice": "0.07946700",
    "bidQty": "9.00000000",
    "askPrice": "100000.00000000",
    "askQty": "1000.00000000"
  }
]


GET /api/v3/ticker/bookTicker

Best price/qty on the order book for a symbol or symbols.

Weight(IP):

Parameter Symbols Provided Weight
symbol 1 1
symbol parameter is omitted 2
symbols Any 2

Parameters:

Name Type Mandatory Description
symbol STRING NO Parameter symbol and symbols cannot be used in combination.

If neither parameter is sent, bookTickers for all symbols will be returned in an array.

Examples of accepted format for the symbols parameter:
[«BTCUSDT»,»BNBUSDT»]

or

%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

symbols STRING NO

Data Source:
Memory

Rolling window price change statistics

Response: — FULL

{
  "symbol":             "BNBBTC",
  "priceChange":        "-8.00000000",  // Absolute price change
  "priceChangePercent": "-88.889",      // Relative price change in percent
  "weightedAvgPrice":   "2.60427807",   // QuoteVolume / Volume
  "openPrice":          "9.00000000",
  "highPrice":          "9.00000000",
  "lowPrice":           "1.00000000",
  "lastPrice":          "1.00000000",
  "volume":             "187.00000000",
  "quoteVolume":        "487.00000000", // Sum of (price * volume) for all trades
  "openTime":           1641859200000,  // Open time for ticker window
  "closeTime":          1642031999999,  // Current Time of the Request
  "firstId":            0,              // Trade IDs
  "lastId":             60,
  "count":              61              // Number of trades in the interval
}

OR

[
  {
    "symbol": "BTCUSDT",
    "priceChange": "-154.13000000",        // Absolute price change
    "priceChangePercent": "-0.740",        // Relative price change in percent
    "weightedAvgPrice": "20677.46305250",  // QuoteVolume / Volume
    "openPrice": "20825.27000000",
    "highPrice": "20972.46000000",
    "lowPrice": "20327.92000000",
    "lastPrice": "20671.14000000",
    "volume": "72.65112300",
    "quoteVolume": "1502240.91155513",     // Sum of (price * volume) for all trades
    "openTime": 1655432400000,             // Open time for ticker window
    "closeTime": 1655446835460,            // Close time for ticker window
    "firstId": 11147809,                   // Trade IDs
    "lastId": 11149775,
    "count": 1967                          // Number of trades in the interval
  },
  {
    "symbol": "BNBBTC",
    "priceChange": "0.00008530",
    "priceChangePercent": "0.823",
    "weightedAvgPrice": "0.01043129",
    "openPrice": "0.01036170",
    "highPrice": "0.01049850",
    "lowPrice": "0.01033870",
    "lastPrice": "0.01044700",
    "volume": "166.67000000",
    "quoteVolume": "1.73858301",
    "openTime": 1655432400000,
    "closeTime": 1655446835460,
    "firstId": 2351674,
    "lastId": 2352034,
    "count": 361
  }
]

Response — MINI

{
    "symbol": "LTCBTC",
    "openPrice": "0.10000000",
    "highPrice": "2.00000000",
    "lowPrice": "0.10000000",
    "lastPrice": "2.00000000",
    "volume": "39.00000000",
    "quoteVolume": "13.40000000",  // Sum of (price * volume) for all trades
    "openTime": 1656986580000,     // Open time for ticker window
    "closeTime": 1657001016795,    // Close time for ticker window
    "firstId": 0,                  // Trade IDs
    "lastId": 34,
    "count": 35                    // Number of trades in the interval
}

OR

[
    {
        "symbol": "BNBBTC",
        "openPrice": "0.10000000",
        "highPrice": "2.00000000",
        "lowPrice": "0.10000000",
        "lastPrice": "2.00000000",
        "volume": "39.00000000",
        "quoteVolume": "13.40000000", // Sum of (price * volume) for all trades
        "openTime": 1656986880000,    // Open time for ticker window
        "closeTime": 1657001297799,   // Close time for ticker window
        "firstId": 0,                 // Trade IDs
        "lastId": 34,
        "count": 35                   // Number of trades in the interval
    },
    {
        "symbol": "LTCBTC",
        "openPrice": "0.07000000",
        "highPrice": "0.07000000",
        "lowPrice": "0.07000000",
        "lastPrice": "0.07000000",
        "volume": "33.00000000",
        "quoteVolume": "2.31000000",
        "openTime": 1656986880000,
        "closeTime": 1657001297799,
        "firstId": 0,
        "lastId": 32,
        "count": 33
    }
]


GET /api/v3/ticker

Note: This endpoint is different from the GET /api/v3/ticker/24hr endpoint.

The window used to compute statistics will be no more than 59999ms from the requested windowSize.

openTime for /api/v3/ticker always starts on a minute, while the closeTime is the current time of the request.
As such, the effective window will be up to 59999ms wider than windowSize.

E.g. If the closeTime is 1641287867099 (January 04, 2022 09:17:47:099 UTC) , and the windowSize is 1d. the openTime will be: 1641201420000 (January 3, 2022, 09:17:00 UTC)

Weight:(IP)

2 for each requested

symbol

regardless of

windowSize

The weight for this request will cap at 100 once the number of symbols in the request is more than 50.

Parameters

Name Type Mandatory Description
symbol STRING YES Either symbol or symbols must be provided

Examples of accepted format for the

symbols parameter:

[«BTCUSDT»,»BNBUSDT»]

or

%5B%22BTCUSDT%22,%22BNBUSDT%22%5D

The maximum number of

symbols allowed in a request is 100.

symbols
windowSize ENUM NO Defaults to 1d if no parameter provided

Supported

windowSize values: 1m,2m….59m for minutes 1h, 2h….23h — for hours 1d…7d — for days

Units cannot be combined (e.g.

1d2h is not allowed)

type ENUM NO Supported values: FULL or MINI.

If none provided, the default is

FULL

Data Source:
Database


Websocket Market Streams

  • The base endpoint is: wss://stream.binance.com:9443 or wss://stream.binance.com:443
  • Streams can be accessed either in a single raw stream or in a combined stream.
  • Users can listen to multiple streams.
  • Raw streams are accessed at /ws/<streamName>
  • Combined streams are accessed at /stream?streams=<streamName1>/<streamName2>/<streamName3>
  • Combined stream events are wrapped as follows: {«stream»:»<streamName>»,»data»:<rawPayload>}
  • All symbols for streams are lowercase
  • A single connection to stream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark
  • The websocket server will send a ping frame every 3 minutes. If the websocket server does not receive a pong frame back from the connection within a 10 minute period, the connection will be disconnected. Unsolicited pong frames are allowed.
  • The base endpoint wss://data-stream.binance.com can be subscribed to receive market data messages. Users data stream is NOT available from this URL.

Live Subscribing/Unsubscribing to streams

  • The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below.
  • The id used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth.
  • In the response, if the result received is null this means the request sent was a success.

Subscribe to a stream

Response

  {
    "result": null,  
    "id": 1
  }
  • Request

    {
    «method»: «SUBSCRIBE»,
    «params»:
    [
    «btcusdt@aggTrade»,
    «btcusdt@depth»
    ],
    «id»: 1
    }

Unsubscribe to a stream

Response

  {
    "result": null,
    "id": 312
  }
  • Request

{
«method»: «UNSUBSCRIBE»,
«params»:
[
«btcusdt@depth»
],
«id»: 312
}

Listing Subscriptions

Response

  {
    "result": [
      "btcusdt@aggTrade"
    ],
    "id": 3
  }
  • Request

{
«method»: «LIST_SUBSCRIPTIONS»,
«id»: 3
}

Setting Properties

Currently, the only property can be set is to set whether combined stream payloads are enabled or not.
The combined property is set to false when connecting using /ws/ («raw streams») and true when connecting using /stream/.

Response

{
  "result": null,
  "id": 5
}
  • Request

{
«method»: «SET_PROPERTY»,
«params»:
[
«combined»,
true
],
«id»: 5
}

Retrieving Properties

Response

  {
    "result": true, // Indicates that combined is set to true.
    "id": 2
  }
  • Request

{
«method»: «GET_PROPERTY»,
«params»:
[
«combined»
],
«id»: 2
}

Error Messages

Error Message Description
{«code»: 0, «msg»: «Unknown property», «id»: ‘%s’} Parameter used in the SET_PROPERTY or GET_PROPERTY was invalid
{«code»: 1, «msg»: «Invalid value type: expected Boolean», «id»: ‘%s’} Value should only be true or false
{«code»: 2, «msg»: «Invalid request: property name must be a string»} Property name provided was invalid
{«code»: 2, «msg»: «Invalid request: request ID must be an unsigned integer»} Parameter id had to be provided or the value provided in the id parameter is an unsupported type
{«code»: 2, «msg»: «Invalid request: unknown variant %s, expected one of SUBSCRIBE, UNSUBSCRIBE, LIST_SUBSCRIPTIONS, SET_PROPERTY, GET_PROPERTY at line 1 column 28″} Possible typo in the provided method or provided method was neither of the expected values
{«code»: 2, «msg»: «Invalid request: too many parameters»} Unnecessary parameters provided in the data
{«code»: 2, «msg»: «Invalid request: property name must be a string»} Property name was not provided
{«code»: 2, «msg»: «Invalid request: missing field method at line 1 column 73″} method was not provided in the data
{«code»:3,»msg»:»Invalid JSON: expected value at line %s column %s»} JSON data sent has incorrect syntax.

Aggregate Trade Streams

Payload:

{
  "e": "aggTrade",  // Event type
  "E": 123456789,   // Event time
  "s": "BNBBTC",    // Symbol
  "a": 12345,       // Aggregate trade ID
  "p": "0.001",     // Price
  "q": "100",       // Quantity
  "f": 100,         // First trade ID
  "l": 105,         // Last trade ID
  "T": 123456785,   // Trade time
  "m": true,        // Is the buyer the market maker?
  "M": true         // Ignore
}

The Aggregate Trade Streams push trade information that is aggregated for a single taker order.

Stream Name: <symbol>@aggTrade

Update Speed: Real-time

Trade Streams

Payload:

{
  "e": "trade",     // Event type
  "E": 123456789,   // Event time
  "s": "BNBBTC",    // Symbol
  "t": 12345,       // Trade ID
  "p": "0.001",     // Price
  "q": "100",       // Quantity
  "b": 88,          // Buyer order ID
  "a": 50,          // Seller order ID
  "T": 123456785,   // Trade time
  "m": true,        // Is the buyer the market maker?
  "M": true         // Ignore
}

The Trade Streams push raw trade information; each trade has a unique buyer and seller.

Stream Name: <symbol>@trade

Update Speed: Real-time

Kline/Candlestick Streams

Payload:

{
  "e": "kline",     // Event type
  "E": 123456789,   // Event time
  "s": "BNBBTC",    // Symbol
  "k": {
    "t": 123400000, // Kline start time
    "T": 123460000, // Kline close time
    "s": "BNBBTC",  // Symbol
    "i": "1m",      // Interval
    "f": 100,       // First trade ID
    "L": 200,       // Last trade ID
    "o": "0.0010",  // Open price
    "c": "0.0020",  // Close price
    "h": "0.0025",  // High price
    "l": "0.0015",  // Low price
    "v": "1000",    // Base asset volume
    "n": 100,       // Number of trades
    "x": false,     // Is this kline closed?
    "q": "1.0000",  // Quote asset volume
    "V": "500",     // Taker buy base asset volume
    "Q": "0.500",   // Taker buy quote asset volume
    "B": "123456"   // Ignore
  }
}

The Kline/Candlestick Stream push updates to the current klines/candlestick every second.

Stream Name: <symbol>@kline_<interval>

Update Speed: 1000ms for 1s, 2000ms for the other intervals

Kline/Candlestick chart intervals:

s-> seconds; m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

  • 1s
  • 1m
  • 3m
  • 5m
  • 15m
  • 30m
  • 1h
  • 2h
  • 4h
  • 6h
  • 8h
  • 12h
  • 1d
  • 3d
  • 1w
  • 1M

Individual Symbol Mini Ticker Stream

Payload:

  {
    "e": "24hrMiniTicker",  // Event type
    "E": 123456789,         // Event time
    "s": "BNBBTC",          // Symbol
    "c": "0.0025",          // Close price
    "o": "0.0010",          // Open price
    "h": "0.0025",          // High price
    "l": "0.0010",          // Low price
    "v": "10000",           // Total traded base asset volume
    "q": "18"               // Total traded quote asset volume
  }

24hr rolling window mini-ticker statistics. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.

Stream Name: <symbol>@miniTicker

Update Speed: 1000ms

All Market Mini Tickers Stream

Payload:

[
  {
    // Same as <symbol>@miniTicker payload
  }
]

24hr rolling window mini-ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.

Stream Name: !miniTicker@arr

Update Speed: 1000ms

Individual Symbol Ticker Streams

Payload:

{
  "e": "24hrTicker",  // Event type
  "E": 123456789,     // Event time
  "s": "BNBBTC",      // Symbol
  "p": "0.0015",      // Price change
  "P": "250.00",      // Price change percent
  "w": "0.0018",      // Weighted average price
  "x": "0.0009",      // First trade(F)-1 price (first trade before the 24hr rolling window)
  "c": "0.0025",      // Last price
  "Q": "10",          // Last quantity
  "b": "0.0024",      // Best bid price
  "B": "10",          // Best bid quantity
  "a": "0.0026",      // Best ask price
  "A": "100",         // Best ask quantity
  "o": "0.0010",      // Open price
  "h": "0.0025",      // High price
  "l": "0.0010",      // Low price
  "v": "10000",       // Total traded base asset volume
  "q": "18",          // Total traded quote asset volume
  "O": 0,             // Statistics open time
  "C": 86400000,      // Statistics close time
  "F": 0,             // First trade ID
  "L": 18150,         // Last trade Id
  "n": 18151          // Total number of trades
}

24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.

Stream Name: <symbol>@ticker

Update Speed: 1000ms

All Market Tickers Stream

Payload:

[
  {
    // Same as <symbol>@ticker payload
  }
]

24hr rolling window ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.

Stream Name: !ticker@arr

Update Speed: 1000ms

Individual Symbol Rolling Window Statistics Streams

Payload:

{
  "e": "1hTicker",    // Event type
  "E": 123456789,     // Event time
  "s": "BNBBTC",      // Symbol
  "p": "0.0015",      // Price change
  "P": "250.00",      // Price change percent
  "o": "0.0010",      // Open price
  "h": "0.0025",      // High price
  "l": "0.0010",      // Low price
  "c": "0.0025",      // Last price
  "w": "0.0018",      // Weighted average price
  "v": "10000",       // Total traded base asset volume
  "q": "18",          // Total traded quote asset volume
  "O": 0,             // Statistics open time
  "C": 86400000,      // Statistics close time
  "F": 0,             // First trade ID
  "L": 18150,         // Last trade Id
  "n": 18151          // Total number of trades
}

Rolling window ticker statistics for a single symbol, computed over multiple windows.

Stream Name: <symbol>@ticker_<window_size>

Window Sizes: 1h,4h,1d

Update Speed: 1000ms

Note: This stream is different from the <symbol>@ticker stream.
The open time O always starts on a minute, while the closing time C is the current time of the update.

As such, the effective window might be up to 59999ms wider that <window_size>.

All Market Rolling Window Statistics Streams

Payload:

[
  {
    // Same as <symbol>@ticker_<window-size> payload,
    // one for each symbol updated within the interval.
  }
]

Rolling window ticker statistics for all market symbols, computed over multiple windows.
Note that only tickers that have changed will be present in the array.

Stream Name: !ticker_<window-size>@arr

Window Size: 1h,4h,1d

Update Speed: 1000ms

Individual Symbol Book Ticker Streams

Payload:

{
  "u":400900217,     // order book updateId
  "s":"BNBUSDT",     // symbol
  "b":"25.35190000", // best bid price
  "B":"31.21000000", // best bid qty
  "a":"25.36520000", // best ask price
  "A":"40.66000000"  // best ask qty
}

Pushes any update to the best bid or ask’s price or quantity in real-time for a specified symbol.

Multiple <symbol>@bookTicker streams can be subscribed to over one connection.

Stream Name: <symbol>@bookTicker

Update Speed: Real-time

Partial Book Depth Streams

Payload:

{
  "lastUpdateId": 160,  // Last update ID
  "bids": [             // Bids to be updated
    [
      "0.0024",         // Price level to be updated
      "10"              // Quantity
    ]
  ],
  "asks": [             // Asks to be updated
    [
      "0.0026",         // Price level to be updated
      "100"             // Quantity
    ]
  ]
}

Top bids and asks, Valid are 5, 10, or 20.

Stream Names: <symbol>@depth<levels> OR <symbol>@depth<levels>@100ms.

Update Speed: 1000ms or 100ms

Diff. Depth Stream

Payload:

{
  "e": "depthUpdate", // Event type
  "E": 123456789,     // Event time
  "s": "BNBBTC",      // Symbol
  "U": 157,           // First update ID in event
  "u": 160,           // Final update ID in event
  "b": [              // Bids to be updated
    [
      "0.0024",       // Price level to be updated
      "10"            // Quantity
    ]
  ],
  "a": [              // Asks to be updated
    [
      "0.0026",       // Price level to be updated
      "100"           // Quantity
    ]
  ]
}

Stream Name: <symbol>@depth OR <symbol>@depth@100ms

Update Speed: 1000ms or 100ms

Order book price and quantity depth updates used to locally manage an order book.

How to manage a local order book correctly

  1. Open a stream to wss://stream.binance.com:9443/ws/bnbbtc@depth.
  2. Buffer the events you receive from the stream.
  3. Get a depth snapshot from https://api.binance.com/api/v3/depth?symbol=BNBBTC&limit=1000 .
  4. Drop any event where u is <= lastUpdateId in the snapshot.
  5. The first processed event should have U <= lastUpdateId+1 AND u >= lastUpdateId+1.
  6. While listening to the stream, each new event’s U should be equal to the previous event’s u+1.
  7. The data in each event is the absolute quantity for a price level.
  8. If the quantity is 0, remove the price level.
  9. Receiving an event that removes a price level that is not in your local order book can happen and is normal.

Note:
Due to depth snapshots having a limit on the number of price levels, a price level outside of the initial snapshot that doesn’t have a quantity change won’t have an update in the Diff. Depth Stream. Consequently, those price levels will not be visible in the local order book even when applying all updates from the Diff. Depth Stream correctly and cause the local order book to have some slight differences with the real order book. However, for most use cases the depth limit of 5000 is enough to understand the market and trade effectively.

Spot Account/Trade

Test New Order (TRADE)

Response:

{}


POST /api/v3/order/test (HMAC SHA256)

Test new order creation and signature/recvWindow long.
Creates and validates a new order but does not send it into the matching engine.

Weight:
1

Parameters:

Same as POST /api/v3/order

Data Source:
Memory

New Order (TRADE)

Response ACK:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "orderListId": -1, //Unless OCO, value will be -1
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595
}

Response RESULT:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "orderListId": -1, //Unless OCO, value will be -1
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "0.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "workingTime": 1507725176595,
  "selfTradePreventionMode": "NONE"
}

Response FULL:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "orderListId": -1, //Unless OCO, value will be -1
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "0.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "workingTime": 1507725176595,
  "selfTradePreventionMode": "NONE",
  "fills": [
    {
      "price": "4000.00000000",
      "qty": "1.00000000",
      "commission": "4.00000000",
      "commissionAsset": "USDT",
      "tradeId": 56
    },
    {
      "price": "3999.00000000",
      "qty": "5.00000000",
      "commission": "19.99500000",
      "commissionAsset": "USDT",
      "tradeId": 57
    },
    {
      "price": "3998.00000000",
      "qty": "2.00000000",
      "commission": "7.99600000",
      "commissionAsset": "USDT",
      "tradeId": 58
    },
    {
      "price": "3997.00000000",
      "qty": "1.00000000",
      "commission": "3.99700000",
      "commissionAsset": "USDT",
      "tradeId": 59
    },
    {
      "price": "3995.00000000",
      "qty": "1.00000000",
      "commission": "3.99500000",
      "commissionAsset": "USDT",
      "tradeId": 60
    }
  ]
}


POST /api/v3/order (HMAC SHA256)

Send in a new order.

Weight(UID): 1
Weight(IP): 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
side ENUM YES
type ENUM YES
timeInForce ENUM NO
quantity DECIMAL NO
quoteOrderQty DECIMAL NO
price DECIMAL NO
newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent.
strategyId INT NO
strategyType INT NO The value cannot be less than 1000000.
stopPrice DECIMAL NO Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
trailingDelta LONG NO Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. For more details on SPOT implementation on trailing stops, please refer to Trailing Stop FAQ
icebergQty DECIMAL NO Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
newOrderRespType ENUM NO Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
selfTradePreventionMode ENUM NO The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Additional mandatory parameters based on type:

Type Additional mandatory parameters
LIMIT timeInForce, quantity, price
MARKET quantity or quoteOrderQty
STOP_LOSS quantity, stopPrice or trailingDelta
STOP_LOSS_LIMIT timeInForce, quantity, price, stopPrice or trailingDelta
TAKE_PROFIT quantity, stopPrice or trailingDelta
TAKE_PROFIT_LIMIT timeInForce, quantity, price, stopPrice or trailingDelta
LIMIT_MAKER quantity, price

Other info:

  • LIMIT_MAKER are LIMIT orders that will be rejected if they would immediately match and trade as a taker.
  • STOP_LOSS and TAKE_PROFIT will execute a MARKET order when the stopPrice is reached.
  • Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty.
  • Any order with an icebergQty MUST have timeInForce set to GTC.
  • MARKET orders using the quantity field specifies the amount of the base asset the user wants to buy or sell at the market price.
    • For example, sending a MARKET order on BTCUSDT will specify how much BTC the user is buying or selling.
  • MARKET orders using quoteOrderQty specifies the amount the user wants to spend (when buying) or receive (when selling) the quote asset; the correct quantity will be determined based on the market liquidity and quoteOrderQty.
    • Using BTCUSDT as an example:
      • On the BUY side, the order will buy as many BTC as quoteOrderQty USDT can.
      • On the SELL side, the order will sell as much BTC needed to receive quoteOrderQty USDT.
  • MARKET orders using quoteOrderQty will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty.
  • same newClientOrderId can be accepted only when the previous one is filled, otherwise the order will be rejected.
  • For STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT_LIMIT and TAKE_PROFIT orders, trailingDelta can be combined with stopPrice.

Trigger order price rules against market price for both MARKET and LIMIT versions:

  • Price above market price: STOP_LOSS BUY, TAKE_PROFIT SELL
  • Price below market price: STOP_LOSS SELL, TAKE_PROFIT BUY

Data Source:
Matching Engine

Conditional fields in Order Responses

There are fields in the order responses (e.g. order placement, order query, order cancellation) that appear only if certain conditions are met.

These fields can apply to OCO Orders.

The fields are listed below:

Field Description Visibility conditions Examples
icebergQty Quantity for the iceberg order Appears only if the parameter icebergQty was sent in the request. "icebergQty": "0.00000000"
preventedMatchId When used in combination with symbol, can be used to query a prevented match. Appears only if the order expired due to STP. "preventedMatchId": 0
preventedQuantity Order quantity that expired due to STP Appears only if the order expired due to STP. "preventedQuantity": "1.200000"
stopPrice Price when the algorithmic order will be triggered Appears for STOP_LOSS. TAKE_PROFIT, STOP_LOSS_LIMIT and TAKE_PROFIT_LIMIT orders. "stopPrice": "23500.00000000"
strategyId Can be used to label an order that’s part of an order strategy. Appears if the parameter was populated in the request. "strategyId": 37463720
strategyType Can be used to label an order that is using an order strategy. Appears if the parameter was populated in the request. "strategyType": 1000000
trailingDelta Delta price change required before order activation Appears for Trailing Stop Orders. "trailingDelta": 10
trailingTime Time when the trailing order is now active and tracking price changes Appears only for Trailing Stop Orders. "trailingTime": -1

Cancel Order (TRADE)

Response:

{
  "symbol": "LTCBTC",
  "origClientOrderId": "myOrder1",
  "orderId": 4,
  "orderListId": -1, //Unless part of an OCO, the value will always be -1.
  "clientOrderId": "cancelMyOrder1",
  "price": "2.00000000",
  "origQty": "1.00000000",
  "executedQty": "0.00000000",
  "cummulativeQuoteQty": "0.00000000",
  "status": "CANCELED",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "BUY",
  "selfTradePreventionMode": "NONE"
}


DELETE /api/v3/order (HMAC SHA256)

Cancel an active order.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO
origClientOrderId STRING NO
newClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default.
cancelRestrictions ENUM NO Supported values:
ONLY_NEW — Cancel will succeed if the order status is NEW.
ONLY_PARTIALLY_FILLED — Cancel will succeed if order status is PARTIALLY_FILLED.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Either orderId or origClientOrderId must be sent.
If both orderId and origClientOrderId are provided, orderId takes precedence.

Data Source:
Matching Engine

Regarding cancelRestrictions

  • If the cancelRestrictions value is not any of the supported values, the error will be:
    • {"code": -1145,"msg": "Invalid cancelRestrictions"}
  • If the order did not pass the conditions for cancelRestrictions, the error will be:
    • {"code": -2011,"msg": "Order was not canceled due to cancel restrictions."}

Note: The payload sample does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

Cancel all Open Orders on a Symbol (TRADE)

Response:

[
  {
    "symbol": "BTCUSDT",
    "origClientOrderId": "E6APeyTJvkMvLMYMqu1KQ4",
    "orderId": 11,
    "orderListId": -1,
    "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
    "price": "0.089853",
    "origQty": "0.178622",
    "executedQty": "0.000000",
    "cummulativeQuoteQty": "0.000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "selfTradePreventionMode": "NONE"
  },
  {
    "symbol": "BTCUSDT",
    "origClientOrderId": "A3EF2HCwxgZPFMrfwbgrhv",
    "orderId": 13,
    "orderListId": -1,
    "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
    "price": "0.090430",
    "origQty": "0.178622",
    "executedQty": "0.000000",
    "cummulativeQuoteQty": "0.000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "selfTradePreventionMode": "NONE"
  },
  {
    "orderListId": 1929,
    "contingencyType": "OCO",
    "listStatusType": "ALL_DONE",
    "listOrderStatus": "ALL_DONE",
    "listClientOrderId": "2inzWQdDvZLHbbAmAozX2N",
    "transactionTime": 1585230948299,
    "symbol": "BTCUSDT",
    "orders": [
      {
        "symbol": "BTCUSDT",
        "orderId": 20,
        "clientOrderId": "CwOOIPHSmYywx6jZX77TdL"
      },
      {
        "symbol": "BTCUSDT",
        "orderId": 21,
        "clientOrderId": "461cPg51vQjV3zIMOXNz39"
      }
    ],
    "orderReports": [
      {
        "symbol": "BTCUSDT",
        "origClientOrderId": "CwOOIPHSmYywx6jZX77TdL",
        "orderId": 20,
        "orderListId": 1929,
        "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
        "price": "0.668611",
        "origQty": "0.690354",
        "executedQty": "0.000000",
        "cummulativeQuoteQty": "0.000000",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "STOP_LOSS_LIMIT",
        "side": "BUY",
        "stopPrice": "0.378131",
        "icebergQty": "0.017083",
        "selfTradePreventionMode": "NONE"
      },
      {
        "symbol": "BTCUSDT",
        "origClientOrderId": "461cPg51vQjV3zIMOXNz39",
        "orderId": 21,
        "orderListId": 1929,
        "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
        "price": "0.008791",
        "origQty": "0.690354",
        "executedQty": "0.000000",
        "cummulativeQuoteQty": "0.000000",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "LIMIT_MAKER",
        "side": "BUY",
        "icebergQty": "0.639962",
        "selfTradePreventionMode": "NONE"
      }
    ]
  }
]


DELETE /api/v3/openOrders

Cancels all active orders on a symbol.

This includes OCO orders.

Weight(IP):
1

Parameters

Name Type Mandatory Description
symbol STRING YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Matching Engine

Note: The payload sample does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

Query Order (USER_DATA)

Response:

{
  "symbol": "LTCBTC",
  "orderId": 1,
  "orderListId": -1, //Unless OCO, value will be -1
  "clientOrderId": "myOrder1",
  "price": "0.1",
  "origQty": "1.0",
  "executedQty": "0.0",
  "cummulativeQuoteQty": "0.0",
  "status": "NEW",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "BUY",
  "stopPrice": "0.0",
  "icebergQty": "0.0",
  "time": 1499827319559,
  "updateTime": 1499827319559,
  "isWorking": true,
  "workingTime":1499827319559,
  "origQuoteOrderQty": "0.000000",
  "selfTradePreventionMode": "NONE"
}


GET /api/v3/order (HMAC SHA256)

Check an order’s status.

Weight(IP):
2

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO
origClientOrderId STRING NO
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Notes:

  • Either orderId or origClientOrderId must be sent.
  • For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.
  • The payload sample does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

Data Source:
Memory => Database

Cancel an Existing Order and Send a New Order (TRADE)

Response SUCCESS:

//Both the cancel order placement and new order placement succeeded.
{
  "cancelResult": "SUCCESS",
  "newOrderResult": "SUCCESS",
  "cancelResponse": {
    "symbol": "BTCUSDT",
    "origClientOrderId": "DnLo3vTAQcjha43lAZhZ0y",
    "orderId": 9,
    "orderListId": -1,
    "clientOrderId": "osxN3JXAtJvKvCqGeMWMVR",
    "price": "0.01000000",
    "origQty": "0.000100",
    "executedQty": "0.00000000",
    "cummulativeQuoteQty": "0.00000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "SELL",
    "selfTradePreventionMode": "NONE"
  },
  "newOrderResponse": {
    "symbol": "BTCUSDT",
    "orderId": 10,
    "orderListId": -1,
    "clientOrderId": "wOceeeOzNORyLiQfw7jd8S",
    "transactTime": 1652928801803,
    "price": "0.02000000",
    "origQty": "0.040000",
    "executedQty": "0.00000000",
    "cummulativeQuoteQty": "0.00000000",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "workingTime": 1669277163808,
    "fills": [],
    "selfTradePreventionMode": "NONE"
  }
}

Response when Cancel Order Fails with STOP_ON_FAILURE:

{
  "code": -2022,
  "msg": "Order cancel-replace failed.",
  "data": {
    "cancelResult": "FAILURE",
    "newOrderResult": "NOT_ATTEMPTED",
    "cancelResponse": {
      "code": -2011,
      "msg": "Unknown order sent."
    },
    "newOrderResponse": null
  }
}

Response when Cancel Order Succeeds but New Order Placement Fails:

{
  "code": -2021,
  "msg": "Order cancel-replace partially failed.",
  "data": {
    "cancelResult": "SUCCESS",
    "newOrderResult": "FAILURE",
    "cancelResponse": {
      "symbol": "BTCUSDT",
      "origClientOrderId": "86M8erehfExV8z2RC8Zo8k",
      "orderId": 3,
      "orderListId": -1,
      "clientOrderId": "G1kLo6aDv2KGNTFcjfTSFq",
      "price": "0.006123",
      "origQty": "10000.000000",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "SELL",
      "selfTradePreventionMode": "NONE"
    },
    "newOrderResponse": {
      "code": -2010,
      "msg": "Order would immediately match and take."
    }
  }
}

Response when Cancel Order fails with ALLOW_FAILURE:

{
  "code": -2021,
  "msg": "Order cancel-replace partially failed.",
  "data": {
    "cancelResult": "FAILURE",
    "newOrderResult": "SUCCESS",
    "cancelResponse": {
      "code": -2011,
      "msg": "Unknown order sent."
    },
    "newOrderResponse": {
      "symbol": "BTCUSDT",
      "orderId": 11,
      "orderListId": -1,
      "clientOrderId": "pfojJMg6IMNDKuJqDxvoxN",
      "transactTime": 1648540168818
    }
  }
}

Response when both Cancel Order and New Order Placement fail:

{
  "code": -2022,
  "msg": "Order cancel-replace failed.",
  "data": {
    "cancelResult": "FAILURE",
    "newOrderResult": "FAILURE",
    "cancelResponse": {
      "code": -2011,
      "msg": "Unknown order sent."
    },
    "newOrderResponse": {
      "code": -2010,
      "msg": "Order would immediately match and take."
    }
  }
}


POST /api/v3/order/cancelReplace

Cancels an existing order and places a new order on the same symbol.

Filters and Order Count are evaluated before the processing of the cancellation and order placement occurs.

A new order that was not attempted (i.e. when newOrderResult: NOT_ATTEMPTED), will still increase the order count by 1.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
side ENUM YES
type ENUM YES
cancelReplaceMode ENUM YES The allowed values are:

STOP_ON_FAILURE — If the cancel request fails, the new order placement will not be attempted.

ALLOW_FAILURE — new order placement will be attempted even if cancel request fails.

timeInForce ENUM NO
quantity DECIMAL NO
quoteOrderQty DECIMAL NO
price DECIMAL NO
cancelNewClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default.
cancelOrigClientOrderId STRING NO Either the cancelOrigClientOrderId or cancelOrderId must be provided. If both are provided, cancelOrderId takes precedence.
cancelOrderId LONG NO Either the cancelOrigClientOrderId or cancelOrderId must be provided. If both are provided, cancelOrderId takes precedence.
newClientOrderId STRING NO Used to identify the new order.
strategyId INT NO
strategyType INT NO The value cannot be less than 1000000.
stopPrice DECIMAL NO
trailingDelta LONG NO
icebergQty DECIMAL NO
newOrderRespType ENUM NO Allowed values:

ACK, RESULT, FULL

MARKET and LIMIT orders types default to FULL; all other orders default to ACK

selfTradePreventionMode ENUM NO The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.
cancelRestrictions ENUM NO Supported values:
ONLY_NEW — Cancel will succeed if the order status is NEW.
ONLY_PARTIALLY_FILLED — Cancel will succeed if order status is PARTIALLY_FILLED. For more information please refer to Regarding cancelRestrictions
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Similar to POST /api/v3/order, additional mandatory parameters are determined by type.

Response format varies depending on whether the processing of the message succeeded, partially succeeded, or failed.

Data Source:
Matching Engine

Note: The payload sample does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

Current Open Orders (USER_DATA)

Response:

[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "orderListId": -1, //Unless OCO, the value will always be -1
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true,
    "workingTime": 1499827319559,
    "origQuoteOrderQty": "0.000000",
    "selfTradePreventionMode": "NONE"
  }
]


GET /api/v3/openOrders (HMAC SHA256)

Get all open orders on a symbol. Careful when accessing this with no symbol.

Weight(IP):
3 for a single symbol;
40 when the symbol parameter is omitted;

Parameters:

Name Type Mandatory Description
symbol STRING NO
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If the symbol is not sent, orders for all symbols will be returned in an array.

Data Source:
Memory => Database

Note: The payload sample does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

All Orders (USER_DATA)

Response:

[
  {
    "symbol": "LTCBTC",
    "orderId": 1,
    "orderListId": -1, //Unless OCO, the value will always be -1
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true,
    "origQuoteOrderQty": "0.000000",
    "workingTime": 1499827319559,
    "selfTradePreventionMode": "NONE"
  }
]


GET /api/v3/allOrders (HMAC SHA256)

Get all account orders; active, canceled, or filled.

Weight(IP):
10 with symbol

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Notes:

  • If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.
  • For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.
  • If startTime and/or endTime provided, orderId is not required.
  • The payload sample does not show all fields that can appear. Please refer to Conditional fields in Order Responses.

Data Source:
Database

New OCO (TRADE)

Response:

{
  "orderListId": 0,
  "contingencyType": "OCO",
  "listStatusType": "EXEC_STARTED",
  "listOrderStatus": "EXECUTING",
  "listClientOrderId": "JYVpp3F0f5CAG15DhtrqLp",
  "transactionTime": 1563417480525,
  "symbol": "LTCBTC",
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "clientOrderId": "Kk7sqHb9J6mJWTMDVW7Vos"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "clientOrderId": "xTXKaGYd4bluPVp78IVRvl"
    }
  ],
  "orderReports": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "orderListId": 0,
      "clientOrderId": "Kk7sqHb9J6mJWTMDVW7Vos",
      "transactTime": 1563417480525,
      "price": "0.000000",
      "origQty": "0.624363",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "STOP_LOSS",
      "side": "BUY",
      "stopPrice": "0.960664",
      "workingTime": -1,
      "selfTradePreventionMode": "NONE"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "orderListId": 0,
      "clientOrderId": "xTXKaGYd4bluPVp78IVRvl",
      "transactTime": 1563417480525,
      "price": "0.036435",
      "origQty": "0.624363",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "BUY",
      "workingTime": 1563417480525,
      "selfTradePreventionMode": "NONE"
    }
  ]
}


POST /api/v3/order/oco (HMAC SHA256)

Send in a new OCO

Weight(UID): 2
Weight(IP): 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
listClientOrderId STRING NO A unique Id for the entire orderList
side ENUM YES
quantity DECIMAL YES
limitClientOrderId STRING NO A unique Id for the limit order
limitStrategyId INT NO
limitStrategyType INT NO The value cannot be less than 1000000.
price DECIMAL YES
limitIcebergQty DECIMAL NO
trailingDelta LONG NO
stopClientOrderId STRING NO A unique Id for the stop loss/stop loss limit leg
stopPrice DECIMAL YES
stopStrategyId INT NO
stopStrategyType INT NO The value cannot be less than 1000000.
stopLimitPrice DECIMAL NO If provided, stopLimitTimeInForce is required.
stopIcebergQty DECIMAL NO
stopLimitTimeInForce ENUM NO Valid values are GTC/FOK/IOC
newOrderRespType ENUM NO Set the response JSON.
selfTradePreventionMode ENUM NO The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Other Info:

  • Price Restrictions:
    • SELL: Limit Price > Last Price > Stop Price
    • BUY: Limit Price < Last Price < Stop Price
  • Quantity Restrictions:
    • Both legs must have the same quantity
    • ICEBERG quantities however do not have to be the same.
  • Order Rate Limit
    • OCO counts as 2 orders against the order rate limit.

Data Source:
Matching Engine

Cancel OCO (TRADE)

Response:

{
  "orderListId": 0,
  "contingencyType": "OCO",
  "listStatusType": "ALL_DONE",
  "listOrderStatus": "ALL_DONE",
  "listClientOrderId": "C3wyj4WVEktd7u9aVBRXcN",
  "transactionTime": 1574040868128,
  "symbol": "LTCBTC",
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "clientOrderId": "pO9ufTiFGg3nw2fOdgeOXa"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "clientOrderId": "TXOvglzXuaubXAaENpaRCB"
    }
  ],
  "orderReports": [
    {
      "symbol": "LTCBTC",
      "origClientOrderId": "pO9ufTiFGg3nw2fOdgeOXa",
      "orderId": 2,
      "orderListId": 0,
      "clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
      "price": "1.00000000",
      "origQty": "10.00000000",
      "executedQty": "0.00000000",
      "cummulativeQuoteQty": "0.00000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "STOP_LOSS_LIMIT",
      "side": "SELL",
      "stopPrice": "1.00000000",
      "selfTradePreventionMode": "NONE"
    },
    {
      "symbol": "LTCBTC",
      "origClientOrderId": "TXOvglzXuaubXAaENpaRCB",
      "orderId": 3,
      "orderListId": 0,
      "clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
      "price": "3.00000000",
      "origQty": "10.00000000",
      "executedQty": "0.00000000",
      "cummulativeQuoteQty": "0.00000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "SELL",
      "selfTradePreventionMode": "NONE"
    }
  ]
}


DELETE /api/v3/orderList (HMAC SHA256)

Cancel an entire Order List.

Weight(IP): 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderListId LONG NO Either orderListId or listClientOrderId must be provided
listClientOrderId STRING NO Either orderListId or listClientOrderId must be provided
newClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Additional notes:

  • Canceling an individual leg will cancel the entire OCO
  • If both orderListId and listClientOrderID are provided, orderId takes precedence.

Data Source:
Matching Engine

Query OCO (USER_DATA)

Response:

{
  "orderListId": 27,
  "contingencyType": "OCO",
  "listStatusType": "EXEC_STARTED",
  "listOrderStatus": "EXECUTING",
  "listClientOrderId": "h2USkA5YQpaXHPIrkd96xE",
  "transactionTime": 1565245656253,
  "symbol": "LTCBTC",
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 4,
      "clientOrderId": "qD1gy3kc3Gx0rihm9Y3xwS"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 5,
      "clientOrderId": "ARzZ9I00CPM8i3NhmU9Ega"
    }
  ]
}


GET /api/v3/orderList (HMAC SHA256)

Retrieves a specific OCO based on provided optional parameters

Weight(IP): 2

Parameters:

Name Type Mandatory Description
orderListId LONG NO Either orderListId or origClientOrderId must be provided
origClientOrderId STRING NO Either orderListId or origClientOrderId must be provided
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Database

Query all OCO (USER_DATA)

Response:

[
  {
    "orderListId": 29,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "amEEAXryFzFwYF1FeRpUoZ",
    "transactionTime": 1565245913483,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 4,
        "clientOrderId": "oD7aesZqjEGlZrbtRpy5zB"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 5,
        "clientOrderId": "Jr1h6xirOxgeJOUuYQS7V3"
      }
    ]
  },
  {
    "orderListId": 28,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "hG7hFNxJV6cZy3Ze4AUT4d",
    "transactionTime": 1565245913407,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 2,
        "clientOrderId": "j6lFOfbmFMRjTYA7rRJ0LP"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 3,
        "clientOrderId": "z0KCjOdditiLS5ekAFtK81"
      }
    ]
  }
]


GET /api/v3/allOrderList (HMAC SHA256)

Retrieves all OCO based on provided optional parameters

Weight(IP): 10

Parameters

Name Type Mandatory Description
fromId LONG NO If supplied, neither startTime or endTime can be provided
startTime LONG NO
endTime LONG NO
limit INT NO Default Value: 500; Max Value: 1000
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Database

Query Open OCO (USER_DATA)

Response:

[
  {
    "orderListId": 31,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "wuB13fmulKj3YjdqWEcsnp",
    "transactionTime": 1565246080644,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 4,
        "clientOrderId": "r3EH2N76dHfLoSZWIUw1bT"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 5,
        "clientOrderId": "Cv1SnyPD3qhqpbjpYEHbd2"
      }
    ]
  }
]


GET /api/v3/openOrderList (HMAC SHA256)

Weight(IP): 3

Parameters

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source: Database

Account Information (USER_DATA)

Response:

{
  "makerCommission": 15,
  "takerCommission": 15,
  "buyerCommission": 0,
  "sellerCommission": 0,
  "commissionRates": {
    "maker": "0.00150000",
    "taker": "0.00150000",
    "buyer": "0.00000000",
    "seller": "0.00000000"
  },
  "canTrade": true,
  "canWithdraw": true,
  "canDeposit": true,
  "brokered": false,
  "requireSelfTradePrevention": false,
  "updateTime": 123456789,
  "accountType": "SPOT",
  "balances": [
    {
      "asset": "BTC",
      "free": "4723846.89208129",
      "locked": "0.00000000"
    },
    {
      "asset": "LTC",
      "free": "4763368.68006011",
      "locked": "0.00000000"
    }
  ],
  "permissions": [
    "SPOT"
  ]
}


GET /api/v3/account (HMAC SHA256)

Get current account information.

Weight(IP):
10

Parameters:

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source: Memory => Database

Account Trade List (USER_DATA)

Response:

[
  {
    "symbol": "BNBBTC",
    "id": 28457,
    "orderId": 100234,
    "orderListId": -1, //Unless OCO, the value will always be -1
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "commission": "10.10000000",
    "commissionAsset": "BNB",
    "time": 1499865549590,
    "isBuyer": true,
    "isMaker": false,
    "isBestMatch": true
  }
]


GET /api/v3/myTrades (HMAC SHA256)

Get trades for a specific account and symbol.

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING YES
orderId LONG NO This can only be used in combination with symbol.
startTime LONG NO
endTime LONG NO
fromId LONG NO TradeId to fetch from. Default gets most recent trades.
limit INT NO Default 500; max 1000.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Notes:

  • If fromId is set, it will get id >= that fromId.
    Otherwise most recent trades are returned.
  • The time between startTime and endTime can’t be longer than 24 hours.
  • These are the supported combinations of all parameters:
    • symbol
    • symbol + orderId
    • symbol + startTime
    • symbol + endTime
    • symbol + fromId
    • symbol + startTime + endTime
    • symbol+ orderId + fromId

Data Source:
Memory => Database

Query Current Order Count Usage (TRADE)

Response:

[

  {
    "rateLimitType": "ORDERS",
    "interval": "SECOND",
    "intervalNum": 10,
    "limit": 10000,
    "count": 0
  },
  {
    "rateLimitType": "ORDERS",
    "interval": "DAY",
    "intervalNum": 1,
    "limit": 20000,
    "count": 0
  }
]


GET /api/v3/rateLimit/order

Displays the user’s current order count usage for all intervals.

Weight(IP):
20

Parameters:

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Data Source:
Memory

Query Prevented Matches (USER_DATA)

Response:

[
  {
    "symbol": "BTCUSDT",
    "preventedMatchId": 1,
    "takerOrderId": 5,
    "makerOrderId": 3,
    "tradeGroupId": 1,
    "selfTradePreventionMode": "EXPIRE_MAKER",
    "price": "1.100000",
    "makerPreventedQuantity": "1.300000",
    "transactTime": 1669101687094
  }
]


GET /api/v3/myPreventedMatches

Displays the list of orders that were expired because of STP trigger.

These are the combinations supported:

  • symbol + preventedMatchId
  • symbol + orderId
  • symbol + orderId + fromPreventedMatchId (limit will default to 500)
  • symbol + orderId + fromPreventedMatchId + limit

Parameters:

Name Type Mandatory Description
symbol STRING YES
preventedMatchId LONG NO
orderId LONG NO
fromPreventedMatchId LONG NO
limit INT NO Default: 500; Max: 1000
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Weight(IP)

Case Weight
If symbol is invalid 1
Querying by preventedMatchId 1
Querying by orderId 10

Data Source:

Database

Margin Account/Trade

Cross Margin Account Transfer (MARGIN)

Response:

{
    //transaction id
    "tranId": 100000001
}


POST /sapi/v1/margin/transfer (HMAC SHA256)

Execute transfer between spot account and cross margin account.

Weight(IP):
600

Parameters:

Name Type Mandatory Description
asset STRING YES The asset being transferred, e.g., BTC
amount DECIMAL YES The amount to be transferred
type INT YES 1: transfer from main account to cross margin account 2: transfer from cross margin account to main account
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Margin Account Borrow (MARGIN)

Response:

{
    //transaction id
    "tranId": 100000001
}


POST /sapi/v1/margin/loan (HMAC SHA256)

Apply for a loan.

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
asset STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
symbol STRING NO isolated symbol
amount DECIMAL YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If «isIsolated» = «TRUE», «symbol» must be sent
  • «isIsolated» = «FALSE» for crossed margin loan

Margin Account Repay (MARGIN)

Response:

{
    //transaction id
    "tranId": 100000001
}


POST /sapi/v1/margin/repay (HMAC SHA256)

Repay loan for margin account.

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
asset STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
symbol STRING NO isolated symbol
amount DECIMAL YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If «isIsolated» = «TRUE», «symbol» must be sent
  • «isIsolated» = «FALSE» for crossed margin repay

Query Margin Asset (MARKET_DATA)

Response:

{
    "assetFullName": "Binance Coin",
    "assetName": "BNB",
    "isBorrowable": false,
    "isMortgageable": true,
    "userMinBorrow": "0.00000000",
    "userMinRepay": "0.00000000"
}


GET /sapi/v1/margin/asset

Weight(IP):
10

Parameters:

Name Type Mandatory Description
asset STRING YES

Query Cross Margin Pair (MARKET_DATA)

Response:

{
   "id":323355778339572400,
   "symbol":"BTCUSDT",
   "base":"BTC",
   "quote":"USDT",
   "isMarginTrade":true,
   "isBuyAllowed":true,
   "isSellAllowed":true
}


GET /sapi/v1/margin/pair

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING YES

Get All Margin Assets (MARKET_DATA)

Response:

  [
      {
          "assetFullName": "USD coin",
          "assetName": "USDC",
          "isBorrowable": true,
          "isMortgageable": true,
          "userMinBorrow": "0.00000000",
          "userMinRepay": "0.00000000"
      },
      {
          "assetFullName": "BNB-coin",
          "assetName": "BNB",
          "isBorrowable": true,
          "isMortgageable": true,
          "userMinBorrow": "1.00000000",
          "userMinRepay": "0.00000000"
      },
      {
          "assetFullName": "Tether",
          "assetName": "USDT",
          "isBorrowable": true,
          "isMortgageable": true,
          "userMinBorrow": "1.00000000",
          "userMinRepay": "0.00000000"
      },
      {
          "assetFullName": "etherum",
          "assetName": "ETH",
          "isBorrowable": true,
          "isMortgageable": true,
          "userMinBorrow": "0.00000000",
          "userMinRepay": "0.00000000"
      },
      {
          "assetFullName": "Bitcoin",
          "assetName": "BTC",
          "isBorrowable": true,
          "isMortgageable": true,
          "userMinBorrow": "0.00000000",
          "userMinRepay": "0.00000000"
      }
  ]


GET /sapi/v1/margin/allAssets

Weight(IP):
1

Parameters:

None

Get All Cross Margin Pairs (MARKET_DATA)

Response:

[
    {
        "base": "BNB",
        "id": 351637150141315861,
        "isBuyAllowed": true,
        "isMarginTrade": true,
        "isSellAllowed": true,
        "quote": "BTC",
        "symbol": "BNBBTC"
    },
    {
        "base": "TRX",
        "id": 351637923235429141,
        "isBuyAllowed": true,
        "isMarginTrade": true,
        "isSellAllowed": true,
        "quote": "BTC",
        "symbol": "TRXBTC"
    },
    {
        "base": "XRP",
        "id": 351638112213990165,
        "isBuyAllowed": true,
        "isMarginTrade": true,
        "isSellAllowed": true,
        "quote": "BTC",
        "symbol": "XRPBTC"
    },
    {
        "base": "ETH",
        "id": 351638524530850581,
        "isBuyAllowed": true,
        "isMarginTrade": true,
        "isSellAllowed": true,
        "quote": "BTC",
        "symbol": "ETHBTC"
    },
    {
        "base": "BNB",
        "id": 376870400832855109,
        "isBuyAllowed": true,
        "isMarginTrade": true,
        "isSellAllowed": true,
        "quote": "USDT",
        "symbol": "BNBUSDT"
  }
]


GET /sapi/v1/margin/allPairs

Weight(IP):
1

Parameters:

None

Query Margin PriceIndex (MARKET_DATA)

Response:

{
   "calcTime": 1562046418000,
   "price": "0.00333930",
   "symbol": "BNBBTC"
}


GET /sapi/v1/margin/priceIndex

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING YES

Margin Account New Order (TRADE)

Response ACK:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "isIsolated": true,       // if isolated margin
  "transactTime": 1507725176595
}

Response RESULT:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "1.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "isIsolated": true,       // if isolated margin
  "side": "SELL"
}

Response FULL:

{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "1.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "marginBuyBorrowAmount": 5,       // will not return if no margin trade happens
  "marginBuyBorrowAsset": "BTC",    // will not return if no margin trade happens
  "isIsolated": true,       // if isolated margin
  "fills": [
    {
      "price": "4000.00000000",
      "qty": "1.00000000",
      "commission": "4.00000000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3999.00000000",
      "qty": "5.00000000",
      "commission": "19.99500000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3998.00000000",
      "qty": "2.00000000",
      "commission": "7.99600000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3997.00000000",
      "qty": "1.00000000",
      "commission": "3.99700000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3995.00000000",
      "qty": "1.00000000",
      "commission": "3.99500000",
      "commissionAsset": "USDT"
    }
  ]
}


POST /sapi/v1/margin/order (HMAC SHA256)

Post a new order for margin account.

Weight(UID):
6

Parameters:

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
side ENUM YES BUY

SELL

type ENUM YES
quantity DECIMAL NO
quoteOrderQty DECIMAL NO
price DECIMAL NO
stopPrice DECIMAL NO Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent.
icebergQty DECIMAL NO Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
newOrderRespType ENUM NO Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
sideEffectType ENUM NO NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY; default NO_SIDE_EFFECT.
timeInForce ENUM NO GTC,IOC,FOK
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Margin Account Cancel Order (TRADE)

Response:

{
  "symbol": "LTCBTC",
  "isIsolated": true,       // if isolated margin
  "orderId": "28",
  "origClientOrderId": "myOrder1",
  "clientOrderId": "cancelMyOrder1",
  "price": "1.00000000",
  "origQty": "10.00000000",
  "executedQty": "8.00000000",
  "cummulativeQuoteQty": "8.00000000",
  "status": "CANCELED",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "SELL"
}


DELETE /sapi/v1/margin/order (HMAC SHA256)

Cancel an active order for margin account.

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
orderId LONG NO
origClientOrderId STRING NO
newClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • Either orderId or origClientOrderId must be sent.

Margin Account Cancel all Open Orders on a Symbol (TRADE)

Response:

[
  {
    "symbol": "BTCUSDT",
    "isIsolated": true,       // if isolated margin
    "origClientOrderId": "E6APeyTJvkMvLMYMqu1KQ4",
    "orderId": 11,
    "orderListId": -1,
    "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
    "price": "0.089853",
    "origQty": "0.178622",
    "executedQty": "0.000000",
    "cummulativeQuoteQty": "0.000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY"
  },
  {
    "symbol": "BTCUSDT",
    "isIsolated": false,       // if isolated margin
    "origClientOrderId": "A3EF2HCwxgZPFMrfwbgrhv",
    "orderId": 13,
    "orderListId": -1,
    "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
    "price": "0.090430",
    "origQty": "0.178622",
    "executedQty": "0.000000",
    "cummulativeQuoteQty": "0.000000",
    "status": "CANCELED",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY"
  },
  {
    "orderListId": 1929,
    "contingencyType": "OCO",
    "listStatusType": "ALL_DONE",
    "listOrderStatus": "ALL_DONE",
    "listClientOrderId": "2inzWQdDvZLHbbAmAozX2N",
    "transactionTime": 1585230948299,
    "symbol": "BTCUSDT",
    "isIsolated": true,       // if isolated margin
    "orders": [
      {
        "symbol": "BTCUSDT",
        "orderId": 20,
        "clientOrderId": "CwOOIPHSmYywx6jZX77TdL"
      },
      {
        "symbol": "BTCUSDT",
        "orderId": 21,
        "clientOrderId": "461cPg51vQjV3zIMOXNz39"
      }
    ],
    "orderReports": [
      {
        "symbol": "BTCUSDT",
        "origClientOrderId": "CwOOIPHSmYywx6jZX77TdL",
        "orderId": 20,
        "orderListId": 1929,
        "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
        "price": "0.668611",
        "origQty": "0.690354",
        "executedQty": "0.000000",
        "cummulativeQuoteQty": "0.000000",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "STOP_LOSS_LIMIT",
        "side": "BUY",
        "stopPrice": "0.378131",
        "icebergQty": "0.017083"
      },
      {
        "symbol": "BTCUSDT",
        "origClientOrderId": "461cPg51vQjV3zIMOXNz39",
        "orderId": 21,
        "orderListId": 1929,
        "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
        "price": "0.008791",
        "origQty": "0.690354",
        "executedQty": "0.000000",
        "cummulativeQuoteQty": "0.000000",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "LIMIT_MAKER",
        "side": "BUY",
        "icebergQty": "0.639962"
      }
    ]
  }
]


DELETE /sapi/v1/margin/openOrders (HMAC SHA256)

Cancels all active orders on a symbol for margin account.

This includes OCO orders.

Weight(IP):
1

Parameters

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Get Cross Margin Transfer History (USER_DATA)

Response:

{
  "rows": [
    {
      "amount": "0.10000000",
      "asset": "BNB",
      "status": "CONFIRMED",
      "timestamp": 1566898617,
      "txId": 5240372201,
      "type": "ROLL_IN"
    },
    {
      "amount": "5.00000000",
      "asset": "USDT",
      "status": "CONFIRMED",
      "timestamp": 1566888436,
      "txId": 5239810406,
      "type": "ROLL_OUT"
    },
    {
      "amount": "1.00000000",
      "asset": "EOS",
      "status": "CONFIRMED",
      "timestamp": 1566888403,
      "txId": 5239808703,
      "type": "ROLL_IN"
    }
  ],
  "total": 3
}


GET /sapi/v1/margin/transfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
type STRING NO Transfer Type: ROLL_IN, ROLL_OUT
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10 Max:100
archived STRING NO Default: false. Set to true for archived data from 6 months ago
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • Response in descending order
  • The max interval between startTime and endTime is 30 days.
  • Returns data for last 7 days by default
  • Set archived to true to query data from 6 months ago

Query Loan Record (USER_DATA)

Response:

{
  "rows": [
    {
        "isolatedSymbol": "BNBUSDT", // isolated symbol, will not be returned for crossed margin
        "txId": 12807067523,
        "asset": "BNB",
        "principal": "0.84624403",
        "timestamp": 1555056425000,
        "status": "CONFIRMED"   //one of PENDING (pending execution), CONFIRMED (successfully loaned), FAILED (execution failed, nothing happened to your account);
    }
  ],
  "total": 1
}


GET /sapi/v1/margin/loan (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
asset STRING YES
isolatedSymbol STRING NO isolated symbol
txId LONG NO the tranId in POST /sapi/v1/margin/loan
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10 Max:100
archived STRING NO Default: false. Set to true for archived data from 6 months ago
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • txId or startTime must be sent. txId takes precedence.
  • Response in descending order
  • If isolatedSymbol is not sent, crossed margin data will be returned
  • The max interval between startTime and endTime is 30 days.
  • If startTimeand endTime not sent, return records of the last 7 days by default
  • Set archived to true to query data from 6 months ago

Query Repay Record (USER_DATA)

Response:

{
     "rows": [
         {
                "isolatedSymbol": "BNBUSDT", // isolated symbol, will not be returned for crossed margin
                "amount": "14.00000000",   //Total amount repaid
                "asset": "BNB",   
                "interest": "0.01866667",    //Interest repaid
                "principal": "13.98133333",   //Principal repaid
                "status": "CONFIRMED",   //one of PENDING (pending execution), CONFIRMED (successfully execution), FAILED (execution failed, nothing happened to your account)
                "timestamp": 1563438204000,
                "txId": 2970933056
         }
     ],
     "total": 1
}


GET /sapi/v1/margin/repay (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
asset STRING YES
isolatedSymbol STRING NO isolated symbol
txId LONG NO return of /sapi/v1/margin/repay
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10 Max:100
archived STRING NO Default: false. Set to true for archived data from 6 months ago
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • txId or startTime must be sent. txId takes precedence.
  • Response in descending order
  • If isolatedSymbol is not sent, crossed margin data will be returned
  • The max interval between startTime and endTime is 30 days.
  • If startTimeand endTime not sent, return records of the last 7 days by default
  • Set archived to true to query data from 6 months ago

Get Interest History (USER_DATA)

Response:

{
  "rows": [
    {            
      "txId": 1352286576452864727,           
      "interestAccuredTime": 1672160400000,            
      "asset": "USDT", 
      "rawAsset": USDT,  // will not be returned for isolated margin           
      "principal": "45.3313",            
      "interest": "0.00024995",            
      "interestRate": "0.00013233",            
      "type": "ON_BORROW",           
      "isolatedSymbol": "BNBUSDT"  // isolated symbol, will not be returned for crossed margin      
    }
  ],
  "total": 1
}


GET /sapi/v1/margin/interestHistory (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
isolatedSymbol STRING NO isolated symbol
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10 Max:100
archived STRING NO Default: false. Set to true for archived data from 6 months ago
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • Response in descending order
  • If isolatedSymbol is not sent, crossed margin data will be returned
  • The max interval between startTime and endTime is 30 days.
  • If startTimeand endTime not sent, return records of the last 7 days by default
  • Set archived to true to query data from 6 months ago
  • type in response has 4 enums:
    • PERIODIC interest charged per hour
    • ON_BORROW first interest charged on borrow
    • PERIODIC_CONVERTED interest charged per hour converted into BNB
    • ON_BORROW_CONVERTED first interest charged on borrow converted into BNB
    • PORTFOLIO interest charged daily on the portfolio margin negative balance

Get Force Liquidation Record (USER_DATA)

Response:

  {
      "rows": [
          {
              "avgPrice": "0.00388359",
              "executedQty": "31.39000000",
              "orderId": 180015097,
              "price": "0.00388110",
              "qty": "31.39000000",
              "side": "SELL",
              "symbol": "BNBBTC",
              "timeInForce": "GTC",
              "isIsolated": true,
              "updatedTime": 1558941374745
          }
      ],
      "total": 1
  }


GET /sapi/v1/margin/forceLiquidationRec (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
startTime LONG NO
endTime LONG NO
isolatedSymbol STRING NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10 Max:100
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • Response in descending order

Query Cross Margin Account Details (USER_DATA)

Response:

{
      "borrowEnabled": true,
      "marginLevel": "11.64405625",
      "totalAssetOfBtc": "6.82728457",
      "totalLiabilityOfBtc": "0.58633215",
      "totalNetAssetOfBtc": "6.24095242",
      "tradeEnabled": true,
      "transferEnabled": true,
      "userAssets": [
          {
              "asset": "BTC",
              "borrowed": "0.00000000",
              "free": "0.00499500",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00499500"
          },
          {
              "asset": "BNB",
              "borrowed": "201.66666672",
              "free": "2346.50000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "2144.83333328"
          },
          {
              "asset": "ETH",
              "borrowed": "0.00000000",
              "free": "0.00000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00000000"
          },
          {
              "asset": "USDT",
              "borrowed": "0.00000000",
              "free": "0.00000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00000000"
          }
      ]
}


GET /sapi/v1/margin/account (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Query Margin Account’s Order (USER_DATA)

Response:

{
   "clientOrderId": "ZwfQzuDIGpceVhKW5DvCmO",
   "cummulativeQuoteQty": "0.00000000",
   "executedQty": "0.00000000",
   "icebergQty": "0.00000000",
   "isWorking": true,
   "orderId": 213205622,
   "origQty": "0.30000000",
   "price": "0.00493630",
   "side": "SELL",
   "status": "NEW",
   "stopPrice": "0.00000000",
   "symbol": "BNBBTC",
   "isIsolated": true,
   "time": 1562133008725,
   "timeInForce": "GTC",
   "type": "LIMIT",
   "updateTime": 1562133008725
}


GET /sapi/v1/margin/order (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
orderId LONG NO
origClientOrderId STRING NO
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • Either orderId or origClientOrderId must be sent.
  • For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.

Query Margin Account’s Open Orders (USER_DATA)

Response:

[
   {
       "clientOrderId": "qhcZw71gAkCCTv0t0k8LUK",
       "cummulativeQuoteQty": "0.00000000",
       "executedQty": "0.00000000",
       "icebergQty": "0.00000000",
       "isWorking": true,
       "orderId": 211842552,
       "origQty": "0.30000000",
       "price": "0.00475010",
       "side": "SELL",
       "status": "NEW",
       "stopPrice": "0.00000000",
       "symbol": "BNBBTC",
       "isIsolated": true,
       "time": 1562040170089,
       "timeInForce": "GTC",
       "type": "LIMIT",
       "updateTime": 1562040170089
    }
]


GET /sapi/v1/margin/openOrders (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING NO
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If the symbol is not sent, orders for all symbols will be returned in an array.
  • When all symbols are returned, the number of requests counted against the rate limiter is equal to the number of symbols currently trading on the exchange.
  • If isIsolated =»TRUE», symbol must be sent.

Query Margin Account’s All Orders (USER_DATA)

Response:

[
      {
          "clientOrderId": "D2KDy4DIeS56PvkM13f8cP",
          "cummulativeQuoteQty": "0.00000000",
          "executedQty": "0.00000000",
          "icebergQty": "0.00000000",
          "isWorking": false,
          "orderId": 41295,
          "origQty": "5.31000000",
          "price": "0.22500000",
          "side": "SELL",
          "status": "CANCELED",
          "stopPrice": "0.18000000",
          "symbol": "BNBBTC",
          "isIsolated": false,
          "time": 1565769338806,
          "timeInForce": "GTC",
          "type": "TAKE_PROFIT_LIMIT",
          "updateTime": 1565769342148
      },
      {
          "clientOrderId": "gXYtqhcEAs2Rn9SUD9nRKx",
          "cummulativeQuoteQty": "0.00000000",
          "executedQty": "0.00000000",
          "icebergQty": "1.00000000",
          "isWorking": true,
          "orderId": 41296,
          "origQty": "6.65000000",
          "price": "0.18000000",
          "side": "SELL",
          "status": "CANCELED",
          "stopPrice": "0.00000000",
          "symbol": "BNBBTC",
          "isIsolated": false,
          "time": 1565769348687,
          "timeInForce": "GTC",
          "type": "LIMIT",
          "updateTime": 1565769352226
      },
      {
          "clientOrderId": "duDq1BqohhcMmdMs9FSuDy",
          "cummulativeQuoteQty": "0.39450000",
          "executedQty": "2.63000000",
          "icebergQty": "0.00000000",
          "isWorking": true,
          "orderId": 41297,
          "origQty": "2.63000000",
          "price": "0.00000000",
          "side": "SELL",
          "status": "FILLED",
          "stopPrice": "0.00000000",
          "symbol": "BNBBTC",
          "isIsolated": false,
          "time": 1565769358139,
          "timeInForce": "GTC",
          "type": "MARKET",
          "updateTime": 1565769358139
      }

]


GET /sapi/v1/margin/allOrders (HMAC SHA256)

Weight(IP):
200

Request Limit
60times/min per IP

Parameters:

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
orderId LONG NO
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 500.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.
  • For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.

Margin Account New OCO (TRADE)

Response:

{
  "orderListId": 0,
  "contingencyType": "OCO",
  "listStatusType": "EXEC_STARTED",
  "listOrderStatus": "EXECUTING",
  "listClientOrderId": "JYVpp3F0f5CAG15DhtrqLp",
  "transactionTime": 1563417480525,
  "symbol": "LTCBTC",
  "marginBuyBorrowAmount": "5",       // will not return if no margin trade happens
  "marginBuyBorrowAsset": "BTC",    // will not return if no margin trade happens
  "isIsolated": false,       // if isolated margin
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "clientOrderId": "Kk7sqHb9J6mJWTMDVW7Vos"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "clientOrderId": "xTXKaGYd4bluPVp78IVRvl"
    }
  ],
  "orderReports": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "orderListId": 0,
      "clientOrderId": "Kk7sqHb9J6mJWTMDVW7Vos",
      "transactTime": 1563417480525,
      "price": "0.000000",
      "origQty": "0.624363",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "STOP_LOSS",
      "side": "BUY",
      "stopPrice": "0.960664"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "orderListId": 0,
      "clientOrderId": "xTXKaGYd4bluPVp78IVRvl",
      "transactTime": 1563417480525,
      "price": "0.036435",
      "origQty": "0.624363",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "BUY"
    }
  ]
}


POST /sapi/v1/margin/order/oco (HMAC SHA256)

Send in a new OCO for a margin account

Weight(UID): 6

Parameters:

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
listClientOrderId STRING NO A unique Id for the entire orderList
side ENUM YES
quantity DECIMAL YES
limitClientOrderId STRING NO A unique Id for the limit order
price DECIMAL YES
limitIcebergQty DECIMAL NO
stopClientOrderId STRING NO A unique Id for the stop loss/stop loss limit leg
stopPrice DECIMAL YES
stopLimitPrice DECIMAL NO If provided, stopLimitTimeInForce is required.
stopIcebergQty DECIMAL NO
stopLimitTimeInForce ENUM NO Valid values are GTC/FOK/IOC
newOrderRespType ENUM NO Set the response JSON.
sideEffectType ENUM NO NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY; default NO_SIDE_EFFECT.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Other Info:

  • Price Restrictions:
    • SELL: Limit Price > Last Price > Stop Price
    • BUY: Limit Price < Last Price < Stop Price
  • Quantity Restrictions:
    • Both legs must have the same quantity
    • ICEBERG quantities however do not have to be the same.
  • Order Rate Limit
    • OCO counts as 2 orders against the order rate limit.

Margin Account Cancel OCO (TRADE)

Response:

{
  "orderListId": 0,
  "contingencyType": "OCO",
  "listStatusType": "ALL_DONE",
  "listOrderStatus": "ALL_DONE",
  "listClientOrderId": "C3wyj4WVEktd7u9aVBRXcN",
  "transactionTime": 1574040868128,
  "symbol": "LTCBTC",
  "isIsolated": false,       // if isolated margin
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 2,
      "clientOrderId": "pO9ufTiFGg3nw2fOdgeOXa"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 3,
      "clientOrderId": "TXOvglzXuaubXAaENpaRCB"
    }
  ],
  "orderReports": [
    {
      "symbol": "LTCBTC",
      "origClientOrderId": "pO9ufTiFGg3nw2fOdgeOXa",
      "orderId": 2,
      "orderListId": 0,
      "clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
      "price": "1.00000000",
      "origQty": "10.00000000",
      "executedQty": "0.00000000",
      "cummulativeQuoteQty": "0.00000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "STOP_LOSS_LIMIT",
      "side": "SELL",
      "stopPrice": "1.00000000"
    },
    {
      "symbol": "LTCBTC",
      "origClientOrderId": "TXOvglzXuaubXAaENpaRCB",
      "orderId": 3,
      "orderListId": 0,
      "clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
      "price": "3.00000000",
      "origQty": "10.00000000",
      "executedQty": "0.00000000",
      "cummulativeQuoteQty": "0.00000000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "SELL"
    }
  ]
}


DELETE /sapi/v1/margin/orderList (HMAC SHA256)

Cancel an entire Order List for a margin account.

Weight(UID): 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
orderListId LONG NO Either orderListId or listClientOrderId must be provided
listClientOrderId STRING NO Either orderListId or listClientOrderId must be provided
newClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Additional notes:

  • Canceling an individual leg will cancel the entire OCO

Query Margin Account’s OCO (USER_DATA)

Response:

{
  "orderListId": 27,
  "contingencyType": "OCO",
  "listStatusType": "EXEC_STARTED",
  "listOrderStatus": "EXECUTING",
  "listClientOrderId": "h2USkA5YQpaXHPIrkd96xE",
  "transactionTime": 1565245656253,
  "symbol": "LTCBTC",
  "isIsolated": false,       // if isolated margin
  "orders": [
    {
      "symbol": "LTCBTC",
      "orderId": 4,
      "clientOrderId": "qD1gy3kc3Gx0rihm9Y3xwS"
    },
    {
      "symbol": "LTCBTC",
      "orderId": 5,
      "clientOrderId": "ARzZ9I00CPM8i3NhmU9Ega"
    }
  ]
}


GET /sapi/v1/margin/orderList (HMAC SHA256)

Retrieves a specific OCO based on provided optional parameters

Weight(IP): 10

Parameters:

Name Type Mandatory Description
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
symbol STRING NO mandatory for isolated margin, not supported for cross margin
orderListId LONG NO Either orderListId or origClientOrderId must be provided
origClientOrderId STRING NO Either orderListId or origClientOrderId must be provided
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Query Margin Account’s all OCO (USER_DATA)

Response:

[
  {
    "orderListId": 29,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "amEEAXryFzFwYF1FeRpUoZ",
    "transactionTime": 1565245913483,
    "symbol": "LTCBTC",
    "isIsolated": true,       // if isolated margin
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 4,
        "clientOrderId": "oD7aesZqjEGlZrbtRpy5zB"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 5,
        "clientOrderId": "Jr1h6xirOxgeJOUuYQS7V3"
      }
    ]
  },
  {
    "orderListId": 28,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "hG7hFNxJV6cZy3Ze4AUT4d",
    "transactionTime": 1565245913407,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 2,
        "clientOrderId": "j6lFOfbmFMRjTYA7rRJ0LP"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 3,
        "clientOrderId": "z0KCjOdditiLS5ekAFtK81"
      }
    ]
  }
]


GET /sapi/v1/margin/allOrderList (HMAC SHA256)

Retrieves all OCO for a specific margin account based on provided optional parameters

Weight(IP): 200

Parameters

Name Type Mandatory Description
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
symbol STRING NO mandatory for isolated margin, not supported for cross margin
fromId LONG NO If supplied, neither startTime or endTime can be provided
startTime LONG NO
endTime LONG NO
limit INT NO Default Value: 500; Max Value: 1000
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Query Margin Account’s Open OCO (USER_DATA)

Response:

[
  {
    "orderListId": 31,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "wuB13fmulKj3YjdqWEcsnp",
    "transactionTime": 1565246080644,
    "symbol": "LTCBTC",
    "isIsolated": false,       // if isolated margin
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 4,
        "clientOrderId": "r3EH2N76dHfLoSZWIUw1bT"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 5,
        "clientOrderId": "Cv1SnyPD3qhqpbjpYEHbd2"
      }
    ]
  }
]


GET /sapi/v1/margin/openOrderList (HMAC SHA256)

Weight(IP): 10

Parameters

Name Type Mandatory Description
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
symbol STRING NO mandatory for isolated margin, not supported for cross margin
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Query Margin Account’s Trade List (USER_DATA)

Response:

[
    {
        "commission": "0.00006000",
        "commissionAsset": "BTC",
        "id": 34,
        "isBestMatch": true,
        "isBuyer": false,
        "isMaker": false,
        "orderId": 39324,
        "price": "0.02000000",
        "qty": "3.00000000",
        "symbol": "BNBBTC",
        "isIsolated": false,
        "time": 1561973357171
    }
]


GET /sapi/v1/margin/myTrades (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
orderId LONG NO
startTime LONG NO
endTime LONG NO
fromId LONG NO TradeId to fetch from. Default gets most recent trades.
limit INT NO Default 500; max 1000.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If fromId is set, it will get trades >= that fromId. Otherwise most recent trades are returned.

Query Max Borrow (USER_DATA)

Response:

{
  "amount": "1.69248805", // account's currently max borrowable amount with sufficient system availability
  "borrowLimit": "60" // max borrowable amount limited by the account level
}


GET /sapi/v1/margin/maxBorrowable (HMAC SHA256)

Weight(IP):
50

Parameters:

Name Type Mandatory Description
asset STRING YES
isolatedSymbol STRING NO isolated symbol
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If isolatedSymbol is not sent, crossed margin data will be sent.
  • borrowLimit is also available from https://www.binance.com/en/margin-fee

Query Max Transfer-Out Amount (USER_DATA)

Response:

 {
      "amount": "3.59498107"
 }


GET /sapi/v1/margin/maxTransferable (HMAC SHA256)

Weight(IP):
50

Parameters:

Name Type Mandatory Description
asset STRING YES
isolatedSymbol STRING NO isolated symbol
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • If isolatedSymbol is not sent, crossed margin data will be sent.

Get Summary of Margin account (USER_DATA)

Response:

{
  "normalBar": "1.5",
  "marginCallBar": "1.3",
  "forceLiquidationBar": "1.1"
}


GET /sapi/v1/margin/tradeCoeff (HMAC SHA256)

Get personal margin level information

Weight(IP):
10

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Isolated Margin Account Transfer (MARGIN)

Response:

{
    //transaction id
    "tranId": 100000001
}

POST /sapi/v1/margin/isolated/transfer (HMAC SHA256)

Weight(UID):
600

Parameters:

Name Type Mandatory Description
asset STRING YES asset,such as BTC
symbol STRING YES
transFrom STRING YES «SPOT», «ISOLATED_MARGIN»
transTo STRING YES «SPOT», «ISOLATED_MARGIN»
amount DECIMAL YES
recvWindow LONG NO No more than 60000
timestamp LONG YES

Get Isolated Margin Transfer History (USER_DATA)

Response:

{
  "rows": [
    {
      "amount": "0.10000000",
      "asset": "BNB",
      "status": "CONFIRMED",
      "timestamp": 1566898617000,
      "txId": 5240372201,
      "transFrom": "SPOT",
      "transTo": "ISOLATED_MARGIN"
    },
    {
      "amount": "5.00000000",
      "asset": "USDT",
      "status": "CONFIRMED",
      "timestamp": 1566888436123,
      "txId": 5239810406,
      "transFrom": "ISOLATED_MARGIN",
      "transTo": "SPOT"
    }
  ],
  "total": 2
}

GET /sapi/v1/margin/isolated/transfer (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
symbol STRING YES
transFrom STRING NO «SPOT», «ISOLATED_MARGIN»
transTo STRING NO «SPOT», «ISOLATED_MARGIN»
startTime LONG NO
endTime LONG NO
current LONG NO Current page, default 1
size LONG NO Default 10, max 100
archived STRING NO Default: false. Set to true for archived data from 6 months ago
recvWindow LONG NO No more than 60000
timestamp LONG YES
  • The max interval between startTime and endTime is 30 days.
  • If startTimeand endTime not sent, return records of the last 7 days by default
  • Set archived to true to query data from 6 months ago

Query Isolated Margin Account Info (USER_DATA)

Response:

If «symbols» is not sent

{
   "assets":[
      {
        "baseAsset": 
        {
          "asset": "BTC",
          "borrowEnabled": true,
          "borrowed": "0.00000000",
          "free": "0.00000000",
          "interest": "0.00000000",
          "locked": "0.00000000",
          "netAsset": "0.00000000",
          "netAssetOfBtc": "0.00000000",
          "repayEnabled": true,
          "totalAsset": "0.00000000"
        },
        "quoteAsset": 
        {
          "asset": "USDT",
          "borrowEnabled": true,
          "borrowed": "0.00000000",
          "free": "0.00000000",
          "interest": "0.00000000",
          "locked": "0.00000000",
          "netAsset": "0.00000000",
          "netAssetOfBtc": "0.00000000",
          "repayEnabled": true,
          "totalAsset": "0.00000000"
        },
        "symbol": "BTCUSDT",
        "isolatedCreated": true, 
        "enabled": true, // true-enabled, false-disabled
        "marginLevel": "0.00000000", 
        "marginLevelStatus": "EXCESSIVE", // "EXCESSIVE", "NORMAL", "MARGIN_CALL", "PRE_LIQUIDATION", "FORCE_LIQUIDATION"
        "marginRatio": "0.00000000",
        "indexPrice": "10000.00000000",
        "liquidatePrice": "1000.00000000",
        "liquidateRate": "1.00000000",
        "tradeEnabled": true
      }
    ],
    "totalAssetOfBtc": "0.00000000",
    "totalLiabilityOfBtc": "0.00000000",
    "totalNetAssetOfBtc": "0.00000000" 
}

If «symbols» is sent

{
   "assets":[
      {
        "baseAsset": 
        {
          "asset": "BTC",
          "borrowEnabled": true,
          "borrowed": "0.00000000",
          "free": "0.00000000",
          "interest": "0.00000000",
          "locked": "0.00000000",
          "netAsset": "0.00000000",
          "netAssetOfBtc": "0.00000000",
          "repayEnabled": true,
          "totalAsset": "0.00000000"
        },
        "quoteAsset": 
        {
          "asset": "USDT",
          "borrowEnabled": true,
          "borrowed": "0.00000000",
          "free": "0.00000000",
          "interest": "0.00000000",
          "locked": "0.00000000",
          "netAsset": "0.00000000",
          "netAssetOfBtc": "0.00000000",
          "repayEnabled": true,
          "totalAsset": "0.00000000"
        },
        "symbol": "BTCUSDT",
        "isolatedCreated": true, 
        "enabled": true, // true-enabled, false-disabled
        "marginLevel": "0.00000000", 
        "marginLevelStatus": "EXCESSIVE", // "EXCESSIVE", "NORMAL", "MARGIN_CALL", "PRE_LIQUIDATION", "FORCE_LIQUIDATION"
        "marginRatio": "0.00000000",
        "indexPrice": "10000.00000000",
        "liquidatePrice": "1000.00000000",
        "liquidateRate": "1.00000000",
        "tradeEnabled": true
      }
    ]
}

GET /sapi/v1/margin/isolated/account (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbols STRING NO Max 5 symbols can be sent; separated by «,». e.g. «BTCUSDT,BNBUSDT,ADAUSDT»
recvWindow LONG NO No more than 60000
timestamp LONG YES
  • If «symbols» is not sent, all isolated assets will be returned.
  • If «symbols» is sent, only the isolated assets of the sent symbols will be returned.

Disable Isolated Margin Account (TRADE)

Response:

{
  "success": true,
  "symbol": "BTCUSDT"
}


DELETE /sapi/v1/margin/isolated/account (HMAC SHA256)

Disable isolated margin account for a specific symbol. Each trading pair can only be deactivated once every 24
hours.

Weight(UID):
300

Parameters:

Name Type Mandatory Description
symbol STRING YES
recvWindow LONG NO No more than 60000
timestamp LONG YES

Enable Isolated Margin Account (TRADE)

Response:

{
  "success": true,
  "symbol": "BTCUSDT"
}


POST /sapi/v1/margin/isolated/account (HMAC SHA256)

Enable isolated margin account for a specific symbol(Only supports activation of previously disabled accounts).

Weight(UID):
300

Parameters:

Name Type Mandatory Description
symbol STRING YES
recvWindow LONG NO No more than 60000
timestamp LONG YES

Query Enabled Isolated Margin Account Limit (USER_DATA)

Response:

{
  "enabledAccount": 5,
  "maxAccount": 20
}


GET /sapi/v1/margin/isolated/accountLimit (HMAC SHA256)

Query enabled isolated margin account limit.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO No more than 60000
timestamp LONG YES

Query Isolated Margin Symbol (USER_DATA)

Response:

{
   "symbol":"BTCUSDT",
   "base":"BTC",
   "quote":"USDT",
   "isMarginTrade":true,
   "isBuyAllowed":true,
   "isSellAllowed":true      
}

GET /sapi/v1/margin/isolated/pair (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
symbol STRING YES
recvWindow LONG NO No more than 60000
timestamp LONG YES

Get All Isolated Margin Symbol(USER_DATA)

Response:

[
    {
        "base": "BNB",
        "isBuyAllowed": true,
        "isMarginTrade": true,
        "isSellAllowed": true,
        "quote": "BTC",
        "symbol": "BNBBTC"     
    },
    {
        "base": "TRX",
        "isBuyAllowed": true,
        "isMarginTrade": true,
        "isSellAllowed": true,
        "quote": "BTC",
        "symbol": "TRXBTC"    
    }
]

GET /sapi/v1/margin/isolated/allPairs (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
recvWindow LONG NO No more than 60000
timestamp LONG YES

Toggle BNB Burn On Spot Trade And Margin Interest (USER_DATA)

Response:

{
   "spotBNBBurn":true,
   "interestBNBBurn": false   
}

POST /sapi/v1/bnbBurn (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
spotBNBBurn STRING NO «true» or «false»; Determines whether to use BNB to pay for trading fees on SPOT
interestBNBBurn STRING NO «true» or «false»; Determines whether to use BNB to pay for margin loan’s interest
recvWindow LONG NO No more than 60000
timestamp LONG YES
  • «spotBNBBurn» and «interestBNBBurn» should be sent at least one.

Get BNB Burn Status (USER_DATA)

Response:

{
   "spotBNBBurn":true,
   "interestBNBBurn": false   
}

GET /sapi/v1/bnbBurn (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO No more than 60000
timestamp LONG YES

Query Margin Interest Rate History (USER_DATA)

Response:

[
    {
        "asset": "BTC",
        "dailyInterestRate": "0.00025000",
        "timestamp": 1611544731000,
        "vipLevel": 1    
    },
    {
        "asset": "BTC",
        "dailyInterestRate": "0.00035000",
        "timestamp": 1610248118000,
        "vipLevel": 1    
    }
]

GET /sapi/v1/margin/interestRateHistory (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING YES
vipLevel INT NO Default: user’s vip level
startTime LONG NO Default: 7 days ago
endTime LONG NO Default: present. Maximum range: 1 months.
recvWindow LONG NO No more than 60000
timestamp LONG YES

Query Cross Margin Fee Data (USER_DATA)

Response:

[
    {
        "vipLevel": 0,
        "coin": "BTC",
        "transferIn": true,
        "borrowable": true,
        "dailyInterest": "0.00026125",
        "yearlyInterest": "0.0953",
        "borrowLimit": "180",
        "marginablePairs": [
            "BNBBTC",
            "TRXBTC",
            "ETHBTC",
            "BTCUSDT"
        ]
    }
]

GET /sapi/v1/margin/crossMarginData (HMAC SHA256)

Get cross margin fee data collection with any vip level or user’s current specific data as https://www.binance.com/en/margin-fee

Weight(IP):
1 when coin is specified;
5 when the coin parameter is omitted

Parameters:

Name Type Mandatory Description
vipLevel INT NO User’s current specific margin data will be returned if vipLevel is omitted
coin STRING NO
recvWindow LONG NO No more than 60000
timestamp LONG YES

Query Isolated Margin Fee Data (USER_DATA)

Response:

[
    {
        "vipLevel": 0,
        "symbol": "BTCUSDT",
        "leverage": "10",
        "data": [
            {
                "coin": "BTC",
                "dailyInterest": "0.00026125",
                "borrowLimit": "270"
            },
            {
                "coin": "USDT",
                "dailyInterest": "0.000475",
                "borrowLimit": "2100000"
            }
        ]
    }
]

GET /sapi/v1/margin/isolatedMarginData (HMAC SHA256)

Get isolated margin fee data collection with any vip level or user’s current specific data as https://www.binance.com/en/margin-fee

Weight(IP):
1 when a single is specified;
10 when the symbol parameter is omitted

Parameters:

Name Type Mandatory Description
vipLevel INT NO User’s current specific margin data will be returned if vipLevel is omitted
symbol STRING NO
recvWindow LONG NO No more than 60000
timestamp LONG YES

Query Isolated Margin Tier Data (USER_DATA)

Response:

[
    {
        "symbol": "BTCUSDT",
        "tier": 1,
        "effectiveMultiple": "10",
        "initialRiskRatio": "1.111",
        "liquidationRiskRatio": "1.05",
        "baseAssetMaxBorrowable": "9",
        "quoteAssetMaxBorrowable": "70000"
    }
]

GET /sapi/v1/margin/isolatedMarginTier (HMAC SHA256)

Get isolated margin tier data collection with any tier as https://www.binance.com/en/margin-data

Weight(IP):
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
tier INTEGER NO All margin tier data will be returned if tier is omitted
recvWindow LONG NO No more than 60000
timestamp LONG YES

Query Current Margin Order Count Usage (TRADE)

Response:

[

  {
    "rateLimitType": "ORDERS",
    "interval": "SECOND",
    "intervalNum": 10,
    "limit": 10000,
    "count": 0
  },
  {
    "rateLimitType": "ORDERS",
    "interval": "DAY",
    "intervalNum": 1,
    "limit": 20000,
    "count": 0
  }
]


GET /sapi/v1/margin/rateLimit/order

Displays the user’s current margin order count usage for all intervals.

Weight(IP):
20

Parameters:

Name Type Mandatory Description
isIsolated STRING NO for isolated margin or not, «TRUE», «FALSE»,default «FALSE»
symbol STRING NO isolated symbol, mandatory for isolated margin
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Margin Dustlog (USER_DATA)

Response:

{
        "total": 8, //Total counts of exchange
        "userAssetDribblets": [
            {
                "operateTime": 1615985535000,
                "totalTransferedAmount": "0.00132256", // Total transfered BNB amount for this exchange.
                "totalServiceChargeAmount": "0.00002699", //Total service charge amount for this exchange.
                "transId": 45178372831,
                "userAssetDribbletDetails": [ //Details of  this exchange.
                    {
                        "transId": 4359321,
                        "serviceChargeAmount": "0.000009",
                        "amount": "0.0009",
                        "operateTime": 1615985535000,
                        "transferedAmount": "0.000441",
                        "fromAsset": "USDT"
                    },
                    {
                        "transId": 4359321,
                        "serviceChargeAmount": "0.00001799",
                        "amount": "0.0009",
                        "operateTime": 1615985535000,
                        "transferedAmount": "0.00088156",
                        "fromAsset": "ETH"
                    }
                ]
            },
            {
                "operateTime":1616203180000,
                "totalTransferedAmount": "0.00058795",
                "totalServiceChargeAmount": "0.000012",
                "transId": 4357015,
                "userAssetDribbletDetails": [       
                    {
                        "transId": 4357015,
                        "serviceChargeAmount": "0.00001",
                        "amount": "0.001",
                        "operateTime": 1616203180000,
                        "transferedAmount": "0.00049",
                        "fromAsset": "USDT"
                    },
                    {
                        "transId": 4357015,
                        "serviceChargeAmount": "0.000002",         
                        "amount": "0.0001",
                        "operateTime": 1616203180000,
                        "transferedAmount": "0.00009795",
                        "fromAsset": "ETH"
                    }
                ]
            }
        ]
    }
}


GET /sapi/v1/margin/dribblet (HMAC SHA256)

Query the historical information of user’s margin account small-value asset conversion BNB.

Parameters:

Name Type Mandatory Description
startTime LONG NO
endTime LONG NO
recvWindow LONG NO
timestamp LONG YES

Cross margin collateral ratio (MARKET_DATA)

Response:

[
  {
    "collaterals": [
      {
        "minUsdValue": "0",
        "maxUsdValue": "13000000",
        "discountRate": "1"
      },
      {
        "minUsdValue": "13000000",
        "maxUsdValue": "20000000",
        "discountRate": "0.975"
      },
      {
        "minUsdValue": "20000000",
        "discountRate": "0"
      }
    ],
    "assetNames": [
      "BNX"
    ]
  },
  {
    "collaterals": [
      {
        "minUsdValue": "0",
        "discountRate": "1"
      }
    ],
    "assetNames": [
      "BTC",
      "BUSD",
      "ETH",
      "USDT"
    ]
  }
]


GET /sapi/v1/margin/crossMarginCollateralRatio (HMAC SHA256)

Weight(IP):
100

Parameters:
None

Get Small Liability Exchange Coin List (USER_DATA)

Query the coins which can be small liability exchange

Response:

[
    {
      "asset": "ETH",
      "interest": "0.00083334",
      "principal": "0.001",
      "liabilityOfBUSD": "1.36214672"
    }
]


GET /sapi/v1/margin/exchange-small-liability (HMAC SHA256)

Weight(UID):
100

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Small Liability Exchange (MARGIN)

Cross Margin Small Liability Exchange


POST /sapi/v1/margin/exchange-small-liability (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
assetNames ARRAY YES The assets list of small liability exchange, Example: assetNames = BTC,USDT
recvWindow LONG NO
timestamp LONG YES
  • Only convert once within 6 hours
  • Only liability valuation less than 10 BUSD are supported
  • The maximum number of coin is 10

Get Small Liability Exchange History (USER_DATA)

Get Small liability Exchange History

Response:

{
    "total": 1,
    "rows": [
      {
        "asset": "ETH",
        "amount": "0.00083434",
        "targetAsset": "BUSD",
        "targetAmount": "1.37576819",
        "bizType": "EXCHANGE_SMALL_LIABILITY",
        "timestamp": 1672801339253
      }
    ]
}


GET /sapi/v1/margin/exchange-small-liability-history (HMAC SHA256)

Weight(UID):
100

Parameters:

Name Type Mandatory Description
current INT YES Currently querying page. Start from 1. Default:1
size INT YES Default:10, Max:100
startTime LONG NO Default: 30 days from current timestamp
endTime LONG NO Default: present timestamp
recvWindow LONG NO
timestamp LONG YES

Get a future hourly interest rate (USER_DATA)


GET /sapi/v1/margin/next-hourly-interest-rate (HMAC SHA256)

Get user the next hourly estimate interest

Response:

[
    {
        "asset": "BTC",
        "nextHourlyInterestRate": "0.00000571"
    },
    {
        "asset": "ETH",
        "nextHourlyInterestRate": "0.00000578"
    }
]

Weight(UID):
100

Parameters:

Name Type Mandatory Description
assets String YES List of assets, separated by commas, up to 20
isIsolated Boolean YES for isolated margin or not, «TRUE», «FALSE»

User Data Streams

  • The base API endpoint is: https://api.binance.com
  • A User Data Stream listenKey is valid for 60 minutes after creation.
  • Doing a PUT on a listenKey will extend its validity for 60 minutes.
  • Doing a DELETE on a listenKey will close the stream and invalidate the listenKey.
  • Doing a POST on an account with an active listenKey will return the currently active listenKey and extend its validity for 60 minutes.
  • A listenKey is a stream.
  • Users can listen to multiple streams.
  • The base websocket endpoint is: wss://stream.binance.com:9443
  • User Data Streams are accessed at /ws/<listenKey> or /stream?streams=<listenKey>
  • A single connection to stream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark

LISTEN KEY (SPOT)

Create a ListenKey (USER_STREAM)

Response:

{
  "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}


POST /api/v3/userDataStream

Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active listenKey, that listenKey will be returned and its validity will be extended for 60 minutes.

Weight:
1

Parameters:

NONE

Data Source:
Memory

Ping/Keep-alive a ListenKey (USER_STREAM)

Response:

{}


PUT /api/v3/userDataStream

Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It’s recommended to send a ping about every 30 minutes.

Weight:
1

Parameters:

Name Type Mandatory Description
listenKey STRING YES

Data Source:
Memory

Close a ListenKey (USER_STREAM)

Response:

{}


DELETE /api/v3/userDataStream

Close out a user data stream.

Weight:
1

Parameters:

Name Type Mandatory Description
listenKey STRING YES

Data Source:
Memory

LISTEN KEY (MARGIN)

Create a ListenKey (USER_STREAM)

Response:

{"listenKey":  "T3ee22BIYuWqmvne0HNq2A2WsFlEtLhvWCtItw6ffhhdmjifQ2tRbuKkTHhr"}


POST /sapi/v1/userDataStream

Weight:
1

Parameters:

NONE

Ping/Keep-alive a ListenKey (USER_STREAM)

Response:

{}


PUT /sapi/v1/userDataStream

Weight:
1

Parameters:

Name Type Mandatory Description
listenKey STRING YES

Close a ListenKey (USER_STREAM)

Response:

{}


DELETE /sapi/v1/userDataStream

Weight:
1

Parameters:

Name Type Mandatory Description
listenKey STRING YES

LISTEN KEY (ISOLATED MARGIN)

Generate a Listen Key (USER_STREAM)

Response:

{
    "listenKey":  "T3ee22BIYuWqmvne0HNq2A2WsFlEtLhvWCtItw6ffhhdmjifQ2tRbuKkTHhr"
}

POST /sapi/v1/userDataStream/isolated

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES

Ping/Keep-alive a Listen Key (USER_STREAM)

Response:

{}

PUT /sapi/v1/userDataStream/isolated

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
listenKey STRING YES

Close a ListenKey (USER_STREAM)

Response:

{}

DELETE /sapi/v1/userDataStream/isolated

Weight:
1

Parameters:

Name Type Mandatory Description
symbol STRING YES
listenKey STRING YES

Payload: Account Update

outboundAccountPosition is sent any time an account balance has changed and contains the assets that were possibly changed by the event that generated the balance change.

Payload:

{
  "e": "outboundAccountPosition", //Event type
  "E": 1564034571105,             //Event Time
  "u": 1564034571073,             //Time of last account update
  "B": [                          //Balances Array
    {
      "a": "ETH",                 //Asset
      "f": "10000.000000",        //Free
      "l": "0.000000"             //Locked
    }
  ]
}

Payload: Balance Update

Balance Update occurs during the following:

  • Deposits or withdrawals from the account
  • Transfer of funds between accounts (e.g. Spot to Margin)

Payload

{
  "e": "balanceUpdate",         //Event Type
  "E": 1573200697110,           //Event Time
  "a": "BTC",                   //Asset
  "d": "100.00000000",          //Balance Delta
  "T": 1573200697068            //Clear Time
}

Payload: Order Update

Orders are updated with the executionReport event.

Execution types:

  • NEW — The order has been accepted into the engine.
  • CANCELED — The order has been canceled by the user.
  • REPLACED (currently unused)
  • REJECTED — The order has been rejected and was not processed (This message appears only with Cancel Replace Orders wherein the new order placement is rejected but the request to cancel request succeeds.)
  • TRADE — Part of the order or all of the order’s quantity has filled.
  • EXPIRED — The order was canceled according to the order type’s rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during liquidation, orders canceled during maintenance).
  • TRADE_PREVENTION — The order has expired due to STP trigger.

Check the Public API Definitions for more relevant enum definitions.

Payload:

{
  "e": "executionReport",        // Event type
  "E": 1499405658658,            // Event time
  "s": "ETHBTC",                 // Symbol
  "c": "mUvoqJxFIILMdfAW5iGSOW", // Client order ID
  "S": "BUY",                    // Side
  "o": "LIMIT",                  // Order type
  "f": "GTC",                    // Time in force
  "q": "1.00000000",             // Order quantity
  "p": "0.10264410",             // Order price
  "P": "0.00000000",             // Stop price
  "F": "0.00000000",             // Iceberg quantity
  "g": -1,                       // OrderListId
  "C": "",                       // Original client order ID; This is the ID of the order being canceled
  "x": "NEW",                    // Current execution type
  "X": "NEW",                    // Current order status
  "r": "NONE",                   // Order reject reason; will be an error code.
  "i": 4293153,                  // Order ID
  "l": "0.00000000",             // Last executed quantity
  "z": "0.00000000",             // Cumulative filled quantity
  "L": "0.00000000",             // Last executed price
  "n": "0",                      // Commission amount
  "N": null,                     // Commission asset
  "T": 1499405658657,            // Transaction time
  "t": -1,                       // Trade ID
  "I": 8641984,                  // Ignore
  "w": true,                     // Is the order on the book?
  "m": false,                    // Is this trade the maker side?
  "M": false,                    // Ignore
  "O": 1499405658657,            // Order creation time
  "Z": "0.00000000",             // Cumulative quote asset transacted quantity
  "Y": "0.00000000",             // Last quote asset transacted quantity (i.e. lastPrice * lastQty)
  "Q": "0.00000000",             // Quote Order Quantity
  "W": 1499405658657,            // Working Time; This is only visible if the order has been placed on the book.
  "V": "NONE"                    // selfTradePreventionMode
}

Note: Average price can be found by doing Z divided by z.

Conditional Fields in Execution Report

These are fields that appear in the payload only if certain conditions are met.

Field Name Description Examples
d Trailing Delta Appears only for trailing stop orders. "d": 4
D Trailing Time "D": 1668680518494
j Strategy Id Appears only if the strategyId parameter was provided upon order placement. "j": 1
J Strategy Type Appears only if the strategyType parameter was provided upon order placement. "J": 1000000
v Prevented Match Id Appears only for orders that expired due to STP. "v": 3
A Prevented Quantity "A":"3.000000"
B Last Prevented Quantity "B":"3.000000"
u Trade Group Id "u":1
U Counter Order Id "U":37

If the order is an OCO, an event will be displayed named ListStatus in addition to the executionReport event.

Payload

{
  "e": "listStatus",                //Event Type
  "E": 1564035303637,               //Event Time
  "s": "ETHBTC",                    //Symbol
  "g": 2,                           //OrderListId
  "c": "OCO",                       //Contingency Type
  "l": "EXEC_STARTED",              //List Status Type
  "L": "EXECUTING",                 //List Order Status
  "r": "NONE",                      //List Reject Reason
  "C": "F4QN4G8DlFATFlIUQ0cjdD",    //List Client Order ID
  "T": 1564035303625,               //Transaction Time
  "O": [                            //An array of objects
    {
      "s": "ETHBTC",                //Symbol
      "i": 17,                      // orderId
      "c": "AJYsMjErWJesZvqlJCTUgL" //ClientOrderId
    },
    {
      "s": "ETHBTC",
      "i": 18,
      "c": "bfYPSQdLoqAJeNrOr9adzq"
    }
  ]
}

Savings Endpoints

  • The endpoints below allow you to interact with Binance Savings, previously known as Binance Lending.
  • For more information on this, please refer to the Binance Savings page

Get Flexible Product List (USER_DATA)

Response:

[
    {
        "asset": "BTC",
        "avgAnnualInterestRate": "0.05000000"
        "tierAnnualInterestRate": {            
              "0-5BTC": 0.05,
              "5-10BTC": 0.03,
              ">10BTC": 0.01
                              },
        "canPurchase": true,
        "canRedeem": true,
        "dailyInterestPerThousand": "0.00685000", //abandoned
        "featured": true,
        "minPurchaseAmount": "0.01000000",
        "productId": "BTC001",
        "purchasedAmount": "16.32467016",
        "status": "PURCHASING", //PREHEATING: Warming up; PURCHASING: Subscribing; END: Finish
        "upLimit": "200.00000000",
        "upLimitPerUser": "5.00000000"
    },
    {
        "asset": "BUSD",
        "avgAnnualInterestRate": "0.01228590",
       "tierAnnualInterestRate":"", 
        "canPurchase": true,
        "canRedeem": true,
        "dailyInterestPerThousand": "0.03836000", //abandoned
        "featured": true,
        "minPurchaseAmount": "0.10000000",
        "productId": "BUSD001",
        "purchasedAmount": "10.38932339",
        "status": "PURCHASING", //PREHEATING: Warming up; PURCHASING: Subscribing; END: Finish
        "upLimit": "100000.00000000",
        "upLimitPerUser": "50000.00000000"
    }
]


GET /sapi/v1/lending/daily/product/list (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
status ENUM NO «ALL», «SUBSCRIBABLE», «UNSUBSCRIBABLE»; Default: «ALL»
asset STRING NO
featured STRING NO «ALL», «TRUE»; Default: «ALL»
current LONG NO Current query page. Default: 1, Min: 1
size LONG NO Default: 50, Max: 100
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Get Left Daily Purchase Quota of Flexible Product (USER_DATA)

Response:

{
    "asset": "BUSD", 
    "leftQuota": "50000.00000000"
}


GET /sapi/v1/lending/daily/userLeftQuota (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
productId STRING YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Purchase Flexible Product (USER_DATA)

Response:

{
    "purchaseId": 40607
}


POST /sapi/v1/lending/daily/purchase (HMAC SHA256)

Weight(IP):
1

Rate Limit:
1/3s per account

Parameters:

Name Type Mandatory Description
productId STRING YES
amount DECIMAL YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Get Left Daily Redemption Quota of Flexible Product (USER_DATA)

Response:

{
    "asset": "USDT",
    "dailyQuota": "10000000.00000000",
    "leftQuota": "0.00000000",
    "minRedemptionAmount": "0.10000000"
}


GET /sapi/v1/lending/daily/userRedemptionQuota (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
productId STRING YES
type ENUM YES «FAST», «NORMAL»
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Redeem Flexible Product (USER_DATA)

Response:

{}


POST /sapi/v1/lending/daily/redeem (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
productId STRING YES
amount DECIMAL YES
type ENUM YES «FAST»
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Get Flexible Product Position (USER_DATA)

Response:

[
    {
        "tierAnnualInterestRate": {              
                 "0-5BTC": 0.05,
                 "5-10BTC": 0.03,
                 ">10BTC": 0.01
                              },
        "annualInterestRate":"0.02599895",        
        "asset": "USDT",
        "avgAnnualInterestRate": "0.02599895", 
        "canRedeem": true,
        "dailyInterestRate": "0.00007123",
        "freeAmount": "75.46000000",
        "freezeAmount": "0.00000000", // abandoned
        "lockedAmount": "0.00000000", // abandoned
        "productId": "USDT001",
        "productName": "USDT",
        "redeemingAmount": "0.00000000",
        "todayPurchasedAmount": "0.00000000",
        "totalAmount": "75.46000000",
        "totalInterest": "0.22759183"
    }
]


GET /sapi/v1/lending/daily/token/position (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Get Fixed and Activity Project List(USER_DATA)

Response:

[
    {
        "asset": "USDT",
        "displayPriority": 1,
        "duration": 90,
        "interestPerLot": "1.35810000",
        "interestRate": "0.05510000",
        "lotSize": "100.00000000",
        "lotsLowLimit": 1,
        "lotsPurchased": 74155,
        "lotsUpLimit": 80000,
        "maxLotsPerUser": 2000,
        "needKyc": false,
        "projectId": "CUSDT90DAYSS001",
        "projectName": "USDT",
        "status": "PURCHASING",
        "type": "CUSTOMIZED_FIXED",
        "withAreaLimitation": false
    }
]


GET /sapi/v1/lending/project/list (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
type ENUM YES «ACTIVITY», «CUSTOMIZED_FIXED»
status ENUM NO «ALL», «SUBSCRIBABLE», «UNSUBSCRIBABLE»; default «ALL»
isSortAsc BOOLEAN NO default «true»
sortBy ENUM NO «START_TIME», «LOT_SIZE», «INTEREST_RATE», «DURATION»; default «START_TIME»
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10, Max:100
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Purchase Fixed/Activity Project (USER_DATA)

Response:

{
    "purchaseId": "18356"
}


POST /sapi/v1/lending/customizedFixed/purchase (HMAC SHA256)

Weight(IP):
1

Rate Limit:
1/3s per account

Parameters:

Name Type Mandatory Description
projectId STRING YES
lot LONG YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Get Fixed/Activity Project Position (USER_DATA)

Response:

[
    {
        "asset": "USDT",
        "canTransfer": true,
        "createTimestamp": 1587010770000,
        "duration": 14,
        "endTime": 1588291200000,
        "interest": "0.19950000",
        "interestRate": "0.05201250",
        "lot": 1,
        "positionId": 51724,
        "principal": "100.00000000",
        "projectId": "CUSDT14DAYSS001",
        "projectName": "USDT",
        "purchaseTime": 1587010771000,
        "redeemDate": "2020-05-01",
        "startTime": 1587081600000,
        "status": "HOLDING",
        "type": "CUSTOMIZED_FIXED"
    }
]


GET /sapi/v1/lending/project/position/list (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING NO
projectId STRING NO
status ENUM NO «HOLDING», «REDEEMED»
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Lending Account (USER_DATA)

Response:

{
    "positionAmountVos": [
        {
            "amount": "75.46000000",
            "amountInBTC": "0.01044819",
            "amountInUSDT": "75.46000000",
            "asset": "USDT"
        },
        {
            "amount": "1.67072036",
            "amountInBTC": "0.00023163",
            "amountInUSDT": "1.67289230",
            "asset": "BUSD"
        }
    ],
    "totalAmountInBTC": "0.01067982",
    "totalAmountInUSDT": "77.13289230",
    "totalFixedAmountInBTC": "0.00000000",
    "totalFixedAmountInUSDT": "0.00000000",
    "totalFlexibleInBTC": "0.01067982",
    "totalFlexibleInUSDT": "77.13289230"
 }


GET /sapi/v1/lending/union/account (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Get Purchase Record (USER_DATA)

Response:

Flexible Products

[
    {
        "amount": "100.00000000",
        "asset": "USDT",
        "createTime": 1575018510000,
        "lendingType": "DAILY",
        "productName": "USDT",
        "purchaseId": 26055,
        "status": "SUCCESS"
    }
]

Fixed/Activity Products

[
    {
        "amount": "100.00000000",
        "asset": "USDT",
        "createTime": 1575018453000,
        "lendingType": "ACTIVITY",
        "lot": 1,
        "productName": "【Special】USDT 7D (8%)",
        "purchaseId": 36857,
        "status": "SUCCESS"
    }
]


GET /sapi/v1/lending/union/purchaseRecord (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
lendingType ENUM YES «DAILY» for flexible, «ACTIVITY» for activity, «CUSTOMIZED_FIXED» for fixed
asset STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10, Max:100
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • The time between startTime and endTime cannot be longer than 30 days.
  • If startTime and endTime are both not sent, then the last 30 days’ data will be returned.

Get Redemption Record (USER_DATA)

Response:

Flexible Products

[
    {
        "amount": "10.54000000",
        "asset": "USDT",
        "createTime": 1577257222000,
        "principal": "10.54000000",
        "projectId": "USDT001",
        "projectName": "USDT",
        "status": "PAID",
        "type": "FAST"
     }
]

Fixed/Activity Products

[
    {
        "amount": "0.07070000",
        "asset": "USDT",
        "createTime": 1566200161000,
        "interest": "0.00070000",
        "principal": "0.07000000",
        "projectId": "test06",
        "projectName": "USDT 1 day (10% anniualized)",
        "startTime": 1566198000000,
        "status": "PAID"
     }
]


GET /sapi/v1/lending/union/redemptionRecord (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
lendingType ENUM YES «DAILY» for flexible, «ACTIVITY» for activity, «CUSTOMIZED_FIXED» for fixed
asset STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10, Max:100
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • The time between startTime and endTime cannot be longer than 30 days.
  • If startTime and endTime are both not sent, then the last 30 days’ data will be returned.

Get Interest History (USER_DATA)

Response:

[
    {
        "asset": "BUSD",
        "interest": "0.00006408",
        "lendingType": "DAILY",
        "productName": "BUSD",
        "time": 1577233578000
    },
    {
        "asset": "USDT",
        "interest": "0.00687654",
        "lendingType": "DAILY",
        "productName": "USDT",
        "time": 1577233562000
    }
]


GET /sapi/v1/lending/union/interestHistory (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
lendingType ENUM YES «DAILY» for flexible, «ACTIVITY» for activity, «CUSTOMIZED_FIXED» for fixed
asset STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10, Max:100
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • The time between startTime and endTime cannot be longer than 30 days.
  • If startTime and endTime are both not sent, then the last 30 days’ data will be returned.

Change Fixed/Activity Position to Daily Position(USER_DATA)

Response:


{
  "dailyPurchaseId": 862290,
  "success": true,      
  "time": 1577233578000
}


POST /sapi/v1/lending/positionChanged (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
projectId STRING YES
lot LONG YES
positionId LONG NO for fixed position
recvWindow LONG NO no more than 60000
timestamp LONG YES
  • PositionId is mandatory parameter for fixed position.
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Staking Endpoints

The endpoints below allow you to interact with Staking.
For more information on this, please refer to the Staking page

Get Staking Product List(USER_DATA)

Response:

[
    {
        "projectId": "Axs*90",
        "detail": {
            "asset":"AXS",       //Lock up asset
            "rewardAsset":"AXS", //Earn Asset
            "duration":90,       //Lock period(days)
            "renewable":true,    //Project supports renewal
            "apy": "1.2069"      
        },
        "quota": {
            "totalPersonalQuota":"2",  //Total Personal quota
            "minimum":"0.001"          //Minimum amount per order
        }
    },
    {
        "projectId": "Fio*90",
        "detail": {
            "asset":"FIO",
            "rewardAsset":"FIO",
            "duration":90,
            "renewable":true,
            "apy":"1.0769"
        },
        "quota": {
            "totalPersonalQuota":"600",
            "minimum":"0.1"
        }
    }
]   


GET /sapi/v1/staking/productList (HMAC SHA256)

Get available Staking product list

Weight(IP):
1

Parameters:

Name Type Mandatory Description
product ENUM YES «STAKING» for Locked Staking, «F_DEFI» for flexible DeFi Staking, «L_DEFI» for locked DeFi Staking
asset STRING NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10, Max:100
recvWindow LONG NO
timestamp LONG YES

Purchase Staking Product(USER_DATA)

Response:


{
  "positionId":"12345",
  "success":true
}


POST /sapi/v1/staking/purchase (HMAC SHA256)

Weight(IP):
1

Rate Limit:
1/3s per account

Parameters:

Name Type Mandatory Description
product ENUM YES «STAKING» for Locked Staking, «F_DEFI» for flexible DeFi Staking, «L_DEFI» for locked DeFi Staking
productId STRING YES
amount DECIMAL YES
renewable STRING NO true or false, default false. Active if product is «STAKING» or «L_DEFI»
recvWindow LONG NO
timestamp LONG YES
  • You need to open Enable Spot & Margin Trading permission for the API Key which requests this endpoint.

Redeem Staking Product(USER_DATA)

Response:

{

 "success":true

}


POST /sapi/v1/staking/redeem (HMAC SHA256)

Redeem Staking product. Locked staking and Locked DeFI staking belong to early redemption, redeeming in advance will result in loss of interest that you have earned.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
product ENUM YES «STAKING» for Locked Staking, «F_DEFI» for flexible DeFi Staking, «L_DEFI» for locked DeFi Staking
positionId STRING NO «1234», Mandatory if product is «STAKING» or «L_DEFI»
productId STRING YES
amount DECIMAL NO Mandatory if product is «F_DEFI»
recvWindow LONG NO
timestamp LONG YES
  • You need to open Enable Spot & Margin Trading permission for the API Key which requests this endpoint.

Get Staking Product Position(USER_DATA)

Response:

[
  {
    "positionId":"123123",  //Staking position ID
    "projectId": "Axs*90",  //Staking project ID
    "asset":"AXS",          //Locked asset 
    "amount":"122.09202928",  //Locked Amount
    "purchaseTime": "1646182276000",  //Subscription time
    "duration": "60",    //Lock period(days) 
    "accrualDays": "4",  //Accrue days
    "rewardAsset":"AXS", //Earned asset
    "APY":"0.2032",      
    "rewardAmt": "5.17181528",  //Earned amount
    "extraRewardAsset":"BNB",   //Rewards assets of extra staking type 
    "extraRewardAPY":"0.0203",  //APY of extra staking type
    "estExtraRewardAmt": "5.17181528", //Rewards of extra staking type, distribute when order expires
    "nextInterestPay": "1.29295383",   //Next estimated interest payment
    "nextInterestPayDate": "1646697600000", //Next interest payment date
    "payInterestPeriod": "1",  //Interest cycle
    "redeemAmountEarly": "2802.24068892", //Early redemption amount
    "interestEndDate": "1651449600000",   //Interest accrual end date
    "deliverDate": "1651536000000",       //Redemption arrival time
    "redeemPeriod": "1",           //Redemption interval
    "redeemingAmt":"232.2323",     //Amount under redemption
    "partialAmtDeliverDate":"1651536000000", //Arrival time of partial redemption amount of order
    "canRedeemEarly": true,  //When it is true, early redemption can be operated 
    "renewable"true,  //When it is true, auto staking can be operated
    "type":"AUTO",   //Order type is auto-staking or normal
    "status": "HOLDING"
  }
]


GET /sapi/v1/staking/position (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
product ENUM YES «STAKING» for Locked Staking, «F_DEFI» for flexible DeFi Staking, «L_DEFI» for locked DeFi Staking
productId STRING NO
asset STRING NO
current LONG NO Currently querying the page. Start from 1. Default:1
size LONG NO Default:10, Max:100
recvWindow LONG NO
timestamp LONG YES

Get Staking History(USER_DATA)

Response:

[
  {
    "positionId":"123123",
    "time":1575018510000,
    "asset":"BNB",
    "project":"BSC", //DeFi Staking’s project 
    "amount":"21312.23223",
    "lockPeriod":"30",
    "deliverDate":"1575018510000",  //Redemption date
    "type":"AUTO", // display only for subscription
    "status":"success"
  }
]


GET /sapi/v1/staking/stakingRecord (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
product ENUM YES «STAKING» for Locked Staking, «F_DEFI» for flexible DeFi Staking, «L_DEFI» for locked DeFi Staking
txnType ENUM YES «SUBSCRIPTION», «REDEMPTION», «INTEREST»
asset STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying the page. Start from 1. Default:1
size LONG NO Default:10, Max:100
recvWindow LONG NO
timestamp LONG YES
  • The time between startTime and endTime cannot be longer than 3 months.
  • If startTime and endTime are both not sent, then the last 30 days’ data will be returned.

Set Auto Staking(USER_DATA)

Response:

{

  "success":true

}


POST /sapi/v1/staking/setAutoStaking (HMAC SHA256)

Set auto staking on Locked Staking or Locked DeFi Staking

Weight(IP):
1

Parameters:

Name Type Mandatory Description
product ENUM YES «STAKING» for Locked Staking, «L_DEFI» for locked DeFi Staking
positionId STRING YES
renewable STRING YES true or false
recvWindow LONG NO
timestamp LONG YES

Get Personal Left Quota of Staking Product(USER_DATA)

Response:

[             
  { 
    "leftPersonalQuota": "1000" // User left quota
  }      
]


GET /sapi/v1/staking/personalLeftQuota(HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
product ENUM YES «STAKING» for Locked Staking, «F_DEFI» for flexible DeFi Staking, «L_DEFI» for locked DeFi Staking
productId STRING YES
recvWindow LONG NO
timestamp LONG YES

Mining Endpoints

  • The endpoints below allow to interact with Binance Pool.
  • For more information on this, please refer to the Binance Pool page

Acquiring Algorithm (MARKET_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": [
    {
      "algoName": "sha256",                        //  Algorithm name
      "algoId": 1,                                 // Algorithm ID
      "poolIndex": 0,                              // Sequence 
      "unit": "h/s"                                //   Unit
    }
  ]
}

GET /sapi/v1/mining/pub/algoList (HMAC SHA256)

Weight(IP):
1

Parameter:

None

Acquiring CoinName (MARKET_DATA)

GET /sapi/v1/mining/pub/coinList (HMAC SHA256)

Weight(IP):
1

Parameter:

None

Response:

{
  "code": 0,
  "msg": "",
  "data": [
    {
      "coinName": "BTC",                      //  Currencyname
      "coinId": 1,                            // id
      "poolIndex": 0,                         // Sort
      "algoId": 1,                            // Algorithm
      "algoName": "sha256"                    //Name of algorithm
    }
  ]
}

Request for Detail Miner List (USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": [
    {
      "workerName": "bhdc1.16A10404B",     //Mining Account name
      "type": "H_hashrate",               // Type of hourly hashrate
      "hashrateDatas": [
        {
          "time": 1587902400000,         //  Time
          "hashrate": "0",               // Hashrate
          "reject": 0                    //Rejection Rate
        },
        {
          "time": 1587906000000,
          "hashrate": "0",
          "reject": 0
        }
      ]
    },
    {
      "workerName": "bhdc1.16A10404B",    //Mining Account name
      "type": "D_hashrate",                //Type of daily hashrate
      "hashrateDatas": [
        {
          "time": 1587902400000,          //  Time
          "hashrate": "0",                // Hashrate 
          "reject": 0                     //Rejection Rate
        },
        {
          "time": 1587906000000,
          "hashrate": "0",
          "reject": 0
        }
      ]
    }
  ]
}

GET /sapi/v1/mining/worker/detail (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description For Example
algo STRING YES Algorithm(sha256) sha256
userName STRING YES Mining account test
workerName STRING YES Miner’s name(required) bhdc1.16A10404B
recvWindow LONG NO
timestamp LONG YES

Request for Miner List (USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": {
    "workerDatas": [
      {
        "workerId": "1420554439452400131",  //Miner ID
        "workerName": "2X73",               //Miner's name  
        "status": 3,                        // Status:1 valid, 2 invalid, 3 no longer valid
        "hashRate": 0,                      // Real-time rate
        "dayHashRate": 0,                   //24H Hashrate
        "rejectRate": 0,                    //Real-time Rejection Rate
        "lastShareTime": 1587712919000      // Last submission time 
      },
      {
        "workerId": "7893926126382807951",
        "workerName": "AZDC1.1A10101",
        "status": 2,
        "hashRate": 29711247541680,
        "dayHashRate": 12697781298013.66,
        "rejectRate": 0,
        "lastShareTime": 1587969727000
      }
    ],
    "totalNum": 18530,           // Total amount
    "pageSize": 20               // Rows per page
  }
}

GET /sapi/v1/mining/worker/list (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description For Example
algo STRING YES Algorithm(sha256) sha256
userName STRING YES Mining account test
pageIndex INTEGER NO Page number,default is first page,start form 1
sort INTEGER NO sort sequence(default=0)0 positive sequence,1 negative sequence
sortColumn INTEGER NO Sort by( default 1):

1: miner name,

2: real-time computing power,

3: daily average computing power,

4: real-time rejection rate,

5: last submission time

workerStatus INTEGER NO miners status(default=0)0 all,1 valid,2 invalid,3failure
recvWindow LONG NO
timestamp LONG YES

Earnings List(USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": {
    "accountProfits": [
      {
        "time": 1586188800000,            // Mining date
        "type": 31, // 0:Mining Wallet,5:Mining Address,7:Pool Savings,8:Transferred,31:Income Transfer ,32:Hashrate Resale-Mining Wallet 33:Hashrate Resale-Pool Savings
        "hashTransfer": null,            // Transferred Hashrate
        "transferAmount": null,          // Transferred Income   
        "dayHashRate": 129129903378244,  // Daily Hashrate
        "profitAmount": 8.6083060304,   //Earnings Amount
        "coinName":"BTC",              // Coin Type
        "status": 2    //Status:0:Unpaid, 1:Paying  2:Paid
      },
      {
        "time": 1607529600000,
        "coinName": "BTC",
        "type": 0,
        "dayHashRate": 9942053925926,
        "profitAmount": 0.85426469,
        "hashTransfer": 200000000000,
        "transferAmount": 0.02180958,
        "status": 2
      },
      {
        "time": 1607443200000,
        "coinName": "BTC",
        "type": 31,
        "dayHashRate": 200000000000,
        "profitAmount": 0.02905916,
        "hashTransfer": null,
        "transferAmount": null,
        "status": 2
      }
    ],
    "totalNum": 3,          // Total Rows
    "pageSize": 20          // Rows per page
  }
}

GET /sapi/v1/mining/payment/list (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description Example
algo STRING YES Transfer algorithm(sha256) sha256
userName STRING YES Mining account test
coin STRING NO Coin name
startDate Long NO Search date, millisecond timestamp, while empty query all
endDate Long NO Search date, millisecond timestamp, while empty query all
pageIndex INTEGER NO Page number, empty default first page, starting from 1
pageSize INTEGER NO Number of pages, minimum 10, maximum 200
recvWindow LONG NO
timestamp LONG YES

Response:

{
  "code": 0,
  "msg": "",
  "data": {
    "otherProfits": [
      {
        "time": 1607443200000,      // Mining date
        "coinName": "BTC",    // Coin Name
        "type": 4,            // 1: Merged Mining, 2: Activity Bonus, 3:Rebate 4:Smart Pool 6:Income Transfer 7:Pool Savings
        "profitAmount": 0.0011859,  //Amount
        "status": 2         //Status:0:Unpaid, 1:Paying  2:Paid
      }
    ],
    "totalNum": 3,          // Total Rows
    "pageSize": 20          // Rows per page
  }
}

GET /sapi/v1/mining/payment/other (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description Example
algo STRING YES Transfer algorithm(sha256) sha256
userName STRING YES Mining Account test
coin STRING NO Coin Name
startDate Long NO Search date, millisecond timestamp, while empty query all
endDate Long NO Search date, millisecond timestamp, while empty query all
pageIndex INTEGER NO Page number, empty default first page, starting from 1
pageSize INTEGER NO Number of pages, minimum 10, maximum 200
recvWindow LONG NO
timestamp LONG YES

Hashrate Resale List (USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": {
    "configDetails": [
      {
        "configId": 168,     // Mining ID
        "poolUsername": "123",  //Transfer out of subaccount
        "toPoolUsername": "user1", //  Transfer into subaccount
        "algoName": "Ethash",     // Transfer algorithm
        "hashRate": 5000000,     //  Transferred Hashrate quantity
        "startDay": 20201210,   // Start date
        "endDay": 20210405,   //End date
        "status": 1       //Status:0 Processing,1:Cancelled,2:Terminated 
      },
      {
        "configId": 166,
        "poolUsername": "pop",
        "toPoolUsername": "111111",
        "algoName": "Ethash",
        "hashRate": 3320000,
        "startDay": 20201226,
        "endDay": 20201227,
        "status": 0
      }
    ],
    "totalNum": 21,
    "pageSize": 200
  }
}

GET /sapi/v1/mining/hash-transfer/config/details/list (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description Example
pageIndex INTEGER NO Page number, empty default first page, starting from 1
pageSize INTEGER NO Number of pages, minimum 10, maximum 200
recvWindow LONG NO
timestamp LONG YES

Hashrate Resale Detail (USER_DATA)

Response:

{
    "code": 0,
    "msg": "",
    "data": {
        "profitTransferDetails": [{
                "poolUsername": "test4001",  // Transfer out of sub-account

                "toPoolUsername": "pop",    // Transfer into subaccount
                "algoName": "sha256",      // Transfer algorithm
                "hashRate": 200000000000,  // Transferred Hashrate quantity
                "day": 20201213,          // Transfer date
                "amount": 0.2256872,     // Transferred income
                "coinName": "BTC"        // Coin Name
            },
            {
                "poolUsername": "test4001",
                "toPoolUsername": "pop",
                "algoName": "sha256",
                "hashRate": 200000000000,
                "day": 20201213,
                "amount": 0.2256872,
                "coinName": "BTC"
            }
        ],
        "totalNum": 8,
        "pageSize": 200
    }
}

GET /sapi/v1/mining/hash-transfer/profit/details (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description Example
configId INTEGER YES Mining ID 168
userName STRING YES Mining Account test
pageIndex INTEGER NO Page number, empty default first page, starting from 1
pageSize INTEGER NO Number of pages, minimum 10, maximum 200
recvWindow LONG NO
timestamp LONG YES

Hashrate Resale Request (USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": 171  // Mining Account
}

POST /sapi/v1/mining/hash-transfer/config (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description Example
userName STRING YES Mining Account test
algo STRING YES Transfer algorithm(sha256) sha256
endDate Long YES Resale End Time (Millisecond timestamp) 1617659086000
startDate Long YES Resale Start Time(Millisecond timestamp) 1607659086000
toPoolUser STRING YES Mining Account S19pro
hashRate Long YES Resale hashrate h/s must be transferred (BTC is greater than 500000000000 ETH is greater than 500000) 100000000
recvWindow LONG NO
timestamp LONG YES

Cancel hashrate resale configuration(USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": true
}

POST /sapi/v1/mining/hash-transfer/config/cancel (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description Example
configId INTEGER YES Mining ID 168
userName STRING YES Mining Account test
recvWindow LONG NO
timestamp LONG YES

Statistic List (USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": {
    "fifteenMinHashRate": "457835490067496409.00000000",          // 15 mins hashrate
    "dayHashRate": "214289268068874127.65000000",                 //  24H Hashrate
    "validNum": 0,                                                // Effective quantity
    "invalidNum": 17562,                                          // Invalid quantity
    "profitToday":{                                              // Today's estimate
      "BTC":"0.00314332",       
      "BSV":"56.17055953",
      "BCH":"106.61586001"
     },
    "profitYesterday":{                                       //  Yesterday's earnings
      "BTC":"0.00314332",
       "BSV":"56.17055953",
       "BCH":"106.61586001"
     },

    "userName": "test",                                    // Mining account
    "unit": "h/s",                                        //  Hashrate unit
    "algo": "sha256"                                      // Algorithm
  }
}

GET /sapi/v1/mining/statistics/user/status (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description For Example
algo STRING YES Algorithm(sha256) sha256
userName STRING YES Mining account test
recvWindow LONG NO
timestamp LONG YES

Account List (USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": [
    {
      "type": "H_hashrate",        //Type of hourly hashrate
      "userName": "test",         // Mining account
      "list": [
        {
          "time": 1585267200000,    // Time
          "hashrate": "0.00000000", // Hashrate
          "reject": "0.00000000"    //Rejection Rate
        },
        {
          "time": 1585353600000,
          "hashrate": "0.00000000",
          "reject": "0.00000000"
        }
      ]
    },
    {
      "type": "D_hashrate",        //Type of daily hashrate
      "userName": "test",          // Mining account
      "list": [
        {
          "time": 1587906000000,     // Time
          "hashrate": "0.00000000", // Hashrate
          "reject": "0.00000000"    //Rejection Rate
        },
        {
          "time": 1587909600000,
          "hashrate": "0.00000000",
          "reject": "0.00000000"
        }
      ]
    }
  ]
}

GET /sapi/v1/mining/statistics/user/list (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description For Example
algo STRING YES Algorithm(sha256) sha256
userName STRING YES Mining account test
recvWindow LONG NO
timestamp LONG YES

Mining Account Earning (USER_DATA)

Response:

{
  "code": 0,
  "msg": "",
  "data": {
    "accountProfits": [
      {
        "time": 1607443200000,      
        "coinName": "BTC",   // Coin
        "type": 2,           // 0:Referral 1:Refund 2:Rebate
        "puid": 59985472,    //Sub-account id
        "subName": "vdvaghani", //Mining account
        "amount": 0.09186957    //Amount
      }
    ],
    "totalNum": 3,          // Total records
    "pageSize": 20          // Size of one page
  }
}

GET /sapi/v1/mining/payment/uid (HMAC SHA256)

Weight(IP):
5

Parameter:

Name Type Mandatory Description For Example
algo STRING YES Algorithm(sha256) sha256
startDate Long NO Millisecond timestamp
endDate Long NO Millisecond timestamp
pageIndex INTEGER NO Default 1
pageSize INTEGER NO Min 10,Max 200
recvWindow LONG NO
timestamp LONG YES

Futures

New Future Account Transfer (USER_DATA)

Response:

{
    "tranId": 100000001    //transaction id
}

POST /sapi/v1/futures/transfer (HMAC SHA256)

Execute transfer between spot account and futures account.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
asset STRING YES The asset being transferred, e.g., USDT
amount DECIMAL YES The amount to be transferred
type INT YES 1: transfer from spot account to USDT-Ⓜ futures account.

2: transfer from USDT-Ⓜ futures account to spot account.

3: transfer from spot account to COIN-Ⓜ futures account.

4: transfer from COIN-Ⓜ futures account to spot account.

recvWindow LONG NO
timestamp LONG YES
  • You need to open Enable Futures permission for the API Key which requests this endpoint.

Get Future Account Transaction History List (USER_DATA)

Response:

{
  "rows": [
    {
      "asset": "USDT",
      "tranId": 100000001,
      "amount": "40.84624400",
      "type": "1",  // one of 1( from spot to USDT-Ⓜ), 2( from USDT-Ⓜ to spot), 3( from spot to COIN-Ⓜ), and 4( from COIN-Ⓜ to spot)
      "timestamp": 1555056425000,
      "status": "CONFIRMED" //one of PENDING (pending to execution), CONFIRMED (successfully transfered), FAILED (execution failed, nothing happened to your account);
    }
  ],
  "total": 1
}

GET /sapi/v1/futures/transfer (HMAC SHA256)

Weight(IP):
10

Parameters:

Name Type Mandatory Description
asset STRING NO
startTime LONG YES
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
size LONG NO Default:10 Max:100
recvWindow LONG NO
timestamp LONG YES
  • Support query within the last 6 months only

Cross-Collateral Borrow History (USER_DATA)

Response:

{
    "rows":[
        {
            "confirmedTime": 1582540328433,
            "coin": "USDT",
            "collateralRate": "0.89991001",  // collateralLevel
            "leftTotal": "4.5",
            "leftPrincipal": "4.5",
            "deadline": 4736102399000,
            "collateralCoin": "BUSD",
            "collateralAmount": "5.0",
            "orderStatus": "PENDING",
            "borrowId": "438648398970089472"
        }
    ],
    "total": 1
}

GET /sapi/v1/futures/loan/borrow/history (HMAC SHA256)

Parameters:

Name Type Mandatory Description
coin STRING NO
startTime LONG NO
endTime LONG NO
limit LONG NO default 500, max 1000
recvWindow LONG NO
timestamp LONG YES

Weight(IP):
10

Cross-Collateral Repayment History (USER_DATA)

Response:

{
    "rows":[
        {
            "coin": "USDT",
            "amount": "1.68",
            "collateralCoin": "BUSD",
            "repayType": "NORMAL", // "COLLATERAL" for collateral repayment
            "releasedCollateral": "1.80288889",
            "price": "1.001", // Loan/collateral exchange rate
            "repayCollateral": "10010", // Only for collateral repayment
            "confirmedTime": 1582781327575,
            "updateTime": 1582794387516, // time
            "status": "PENDING",
            "repayId": "439659223998894080"
        }
    ],
    "total": 1
}

GET /sapi/v1/futures/loan/repay/history HMAC SHA256)

Parameters:

Name Type Mandatory Description
coin STRING NO
startTime LONG NO
endTime LONG NO
limit LONG NO default 500, max 1000
recvWindow LONG NO
timestamp LONG YES

Weight(IP):
10

Cross-Collateral Wallet V2 (USER_DATA)

Response:

{
    "totalCrossCollateral":"5.8238577133",
    "totalBorrowed":"5.07000000",
    "totalInterest":"0.0", // New for interest collection
    "interestFreeLimit": "100000", // New for interest free limit
    "asset": "USD", // New for USD value
    "crossCollaterals":[
        {
            "loanCoin":"USDT",
            "collateralCoin":"BUSD",
            "locked":"5.82211108",
            "loanAmount": "5.07",
            "currentCollateralRate": "0.87168984",   // collateralLevel
            "interestFreeLimitUsed": "5.07", // New for interest free limit
            "principalForInterest": "0.0", // New for interest collection
            "interest": "0.0"  // New for interest collection
        },
        {
            "loanCoin":"BUSD",
            "collateralCoin":"BTC",
            "locked":"0",
            "loanAmount": "0",
            "currentCollateralRate": "0",   // collateralLevel
            "interestFreeLimitUsed": "0", // New for interest free limit
            "principalForInterest": "0.0", // New for interest collection
            "interest": "0.0"  // New for interest collection
        }
    ]
}

GET /sapi/v2/futures/loan/wallet (HMAC SHA256)

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Weight(IP):
1

Adjust Cross-Collateral LTV History (USER_DATA)

Response:

{ 
    "rows":[
        {
            "amount": ".17398184",
            "collateralCoin": "BUSD", 
            "coin": "USDT", 
            "preCollateralRate":"0.87054861",
            "afterCollateralRate":"0.89736451",
            "direction": "REDUCED",
            "status": "COMPLETED",
            "adjustTime": 1583978243588
        }
    ],
    "total": 1
}

GET /sapi/v1/futures/loan/adjustCollateral/history (HMAC SHA256)

Parameters:

Name Type Mandatory Description
loanCoin STRING NO
collateralCoin STRING NO
startTime LONG NO
endTime LONG NO
limit LONG NO default 500, max 1000
recvWindow LONG NO
timestamp LONG YES
  • All data will be returned if loanCoin or collateralCoin is not sent

Weight(IP):
10

Cross-Collateral Liquidation History (USER_DATA)

Response:

{
    "rows":[
        {
            "collateralAmountForLiquidation":"10.12345678",
            "collateralCoin": "BUSD",
            "forceLiquidationStartTime": 1583978243588,
            "coin": "USDT", 
            "restCollateralAmountAfterLiquidation": "15.12345678",
            "restLoanAmount": "11.12345678",
            "status": "PENDING"
        }
    ],
    "total": 1
}

GET /sapi/v1/futures/loan/liquidationHistory (HMAC SHA256)

Parameters:

Name Type Mandatory Description
loanCoin STRING NO
collateralCoin STRING NO
startTime LONG NO
endTime LONG NO
limit LONG NO default 500, max 1000
recvWindow LONG NO
timestamp LONG YES
  • All data will be returned if loanCoin or collateralCoin is not sent

Weight(IP):
10

Cross-Collateral Interest History (USER_DATA)

Response:

{
    "rows":[
        {
            "collateralCoin": "BUSD",
            "interestCoin": "USDT",
            "interest": "2.354",
            "interestFreeLimitUsed": "0", // New for interest free limit
            "principalForInterest": "10000",
            "interestRate": "0.002",
            "time": 1582794387516
        }
    ],
    "total": 1
}

GET /sapi/v1/futures/loan/interestHistory (HMAC SHA256)

Parameters:

Name Type Mandatory Description
collateralCoin STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1. Default:1
limit LONG NO Default:500 Max:1000
recvWindow LONG NO
timestamp LONG YES

Weight(IP):
1

Futures Algo Endpoints

Binance Futures Execution Algorithm API solution aims to provide users ability to programmatically leverage Binance in-house algorithmic trading capability to automate order execution strategy, improve execution transparency and give users smart access to the available market liquidity.

FAQ: Volume Participation(VP) Introduction

FAQ: Time-Weighted Average Price(Twap) Introduction

Volume Participation(VP) New Order (TRADE)

Response:

{
    "clientAlgoId": "00358ce6a268403398bd34eaa36dffe7",
    "success": true,
    "code": 0,
    "msg": "OK"
}


POST /sapi/v1/algo/futures/newOrderVp (HMAC SHA256)

Send in a VP new order.
Only support on USDⓈ-M Contracts.

Weight(UID):
3000

Noted:

  • You need to enable Futures Trading Permission for the api key which requests this endpoint.
  • Base URL: https://api.binance.com

Parameters:

Name Type Mandatory Description
symbol STRING YES Trading symbol eg. BTCUSDT
side ENUM YES Trading side ( BUY or SELL )
positionSide ENUM NO Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode.
quantity DECIMAL YES Quantity of base asset; The notional (quantity * mark price(base asset)) must be more than the equivalent of 10,000 USDT and less than the equivalent of 1,000,000 USDT
urgency ENUM YES Represent the relative speed of the current execution; ENUM: LOW, MEDIUM, HIGH
clientAlgoId STRING NO A unique id among Algo orders (length should be 32 characters), If it is not sent, we will give default value
reduceOnly BOOLEAN NO «true» or «false». Default «false»; Cannot be sent in Hedge Mode; Cannot be sent when you open a position
limitPrice DECIMAL NO Limit price of the order; If it is not sent, will place order by market price by default
recvWindow LONG NO
timestamp LONG YES

Other Info:

  • Total Algo open orders max allowed: 10 orders.
  • Leverage of symbols and position mode will be the same as your futures account settings. You can set up through the trading page or fapi.
  • Receiving "success": true does not mean that your order will be executed. Please use the query order endpoints(GET sapi/v1/algo/futures/openOrders or GET sapi/v1/algo/futures/historicalOrders) to check the order status.
    For example: Your futures balance is insufficient, or open position with reduce only or position side is inconsistent with your own setting. In these cases you will receive "success": true, but the order status will be expired after we check it.

Time-Weighted Average Price(Twap) New Order (TRADE)

Response:

{
    "clientAlgoId": "65ce1630101a480b85915d7e11fd5078",
    "success": true,
    "code": 0,
    "msg": "OK"
}


POST /sapi/v1/algo/futures/newOrderTwap (HMAC SHA256)

Send in a Twap new order.
Only support on USDⓈ-M Contracts.

Weight(UID):
3000

Noted:

  • You need to enable Futures Trading Permission for the api key which requests this endpoint.
  • Base URL: https://api.binance.com

Parameters:

Name Type Mandatory Description
symbol STRING YES Trading symbol eg. BTCUSDT
side ENUM YES Trading side ( BUY or SELL )
positionSide ENUM NO Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode.
quantity DECIMAL YES Quantity of base asset; The notional (quantity * mark price(base asset)) must be more than the equivalent of 10,000 USDT and less than the equivalent of 1,000,000 USDT
duration LONG YES Duration for TWAP orders in seconds. [300, 86400];Less than 5min => defaults to 5 min; Greater than 24h => defaults to 24h
clientAlgoId STRING NO A unique id among Algo orders (length should be 32 characters), If it is not sent, we will give default value
reduceOnly BOOLEAN NO «true» or «false». Default «false»; Cannot be sent in Hedge Mode; Cannot be sent when you open a position
limitPrice DECIMAL NO Limit price of the order; If it is not sent, will place order by market price by default
recvWindow LONG NO
timestamp LONG YES

Other Info:

  • Total Algo open orders max allowed: 10 orders.
  • Leverage of symbols and position mode will be the same as your futures account settings. You can set up through the trading page or fapi.
  • Receiving "success": true does not mean that your order will be executed. Please use the query order endpoints(GET sapi/v1/algo/futures/openOrders or GET sapi/v1/algo/futures/historicalOrders) to check the order status.
    For example: Your futures balance is insufficient, or open position with reduce only or position side is inconsistent with your own setting. In these cases you will receive "success": true, but the order status will be expired after we check it.
  • quantity * 60 / duration should be larger than minQty
  • duration cannot be less than 5 mins or more than 24 hours.
  • For delivery contracts, TWAP end time should be one hour earlier than the delivery time of the symbol.

Cancel Algo Order (TRADE)

Response:

{
    "algoId": 14511,
    "success": true,
    "code": 0,
    "msg": "OK"
}


DELETE /sapi/v1/algo/futures/order (HMAC SHA256)

Cancel an active order.

Weight(IP):
1

Noted:

  • You need to enable Futures Trading Permission for the api key which requests this endpoint.
  • Base URL: https://api.binance.com

Parameters:

Name Type Mandatory Description
algoId LONG YES eg. 14511
recvWindow LONG NO
timestamp LONG YES

Query Current Algo Open Orders (USER_DATA)

Response:

{
    "total": 1,
    "orders": [
        {
            "algoId": 14517,
            "symbol": "ETHUSDT",
            "side": "SELL",
            "positionSide": "SHORT",
            "totalQty": "5.000",
            "executedQty": "0.000",
            "executedAmt": "0.00000000",
            "avgPrice": "0.00",
            "clientAlgoId": "d7096549481642f8a0bb69e9e2e31f2e",
            "bookTime": 1649756817004,
            "endTime": 0,
            "algoStatus": "WORKING",
            "algoType": "VP",
            "urgency": "LOW"
        }
    ]
}


GET /sapi/v1/algo/futures/openOrders (HMAC SHA256)

Weight(IP):
1

Noted:

  • You need to enable Futures Trading Permission for the api key which requests this endpoint.
  • Base URL: https://api.binance.com

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Query Historical Algo Orders (USER_DATA)

Response:

{
    "total": 1,
    "orders": [
        {
            "algoId": 14518,
            "symbol": "BNBUSDT",
            "side": "BUY",
            "positionSide": "BOTH",
            "totalQty": "100.00",
            "executedQty": "0.00",
            "executedAmt": "0.00000000",
            "avgPrice": "0.000",
            "clientAlgoId": "acacab56b3c44bef9f6a8f8ebd2a8408",
            "bookTime": 1649757019503,
            "endTime": 1649757088101,
            "algoStatus": "CANCELLED",
            "algoType": "VP",
            "urgency": "LOW"
        }
    ]
}


GET /sapi/v1/algo/futures/historicalOrders (HMAC SHA256)

Weight(IP):
1

Noted:

  • You need to enable Futures Trading Permission for the api key which requests this endpoint.
  • Base URL: https://api.binance.com

Parameters:

Name Type Mandatory Description
symbol STRING NO Trading symbol eg. BTCUSDT
side ENUM NO BUY or SELL
startTime LONG NO in milliseconds eg.1641522717552
endTime LONG NO in milliseconds eg.1641522526562
page INT NO Default is 1
pageSize INT NO MIN 1, MAX 100; Default 100
recvWindow LONG NO
timestamp LONG YES

Query Sub Orders (USER_DATA)

Response:

{
    "total": 1,
    "executedQty": "1.000",
    "executedAmt": "3229.44000000",
    "subOrders": [
        {
            "algoId": 13723,
            "orderId": 8389765519993908929,
            "orderStatus": "FILLED",
            "executedQty": "1.000",
            "executedAmt": "3229.44000000",
            "feeAmt": "-1.61471999",
            "feeAsset": "USDT",
            "bookTime": 1649319001964,
            "avgPrice": "3229.44",
            "side": "SELL",
            "symbol": "ETHUSDT",
            "subId": 1,
            "timeInForce": "IMMEDIATE_OR_CANCEL",
            "origQty": "1.000"
        }
    ]
}


GET /sapi/v1/algo/futures/subOrders (HMAC SHA256)

Get respective sub orders for a specified algoId

Weight(IP):
1

Noted:

  • You need to enable Futures Trading Permission for the api key which requests this endpoint.
  • Base URL: https://api.binance.com

Parameters:

Name Type Mandatory Description
algoId LONG YES
page INT NO Default is 1
pageSize INT NO MIN 1, MAX 100; Default 100
recvWindow LONG NO
timestamp LONG YES

Spot Algo Endpoints

Binance Spot Execution Algorithm API solution aims to provide users ability to programmatically leverage Binance in-house algorithmic trading capability to automate order execution strategy, improve execution transparency and give users smart access to the available market liquidity. During the introductory period, there will be no additional fees for TWAP orders. Standard trading fees apply. Order size exceeds to maximum API supported size (100,000 USDT). Please contact liquidity@binance.com for larger sizes.

Time-Weighted Average Price (Twap) New Order (TRADE)

Response:

{
    "clientAlgoId": "65ce1630101a480b85915d7e11fd5078",
    "success": true,
    "code": 0,
    "msg": "OK"
}


POST /sapi/v1/algo/spot/newOrderTwap (HMAC SHA256)

Place a new spot TWAP order with Algo service.

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
symbol STRING YES Trading symbol eg. BTCUSDT
side ENUM YES Trading side ( BUY or SELL )
quantity DECIMAL YES Quantity of base asset; The notional (quantity * last price(base asset)) must be more than the equivalent of 1,000 USDT and less than the equivalent of 100,000 USDT
duration LONG YES Duration for TWAP orders in seconds. [300, 86400]
clientAlgoId STRING NO A unique id among Algo orders (length should be 32 characters), If it is not sent, we will give default value
limitPrice DECIMAL NO Limit price of the order; If it is not sent, will place order by market price by default
recvWindow LONG NO
timestamp LONG YES

Other Info:

  • Total Algo open orders max allowed: 10 orders.

Cancel Algo Order (TRADE)

Response:

{
    "algoId": 14511,
    "success": true,
    "code": 0,
    "msg": "OK"
}


DELETE /sapi/v1/algo/spot/order (HMAC SHA256)

Cancel an open TWAP order

Weight(IP):
1

Parameters:

Name Type Mandatory Description
algoId LONG YES eg. 14511
recvWindow LONG NO
timestamp LONG YES

Query Current Algo Open Orders (USER_DATA)

Response:

{
    "total": 1,
    "orders": [
        {
            "algoId": 14517,
            "symbol": "ETHUSDT",
            "side": "SELL",
            "totalQty": "5.000",
            "executedQty": "0.000",
            "executedAmt": "0.00000000",
            "avgPrice": "0.00",
            "clientAlgoId": "d7096549481642f8a0bb69e9e2e31f2e",
            "bookTime": 1649756817004,
            "endTime": 0,
            "algoStatus": "WORKING",
            "algoType": "TWAP",
            "urgency": "LOW"
        }
    ]
}


GET /sapi/v1/algo/spot/openOrders (HMAC SHA256)

Weight(IP):
1

Get all open SPOT TWAP orders

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Query Historical Algo Orders (USER_DATA)

Response:

{
    "total": 1,
    "orders": [
        {
            "algoId": 14518,
            "symbol": "BNBUSDT",
            "side": "BUY",
            "totalQty": "100.00",
            "executedQty": "0.00",
            "executedAmt": "0.00000000",
            "avgPrice": "0.000",
            "clientAlgoId": "acacab56b3c44bef9f6a8f8ebd2a8408",
            "bookTime": 1649757019503,
            "endTime": 1649757088101,
            "algoStatus": "CANCELLED",
            "algoType": "VP",
            "urgency": "LOW"
        }
    ]
}


GET /sapi/v1/algo/spot/historicalOrders (HMAC SHA256)

Weight(IP):
1

Get all historical SPOT TWAP orders

Parameters:

Name Type Mandatory Description
symbol STRING NO Trading symbol eg. BTCUSDT
side ENUM NO BUY or SELL
startTime LONG NO in milliseconds eg.1641522717552
endTime LONG NO in milliseconds eg.1641522526562
page INT NO Default is 1
pageSize INT NO MIN 1, MAX 100; Default 100
recvWindow LONG NO
timestamp LONG YES

Query Sub Orders (USER_DATA)

Response:

{
    "total": 1,
    "executedQty": "1.000",
    "executedAmt": "3229.44000000",
    "subOrders": [
        {
            "algoId": 13723,
            "orderId": 8389765519993908929,
            "orderStatus": "FILLED",
            "executedQty": "1.000",
            "executedAmt": "3229.44000000",
            "feeAmt": "-1.61471999",
            "feeAsset": "USDT",
            "bookTime": 1649319001964,
            "avgPrice": "3229.44",
            "side": "SELL",
            "symbol": "ETHUSDT",
            "subId": 1,
            "timeInForce": "IMMEDIATE_OR_CANCEL",
            "origQty": "1.000"
        }
    ]
}


GET /sapi/v1/algo/spot/subOrders (HMAC SHA256)

Get respective sub orders for a specified algoId

Weight(IP):
1

Parameters:

Name Type Mandatory Description
algoId LONG YES
page INT NO Default is 1
pageSize INT NO MIN 1, MAX 100; Default 100
recvWindow LONG NO
timestamp LONG YES

Classic Portfolio Margin Endpoints

The Binance Classic Portfolio Margin Program is a cross-asset margin program supporting consolidated margin balance across trading products with over 200+ effective crypto collaterals. It is designed for professional traders, market makers, and institutional users looking to actively trade & hedge cross-asset and optimize risk-management in a consolidated setup.

FAQ: Classic Portfolio Margin Program

Only Classic Portfolio Margin Account is accessible to these endpoints. To enroll, kindly refer to: How to Enroll into the Binance Portfolio Margin Program

Get Classic Portfolio Margin Account Info (USER_DATA)

Response:

{
        "uniMMR": "5167.92171923",        // Classic Portfolio margin account maintenance margin rate
        "accountEquity": "122607.35137903",  // Account equity, unit:USD
        "actualEquity": "142607.35137903",   // Actual equity, unit:USD
        "accountMaintMargin": "23.72469206", // Classic Portfolio margin account maintenance margin, unit:USD
        "accountStatus": "NORMAL"   // Classic Portfolio margin account status:"NORMAL", "MARGIN_CALL", "SUPPLY_MARGIN", "REDUCE_ONLY", "ACTIVE_LIQUIDATION", "FORCE_LIQUIDATION", "BANKRUPTED"
}


GET /sapi/v1/portfolio/account (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Classic Portfolio Margin Collateral Rate (MARKET_DATA)

Response:

[
   {
       "asset": "USDC",
       "collateralRate": "1.0000"
   },
   {
       "asset": "BUSD",
       "collateralRate": "1.0000"
   },
]


GET /sapi/v1/portfolio/collateralRate

Classic Portfolio Margin Collateral Rate

Weight(IP):
50

Parameters:
None

Query Classic Portfolio Margin Bankruptcy Loan Amount (USER_DATA)

Response:

{
        "asset": "BUSD",   
        "amount":  "579.45", // portfolio margin bankruptcy loan amount in BUSD
}


GET /sapi/v1/portfolio/pmLoan

Query Classic Portfolio Margin Bankruptcy Loan Amount

Weight(UID):
500

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES
  • If there’s no classic portfolio margin bankruptcy loan, the amount would be 0

Classic Portfolio Margin Bankruptcy Loan Repay

Response:

{
    "tranId": 58203331886213504
}


POST /sapi/v1/portfolio/repay

Repay Classic Portfolio Margin Bankruptcy Loan

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Query Classic Portfolio Margin Interest History(USER_DATA)

Response:

[
    {
        "asset": "USDT",    
        "interest": "24.4440",               //interest amount
        "interestAccruedTime": 1670227200000,
        "interestRate": "0.0001164",         //daily interest rate
        "principal": "210000",
        "type": "um_negative_balance"
    } 
]


GET /sapi/v1/portfolio/interest-history

Query user’s porfolio margin interest history.

Weight(IP):
50

Parameters:

Name Type Mandatory Description
asset STRING NO
startTime LONG NO
endTime LONG NO
size LONG NO Default:10 Max:100
recvWindow LONG NO
timestamp LONG YES

Query Classic Portfolio Margin Interest Rate (MARKET_DATA)

Response:

[
    {
        "asset": "USDT",    
        "dailyInterest": "0.00012329",    //daily interest rate
        "yearlyInterest": "0.045"         //annual interest rate
    }
]


GET /sapi/v1/portfolio/interest-rate

Query Classic Portfolio Margin Interest Rate

Weight(IP):
50

Parameters:

Name Type Mandatory Description
asset STRING NO
recvWindow LONG NO
timestamp LONG YES

Query Portfolio Margin Asset Index Price (MARKET_DATA)

Response:

[
   {
       "asset": "BTC",
       "assetIndexPrice": "28251.9136906",  // in USD
       "time": 1683518338121
   }
]


GET /sapi/v1/portfolio/asset-index-price

Query Portfolio Margin Asset Index Price

Weight(IP):

1 if send asset or 50 if not send asset

Parameters:

Name Type Mandatory Description
asset STRING NO

BLVT Endpoints

Get BLVT Info (MARKET_DATA)

Response:

[  
  {
    "tokenName": "BTCDOWN",  
    "description": "3X Short Bitcoin Token",
    "underlying": "BTC",
    "tokenIssued": "717953.95",
    "basket": "-821.474 BTCUSDT Futures",
    "currentBaskets":[
       {
         "symbol":"BTCUSDT",
         "amount":"-1183.984",
         "notionalValue":"-22871089.96704"
       }
     ], 
    "nav": "4.79",
    "realLeverage": "-2.316",
    "fundingRate": "0.001020",
    "dailyManagementFee": "0.0001",
    "purchaseFeePct": "0.0010",  
    "dailyPurchaseLimit": "100000.00", 
    "redeemFeePct": "0.0010",  
    "dailyRedeemLimit": "1000000.00",  
    "timestamp":1583127900000  
  },
  {
    "tokenName": "LINKUP",  
    "description": "3X LONG ChainLink Token",
    "underlying": "LINK",
    "tokenIssued": "163846.99",
    "basket": "417288.870 LINKUSDT Futures",
    "currentBaskets":[
       {
         "symbol":"LINKUSDT",
         "amount":"1640883.83",
         "notionalValue":"22596611.22293"
       }
     ], 
    "nav": "9.60",
    "realLeverage": "2.597",
    "fundingRate": "-0.000917",
    "dailyManagementFee": "0.0001",
    "purchaseFeePct": "0.0010",
    "dailyPurchaseLimit": "100000.00",
    "redeemFeePct": "0.0010",
    "dailyRedeemLimit": "1000000.00",
    "timestamp":1583127900000  
  }
 ]

GET /sapi/v1/blvt/tokenInfo

Weight(IP):
1

Parameters:

Name Type Mandatory Description
tokenName STRING NO BTCDOWN, BTCUP

Historical BLVT NAV Kline/Candlestick

The BLVT NAV system is based on Binance Futures, so the endpoint is based on fapi

Please go to here to check the endpoint and operate in accordance with the fapi usage specifications.

Subscribe BLVT (USER_DATA)

Response:

 {
    "id": 123,  
    "status": "S", // S, P, and F for "success", "pending", and "failure"
    "tokenName": "LINKUP",
    "amount": "0.95590905", // subscribed token amount
    "cost": "9.99999995", // subscription cost in usdt
    "timestamp":1600249972899  
 }

POST /sapi/v1/blvt/subscribe (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
tokenName STRING YES BTCDOWN, BTCUP
cost DECIMAL YES spot balance
recvWindow LONG NO
timestamp LONG YES
  • You need to openEnable Spot&Margin Trading permission for the API Key which requests this endpoint.

Query Subscription Record (USER_DATA)

Response:

[  
  {
    "id": 1,  
    "tokenName": "LINKUP",
    "amount": "0.54216292", // Subscription amount
    "nav": "18.42621386", // NAV price of subscription 
    "fee": "0.00999000", // Subscription fee in usdt
    "totalCharge": "9.99999991", // Subscription cost in usdt
    "timestamp":1599127217916  
  }
]

GET /sapi/v1/blvt/subscribe/record (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
tokenName STRING NO BTCDOWN, BTCUP
id LONG NO
startTime LONG NO
endTime LONG NO
limit INT NO default 1000, max 1000
recvWindow LONG NO
timestamp LONG YES
  • Only the data of the latest 90 days is available

Redeem BLVT (USER_DATA)

Response:

 {
    "id": 123,  
    "status": "S", // S, P, and F for "success", "pending", and "failure"
    "tokenName": "LINKUP",
    "redeemAmount": "0.95590905",       // Redemption token amount
    "amount": "10.05022099",    // Redemption value in usdt
    "timestamp":1600250279614  
 }

POST /sapi/v1/blvt/redeem (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
tokenName STRING YES BTCDOWN, BTCUP
amount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to openEnable Spot&Margin Trading permission for the API Key which requests this endpoint.

Query Redemption Record (USER_DATA)

Response:

[  
  {
    "id": 1,  
    "tokenName": "LINKUP",
    "amount": "0.54216292", // Redemption amount
    "nav": "18.36345064",  // NAV of redemption
    "fee": "0.00995598", // Reemption fee
    "netProceed": "9.94602604", // Net redemption value in usdt
    "timestamp":1599128003050  
  }
]

GET /sapi/v1/blvt/redeem/record (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
tokenName STRING NO BTCDOWN, BTCUP
id LONG NO
startTime LONG NO
endTime LONG NO
limit INT NO default 1000, max 1000
recvWindow LONG NO
timestamp LONG YES
  • Only the data of the latest 90 days is available

Get BLVT User Limit Info (USER_DATA)

Response:

[  
  {
    "tokenName": "LINKUP",
    "userDailyTotalPurchaseLimit": "1000", // USDT
    "userDailyTotalRedeemLimit": "1000"    // USDT
  },
  {
    "tokenName": "LINKDOWN",
    "userDailyTotalPurchaseLimit": "1000", // USDT
    "userDailyTotalRedeemLimit": "50000"   // USDT
  } 
]

GET /sapi/v1/blvt/userLimit (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
tokenName STRING NO BTCDOWN, BTCUP
recvWindow LONG NO
timestamp LONG YES

Websocket BLVT Info Streams

Payload:

{
    "e":"nav",      // Event type
    "E":1600245286355,  // Event time
    "s":"TRXDOWN",  // BLVT name
    "m":74164.75496502663,  // Token issued
    "b":[   // Baskets
        {
            "s":"TRXUSDT",  // futures symbol
            "n":-87988261       // position
        }
    ],
    "n":14.78454447,        // BLVT NAV
    "l":2.1786579638117898,      // Real leverage
    "t":3,      // Target leverage
    "f":-0.0048925  // Funding ratio
}

Stream Name: <tokenName>@tokenNav

  • Note: You should use the base url:wss://nbstream.binance.com/lvt-p for this stream
  • Note: tokenName must be uppercase, e.g. «TRXDOWN@tokenNav»

Update Speed: 3s

Websocket BLVT NAV Kline/Candlestick Streams

Payload:

{
    "e":"kline",    // Event name
    "E":1600243159447,  // Event time
    "s":"TRXDOWN",  // BLVT name
    "k":{
        "t":1600243140000,  // Kline start time
        "T":1600243199999,  // Kline close time
        "s":"TRXDOWN",  // BLVT name
        "i":"1m",   // Interval
        "f":1600243140484,  // First NAV update time
        "L":1600243159424,  // Last NAV update time
        "o":"14.56800297",  // Open NAV price
        "c":"14.59766270",  // CLose NAV price
        "h":"14.63325437",  // Highest NAV price
        "l":"14.56207102",  // Lowest NAV price
        "v":"2.22524220",   // Real leverage
        "n":33, // Number of NAV update
        "x":false,  // Ignore
        "q":"0",    // Ignore
        "V":"73.42663923",  // Ignore
        "Q":"0",    // Ignore
        "B":"0" // Ignore
   }
}

Stream Name: <tokenName>@nav_kline_<interval>

  • Note: You should use the base url:wss://nbstream.binance.com/lvt-p for this stream
  • Note: tokenName must be uppercase, e.g. «TRXDOWN@nav_kline_1d»

Update Speed: 300ms

Kline/Candlestick chart intervals:

m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

  • 1m
  • 3m
  • 5m
  • 15m
  • 30m
  • 1h
  • 2h
  • 4h
  • 6h
  • 8h
  • 12h
  • 1d
  • 3d
  • 1w
  • 1M

BSwap Endpoints

  • The endpoints below allow you to interact with BSwap.
  • For more information on this, please refer to the BSwap page

List All Swap Pools (MARKET_DATA)

Response:

[
    {
        "poolId": 2,
        "poolName": "BUSD/USDT",
        "assets": [
            "BUSD",
            "USDT"
        ]
    },
    {
        "poolId": 3,
        "poolName": "BUSD/DAI",
        "assets": [
            "BUSD",
            "DAI"
        ]
    },
    {
        "poolId": 4,
        "poolName": "USDT/DAI",
        "assets": [
            "USDT",
            "DAI"
        ]
    }
]


GET /sapi/v1/bswap/pools

Get metadata about all swap pools.

Weight(IP):
1

Parameters:

None

Get liquidity information of a pool (USER_DATA)

Response:

[
    {
        "poolId": 2,
        "poolNmae": "BUSD/USDT",
        "updateTime": 1565769342148,
        "liquidity": {
            "BUSD": 100000315.79,
            "USDT": 99999245.54
        },
        "share": {
            "shareAmount": 12415,
            "sharePercentage": 0.00006207,
            "asset": {
                "BUSD": 6207.02,
                "USDT": 6206.95
            }
        }
    }
]


GET /sapi/v1/bswap/liquidity (HMAC SHA256)

Get liquidity information and user share of a pool.

Weight(IP):

1 for one pool

10 when the poolId parameter is omitted

Rate Limit:
3/1s per account and per pool

Parameter:

Name Type Mandatory Description
poolId LONG NO
recvWindow LONG NO
timestamp LONG YES

Add Liquidity (TRADE)

Response:

{
    "operationId": 12341
}


POST /sapi/v1/bswap/liquidityAdd (HMAC SHA256)

Add liquidity to a pool.

Weight(UID):
1000 (Additional: 1 request every two seconds per pool and per account)

Parameter:

Name Type Mandatory Description
poolId LONG YES
type STRING NO «SINGLE» to add a single token; «COMBINATION» to add dual tokens. Default «SINGLE»
asset STRING YES
quantity DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Remove Liquidity (TRADE)

Response:

{
    "operationId": 12341
}


POST /sapi/v1/bswap/liquidityRemove (HMAC SHA256)

Remove liquidity from a pool, type include SINGLE and COMBINATION, asset is mandatory for single asset removal

Weight(UID):
1000 (Additional: 1 request every two seconds per pool and per account)

Parameters:

Name Type Mandatory Description
poolId LONG YES
type STRING YES SINGLE for single asset removal, COMBINATION for combination of all coins removal
asset LIST NO Mandatory for single asset removal
shareAmount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Get Liquidity Operation Record (USER_DATA)

Response:

[
    {
        "operationId": 12341,
        "poolId": 2,
        "poolName": "BUSD/USDT",
        "operation": "ADD", // "ADD" or "REMOVE"
        "status": 1, // 0: pending, 1: success, 2: failed 
        "updateTime": 1565769342148,
        "shareAmount": "10.1"
    }
]


GET /sapi/v1/bswap/liquidityOps (HMAC SHA256)

Get liquidity operation (add/remove) records.

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
operationId LONG NO
poolId LONG NO
operation ENUM NO ADD or REMOVE
startTime LONG NO
endTime LONG NO
limit LONG NO default 3, max 100
recvWindow LONG NO
timestamp LONG YES

Request Quote (USER_DATA)

Response:

{
    "quoteAsset": "USDT",
    "baseAsset": "BUSD",
    "quoteQty": 300000,
    "baseQty": 299975,
    "price": 1.00008334,
    "slippage": 0.00007245,
    "fee": 120
}


GET /sapi/v1/bswap/quote (HMAC SHA256)

Request a quote for swap quote asset (selling asset) for base asset (buying asset), essentially price/exchange rates.

quoteQty is quantity of quote asset (to sell).

Please be noted the quote is for reference only, the actual price will change as the liquidity changes, it’s recommended to swap immediate after request a quote for slippage prevention.

Weight(UID):
150

Rate Limit:
3/1s per account and per pool

Parameters:

Name Type Mandatory Description
quoteAsset STRING YES
baseAsset STRING YES
quoteQty DECIMAL YES
recvWindow LONG NO
timestamp LONG YES

Swap (TRADE)

Response:

{
    "swapId": 2314
}


POST /sapi/v1/bswap/swap (HMAC SHA256)

Swap quoteAsset for baseAsset.

Weight(UID):
1000 (Additional: 1 request every two seconds per pool)

Parameters:

Name Type Mandatory Description
quoteAsset STRING YES
baseAsset STRING YES
quoteQty DECIMAL YES
recvWindow LONG NO
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Get Swap History (USER_DATA)

Response:

[
    {
        "swapId": 2314,
        "swapTime": 1565770342148,
        "status": 0, // 0: pending, 1: success, 2: failed 
        "quoteAsset": "USDT",
        "baseAsset": "BUSD",
        "quoteQty": 300000,
        "baseQty": 299975,
        "price": 1.00008334,
        "fee": 120
    }
]


GET /sapi/v1/bswap/swap (HMAC SHA256)

Get swap history.

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
swapId LONG NO
startTime LONG NO
endTime LONG NO
status INT NO 0: pending for swap, 1: success, 2: failed
quoteAsset STRING NO
baseAsset STRING NO
limit LONG NO default 3, max 100
recvWindow LONG NO
timestamp LONG YES

Get Pool Configure (USER_DATA)

Response:

[
    {
        "poolId": 2,
        "poolNmae": "BUSD/USDT",
        "updateTime": 1565769342148,
        "liquidity": {
            "constantA": 2000, //"NA" if pool is an innovation pool
            "minRedeemShare": 0.1,
            "slippageTolerance":0.2 //The swap proceeds only when the slippage is within the set range
        },   
        "assetConfigure":{
            "BUSD": {
                "minAdd":10,
                "maxAdd": 20, 
                "minSwap": 10,
                "maxSwap": 30            
            },
            "USDT": {
                "minAdd":10,
                "maxAdd": 20, 
                "minSwap": 10,
                "maxSwap": 30   
            }
        }
    }
]


GET /sapi/v1/bswap/poolConfigure (HMAC SHA256)

Weight(IP):
150

Parameters:

Name Type Mandatory Description
poolId LONG NO
recvWindow LONG NO
timestamp LONG YES

Add Liquidity Preview (USER_DATA)

Response:

{
        "quoteAsset": "USDT",
        "baseAsset": "BUSD", //Display when type is "COMBINATION"
        "quoteAmt": 300000,
        "baseAmt": 299975, // Display when type is "COMBINATION" 
        "price": 1.00008334,
        "share":1.23,
        "slippage": 0.00007245, //Display when type is "SINGLE" 
        "fee": 120, //Display when type is "SINGLE" 
}


GET /sapi/v1/bswap/addLiquidityPreview (HMAC SHA256)

Calculate expected share amount for adding liquidity in single or dual token.

Weight(IP):
150

Parameters:

Name Type Mandatory Description
poolId LONG YES
type STRING YES «SINGLE» for adding a single token;»COMBINATION» for adding dual tokens
quoteAsset STRING YES
quoteQty DECIMAL YES
recvWindow LONG NO
timestamp LONG YES

Remove Liquidity Preview (USER_DATA)

Response:

{
        "quoteAsset": "USDT",
        "baseAsset": "BUSD", //Display when type is "COMBINATION" 
        "quoteAmt": 300000,
        "baseAmt": 299975, //Display when type is "COMBINATION" 
        "price": 1.00008334,
        "slippage": 0.00007245, //Display when type is "SINGLE" 
        "fee": 120 //Display when type is "SINGLE" 
}


GET /sapi/v1/bswap/removeLiquidityPreview (HMAC SHA256)

Calculate the expected asset amount of single token redemption or dual token redemption.

Weight(IP):
150

Parameters:

Name Type Mandatory Description
poolId LONG YES
type STRING YES Type is «SINGLE», remove and obtain a single token;Type is «COMBINATION», remove and obtain dual token.
quoteAsset STRING YES
shareAmount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES

Get Unclaimed Rewards Record (USER_DATA)

Response:

{
        "totalUnclaimedRewards": {         
            "BUSD": 100000315.79,
            "BNB": 0.00000001,
            "USDT": 0.00000002                              
         },         
    "details":{
            "BNB/USDT":{
                "BUSD": 100000315.79,
                "USDT": 0.00000002                        
                },
            "BNB/BTC":{
                "BNB": 0.00000001
                } 
        }
}



GET /sapi/v1/bswap/unclaimedRewards (HMAC SHA256)

Get unclaimed rewards record.

Weight(UID):
1000

Parameters:

Name Type Mandatory Description
type INT NO 0: Swap rewards,1:Liquidity rewards, default to 0
recvWindow LONG NO
timestamp LONG YES

Claim Rewards (TRADE)

Response:

{
    "success":true
}


POST /sapi/v1/bswap/claimRewards (HMAC SHA256)

Claim swap rewards or liquidity rewards

Weight(UID):
1000

Parameters:

Name Type Mandatory Description
type INT NO 0: Swap rewards,1:Liquidity rewards, default to 0
recvWindow LONG NO
timestamp LONG YES
  • You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

Get Claimed History (USER_DATA)

Response:

[
    {
        "poolId":52,  
        "poolName":"BNB/USDT",                     
        "assetRewards": "BNB",
        "claimTime":1565769342148,             
        "claimAmount":0.00000023,
        "status":1 // 0: pending, 1: success
    }
]



GET /sapi/v1/bswap/claimedHistory (HMAC SHA256)

Get history of claimed rewards.

Weight(UID):
1000

Parameters:

Name Type Mandatory Description
poolId LONG NO
assetRewards STRING NO
type INT NO 0: Swap rewards,1:Liquidity rewards, default to 0
startTime LONG NO
endTime LONG NO
limit LONG NO Default 3, max 100
recvWindow LONG NO
timestamp LONG YES

Fiat Endpoints

Get Fiat Deposit/Withdraw History (USER_DATA)

Response:

{
   "code": "000000",
   "message": "success",
   "data": [
   {
      "orderNo":"7d76d611-0568-4f43-afb6-24cac7767365",
      "fiatCurrency": "BRL",
      "indicatedAmount": "10.00",  
      "amount": "10.00", 
      "totalFee": "0.00",   // Trade fee
      "method": "BankAccount",  // Trade method
      "status": "Expired",  // Processing, Failed, Successful, Finished, Refunding, Refunded, Refund Failed, Order Partial credit Stopped
      "createTime": 1626144956000,
      "updateTime": 1626400907000   
   }
   ],
   "total": 1,
   "success": true
}


GET /sapi/v1/fiat/orders (HMAC SHA256)

Weight(UID):
90000

Parameters:

Name Type Mandatory Description
transactionType STRING YES 0-deposit,1-withdraw
beginTime LONG NO
endTime LONG NO
page INT NO default 1
rows INT NO default 100, max 500
recvWindow LONG NO
timestamp LONG YES
  • If beginTime and endTime are not sent, the recent 30-day data will be returned.

Get Fiat Payments History (USER_DATA)

Response:

{
   "code": "000000",
   "message": "success",
   "data": [
   {
      "orderNo": "353fca443f06466db0c4dc89f94f027a",
      "sourceAmount": "20.0",  // Fiat trade amount
      "fiatCurrency": "EUR",   // Fiat token
      "obtainAmount": "4.462", // Crypto trade amount
      "cryptoCurrency": "LUNA",  // Crypto token
      "totalFee": "0.2",     // Trade fee
      "price": "4.437472", 
      "status": "Failed",  // Processing, Completed, Failed, Refunded
      "paymentMethod": "Credit Card",
      "createTime": 1624529919000,
      "updateTime": 1624529919000  
   }
   ],
   "total": 1,
   "success": true
}


GET /sapi/v1/fiat/payments (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
transactionType STRING YES 0-buy,1-sell
beginTime LONG NO
endTime LONG NO
page INT NO default 1
rows INT NO default 100, max 500
recvWindow LONG NO
timestamp LONG YES
  • If beginTime and endTime are not sent, the recent 30-day data will be returned.
  • paymentMethod: Only when requesting payments history for buy (transactionType=0), response contains paymentMethod representing the way of purchase. Now we have:
    • Cash Balance
    • Credit Card
    • Online Banking
    • Bank Transfer

C2C Endpoints

Get C2C Trade History (USER_DATA)

Response:

{
   "code": "000000",
   "message": "success",
   "data": [
   {
      "orderNumber":"20219644646554779648",
      "advNo": "11218246497340923904",
      "tradeType": "SELL",  
      "asset": "BUSD", 
      "fiat": "CNY",  
      "fiatSymbol": "¥",
      "amount": "5000.00000000",  // Quantity (in Crypto)
      "totalPrice": "33400.00000000",
      "unitPrice": "6.68", // Unit Price (in Fiat)
      "orderStatus": "COMPLETED",  // PENDING, TRADING, BUYER_PAYED, DISTRIBUTING, COMPLETED, IN_APPEAL, CANCELLED, CANCELLED_BY_SYSTEM
      "createTime": 1619361369000,
      "commission": "0",   // Transaction Fee (in Crypto)
      "counterPartNickName": "ab***",
      "advertisementRole": "TAKER"        
     }
   ],
   "total": 1,
   "success": true
}


GET /sapi/v1/c2c/orderMatch/listUserOrderHistory (HMAC SHA256)

Weight(IP):
1

Parameters:

Name Type Mandatory Description
tradeType STRING YES BUY, SELL
startTimestamp LONG NO
endTimestamp LONG NO
page INT NO default 1
rows INT NO default 100, max 100
recvWindow LONG NO
timestamp LONG YES
  • If startTimestamp and endTimestamp are not sent, the recent 30-day data will be returned.
  • The max interval between startTimestamp and endTimestamp is 30 days.
  • Only the last 6 months of data can be retrieved. To view the complete P2P order history, you can download it from https://c2c.binance.com/en/fiatOrder

VIP Loans Endpoints

Get VIP Loan Ongoing Orders (USER_DATA)

Response:

{
  "rows": [
    {
      "orderId": 100000001,
      "loanCoin": "BUSD",
      "totalDebt": "10000",
      "residualInterest": "10.27687923",
      "collateralAccountId": "12345678", "23456789",
      "collateralCoin": "BNB,BTC,ETH",
      "totalCollateralValueAfterHaircut": "25000.27565492", 
      "lockedCollateralValue": "25000.27565492", 
      "currentLTV": "0.57",
      "expirationTime": 1575018510000
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/vip/ongoing/orders

VIP loan is available for VIP users only.

Weight(IP):
400

Parameters:

Name Type Mandatory Description
orderId LONG NO
collateralAccountId LONG NO
loanCoin STRING NO
collateralCoin STRING NO
current LONG NO Currently querying page. Start from 1, Default:1, Max: 1000.
limit LONG NO Default: 10, Max: 100
recvWindow LONG NO
timestamp LONG YES

VIP Loan Repay (TRADE)

Response:

{
  "loanCoin": "BUSD",
  "repayAmount": "200.5",
  "remainingPrincipal": "100.5",
  "remainingInterest": "0",
  "collateralCoin": "BNB,BTC,ETH",
  "currentLTV": "0.25",
  "repayStatus": "Repaid" // Repaid, Repaying, Failed
}


POST /sapi/v1/loan/vip/repay

VIP loan is available for VIP users only.

Weight(UID):
6000

Parameters:

Name Type Mandatory Description
orderId LONG YES
amount DECIMAL YES
recvWindow LONG NO
timestamp LONG YES

Get VIP Loan Repayment History (USER_DATA)

Response:

{
  "rows": [
    {
      "loanCoin": "BUSD",
      "repayAmount": "10000",
      "collateralCoin": "BNB,BTC,ETH",
      "repayStatus": "Repaid", // Repaid, Repaying, Failed
      "repayTime": "1575018510000",
      "orderId": "756783308056935434"
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/vip/repay/history

VIP loan is available for VIP users only.

Weight(IP):
400

Parameters:

Name Type Mandatory Description
orderId LONG NO
loanCoin STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Currently querying page. Start from 1, Default:1, Max: 1000
limit LONG NO Default: 10, Max: 100
recvWindow LONG NO
timestamp LONG YES
  • If startTime and endTime are not sent, the recent 90-day data will be returned
  • The max interval between startTime and end Time is 180 days.

Check Locked Value of VIP Collateral Account (USER_DATA)

Response:

{
  "rows": [
    {
      "collateralAccountId": "12345678",
      "collateralCoin": "BNB,BTC,ETH",
      "collateralValue": "500.27565492" // locked collateral value shown in USD value
    }
  ],
  [
    {
      "collateralAccountId": "23456789",
      "collateralCoin": "BNB,BTC,ETH",
      "collateralValue": "25000.238752" // locked collateral value shown in USD value
    }
  ],
  "total": 2
}


GET /sapi/v1/loan/vip/collateral/account

VIP loan is available for VIP users only.

Weight(IP):
6000

Parameters:

Name Type Mandatory Description
orderId LONG NO
collateralAccountId LONG NO
recvWindow LONG NO
timestamp LONG YES
  • If the login account is loan account, frozen value of all collateral accounts under the loan account can be queried.
  • If the login account is collateral account, only the frozen amount of current collateral account can be queried.

Crypto Loans Endpoints

Get Crypto Loans Income History (USER_DATA)

Response:

[
   {
        "asset": "BUSD",
        "type": "borrowIn",
        "amount": "100",
        "timestamp": 1633771139847,
        "tranId": "80423589583"
    },
    {
        "asset": "BUSD",
        "type": "borrowIn",
        "amount": "100",
        "timestamp": 1634638371496,
        "tranId": "81685123491"
    }
 ]


GET /sapi/v1/loan/income (HMAC SHA256)

Weight(UID):
6000

Parameters:

Name Type Mandatory Description
asset STRING NO
type STRING NO All types will be returned by default. Enum:borrowIn ,collateralSpent, repayAmount, collateralReturn(Collateral return after repayment), addCollateral, removeCollateral, collateralReturnAfterLiquidation
startTime LONG NO
endTime LONG NO
limit INT NO default 20, max 100
recvWindow LONG NO
timestamp LONG YES
  • If startTime and endTime are not sent, the recent 7-day data will be returned.
  • The max interval between startTime and endTime is 30 days.

Borrow — Crypto Loan Borrow (TRADE)

Response:

{
  "loanCoin": "BUSD",
  "loanAmount": "100.5",
  "collateralCoin": "BNB",
  "collateralAmount": "50.5",
  "hourlyInterestRate": "0.001234",
  "orderId": "100000001"
}


POST /sapi/v1/loan/borrow

Weight(UID):
6000

Parameters:

Name Type Mandatory Description
loanCoin STRING YES
loanAmount DECIMAL NO Mandatory when collateralAmount is empty
collateralCoin STRING YES
collateralAmount DECIMAL NO Mandatory when loanAmount is empty
loanTerm INT YES 7/30 days
recvWindow LONG NO
timestamp LONG YES

Borrow — Get Loan Borrow History (USER_DATA)

Response:

{
  "rows": [
    {
    "orderId": 100000001,
    "loanCoin": "BUSD",
    "initialLoanAmount": "10000",
    "hourlyInterestRate": "0.000057"
    "loanTerm": "7"
    "collateralCoin": "BNB",
    "initialCollateralAmount": "49.27565492"
    "borrowTime": 1575018510000
    "status": "Repaid" // Accruing_Interest, Overdue, Liquidating, Repaying, Repaid, Liquidated, Pending, Failed
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/borrow/history

Weight(IP):
400

Parameters:

Name Type Mandatory Description
orderId LONG NO orderId in POST /sapi/v1/loan/borrow
loanCoin STRING NO
collateralCoin STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Current querying page. Start from 1; default: 1; max: 1000.
limit LONG NO Default: 10; max: 100.
recvWindow LONG NO
timestamp LONG YES
  • If startTime and endTime are not sent, the recent 90-day data will be returned.
  • The max interval between startTime and endTime is 180 days.

Borrow — Get Loan Ongoing Orders (USER_DATA)

Response:

{
  "rows": [
    {
    "orderId": 100000001,
    "loanCoin": "BUSD",
    "totalDebt": "10000",
    "residualInterest":"10.27687923"
    "collateralCoin": "BNB",
    "collateralAmount": "49.27565492"
    "currentLTV": "0.57"
    "expirationTime": 1575018510000
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/ongoing/orders

Weight(IP):
300

Parameters:

Name Type Mandatory Description
orderId LONG NO orderId in POST /sapi/v1/loan/borrow
loanCoin STRING NO
collateralCoin STRING NO
current LONG NO Current querying page. Start from 1; default: 1; max: 1000
limit LONG NO Default: 10; max: 100
recvWindow LONG NO
timestamp LONG YES

Repay — Crypto Loan Repay (TRADE)

Response:

{
  "loanCoin": "BUSD"
  "remainingPrincipal": "100.5"
  "remainingInterest": "0"
  "collateralCoin": "BNB"
  "remainingCollateral": "5.253"
  "currentLTV": "0.25"
  "repayStatus": "Repaid" // Repaid, Repaying
}

or

{
  "loanCoin": "BUSD"
  "collateralCoin": "BNB"
  "repayStatus": "Repaying" // Repaid, Repaying
}


POST /sapi/v1/loan/repay

Weight(UID):
6000

Parameters:

Name Type Mandatory Description
orderId LONG YES
amount DECIMAL YES
type INT NO Default: 1. 1 for «repay with borrowed coin»; 2 for «repay with collateral».
collateralReturn BOOLEAN NO Default: TRUE. TRUE: Return extra collateral to spot account; FALSE: Keep extra collateral in the order.
recvWindow LONG NO
timestamp LONG YES

Repay — Get Loan Repayment History (USER_DATA)

Response:

{
  "rows": [
    {
    "loanCoin": "BUSD",
    "repayAmount": "10000",
    "collateralCoin": "BNB",
    "collateralUsed": "0"
    "collateralReturn": "49.27565492"
    "repayType": "1" // 1 for "repay with borrowed coin", 2 for "repay with collateral"
    "repayStatus": "Repaid" // Repaid, Repaying, Failed
    "repayTime": 1575018510000
    "orderId": 756783308056935434
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/repay/history

Weight(IP):
400

Parameters:

Name Type Mandatory Description
orderId LONG NO
loanCoin STRING NO
collateralCoin STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Current querying page. Start from 1; default: 1; max: 1000
limit LONG NO Default: 10; max: 100
recvWindow LONG NO
timestamp LONG YES
  • If startTime and endTime are not sent, the recent 90-day data will be returned.
  • The max interval between startTime and endTime is 180 days.

Adjust LTV — Crypto Loan Adjust LTV (TRADE)

Response:

{
  "loanCoin": "BUSD",
  "collateralCoin": "BNB",
  "direction": "ADDITIONAL",
  "amount": "5.235",
  "currentLTV": "0.52"
}


POST /sapi/v1/loan/adjust/ltv

Weight(UID):
6000

Parameters:

Name Type Mandatory Description
orderId LONG YES
amount DECIMAL YES
direction ENUM YES «ADDITIONAL», «REDUCED»
recvWindow LONG NO
timestamp LONG YES

Adjust LTV — Get Loan LTV Adjustment History (USER_DATA)

Response:

{
  "rows": [
    {
    "loanCoin": "BUSD",
    "collateralCoin": "BNB",
    "direction": "ADDITIONAL",
    "amount": "5.235",
    "preLTV": "0.78",
    "afterLTV": "0.56",
    "adjustTime": 1575018510000,
    "orderId": 756783308056935434
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/ltv/adjustment/history

Weight(IP):
400

Parameters:

Name Type Mandatory Description
orderId LONG NO
loanCoin STRING NO
collateralCoin STRING NO
startTime LONG NO
endTime LONG NO
current LONG NO Current querying page. Start from 1; default: 1; max: 1000
limit LONG NO Default: 10; max: 100
recvWindow LONG NO
timestamp LONG YES
  • If startTime and endTime are not sent, the recent 90-day data will be returned.
  • The max interval between startTime and endTime is 180 days.

Get Loanable Assets Data (USER_DATA)

Response:

{
  "rows": [
    {
      "loanCoin": "BUSD",
      "_7dHourlyInterestRate": "0.00000491",
      "_7dDailyInterestRate": "0.000118",
      "_14dHourlyInterestRate": "0.00000491",
      "_14dDailyInterestRate": "0.000118",
      "_30dHourlyInterestRate": "0.00000567",
      "_30dDailyInterestRate": "0.000136",
      "_90dHourlyInterestRate": "0.00000596",
      "_90dDailyInterestRate": "0.000143",
      "_180dHourlyInterestRate": "0.00000631",
      "_180dDailyInterestRate": "0.000151",
      "minLimit": "100"
      "maxLimit": "1000000"
      "vipLevel": 1
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/loanable/data

Get interest rate and borrow limit of loanable assets. The borrow limit is shown in USD value.

Weight(IP):
400

Parameters:

Name Type Mandatory Description
loanCoin STRING NO
vipLevel INT NO Default: user’s vip level. Send «-1» to check specified configuration
recvWindow LONG NO
timestamp LONG YES

Get Collateral Assets Data (USER_DATA)

Response:

{
  "rows": [
    {
      "collateralCoin": "BNB",
      "initialLTV": "0.65",
      "marginCallLTV": "0.75",
      "liquidationLTV": "0.83",
      "maxLimit": "1000000"
      "vipLevel": 1
    }
  ],
  "total": 1
}


GET /sapi/v1/loan/collateral/data

Get LTV information and collateral limit of collateral assets. The collateral limit is shown in USD value.

Weight(IP):
400

Parameters:

Name Type Mandatory Description
collateralCoin STRING NO
vipLevel INT NO Default: user’s vip level. Send «-1» to check specified configuration
recvWindow LONG NO
timestamp LONG YES

Check Collateral Repay Rate (USER_DATA)

Response:

{
  "loanlCoin": "BUSD",
  "collateralCoin": "BNB",
  "repayAmount": "1000",
  "rate": "300.36781234" // rate of collateral coin/loan coin
}


GET /sapi/v1/loan/repay/collateral/rate

Get the the rate of collateral coin / loan coin when using collateral repay, the rate will be valid within 8 second.

Weight(IP):
6000

Parameters:

Name Type Mandatory Description
loanCoin STRING YES
collateralCoin STRING YES
repayAmount DECIMAL YES repay amount of loanCoin
recvWindow LONG NO
timestamp LONG YES

Crypto Loan Customize Margin Call (TRADE)

Response:

{
  "rows": [
    {
    "orderId": "100000001"
    "collateralCoin": "BNB"
    "preMarginCall": "0.8"
    "afterMarginCall": "0.7"
    "customizeTime": 1575018510000
    }
  ],
  "total": 1
}


POST /sapi/v1/loan/customize/margin_call

Customize margin call for ongoing orders only.

Weight(UID):
6000

Parameters:

Name Type Mandatory Description
orderId LONG NO Mandatory when collateralCoin is empty. Send either orderId or collateralCoin, if both parameters are sent, take orderId only.
collateralCoin STRING NO Mandatory when orderID is empty. Send either orderId or collateralCoin, if both parameters are sent, take orderId only.
marginCall DECIMAL YES
recvWindow LONG NO
timestamp LONG YES

Pay Endpoints

Get Pay Trade History (USER_DATA)

Response:

{
   "code": "000000",
   "message": "success",
   "data": [
   {
       "orderType": "C2C", // Enum:PAY(C2B Merchant Acquiring Payment), PAY_REFUND(C2B Merchant Acquiring Payment,refund), C2C(C2C Transfer Payment),CRYPTO_BOX(Crypto box), CRYPTO_BOX_RF(Crypto Box, refund), C2C_HOLDING(Transfer to new Binance user), C2C_HOLDING_RF(Transfer to new Binance user,refund), PAYOUT(B2C Disbursement Payment)
       "transactionId": "M_P_71505104267788288",  
       "transactionTime": 1610090460133, //trade timestamp
       "amount": "23.72469206", //order amount(up to 8 decimal places), positive is income, negative is expenditure
       "currency": "BNB",
       "walletType": 1, // 1 for funding wallet and 2 for spot wallet 
       "fundsDetail": [ // details
               {
                "currency": "USDT", //asset 
                "amount": "1.2" 
                },
                {
                 "currency": "ETH",
                 "amount": "0.0001"
                }
          ]
     }
   ],
  "success": true
}


GET /sapi/v1/pay/transactions (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
startTime LONG NO
endTime LONG NO
limit INT NO default 100, max 100
recvWindow LONG NO
timestamp LONG YES
  • If startTime and endTime are not sent, the recent 90 days’ data will be returned.
  • The max interval between startTime and endTime is 90 days.
  • Support for querying orders within the last 18 months.

Convert Endpoints

Would you like to have access to Binance Convert API? Please complete the questionnaire to submit your request for access. The Convert API service is created for users who wish to automate their trading on Binance Convert. You will receive a confirmation email after we have approved your application.

Note: All users of this service are subject to the Binance Terms of Use and the use of the API services is not suitable for purposes including price arbitrage, high frequency trading or price exploitation. Binance may restrict or terminate a Binance API Connection at any time for any reason in its sole discretion and is not obliged to provide any prior notice to the User of any such restriction or termination or any reason therefore.

List All Convert Pairs

Response:

[
  {
    "fromAsset":"BTC",
    "toAsset":"USDT",
    "fromAssetMinAmount":"0.0004",
    "fromAssetMaxAmount":"50",
    "toAssetMinAmount":"20",
    "toAssetMaxAmount":"2500000"
  }
]


GET /sapi/v1/convert/exchangeInfo

Query for all convertible token pairs and the tokens’ respective upper/lower limits

Weight(IP):
3000

Parameters:

Name Type Mandatory Description
fromAsset STRING EITHER OR BOTH User spends coin
toAsset STRING EITHER OR BOTH User receives coin
  • User needs to supply either or both of the input parameter
  • If not defined for both fromAsset and toAsset, only partial token pairs will be returned

Query order quantity precision per asset (USER_DATA)

Response:

[
  {
    "asset": "BTC", 
    "fraction": 8
  },
  {
    "asset": "SHIB", 
    "fraction": 2
  }
]


GET /sapi/v1/convert/assetInfo

Query for supported asset’s precision information

Weight(IP):
100

Parameters:

Name Type Mandatory Description
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Send quote request (USER_DATA)

Response:

{
   "quoteId":"12415572564",
   "ratio":"38163.7",
   "inverseRatio":"0.0000262",
   "validTimestamp":1623319461670,
   "toAmount":"3816.37",
   "fromAmount":"0.1"
}


POST /sapi/v1/convert/getQuote

Request a quote for the requested token pairs

Weight(UID):
200

Parameters:

Name Type Mandatory Description
fromAsset STRING YES
toAsset STRING YES
fromAmount DECIMAL EITHER When specified, it is the amount you will be debited after the conversion
toAmount DECIMAL EITHER When specified, it is the amount you will be credited after the conversion
walletType ENUM NO SPOT or FUNDING. Default is SPOT
validTime ENUM NO 10s, 30s, 1m, 2m, default 10s
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
  • Either fromAmount or toAmount should be sent
  • quoteId will be returned only if you have enough funds to convert

Accept Quote (TRADE)

Response:

{
  "orderId":"933256278426274426",
  "createTime":1623381330472,
  "orderStatus":"PROCESS" //PROCESS/ACCEPT_SUCCESS/SUCCESS/FAIL
}


POST /sapi/v1/convert/acceptQuote

Accept the offered quote by quote ID.

Weight(UID):
500

Parameters:

Name Type Mandatory Description
quoteId STRING YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Order status (USER_DATA)

Response:

{
  "orderId":933256278426274426,
  "orderStatus":"SUCCESS",
  "fromAsset":"BTC",
  "fromAmount":"0.00054414",
  "toAsset":"USDT",
  "toAmount":"20",
  "ratio":"36755",
  "inverseRatio":"0.00002721",
  "createTime":1623381330472
}


GET /sapi/v1/convert/orderStatus

Query order status by order ID.

Weight(UID):
100

Parameters:

Name Type Mandatory Description
orderId STRING NO Either orderId or quoteId is required
quoteId STRING NO Either orderId or quoteId is required

Get Convert Trade History (USER_DATA)

Response:

{
   "list": [
        {
            "quoteId": "f3b91c525b2644c7bc1e1cd31b6e1aa6",
            "orderId": 940708407462087195,  
            "orderStatus": "SUCCESS",  // order status
            "fromAsset": "USDT",       // from asset
            "fromAmount": "20",        // from amount
            "toAsset": "BNB",          // to asset
            "toAmount": "0.06154036",  // to amount
            "ratio": "0.00307702",     // price ratio
            "inverseRatio": "324.99",  // inverse price 
            "createTime": 1624248872184
        }
   ],
    "startTime": 1623824139000,
    "endTime": 1626416139000,
    "limit": 100,
    "moreData": false
}


GET /sapi/v1/convert/tradeFlow (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
startTime LONG YES
endTime LONG YES
limit INT NO Default 100, Max 1000
recvWindow LONG NO
timestamp LONG YES
  • The max interval between startTime and endTime is 30 days.

Rebate Endpoints

Get Spot Rebate History Records (USER_DATA)

Response:

{
   "status": "OK",
   "type": "GENERAL",
   "code": "000000000",
   "data": {
        "page": 1,  // current page
        "totalRecords": 2,  // total records
        "totalPageNum": 1,  // total pages
        "data": [
            {
                "asset": "USDT",  // rebate asset
                "type": 1,        // rebate type:1 is commission rebate,2 is referral kickback
                "amount": "0.0001126", 
                "updateTime": 1637651320000
            },
            {
                "asset": "ETH",
                "type": 1,
                "amount": "0.00000056",
                "updateTime": 1637928379000
            }
        ]
    }

}


GET /sapi/v1/rebate/taxQuery (HMAC SHA256)

Weight(UID):
12000

Parameters:

Name Type Mandatory Description
startTime LONG NO
endTime LONG NO
page INT NO Default 1
recvWindow LONG NO
timestamp LONG YES
  • The max interval between startTime and endTime is 30 days.
  • If startTime and endTime are not sent, the recent 7 days’ data will be returned.
  • The earliest startTime is supported on June 10, 2020

NFT Endpoints

Get NFT Transaction History (USER_DATA)

Response:

{
  "total": 2,  //total records
  "list": [
    {
      "orderNo": "1_470502070600699904", // 0: purchase order, 1: sell order, 2: royalty income, 3: primary market order, 4: mint fee
      "tokens": [
        {
          "network": "BSC",  // NFT Network
          "tokenId": "216000000496",  // NFT Token ID
          "contractAddress": "MYSTERY_BOX0000087"  // NFT Contract Address
        }
      ],
      "tradeTime": 1626941236000,     
      "tradeAmount": "19.60000000",  
      "tradeCurrency": "BNB"            
    },
    {
      "orderNo": "1_488306442479116288",
      "tokens": [
        {
          "network": "BSC",
          "tokenId": "132900000007",
          "contractAddress": "0xAf12111a592e408DAbC740849fcd5e68629D9fb6"
        }
      ],
      "tradeTime": 1631186130000,
      "tradeAmount": "192.00000000",
      "tradeCurrency": "BNB"
    }
  ]
}


GET /sapi/v1/nft/history/transactions (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
orderType INT YES 0: purchase order, 1: sell order, 2: royalty income, 3: primary market order, 4: mint fee
startTime LONG NO
endTime LONG NO
limit INT NO Default 50, Max 50
page INT NO Default 1
recvWindow LONG NO
timestamp LONG YES
  • The max interval between startTime and endTime is 90 days.
  • If startTime and endTime are not sent, the recent 7 days’ data will be returned.

Get NFT Deposit History(USER_DATA)

Response:

{
  "total": 2,
  "list": [
    {
      "network": "ETH",  // NFT Network
      "txID": null,      // Transaction ID
      "contractAdrress": "0xe507c961ee127d4439977a61af39c34eafee0dc6",  // NFT Contract Address
      "tokenId": "10014",   // NFT Token ID
      "timestamp": 1629986047000  
    },
    {
      "network": "BSC",
      "txID": null,
      "contractAdrress": "0x058451b463bab04f52c0799d55c4094f507acfa9",
      "tokenId": "10016",
      "timestamp": 1630083581000
    }
  ]
}


GET /sapi/v1/nft/history/deposit (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
startTime LONG NO
endTime LONG NO
limit INT NO Default 50, Max 50
page INT NO Default 1
recvWindow LONG NO
timestamp LONG YES
  • The max interval between startTime and endTime is 90 days.
  • If startTime and endTime are not sent, the recent 7 days’ data will be returned.

Get NFT Withdraw History (USER_DATA)

Response:

{
  "total": 178,
  "list": [
    {
      "network": "ETH",
      "txID": "0x2be5eed31d787fdb4880bc631c8e76bdfb6150e137f5cf1732e0416ea206f57f",
      "contractAdrress": "0xe507c961ee127d4439977a61af39c34eafee0dc6",  // NFT Contract Address
      "tokenId": "1000001247",    // NFT Token ID
      "timestamp": 1633674433000, 
      "fee": 0.1,         // Withdraw Fee
      "feeAsset": "ETH"   // Asset
    },
    {
      "network": "ETH",
      "txID": "0x3b3aea5c0a4faccd6f306641e6deb9713ab229ac233be3be227f580311e4362a",
      "contractAdrress": "0xe507c961ee127d4439977a61af39c34eafee0dc6",
      "tokenId": "40000030",
      "timestamp": 1633677022000,
      "fee": 0.1,
      "feeAsset": "ETH"
    }
  ]
}


GET /sapi/v1/nft/history/withdraw (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
startTime LONG NO
endTime LONG NO
limit INT NO Default 50, Max 50
page INT NO Default 1
recvWindow LONG NO
timestamp LONG YES
  • The max interval between startTime and endTime is 90 days.
  • If startTime and endTime are not sent, the recent 7 days’ data will be returned.

Get NFT Asset (USER_DATA)

Response:

{
  "total": 347,
  "list": [
    {
      "network": "BSC",  // NFT Network
      "contractAddress": "REGULAR11234567891779", // NFT Contract Address
      "tokenId": "100900000017"  // NFT Token ID
    },
    {
      "network": "BSC",
      "contractAddress": "SSMDQ8W59",
      "tokenId": "200500000011"
    },
    {
      "network": "BSC",
      "contractAddress": "SSMDQ8W59",
      "tokenId": "200500000019"
    }
  ]
}


GET /sapi/v1/nft/user/getAsset (HMAC SHA256)

Weight(UID):
3000

Parameters:

Name Type Mandatory Description
limit INT NO Default 50, Max 50
page INT NO Default 1
recvWindow LONG NO
timestamp LONG YES

Binance Gift Card Endpoints

Binance Gift Card allows simple crypto transfer and exchange through secured and prepaid codes. Binance Gift Card API solution is to facilitate instant creation, redemption and value-checking for Binance Gift Card. Binance Gift Card product feature consists of two parts: “Gift Card Number” and “Binance Gift Card Redemption Code”. The Gift Card Number can be circulated in public, and it is used to verify the validity of the Binance Gift Card; Binance Gift Card Redemption Code should be kept confidential, because as long as someone knows the redemption code, that person can redeem it anytime.

Create a single-token gift card (USER_DATA)

Response:

{
   "code": "000000",
   "message": "success",
   "data": {
    "referenceNo": "0033002327977405", // Gift Card Number
    "code": "AOGANK3NB4GIT3C6"         // Redemption Code
  },
   "success": true
}


POST /sapi/v1/giftcard/createCode (HMAC SHA256)

This API is for creating a Binance Gift Card.

To get started with, please make sure:

  • You have a Binance account
  • You have passed kyc
  • You have a sufficient balance in your Binance funding wallet
  • You need Enable Withdrawals for the API Key which requests this endpoint.

Weight(IP):
1

  • Daily creation volume: 2 BTC / 24H / account
  • Daily creation quantity: 200 Gift Cards / 24H / account

Parameters:

Name Type Mandatory Description
token STRING YES The token type contained in the Binance Gift Card
amount DOUBLE YES The amount of the token contained in the Binance Gift Card
recvWindow LONG NO
timestamp LONG YES

Create a dual-token gift card (fixed value, discount feature) (TRADE)

Response:

{
  "code": "000000",
  "message": "success",
  "data": {
    "referenceNo": "0033002327977405",
    "code": "AOGANK3NB4GIT3C6"
  },
  "success": true
}


POST /sapi/v1/giftcard/buyCode (HMAC SHA256)

  • This API is for creating a dual-token ( stablecoin-denominated) Binance Gift Card. You may create a gift card using USDT, BUSD or any supported fiat currency as baseToken, that is redeemable to another designated token (faceToken). For example, you can create a fixed-value BTC gift card and pay with 100 USDT. This gift card can keep the value fixed at 100 USDT before redemption, and will be redeemable to BTC equivalent to 100 USDT upon redemption.
  • Once successfully created, the amount of baseToken (e.g. USDT) in the fixed-value gift card would be deducted from your funding wallet.
  • On top of the dual-token gift card, the discount option allows you to create Binance Gift Cards at a discount within the designated discount limit. Discounted Binance Gift Cards are only available to selected partners. To apply, please reach out to the GIft Card team via giftcard@binance.com.

  • To get started with, please make sure:

    • You have a Binance account
    • You have passed kyc
    • You have a sufficient balance in your Binance funding wallet
    • You need Enable Withdrawals for the API Key which requests this endpoint.

Weight(IP):
1

  • Daily creation volume: 2 BTC / 24H / account
  • Daily creation quantity: 200 Gift Cards / 24H / account

Parameters:

Name Type Mandatory Description
baseToken STRING YES The token you want to pay, example: BUSD
faceToken STRING YES The token you want to buy, example: BNB. If faceToken = baseToken, it’s the same as createCode endpoint.
baseTokenAmount DOUBLE YES The base token asset quantity, example : 1.002
discount DOUBLE NO Stablecoin-denominated card discount percentage, Example: 1 for 1% discount. Scale should be less than 6.
recvWindow LONG NO
timestamp LONG YES

Redeem a Binance Gift Card (USER_DATA)

Response:

{
  "code":"000000",
  "message":"success",
  "data":{
    "referenceNo":"0033002328060227",
    "identityNo":"10317392647411060736",
    "token":"BNB",
    "amount":"0.00000001"
  },
  "success":true
}


POST /sapi/v1/giftcard/redeemCode (HMAC SHA256)

This API is for redeeming a Binance Gift Card

Once redeemed, the coins will be deposited in your funding wallet.

Please note that if you enter the wrong redemption code 5 times within 24 hours, you will no longer be able to redeem any Binance Gift Cards that day

Weight(IP):
1

Parameters:

Name Type Mandatory Description
code STRING YES Redemption code of Binance Gift Card to be redeemed, supports both Plaintext & Encrypted code.
externalUid STRING NO Each external unique ID represents a unique user on the partner platform. The function helps you to identify the redemption behavior of different users, such as redemption frequency and amount. It also helps risk and limit control of a single account, such as daily limit on redemption volume, frequency, and incorrect number of entries. This will also prevent a single user account reach the partner’s daily redemption limits. We strongly recommend you to use this feature and transfer us the User ID of your users if you have different users redeeming Binance Gift Cards on your platform. To protect user data privacy, you may choose to transfer the user id in any desired format (max. 400 characters).
recvWindow LONG NO
timestamp LONG YES

Notes:

  • Parameter code can be sent in two formats:

    • Plaintext
    • Encrypted
  • Sending code in Encrypted format provides more security than sending it as a plaintext. To send card code in encrypted format the following steps must be followed:

    • Fetch RSA public key from api stated below.
    • Use the below algorithm to encrypt the card code using the RSA public key fetched above: RSA/ECB/OAEPWithSHA-256AndMGF1Padding

A sample code snippet (JAVA) is stated below for reference, the same approach can be used for different languages like C#, PERL, PYTHON, SHELL etc.:

  private static PublicKey getPublicKey(String publicKey) throws Exception {
     KeyFactory keyFactory = KeyFactory.getInstance("RSA");
     byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
     X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
     return keyFactory.generatePublic(keySpec);
  }

  public static String encrypt(String content, String publicKeyString) throws Exception {
     if (StringUtils.isAnyEmpty(new CharSequence[]{content, publicKeyString})) {
        throw new IllegalArgumentException("invalid content or privateKey.");
     } else {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyString));
        return new String(Base64.encodeBase64URLSafe(cipher.doFinal(content.getBytes("UTF-8"))));
     }
  }

  static {
     Security.addProvider(new BouncyCastleProvider());
  }

Verify Binance Gift Card by Gift Card Number (USER_DATA)

Response:

{
   "code": "000000",
   "message": "success",
   "data": {
    "valid":true,  
    "token":"BNB",  // coin
    "amount":"0.00000001"  // amount
  }, 
   "success": true
}


GET /sapi/v1/giftcard/verify (HMAC SHA256)

This API is for verifying whether the Binance Gift Card is valid or not by entering Gift Card Number.

Please note that if you enter the wrong Gift Card Number 5 times within an hour, you will no longer be able to verify any Gift Card Number for that hour.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
referenceNo STRING YES Enter the Gift Card Number
recvWindow LONG NO
timestamp LONG YES

Fetch RSA Public Key (USER_DATA)

Response:

{
   "code": "000000",
   "message": "success",
    "data": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXBBVKLAc1GQ5FsIFFqOHrPTox5noBONIKr+IAedTR9FkVxq6e65updEbfdhRNkMOeYIO2i0UylrjGC0X8YSoIszmrVHeV0l06Zh1oJuZos1+7N+WLuz9JvlPaawof3GUakTxYWWCa9+8KIbLKsoKMdfS96VT+8iOXO3quMGKUmQIDAQAB",
   "success": true
}


GET /sapi/v1/giftcard/cryptography/rsa-public-key (HMAC SHA256)

This API is for fetching the RSA Public Key.
This RSA Public key will be used to encrypt the card code.

Please note that the RSA Public key fetched is valid only for the current day.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
recvWindow LONG NO
timestamp LONG YES

Fetch Token Limit (USER_DATA)

Response:

{
  "code": "000000",
  "message": "success",
  "data": [
    {
      "coin": "BNB",
      "fromMin": "0.01",
      "fromMax": "1"
    }
  ],
  "success":true
}


GET /sapi/v1/giftcard/buyCode/token-limit (HMAC SHA256)

This API is to help you verify which tokens are available for you to create Stablecoin-Denominated gift cards as mentioned in section 2 and its’ limitation.

Weight(IP):
1

Parameters:

Name Type Mandatory Description
baseToken STRING YES The token you want to pay, example: BUSD
recvWindow LONG NO
timestamp LONG YES

Error Codes

The error JSON payload:

{
  "code":-1121,
  "msg":"Invalid symbol."
}

Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary.

10xx — General Server or Network issues

-1000 UNKNOWN

  • An unknown error occurred while processing the request.
  • An unknown error occurred while processing the request.[%s]

-1001 DISCONNECTED

  • Internal error; unable to process your request. Please try again.
  • You are not authorized to execute this request.

-1003 TOO_MANY_REQUESTS

  • Too many requests queued.
  • Too much request weight used; current limit is %s request weight per %s. Please use WebSocket Streams for live updates to avoid polling the API.
  • Way too much request weight used; IP banned until %s. Please use WebSocket Streams for live updates to avoid bans.

-1004 SERVER_BUSY

  • Server is busy, please wait and try again

-1006 UNEXPECTED_RESP

  • An unexpected response was received from the message bus. Execution status unknown.

-1007 TIMEOUT

  • Timeout waiting for response from backend server. Send status unknown; execution status unknown.

-1008 SERVER_BUSY

  • Spot server is currently overloaded with other requests. Please try again in a few minutes.

-1014 UNKNOWN_ORDER_COMPOSITION

  • Unsupported order combination.

-1015 TOO_MANY_ORDERS

  • Too many new orders.
  • Too many new orders; current limit is %s orders per %s.

-1016 SERVICE_SHUTTING_DOWN

  • This service is no longer available.

-1020 UNSUPPORTED_OPERATION

  • This operation is not supported.

-1021 INVALID_TIMESTAMP

  • Timestamp for this request is outside of the recvWindow.
  • Timestamp for this request was 1000ms ahead of the server’s time.

-1022 INVALID_SIGNATURE

  • Signature for this request is not valid.

-1099 Not found, authenticated, or authorized

  • This replaces error code -1999

11xx — 2xxx Request issues

-1100 ILLEGAL_CHARS

  • Illegal characters found in a parameter.
  • Illegal characters found in a parameter. %s
  • Illegal characters found in parameter %s; legal range is %s.

-1101 TOO_MANY_PARAMETERS

  • Too many parameters sent for this endpoint.
  • Too many parameters; expected %s and received %s.
  • Duplicate values for a parameter detected.

-1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED

  • A mandatory parameter was not sent, was empty/null, or malformed.
  • Mandatory parameter %s was not sent, was empty/null, or malformed.
  • Param %s or %s must be sent, but both were empty/null!

-1103 UNKNOWN_PARAM

  • An unknown parameter was sent.

-1104 UNREAD_PARAMETERS

  • Not all sent parameters were read.
  • Not all sent parameters were read; read %s parameter(s) but was sent %s.

-1105 PARAM_EMPTY

  • A parameter was empty.
  • Parameter %s was empty.

-1106 PARAM_NOT_REQUIRED

  • A parameter was sent when not required.
  • Parameter %s sent when not required.

-1111 BAD_PRECISION

  • Precision is over the maximum defined for this asset.

-1112 NO_DEPTH

  • No orders on book for symbol.

-1114 TIF_NOT_REQUIRED

  • TimeInForce parameter sent when not required.

-1115 INVALID_TIF

  • Invalid timeInForce.

-1116 INVALID_ORDER_TYPE

  • Invalid orderType.

-1117 INVALID_SIDE

  • Invalid side.

-1118 EMPTY_NEW_CL_ORD_ID

  • New client order ID was empty.

-1119 EMPTY_ORG_CL_ORD_ID

  • Original client order ID was empty.

-1120 BAD_INTERVAL

  • Invalid interval.

-1121 BAD_SYMBOL

  • Invalid symbol.

-1125 INVALID_LISTEN_KEY

  • This listenKey does not exist.

-1127 MORE_THAN_XX_HOURS

  • Lookup interval is too big.
  • More than %s hours between startTime and endTime.

-1128 OPTIONAL_PARAMS_BAD_COMBO

  • Combination of optional parameters invalid.

-1130 INVALID_PARAMETER

  • Invalid data sent for a parameter.
  • Data sent for parameter %s is not valid.

-1131 BAD_RECV_WINDOW

  • recvWindow must be less than 60000

-1134 BAD_STRATEGY_TYPE

  • strategyType was less than 1000000.

-1145 INVALID_CANCEL_RESTRICTIONS

  • cancelRestrictions has to be either ONLY_NEW or ONLY_PARTIALLY_FILLED.

-2010 NEW_ORDER_REJECTED

  • NEW_ORDER_REJECTED

-2011 CANCEL_REJECTED

  • CANCEL_REJECTED

-2013 NO_SUCH_ORDER

  • Order does not exist.

-2014 BAD_API_KEY_FMT

  • API-key format invalid.

-2015 REJECTED_MBX_KEY

  • Invalid API-key, IP, or permissions for action.

-2016 NO_TRADING_WINDOW

  • No trading window could be found for the symbol. Try ticker/24hrs instead.

-2026 ORDER_ARCHIVED

  • Order was canceled or expired with no executed qty over 90 days ago and has been archived.

3xxx-5xxx SAPI-specific issues

-3000 INNER_FAILURE

  • Internal server error.

-3001 NEED_ENABLE_2FA

  • Please enable 2FA first.

-3002 ASSET_DEFICIENCY

  • We don’t have this asset.

-3003 NO_OPENED_MARGIN_ACCOUNT

  • Margin account does not exist.

-3004 TRADE_NOT_ALLOWED

  • Trade not allowed.

-3005 TRANSFER_OUT_NOT_ALLOWED

  • Transferring out not allowed.

-3006 EXCEED_MAX_BORROWABLE

  • Your borrow amount has exceed maximum borrow amount.

-3007 HAS_PENDING_TRANSACTION

  • You have pending transaction, please try again later.

-3008 BORROW_NOT_ALLOWED

  • Borrow not allowed.

-3009 ASSET_NOT_MORTGAGEABLE

  • This asset are not allowed to transfer into margin account currently.

-3010 REPAY_NOT_ALLOWED

  • Repay not allowed.

-3011 BAD_DATE_RANGE

  • Your input date is invalid.

-3012 ASSET_ADMIN_BAN_BORROW

  • Borrow is banned for this asset.

-3013 LT_MIN_BORROWABLE

  • Borrow amount less than minimum borrow amount.

-3014 ACCOUNT_BAN_BORROW

  • Borrow is banned for this account.

-3015 REPAY_EXCEED_LIABILITY

  • Repay amount exceeds borrow amount.

-3016 LT_MIN_REPAY

  • Repay amount less than minimum repay amount.

-3017 ASSET_ADMIN_BAN_MORTGAGE

  • This asset are not allowed to transfer into margin account currently.

-3018 ACCOUNT_BAN_MORTGAGE

  • Transferring in has been banned for this account.

-3019 ACCOUNT_BAN_ROLLOUT

  • Transferring out has been banned for this account.

-3020 EXCEED_MAX_ROLLOUT

  • Transfer out amount exceeds max amount.

-3021 PAIR_ADMIN_BAN_TRADE

  • Margin account are not allowed to trade this trading pair.

-3022 ACCOUNT_BAN_TRADE

  • You account’s trading is banned.

-3023 WARNING_MARGIN_LEVEL

  • You can’t transfer out/place order under current margin level.

-3024 FEW_LIABILITY_LEFT

  • The unpaid debt is too small after this repayment.

-3025 INVALID_EFFECTIVE_TIME

  • Your input date is invalid.

-3026 VALIDATION_FAILED

  • Your input param is invalid.

-3027 NOT_VALID_MARGIN_ASSET

  • Not a valid margin asset.

-3028 NOT_VALID_MARGIN_PAIR

  • Not a valid margin pair.

-3029 TRANSFER_FAILED

  • Transfer failed.

-3036 ACCOUNT_BAN_REPAY

  • This account is not allowed to repay.

-3037 PNL_CLEARING

  • PNL is clearing. Wait a second.

-3038 LISTEN_KEY_NOT_FOUND

  • Listen key not found.

-3041 BALANCE_NOT_CLEARED

  • Balance is not enough

-3042 PRICE_INDEX_NOT_FOUND

  • PriceIndex not available for this margin pair.

-3043 TRANSFER_IN_NOT_ALLOWED

  • Transferring in not allowed.

-3044 SYSTEM_BUSY

  • System busy.

-3045 SYSTEM

  • The system doesn’t have enough asset now.

-3999 NOT_WHITELIST_USER

  • This function is only available for invited users.

-4001 CAPITAL_INVALID

  • Invalid operation.

-4002 CAPITAL_IG

  • Invalid get.

-4003 CAPITAL_IEV

  • Your input email is invalid.

-4004 CAPITAL_UA

  • You don’t login or auth.

-4005 CAPAITAL_TOO_MANY_REQUEST

  • Too many new requests.

-4006 CAPITAL_ONLY_SUPPORT_PRIMARY_ACCOUNT

  • Support main account only.

-4007 CAPITAL_ADDRESS_VERIFICATION_NOT_PASS

  • Address validation is not passed.

-4008 CAPITAL_ADDRESS_TAG_VERIFICATION_NOT_PASS

  • Address tag validation is not passed.

-4010 CAPITAL_WHITELIST_EMAIL_CONFIRM

  • White list mail has been confirmed.

-4011 CAPITAL_WHITELIST_EMAIL_EXPIRED

  • White list mail is invalid.

-4012 CAPITAL_WHITELIST_CLOSE

  • White list is not opened.

-4013 CAPITAL_WITHDRAW_2FA_VERIFY

  • 2FA is not opened.

-4014 CAPITAL_WITHDRAW_LOGIN_DELAY

  • Withdraw is not allowed within 2 min login.

-4015 CAPITAL_WITHDRAW_RESTRICTED_MINUTE

  • Withdraw is limited.

-4016 CAPITAL_WITHDRAW_RESTRICTED_PASSWORD

  • Within 24 hours after password modification, withdrawal is prohibited.

-4017 CAPITAL_WITHDRAW_RESTRICTED_UNBIND_2FA

  • Within 24 hours after the release of 2FA, withdrawal is prohibited.

-4018 CAPITAL_WITHDRAW_ASSET_NOT_EXIST

  • We don’t have this asset.

-4019 CAPITAL_WITHDRAW_ASSET_PROHIBIT

  • Current asset is not open for withdrawal.

-4021 CAPITAL_WITHDRAW_AMOUNT_MULTIPLE

  • Asset withdrawal must be an %s multiple of %s.

-4022 CAPITAL_WITHDRAW_MIN_AMOUNT

  • Not less than the minimum pick-up quantity %s.

-4023 CAPITAL_WITHDRAW_MAX_AMOUNT

  • Within 24 hours, the withdrawal exceeds the maximum amount.

-4024 CAPITAL_WITHDRAW_USER_NO_ASSET

  • You don’t have this asset.

-4025 CAPITAL_WITHDRAW_USER_ASSET_LESS_THAN_ZERO

  • The number of hold asset is less than zero.

-4026 CAPITAL_WITHDRAW_USER_ASSET_NOT_ENOUGH

  • You have insufficient balance.

-4027 CAPITAL_WITHDRAW_GET_TRAN_ID_FAILURE

  • Failed to obtain tranId.

-4028 CAPITAL_WITHDRAW_MORE_THAN_FEE

  • The amount of withdrawal must be greater than the Commission.

-4029 CAPITAL_WITHDRAW_NOT_EXIST

  • The withdrawal record does not exist.

-4030 CAPITAL_WITHDRAW_CONFIRM_SUCCESS

  • Confirmation of successful asset withdrawal.

-4031 CAPITAL_WITHDRAW_CANCEL_FAILURE

  • Cancellation failed.

-4032 CAPITAL_WITHDRAW_CHECKSUM_VERIFY_FAILURE

  • Withdraw verification exception.

-4033 CAPITAL_WITHDRAW_ILLEGAL_ADDRESS

  • Illegal address.

-4034 CAPITAL_WITHDRAW_ADDRESS_CHEAT

  • The address is suspected of fake.

-4035 CAPITAL_WITHDRAW_NOT_WHITE_ADDRESS

  • This address is not on the whitelist. Please join and try again.

-4036 CAPITAL_WITHDRAW_NEW_ADDRESS

  • The new address needs to be withdrawn in {0} hours.

-4037 CAPITAL_WITHDRAW_RESEND_EMAIL_FAIL

  • Re-sending Mail failed.

-4038 CAPITAL_WITHDRAW_RESEND_EMAIL_TIME_OUT

  • Please try again in 5 minutes.

-4039 CAPITAL_USER_EMPTY

  • The user does not exist.

-4040 CAPITAL_NO_CHARGE

  • This address not charged.

-4041 CAPITAL_MINUTE_TOO_SMALL

  • Please try again in one minute.

-4042 CAPITAL_CHARGE_NOT_RESET

  • This asset cannot get deposit address again.

-4043 CAPITAL_ADDRESS_TOO_MUCH

  • More than 100 recharge addresses were used in 24 hours.

-4044 CAPITAL_BLACKLIST_COUNTRY_GET_ADDRESS

  • This is a blacklist country.

-4045 CAPITAL_GET_ASSET_ERROR

  • Failure to acquire assets.

-4046 CAPITAL_AGREEMENT_NOT_CONFIRMED

  • Agreement not confirmed.

-4047 CAPITAL_DATE_INTERVAL_LIMIT

  • Time interval must be within 0-90 days

-4060 CAPITAL_WITHDRAW_USER_ASSET_LOCK_DEPOSIT

  • As your deposit has not reached the required block confirmations, we have temporarily locked {0} asset

-5001 ASSET_DRIBBLET_CONVERT_SWITCH_OFF

  • Don’t allow transfer to micro assets.

-5002 ASSET_ASSET_NOT_ENOUGH

  • You have insufficient balance.

-5003 ASSET_USER_HAVE_NO_ASSET

  • You don’t have this asset.

-5004 USER_OUT_OF_TRANSFER_FLOAT

  • The residual balances have exceeded 0.001BTC, Please re-choose.
  • The residual balances of %s have exceeded 0.001BTC, Please re-choose.

-5005 USER_ASSET_AMOUNT_IS_TOO_LOW

  • The residual balances of the BTC is too low
  • The residual balances of %s is too low, Please re-choose.

-5006 USER_CAN_NOT_REQUEST_IN_24_HOURS

  • Only transfer once in 24 hours.

-5007 AMOUNT_OVER_ZERO

  • Quantity must be greater than zero.

-5008 ASSET_WITHDRAW_WITHDRAWING_NOT_ENOUGH

  • Insufficient amount of returnable assets.

-5009 PRODUCT_NOT_EXIST

  • Product does not exist.

-5010 TRANSFER_FAIL

  • Asset transfer fail.

-5011 FUTURE_ACCT_NOT_EXIST

  • future account not exists.

-5012 TRANSFER_PENDING

  • Asset transfer is in pending.

-5021 PARENT_SUB_HAVE_NO_RELATION

  • This parent sub have no relation

-5012 FUTURE_ACCT_OR_SUBRELATION_NOT_EXIST

  • future account or sub relation not exists.

6XXX — Savings Issues

-6001 DAILY_PRODUCT_NOT_EXIST

  • Daily product not exists.

-6003 DAILY_PRODUCT_NOT_ACCESSIBLE

  • Product not exist or you don’t have permission

-6004 DAILY_PRODUCT_NOT_PURCHASABLE

  • Product not in purchase status

-6005 DAILY_LOWER_THAN_MIN_PURCHASE_LIMIT

  • Smaller than min purchase limit

-6006 DAILY_REDEEM_AMOUNT_ERROR

  • Redeem amount error

-6007 DAILY_REDEEM_TIME_ERROR

  • Not in redeem time

-6008 DAILY_PRODUCT_NOT_REDEEMABLE

  • Product not in redeem status

-6009 REQUEST_FREQUENCY_TOO_HIGH

  • Request frequency too high

-6011 EXCEEDED_USER_PURCHASE_LIMIT

  • Exceeding the maximum num allowed to purchase per user

-6012 BALANCE_NOT_ENOUGH

  • Balance not enough

-6013 PURCHASING_FAILED

  • Purchasing failed

-6014 UPDATE_FAILED

  • Exceed up-limit allowed to purchased

-6015 EMPTY_REQUEST_BODY

  • Empty request body

-6016 PARAMS_ERR

  • Parameter err

-6017 NOT_IN_WHITELIST

  • Not in whitelist

-6018 ASSET_NOT_ENOUGH

  • Asset not enough

-6019 PENDING

  • Need confirm

-6020 PROJECT_NOT_EXISTS

  • Project not exists

70xx — Futures

-7001 FUTURES_BAD_DATE_RANGE

  • Date range is not supported.

-7002 FUTURES_BAD_TYPE

  • Data request type is not supported.

20xxx — Futures/Spot Algo

-20121

  • Invalid symbol.

-20124

  • Invalid algo id or it has been completed.

-20130

  • Invalid data sent for a parameter.

-20132

  • The client algo id is duplicated.

-20194

  • Duration is too short to execute all required quantity.

-20195

  • The total size is too small.

-20196

  • The total size is too large.

-20198

  • Reach the max open orders allowed.

-20204

  • The notional of USD is less or more than the limit.

Filter failures

Error message Description
«Filter failure: PRICE_FILTER» price is too high, too low, and/or not following the tick size rule for the symbol.
«Filter failure: PERCENT_PRICE» price is X% too high or X% too low from the average weighted price over the last Y minutes.
«Filter failure: PERCENT_PRICE_BY_SIDE» price is X% too high or Y% too low from the lastPrice on that side (i.e. BUY/SELL)
«Filter failure: LOT_SIZE» quantity is too high, too low, and/or not following the step size rule for the symbol.
«Filter failure: MIN_NOTIONAL» price * quantity is too low to be a valid order for the symbol.
«Filter failure: ICEBERG_PARTS» ICEBERG order would break into too many parts; icebergQty is too small.
«Filter failure: MARKET_LOT_SIZE» MARKET order’s quantity is too high, too low, and/or not following the step size rule for the symbol.
«Filter failure: MAX_POSITION» The account’s position has reached the maximum defined limit.

This is composed of the sum of the balance of the base asset, and the sum of the quantity of all open BUYorders.

«Filter failure: MAX_NUM_ORDERS» Account has too many open orders on the symbol.
«Filter failure: MAX_NUM_ALGO_ORDERS» Account has too many open stop loss and/or take profit orders on the symbol.
«Filter failure: MAX_NUM_ICEBERG_ORDERS» Account has too many open iceberg orders on the symbol.
«Filter failure: TRAILING_DELTA» trailingDelta is not within the defined range of the filter for that order type.
«Filter failure: EXCHANGE_MAX_NUM_ORDERS» Account has too many open orders on the exchange.
«Filter failure: EXCHANGE_MAX_NUM_ALGO_ORDERS» Account has too many open stop loss and/or take profit orders on the exchange.

10xxx — Crypto Loans

-10001 SYSTEM_MAINTENANCE

  • The system is under maintenance, please try again later.

-10002 INVALID_INPUT

  • Invalid input parameters.

-10005 NO_RECORDS

  • No records found.

-10007 COIN_NOT_LOANABLE

  • This coin is not loanable.

-10008 COIN_NOT_LOANABLE

  • This coin is not loanable

-10009 COIN_NOT_COLLATERAL

  • This coin can not be used as collateral.

-10010 COIN_NOT_COLLATERAL

  • This coin can not be used as collateral.

-10011 INSUFFICIENT_ASSET

  • Insufficient spot assets.

-10012 INVALID_AMOUNT

  • Invalid repayment amount.

-10013 INSUFFICIENT_AMOUNT

  • Insufficient collateral amount.

-10015 DEDUCTION_FAILED

  • Collateral deduction failed.

-10016 LOAN_FAILED

  • Failed to provide loan.

-10017 REPAY_EXCEED_DEBT

  • Repayment amount exceeds debt.

-10018 INVALID_AMOUNT

  • Invalid repayment amount.

-10019 CONFIG_NOT_EXIST

  • Configuration does not exists.

-10020 UID_NOT_EXIST

  • User ID does not exist.

-10021 ORDER_NOT_EXIST

  • Order does not exist.

-10022 INVALID_AMOUNT

  • Invalid adjustment amount.

-10023 ADJUST_LTV_FAILED

  • Failed to adjust LTV.

-10024 ADJUST_LTV_NOT_SUPPORTED

  • LTV adjustment not supported.

-10025 REPAY_FAILED

  • Repayment failed.

-10026 INVALID_PARAMETER

  • Invalid parameter.

-10028 INVALID_PARAMETER

  • Invalid parameter.

-10029 AMOUNT_TOO_SMALL

  • Loan amount is too small.

-10030 AMOUNT_TOO_LARGE

  • Loan amount is too much.

-10031 QUOTA_REACHED

  • Individual loan quota reached.

-10032 REPAY_NOT_AVAILABLE

  • Repayment is temporarily unavailable.

-10034 REPAY_NOT_AVAILABLE

  • Repay with collateral is not available currently, please try to repay with borrowed coin.

-10039 AMOUNT_TOO_SMALL

  • Repayment amount is too small.

-10040 AMOUNT_TOO_LARGE

  • Repayment amount is too large.

-10041 INSUFFICIENT_AMOUNT

  • Due to high demand, there are currently insufficient loanable assets for {0}. Please adjust your borrow amount or try again tomorrow.

-10042 ASSET_NOT_SUPPORTED

  • asset %s is not supported

-10043 ASSET_NOT_SUPPORTED

  • {0} borrowing is currently not supported.

-10044 QUOTA_REACHED

  • Collateral amount has reached the limit. Please reduce your collateral amount or try with other collaterals.

-10045 COLLTERAL_REPAY_NOT_SUPPORTED

  • The loan coin does not support collateral repayment. Please try again later.

-10046 EXCEED_MAX_ADJUSTMENT

  • Collateral Adjustment exceeds the maximum limit. Please try again.

-10047 REGION_NOT_SUPPORTED

  • This coin is currently not supported in your location due to local regulations.

13xxx — BLVT

-13000 BLVT_FORBID_REDEEM

  • Redeption of the token is forbiden now

-13001 BLVT_EXCEED_DAILY_LIMIT

  • Exceeds individual 24h redemption limit of the token

-13002 BLVT_EXCEED_TOKEN_DAILY_LIMIT

  • Exceeds total 24h redemption limit of the token

-13003 BLVT_FORBID_PURCHASE

  • Subscription of the token is forbiden now

-13004 BLVT_EXCEED_DAILY_PURCHASE_LIMIT

  • Exceeds individual 24h subscription limit of the token

-13005 BLVT_EXCEED_TOKEN_DAILY_PURCHASE_LIMIT

  • Exceeds total 24h subscription limit of the token

-13006 BLVT_PURCHASE_LESS_MIN_AMOUNT

  • Subscription amount is too small

-13007 BLVT_PURCHASE_AGREEMENT_NOT_SIGN

  • The Agreement is not signed

12xxx — Liquid Swap

-12014 TOO MANY REQUESTS

  • More than 1 request in 2 seconds

18xxx — Binance Code

-18002

  • The total amount of codes you created has exceeded the 24-hour limit, please try again after UTC 0

-18003

  • Too many codes created in 24 hours, please try again after UTC 0

-18004

  • Too many invalid redeem attempts in 24 hours, please try again after UTC 0

-18005

  • Too many invalid verify attempts, please try later

-18006

  • The amount is too small, please re-enter

-18007

  • This token is not currently supported, please re-enter

21xxx — Portfolio Margin Account

-21001 USER_IS_NOT_UNIACCOUNT

  • Request ID is not a Portfolio Margin Account.

-21002 UNI_ACCOUNT_CANT_TRANSFER_FUTURE

  • Portfolio Margin Account doesn’t support transfer from margin to futures.

-21003 NET_ASSET_MUST_LTE_RATIO

  • Fail to retrieve margin assets.

-21004 USER_NO_LIABILITY

  • User doesn’t have portfolio margin bankruptcy loan

-21005 NO_ENOUGH_ASSET

  • User’s spot wallet doesn’t have enough BUSD to repay portfolio margin bankruptcy loan

-21006 HAD_IN_PROCESS_REPAY

  • User had portfolio margin bankruptcy loan repayment in process

-21007 IN_FORCE_LIQUIDATION

  • User failed to repay portfolio margin bankruptcy loan since liquidation was in process

Order Rejection Issues

Error messages like these are indicated when the error is coming specifically from the matching engine:

  • -1010 ERROR_MSG_RECEIVED
  • -2010 NEW_ORDER_REJECTED
  • -2011 CANCEL_REJECTED

The following messages which will indicate the specific error:

Error message Description
«Unknown order sent.» The order (by either orderId, clientOrderId, origClientOrderId) could not be found.
«Duplicate order sent.» The clientOrderId is already in use.
«Market is closed.» The symbol is not trading.
«Account has insufficient balance for requested action.» Not enough funds to complete the action.
«Market orders are not supported for this symbol.» MARKET is not enabled on the symbol.
«Iceberg orders are not supported for this symbol.» icebergQty is not enabled on the symbol
«Stop loss orders are not supported for this symbol.» STOP_LOSS is not enabled on the symbol
«Stop loss limit orders are not supported for this symbol.» STOP_LOSS_LIMIT is not enabled on the symbol
«Take profit orders are not supported for this symbol.» TAKE_PROFIT is not enabled on the symbol
«Take profit limit orders are not supported for this symbol.» TAKE_PROFIT_LIMIT is not enabled on the symbol
«Price * QTY is zero or less.» price * quantity is too low
«IcebergQty exceeds QTY.» icebergQty must be less than the order quantity
«This action is disabled on this account.» Contact customer support; some actions have been disabled on the account.
«This account may not place or cancel orders.» Contact customer support; the account has trading ability disabled.
«Unsupported order combination» The orderType, timeInForce, stopPrice, and/or icebergQty combination isn’t allowed.
«Order would trigger immediately.» The order’s stop price is not valid when compared to the last traded price.
«Cancel order is invalid. Check origClientOrderId and orderId.» No origClientOrderId or orderId was sent in.
«Order would immediately match and take.» LIMIT_MAKER order type would immediately match and trade, and not be a pure maker order.
«The relationship of the prices for the orders is not correct.» The prices set in the OCO is breaking the Price rules.

The rules are:

SELL Orders: Limit Price > Last Price > Stop Price

BUY Orders: Limit Price < Last Price < Stop Price

«OCO orders are not supported for this symbol» OCO is not enabled on the symbol.
«Quote order qty market orders are not support for this symbol.» MARKET orders using the parameter quoteOrderQty are not enabled on this symbol.
«Trailing stop orders are not supported for this symbol.» Orders using trailingDelta are not enabled on the symbol.
«Order cancel-replace is not supported for this symbol.» POST /api/v3/order/cancelReplace is not enabled for the symbol.
«This symbol is not permitted for this account.» Account does not have permission to trade on this symbol.
«This symbol is restricted for this account.» Account does not have permission to trade on this symbol.
«Order was not canceled due to cancel restrictions.» Either cancelRestrictions was set to ONLY_NEW but the order status was not NEW
or
cancelRestrictions was set to ONLY_PARTIALLY_FILLED but the order status was not PARTIALLY_FILLED.

Errors regarding POST /api/v3/order/cancelReplace

-2021 Order cancel-replace partially failed

This code is sent when either the cancellation of the order failed or the new order placement failed but not both.

-2022 Order cancel-replace failed.

This code is sent when both the cancellation of the order failed and the new order placement failed.

Notes

Request Parameters

Email Address

  • Email address should be encoded. e.g. alice@test.com should be encoded into alice%40test.com
  • Email address should be in lower case.

Понимание и использование API для торговли криптовалютой может открыть мир возможностей, когда дело доходит до входа и выхода из позиций. Обладая некоторыми простыми знаниями в области программирования, вы можете подключиться к серверной части биржи, чтобы автоматизировать свои торговые стратегии . Обойдя веб-сайт, вы сможете гораздо быстрее перейти к механизму сопоставления для высокопроизводительных приложений.

Цель этой серии — познакомить вас с Binances REST API и научить, как с ним взаимодействовать. К концу вы должны быть уверены в своей способности запрашивать информацию о рынках и вашей позиции и размещать ряд различных типов ордеров.

В этой статье мы будем использовать Postman для связи с биржей. Не волнуйтесь, мы не будем подвергать риску реальные средства.

Ключи тестовой сети

Мы собираемся использовать тестовую сеть для наших целей. Это даст нам немного средств, не имеющих реальной ценности, с которыми можно было бы поиграть. Они работают точно так же, как настоящие монеты и токены, поэтому, как только вы освоитесь с API, вы можете начать использовать его для торговли реальными средствами.

  1. Начните с перехода к сети Spot Test .
  2. Чтобы получить доступ, вам необходимо войти в систему с учетной записью GitHub . Создайте его, если вы еще этого не сделали.
  3. Нажмите « Аутентификация» и войдите через GitHub.
  4. В разделе «Ключи API» вы получите сообщение о том, что у вас не зарегистрированы ключи. Нажмите « Создать ключ HMAC_SHA256», чтобы создать пару.
  5. На следующем экране присвойте клавишам метку. Называйте их как хотите и нажмите « Создать» .
  6. Вам представлены два ключа: ключ API и секретный ключ . Важно, чтобы вы записали это сейчас. Если вы этого не сделаете, вам нужно будет снова запустить процесс создания ключа. Мы рекомендуем хранить их в приложении для заметок на вашем компьютере, чтобы потом их было легко скопировать.

Примечание: маркировка ваших ключей — это то, что стоит сделать при использовании реальной биржи для управления разными ключами. У вашей учетной записи может быть несколько ключей с разными разрешениями. Если вы используете несколько торговых ботов, использование отдельных ключей с описательными метками упрощает управление разрешениями или удаление отдельных ключей без изменения всех ваших ботов.

Скачивание и установка Postman

Postman — это платформа для совместной работы API. Это идеальная отправная точка для нас, у нас есть доступ к коллекциям запросов Binance, которые хорошо тестируются без необходимости писать ни одной строчки кода.

Программа доступна для Mac, Windows и Linux . Перейдите на страницу загрузок и загрузите файл .zip.

Как только это будет завершено, найдите его в проводнике файлов и установите. Запустите приложение, и все готово! Обратите внимание, что вы можете создать учетную запись для входа в систему, но это не обязательно. Если вы хотите пропустить этот шаг, просто выберите соответствующий вариант в нижней части окна.

На этом этапе у вас должен быть интерфейс, похожий на следующий.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Мы хотим сначала создать нашу среду. Это просто способ добавить переменные к набору запросов, с которыми мы собираемся работать. Для этого сначала нужно получить некоторую информацию из репозитория Binance GitHub. Зайдите сюда и загрузите файл .zip.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Загрузка не займет много времени. Найдите его в проводнике и разархивируйте. Затем мы можем вернуться в Почтальон.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Щелкните значок шестеренки в правом верхнем углу (как показано выше). Вы увидите всплывающее окно « Управление средами».

  1. Выберите « Импорт» и перейдите в только что извлеченную папку (binance-postman-api).
  2. Войдите в него, затем войдите в папку сред.
  3. Теперь вы увидите два файла (один для основной сети и один для тестовой). После этого был binance_com_spot_testnet_api.postman_environment.json . Убедитесь, что вы выбрали правильный, потому что наши ключи не будут работать с другими.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Почти готово. Нажмите Binance Spot Testnet API , и вы увидите переменные ниже. Отредактируйте два параметра, выделенных красным, вставив ключи, которые вы сохранили ранее. Нажмите «Обновить» и выйдите из всплывающего окна.

Binance API Series Pt. I - Спотовая торговля с почтальоном

На этом экране оставьте поля отметки времени и подписи пустыми. Эти два значения будут автоматически создаваться при каждом запросе.

Осталось сделать последнее. Справа от значка шестеренки, который мы щелкнули, чтобы настроить среду ранее, вы увидите раскрывающееся меню, в котором в настоящее время указано « Нет среды» . Нажмите на нее и выберите Binance Spot Testnet API .

Теперь мы собираемся импортировать коллекцию, это обширный набор запросов, которые делают за нас тяжелую работу, когда мы делаем звонки. Чтобы загрузить его в нашу среду:

  1. Щелкните Импорт в верхнем левом углу.
  2. Во всплывающем окне на вкладке « Файл » выберите « Загрузить файлы» .
  3. Снова искали папку binance-postman-api . Найдите и откройте его.
  4. На этот раз введите коллекции в подкаталог.
  5. Здесь снова два файла. Один для работы с Futures API. Но мы работали со спотовым, поэтому вам нужно выбрать файл binance_spot_api_v1.postman_collection.json .
  6. Теперь вы должны увидеть экран подтверждения, который идентифицирует импорт как имеющийся в формате коллекции почтальона. Выберите Импорт.

На вкладке Коллекция слева от окна вы теперь заметите, что у нас есть папка с более чем 100 запросами. Поздравляю! Было хорошо идти. В следующем разделе мы рассмотрим, какие запросы мы можем делать.

Если вы развернете папки на вкладке «Коллекция», вы увидите, что у нас есть множество различных запросов, которые мы можем сделать. По цветовой кодировке вы можете заметить, что есть три типа методов, которые мы можем использовать:

  • GET :метод GET используется для получения данных с сервера. Хорошо используйте это, чтобы узнать информацию о балансе вашего счета, ценах на активы и т. Д.
  • POST : Обычно используйтеметод POST для создания информации на сервере. Это необходимо для таких вещей, как размещение заказов, запрос на снятие средств и т. Д.
  • DELETE :метод DELETE — это запрос к серверу на удаление информации. Пригодится для отмены заказов.

Найдите список символов и правила торговли

Время для нашего первого запроса! Мы собираемся получить символы, которыми можно торговать на бирже, и правила торговли:

GET / exchangeInfo

Он не принимает никаких дополнительных параметров, вы можете скопировать их и вставить в адресную строку, и вы получите ответ. Но для запросов, в которых мы включаем несколько параметров, Postman упрощает их просмотр и изменение.

Чтобы загрузить этот запрос, выберите Market Exchange Information . Появится следующая вкладка:

Binance API Series Pt. I - Спотовая торговля с почтальоном

Здесь нам больше ничего делать не нужно, так что нажмите « Отправить» . Тогда вы получите ответ:

Binance API Series Pt. I - Спотовая торговля с почтальоном

В самом верхнем выделенном разделе вы увидите важную информацию:

  • статус ответа ( 200 означает, что мы успешно, 400-499 означает, что мы столкнулись с проблемой)

  • время, необходимое для получения ответа (менее секунды)

  • размер ответа (~ 22КБ).

Во втором поле — основная часть ответа. Это было красиво напечатано, так что это немного легче для глаз. Он содержит информацию о самой бирже, а также о парах, которыми вы можете торговать, и их минимальных / максимальных суммах.

Похоже, что информации много, но формат позволяет легко работать с ней программно. При написании скриптов для взаимодействия с ним вы легко сможете выбрать конкретные свойства определенных элементов из ответа.

Проверить остаток на счете

Давайте проверим, какие активы у нас есть и сколько их:

ПОЛУЧИТЬ / аккаунт

Его можно найти в разделе « Информация о торговом счете» . Щелкните по нему, и вы увидите макет, похожий на предыдущий. Однако вы также заметите, что у нас есть две новые переменные: отметка времени и подпись . Подпись — мера безопасности. Поскольку теперь запрашивали конфиденциальную информацию, это докажет, что это был владелец учетной записи.

Отметка времени сообщает серверу, когда запрос был отправлен. Поскольку сети могут быть ненадежными или иметь простои, сервер может получить наш запрос намного позже, чем предполагалось. Если прошло слишком много времени, он отклонит запрос. Вы можете указать, как долго вы хотите ждать, с помощью параметра recvWindow , который по умолчанию равен 5000 миллисекунд.

Почтальон обрабатывает за нас создание обоих этих полей. Нажмите «Отправить», и вы получите ответ. Под балансами вы должны увидеть шесть активов: BNB, BTC, BUSD, ETH, LTC и TRX. Баланс будет разделен на бесплатный и заблокированный . Мы еще ничего не заблокировали, поэтому все ваши активы должны быть свободны.

Поздравляю с новообретенным (несуществующим) богатством!

Как узнать текущую цену символа

Мы можем получить текущую цену актива по-разному. Возможно, самый простой — со следующей просьбой:

GET / api / v3 / тикер / 24 часа

Как вы могли догадаться, это даст нам информацию о ценах на активы за последние сутки. Найдите его в статистике изменения цен тикера за 24 часа . Пара по умолчанию была встречена, поскольку переменная символа — BTCUSDT .

Вы можете отправить это прямо сейчас, чтобы увидеть разбивку информации о ценах. Вы также можете изменить символ (на BNBBUSD , LTCUSDT и т. Д.) Или снять флажок с переменной, чтобы возвращать данные для 40 пар.

У нас также есть более простой вызов ( Market Symbol Price Ticker ), который возвращает текущую цену, по которой торгуется актив:

GET / api / v3 / цена

Как и в предыдущем случае, вы можете изменить переменную символа или полностью удалить ее и получить последнюю цену для всех символов.

Проверить текущую глубину стакана заказов

Глубина книги заказов (также называемая стаканом цен или DOM) может многое рассказать нам о рынке. Мы собираемся сделать звонок, который вернет некоторую полезную информацию:

GET api / v3 / depth

Когда мы отправляем это со значениями по умолчанию (Market Order Book), мы получаем ответ, который сообщает нам о ставках и запрашивает BTCUSDT. Сервер тестовой сети не выдаст столько данных, сколько фактический, поэтому ниже приведен снимок экрана того, что вы ожидаете увидеть в реальной среде:

Binance API Series Pt. I - Спотовая торговля с почтальоном

В выделенном выше разделе мы видим первую ставку. Поскольку мы смотрели книгу по BTCUSDT, верхнее число — это цена, которую кто-то готов заплатить за ваш BTC. Ниже указана сумма, которую они готовы купить. Таким образом, это говорит о том, что этот заказ запрашивает 0,999 BTC по курсу 9704,65 долларов США за BTC. Если мы продолжим прокрутку вниз, то увидим снижение цены предложения, представляющее покупателей, которые заплатят меньше.

Лучшее предложение, естественно, будет самым привлекательным, если вы ищете выгодную цену. Тем не менее, если вы пытаетесь продать на рынке, скажем, 3 BTC, вы сможете продать только 0,999 BTC по лучшей цене. Вам нужно будет принимать последующие (более дешевые) предложения, пока ваш заказ не будет выполнен полностью.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Продолжайте прокручивать, и вы увидите вопросы. Функционально они аналогичны заявкам, за исключением того, что представляют собой заказы на продажу BTC за USDT.

Разместите тестовый заказ

Сейчас собирались выложить тестовый заказ.

POST api / v3 / заказ / тест

Несмотря на то, что мы просто использовали средства тестовой сети, этот запрос на самом деле не размещает заказ. Это может пригодиться для тестирования заказов перед их отправкой. Найдите его в разделе Trade Test New Order (TRADE) .

Binance API Series Pt. I - Спотовая торговля с почтальоном

Как видите, у нас задействовано еще много параметров. Пройдемся по отмеченным:

  • символ WeVe попадался этой ранее. Это пара, которой вы хотите торговать.
  • сторона здесь, вы будете оговорить , хотите ли вы купить или продать. Для пары BTCUSDT, ПОКУПКА означает, что вы хотите купить BTC за USDT, тогда как продажа будет продавать BTC за USDT.
  • введите тип заказа, который вы хотите отправить. Возможные значения (подробно здесь ):
    • LIMIT
    • РЫНОК
    • ОСТАНОВИТЬ ПОТЕРИ
    • STOP_LOSS_LIMIT
    • TAKE_PROFIT
    • TAKE_PROFIT_LIMIT
    • LIMIT_MAKER
  • timeInForce этот параметр выражает, как вы хотите, чтобы приказ выполнялся:

    • GTC (действителен до отмены), пожалуй, самая популярная установка, GTC гарантирует, что ваш заказ действителен до тех пор, пока он не будет заполнен, или пока вы его не отмените.
    • FOK (заполнить или уничтожить) FOK предписывает бирже выполнить ордер сразу. Если обмен не может быть осуществлен, заказ немедленно аннулируется.
    • IOC (немедленно или отменить), либо весь заказ, либо его часть должны быть выполнены немедленно, либо он отменен. В отличие от ФОК, заказы не отменяются, если они могут быть выполнены частично.
  • количество просто количество актива, которое вы хотите купить или продать.
  • цена цена, по которой вы хотите продать. Для пары BTCUSDT это выражается в долларах США.
  • newClientOrderId — идентификатор заказа. Это не обязательное поле, но вы можете установить в нем идентификатор, который упростит запрос позже. В противном случае он генерируется случайным образом на бирже.

Хорошо! Теперь создадим тестовый заказ. Мы собираемся использовать автоматически сгенерированные значения: лимитный ордер на продажу 0,1 BTC за USDT по цене 9000 долларов США. Нажмите » Отправить» . Если это было успешно, тогда просто получите {} в качестве ответа.

Сделайте реальный заказ

Пришло время разместить настоящий фальшивый заказ.

POST / api / v3 / заказ

Перейдите к Trade New Order . Вы уже знакомы с тестовыми заказами, поэтому параметры здесь не удивят. Давайте оставим все значения такими, какие они есть, но, поскольку были постоянные цены, мы изменим цену, по которой продавались, на 40 000 долларов. Измените значение цены, чтобы отразить это. Затем нажмите « Отправить» .

В случае успеха ваш ответ содержит подробную информацию о заказе.

Проверить статус открытых заказов

Мы получили подтверждение, что заказ был размещен в предыдущем разделе, но что, если мы захотим проверить его позже? В нашем распоряжении есть несколько запросов.

GET / api / v3 / openOrders

Вы найдете это в Trade Current Open Orders (USER_DATA) . По умолчанию выбран BTCUSDT . Если вы нажмете « Отправить» , вы получите все свои открытые ордера BTCUSDT (пока вы должны видеть только тот, который мы установили ранее). Вы можете не указывать символ, который вместо этого вернет все ваши открытые ордера.

ПОЛУЧИТЬ / api / v3 / allOrders

Торговля всеми ордерами (USER_DATA) дает вам обзор всех ордеров, а не только открытых. Здесь вы должны указать символ. orderId , startTime , endTime и limit — необязательные параметры, которые помогут вам уточнить поиск. Что ж, оставьте их здесь, так что снимите с них отметку. Нажмите « Отправить» , и вы увидите тот же ответ, что и раньше. Если у вас были закрытые или отмененные заказы, вы также увидите их здесь.

Наконец, мы можем запрашивать конкретные заказы с помощью:

ПОЛУЧИТЬ / api / v3 / заказ

Получите это в разделе « Заказ торгового запроса» (USER_DATA) . Вам нужно будет указать либо orderId, либо origClientOrderId (необязательный тег newClientOrderId, который вы можете добавить к заказам). Снимите флажок orderId . Для origClientOrderId мы собирались предоставить тег по умолчанию из более раннего my_order_id_1. Заполните поле и нажмите « Отправить», чтобы получить ответ.

Отменить заказ

Через некоторое время мы можем решить, что цель в 40 000 долларов слишком оптимистична, поэтому мы хотим ее отменить. В этом случае используйте:

УДАЛИТЬ / api / v3 / заказ

В разделе « Ордер на отмену сделки» — это запрос, который позволит нам выделить ордера для отмены. Снимите флажки orderId и newClientOrderId и передайте my_order_id_1 в качестве значения origClientOrderId .

Когда вы отправите этот запрос, заказ будет возвращен. Если вы прокрутите вниз до статуса , вы увидите, что он действительно отменен. Чтобы подтвердить это, снова используйте конечную точку GET / api / v3 / openOrders (с пустым списком) или GET / api / v3 / order с origClientOrderId .

Разместите заказ, который заполняется мгновенно

Наш предыдущий ордер не был исполнен, потому что это был лимитный ордер, который сработает только тогда, когда цена BTC достигнет 40 000 долларов. С рыночным ордером мы в основном говорили покупать / продавать по любой цене, по которой в настоящее время торгуется актив. Это заполнится мгновенно.

Для этого давайте вернемся к Trade New Order . Мы собираемся продемонстрировать тип ответа ( newOrderRespType ), который является параметром, который мы можем настроить в зависимости от ответа, который мы хотим получить от сервера. Есть три варианта здесь: ACK , РЕЗУЛЬТАТ , или ПОЛНЫЙ вы можете увидеть примеры каждого ответа здесь . Мы собираемся использовать ACK , который даст нам простое подтверждение того, что заказ был получен.

Ниже вы можете увидеть, что мы собирались подать рыночный ордер на продажу BNB за BUSD по текущей рыночной цене.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Обратите внимание, что ответ дает нам минимальную информацию:

Binance API Series Pt. I - Спотовая торговля с почтальоном

Вы можете убедиться, что заказ был заполнен конечной точкой / api / v3 / allOrders .

Проверка ваших сделок

Давайте, наконец, посмотрим на конечную точку для проверки ваших сделок:

GET / api / v3 / myTrades

Он находится в торговом списке торгового счета (USER_DATA) . Он позволяет вам проверять каждую сделку по определенному символу. Если вы хотите видеть все свои сделки для символа по умолчанию ( BTCUSDT ), просто снимите флажки startTime , endTime и fromId . Ответ вернет до 500 сделок, просто измените лимит, если хотите увидеть больше.

В Postman можно дополнительно раскрыть необработанный HTTP-запрос и ответ.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Это меню откроет консоль Postman, которая распечатывает детали каждого запроса.

Binance API Series Pt. I - Спотовая торговля с почтальоном

Целью этого руководства было мягко познакомить вас с Binance API, не написав ни единой строчки кода. Если вы следовали инструкциям, теперь у вас должно быть представление о том, как мы можем запрашивать и отправлять информацию.

В следующих частях этой серии мы расскажем о некоторых базовых концепциях кодирования, которые позволят нам автоматизировать покупку и продажу криптовалют и других цифровых активов.

А пока есть вопросы? Посетите наш растущий форум сообщества разработчиков Binance или ознакомьтесь с документацией.

Кратко расскажем, что такое ключи API Binance и для чего они нужны. Как и любые другие апи, на бинансе их создают для предоставления доступа внешним программам, которые осуществляют автоматическую торговлю на бирже. Сам ключ состоит некоторого набора букв и цифр, известных только трейдеру. Всего есть два типа апи на бинансе:

  • открытый (API-key) – можно предоставлять
  • секретный (закрытый или Secret Key) – хранить в надежном месте, предоставлять исключительно брокеру или программе

При помощи api key binance можно не только просматривать данные на кошельках аккаунта, но и совершать сделки, а также заводить и выводить активы. Ниже мы разберемся, как создать апи на бинансе и получить секретный код для фьючерсов.

Как создать апи ключ бинанс?

Процедура для получения API key проста и занимает не более 5 минут. Алгоритм действий:

  1. Авторизуемся на сайте www.binance.com или в приложении
  2. Заходим в “Управление API” через профиль (иконка пользователя), либо через меню слева
  3. Binance API - создание и настройка ключей

  4. Изучаем информацию на странице и нажимаем “Создать API”
  5. Binance API - создание и настройка ключей

  6. В типе выбираем “Сгенерированный системой” и идем далее
  7. Binance API как подключить

  8. Создаем метку для ключа (придумываем название, чтобы не путаться в будущем)
  9. Binance API

  10. Проходим проверку кода доступа и проверку безопасности. Вводим все коды верификации, которые подключены.

Таким образом мы получили binance api.

Binance API - создание и настройка ключей

Важно! Сохраните ключи в надежном месте, так как при обновлении страницы его больше не покажут. Если вы не скопировали данные или забыли текущее API подключение – придется создавать новое. Не рекомендуем передавать ключи апи от биржи бинанс третьим лицам, во избежании потери активов!

Как создать апи ключ бинанс для фьючерсов

Стоит понимать, что созданный api key binance имеет очень ограниченный права. Для фьючерсной или любой другой торговли он совсем не подходит. Дальше нужно отредактировать ключ. Для этого выбираем “Редактировать ограничения” и включаем нужные опции.

Binance API - как удалить ключ

Обратите внимание на пункт “Ограничение доступа по IP”. Если выбрать Неограниченный (менее безопасный), то доступ будет с любого ip адреса, а сам ключ работает всего 3 месяца. Сам бинанс не рекомендует его использовать. Если мы разрешаем доступ только доверенным IP адресам, то каждый из них нужно вбить в строку вручную.

Binance API - создание и настройка ключей

Нужно знать, что подключение апи на бинансе имеют свои ограничения, нарушение которых может повлечь бан аккаунта. Также стоит обратить внимание на правила безопасности, нарушив которые можно потерять средства на кошельке. Эти правила прописаны на странице создания управления:

Регистрируйся с указанием реферального ID: AHJUCEJW и получай скидку до 40% на комиссии в бинанс на все операции.

  1. На одном профиле нельзя создавать более 30 ключей API.
  2. Не передавать никому API, секретный ключ (HMAC) или приватный (RSA). Нужно относиться к API на Binance, секретному (HMAC) или приватному ключу (RSA) так же, как и к своим паролям, чтобы избежать потери криптовалюты.
  3. Рекомендуется разрешать доступ только к доверенным IP-адресам для обеспечения безопасности аккаунта.
  4. Невозможно создать API на Бинанс, если не прошли верификацию KYC.

Как удалить ключи апи на бинансе?

Для этого необходимо пройти в уже знакомый раздел “Управление API”, выбрать нужный и напротив его нажать кнопку “Удалить”.

Binance API - создание и настройка ключей

И подтвердить операцию.

Binance API - создание и настройка ключей

Если у вас имеются какие-либо вопросы по созданию или настройке ключей API Binance – задавайте их в комментарии к записи.

Понравилась статья? Поделить с друзьями:
  • Сероквель инструкция по применению таблетки взрослым от чего назначают
  • Гуопп моб мвд республики беларусь руководство
  • Снять классное руководство приказ образец
  • Экотрит в 25 инструкция по применению
  • Примаксетин инструкция по применению цена отзывы мужчин таблетки аналоги дешевые