Skip to main content

Binance Margin Trade Connector

Features

crypto-binanceConnector Key
Instruments
FX
Request Types
SUBMITCANCEL
Order Types
MARKETLIMITSTOPSTOP_LIMIT
Time In Force
GTCIOCFOK
Order ID Mapper
SEQUENCE
Order Status Request
Cancel On Disconnect
Commission
Post Only
Fast Cancel
Fast Replace

Notes

Margin Trading

Connector works in MARGIN mode only.

Some info about Binance margin trading: https://www.binance.vision/tutorials/binance-margin-trading-guide

API Key Permissions

Binance API-keys can be configured to only access certain types of secure endpoints.

The following Security Types for API key must be enabled for proper connector's functionality:

  • TRADE
  • USER_DATA
  • USER_STREAM

API Key Types

Two types of API Keys are supported: HMAC and Ed25519.

The connector first attempts to use the provided apiSecret as an Ed25519 key. If that fails, it falls back to using apiSecret for HMAC signature computation.

note

Ed25519 private key must contain -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- parts. It can be configured as a single-line parameter using # character as a line separator.

Rate Limits

Rate limits available via the following public REST API request: https://api.binance.com/api/v3/exchangeInfo

  • The /api/v3/exchangeInfo rateLimits array contains objects related to the exchange's RAW_REQUEST, REQUEST_WEIGHT, and ORDER rate limits.
  • A 429 is returned when either rate limit is violated.
  • Each route has a weight which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier weight.
  • When a 429 is received, it's your obligation as an API to back off and not spam the API.
  • Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (http status 418).
  • IP bans are tracked and scale in duration for repeat offenders, from 2 minutes to 3 days.
  • The limits on the API are based on the IPs, not the API keys.
  • The order rate limit is counted against each account.
  • Note: The connector does not currently track rate limit usage.

Client Order ID

Allowed characters: a-z, A-Z, 0-9, -, _. Maximum length is 36 characters.

Source and format of the Client Order ID are controlled by the orderMapperType setting:

Order Mapper TypeClient Order ID sourceRules and Restrictions
SEQUENCEOrder request's sequence numbersequence is numeric. clientOrderIdPrefix setting can be used for customization.
COMPOSITEOrder request's sourceId and orderIdsourceId and orderId are concatenated with '-' delimiter. Important: '-' cannot be used in sourceId. clientOrderIdPrefix is not applied to the Client Order ID.

Margin Automatic Borrowing

Margin auto-borrow is controlled by Side Effect Type order attribute.

Note: automatic borrowing occurs just before order placement and is not repaid on order cancellation.

From the exchange documentation:

  • Automatic borrowing: Place a buy/sell order by automatically borrowing crypto assets according to the user's maximum leverage. In short, it is equivalent to "borrowing + (ordinary) ordering".
  • Note: The borrowing is completed when the order is successfully placed, and the borrowing is not related to the completion of the order.
  • Automatic repayment: After the buy/sell order is completed, the system automatically uses the received crypto assets to repay the asset's liabilities. In short, it is equivalent to "(ordinary) order + order filled + repayment".
  • After the order is filled, if the amount is not sufficient to repay the loan of the asset, the system will choose to repay 90% of the loan asset, and the remaining liabilities need to be repaid manually by the user.
  • You need to repay in the same asset you borrowed (e.g. borrowed BTC, repay in BTC) and the interest will be paid before the principal.
  • If an automatic borrowing order is canceled, a corresponding interest may still be generated. You can check your borrowing history by visiting the [Repayment History] page.

Side Effect Type

When margin trading is enabled, the side effect type can be specified per order via the 6101 (SideEffectType) attribute. The default value can be set in the connector settings.

Side Effect Type settingSide Effect Type for BUY ordersSide Effect Type for SELL orders
NO_SIDE_EFFECTNO_SIDE_EFFECTNO_SIDE_EFFECT
MARGIN_BUYMARGIN_BUYMARGIN_BUY
AUTO_REPAYAUTO_REPAYAUTO_REPAY
AUTO_BORROW_REPAYAUTO_BORROW_REPAYAUTO_BORROW_REPAY
MARGIN_BUY_REPAY_SELLMARGIN_BUYAUTO_REPAY
MARGIN_SELL_REPAY_BUYAUTO_REPAYMARGIN_BUY

Filters and errors

