Files
ritmex-bot/docs/binance/binance_derivatives/docs_derivatives_coin-margined-futures_websocket-api-general-info.md
DisneyandGitHub d6399b92aa Feat/support binance (#22)
* add docs

* Add Binance exchange support

- Updated the environment configuration to include Binance as a selectable exchange option.
- Enhanced the README documentation to reflect the addition of Binance.
- Implemented the Binance exchange adapter and integrated it into the existing exchange framework.
- Modified the basis arbitrage strategy to support Binance alongside existing exchanges.
- Added tests to ensure proper functionality and integration of Binance within the trading system.

* Enhance README with detailed Binance exchange configuration

- Added comprehensive instructions for setting up Binance as an exchange option.
- Included environment variable specifications for API keys, market types, and trading symbols.
- Provided examples for both perpetual and spot trading strategies.
- Clarified the use of WebSocket and REST for the Binance adapter.

* Enhance exchange support and testing framework

- Added a new test suite for exchange contracts to ensure consistency and functionality across supported exchanges.
- Refactored exchange ID handling to utilize a centralized list of supported exchanges, improving maintainability.
- Updated CLI argument parsing and help documentation to reflect the new exchange structure.
- Introduced utility functions for validating supported exchanges and their display names.
- Enhanced the BasisApp and strategy runner to leverage the new exchange validation logic.
- Added a new test command for running exchange-related tests.

* Refactor exchange contract tests and update CLI commands

- Removed the trailing supported exchanges set and simplified the logic for trailing stop support in the exchange contract tests.
- Updated the test command for exchange contracts to exclude unnecessary tests, streamlining the testing process.
- Enhanced test descriptions for clarity and improved understanding of the functionality being tested.
2026-02-27 11:37:44 +08:00

15 KiB
Raw Permalink Blame History

title, source, fetched_at
title source fetched_at
Websocket API General Info | Binance Open Platform https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info 2026-01-27T05:28:07.643Z

WebSocket API General Info

  • The base endpoint is: wss://ws-dapi.binance.com/ws-dapi/v1
    • The base endpoint for testnet is: wss://testnet.binancefuture.com/ws-dapi/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": "60fa4366-f96e-42fe-a82b-f819952c6db4",  "method": "order.place",  "params": {    "apiKey": "",    "price": "50000",    "quantity": 1,    "side": "BUY",    "symbol": "BTCUSD_PERP",    "timeInForce": "GTC",    "timestamp": 1728413737111,    "type": "LIMIT",    "signature": "996962a19802b5a09d7bc6ab1524227894533322a2f8a1f8934991689cabf8fe",  }}

Request fields:

Name

Type

Mandatory

 Description

id

INT/STRING/null

YES

Arbitrary ID used to match responses to requests

method

STRING

YES

Request method name

params

OBJECT

NO

Request 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": "60fa4366-f96e-42fe-a82b-f819952c6db4",    "status": 200,    "result": {        "orderId": 333245211,        "symbol": "BTCUSD_PERP",        "pair": "BTCUSD",        "status": "NEW",        "clientOrderId": "5SztZiGFAxgAqw4J9EN9fA",        "price": "50000",        "avgPrice": "0.00",        "origQty": "1",        "executedQty": "0",        "cumQty": "0",        "cumBase": "0",        "timeInForce": "GTC",        "type": "LIMIT",        "reduceOnly": false,        "closePosition": false,        "side": "BUY",        "positionSide": "BOTH",        "stopPrice": "0",        "workingType": "CONTRACT_PRICE",        "priceProtect": false,        "origType": "LIMIT",        "updateTime": 1728413795125    },    "rateLimits": [        {            "rateLimitType": "REQUEST_WEIGHT",            "interval": "MINUTE",            "intervalNum": 1,            "limit": 2400,            "count": 6        },        {            "rateLimitType": "ORDERS",            "interval": "MINUTE",            "intervalNum": 1,            "limit": 1200,            "count": 1        }    ]}

Example of failed response:

{  "id": "9ca10e58-7452-467e-9454-f669bb9c764e",  "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": "MINUTE",      "intervalNum": 1,      "limit": 1200,      "count": 1    }  ]}

Response fields:

Name

Type

Mandatory

 Description

id

INT/STRING/null

YES

Same as in the original request

status

INT

YES

Response status. See status codes

result

OBJECT/ARRAY

YES

Response content. Present if request succeeded

error

OBJECT

YES

Error description. Present if request failed

rateLimits

ARRAY

NO

Rate 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-dapi.binance.com/ws-dapi/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

Authenticate WebSocket connection using the provided API key.

