Brokerages

QuantConnect Paper Trading

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 $15B 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.

QuantConnect Paper Trading lets you run live, real-time data feeds into your algorithm but execute trades using fictional capital. Instead of your orders being routed to an exchange when you're paper trading, your order fills are simulated. Use paper trading to test your algorithm without risking real money and to ensure your backtest wasn't overfit before deploying with real money. You can use the paper trading brokerage without needing to sign up for a real brokerage account. If you don't set a brokerage model in your algorithm with the SetBrokerageModel method, the paper trading brokerage uses the DefaultBrokerageModel to simulate trades.

Account Types

The QuantConnect Paper Trading brokerage supports cash and margin accounts.

SetBrokerageModel(BrokerageName.QuantConnectBrokerage, AccountType.Cash);
SetBrokerageModel(BrokerageName.QuantConnectBrokerage, AccountType.Margin);
self.SetBrokerageModel(BrokerageName.QuantConnectBrokerage, AccountType.Cash)
self.SetBrokerageModel(BrokerageName.QuantConnectBrokerage, AccountType.Margin)

If you pass a different BrokerageName to the SetBrokerageModel method, the new brokerage model defines the account types that are available.

Asset Classes

The QuantConnect Paper Trading brokerage supports trading Equities, Crypto, Forex, CFDs, Futures, and Future Options.

AddEquity("SPY", Resolution.Minute, Market.USA);

AddCrypto("BTCUSD", Resolution.Minute, Market.GDAX);

AddForex("EURUSD", Resolution.Minute, Market.Oanda);

AddCfd("AU200AUD", Resolution.Minute, Market.Oanda);

var goldFutures = AddFuture(Futures.Metals.Gold, Resolution.Minute, Market.CME);

AddFutureOption(goldFutures.Symbol, universe => universe.Strikes(-5, +5));
self.AddEquity("SPY", Resolution.Minute, Market.USA)

self.AddCrypto("BTCUSD", Resolution.Minute, Market.GDAX)

self.AddForex("EURUSD", Resolution.Minute, Market.Oanda)

self.AddCfd("AU200AUD", Resolution.Minute, Market.Oanda)

gold_futures = self.AddFuture(Futures.Metals.Gold, Resolution.Minute, Market.CME)

self.AddFutureOption(gold_futures.Symbol, lambda universe: universe.Strikes(-5, +5))

If you set the brokerage model to a model other than the DefaultBrokerageModel, the new brokerage model defines the asset classes that you can trade. If you call the SetBrokerageModel method with the correct BrokerageName, then you don't need to pass a Market argument to the method calls above because the brokerage model automatically selects the correct market.

We can only provide paper trading on the assets for which we have a live data feed.

Assets Available

Refer to the dataset listing of the asset class and market you are trading to see the assets available. The following table shows the dataset listing of each asset class and market that the QuantConnect Paper Trading brokerage supports:

Asset ClassMarketDataset Listing
EquitiesUSAUS Equities
CryptoBinanceBinance Crypto Price Data
CryptoBitfinexBitfinex Crypto Price Data
CryptoCoinbaseProCoinbase Pro Crypto Price Data
CryptoFTXFTX Crypto Price Data
CryptoFTXUSFTXUS Crypto Price Data
CryptoKrakenKraken Crypto Price Data
ForexOandaFOREX Data
CFDOandaCFD Data
FuturesCBOT, CFE, CME, COMEX, HFKE, ICE, INDIA, NYMEX, SGXUS Futures
Future OptionsCBOT, CME, COMEX, NYMEXUS Future Options

Orders

The following sections describe how the DefaultBrokerageModel handles orders. If you set the brokerage model to a different model, the new brokerage model defines how orders are handled.

Order Types

The DefaultBrokerageModel supports the following order types:

  • MarketOrder
  • LimitOrder
  • StopMarketOrder
  • StopLimitOrder
  • MarketOnOpenOrder
  • MarketOnCloseOrder
  • LimitIfTouchedOrder
  • ExerciseOption
MarketOrder(_symbol, quantity);
LimitOrder(_symbol, quantity, limitPrice);
StopMarketOrder(_symbol, quantity, stopPrice);
StopLimitOrder(_symbol, quantity, stopPrice, limitPrice);
MarketOnOpenOrder(_symbol, quantity);
MarketOnCloseOrder(_symbol, quantity);
LimitIfTouchedOrder(_symbol, quantity, triggerPrice, limitPrice);
ExerciseOption(_optionSymbol, quantity);
self.MarketOrder(self.symbol, quantity)
self.LimitOrder(self.symbol, quantity, limit_price)
self.StopMarketOrder(self.symbol, quantity, stop_price)
self.StopLimitOrder(self.symbol, quantity, stop_price, limit_price)
self.MarketOnOpenOrder(self.symbol, quantity)
self.MarketOnCloseOrder(self.symbol, quantity)
self.LimitIfTouchedOrder(self.symbol, quantity, trigger_price, limit_price)
self.ExerciseOption(self.option_symbol, quantity)

Market on open orders are not available for Futures or Future Options.

Time In Force

The DefaultBrokerageModel supports the following TimeInForce instructions:

  • Day
  • GoodTilCanceled
  • GoodTilDate
