Skip to content

QuantConnect/Lean.Brokerages.Template

Repository files navigation

lean-brokerage-template

Lean.Brokerages.Template

Build Status

Template Brokerage Plugin for Lean

See the brokerage development guide

Develop new Brokerage plugin

Initial Setup

  1. Review documentation for the new brokerage integration.

  2. Approve supported Security types (e.g., Equity, Index, Option).

  3. Approve support Order types: Market, Limit, Stop, StopLimit, TrailingStop, MarketOnClose, TrailingStopLimit, etc.

  4. Create a new brokerage development account.

  5. Generate API keys.

  6. 🍴📦Fork QuantConnect brokerage repository.

  7. Rename all template to new brokerage names by a skeleton.

    • for instance:
      • TemplateBrokerage.cs -> BinanceBrokerage.cs
      • public class TemplateBrokerage -> public class InteractiveBrokersBrokerage
  8. Remove: not used parts (for instance: downloader lean has generic now, but some brokerages support downloading trading pairs process like some crypto exchanges) - Lean download data provider source, Bybit Exchange Info Downloader

  9. Implement API connection (simple request) infrastructure (generic method that send GET/POST requests)

  10. If brokerage support several steps of authentication like OAuth 2 - TradeStation example

  11. Implement URL method to generate Authorization URL - TradeStation example

  12. 🧪 Unit test: to get Authorization URL - TradeStation example

  13. Create a method to automatically generate a new refresh token using the Authorization URL. Allow passing either the authorization code manually or the full URL in the configuration. Use a breakpoint to retrieve the refresh token and update the config file, streamlining the development process. - TradeStation example

  14. Create brokerage config file in test project:

    {
      "brokerage-api-url": "api-url",
      "brokerage-app-key": "app-key",
      "brokerage-secret": "secret",
      "brokerage-authorization-code": "",
      "brokerage-refresh-token": "",
      "brokerage-redirect-url": "https://127.0.0.1"
    }
  15. Create an independent class that manages the authentication process, ensuring it is solely responsible for authentication tasks. This class should be designed to function as middleware for our HTTP client in the future.

  16. 🧪 Unit test for the authentication process.

Brokerage Features Implementation

