Brokerages

TD Ameritrade

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.

TD Ameritrade was founded by Joe Ricketts in 1971 with the goal to make "smart investors smarter through award-winning trading technology, education, and service". TD Ameritrade provides access to trading Equities, Options, Futures, Forex, Crypto, and other assets for clients with no minimum deposit. TD Ameritrade also provides a collateral lending program, education services, and a desktop trading platform.

To view the implementation of the TD Ameritrade brokerage integration, see the Lean.Brokerages.TDAmeritrade repository.

Account Types

TD Ameritrade supports cash and margin accounts.

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

Create an Account

Follow the account creation wizard on the TD Ameritrade website to create a TD Ameritrade account.

You will need API credentials to deploy live algorithms with your brokerage account. After you open your account, see the following resources to create API credentials and then store them somewhere safe:

Paper Trading

The TD Ameritrade API doesn't support paper trading, but you can follow these steps to simulate it:

  1. In the Initialize method of your algorithm, add one of the preceding SetBrokerageModel method calls.
  2. Deploy your algorithm with the QuantConnect Paper Trading brokerage.

Asset Classes

TD Ameritrade supports trading US Equities.

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

If you set the brokerage model to a model other than the TDAmeritradeBrokerageModel, 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 has default markets.

Assets Available

Refer to the US Equities dataset to see the assets available.

Orders

We model the TD Ameritrade API by supporting several order types, the TimeInForce order property, and 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 TD Ameritrade supports:

Order TypeEquity
MarketOrdergreen check
LimitOrdergreen check
StopMarketOrdergreen check
StopLimitOrdergreen check
MarketOrder(_symbol, quantity);
LimitOrder(_symbol, quantity, limitPrice);
StopMarketOrder(_symbol, quantity, stopPrice);
StopLimitOrder(_symbol, quantity, stopPrice, limitPrice);
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)

Time In Force

We model custom order properties from the TD Ameritrade API. TD Ameritrade 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 TDAmeritradeOrderProperties
               { 
                   TimeInForce = TimeInForce.Day
               });
    LimitOrder(_symbol, quantity, limitPrice, 
               orderProperties: new TDAmeritradeOrderProperties
               { 
                   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 = TDAmeritradeOrderProperties()
    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

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

  • Quantity
  • LimitPrice
  • StopPrice
  • 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

In live trading, if you're using raw data normalization and you have active limit, stop limit, or stop market orders in the market for a US Equity when a stock split occurs, the quantity, limit price, and stop price of your orders are automatically adjusted to reflect the stock split.

Fees

We model the order fees of TD Ameritrade, which are $0 for Equities. To check the latest fees, see the Pricing page on the TD Ameritrade website.

For default backtest fee model, see TD Ameritrade Supported Models.

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

In the US, TD Ameritrade allows up to 2x leverage on Equity trades for margin accounts. In other countries, TD Ameritrade may offer different amounts of leverage. To figure out how much leverage you can access, check with your local legislation or contact a TD Ameritrade representative. We model the US version of TD Ameritrade leverage by default.

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 TD Ameritrade do not experience slippage in backtests. In paper trading and live trading, your orders may experience slippage.

For default backtest slippage model, see TD Ameritrade 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 TD Ameritrade Supported Models.

Settlements

If you trade with a margin account, trades settle immediately

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

For default settlement model, see TD Ameritrade Supported Models.

Security and Stability

When you deploy live algorithms with TD Ameritrade, 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 TD Ameritrade brokerage:

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 Lightning icon Deploy Live icon.
  3. On the Deploy Live page, click the Brokerage field and then click TD Ameritrade from the drop-down menu.
  4. Enter your TD Ameritrade account ID, key, and token.
  5. To get your account credentials, see Account Types. Your account details are not saved on QuantConnect.

  6. Click the Node field and then click the live trading node that you want to use from the drop-down menu.
  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. 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: