Skip to main content

Binance Portfolio Margin Trade Connector

Features

crypto-binancepmConnector Key
Instruments
FXFUTURE
Request Types
SUBMITCANCELREPLACE
Order Types
MARKETLIMIT
Time In Force
GTCIOCFOK
Order ID Mapper
SEQUENCE
Order Status Request
Cancel On Disconnect
Commission
Post Only
Fast Cancel
Fast Replace

Notes

Product Type

The Binance Portfolio Margin account supports trading across multiple product types. Set the specific product type via the <attributeKey>ProductType column in Security Metadata. Binance-to-connector product type mapping:

Exchange Product TypeConnector Product Type
Spot/MarginSPOT
USDⓈ-M FuturesFUTURE
COIN-M FuturesDELIVERY

Connector uses a valid value from the column as a product type for an instrument. When the column value is absent for an instrument, the product type is inferred from the instrument type and the futureInstrumentCurrencies / deliveryInstrumentCurrencies configuration settings. At least one of these currency lists must be specified and non-empty.

Connector uses the following checks to determine a product type for an instrument:

Instrument TypefutureInstrumentCurrenciesdeliveryInstrumentCurrenciesInstrument CurrencyResulting Product Type
FXnot usednot usednot usedSPOT
FUTUREnot defineddefineddelivery currencyDELIVERY
FUTUREnot defineddefinednon-delivery currencyFUTURE
FUTUREdefinednot definedfuture currencyFUTURE
FUTUREdefinednot definednon-future currencyDELIVERY
FUTUREdefineddefinedfuture currencyFUTURE
FUTUREdefineddefineddelivery currencyDELIVERY
FUTUREdefineddefinednon-future and non-delivery currencyunsupported instrument

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 connector's proper 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.

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

Replacement

Important: Orders with SPOT product type symbols DO NOT SUPPORT replacement.

Order Replacement limitations:

When the new quantity or price doesn't satisfy PRICE_FILTER / PERCENT_FILTER / LOT_SIZE, amendment will be rejected and the order will stay as it is.

However the order will be cancelled by the amendment in the following situations:

  • when the order is in partially filled status and the new quantity <= executedQty
  • when the order is GTX and the new price will cause it to be executed immediately

One order can only be modified for less than 10000 times

Modify order will set selfTradePreventionMode to NONE

Rate Limits

IP Limits:

  • Every request will contain X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) in the response headers which has the current used weight for the IP for all request rate limiters defined.
  • Each route has a weight which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier weight.
  • When a 429 is received, it's your obligation as an API to back off and not spam the API.
  • Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).
  • IP bans are tracked and scale in duration for repeat offenders, from 2 minutes to 3 days.
  • The limits on the API are based on the IPs, not the API keys.
  • Portfolio Margin IP Limit is 6000/min.
  • Note: The connector does not currently track rate limit usage.

Order Rate Limits:

  • Every order response will contain a X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter) header which has the current order count for the account for all order rate limiters defined.
  • Rejected/unsuccessful orders are not guaranteed to have X-MBX-ORDER-COUNT-** headers in the response.
  • The order rate limit is counted against each account.
  • Portfolio Margin Order Limits are 1200/min.
  • 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.

Side Effect Type

Important: Applies to orders with SPOT instruments only.

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

Note: automatic borrowing is performed just before order placement and is not repaid on cancellation by default. To enable automatic repayment on cancellation, set autoRepayAtCancel to true.

For SPOT instrument orders, specify the side effect type per order via 6101 (SideEffectType) attribute. The default value can be set in the connector settings.

  • NO_SIDE_EFFECT (normal mode): It places a buy/sell order using the existing assets in the Margin Account. Under normal circumstances, you’d need to manually borrow and repay on the Portfolio Margin platform, or through requests POST /papi/v1/marginLoan and/or POST /papi/v1/repayLoan.
  • MARGIN_BUY (automatic borrowing): It automatically borrows assets to place a buy/sell order based on your maximum leverage level. It’s equivalent to "borrow asset + place order".
  • Please note that borrowing is considered complete when the order is successfully placed. It doesn’t mean that your order is executed.
  • AUTO_REPAY (automatic repayment): After the buy/sell order is complete, the system will automatically use the received assets to repay that asset’s liabilities. Simply put, it’s equivalent to “place order + order execution + repayment".
  • Your repayment needs to be the same cryptocurrency as the one you borrowed. For example, if you borrowed ETH, your account must have ETH when you repay.
  • Any repayment will be applied to the outstanding interest first before being used to reduce the outstanding principal.
  • AUTO_BORROW_REPAY (automatic borrowing and repayment, simultaneously): When the user places an order, combining MARGIN_BUY and AUTO_REPAY modes, it completes "borrow asset + place order + order execution + repayment".

Connector maps Side Effect Type value the following way:

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

Position Mode

Important: Applies to orders with FUTURE and DELIVERY instruments only.

Binance Portfolio Margin supports One-Way and Hedge position mode for FUTURE (USDⓈ-M Futures) and DELIVERY (COIN-M Futures) products.

In Hedge mode it is possible to hold long and short positions on the same contract simultaneously, allowing traders to maintain long-term positions while participating in short-term movements.

To switch position mode, use the Binance exchange GUI directly. The trade connector does not support switching position modes.

Position Side

Important: Applies to orders with FUTURE and DELIVERY instruments only.

When Hedge mode is enabled, specify the position side for each order via 6200 (PositionSide) attribute. Allowed values per position mode:

Position ModePosition Side
One-WayBOTH
HedgeLONG, SHORT

PostOnly Orders