After calling session.logon, you can omit apiKey and signature parameters for future requests that require them.

Note that only one API key can be authenticated. Calling session.logon multiple times changes the current authenticated API key.

Weight: 2

Method: "session.logon"

Parameters

Name

Type

Mandatory

 Description

apiKey

STRING

YES

recvWindow

INT

NO

signature

STRING

YES

timestamp

INT

YES

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": "1cf54395b336b0a9727ef27d5d98987962bc47aca6e13fe978612d0adee066ed",    "timestamp": 1649729878532  }}

Response

{  "id": "c174a2b1-3f51-4580-b200-8528bd237cb7",  "status": 200,  "result": {    "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",    "authorizedSince": 1649729878532,    "connectedSince": 1649729873021,    "returnRateLimits": true,    "serverTime": 1649729878630  },	"rateLimits": [        {            "rateLimitType": "REQUEST_WEIGHT",            "interval": "MINUTE",            "intervalNum": 1,            "limit": 2400,            "count": 2        }    ]}

Query session status

Query the status of the WebSocket connection, inspecting which API key (if any) is used to authorize requests.

Weight: 2

Method: "session.status"

Parameters: None

Request

{  "id": "b50c16cd-62c9-4e29-89e4-37f10111f5bf",  "method": "session.status"}

Response

{  "id": "b50c16cd-62c9-4e29-89e4-37f10111f5bf",  "status": 200,  "result": {    // if the connection is not authenticated, "apiKey" and "authorizedSince" will be shown as null    "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",    "authorizedSince": 1649729878532,    "connectedSince": 1649729873021,    "returnRateLimits": true,    "serverTime": 1649730611671  },	"rateLimits": [        {            "rateLimitType": "REQUEST_WEIGHT",            "interval": "MINUTE",            "intervalNum": 1,            "limit": 2400,            "count": 4        }    ]}

Log out of the session

Forget the API key previously authenticated. If the connection is not authenticated, this request does nothing.

Note that the WebSocket connection stays open after session.logout request. You can continue using the connection, but now you will have to explicitly provide the apiKey and signature parameters where needed.

Weight: 2

Method: "session.logout"

Parameters: None

SIGNED (TRADE and USER_DATA) Endpoint Security

SIGNED request example (Ed25519)

Parameter

Value

symbol

BTCUSD_PERP

side

SELL

type

LIMIT

timeInForce

GTC

quantity

1

price

0.2

timestamp

1668481559918

Request

{  "id": "c174a2b1-3f51-4580-b200-8528bd237cb7",  "method": "session.logout"}

Response

{  "id": "c174a2b1-3f51-4580-b200-8528bd237cb7",  "status": 200,  "result": {    "apiKey": null,    "authorizedSince": null,    "connectedSince": 1649729873021,    "returnRateLimits": false,    "serverTime": 1649730611671  },	"rateLimits": [        {            "rateLimitType": "REQUEST_WEIGHT",            "interval": "MINUTE",            "intervalNum": 1,            "limit": 2400,            "count": 6        }    ]}

A sample code in Python to show how to sign the payload with an Ed25519 key is available below.

#!/usr/bin/env python3import base64import timeimport jsonfrom cryptography.hazmat.primitives.serialization import load_pem_private_keyfrom websocket import create_connection# Set up authenticationAPI_KEY='put your own API Key here'PRIVATE_KEY_PATH='test-prv-key.pem'# Load the private key.# In this example the key is expected to be stored without encryption,# but we recommend using a strong password for improved security.with open(PRIVATE_KEY_PATH, 'rb') as f:    private_key = load_pem_private_key(data=f.read(),                                       password=None)# Set up the request parametersparams = {    'apiKey':        API_KEY,    'symbol':       'BTCUSD_PERP',    'side':         'SELL',    'type':         'LIMIT',    'timeInForce':  'GTC',    'quantity':     '1.0000000',    'price':        '0.20'}# Timestamp the requesttimestamp = int(time.time() * 1000) # UNIX timestamp in millisecondsparams['timestamp'] = timestamp# Sign the requestpayload = '&'.join([f'{param}={value}' for param, value in sorted(params.items())])signature = base64.b64encode(private_key.sign(payload.encode('ASCII')))params['signature'] = signature.decode('ASCII')# Send the requestrequest = {    'id': 'my_new_order',    'method': 'order.place',    'params': params}ws = create_connection("wss://ws-dapi.binance.com/ws-dapi/v1")ws.send(json.dumps(request))result =  ws.recv()ws.close()print(result)

A sample code in Python to show how to sign the payload with an Ed25519 key is available on the right side.