I recommend starting with the GetHistory() method, as it provides a clear understanding of the logic behind the SymbolMapper as well.

  1. Implement CanSubscribe() - TradeStation example
    • Symbol must not be universe or canonical.;
    • Brokerage must support the symbol's security type.
  2. Implement GetHistory() - TradeStation example
    1. For each support Security Type;
    2. For each Resolution (which brokerage supports);
      1. Tick, Second, Minute, Hour, Daily
    3. For each TickType;
      1. Trade, Quote, OpenInterest
    4. Remarks:
      1. If the brokerage does not support a specific input parameter, it should log a warning immediately and return null from the GetHistory() method.
      2. Use different Consolidators to aggregate bar resolution.
  3. 🧪 Unit test: GetHistory() - TradeStation example
    1. Create valid test cases for each combination of ResolutionTickTypeSecurityType, and other relevant parameters;
    2. Create invalid test cases to ensure the method returns null and no internal exceptions are thrown.
  4. Implement GetBrokerageSymbol() in class SymbolMapper - TradeStation example
  5. 🧪 Unit test: ReturnsCorrectBrokerageSymbol() - TradeStation example
    1. We pass Lean Symbol and get string of brokerage symbol
  6. Implement GetCashBalance() - TradeStation example
  7. 🧪 Unit test: GetCashBalance()
    1. We have generic method in class BrokerageTests
  8. Implement GetAccountHoldings() - TradeStation example
  9. 🧪 Unit test: GetAccountHoldings()
    1. Note: skip doesn't support Security Types.
  10. Implement GetOpenOrders() - Binance example
    1. All support OrderType;
    2. Convert brokerage order duration to Lean TimeInForce for each order;
    3. Note: skip doesn't support Security Types;
    4. Note: can create simple order with using brokerage Web UI or desktop app.
  11. Implement GetLeanSymbol() (Brokerage Ticker → Lean Symbol) - TradeStation example
    1. Reuse existing conversion methods from the Lean source
  12. 🧪 Unit test: GetLeanSymbol() - TradeStation example
    1. ReturnsCorrectLeanSymbol()
  13. Implement PlaceOrder() - Binance example, TradeStation example with CrossZeroOrder
    1. Convert the Lean order type to the corresponding brokerage order type using specific parameters, then pass the request to the brokerage API.
    2. Add new BrokerageId to Lean.Order.BrokerId.
    3. Send the new OrderEvent(...) that the order was submitted successfully.
  14. 🧪 Unit test: PlaceOrder() - TradeStation example
    1. different Security Types
    2. different MarketType (Market, Limit, Stop)
  15. Implement CancelOrder() - Bybit example
    1. Validate that order has not cancelled or filled already to prevent from extra steps.
  16. Set up a continuous WebSocket connection.
  17. Implement Connect() - TradeStation example
    1. public override bool IsConnected - Returns true if the WebSocket is connected and the subscription to user/order updates is active.
  18. Implement Disconnect() - TradeStation example
    1. Stop all WS subscription.
    2. Close connection.
  19. Implement User/Order update event. - Coinbase example
    1. PlaceOrder() and receive updates about it via WebSocket, sending the relevant OrderEvent to Lean in real-time.
    2. Note: We should synchronize the process to avoid race conditions. First, complete the PlaceOrder operation, then return the corresponding event. This means we need to pause new updates from the WebSocket until the order is fully processed.
  20. 🧪 Unit test: PlaceOrder() → WS Update about filled.
  21. Implement ReSubscribe to user update.
    1. When the internet connection is lost, we should initiate a new WebSocket connection.
  22. Implement UpdateOrder() - TradeStation example
  23. 🧪 Unit test: UpdateOrder()
    1. different Security Types.
    2. different quantities.
    3. different price.
    4. wrong price.
    5. wrong quantity.
  24. Implement the Subscription/Unsubscription process. (interface IDataQueueHandler )
    1. subscribe on level one update (quotes, trades, openInterest)
    2. Remarks:
      1. Use IDataAggregator;
      2. Use different ExchangeTimeZone to different symbols - TradeStation example;
      3. IDataAggregator.Update() - different tick data.
      4. use DataQueueHandlerSubscriptionManager SubscriptionManager from abstract class BaseWebsocketsBrokerage for Subscription/UnSubscription and count symbol, etc.
      5. Use class BrokerageMultiWebSocketSubscriptionManager to multiple connection.
  25. 🧪 Unit test: DataQueueHandler - TradeStation example
    1. Different Security Types;
    2. Different SubscriptionDataConfig (Resolution, TickType).
  26. Implement ReSubscriptionProcess - TradeStation example
    1. When the internet connection is lost, we should establish a new stable connection and resubscribe to all the symbols that were previously subscribed to.
  27. Implement IDataQueueUniverseProvider - TradeStation example
    1. option chain provider
  28. 🧪 Unit test: IDataQueueUniverseProvider
    1. different symbol of the same security type (Option, IndexOption)
  29. Implement Initialize() to initialize brokerage only through one method. - TradeStation example
  30. NOT FORGET: ValidateSubscription() - TradeStation example
    1. place in Initialize()
    2. The same in all brokerages.
  31. Implement SetJob() - TradeStation example
    1. A brokerage can be started IDataQueueHandler and not as a brokerage.
  32. Implement class BrokerageFactory - TradeStation example
    1. Dictionary<string, string> BrokerageData - all brokerage configs.
    2. GetBrokerageModel(...) - use it like reference to model in Lean.
  33. 🧪 Unit test: BrokerageFactory
  34. Refactor: brokerage.json file in root of .sln
  35. Implement gh-actions.yml to great CI/CD.

Lean integration - TradeStation Lean PR

Use any Lean project as a reference within the brokerage integration to enhance debugging and streamline development.

  1. Fork Lean
  2. Implement class BrokerageModel
    1. Support securities.
    2. Place and update orders.
  3. 🧪 Unit test: BrokerageModel
  4. Added brokerage name in BrokerageName.cs
  5. Added brokerage in IBrokerageModel.cs
  6. Implement class class BrokreageOrderProperties.cs
    1. different additional property for brokerage (e.g. support extend hours when place order)
  7. Implement class BrokerageFeeModel
  8. Added config in Launcher/config.json

Lean-CLI integration - CharlesSchwab Lean-CLI PR

  1. Fork lean-cli
  2. Upgrade modules.json
  3. Update lean-cli Readmi file
    1. python scripts/readme.py

Manual integration test

  1. Re-Subscription Process (after internet disconnect)
    1. Re-subscribe to User/Order WebSocket Events;
    2. Re-subscribe to Market Data;
      1. Order Book;
      2. Trade Information;
      3. Level 1 Data.
  2. Multiple Subscriptions on Symbols
    1. Subscribe to Option Chains;
    2. Subscribe to Symbols with 500+;
    3. Subscribe to Symbols with 1.000+.
  3. Long-Running Test for Night and Weekend.
    1. Test Server Stability and Connection Resilience.
      • Perform long-running tests during off-hours, such as nights and weekends, to validate that the remote server closes properly and that our connection remains stable.
      • During this test, monitor the connection for unexpected disruptions or failures after the server shutdown.

Best Practices for Implementing a New Plugin in Lean

About

Lean Brokerages Template

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages