Giter VIP home page Giter VIP logo

lean.brokerages.binance's Introduction

header-cheetah

     

Introduction

This repository hosts the Binance and BinanceUS Brokerage Plugin Integration with the QuantConnect LEAN Algorithmic Trading Engine. LEAN is a brokerage agnostic operating system for quantitative finance. Thanks to open-source plugins such as this LEAN can route strategies to almost any market.

LEAN is maintained primarily by QuantConnect, a US based technology company hosting a cloud algorithmic trading platform. QuantConnect has successfully hosted more than 200,000 live algorithms since 2015, and trades more than $1B volume per month.

About Binance

binance

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.

For more information about the Binance brokerage, see the QuantConnect-Binance Integration Page.

Using the Brokerage Plugin

Deploying Binance with VSCode User Interace

You can deploy using a visual interface in the QuantConnect Cloud. For more information see the QuantConnect-Binance Integration Page.

deploy-binance

In the QuantConnect Cloud Platform you can harness the QuantConnect Live Data Feed. For most users this is substantially cheaper and easier than self-hosting.

Deploying Binance with LEAN CLI

Follow these steps to start local live trading with the Binance brokerage:

  1. Open a terminal in your CLI root directory.

  2. Run lean live "<projectName>" to start a live deployment wizard for the project in ./<projectName> and then enter the brokerage number.

    $ lean live 'My Project'
     
    Select a brokerage:
    1. Paper Trading
    2. Interactive Brokers
    3. Tradier
    4. OANDA
    5. Bitfinex
    6. Coinbase Pro
    7. Binance
    8. Zerodha
    9. Samco
    10. Terminal Link
    11. Atreyu
    12. Trading Technologies
    13. Kraken
    14. FTX
    Enter an option: 
    
  3. Enter the number of the organization that has a subscription for the Binance module.

    $ lean live "My Project"
    
    Select the organization with the Binance module subscription:
    1. Organization 1
    2. Organization 2
    3. Organization 3
       Enter an option: 1
    
  4. Enter the exchange to use.

    $ lean live "My Project"
    
    Binance Exchange (Binance, BinanceUS): BinanceUS
    
  5. Enter the environment to use.

    $ lean live "My Project"
    
    Use the testnet? (live, paper): live
    
  6. Enter your API key id and secret.

    $ lean live "My Project"
    
    API key: 6d3ef5ca2d2fa52e4ee55624b0471261
    API secret: ********************************
    

    To create a new API key, see the API Management page on Binance or Binance US.

  7. Enter the number of the data feed to use and then follow the steps required for the data connection.

    $ lean live 'My Project'
    
    Select a data feed:
    1. Interactive Brokers
    2. Tradier
    3. Oanda
    4. Bitfinex
    5. Coinbase Pro
    6. Binance
    7. Zerodha
    8. Samco
    9. Terminal Link
    10. Trading Technologies
    11. Kraken
    12. FTX
    13. IQFeed
    14. Polygon Data Feed
    15. Custom Data Only
    
        To enter multiple options, separate them with comma:
    
  8. View the result in the <projectName>/live/<timestamp> directory. Results are stored in real-time in JSON format. You can save results to a different directory by providing the --output <path> option in step 2.

If you already have a live environment configured in your Lean configuration file, you can skip the interactive wizard by providing the --environment <value> option in step 2. The value of this option must be the name of an environment which has live-mode set to true.

Account Types

Binance supports cash and margin accounts, but Binance US only supports cash accounts.

Order Types and Asset Classes

Our Binance and Binance US integrations support trading Crypto and the following order types:

  • Market Order
  • Limit Order
  • Stop-Limit Order

Downloading Data

For local deployment, the algorithm needs to download the following dataset:

Binance Crypto Price Data
Binance US Crypto Price Data

Brokerage Model

Lean models the brokerage behavior for backtesting purposes. The margin model is used in live trading to avoid placing orders that will be rejected due to insufficient buying power.

You can set the Brokerage Model with the following statements

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

SetBrokerageModel(BrokerageName.BinanceUS, AccountType.Cash)

Read Documentation

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.

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 margin accounts, but 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.

Slippage

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

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.

Settlements

Trades settle immediately after the transaction.

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).

     

whats-lean

     