PostOnly order can be submitted with LIMIT order request with TimInForce = GOOD TILL CANCEL and 18 (PostOnly) tag set to 6. Connector performs the following conversion:

  • SPOT instruments: Order will be sent to Binance with OrderType = LIMIT_MAKER.
  • FUTURE and DELIVERY instruments: Order will be sent to Binance with TimeInForce = GTX.

Requests with other TimInForce values and 18 (PostOnly) tag set to 6 will be rejected for LIMIT orders.

ReduceOnly Orders

Important: Applies to orders with FUTURE and DELIVERY instruments only.

The ReduceOnly option can be used to close positions for all futures products. It cannot be used in Hedge position mode because close position orders in Hedge mode always act as ReduceOnly.

Close position orders in One-Way position mode are controlled by 6201 (ReduceOnly) tag.

Close position quantity cannot be greater than the open position size. When a ReduceOnly order quantity is greater than the open position, the exchange accepts the order but reduces the order quantity to the actual open position quantity. After this reduced quantity is completely filled, the remaining order quantity is cancelled by the connector.

Position Mode, Position Side and ReduceOnly interaction

Important: Applies to orders with FUTURE and DELIVERY instruments only.

One-Way Position Mode

Positions have BOTH type. Actual position type is represented by the sign of a position size: positive means long, negative means short.

Execution of an order that reduces position size (a close position order) will result in position type change if the executed order amount is greater than the position size. ReduceOnly option helps to prevent this behaviour.

Sample order executions with the ReduceOnly option:

Open PositionOrderReduceOnlyResulting Position*Notes
10001000 BUYfalse2000
10001000 SELLfalse0
10003000 BUYfalse4000
10003000 SELLfalse-2000Actual position type changes from long to short
10001000 BUYtrue1000The exchange rejects such orders
10001000 SELLtrue0
10003000 BUYtrue1000The exchange rejects such orders
10003000 SELLtrue01000 is executed, 2000 is cancelled by the connector

* Position size after order execution

Hedge Position Mode

Positions have LONG and SHORT type. They can exist simultaneously.

Execution of an order that reduces position size (a close position order) will result in the position size change, but not lower than 0. Since each such order acts as a ReduceOnly order in One-Way mode, ReduceOnly option is redundant in Hedge mode and is not permitted by the exchange.

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:

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 fstream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark

Important: Binance reuses the WebSocket Listen Key across connections sharing the same Api Key (and possibly within the same account). Closing a Listen Key for one connection closes the WebSocket channel for all other connections using the same key.

To avoid unintended disconnections, the connector does not close the Listen Key on disconnect.

Symbology

Currency pairs without separator, uppercase required, e.g. BTCUSDT, LTCUSDT.

Symbol lists are available via public REST API:

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.
websocketHeartbeatInterval30 minutesKeepalive 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.
staleWebsocketTimeout5 secondsTimeout for reconnection when no websockets messages received after any order message sent to exchange.
selfMatchPreventionInstructionCANCEL_RESTINGOptional setting for Self-Trade Prevention function. Supported values: CANCEL_RESTING, CANCEL_TAKING, CANCEL_BOTH.
sideEffectTypeNO_SIDE_EFFECTIs actual for instruments with SPOT product 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.
autoRepayAtCancelfalseIs actual for instruments with SPOT product type. Only works when the automatic loan order or automatic loan repayment order is in effect. Supported values: true, false.
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.
futureInstrumentCurrenciesList of currencies supported by instruments with FUTURE product type. See ...
deliveryInstrumentCurrenciesList of currencies supported by instruments with DELIVERY product type. See ...
binancePmSyncSettings.spotOrdersRequestSizeLimit200Limitation for the number of orders in the orders history response for SPOT instruments. Maximum value is 1000 for Futures (USDT-Futures), 100 for Delivery Futures (Coin-Futures).
binancePmSyncSettings.spotTradesRequestSizeLimit100Limitation for the number of trades in the account trade list history response for SPOT instruments. Maximum value is 1000.
binancePmSyncSettings.futureOrdersRequestSizeLimit200Limitation for the number of orders in the orders history response for FUTURE instruments. Maximum value is 1000 for Futures (USDT-Futures), 100 for Delivery Futures (Coin-Futures).
binancePmSyncSettings.futureTradesRequestSizeLimit100Limitation for the number of trades in the account trade list history response for FUTURE instruments. Maximum value is 1000.
binancePmSyncSettings.deliveryOrdersRequestSizeLimit50Limitation for the number of orders in the orders history response for DELIVERY instruments. Maximum value is 1000 for Futures (USDT-Futures), 100 for Delivery Futures (Coin-Futures).
binancePmSyncSettings.deliveryTradesRequestSizeLimit50Limitation for the number of trades in the account trade list history response for DELIVERY instruments. Maximum value is 1000.

Supported order attributes

KeyDescription
1818 (PostOnly) attribute relevant only for LIMIT orders. Switches between LIMIT and LIMIT_MAKER order types for SPOT instruments. Switches between GTC and GTX order time in force for FUTURE and DELIVERY instruments. Possible values: 6.
6101For SPOT instruments 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 (selfMatchPreventionInstruction). Possible values: EXPIRE_MAKER, EXPIRE_TAKER, EXPIRE_BOTH.
6200Orders in Hedge position mode should have 6200 (PositionSide) attribute. Is actual for FUTURE and DELIVERY instruments. Possible values: BOTH, LONG, SHORT. See Position Side section for detailed explanation.
6201reduceOnly switch. Cannot be sent in Hedge position mode. Is actual for FUTURE and DELIVERY instruments. Possible values: true, false. Default: false. See ReduceOnly orders section for detailed explanation.

Config sample

include classpath("crypto-connectors.conf")

connectors {
BINANCEPM: ${template.connector.crypto.binancepm} {
settings {
restUrl = "https://papi.binance.com"
websocketUrl = "wss://fstream.binance.com/pm"

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