Filters define trading rules on a symbol or an exchange.

Exchange and symbol filters information can be retrieved via public REST API: https://api.binance.com/api/v3/exchangeInfo

Timing security

If the recvWindow connector setting is 0, the recvWindow parameter is omitted from requests.

From the exchange specification:

A SIGNED endpoint also requires a parameter, timestamp, to be sent which should be the millisecond timestamp of when the request was created and sent. An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The logic is as follows:

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

It's recommended to use a small recvWindow of 5_000 or less. The max cannot go beyond 60_000.

WebSocket

A single connection to stream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark.

Self Trade Prevention

Default Self Trade Prevention Mode value for specific symbol can be found here: https://api.binance.com/api/v3/exchangeInfo

From the exchange STP Function FAQ:

Symbols may be configured to allow different sets of STP modes and take different default STP modes. defaultSelfTradePreventionMode - Orders will use this STP mode if the user does not provide one on order placement. allowedSelfTradePreventionModes - Defines the allowed set of STP modes for order placement on that symbol.

Symbology

Currency pairs without separator, case-sensitive — uppercase required, e.g. BTCUSDT, LTCUSDT. For the full list of available currency pairs, see the exchange GUI or query the REST API: https://api.binance.com/api/v3/exchangeInfo

Configuration

Connector settings

ParameterDefault ValueDescription
recvWindowIf recvWindow is not sent, it defaults to 5000. It's recommended to use a small recvWindow of 5_000 or less. The max cannot go beyond 60_000. See Timing security section for detailed explanation.
websocketHeartbeatInterval30mKeepalive period for a user data stream. User data streams will close after 60 minutes. It's recommended to send a ping about every 30 minutes.
staleWebsocketTimeout5sTimeout for reconnection when no websockets messages received after any order message sent to exchange.
selfTradePreventionModeEXPIRE_MAKEROptional setting for Self-Trade Prevention function. Supported values: EXPIRE_MAKER, EXPIRE_TAKER, EXPIRE_BOTH.
sideEffectTypeNO_SIDE_EFFECTOnly for margin trading type. You will be able to use coins as collateral to borrow funds with MARGIN_BUY. To repay your debt use AUTO_REPAY. Supported values: NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY, AUTO_BORROW_REPAY, MARGIN_BUY_REPAY_SELL, MARGIN_SELL_REPAY_BUY. See Side Effect Type section for detailed explanation.
clientOrderIdPrefixOptional prefix for Client Order ID. Only the following symbols are accepted by exchange: 'a'-'z', 'A'-'Z', '0'-'9', '-', '_'. See Client Order ID section for detailed explanation.
orderMapperTypeSEQUENCEType of the mapper which is used to map order to Client Order ID. Supported values: COMPOSITE, SEQUENCE. See Client Order ID section for detailed explanation.
binanceSyncSettings.ordersRequestSizeLimit200Limitation for the number of orders in the all orders history response. Maximum value is 1000.
binanceSyncSettings.tradesRequestSizeLimit100Limitation for the number of trades in the account trade list history response. Maximum value is 1000.

Supported order attributes

KeyDescription
1818 (PostOnly) attribute relevant only for LIMIT orders. Switches between LIMIT and LIMIT_MAKER order types. Possible values: 6.
6100Stop order type can be changed with 6100 (StopOrderType) attribute. Possible values: StopLoss or TakeProfit. Default value is StopLoss.
6101When margin trading enabled, side effect type can be specified for each order via 6101 (SideEffectType) attribute. Default value can be specified in connector settings. Possible values: NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY, AUTO_BORROW_REPAY, MARGIN_BUY_REPAY_SELL, MARGIN_SELL_REPAY_BUY. See Side Effect Type section for detailed explanation.
6102Self-Trade Prevention function mode can be specified for each order via 6102 (SelfTradePreventionMode) attribute. Default value can be specified in connector settings. Possible values: EXPIRE_MAKER, EXPIRE_TAKER, EXPIRE_BOTH.

Config sample

connectors {
BINANCE: ${template.connector.crypto.binance} {
settings {
restUrl = "https://api.binance.com"
websocketUrl = "wss://ws-api.binance.com:443/ws-api/v3"

apiKeys: [
{
apiKey = "<API_KEY>"
apiSecret = "<API_SECRET>"
}
]
}
}
}