LEAN Engine is an open-source algorithmic trading engine built for easy strategy research, backtesting, and live trading. We integrate with common data providers and brokerages, so you can quickly deploy algorithmic trading strategies.

The core of the LEAN Engine is written in C#, but it operates seamlessly on Linux, Mac and Windows operating systems. To use it, you can write algorithms in Python 3.8 or C#. QuantConnect maintains the LEAN project and uses it to drive the web-based algorithmic trading platform on the website.

Contributions

Contributions are warmly very welcomed but we ask you to read the existing code to see how it is formatted, commented and ensure contributions match the existing style. All code submissions must include accompanying tests. Please see the contributor guide lines.

Code of Conduct

We ask that our users adhere to the community code of conduct to ensure QuantConnect remains a safe, healthy environment for high quality quantitative trading discussions.

License Model

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

lean.brokerages.binance's People

Contributors

alexcatarino avatar derekmelchin avatar ilshatgaripov avatar jaredbroad avatar jhonabreul avatar martin-molinero avatar romazes avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lean.brokerages.binance's Issues

Binance Futures invalid live trades (X=INSURANCE_FUND)

Expected Behavior

Trades from the binance futures trade sometimes have very large outliers which leads to incorrect live data very often (sometimes even 10% price difference). This is because of this issue https://dev.binance.vision/t/binance-futures-there-are-some-strange-trades-from-trade-stream/963 .

Actual Behavior

Insurance fund type trades are put together with all other trades and lead to incorrect trade bars.

Potential Solution

Trades with type INSURANCE_FUND have to be filtered out.

Enable Automatic Debt Repayment

Expected Behavior

Automatically repay dept for short-margin trades.

Actual Behavior

Debt is not automatically repaid and users need to manually do it.

Potential Solution

To enable auto replay, we need to set

body["sideEffectType"] = "MARGIN_BUY";

to

body["sideEffectType"] = "AUTO_REPAY";

However, we may want to do it via BinanceOrderProperties

Note

Lean doesn't model debt for short-margin trades, so the portfolio value is probably diverging.

From Binance user:

Currently, when closing a margin position, any outstanding debts need to be explicitly repaid via a separate API call. Closing a position via an opposite market order is not enough and will instead result in two opposite open positions. Setting the side effect type to AUTO_REPAY resolves this by automating the repay call when closing a short or leveraged margin position. I confirmed this with Binance support as my algorithms are constantly leaving open short positions behind after closing them.

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Review WS Trade Channel

Expected Behavior

  • Correct trade data is generated

Actual Behavior

Potential Solution

  • Review WS trade channel usages and where we should be using aggTrade channel instead where appropriate

Reproducing the Problem

N/A

System Information

N/A

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Binance Crypto Futures v2 API Support

Expected Behavior

Support crypto futures v2 api per the change log below:

REST

The following endpoints will no longer be supported from 2023-07-15:
GET /fapi/v1/account
GET /fapi/v1/balance
GET /fapi/v1/positionRisk
Please switch to corresponding v2 endpoints:
GET /fapi/v2/account
GET /fapi/v2/balance
GET /fapi/v2/positionRisk

Actual Behavior

Currently only supports v1 api.

Potential Solution

Reproducing the Problem

Deploy a Binance Crypto Futures strategy and get back this error message:

During the algorithm initialization, the following exception has occurred: Error getting cash balance from brokerage: BinanceBrokerage.GetCashBalance: request failed: [400] Bad Request, Content: {"code":-5000,"msg":"GET /fapi/v1/account is retired, please use GET /fapi/v2/account"}, ErrorMessage: BinanceBrokerage.GetCashBalance: request failed: [400] Bad Request, Content: {"code":-5000,"msg":"GET /fapi/v1/account is retired, please use GET /fapi/v2/account"}, ErrorMessage:  in BinanceBaseRestApiClient.cs:line 154 BinanceBrokerage.GetCashBalance: request failed: [400] Bad Request, Content: {"code":-5000,"msg":"GET /fapi/v1/account is retired, please use GET /fapi/v2/account"}, ErrorMessage: 
 BinanceBrokerage.GetCashBalance: request failed: [400] Bad Request, Content: {"code":-5000,"msg":"GET /fapi/v1/account is retired, please use GET /fapi/v2/account"}, ErrorMessage:  in BinanceBaseRestApiClient.cs:line 154 BinanceBrokerage.GetCashBalance: request failed: [400] Bad Request, Content: {"code":-5000,"msg":"GET /fapi/v1/account is retired, please use GET /fapi/v2/account"}, ErrorMessage:

