ZenCex.Adapters.Binance.PortfolioMargin (zen_cex v0.2.1)
View SourcePortfolio Margin trading endpoints for Binance.
Portfolio Margin is Binance's advanced trading mode that provides unified margin and risk management across multiple trading products. It's designed for sophisticated traders who need capital efficiency across different markets.
Supported Product Types
- USD-M Futures (UM): USDT-margined perpetual and quarterly futures
- COIN-M Futures (CM): Coin-margined perpetual and quarterly futures
- Margin Trading: Cross and isolated margin trading (spot with leverage)
Key Features
Cross-Collateralization
All assets in your portfolio can be used as collateral across different products. For example, your BTC holdings can secure USDT futures positions.
Unified Risk Management
- Single maintenance margin calculation across all positions
- Portfolio-level liquidation instead of position-level
- Advanced risk metrics including Greeks for options (when available)
Enhanced Capital Efficiency
- Lower margin requirements due to portfolio offsetting
- Hedged positions require less collateral
- Automatic borrowing and lending between products
API Characteristics
- Base URL:
https://papi.binance.com(production only) - Rate Limit: 3,000 requests per minute (higher than standard APIs)
- Testnet Support: NOT available - returns 404 on testnet
- Path Prefix: All endpoints use
/papi/v1/prefix
Account Requirements
- Activation Required: Portfolio Margin must be activated on your account
- VIP Level: Generally requires VIP 1 or higher
- API Permissions: API key needs Portfolio Margin trading permission
- IP Whitelist: Recommended for security
Common Use Cases
1. Unified Account View
# Get complete account information across all products
{:ok, account} = PortfolioMargin.get_unified_account()2. Cross-Product Orders
# Place order using cross-collateral
{:ok, order} = PortfolioMargin.place_unified_order(%{
symbol: "BTCUSDT",
side: "BUY",
type: "LIMIT",
quantity: "0.001",
price: "40000",
product_type: "UM" # Optional: auto-detected from symbol
})3. Risk Monitoring
# Get all positions with unified margin calculations
{:ok, positions} = PortfolioMargin.get_all_positions()Important Considerations
- No Testnet: All testing must be done carefully in production with small amounts
- Liquidation Risk: Portfolio liquidation affects ALL positions
- Complexity: Requires understanding of cross-margin and portfolio risk
- Product Limits: Some features may be limited based on your VIP level
Error Handling
Common errors specific to Portfolio Margin:
{:error, {:not_activated, _}}- Portfolio Margin not activated on account{:error, {:insufficient_margin, _}}- Not enough collateral across portfolio{:error, {:invalid_product_type, _}}- Product type not supported or detected{:error, {:no_testnet_for_portfolio_margin}}- Testnet access attempted
Rate Limiting
Portfolio Margin has a separate rate limit pool:
- 3,000 weight per minute (compared to 1,200 for spot)
- Shared across all /papi/ endpoints
- Not affected by spot or futures rate limits
Summary
Functions
Account Balance
Account Information
Returns all configured endpoints.
BNB transfer
Cancel All CM Open Conditional Orders
Cancel All CM Open Orders
Cancel All UM Open Conditional Orders
Cancel All UM Open Orders
Cancel CM Conditional Order
Cancel CM Order
Cancel Margin Account All Open Orders on a Symbol
Cancel Margin Account OCO Orders
Cancel Margin Account Order
Cancel UM Conditional Order
Cancel UM Order
Change Auto-repay-futures Status
Change CM Initial Leverage
Change CM Position Mode
Change UM Initial Leverage
Change UM Position Mode
CM Account Trade List
CM Notional and Leverage Brackets
CM Position ADL Quantile Estimation
Fund Auto-collection
Fund Collection by Asset
Get all positions across UM, CM, and Margin products.
Get Auto-repay-futures Status
Get CM Account Detail
Get CM Current Position Mode
Get CM Income History
Get Download Id For UM Futures Order History
Get Download Id For UM Futures Trade History
Get Download Id For UM Futures Transaction History
Returns the endpoint configuration for the given operation.
Get Margin Borrow/Loan Interest History
Get UM Account Detail
Get UM Account Detail V2
Get UM Current Position Mode
Get UM Futures BNB Burn Status
Get UM Futures Order Download Link by Id
Get UM Futures Trade Download Link by Id
Get UM Futures Transaction Download Link by Id
Get UM Income History
Get unified account information across all product types.
Get User Commission Rate for CM
Get User Commission Rate for UM
Returns the rate limit weight for an operation.
Margin Account Borrow
Margin Account New OCO
Margin Account Repay
Margin Account Repay Debt
Margin Account Trade List
Margin Max Borrow
Modify CM Order
Modify UM Order
New CM Conditional Order
New CM Order
New Margin Order
New UM Conditional Order
New UM Order
Place a unified order that can span multiple product types.
Portfolio Margin UM Trading Quantitative Rules Indicators
Query All CM Conditional Orders
Query All CM Orders
Query All Current CM Open Conditional Orders
Query All Current CM Open Orders
Query All Current UM Open Conditional Orders
Query All Current UM Open Orders
Query All Margin Account Orders
Query All UM Conditional Orders
Query All UM Orders
Query CM Conditional Order History
Query CM Modify Order History
Query CM Order
Query CM Position Information
Query Current CM Open Conditional Order
Query Current CM Open Order
Query Current Margin Open Order
Query Current UM Open Conditional Order
Query Current UM Open Order
Query Margin Account Order
Query Margin Account's all OCO
Query Margin Account's OCO
Query Margin Account's Open OCO
Query Margin Loan Record
Query Margin Max Withdraw
Query Margin repay Record
Query Portfolio Margin Negative Balance Interest History
Query UM Conditional Order History
Query UM Modify Order History
Query UM Order
Query UM Position Information
Query User Negative Balance Auto Exchange Record
Query User Rate Limit
Query User's CM Force Orders
Query User's Margin Force Orders
Query User's UM Force Orders
Repay futures Negative Balance
Toggle BNB Burn On UM Futures Trade
UM Account Trade List
UM Futures Account Configuration
UM Futures Symbol Configuration
UM Notional and Leverage Brackets
UM Position ADL Quantile Estimation
Functions
Account Balance
Account Information
@spec all_endpoints() :: [map()]
Returns all configured endpoints.
BNB transfer
Cancel All CM Open Conditional Orders
Cancel All CM Open Orders
Cancel All UM Open Conditional Orders
Cancel All UM Open Orders
Cancel CM Conditional Order
Cancel CM Order
Cancel Margin Account All Open Orders on a Symbol
Cancel Margin Account OCO Orders
Cancel Margin Account Order
Cancel UM Conditional Order
Cancel UM Order
Change Auto-repay-futures Status
Change CM Initial Leverage
Change CM Position Mode
Change UM Initial Leverage
Change UM Position Mode
CM Account Trade List
CM Notional and Leverage Brackets
CM Position ADL Quantile Estimation
Fund Auto-collection
Fund Collection by Asset
Get all positions across UM, CM, and Margin products.
Returns a unified view of all positions with cross-margin calculations. This provides a complete picture of your portfolio risk exposure.
Response Structure
Returns a map with product types as keys:
%{
um_futures: [
%{
"symbol" => "BTCUSDT",
"positionAmt" => "0.001",
"entryPrice" => "45000",
"markPrice" => "46000",
"unRealizedProfit" => "1.00",
"marginType" => "cross",
"positionSide" => "BOTH"
}
],
cm_futures: [
%{
"symbol" => "BTCUSD_PERP",
"positionAmt" => "100", # contracts
"entryPrice" => "45000",
"markPrice" => "46000",
"unRealizedProfit" => "0.002", # in BTC
"marginType" => "cross"
}
]
}Parameters
symbol(optional): Filter for specific symbolrecvWindow(optional): Request validity window
Examples
# Get all positions
{:ok, positions} = PortfolioMargin.get_all_positions()
# Get positions for specific symbol
{:ok, positions} = PortfolioMargin.get_all_positions(%{symbol: "BTCUSDT"})
# Access specific product positions
{:ok, %{um_futures: um, cm_futures: cm}} = PortfolioMargin.get_all_positions()Notes
- Margin positions endpoint is not yet available from Binance
- Empty positions are returned as empty lists
- All positions use cross margin in Portfolio Margin mode
Get Auto-repay-futures Status
Get CM Account Detail
Get CM Current Position Mode
Get CM Income History
Get Download Id For UM Futures Order History
Get Download Id For UM Futures Trade History
Get Download Id For UM Futures Transaction History
Returns the endpoint configuration for the given operation.
Examples
iex> get_endpoint(:get_balances)
%{operation: :get_balances, path: "/api/v3/account", ...}
Get Margin Borrow/Loan Interest History
Get UM Account Detail
Get UM Account Detail V2
Get UM Current Position Mode
Get UM Futures BNB Burn Status
Get UM Futures Order Download Link by Id
Get UM Futures Trade Download Link by Id
Get UM Futures Transaction Download Link by Id
Get UM Income History
Get unified account information across all product types.
Returns consolidated account data including UM, CM, and Margin positions with cross-collateralization details. This is the primary endpoint for understanding your portfolio margin account status.
Response Structure
The response includes:
uniMMR: Unified Maintenance Margin Ratio (critical for liquidation)accountEquity: Total equity across all productsactualEquity: Equity after unrealized PnLaccountInitialMargin: Total initial margin requiredaccountMaintMargin: Total maintenance margin requiredaccountStatus: NORMAL, MARGIN_CALL, or LIQUIDATIONvirtualMaxWithdrawAmount: Maximum withdrawable amount
Parameters
recvWindow(optional): Request validity window in milliseconds (max 60000)
Examples
# Get basic account information
{:ok, account} = PortfolioMargin.get_unified_account()
# With custom receive window
{:ok, account} = PortfolioMargin.get_unified_account(%{recvWindow: 5000})Error Responses
{:error, {:not_activated, _}}- Portfolio margin not activated{:error, {:unauthorized, _}}- API key lacks portfolio margin permission
Get User Commission Rate for CM
Get User Commission Rate for UM
Returns the rate limit weight for an operation.
Margin Account Borrow
Margin Account New OCO
Margin Account Repay
Margin Account Repay Debt
Margin Account Trade List
Margin Max Borrow
Modify CM Order
Modify UM Order
New CM Conditional Order
New CM Order
New Margin Order
New UM Conditional Order
New UM Order
Place a unified order that can span multiple product types.
This intelligently routes orders to the appropriate product endpoint while utilizing the cross-collateralization benefits of Portfolio Margin. The order will use available collateral from your entire portfolio.
Product Type Detection
The function automatically detects the product type from:
- Explicit
product_typeparameter ("UM", "CM", or "MARGIN") - Symbol pattern analysis (see
ProductDetectorfor patterns)
Parameters
Required:
symbol: Trading pair (e.g., "BTCUSDT", "BTCUSD_PERP", "ETHBTC")side: "BUY" or "SELL"type: Order type ("LIMIT", "MARKET", "STOP", etc.)quantity: Order quantity as string
Optional:
product_type: Explicit product type ("UM", "CM", "MARGIN")price: Required for LIMIT ordersstopPrice: For STOP orderstimeInForce: "GTC", "IOC", "FOK" (default: "GTC")positionSide: "BOTH", "LONG", "SHORT" (futures only)reduceOnly: true/false (futures only)closePosition: true/false to close entire position (futures)
Examples
# USD-M Futures order (auto-detected from USDT suffix)
{:ok, order} = PortfolioMargin.place_unified_order(%{
symbol: "BTCUSDT",
side: "BUY",
type: "LIMIT",
quantity: "0.001",
price: "40000"
})
# COIN-M Futures order (auto-detected from underscore)
{:ok, order} = PortfolioMargin.place_unified_order(%{
symbol: "BTCUSD_PERP",
side: "SELL",
type: "MARKET",
quantity: "100" # contracts
})
# Margin order with explicit type
{:ok, order} = PortfolioMargin.place_unified_order(%{
symbol: "ETHBTC",
side: "BUY",
type: "LIMIT",
quantity: "0.1",
price: "0.065",
product_type: "MARGIN"
})Error Responses
{:error, {:invalid_product_type, _}}- Unable to detect or invalid product type{:error, {:insufficient_margin, _}}- Not enough collateral across portfolio{:error, {:invalid_symbol, _}}- Symbol not valid for detected product type
@spec portfolio_margin_um_trading_quantitative_rules_indicators(map()) :: {:ok, term()} | {:error, term()}
Portfolio Margin UM Trading Quantitative Rules Indicators
Query All CM Conditional Orders
Query All CM Orders
Query All Current CM Open Conditional Orders
Query All Current CM Open Orders
Query All Current UM Open Conditional Orders
Query All Current UM Open Orders
Query All Margin Account Orders
Query All UM Conditional Orders
Query All UM Orders
Query CM Conditional Order History
Query CM Modify Order History
Query CM Order
Query CM Position Information
Query Current CM Open Conditional Order
Query Current CM Open Order
Query Current Margin Open Order
Query Current UM Open Conditional Order
Query Current UM Open Order
Query Margin Account Order
Query Margin Account's all OCO
Query Margin Account's OCO
Query Margin Account's Open OCO
Query Margin Loan Record
Query Margin Max Withdraw
Query Margin repay Record
@spec query_portfolio_margin_negative_balance_interest_history(map()) :: {:ok, term()} | {:error, term()}
Query Portfolio Margin Negative Balance Interest History
Query UM Conditional Order History
Query UM Modify Order History
Query UM Order
Query UM Position Information
Query User Negative Balance Auto Exchange Record
Query User Rate Limit
Query User's CM Force Orders
Query User's Margin Force Orders
Query User's UM Force Orders
Repay futures Negative Balance
Toggle BNB Burn On UM Futures Trade
UM Account Trade List
UM Futures Account Configuration
UM Futures Symbol Configuration
UM Notional and Leverage Brackets
UM Position ADL Quantile Estimation