Binance Portfolio Margin Trade Connector
Features
crypto-binancepmConnector KeyNotes
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 Type | Connector Product Type |
|---|---|
Spot/Margin | SPOT |
USDⓈ-M Futures | FUTURE |
COIN-M Futures | DELIVERY |
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 Type | futureInstrumentCurrencies | deliveryInstrumentCurrencies | Instrument Currency | Resulting Product Type |
|---|---|---|---|---|
| FX | not used | not used | not used | SPOT |
| FUTURE | not defined | defined | delivery currency | DELIVERY |
| FUTURE | not defined | defined | non-delivery currency | FUTURE |
| FUTURE | defined | not defined | future currency | FUTURE |
| FUTURE | defined | not defined | non-future currency | DELIVERY |
| FUTURE | defined | defined | future currency | FUTURE |
| FUTURE | defined | defined | delivery currency | DELIVERY |
| FUTURE | defined | defined | non-future and non-delivery currency | unsupported 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 Type | Client Order ID source | Rules and Restrictions |
|---|---|---|
SEQUENCE | Order request's sequence number | sequence is numeric. clientOrderIdPrefix setting can be used for customization. |
COMPOSITE | Order request's sourceId and orderId | sourceId 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, combiningMARGIN_BUYandAUTO_REPAYmodes, it completes "borrow asset + place order + order execution + repayment".
Connector maps Side Effect Type value the following way:
| Side Effect Type setting | Side Effect Type for BUY orders | Side Effect Type for SELL orders |
|---|---|---|
| NO_SIDE_EFFECT | NO_SIDE_EFFECT | NO_SIDE_EFFECT |
| MARGIN_BUY | MARGIN_BUY | MARGIN_BUY |
| AUTO_REPAY | AUTO_REPAY | AUTO_REPAY |
| AUTO_BORROW_REPAY | AUTO_BORROW_REPAY | AUTO_BORROW_REPAY |
| MARGIN_BUY_REPAY_SELL | MARGIN_BUY | AUTO_REPAY |
| MARGIN_SELL_REPAY_BUY | AUTO_REPAY | MARGIN_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 Mode | Position Side |
|---|---|
One-Way | BOTH |
Hedge | LONG, 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:
SPOTinstruments: Order will be sent to Binance withOrderType=LIMIT_MAKER.FUTUREandDELIVERYinstruments: Order will be sent to Binance withTimeInForce=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 Position | Order | ReduceOnly | Resulting Position* | Notes |
|---|---|---|---|---|
| 1000 | 1000 BUY | false | 2000 | |
| 1000 | 1000 SELL | false | 0 | |
| 1000 | 3000 BUY | false | 4000 | |
| 1000 | 3000 SELL | false | -2000 | Actual position type changes from long to short |
| 1000 | 1000 BUY | true | 1000 | The exchange rejects such orders |
| 1000 | 1000 SELL | true | 0 | |
| 1000 | 3000 BUY | true | 1000 | The exchange rejects such orders |
| 1000 | 3000 SELL | true | 0 | 1000 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:
- SPOT instruments: https://api.binance.com/api/v3/exchangeInfo
- FUTURE instruments: https://fapi.binance.com/fapi/v1/exchangeInfo
- DELIVERY instruments: https://dapi.binance.com/dapi/v1/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
recvWindowof 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:
- SPOT instruments: https://api.binance.com/api/v3/exchangeInfo
- FUTURE instruments: https://fapi.binance.com/fapi/v1/exchangeInfo
- DELIVERY instruments: https://dapi.binance.com/dapi/v1/exchangeInfo
Configuration
Connector settings
| Parameter | Default Value | Description |
|---|---|---|
recvWindow | If 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. | |
websocketHeartbeatInterval | 30 minutes | Keepalive 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. |
staleWebsocketTimeout | 5 seconds | Timeout for reconnection when no websockets messages received after any order message sent to exchange. |
selfMatchPreventionInstruction | CANCEL_RESTING | Optional setting for Self-Trade Prevention function. Supported values: CANCEL_RESTING, CANCEL_TAKING, CANCEL_BOTH. |
sideEffectType | NO_SIDE_EFFECT | Is 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. |
autoRepayAtCancel | false | Is 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. |
clientOrderIdPrefix | Optional 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. | |
orderMapperType | SEQUENCE | Type 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. |
futureInstrumentCurrencies | List of currencies supported by instruments with FUTURE product type. See ... | |
deliveryInstrumentCurrencies | List of currencies supported by instruments with DELIVERY product type. See ... | |
binancePmSyncSettings.spotOrdersRequestSizeLimit | 200 | Limitation 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.spotTradesRequestSizeLimit | 100 | Limitation for the number of trades in the account trade list history response for SPOT instruments. Maximum value is 1000. |
binancePmSyncSettings.futureOrdersRequestSizeLimit | 200 | Limitation 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.futureTradesRequestSizeLimit | 100 | Limitation for the number of trades in the account trade list history response for FUTURE instruments. Maximum value is 1000. |
binancePmSyncSettings.deliveryOrdersRequestSizeLimit | 50 | Limitation 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.deliveryTradesRequestSizeLimit | 50 | Limitation for the number of trades in the account trade list history response for DELIVERY instruments. Maximum value is 1000. |
Supported order attributes
| Key | Description |
|---|---|
| 18 | 18 (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. |
| 6101 | For 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. |
| 6102 | Self-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. |
| 6200 | Orders 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. |
| 6201 | reduceOnly 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"
}
]
}
}
}