System Information

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Wrong endpoint for 24hr Ticker Price Change Statistics

Expected Behavior

An application should use the proper endpoint for "24hr Ticker Price Change Statistics", ie.
GET /api/v3/ticker/24hr

More:
https://binance-docs.github.io/apidocs/spot/en/#24hr-ticker-price-change-statistics

Actual Behavior

Currently an application tries to use an endpoint:
GET /sapi/v1/margin/ticker/24hr
... invoking the error:

20230120 20:27:20.436 ERROR:: BinanceBrokerage.FetchSymbolWeights():  System.Exception: BinanceBrokerage.GetCashBalance: request failed: [404] , Content: {"timestamp":1674246440091,"status":404,"error":"Not Found","message":"No message available","path":"/sapi/v1/margin/ticker/24hr"}, ErrorMessage:
   at QuantConnect.BinanceBrokerage.BinanceBaseRestApiClient.GetTickerPriceChangeStatistics() in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBaseRestApiClient.cs:line 415
   at QuantConnect.BinanceBrokerage.BinanceBrokerage.FetchSymbolWeights(String restApiUrl) in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBrokerage.cs:line 670
20230120 20:27:20.465 ERROR:: Engine.Run():  System.Exception: BinanceBrokerage.GetCashBalance: request failed: [404] , Content: {"timestamp":1674246440091,"status":404,"error":"Not Found","message":"No message available","path":"/sapi/v1/margin/ticker/24hr"}, ErrorMessage:
   at QuantConnect.BinanceBrokerage.BinanceBaseRestApiClient.GetTickerPriceChangeStatistics() in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBaseRestApiClient.cs:line 415
   at QuantConnect.BinanceBrokerage.BinanceBrokerage.FetchSymbolWeights(String restApiUrl) in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBrokerage.cs:line 670
   at QuantConnect.BinanceBrokerage.BinanceBrokerage.Initialize(String wssUrl, String restApiUrl, String apiKey, String apiSecret, IAlgorithm algorithm, IDataAggregator aggregator, LiveNodePacket job, String marketName) in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBrokerage.cs:line 494
   at QuantConnect.BinanceBrokerage.BinanceBrokerage..ctor(String apiKey, String apiSecret, String restApiUrl, String webSocketBaseUrl, IAlgorithm algorithm, IDataAggregator aggregator, LiveNodePacket job, String marketName) in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBrokerage.cs:line 115
   at QuantConnect.BinanceBrokerage.BinanceBrokerage..ctor(String apiKey, String apiSecret, String restApiUrl, String webSocketBaseUrl, IAlgorithm algorithm, IDataAggregator aggregator, LiveNodePacket job) in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBrokerage.cs:line 97
   at QuantConnect.BinanceBrokerage.BinanceBrokerageFactory.CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm) in C:\Users\adria\workspace\QuantConnect\Lean.Brokerages.Binance\QuantConnect.BinanceBrokerage\BinanceBrokerageFactory.cs:line 88
   at QuantConnect.Lean.Engine.Setup.BrokerageSetupHandler.CreateBrokerage(AlgorithmNodePacket algorithmNodePacket, IAlgorithm uninitializedAlgorithm, IBrokerageFactory& factory) in C:\Users\adria\workspace\QuantConnect\Lean\Engine\Setup\BrokerageSetupHandler.cs:line 134
   at QuantConnect.Lean.Engine.Engine.Run(AlgorithmNodePacket job, AlgorithmManager manager, String assemblyPath, WorkerThread workerThread) in C:\Users\adria\workspace\QuantConnect\Lean\Engine\Engine.cs:line 138

Potential Solution

