Brokerages

Binance

Introduction

QuantConnect enables you to run your algorithms in live mode with real-time market data. We have successfully hosted more than 200,000 live algorithms and have had more than $22B in volume traded on our servers since 2015. Brokerages supply a connection to the exchanges so that you can automate orders using LEAN. You can use multiple data feeds in live trading algorithms.

Binance was founded by Changpeng Zhao in 2017 with the goal to "increase the freedom of money globally". Binance provides access to trading Crypto through spot markets and perpetual Futures. They serve clients with no minimum deposit when depositing Crypto. Binance also provides an NFT marketplace, a mining pool, and services to deposit Crypto coins in liquidity pools to earn rewards.

To view the implementation of the Binance brokerage integration, see the Lean.Brokerages.Binance repository.

Account Types

Binance supports cash and margin accounts for spot trades, but only supports margin accounts for Futures trades. Binance US only supports cash accounts.

// Binance Spot
SetBrokerageModel(BrokerageName.Binance, AccountType.Cash);
SetBrokerageModel(BrokerageName.Binance, AccountType.Margin);

// Binance Futures
SetBrokerageModel(BrokerageName.BinanceFutures, AccountType.Margin);
SetBrokerageModel(BrokerageName.BinanceCoinFutures, AccountType.Margin);

// Binance US Spot
SetBrokerageModel(BrokerageName.BinanceUS, AccountType.Cash);
# Binance Spot
self.SetBrokerageModel(BrokerageName.Binance, AccountType.Cash)
self.SetBrokerageModel(BrokerageName.Binance, AccountType.Margin)

# Binance Futures
self.SetBrokerageModel(BrokerageName.BinanceFutures, AccountType.Margin)
self.SetBrokerageModel(BrokerageName.BinanceCoinFutures, AccountType.Margin)

# Binance US Spot
self.SetBrokerageModel(BrokerageName.BinanceUS, AccountType.Cash)

Create an Account

Follow the account creation wizard on the Binance.com or Binance.us website to create a Binance account.

You will need API credentials to deploy live algorithms with your brokerage account. After you open your account, create API credentials and store them somewhere safe. As you create credentials, set the IP access restrictions to Unrestricted and, if you are going to trade Crypto Futures, select the Enable Futures check box.

Paper Trading

Binance supports paper trading through the Binance Spot Test Network. You don't need a Binance account to create API credentials for the Spot Test Network.

Follow these steps to set up paper trading with the Binance Spot Test Network:

  1. Log in to the Binance Spot Test Network with your GitHub credentials.
  2. In the API Keys section, click Generate HMAC_SHA256 Key.
  3. Enter a description and then click Generate.
  4. Store your API key and API key secret somewhere safe.

Paper trading Binance Crypto Futures isn't currently available.

Sub-Accounts

Our Binance and Binance US integrations don't support trading with sub-accounts. You must use your main account.

Asset Classes

Our Binance integration supports trading Crypto and Crypto Futures. Our Binance US integrations support trading Crypto.

// Binance
AddCrypto("BTCUSDT", Resolution.Minute, Market.Binance);
AddCryptoFuture("BTCUSD", Resolution.Minute, Market.Binance);

// Binance US 
AddCrypto("BTCUSDT", Resolution.Minute, Market.BinanceUS);
# Binance 
self.AddCrypto("BTCUSDT", Resolution.Minute, Market.Binance)
self.AddCryptoFuture("BTCUSD", Resolution.Minute, Market.Binance)

# Binance US
self.AddCrypto("BTCUSDT", Resolution.Minute, Market.BinanceUS)

If you call the SetBrokerageModel method with the correct BrokerageName, then you don't need to pass a Market argument to the AddCrypto method because the brokerage model has a default market.

Assets Available

Refer to the dataset listing of the Binance market you are trading to see the assets available. The following table shows the dataset listing of each Binance market:

MarketAsset ClassDataset Listing
BinanceCryptoBinance Crypto Price Data
BinanceCrypto FuturesBinance Crypto Price Data
BinanceUSCryptoBinance US Crypto Price Data

Orders

We model the Binance and Binance US APIs by supporting several order types, supporting order properties, and not supporting order updates. When you deploy live algorithms, you can place manual orders through the IDE.

Order Types

The following table describes the available order types for each asset class that Binance and Binance US support:

Order TypeCryptoCrypto Futures
MarketOrdergreen checkgreen check
LimitOrdergreen checkgreen check
StopLimitOrdergreen check
MarketOrder(_symbol, quantity);
LimitOrder(_symbol, quantity, limitPrice);
StopLimitOrder(_symbol, quantity, stopPrice, limitPrice);
self.MarketOrder(self.symbol, quantity)
self.LimitOrder(self.symbol, quantity, limit_price)
self.StopLimitOrder(self.symbol, quantity, stop_price, limit_price)

Order Properties

We model custom order properties from the Binance and Binance US APIs. The following table describes the members of the BinanceOrderProperties object that you can set to customize order execution:

PropertyDescription
TimeInForce A TimeInForce instruction to apply to the order. The following instructions are supported:
  • Day
  • GoodTilCanceled
  • GoodTilDate
PostOnlyA flag to signal that the order must only add liquidity to the order book and not take liquidity from the order book. If part of the order results in taking liquidity rather than providing liquidity, the order is rejected without any part of it being filled.
public override void Initialize()
{
    // Set the default order properties
    DefaultOrderProperties = new BinanceOrderProperties
    {
        TimeInForce = TimeInForce.GoodTilCanceled,
        PostOnly = false
    };
}

public override void OnData(Slice slice)
{
    // Use default order order properties
    LimitOrder(_symbol, quantity, limitPrice);
    
    // Override the default order properties
    LimitOrder(_symbol, quantity, limitPrice, 
               orderProperties: new BinanceOrderProperties
               { 
                   TimeInForce = TimeInForce.Day,
                   PostOnly = false
               });
    LimitOrder(_symbol, quantity, limitPrice, 
               orderProperties: new BinanceOrderProperties
               { 
                   TimeInForce = TimeInForce.GoodTilDate(new DateTime(year, month, day)),
                   PostOnly = true
               });
}
def Initialize(self) -> None:
    # Set the default order properties
    self.DefaultOrderProperties = BinanceOrderProperties()
    self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled
    self.DefaultOrderProperties.PostOnly = False

def OnData(self, slice: Slice) -> None:
    # Use default order order properties
    self.LimitOrder(self.symbol, quantity, limit_price)
    
    # Override the default order properties
    order_properties = BinanceOrderProperties()
    order_properties.TimeInForce = TimeInForce.Day
    order_properties.PostOnly = True
    self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties)

    order_properties.TimeInForce = TimeInForce.GoodTilDate(datetime(year, month, day))
    self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties)

Updates

We model the Binance and Binance US APIs by not supporting order updates, but you can cancel an existing order and then create a new order with the desired arguments.

var ticket = LimitOrder(_symbol, quantity, limitPrice);
ticket.Cancel();
ticket = LimitOrder(_symbol, newQuantity, newLimitPrice);
ticket = self.LimitOrder(self.symbol, quantity, limit_price)
ticket.Cancel()
ticket = self.LimitOrder(self.symbol, new_quantity, new_limit_price)

Fees

We model the order fees of Binance and Binance US at the VIP 0 level, which is a 0.1% maker and taker fee. If you add liquidity to the order book by placing a limit order that doesn't cross the spread, you pay maker fees. If you remove liquidity from the order book by placing an order that crosses the spread, you pay taker fees. Binance adjusts your fees based on your 30-day trading volume and BNB balance, but we don't currently model these metrics to adjust fees. To check the latest fees at all the fee levels, see the Trading Fees page on the Binance.com website or the Fee Structure page on the Binance.us website. The Binance Spot Test Network does not charge order fees.

For default backtest fee model, see Binance Supported Models.

Margin

We model buying power and margin calls to ensure your algorithm stays within the margin requirements.

Buying Power

Binance allows up to 3x leverage for spot trades in margin accounts and up to 25x leverage for Futures trades. Binance US doesn't currently support margin accounts.

Margin Calls

Regulation T margin rules apply. When the amount of margin remaining in your portfolio drops below 5% of the total portfolio value, you receive a warning. When the amount of margin remaining in your portfolio drops to zero or goes negative, the portfolio sorts the generated margin call orders by their unrealized profit and executes each order synchronously until your portfolio is within the margin requirements.

Margin Interest Payments

If you trade Crypto Perpetual Futures, we model the margin cost and payments of your Crypto Future holdings by directly adjusting your portfolio cash. For more information about Futures margin interest modeling, see Binance Futures Model.

Slippage

Orders through Binance and Binance US do not experience slippage in backtests. In live trading, your orders may experience slippage.

For default backtest slippage model, see Binance Supported Models.

Fills

We fill market orders immediately and completely in backtests. In live trading, if the quantity of your market orders exceeds the quantity available at the top of the order book, your orders are filled according to what is available in the order book.

For default fill model, see Binance Supported Models.

Settlements

Trades settle immediately after the transaction

security.SettlementModel = new ImmediateSettlementModel();
security.SettlementModel = ImmediateSettlementModel()

For default settlement model, see Binance Supported Models.

Security and Stability

When you deploy live algorithms with Binance or Binance US, we don't save your brokerage account credentials.

Deposits and Withdraws

You can deposit and withdraw cash from your brokerage account while you run an algorithm that's connected to the account. We sync the algorithm's cash holdings with the cash holdings in your brokerage account every day at 7:45 AM Eastern Time (ET).

Demo Algorithm

The following algorithm demonstrates the functionality of the Binance and Binance US brokerages:

Binance

Binance US

Virtual Pairs

All fiat and Crypto currencies are individual assets. When you buy a pair like BTCUSD, you trade USD for BTC. In this case, LEAN removes some USD from your portfolio cashbook and adds some BTC. The virtual pair BTCUSD represents your position in that trade, but the virtual pair doesn't actually exist. It simply represents an open trade.When you deploy a live algorithm, LEAN populates your cashbook with the quantity of each currency, but it can't get your position of each virtual pair.

Deploy Live Algorithms

You must have an available live trading node for each live trading algorithm you deploy.

Follow these steps to deploy a live algorithm:

  1. Open the project you want to deploy.
  2. Click the Lightning icon Deploy Live icon.
  3. On the Deploy Live page, click the Brokerage field and then click Binance Exchange from the drop-down menu.
  4. Enter your API key and secret.
  5. To generate your API credentials, see Account Types. Your account details are not saved on QuantConnect.

  6. Click on the Environment field and then click one of the environments.
  7. The following table shows the supported environments:

    EnvironmentDescription
    RealTrade with real money
    DemoTrade with paper money
  8. Click the Node field and then click the live trading node that you want to use from the drop-down menu.
  9. (Optional) Set up notifications.
  10. Configure the Automatically restart algorithm setting.
  11. By enabling automatic restarts, the algorithm will use best efforts to restart the algorithm if it fails due to a runtime error. This can help improve the algorithm's resilience to temporary outages such as a brokerage API disconnection.

  12. Click Deploy.

The deployment process can take up to 5 minutes. When the algorithm deploys, the live results page displays. If you know your brokerage positions before you deployed, you can verify they have been loaded properly by checking your equity value in the runtime statistics, your cashbook holdings, and your position holdings.

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: