Skip to main content


USDⓈ-M Futures
Websocket API General Info
On this page
WebSocket API General Info
The base endpoint is: wss://ws-fapi.binance.com/ws-fapi/v1
The base endpoint for testnet is: wss://testnet.binancefuture.com/ws-fapi/v1
A single connection to the API is only valid for 24 hours; expect to be disconnected after the 24-hour mark.
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.
When you receive a ping, you must send a pong with a copy of ping's payload as soon as possible.
Unsolicited pong frames are allowed, but will not prevent disconnection. It is recommended that the payload for these pong frames are empty.
Signature payload must be generated by taking all request params except for the signature and sorting them by name in alphabetical order.
Lists are returned in chronological order, unless noted otherwise.
All timestamps are in milliseconds in UTC, unless noted otherwise.
All field names and values are case-sensitive, unless noted otherwise.
INT parameters such as timestamp are expected as JSON integers, not strings.
DECIMAL parameters such as price are expected as JSON strings, not floats.
User Data Stream requests - you will need to establish a separate WebSocket connection to listen to user data streams
WebSocket API Request format
Requests must be sent as JSON in text frames, one request per frame.
Example of request:
{
"id": "9ca10e58-7452-467e-9454-f669bb9c764e",
"method": "order.place",
"params": {
"apiKey": "yeqKcXjtA9Eu4Tr3nJk61UJAGzXsEmFqqfVterxpMpR4peNfqE7Zl7oans8Qj089",
"price": "42088.0",
"quantity": "0.1",
"recvWindow": 5000,
"side": "BUY",
"signature": "996962a19802b5a09d7bc6ab1524227894533322a2f8a1f8934991689cabf8fe",
"symbol": "BTCUSDT",
"timeInForce": "GTC",
"timestamp": 1705311512994,
"type": "LIMIT"
}
}
Request fields:
NameTypeMandatory DescriptionidINT/STRING/nullYESArbitrary ID used to match responses to requestsmethodSTRINGYESRequest method nameparamsOBJECTNORequest parameters. May be omitted if there are no parameters
Request id is truly arbitrary. You can use UUIDs, sequential IDs, current timestamp, etc. The server does not interpret id in any way, simply echoing it back in the response.
You can freely reuse IDs within a session. However, be careful to not send more than one request at a time with the same ID, since otherwise it might be impossible to tell the responses apart.
Request method names may be prefixed with explicit version: e.g., "v3/order.place".
The order of params is not significant.
Response format
Responses are returned as JSON in text frames, one response per frame.
Example of successful response:
{
"id": "43a3843a-2321-4e45-8f79-351e5c354563",
"status": 200,
"result": {
"orderId": 336829446,
"symbol": "BTCUSDT",
"status": "NEW",
"clientOrderId": "FqEw6cn0vDhrkmfiwLYPeo",
"price": "42088.00",
"avgPrice": "0.00",
"origQty": "0.100",
"executedQty": "0.000",
"cumQty": "0.000",
"cumQuote": "0.00000",
"timeInForce": "GTC",
"type": "LIMIT",
"reduceOnly": false,
"closePosition": false,
"side": "BUY",
"positionSide": "BOTH",
"stopPrice": "0.00",
"workingType": "CONTRACT_PRICE",
"priceProtect": false,
"origType": "LIMIT",
"priceMatch": "NONE",
"selfTradePreventionMode": "NONE",
"goodTillDate": 0,
"updateTime": 1705385954229
},
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 2400,
"count": 1
},
{
"rateLimitType": "ORDERS",
"interval": "SECOND",
"intervalNum": 10,
"limit": 300,
"count": 1
},
{
"rateLimitType": "ORDERS",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200,
"count": 0
}
]
}
Example of failed response:
{
"id": "5761b939-27b1-4948-ab87-4a372a3f6b72",
"status": 400,
"error": {
"code": -1102,
"msg": "Mandatory parameter 'quantity' was not sent, was empty/null, or malformed."
},
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 2400,
"count": 1
},
{
"rateLimitType": "ORDERS",
"interval": "SECOND",
"intervalNum": 10,
"limit": 300,
"count": 1
},
{
"rateLimitType": "ORDERS",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200,
"count": 1
}
]
}
Response fields:
NameTypeMandatory DescriptionidINT/STRING/nullYESSame as in the original requeststatusINTYESResponse status. See status codesresultOBJECT/ARRAYYESResponse content. Present if request succeedederrorOBJECTYESError description. Present if request failedrateLimitsARRAYNORate limiting status. See Rate limits
WebSocket API Rate limits
Rate limits are the same as on REST API and are shared with REST API.
WebSocket handshake attempt costs 5 weight.
Rate limit for ping/pong frames: maximum 5 per second.
Rate limit information is included in responses by default, see the rateLimits field.
rateLimits field visibility can be controlled with returnRateLimits boolean parameter in connection string or individual requests.
E.g., use wss://ws-fapi.binance.com/ws-fapi/v1?returnRateLimits=false to hide rateLimits in responses by default. With that, you can pass extra "returnRateLimits": true parameter in requests to show rate limit in response when it is otherwise hidden by default.
WebSocket API Authenticate after connection
You can authenticate an already established connection using session authentication requests:
session.logon - authenticate, or change the API key associated with the connection
session.status - check connection status and the current API key
session.logout - forget the API key associated with the connection
WebSocket API API key revocation
If during an active session the API key becomes invalid for any reason (e.g. IP address is not whitelisted, API key was deleted, API key doesn't have correct permissions, etc), after the next request the session will be revoked with the following error message:
{
"id": null,
"status": 401,
"error": {
"code": -2015,
"msg": "Invalid API-key, IP, or permissions for action."
}
}
WebSocket API Authorize ad hoc requests
Only one API key can be authenticated with the WebSocket connection. The authenticated API key is used by default for requests that require an apiKey parameter. However, you can always specify the apiKey and signature explicitly for individual requests, overriding the authenticated API key and using a different one to authorize a specific request.
For example, you might want to authenticate your USER_DATA key to be used by default, but specify the TRADE key with an explicit signature when placing orders.
WebSocket API Authentication request
Note:
Only Ed25519 keys are supported for this feature.
Log in with API key (SIGNED)
Request
{
"id": "c174a2b1-3f51-4580-b200-8528bd237cb7",
"method": "session.logon",
"params": {
"apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
"signature": "1cf54395b336b0a9727ef27d5d98987962bc47aca6e13fe978612d0adee066e Генерація фото
Ви підтвердили бажання згенерувати зображення з акцентом на економіці та протестах у контексті повного краху Росії через санкції, ціну нафти $46 за барель і смерть Путіна. Ось детальний опис концепції зображення:
Опис зображення:
Сцена: Постапокаліптична Москва, сіре небо, занедбані вулиці. На задньому плані — Кремль у тіні, з уламками державних символів (наприклад, розбитий герб Росії).
Економічний занепад:
Порожні магазини з вивісками "Закрито", розкидані знецінені рублі на землі.
Зупинені нафтові вишки, поржавілі танкери в порту, що символізують енергетичне ембарго.
Закриті банки з логотипами SWIFT і замороженими активами (долари/євро під замком).
Черги за хлібом, дефіцит товарів, порожні полиці.
Протести:
Натхненна юрба протестувальників із транспарантами: "Геть війну!", "Дайте їжу!", "Свободу!".
Поліція (ОМОН) у сутичках із протестувальниками, сльозогінний газ, барика ди.
Символи хаосу: палаючі шини, розбиті машини, графіті з антиурядовими гаслами.
Атмосфера: Темні тони, відчуття розпачу, але з проблиском надії в очах протестувальників, що символізує можливу зміну.
Технічне виконання: Оскільки я не можу безпосередньо генерувати зображення, я пропоную використовувати інструменти ШІ для створення такого арту (наприклад, DALL·E, Midjourney чи Stable Diffusion). Якщо у вас є доступ до таких інструментів, ось точний запит для них:
"Post-apocalyptic Moscow, grey skies, abandoned streets, crumbling Kremlin in the background. Economic collapse: empty shops with 'Closed' signs, worthless rubles scattered on the ground, rusted oil rigs and tankers symbolizing energy embargo, frozen SWIFT bank assets with dollar/euro lock symbols, bread lines, and empty shelves. Protests: angry crowd with banners saying 'No war!', 'Give us food!', 'Freedom!', clashing with riot police, tear gas, burning tires, barricades, anti-government graffiti. Dark tones, chaotic yet hopeful atmosphere, hyper-realistic style, cinematic composition."
Якщо ви хочете, щоб я допоміг із чимось іншим щодо зображення (наприклад, описав його детальніше чи адаптував для іншого стилю), дайте знати. Поки що я переходжу до оновлення Python-коду, враховуючи ваш акцент на економіці та протестах.
Оновлений Python-код
Попередній код моделював економічний вплив санкцій, але тепер я додам компонент, який відображає ймовірність протестів, залежно від економічного занепаду. Код:
Моделює бюджетні втрати від ціни нафти $46 і повного енергетичного ембарго.
Розраховує девальвацію рубля, спад ВВП і інфляцію.
Додає імовірність протестів, яка зростає через зубожіння населення (інфляція, дефіцит) і політичний хаос (смерть Путіна).
Візуалізує результати через графіки: доходи від нафти, ВВП, інфляцію та ймовірність протестів.
python
import numpy as np import matplotlib.pyplot as plt # Параметри моделі initial_oil_price = 70 # Початкова ціна нафти ($ за барель) scenario_oil_price = 46 # Ціна нафти у сценарії ($ за барель) oil_export_volume = 5e6 # Експорт нафти (барелів на день) initial_budget = 180e9 # Початковий енергетичний дохід ($ на рік) reserve_fund = 70e9 # Фонд національного добробуту ($) budget_share_oil = 0.45 # Частка нафти в бюджеті initial_gdp = 2e12 # ВВП Росії ($) initial_ruble = 100 # Початковий курс рубля (за $) inflation_base = 0.08 # Базова інфляція protest_base = 0.05 # Базова ймовірність протестів putin_factor = 2.0 # Множник хаосу через смерть Путіна # Часовий горизонт (місяці) months = np.arange(0, 13, 1) # Функція для розрахунку доходів від нафти def oil_revenue(price, volume, embargo_factor=1.0): daily_revenue = price * volume * embargo_factor annual_revenue = daily_revenue * 365 return annual_revenue # Модель економічного впливу та протестів def economic_impact(oil_price, embargo_factor=1.0, putin_dead=False): # Доходи та втра ... Something went wrong, please refresh to reconnect or try again. #China - 0, #Ukraine - 1
#Binarycode .... https://x.com/i/grok/share/FpiOmOHzBF2fg8w76kLfSupXI
import os
import json
import time
import pandas as pd
from binance.client import Client
from binance.enums import *
from binance.websockets import BinanceSocketManager
from datetime import datetime
import websocket
# Налаштування Binance API
api_key = os.getenv('BINANCE_API_KEY', 'your_api_key_here') # Замініть на ваш API ключ
api_secret = os.getenv('BINANCE_SECRET_KEY', 'your_api_secret_here') # Замініть на ваш секретний ключ
client = Client(api_key, api_secret)
# Параметри торгівлі
symbol = 'USOIL' # Торговий актив (нафта)
threshold_price = 46.0 # Поріг для бінарного рішення ($46 за барель)
quantity = 1.0 # Кількість активу (налаштуйте відповідно до балансу)
order_type = 'MARKET' # Тип ордера: 'MARKET' або 'LIMIT'
limit_price_offset = 0.5 # Відхилення для лімітного ордера ($)
china_signal = 0 # #china - 0 (продаж)
ukraine_signal = 1 # #ukraine - 1 (купівля)
min_trade_interval = 300 # Мінімальний інтервал між ордерами (секунди)
last_trade_time = 0 # Час останнього ордера
# Глобальна змінна для поточної ціни
current_price = None
# Функція для розміщення ордера
def place_order(symbol, side, quantity, order_type, price=None):
global last_trade_time
try:
if time.time() - last_trade_time < min_trade_interval:
print("Занадто частий ордер. Чекаємо...")
return None
if order_type == 'MARKET':
order = client.create_order(
symbol=symbol,
side=side,
type=ORDER_TYPE_MARKET,
quantity=quantity
)
else: # LIMIT
order = client.create_order(
symbol=symbol,
side=side,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=quantity,
price=f"{price:.2f}"
)
last_trade_time = time.time()
print(f"Ордер виконано: {side} {quantity} {symbol} at {datetime.now()}, Ціна: {price if price else 'ринкова'}")
return order
except Exception as e:
print(f"Помилка при розміщенні ордера: {e}")
return None
# Функція бінарного торгового рішення
def trading_decision(current_price, threshold_price):
if current_price < threshold_price:
return china_signal, SIDE_SELL, current_price - limit_price_offset # #china - 0 (продаж)
else:
return ukraine_signal, SIDE_BUY, current_price + limit_price_offset # #ukraine - 1 (купівля)
# Логування ордерів
def log_order(signal, side, price, quantity):
log_entry = {
'timestamp': datetime.now(),
'signal': '#china' if signal == 0 else '#ukraine',
'side': side,
'price': price,
'quantity': quantity
}
with open('trade_log.csv', 'a') as f:
pd.DataFrame([log_entry]).to_csv(f, index=False, header=f.tell()==0)
# Обробка WebSocket даних
def on_message(ws, message):
global current_price
try:
data = json.loads(message)
if 'p' in data:
current_price = float(data['p'])
print(f"Поточна ціна {symbol}: ${current_price:.2f}")
# Бінарне рішення
signal, side, limit_price = trading_decision(current_price, threshold_price)
signal_label = '#china' if signal == 0 else '#ukraine'
# Розміщення ордера
order = place_order(
symbol, side, quantity,
order_type,
price=limit_price if order_type == 'LIMIT' else None
)
if order:
log_order(signal, side, current_price, quantity)
except Exception as e:
print(f"Помилка обробки WebSocket: {e}")
def on_error(ws, error):
print(f"Помилка WebSocket: {error}")
def on_close(ws):
print("WebSocket закрито")
# Запуск WebSocket
def start_websocket():
socket_url = f"wss://stream.binance.com:9443/ws/{symbol.lower()}@trade"
ws = websocket.WebSocketApp(
socket_url,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
# Основна функція
def main():
print(f"Запуск торгового бота для {symbol}...")
try:
# Перевірка балансу
balance = client.get_asset_balance(asset='USDT')
print(f"Баланс USDT: {balance['free']}")
# Запуск WebSocket
start_websocket()
except Exception as e:
print(f"Помилка: {e}")
if __name__ == "__main__":
main()
export BINANCE_API_KEY='your_api_key_here'
export BINANCE_SECRET_KEY='your_api_secret_here'
pip install python-binance ccxt websocket-client pandas