diff --git a/QuantConnect.BinanceBrokerage/BinanceBaseRestApiClient.cs b/QuantConnect.BinanceBrokerage/BinanceBaseRestApiClient.cs
index 0b91c82..aee8d66 100644
--- a/QuantConnect.BinanceBrokerage/BinanceBaseRestApiClient.cs
+++ b/QuantConnect.BinanceBrokerage/BinanceBaseRestApiClient.cs
@@ -406,7 +406,7 @@ namespace QuantConnect.BinanceBrokerage
         /// </summary>
         public PriceChangeStatistics[] GetTickerPriceChangeStatistics()
         {
-            var endpoint = $"{ApiPrefix}/ticker/24hr";
+            var endpoint = $"{GetBaseDataEndpoint()}/ticker/24hr";
             var request = new RestRequest(endpoint, Method.GET);

             var response = ExecuteRestRequest(request);

Reproducing the Problem

  1. Compile locally the newest version of Lean and Lean.Brokerages.Binance
  2. Start an algorithm:
    lean live deploy "strategy" --brokerage Binance --data-feed Binance

System Information

Win11, Docker, WSL2

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Adds Support to StopMarketOrder

Expected Behavior

Supports StopMarketOrder.

Actual Behavior

In Lean we have the following message explaining why this implementation doesn't support StopMarketOrder:
Despite Binance API allows you to post STOP_LOSS and TAKE_PROFIT order types, they always fail with the content
{"code":-1013,"msg":"Take profit orders are not supported for this symbol."}

Potential Solution

N/A. Investigate whether this is still the case and why.

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues

Implement Rate Limit per Rest Client

Expected Behavior

Support a rate limit for each endpoint. BinanceFutures has a higher rate limit 300 per 10 seconds (30/s) against 5 messages per second from Binance.

Actual Behavior

There is a single rate limit per endpoint.

Potential Solution

N/A

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Supports Binance Subaccount

Expected Behavior

Supports Binance Subaccount:
https://binance-docs.github.io/apidocs/spot/en/#sub-account-endpoints

Actual Behavior

Does not support it.

Potential Solution

N/A

Reproducing the Problem

Open a subaccount according to this post, create the credentials, and try to deploy with them.

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Update CI

  • Part of Binance global CI can only run on non US (and other locations) serves, CI is failing because of this

Margin Account Should Not Use Cached Holdings

Expected Behavior

If we deploy to a margin account, we should never read the cached holdings.

Actual Behavior

When we deploy the algorithm to a cash account, ApiClient.GetAccountHoldings(); always returns an empty list, so we should use the cashed holdings: base.GetAccountHoldings(_job?.BrokerageData, _algorithm.Securities.Values);. If we deploy to a margin account, and get an empty list from Binance, we use cached values too.

Potential Solution

If we are trading a margin account, GetAccountHoldings should never use cached values.

Reproducing the Problem

The problem below is from a Cash case. it's correct, but the UI doesn't let us remove the cached position.

Buy BTCUSDT, then stop the algorithm. Redeploy. Verify the BTCUSDT position is loaded. Stop the algorithm.
Close the project, deploy it, and verify that there is no BTCUSDT position.
So the same account returns two different states.

2023-06-30T21:28:03.0585556Z TRACE:: BrokerageSetupHandler.Setup(): Setting BTC cash to 0.00126482
2023-06-30T21:28:03.0585999Z TRACE:: BrokerageSetupHandler.Setup(): Setting TUSD cash to 661.13740660
2023-06-30T21:28:03.0646670Z TRACE:: BrokerageSetupHandler.Setup(): Fetching open orders from brokerage...
2023-06-30T21:28:03.2394701Z TRACE:: BrokerageSetupHandler.Setup(): Fetching holdings from brokerage...
2023-06-30T21:28:03.2458444Z TRACE:: Brokerage.GetAccountHoldings(): sourcing holdings from provided brokerage data, found 1 entries
2023-06-30T21:28:03.2476051Z TRACE:: BrokerageSetupHandler.Setup(): Has existing holding: BTCTUSD: -0.002 @ $30548.01 - Market: $0 - Conversion: 
2023-06-30T21:26:38.1517871Z TRACE:: BrokerageSetupHandler.Setup(): Setting BTC cash to 0.00126482
2023-06-30T21:26:38.1518244Z TRACE:: BrokerageSetupHandler.Setup(): Setting TUSD cash to 661.13740660
2023-06-30T21:26:38.1566469Z TRACE:: BrokerageSetupHandler.Setup(): Fetching open orders from brokerage...
2023-06-30T21:26:38.3464017Z TRACE:: BrokerageSetupHandler.Setup(): Fetching holdings from brokerage...
2023-06-30T21:26:38.3474590Z TRACE:: Brokerage.GetAccountHoldings(): sourcing holdings from provided brokerage data, found 0 entries

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.