public override void Initialize()
{
    // Set the default order properties
    DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled;
}

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 OrderProperties
               { 
                   TimeInForce = TimeInForce.Day 
               });
    LimitOrder(_symbol, quantity, limitPrice, 
               orderProperties: new OrderProperties
               { 
                   TimeInForce = TimeInForce.GoodTilDate(new DateTime(year, month, day)) 
               });
}
def Initialize(self) -> None:
    # Set the default order properties
    self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled

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 = OrderProperties()
    order_properties.TimeInForce = TimeInForce.Day
    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

The DefaultBrokerageModel supports order updates. You can define the following members of an UpdateOrderFields object to update active orders:

  • Quantity
  • LimitPrice
  • StopPrice
  • TriggerPrice
  • Tag
var ticket = StopLimitOrder(symbol, quantity, stopPrice, limitPrice, tag);
var orderFields = new UpdateOrderFields { 
Quantity = newQuantity,
LimitPrice = newLimitPrice,
StopPrice = newStopPrice,
Tag = newTag
}; ticket.Update(orderFields);
ticket = self.StopLimitOrder(self.symbol, quantity, stop_price, limit_price, tag)
update_fields = UpdateOrderFields() update_fields.Quantity = new_quantity
update_fields.LimitPrice = new_limit_price
update_fields.StopPrice = new_stop_price update_fields.Tag = new_tag ticket.Update(update_fields)

Handling Splits

If you have limit orders in an order book and a stock split occurs, the DefaultBrokerageModel automatically adjusts the quantity, limit price, and stop price of your orders.

Fees

The following table shows the fees that the DefaultBrokerageModel charges for each of the supported asset classes:

Asset ClassFee
Equities$0.005/share with a $1 minimum fee
Crypto$0
Forex$0
CFDs$0
Futures$1.85/contract
Future Options$1.85/contract

There is no fee to exercise Option contracts.

If you set the brokerage model to a model other than the DefaultBrokerageModel, the new brokerage model defines the order fees.

Margin

We model buying power and margin calls to ensure your algorithm stays within the margin requirements. If you set the brokerage model to a different model, the new brokerage model defines how margin is modeled.

Buying Power

The DefaultBrokerageModel allows up to 2x leverage for Equity trades and up to 50x leverage for Forex trades from 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.

Pattern Day Trading

If all of the following statements are true, you are classified as a pattern day trader:

  • You reside in the United States.
  • You trade in a margin account.
  • You execute 4+ intraday US Equity trades within 5 business days.
  • Your intraday US Equity trades represent more than 6% of your total trades.

Pattern day traders must maintain a minimum equity of $25,000 in their margin account to continue trading. For more information about pattern day trading, see Am I a Pattern Day Trader? on the FINRA website.

The PatternDayTradingMarginModel doesn't enforce minimum equity rules and doesn't limit your trades, but it adjusts your available leverage based on the market state. During regular market hours, you can use up to 4x leverage. During extended market hours, you can use up to 2x leverage.

security.MarginModel = new PatternDayTradingMarginModel();
security.MarginModel = PatternDayTradingMarginModel()

Slippage

Orders through the DefaultBrokerageModel do not experience slippage in backtests or paper trading.

Fills

The DefaultBrokerageModel fills market orders immediately and completely.

Settlements

If you trade with a margin account, trades settle immediately. If you trade with a cash account, Equity trades settle 3 days after the transaction date (T+3)

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

If you set the brokerage model to a model other than the DefaultBrokerageModel, the new brokerage model defines how trades settle.

Brokerage Models

The QuantConnect Paper Trading brokerage uses the DefaultBrokerageModel by default. To use a different brokerage model, pass any of the following BrokerageName enumerations to the SetBrokerageModel method:

SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin);
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)

Deposits and Withdraws

The QuantConnect Paper Trading brokerage supports deposits and withdraws.

Porfolio.CashBook.Add(AccountCurrency, 100);
Porfolio.CashBook.Add("ETH", -1);
self.Porfolio.CashBook.Add(self.AccountCurrency, 100)
self.Porfolio.CashBook.Add("ETH", -1)

Demo Algorithm

The following algorithm demonstrates the functionality of the DefaultBrokerageModel:

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 that you want to deploy.
  2. Click the Deploy Live icon.
  3. On the Deploy Live page, click the Brokerage field and then click Paper Trading from the drop-down menu.
  4. Click the Node field and then click the live trading node that you want to use from the drop-down menu.
  5. If you want to start with cash holdings, follow these steps:
    1. In the Algorithm Cash State section, click Show.
    2. Click Add Currency.
    3. Enter the currency ticker (for example, USD or BTC) and a quantity.
  6. If you want to start with position holdings, follow these steps:
    1. In the Algorithm Holdings State section, click Show.
    2. Click Add Holding.
    3. Enter the symbol ID, symbol, quantity, and average price.
  7. (Optional) Set up notifications.
  8. Configure the Automatically restart algorithm setting.
  9. 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.

  10. Click Deploy.

The deployment process can take up to 5 minutes. When the algorithm deploys, the live results page displays.

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: