Работа с API Binance: описание, код и примеры
Биржа 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, и вставьте туда этот код:
Для тестирования методов, создайте в этой же папке второй файл, например, binance_test.py, туда вставьте вот такой код (подставьте свои API ключи):
После этого код можно запускать. К примеру, если вы только установили Python и не знаете, что делать, найдите редактор Idle (он устанавливается вместе с питоном), в нем File -> Open, откройте файл binance_test.py и нажмите F5. Код, представленный выше, вернет информацию по вашему аккаунту — подробности ниже.
Еще немного общей информации: практически во всех подписанных запросах необходимо указывать параметр timestamp — это текущее unix-время в милиосекундах. Но, так как некоторые сети бывают перегружены, то ваш запрос может заблудиться и придти позже. Поэтому биржа предоставляет вам временное окно (по умолчанию 5000 милисекунд). Если у вас запросы не успевают придти в это окно, вы можете его расширить с помощью параметра recvWindow. Но, думаю, это мало кому понадобится.
Публичные запросы
Проверка связи — /api/v1/ping
Метод для проверки работы API.
Возвращает пустой словарь
Ссылка для просмотра в браузере https://api.binance.com/api/v1/ping.
Вес — 1
Код для проверки:
Получение времени биржи — /api/v1/time
Ссылка для просмотра в браузере https://api.binance.com/api/v1/time
Вес — 1
Возвращает словарь с текущим временем:
Код для проверки:
Настройки и лимиты биржи — /api/v1/exchangeInfo
Ссылка для просмотра в браузере https://api.binance.com/api/v1/exchangeInfo
Вес — 1
Возвращает структуру данных:
Ключ rateLimits ведет на массив с лимитами — сколько запросов в секунду/минуту/день можно делать.
Ключ symbols содержит настройки для каждой пары — рассмотрим одну, ETHBTC
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.
Код для проверки:
Открытые ордера на бирже — /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
Возвращает значения:
bids — это списки цен/объемов на покупку, asks — на продажу.
Пример кода:
Последние (чужие) сделки — /api/v1/trades
Принимает параметры:
Обязательные:
symbol — пара
Необязательные:
limit — кол-во возвращаемых записей (максимум 500, по умолчанию 500).
Вес — 1
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/trades?symbol=ETHBTC
Пример ответа:
id — id сделки
price — цена
qty — количество
time — время сделки
isBuyerMaker — была ли покупка по указанной покупателем цене,
isBestMatch — была ли встречная сделка
Пример кода:
Сжатая история сделок — /api/v1/aggTrades
Метод позволяет получить суммарную историю сделок. Сделки, выполненные в одно время по одному ордеру и по одной цене будут представлены одной строкой с объединенным количеством.
Вес — 1
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/aggTrades?symbol=ETHBTC
Принимает параметры:
Обязательные:
symbol — пара
Необязательные:
fromID — показывать начиная со сделки № (включительно)
startTime — начиная с какого времени (включительно)
endTime — заканчивая каким временем (включительно)
limit — Кол-во записей (максимум 500, по умолчанию 500)
Возвращает данные:
Данные по свечам – /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, то возвращаются самые последние свечи.
Пример ответа:
Статистика за 24 часа — /api/v1/ticker/24hr
Вес – 1, если указана пара, иначе вес равен (количеству всех торгуемых пар)/2.
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/ticker/24hr?symbol=BNBBTC
Параметры:
Необязательные:
symbol – пара
Если symbol не указан, возвращаются данные по всем парам. В этом случае, считается, что вы сделали столько запросов к бирже, сколько вернулось пар.
Пример ответа:
Если пар несколько, то такие словари вкладываются в массив, вот так:
Последняя цена по паре (или парам) — /api/v3/ticker/price
Вес — 1
Параметры:
Необязательные:
symbol – пара
Если параметр symbol не указан, то возвращаются цены по всем парам.
Ссылка для просмотра в браузере: https://api.binance.com/api/v3/ticker/price?symbol=BNBBTC
Пример ответа:
Или (если не указан параметр)
Лучшие цены покупки/продажи — /api/v3/ticker/bookTicker
Вес 1
Параметры:
Необязательные:
symbol – пара
Если параметр symbol не указан, возвращаются данные по всем парам.
Ссылка для просмотра в браузере: https://api.binance.com/api/v3/ticker/bookTicker?symbol=BNBBTC
Пример ответа:
Или (если не указан параметр):
Авторизованные запросы:
Создание ордера — /api/v3/order
Вес – 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_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:
General Info
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 /papi/v1/um/order
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 | 22BjeOROKiXJ3NxbR3zjh3uoGcaflPu3VMyBXAg8Jj2J1xVSnY0eB4dzacdE9IWn |
| secretKey | YtP1BudNOWZE1ag5uzCkh4hIC7qSmQOu797r5EJBFGhxBYivjj8HIX0iiiPof5yG |
| Parameter | Value |
|---|---|
| symbol | BTCUSDT |
| side | BUY |
| type | LIMIT |
| timeInForce | GTC |
| quantity | 1 |
| price | 2000 |
| recvWindow | 5000 |
| timestamp | 1611825601400 |
Example 1: As a request body
Example 1
HMAC SHA256 signature:
- requestBody:
symbol=BTCUSDT &side=BUY
&type=LIMIT
&timeInForce=GTC
&quantity=1
&price=2000
&recvWindow=5000
×tamp=1611825601400
Example 2: As a query string
Example 2
HMAC SHA256 signature:
queryString:
symbol=BTCUSDT
&side=BUY
&type=LIMIT
&timeInForce=GTC
&quantity=1
&price=2000
&recvWindow=5000
×tamp=1611825601400
Example 3: Mixed query string and request body
Example 3
HMAC SHA256 signature:
- queryString:
- requestBody:
Note that the signature is different in example 3. There is no & between "GTC" and "quantity=1".
### RSA Keys — SIGNED Endpoint Examples for POST /papi/v1/um/order
- 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 | vE3BDAL1gP1UaexugRLtteaAHg3UO8Nza20uexEuW1Kh3tVwQfFHdAiyjjY428o2 |
| Parameter | Value |
|---|---|
| symbol | BTCUSDT |
| side | BUY |
| type | LIMIT |
| timeInForce | GTC |
| quantity | 1 |
| price | 2000 |
| recvWindow | 5000 |
| timestamp | 1611825601400 |
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 console $ echo -n 'timestamp=1671090801999&recvWindow=9999999&symbol=BTCUSDT&side=SELL&type=MARKET&quantity=1.23' | openssl dgst -keyform PEM -sha256 -sign ./test-prv-key.pem
2.2 — Sign payload using RSASSA-PKCS1-v1_5 algorithm with SHA-256 hash function.
Step 2.3 console $ echo -n 'timestamp=1671090801999&recvWindow=9999999&symbol=BTCUSDT&side=SELL&type=MARKET&quantity=1.23' | openssl dgst -keyform PEM -sha256 -sign ./test-prv-key.pem | openssl enc -base64 aap36wD5loVXizxvvPI3wz9Cjqwmb3KVbxoym0XeWG1jZq8umqrnSk8H8dkLQeySjgVY91Ufs%2BBGCW%2B4sZjQEpgAfjM76riNxjlD3coGGEsPsT2lG39R%2F1q72zpDs8pYcQ4A692NgHO1zXcgScTGgdkjp%2Brp2bcddKjyz5XBrBM%3D
2.3 — Encode output as base64 string.
Step 2.4 console $ echo -n 'timestamp=1671090801999&recvWindow=9999999&symbol=BTCUSDT&side=SELL&type=MARKET&quantity=1.23' | openssl dgst -keyform PEM -sha256 -sign ./test-prv-key.pem | openssl enc -base64 | tr -d '\n' aap36wD5loVXizxvvPI3wz9Cjqwmb3KVbxoym0XeWG1jZq8umqrnSk8H8dkLQeySjgVY91Ufs%2BBGCW%2B4sZjQEpgAfjM76riNxjlD3coGGEsPsT2lG39R%2F1q72zpDs8pYcQ4A692NgHO1zXcgScTGgdkjp%2Brp2bcddKjyz5XBrBM%3D
2.4 — Delete any newlines in the signature.
Step 2.5 console aap36wD5loVXizxvvPI3wz9Cjqwmb3KVbxoym0XeWG1jZq8umqrnSk8H8dkLQeySjgVY91Ufs%2BBGCW%2B4sZjQEpgAfjM76riNxjlD3coGGEsPsT2lG39R%2F1q72zpDs8pYcQ4A692NgHO1zXcgScTGgdkjp%2Brp2bcddKjyz5XBrBM%3D
2.5 — Since the signature may contain / and = , this could cause issues with sending the request. So the signature has to be URL encoded.
Step 2.6 console curl -H "X-MBX-APIKEY: vE3BDAL1gP1UaexugRLtteaAHg3UO8Nza20uexEuW1Kh3tVwQfFHdAiyjjY428o2" -X POST 'https://papi.binance.com/papi/v1/um/order?timestamp=1671090801999&recvWindow=9999999&symbol=BTCUSDT&side=SELL&type=MARKET&quantity=1.23&signature=aap36wD5loVXizxvvPI3wz9Cjqwmb3KVbxoym0XeWG1jZq8umqrnSk8H8dkLQeySjgVY91Ufs%2BBGCW%2B4sZjQEpgAfjM76riNxjlD3coGGEsPsT2lG39R%2F1q72zpDs8pYcQ4A692NgHO1zXcgScTGgdkjp%2Brp2bcddKjyz5XBrBM%3D'
2.6 — curl command
A sample Bash script containing similar steps is available in the right side.
Public API Definitions
Terminology
- baseasseet refers to the asset that is the quantity of a symbol.
- quoteAsset refers to the asset that is the price of a symbol.
- Margin refers to Cross Margin
- UM refers to USD-M Futures
- CM refers to Coin-M Futures
ENUM definitions
Order side
- BUY
- SELL
Position side for Futures
- BOTH
- LONG
- SHORT
Time in force
- GTC — Good Till Cancel
- IOC — Immediate or Cancel
- FOK — Fill or Kill
- GTX — Good Till Crossing (Post Only)
Response Type (newOrderRespType)
- ACK
- RESULT
Order types (type)
- LIMIT
- MARKET
Conditional Order types (strategyType)
- STOP
- STOP_MARKET
- TAKE_PROFIT
- TAKE_PROFIT_MARKET
- TRAILING_STOP_MARKET
Working Type for Futures Conditional Orders (workingType)
- MARK_PRICE
Order status (status)
- NEW
- CANCELED
- REJECTED
- PARTIALLY_FILLED
- FILLED
- EXPIRED
Conditional Order status (strategyStatus)
- NEW
- CANCELED
- TRIGGERED — conditional order is triggered
- FINISHED — triggered order is filled
- EXPIRED
Futures Contract type (contractType):
- PERPETUAL
- CURRENT_MONTH
- NEXT_MONTH
- CURRENT_QUARTER
- NEXT_QUARTER
- PERPETUAL_DELIVERING
Contract status(contractStatus,status):
- PENDING_TRADING
- TRADING
- PRE_DELIVERING
- DELIVERING
- DELIVERED
- PRE_SETTLE
- SETTLING
- CLOSE
Rate limiters (rateLimitType)
- REQUEST_WEIGHT
- ORDERS
Rate limit intervals (interval)
- MINUTE
Filters
Filters define trading rules on a symbol or an exchange.
Symbol filters
PRICE_FILTER
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:
- sell order price >= minPrice
- buy order price <= maxPrice
- ( price — minPrice ) % tickSize == 0
ExchangeInfo format: javascript
LOT_SIZE
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 allowed.
- maxQty defines the maximum quantity allowed.
- stepSize defines the intervals that a quantity can be increased/decreased by.
In order to pass the lot size , the following must be true for quantity :
- quantity >= minQty
- quantity <= maxQty
- ( quantity — minQty ) % stepSize == 0
/exchangeInfo format: javascript
PERCENT_PRICE
The PERCENT_PRICE filter defines valid range for a price based on the mark price in Futures and on the average of the previous trades in Cross Margin. For Cross Margin 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 : * Futures BUY: price <= markPrice * multiplierUp SELL: price >= markPrice * multiplierDown * Cross Margin BUY: price <= weightedAveragePrice * multiplierUp SELL: price >= weightedAveragePrice * multiplierDown
MIN_NOTIONAL
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 . Since MARKET orders have no price, the mark price is used in Futures and the average price is used over the last avgPriceMins for Cross Margin. avgPriceMins is the number of minutes the average price is calculated over. 0 means the last price is used.
MARKET_LOT_SIZE
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 — minQty ) % stepSize == 0
MAX_NUM_ORDERS
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.
/exchangeInfo format: javascript
MAX_NUM_ALGO_ORDERS
The MAX_NUM_ALGO_ORDERS filter defines the maximum number of all kinds of algo orders an account is allowed to have open on a symbol. The algo orders include STOP , STOP_MARKET , TAKE_PROFIT , TAKE_PROFIT_MARKET , and TRAILING_STOP_MARKET orders.
/exchangeInfo format: javascript
Market Data Endpoints
Test Connectivity
Test connectivity to the Rest API.
Weight: 1
Parameters: NONE
New Order
Send in a new order/orders.
New UM Order (TRADE)
POST /papi/v1/um/order (HMAC SHA256)
Weight(order): 1
Parameters:
| Name | Type | Mandatory | Description |
|---|---|---|---|
| symbol | STRING | YES | |
| side | ENUM | YES | |
| positionSide | ENUM | NO | Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode. |
| type | ENUM | YES | LIMIT , MARKET |
| timeInForce | ENUM | NO | |
| quantity | DECIMAL | NO | |
| reduceOnly | STRING | NO | "true" or "false". default "false". Cannot be sent in Hedge Mode . |
| price | DECIMAL | NO | |
| newClientOrderId | STRING | NO | A unique id among open orders. Automatically generated if not sent. Can only be string following the rule: ^[\.A-Z\:/a-z0-9_-]<1,32>$ |
| newOrderRespType | ENUM | NO | ACK , RESULT , default ACK |
| recvWindow | LONG | NO | |
| timestamp | LONG | YES |
Additional mandatory parameters based on type:
- If newOrderRespType is sent as RESULT :
- MARKET order: the final FILLED result of the order will be return directly.
- LIMIT order with special timeInForce : the final status result of the order(FILLED or EXPIRED) will be returned directly.
New CM Order (TRADE)
POST /papi/v1/cm/order (HMAC SHA256)
Weight(order): 1
Parameters:
Name Type Mandatory Description symbol STRING YES side ENUM YES positionSide ENUM NO Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode. type ENUM YES "LIMIT", "MARKET" timeInForce ENUM NO quantity DECIMAL NO reduceOnly STRING NO "true" or "false". default "false". Cannot be sent in Hedge Mode. price DECIMAL NO newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent. Can only be string following the rule: ^[\.A-Z\:/a-z0-9_-]<1,32>$ newOrderRespType ENUM NO "ACK", "RESULT", default "ACK" recvWindow LONG NO timestamp LONG YES Additional mandatory parameters based on type :
- If newOrderRespType is sent as RESULT :
- MARKET order: the final FILLED result of the order will be return directly.
- LIMIT order with special timeInForce : the final status result of the order(FILLED or EXPIRED) will be returned directly.
New Margin Order (TRADE)
POST /papi/v1/margin/order (HMAC SHA256)
Weight(order): 1
Parameters:
Name Type Mandatory Description symbol STRING YES 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. 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. icebergQty DECIMAL NO Used with LIMIT , STOP_LOSS_LIMIT , and TAKE_PROFIT_LIMIT to create an iceberg order 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 Borrow (MARGIN)
Apply for a margin loan.
Weight: 100
Parameters:
Name Type Mandatory Description asset STRING YES amount DECIMAL YES recvWindow LONG NO The value cannot be greater than 60000 timestamp LONG YES Margin Account Repay (MARGIN)
Repay for a margin loan.
Weight: 100
Parameters:
Name Type Mandatory Description asset STRING YES amount DECIMAL YES recvWindow LONG NO The value cannot be greater than 60000 timestamp LONG YES Margin Account New OCO (TRADE)
POST /papi/v1/margin/order/oco (HMAC SHA256)
Send in a new OCO for a margin account
Weight(order): 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 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.
New UM Conditional Order (TRADE)
Weight(Order): 1
Parameters:
Name Type Mandatory Description symbol STRING YES side ENUM YES positionSide ENUM NO Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode. strategyType ENUM YES "STOP", "STOP_MARKET", "TAKE_PROFIT", "TAKE_PROFIT_MARKET", and "TRAILING_STOP_MARKET" timeInForce ENUM NO quantity DECIMAL NO reduceOnly STRING NO "true" or "false". default "false". Cannot be sent in Hedge Mode ; cannot be sent with closePosition = true price DECIMAL NO workingType ENUM NO stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" priceProtect STRING NO "TRUE" or "FALSE", default "FALSE". Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders newClientStrategyId STRING NO A unique id among open orders. Automatically generated if not sent. Can only be string following the rule: ^[\.A-Z\:/a-z0-9_-]<1,32>$ stopPrice DECIMAL NO Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders. activationPrice DECIMAL NO Used with TRAILING_STOP_MARKET orders, default as the mark price callbackRate DECIMAL NO Used with TRAILING_STOP_MARKET orders, min 0.1, max 5 where 1 for 1% recvWindow LONG NO timestamp LONG YES Additional mandatory parameters based on type:
- Order with type STOP/TAKE_PROFIT , parameter timeInForce can be sent ( default GTC ).
- Condition orders will be triggered when:
- STOP , STOP_MARKET :
- BUY: "MARK_PRICE" >= stopPrice
- SELL: "MARK_PRICE" <= stopPrice
- BUY: "MARK_PRICE" <= stopPrice
- SELL: "MARK_PRICE" >= stopPrice
- BUY: the lowest mark price after order placed <= activationPrice , and the latest mark price >= the lowest mark price * (1 + callbackRate )
- SELL: the highest mark price after order placed >= activationPrice , and the latest mark price <= the highest mark price * (1 — callbackRate )
- BUY: activationPrice should be smaller than latest mark price.
- SELL: activationPrice should be larger than latest mark price.
Condition orders will be triggered when:
- If parameter priceProtect is sent as true:
- when price reaches the stopPrice ,the difference rate between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than the "triggerProtect" of the symbol
- "triggerProtect" of a symbol can be got from GET /fapi/v1/exchangeInfo
- BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
- SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
- BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
- SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
New CM Conditional Order (TRADE)
Weight(Order): 1
Parameters:
Name Type Mandatory Description symbol STRING YES side ENUM YES positionSide ENUM NO Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode. strategyType ENUM YES "STOP", "STOP_MARKET", "TAKE_PROFIT", "TAKE_PROFIT_MARKET", and "TRAILING_STOP_MARKET" timeInForce ENUM NO quantity DECIMAL NO reduceOnly STRING NO "true" or "false". default "false". Cannot be sent in Hedge Mode price DECIMAL NO workingType ENUM NO stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" priceProtect STRING NO "TRUE" or "FALSE", default "FALSE". Used with STOP / STOP_MARKET or TAKE_PROFIT / TAKE_PROFIT_MARKET orders newClientStrategyId STRING NO A unique id among open orders. Automatically generated if not sent. Can only be string following the rule: ^[\.A-Z\:/a-z0-9_-]<1,36>$ stopPrice DECIMAL NO Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders. activationPrice DECIMAL NO Used with TRAILING_STOP_MARKET orders, default as the mark price callbackRate DECIMAL NO Used with TRAILING_STOP_MARKET orders, min 0.1, max 5 where 1 for 1% recvWindow LONG NO timestamp LONG YES Additional mandatory parameters based on type:
- Order with type STOP/TAKE_PROFIT , parameter timeInForce can be sent ( default GTC ).
- Condition orders will be triggered when:
- STOP , STOP_MARKET :
- BUY: "MARK_PRICE" >= stopPrice
- SELL: "MARK_PRICE" <= stopPrice
- BUY: "MARK_PRICE" <= stopPrice
- SELL: "MARK_PRICE" >= stopPrice
- BUY: the lowest mark price after order placed <= activationPrice , and the latest mark price >= the lowest mark price * (1 + callbackRate )
- SELL: the highest mark price after order placed >= activationPrice , and the latest mark price <= the highest mark price * (1 — callbackRate )
- BUY: activationPrice should be smaller than latest mark price.
- SELL: activationPrice should be larger than latest mark price.
Condition orders will be triggered when:
- If parameter priceProtect is sent as true:
- when price reaches the stopPrice ,the difference rate between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than the "triggerProtect" of the symbol
- "triggerProtect" of a symbol can be got from GET /fapi/v1/exchangeInfo
- BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
- SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
- BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
- SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
Cancel Order
Cancel an active order/orders.
Cancel UM Order (TRADE)
DELETE /papi/v1/um/order (HMAC SHA256)
Cancel an active UM LIMIT order
Weight: 1
Parameters:
- Either orderId or origClientOrderId must be sent.
Cancel All UM Open Orders (TRADE)
DELETE /papi/v1/um/allOpenOrders (HMAC SHA256)
Cancel all active LIMIT orders on specific symbol
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES Cancel CM Order (TRADE)
DELETE /papi/v1/cm/order (HMAC SHA256)
Cancel an active LIMIT order
Weight: 1
Parameters:
- Either orderId or origClientOrderId must be sent.
Cancel All CM Open Orders (TRADE)
DELETE /papi/v1/cm/allOpenOrders (HMAC SHA256)
Cancel all active LIMIT orders on specific symbol
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES Cancel Margin Account Order (TRADE)
DELETE /papi/v1/margin/order (HMAC SHA256)
Cancel Margin Account Order
Weight: 2
Parameters:
- Either orderId or origClientOrderId must be sent.
Cancel Margin Account All Open Orders on a Symbol (TRADE)
DELETE /papi/v1/margin/allOpenOrders (HMAC SHA256)
Weight: 5
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO The value cannot be greater than 60000 timestamp LONG YES Cancel Margin Account OCO Orders(TRADE)
DELETE /papi/v1/margin/orderList (HMAC SHA256)
Cancel Margin Account OCO Orders
Weight: 2
Parameters:
- Additional notes: Canceling an individual leg will cancel the entire OCO
Cancel UM Conditional Order (TRADE)
DELETE /papi/v1/um/conditional/order (HMAC SHA256)
Weight: 1
Parameters:
- Either strategyId or newClientStrategyId must be sent.
Cancel All UM Open Conditional Orders (TRADE)
DELETE /papi/v1/um/conditional/allOpenOrders (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES Cancel CM Conditional Order (TRADE)
DELETE /papi/v1/cm/conditional/order (HMAC SHA256)
Weight: 1
Parameters:
- Either strategyId or newClientStrategyId must be sent.
Cancel All CM Open Conditional Orders (TRADE)
DELETE /papi/v1/cm/conditional/allOpenOrders (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES Query Order
Query UM Order (USER_DATA)
GET /papi/v1/um/order (HMAC SHA256)
Check an UM order's status.
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES orderId LONG NO origClientOrderId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either orderId or origClientOrderId must be sent. * These orders will not be found: * order status is CANCELED or EXPIRED , AND * order has NO filled trade, AND * created time + 3 days < current time
Query Current UM Open Order (USER_DATA)
GET /papi/v1/um/openOrder (HMAC SHA256)
Query current UM open order
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES orderId LONG NO origClientOrderId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either orderId or origClientOrderId must be sent. * If the queried order has been filled or cancelled, the error message "Order does not exist" will be returned.
Query All Current UM Open Orders (USER_DATA)
GET /papi/v1/um/openOrders (HMAC SHA256)
Get all open orders on a symbol. Careful when accessing this with no symbol.
Weight: 1 for a single symbol; 40 when the symbol parameter is omitted
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Notes: * If the symbol is not sent, orders for all symbols will be returned in an array.
Query All UM Orders (USER_DATA)
GET /papi/v1/um/allOrders (HMAC SHA256)
Get all account UM orders; active, canceled, or filled.
- These orders will not be found:
- order status is CANCELED or EXPIRED , AND
- order has NO filled trade, AND
- created time + 3 days < current time
Weight: 5
Parameters:
- If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.
- The query time period must be less then 7 days( default as the recent 7 days).
Query CM Order (USER_DATA)
GET /papi/v1/cm/order (HMAC SHA256)
Check an CM order's status.
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES orderId LONG NO origClientOrderId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either orderId or origClientOrderId must be sent. * These orders will not be found: * order status is CANCELED or EXPIRED , AND * order has NO filled trade, AND * created time + 3 days < current time
Query Current CM Open Order (USER_DATA)
GET /papi/v1/cm/openOrder (HMAC SHA256)
Query current CM open order
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES orderId LONG NO origClientOrderId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either orderId or origClientOrderId must be sent. * If the queried order has been filled or cancelled, the error message "Order does not exist" will be returned.
Query All Current CM Open Orders (USER_DATA)
GET /papi/v1/cm/openOrders (HMAC SHA256)
Get all open orders on a symbol. Careful when accessing this with no symbol.
Weight:
1 for a single symbol; 40 when the symbol parameter is omitted
Parameters:
Name Type Mandatory Description symbol STRING NO pair STRING NO recvWindow LONG NO timestamp LONG YES Notes: * If the symbol is not sent, orders for all symbols will be returned in an array.
Query All CM Orders (USER_DATA)
GET /papi/v1/cm/allOrders (HMAC SHA256)
Get all account CM orders; active, canceled, or filled.
Weight:
20 with symbol 40 with pair
Parameters:
- Either symbol or pair must be sent.
- If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.
- These orders will not be found:
- order status is CANCELED or EXPIRED , AND
- order has NO filled trade, AND
- created time + 3 days < current time
Query Current UM Open Conditional Order (USER_DATA)
GET /papi/v1/um/conditional/openOrder (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES strategyId LONG NO newClientStrategyId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either strategyId or newClientStrategyId must be sent. * If the queried order has been CANCELED , TRIGGERED 或 EXPIRED , the error message "Order does not exist" will be returned.
Query All Current UM Open Conditional Orders (USER_DATA)
GET /papi/v1/um/conditional/openOrders (HMAC SHA256)
Get all open conditional orders on a symbol. Careful when accessing this with no symbol.
Weight: 1 for a single symbol; 40 when the symbol parameter is omitted
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Notes: * If the symbol is not sent, orders for all symbols will be returned in an array.
Query UM Conditional Order History (USER_DATA)
GET /papi/v1/um/conditional/orderHistory (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES strategyId LONG NO newClientStrategyId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either strategyId or newClientStrategyId must be sent. * NEW orders will not be found. * These orders will not be found: * order status is CANCELED or EXPIRED , AND * order has NO filled trade, AND * created time + 7 days < current time
Query All UM Conditional Orders (USER_DATA)
GET /papi/v1/um/conditional/allOrders (HMAC SHA256)
Weight: 1 for a single symbol; 40 when the symbol parameter is omitted
Parameters:
Name Type Mandatory Description symbol STRING NO strategyId LONG NO startTime LONG NO endTime LONG NO limit INT NO Default 500; max 1000. recvWindow LONG NO timestamp LONG YES Notes: * These orders will not be found: * order strategyStatus is CANCELED or EXPIRED , AND * order has NO filled trade, AND * created time + 7 days < current time * The query time period must be less than 7 days( default as the recent 7 days).
Query Current CM Open Conditional Order (USER_DATA)
GET /papi/v1/cm/conditional/openOrder (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES strategyId LONG NO newClientStrategyId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either strategyId or newClientStrategyId must be sent. * If the queried order has been triggered, cancelled or expired, the error message "Order does not exist" will be returned.
Query All Current CM Open Conditional Orders (USER_DATA)
GET /papi/v1/cm/conditional/openOrders (HMAC SHA256)
Get all open conditional orders on a symbol. Careful when accessing this with no symbol.
Weight: 1 for a single symbol; 40 when the symbol parameter is omitted
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Notes: * If the symbol is not sent, orders for all symbols will be returned in an array.
Query CM Conditional Order History (USER_DATA)
GET /papi/v1/cm/conditional/orderHistory (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES strategyId LONG NO newClientStrategyId STRING NO recvWindow LONG NO timestamp LONG YES Notes: * Either strategyId or newClientStrategyId must be sent. * NEW orders will not be found. * These orders will not be found: * order status is CANCELED or EXPIRED , AND * order has NO filled trade, AND * created time + 7 days < current time
Query All CM Conditional Orders (USER_DATA)
Weight: 1 for a single symbol; 40 when the symbol parameter is omitted
Parameters:
Name Type Mandatory Description symbol STRING NO strategyId LONG NO startTime LONG NO endTime LONG NO limit INT NO Default 500; max 1000. recvWindow LONG NO timestamp LONG YES Notes: * These orders will not be found: * order strategyStatus is CANCELED or EXPIRED , AND * order has NO filled trade, AND * created time + 7 days < current time * The query time period must be less than 7 days( default as the recent 7 days).
Query Margin Account Order (USER_DATA)
Weight: 5
Parameters:
- 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 Current Margin Open Order (USER_DATA)
GET /papi/v1/margin/openOrders (HMAC SHA256)
Weight: 5
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO The value cannot be greater than 60000 timestamp LONG YES Notes: * 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.
Query All Margin Account Orders (USER_DATA)
GET /papi/v1/margin/allOrders (HMAC SHA256)
Weight: 100
Request Limit: 60times/min per IP
Parameters:
- 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.
Query Margin Account's OCO (USER_DATA)
GET /papi/v1/margin/orderList (HMAC SHA256)
Retrieves a specific OCO based on provided optional parameters
Weight: 5
Parameters:
Name Type Mandatory Description orderListId LONG NO Either orderListId or origClientOrderI d 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)
GET /papi/v1/margin/allOrderList (HMAC SHA256)
Query all OCO for a specific margin account based on provided optional parameters
Weight: 100
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 Query Margin Account's Open OCO (USER_DATA)
GET /papi/v1/margin/openOrderList (HMAC SHA256)
Weight: 5
Parameters:
Name Type Mandatory Description recvWindow LONG NO The value cannot be greater than 60000 timestamp LONG YES Margin Account Trade List (USER_DATA)
GET /papi/v1/margin/myTrades (HMAC SHA256)
Weight: 5
Parameters:
- If fromId is set, it will get trades >= that fromId. Otherwise most recent trades are returned.
Account
Account Balance(USER_DATA)
GET /papi/v1/balance (HMAC SHA256)
query account balance
Weight: 20
Parameters:
Name Type Mandatory Description asset STRING NO recvWindow LONG NO timestamp LONG YES Account Information(USER_DATA)
GET /papi/v1/account (HMAC SHA256)
Query account information
Weight: 20
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES Margin Max Borrow(USER_DATA)
GET /papi/v1/margin/maxBorrowable (HMAC SHA256)
Weight: 5
Query margin max borrow
Parameters:
Name Type Mandatory Description asset STRING YES recvWindow LONG NO The value cannot be greater than 60000 timestamp LONG YES Query Margin Max Withdraw(USER_DATA)
GET /papi/v1/margin/maxWithdraw (HMAC SHA256)
Weight: 5
Parameters:
Name Type Mandatory Description asset STRING YES recvWindow LONG NO The value cannot be greater than 60000 timestamp LONG YES Query UM Position Information(USER_DATA)
Get current UM position information.
Weight: 5
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Note Please use with user data stream ACCOUNT_UPDATE to meet your timeliness and accuracy needs.
- for One-way Mode user, the response will only show the "BOTH" positions
- for Hedge Mode user, the response will show "LONG", and "SHORT" positions.
Query CM Position Information(USER_DATA)
GET /papi/v1/cm/positionRisk (HMAC SHA256)
Get current CM position information.
Weight: 1
Parameters:
- If neither marginAsset nor pair is sent, positions of all symbols with TRADING status will be returned.
- for One-way Mode user, the response will only show the "BOTH" positions
- for Hedge Mode user, the response will show "LONG", and "SHORT" positions.
Note Please use with user data stream ACCOUNT_UPDATE to meet your timeliness and accuracy needs.
Change UM Initial Leverage (TRADE)
POST /papi/v1/um/leverage (HMAC SHA256)
Change user's initial leverage of specific symbol in UM.
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES leverage INT YES target initial leverage: int from 1 to 125 recvWindow LONG NO timestamp LONG YES Change CM Initial Leverage (TRADE)
Change user's initial leverage of specific symbol in CM.
POST /papi/v1/cm/leverage (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES leverage INT YES target initial leverage: int from 1 to 125 recvWindow LONG NO timestamp LONG YES Change UM Position Mode(TRADE)
POST /papi/v1/um/positionSide/dual (HMAC SHA256)
Change user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in UM
Weight: 1
Parameters:
Name Type Mandatory Description dualSidePosition STRING YES "true": Hedge Mode; "false": One-way Mode recvWindow LONG NO timestamp LONG YES Change CM Position Mode(TRADE)
POST /papi/v1/cm/positionSide/dual (HMAC SHA256)
Change user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in CM
Weight: 1
Parameters:
Name Type Mandatory Description dualSidePosition STRING YES "true": Hedge Mode; "false": One-way Mode recvWindow LONG NO timestamp LONG YES Get UM Current Position Mode(USER_DATA)
GET /papi/v1/um/positionSide/dual (HMAC SHA256)
Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in UM
Weight: 30
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES Get CM Current Position Mode(USER_DATA)
GET /papi/v1/cm/positionSide/dual (HMAC SHA256)
Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in CM
Weight: 30
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES UM Account Trade List (USER_DATA)
GET /papi/v1/um/userTrades (HMAC SHA256)
Get trades for a specific account and UM symbol.
Weight: 5
Parameters:
- If startTime and endTime are both not sent, then the last '24 hours' data will be returned.
- The time between startTime and endTime cannot be longer than 24 hours.
- The parameter fromId cannot be sent with startTime or endTime .
CM Account Trade List (USER_DATA)
Get trades for a specific account and CM symbol.
Weight: 20 with symbol 40 with pair
Parameters:
- Either symbol or pair must be sent
- symbol and pair cannot be sent together
- pair and fromId cannot be sent together
- If a pair is sent, tickers for all symbols of the pair will be returned
- The parameter fromId cannot be sent with startTime or endTime
- If startTime and endTime are both not sent, then the last '24 hours' data will be returned.
- The time between startTime and endTime cannot be longer than 24 hours.
UM Notional and Leverage Brackets (USER_DATA)
Query UM notional and leverage brackets
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES CM Notional and Leverage Brackets (USER_DATA)
Query CM notional and leverage brackets
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Query User's Margin Force Orders (USER_DATA)
GET /papi/v1/margin/forceOrders (HMAC SHA256)
Query user's margin force orders
Weight: 1
Parameters:
Name Type Mandatory Description 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 Query User's UM Force Orders (USER_DATA)
GET /papi/v1/um/forceOrders (HMAC SHA256)
Query User's UM Force Orders
Weight:
20 with symbol, 50 without symbol
Parameters:
- If autoCloseType is not sent, orders with both of the types will be returned
- If startTime is not sent, data within 7 days before endTime can be queried
Query User's CM Force Orders (USER_DATA)
GET /papi/v1/cm/forceOrders (HMAC SHA256)
Query User's CM Force Orders
Weight:
20 with symbol, 50 without symbol
Parameters:
- If "autoCloseType" is not sent, orders with both of the types will be returned
- If "startTime" is not sent, data within 7 days before "endTime" can be queried
Portfolio Margin UM Trading Quantitative Rules Indicators (USER_DATA)
Or (account violation triggered)
Weight: 1 for a single symbol 10 when the symbol parameter is omitted
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Get User Commission Rate for UM (USER_DATA)
GET /papi/v1/um/commissionRate (HMAC SHA256)
Weight: 20
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES Get User Commission Rate for CM (USER_DATA)
GET /papi/v1/cm/commissionRate (HMAC SHA256)
Weight: 20
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES Query Margin Loan Record(USER_DATA)
Query margin loan record
Weight: 10
Parameters:
- txId or startTime must be sent. txId takes precedence.
- Response in descending order
- The max interval between startTime and endTime is 30 days.
- If startTime and endTime not sent, return records of the last 7 days by default
- Set archived to true to query data from 6 months ago
Query Margin repay Record(USER_DATA)
Query margin repay record.
Weight: 10
Parameters:
- txId or startTime must be sent. txId takes precedence.
- Response in descending order
- The max interval between startTime and endTime is 30 days.
- If startTime and endTime not sent, return records of the last 7 days by default
- Set archived to true to query data from 6 months ago
Get Margin Borrow/Loan Interest History (USER_DATA)
GET/papi/v1/margin/marginInterestHistory (HMAC SHA256)
Weight: 1
Parameters:
- Response in descending order
- The max interval between startTime and endTime is 30 days.
- If startTime and 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
Query Portfolio Margin Negative Balance Interest History(USER_DATA)
Query interest history of negative balance for portfolio margin.
Weight: 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 Fund Auto-collection (TRADE)
Fund collection for Portfolio Margin
Weight: 750
Parameters:
- The BNB would not be collected from UM-PM account to the Portfolio Margin account.
- You can only use this function 500 times per hour in a rolling manner.
Fund Collection by Asset (TRADE)
Transfers specific asset from Futures Account to Margin account
Weight(IP):
Parameters:
- The BNB transfer is not be supported
BNB transfer (TRADE)
Weight: 750
Parameters:
- The endpoint can only be called 10 times per 10 minutes in a rolling manner
Get UM Income History (USER_DATA)
Response:
GET /papi/v1/um/income (HMAC SHA256)
Weight: 30
Parameters:
- If neither startTime nor endTime is sent, the recent 7-day data will be returned.
- If incomeType is not sent, all kinds of flow will be returned
- "trandId" is unique in the same incomeType for a user
- Income history only contains data for the last three months
Get CM Income History(USER_DATA)
Response:
GET /papi/v1/cm/income (HMAC SHA256)
Weight: 30
Parameters:
- If incomeType is not sent, all kinds of flow will be returned
- "trandId" is unique in the same "incomeType" for a user
- The interval between startTime and endTime can not exceed 200 days:
- If startTime and endTime are not sent, the last 200 days will be returned
Get UM Account Detail (USER_DATA)
Response:
GET /papi/v1/um/account (HMAC SHA256)
Get current UM account asset and position information.
Weight: 5
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES Get CM Account Detail (USER_DATA)
Response:
GET /papi/v1/cm/account (HMAC SHA256)
Get current CM account asset and position information.
Weight: 5
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES Change Auto-repay-futures Status (TRADE)
POST /papi/v1/repay-futures-switch (HMAC SHA256)
Change Auto-repay-futures Status
Weight(IP):
Parameters:
Name Type Mandatory Description autoRepay STRING YES Default: true ; false for turn off the auto-repay futures negative balance function recvWindow LONG NO timestamp LONG YES Get Auto-repay-futures Status (USER_DATA)
GET /papi/v1/repay-futures-switch (HMAC SHA256)
Query Auto-repay-futures Status
Weight(IP):
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES Repay futures Negative Balance (USER_DATA)
POST /papi/v1/repay-futures-negative-balance (HMAC SHA256)
Repay futures Negative Balance
Weight(IP):
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES UM Position ADL Quantile Estimation (USER_DATA)
Weight: 5
Parameters:
Values update every 30s.
Values 0, 1, 2, 3, 4 shows the queue position and possibility of ADL from low to high.
For positions of the symbol are in One-way Mode or isolated margined in Hedge Mode, "LONG", "SHORT", and "BOTH" will be returned to show the positions' adl quantiles of different position sides.
If the positions of the symbol are crossed margined in Hedge Mode:
- "HEDGE" as a sign will be returned instead of "BOTH";
- A same value caculated on unrealized pnls on long and short sides' positions will be shown for "LONG" and "SHORT" when there are positions in both of long and short sides.
CM Position ADL Quantile Estimation (USER_DATA)
Weight: 5
Parameters:
Values update every 30s.
Values 0, 1, 2, 3, 4 shows the queue position and possibility of ADL from low to high.
For positions of the symbol are in One-way Mode or isolated margined in Hedge Mode, "LONG", "SHORT", and "BOTH" will be returned to show the positions' adl quantiles of different position sides.
If the positions of the symbol are crossed margined in Hedge Mode:
- "HEDGE" as a sign will be returned instead of "BOTH";
- A same value caculated on unrealized pnls on long and short sides' positions will be shown for "LONG" and "SHORT" when there are positions in both of long and short sides.
User Data Streams
- The base API endpoint is: https://papi.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.
- Connection method for Websocket:
- Base Url: wss://fstream.binance.com/pm
- User Data Streams are accessed at /ws/<listenKey>
- Example: wss://fstream.binance.com/pm/ws/pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1
Start User Data Stream (USER_STREAM)
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
Keepalive User Data Stream (USER_STREAM)
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 60 minutes.
Weight: 1
Parameters:
Close User Data Stream (USER_STREAM)
Close out a user data stream.
Weight: 1
Parameters:
Event: User Data Stream Expired
When the listenKey used for the user data stream turns expired, this event will be pushed.
Notice:
- This event is not related to the websocket disconnection.
- This event will be received only when a valid listenKey in connection got expired.
- No more user data event will be updated after this event received until a new valid listenKey used.
Event: Futures Balance and Position Update
- Update Speed: 50ms
- Update under the following conditions:
- Account deposit or withdrawal
- A transfer occurs between trading accounts (e.g. transfer from spot to option accounts)
- Position changes
- Greek update
Event: Futures Order update
When new order created, order status changed will push such event. event type is ORDER_TRADE_UPDATE .
Side
- BUY
- SELL
Order Type
- MARKET
- LIMIT
- LIQUIDATION
Execution Type
- NEW
- CANCELED
- CALCULATED — Liquidation Execution
- EXPIRED
- TRADE
Order Status
- NEW
- PARTIALLY_FILLED
- FILLED
- CANCELED
- EXPIRED
Time in force
- GTC
- IOC
- FOK
- GTX
Liquidation and ADL:
- If user gets liquidated due to insufficient margin balance:
- c shows as "autoclose-XXX",X shows as "NEW"
- c shows as “adl_autoclose”,X shows as “NEW”
Event: Conditional Order Trade Update
When new order created, order status changed will push such event. event type is CONDITIONAL_ORDER_TRADE_UPDATE .
Side
- BUY
- SELL
Conditional Order Type
- STOP
- TAKE_PROFIT
- STOP_MARKET
- TAKE_PROFIT_MARKET
- TRAILING_STOP_MARKET
Execution Type
- NEW
- CANCELED
- CALCULATED — Liquidation Execution
- EXPIRED
- TRADE
Order Status
- NEW
- CANCELED
- EXPIRED
- TRIGGERING //Order meet the trigger condition
- TRIGGERED //Order pass the trigger condition check
- FINISHED
Time in force
- GTC
- IOC
- FOK
- GTX
Event: riskLevelChange
- When the user's position risk ratio is too high, this stream will be pushed.
- This message is only used as risk guidance information and is not recommended for investment strategies.
- RISK_LEVEL_CHANGE includes following types: MARGIN_CALL , SUPPLY_MARGIN , REDUCE_ONLY , FORCE_LIQUIDATION
- In the case of a highly volatile market, there may be the possibility that the user's position has been liquidated at the same time when this stream is pushed out.
Event: Futures Account Configuration Update (Leverage Update)
When the account configuration is changed, the event type will be pushed as ACCOUNT_CONFIG_UPDATE
When the leverage of a trade pair changes, the payload will contain the object ac to represent the account configuration of the trade pair, where s represents the specific trade pair and l represents the leverage.
Event: OpenOrderLoss Update
Event: Liability Update
Event: Margin 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.
Event: Margin Balance Update
Event: Margin Order Update
Margin 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.
- 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.
Error Codes
Here is the error JSON payload:
Errors consist of two parts: an error code and a message.
Codes are universal,but messages can vary.Как узнать о листинге на Binance до самого листинга?
Мы поговорим о том, что такое листинг, почему после появления в списке на листинг, цена монеты резко растет. И как узнать о потенциале той или иной монеты попасть в листинг на бирже Binance заранее и заработать на этом!
Обязательно подпишись на нас в Telegram мы публикуем там больше возможностей и отвечаем в чате на все вопросы.
Если еще не зарегистрированы на Binance — можете воспользоваться нашей реферальной ссылкой с бонусами — зарегистрироваться.
Для начала, скажем, что листинг — это процедура допуска монеты к торговле на бирже. Простыми словами, новая монета появляется в списке монет биржи. Это анонсируется, на хайпе монету начинают покупать и цена ее растет.
На недавнем примере проекта Gains Network после листинга 17 февраля 2023 года на Binance токен GNS вырос за 4 часа почти на 100%.
Именно такие импульсы позволяют зарабатывать хорошую прибыль.
Очень часто рост цены происходит после анонса о предстоящем листинге. Уже после новости о том, что монета попала в список листинга происходит ее резкий памп (рост). Но как узнать о потенциале токена или монеты попасть в листинг? И купить монету до того, как произойдет рост?
Найти точную дату листинга монеты или токена крайне сложно. Обычно данные держат в строгом секрете. Первая новость о добавлении в торги новой крипты публикуется за 24 часа в официальных ресурсах биржи и разработчиков проекта. На Binance новые крипто-листинги публикуется в разделе “Объявления”.
Но есть аналитический способ предсказать появление токена или монеты в списке листинга на бирже.
Один из сервисов, которые мы используем в аналитике проектов — https://cryptorank.io/. Что нужно сделать:
В верхнем меню открываем фонды. Если язык интерфейса английский — вы можете сменить его на русский в верхнем правом углу.
Далее в списке фондов находим Binance Labs — фонд венчурного капитала Binance. Они часто инвестируют в проекты, токены или монеты которых с очень большой вероятностью будут зарегистрированы на бирже Binance. Так как это в их интересах.
Итак, выбрав Binance Labs вы можете увидеть все криптосистемы, в которые инвестировал данный фонд. Многие из перечисленных проектов уже зарегистрированы на Binance.
На картинке ниже представлена первая страница, где вы найдете популярные токены/монеты: APT, SAND, EGLD, CAKE, CHZ и другие. Они уже есть на Binance.
Проекты с обозначениями N/A еще не имеют собственного токена, пока что они нам не интересны, мы их пропускаем.
Нас же интересуют те, которые имеют свой токен и еще не зарегистрированы на бирже Binance, но имеют достаточно сильный потенциал и высокий шанс на это. И таких проектов не так уж много. На первых трех страницах этого раздела перечислены криптосистемы, листинг которых уже состоялся.
Следует анализировать проекты начиная с третьей или четвертой страницы. Чтобы узнать, на каких биржах уже состоялся листинг — нажмите на проект (у меня это Troy TROY)
И перейдите на Котировки
Вы увидите биржи, на которых торгуется монета/токен. В данном случае это Binance и Gate.io. Такой проект мы пропускаем, так как он уже котируется на интересующей нас бирже.
Давайте разберем один из проектов, который еще не котируется на Binance. А именно Cere Network (CERE).
На что обращаем внимание:
1 — Капитализация — умножение количества криптоактивов в обращении на цену соответствующего актива. Простыми словами это стоимость выкупленного объема. Чем выше этот показатель, тем актив более привлекателен для инвесторов.
Cere Network имеет капитализацию $ 36,648,365, что очень даже неплохо
2 — Котировки — видим, что на еще не было листинга на Binance.
3 — Фонды — кто еще инвестировал в проект.
Мы видим, что кроме Binance Labs еще есть ряд привлекательных инвесторов, таких как Kenetic Capital, LD Capital, NGC Ventures, Arrington XRP Capital Ledger, OKX Blockdream Ventures, AU21 Capital и Polygon Fund.
Кроме того, в проект было инвестировано $31M, из них $3M было инвестировано фондом Polygon (информация взята из источника).
Проведенный анализ показывает, что проект имеет высокие шансы на листинг на бирже Binance.
Таким образом, вы можете самостоятельно оценивать проекты, которые имеют потенциал скорого листинга. Мы советуем следить за новостями проекта, который вы выбрали как потенциальный. Если вы уже зарегистрированы на другой бирже, где этот токен уже торгуется, то отслеживая момент листинга, вы можете купить токен/монету до подъема цены.
Если статья была полезна — ставь отметку и подписывайся на канал.
Задать вопрос или обсудить вопрос по тестнетам, NFT или инвестициям можно в нашем чате:
Расскажу вам ребята про то как происходит листинг. Эксклюзив из первых рук. Есть несколько контор, занимающихся листингом. Заветная цифра для всех — 1 млн долларов. За процент от токенов, от 30 до 70, в зависимости от жадности. Код проверяется несколькими консалт агентствами, чтобы это не был откровенный скам. Дальше они требуют заморозки оставшихся токенов у владельца. За этим через сеть карманных ломов идет разгон, памп, на хаях инвестор сливает свою долю. Мой знакомый так выводил свой проект, инвестор дал 1 лям, на хаях заработал 15. Абсолютно легальная схема. Ничего личного, хомяки, так устроен бизнес больших ребят.
Способы заработать на Binance и как получать прибыль без больших рисков

Если вы уже слышали про Binance, то вы наверное уже понимаете, что эта самая крупная биржа в мире, которая предоставляет своим клиентам не только возможность покупки крипты / трейдинга. Она сразу представляет вам возможность покупать криптовалюту, трейдить с плечом (до 125X), вкладывать свои деньги и т.д.
реклама
В этой статье мы разберём основные функции биржи и функционал со стабильным увеличением своего портфеля без рисков потери крипты.
Покупка криптовалюты
Самое главное — это конечно же покупка криптовалюты, вы можете покупать крипту как у пользователей биржи, так и у самой биржи с комиссией (1 — 4%). Биржа предоставляет довольно маленькую комиссию для своих пользователей с учётом ещё и скидки на комиссии внутри системы при помощи реферальных бонусов, которые мы тоже рассмотрим. Купить можно довольно быстро даже без KYC подтверждения у биржи и с KYC для покупок на P2P.
реклама
Этот способ больше подходит для покупок крипты на долгий срок для инвесторов, которые наращивают свой портфель ценными активами.

Маржа: кросс(3X) и изолированная(10X)
Предназначены для торговли криптовалютой с торговыми плечами в 3X и 10X. Их разница в том, что кросс имеет общий кошелёк для торговли, а в изолированной ваш кошелёк поделён на торговые пары (BTC/USDT. ).
реклама
Это уже заработок с большими рисками и предназначен он для профессионалов, поэтому нужно быть крайне осторожным.
Комиссия на трейдинг рассчитывается почасово. В час — 0.09% / В день — 2.16%(VIP 0)

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

Binance Earn
Теперь же мы переходим к более безопасным видам заработка, но которые могут принести вам в разы меньше профита. Меньше риска = Меньше профита.
Первый из таких видов заработка на Binance — Binance Earn. Тут вы можете делать вклады в криптовалюту, как в обычных банках под годовые. Простой способ быстро положить деньги и начать зарабатывать.
Есть два основных вида вкладов
- Фиксированный вклад. Вы вкладываете крипту на определённый срок и не можете взять эти деньги до истечения времени. (высокие проценты)
- Гибкий вклад. Вы вкладываете крипту на неопределённый срок и можете забрать деньги в любой момент. (низкие проценты)

Binance Savings
Binance Savings — работает примерно так же как и Binance Earn. Разница только в процентах и в том что Savings — более сложный инструмент для заработка. А так суть примерно такая же: вы даёте в долг свои активы.
Кроме этого не смотрите на монеты с большими процентами, или же будьте крайне осторожны, так как большие проценты означают больший спрос на крипту на рынке, который не удовлетворяется, следовательно этому есть причины. Поэтому люди скорее всего понимают, что данный актив не надёжен и не покупают его. Или часто большие проценты связаны с раскруткой новых монет.

Binance Staking
Binance Staking — это система для стекинга криптовалют, имеет больший процент, но риски с датой стекинга, так как его могут постоянно переносить, но если вы — долгосрочный инвестор — и ваши монеты просто так лежат, то будет лучше всего положить их именно сюда.
Чтобы вы не искали, что такое стекинг:
Стекинг — это способ пассивного заработка, при котором пользователи хранят монеты на алгоритме Proof of Stake и обеспечивают работоспособность блокчейна. За это держатели цифровых монет получают вознаграждение. Другими словами, вы поддерживаете работу крипты, когда, например, разработчики совершают глобальные изменения по сети. Пример: стекинг эфира, к выходу Ethreum 2.0.

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

Binance Liquid Swap
Liquid Swap — Система для размещения монетных пар на пулах, для получения выгоды и помощи пулам.
Хорошие проценты на размещение, но перед началом нужно будет посмотреть руководство и узнать о возможных рисках.

Реферальные ссылки
Самая безопасная система для заработка — реферальная программа Binance. Вы можете рекомендовать Binance своим друзьям, делясь с ними своей реферальной ссылкой, с которой и вы и они получат выгоду, а именно вычет процентов из комиссии. Кроме друзей вы можете делиться ею в соц. сетях, очень яркий пример — видео на YouTube, или например в вашем блоге.
- STOP , STOP_MARKET :
- STOP , STOP_MARKET :