Auto-Trade with Interactive Brokers
Published: 2021-11-04 by Cone
3 Steps to Auto-Trade with Interactive Brokers
What is Auto-Trading?
Auto-trading is the practice of allowing a set of programmed rules fully or partially control your brokerage trading. Successful active trading relies on using a strategy that has a high probability of a positive return given a statistically large number of trading opportunities. Auto-trading, or using a "trading bot" (as if "robot" needs an abbreviation) reduces a trader's workload by making decisions with real-time market data and automatically placing orders with a broker. Auto-trading greatly reduces a trader's workload, doesn't miss opportunities, and places orders with a minimal amount of delay - and without error.
Step 1 - Build a Trading Strategy
A trading strategy is a set of rules that determines when to enter and exit the market. Rules can be based on anything that you can program such as a relationship between price and its moving average, an overbought/oversold indicator like a Relative Strength Index (RSI), words in a news headline, or even the phases of the moon!
When you boil it all down, it's essential for a trading strategy to have these 3 elements:
- Entry rule(s) - when to get in
- Exit rule(s) - when to get out for a profit or loss
- Position sizing rule(s) - how much capital to use for a trade. Also known as money management.
Each of the rules can be as simple or complex as you want to make it, and the KISS Principle often works well in trading. Nonetheless, seasoned traders will take into account many other factors, like optimizing their choice of indicator parameter values or adding logic for handling too many trade candidates when buying power is limited.
Step 2 - Backtest your Strategy
It's really a matter of due diligence. Would you risk money on a strategy that you knew was a bad idea? No one knows for sure if a trading strategy will work in the future, but you can find out if it would have worked in the past. Understanding that no period in the future will be precisely like it was before, backtesting is quick way to show that your strategy had worked using real historical market data.
A backtest uses real historical market data to feed a backtesting engine on a bar-by-bar basis and creating [hypothetical] trades as if the strategy were actually trading at that time. When a backtest uses real-world portfolio rules for buying power and trading costs, it's also called a trading simulation.
Backtesting gives you insight about what you can expect when you trade a strategy. For example, an equity curve shows how the value of an account would have grown. We're also able to use hypothetical trading results to calculate any number of metrics. Just to name a few: Annual Percent Return, Average Profit Percent per trade, Maximum Drawdown amount, or the number of days it could take to make a new equity high following a period of drawdown. If you find that the backtest results don't match your trading goals or risk profile, it could be time to revisit Step 1 until you find a strategy that does!
Step 3 - Connect WealthLab to Interactive Brokers
Armed with a strategy that backtesting has given you confidence to trade, it's time to connect to a broker. The Interactive Brokers Extension for WealthLab 8 will link WealthLab to your account(s) at IB, giving you access to all your subscribed data and ability to trade through IB's API. Complete the one-time setup to enable the API connection and just log in to either the IB Gateway or Trader WorkStation (TWS) to connect WealthLab to your Interactive Brokers account.
If your account is at another brokerage, WealthLab has also Auto-Trading and data connectors for the following:
- Interactive Brokers
- Schwab/TD Ameritrade - We're waiting on information for new API at Schwab
As well as for these crypto brokers/exchanges:
Auto-Trade Methods and Tools
The 3-Step Video above demonstrated just one way to auto-trade end-of-day signals. Depending on the type of strategy, the trading interval, and the number of symbols in your watchlist, you need the right automated trading tool to signal and place your trades.
A Strategy Window contains the code or the visual design surface for a strategy, so this is always where you start. But once your strategy development and analysis is complete, you can also use a Strategy Window to stage or place orders for one symbol or even for an entire Portfolio.
In WealthLab, when orders need to be placed on a future bar, a Signals view/tab appears. You can choose to "Stage" or "Place" signals directly to the Order Manager, or you can send the limit and stop orders to the Quotes tool for triggering and automatic placement, as demonstrated in the 3-Steps video.
Because it requires clicking a button to run the strategy and a couple more to place the orders, end-of-day (EOD) trading from the Strategy window is pseudo-automatation - orders are automatically sized and populated with the necessary parameters, but a few clicks are required to start the process.
You can successfully trade end-of-day (EOD) Strategies with Strategy Window, and if you're trading only one strategy it may be all you need. When you need to trade multiple EOD and/or intraday strategies, read on...
End-of-Day Quotes Triggering
Although Interactive Brokers is not one of them, many brokers don't allow placing simultaneous stop and/or limit orders whose total value exceeds your account's buying power. In these cases you need a way to monitor stop/limit orders and automatically place them in the market at the time the market approaches or exceeds their price trigger.
This is where WealthLab's Quotes & Price Triggers tool comes in. Any tool that can generate a stop or limit order - like the Strategy Window or Strategy Monitor - can send signals to the Quotes tool, which uses streaming data to monitor and eventually trigger stop/limit orders when they become marketable during the day. Triggered orders can be placed automatically in the Order Manager.
|Auto Trading EOD limit signals using Quotes and Triggers|
To trade a handful of symbols with intraday data, you can run strategies from individual streaming chart windows. A "streaming provider" sends trades or "ticks" to the chart and this information is used to build new bars. Each time an interval is completed a new bar is added to the chart. Adding a new bar causes the strategy to execute immediately, and the result is the most minimal delay to generate automated trading signals.
The accuracy of the new bars generated in a streaming chart depends if the provider is a true "tick-by-tick" provider, like IQFeed. Streaming data provided by broker connections are generally conflated or sampled at a lower rate which often results in OHLC/V bars that don't precisely match the historical data bars.
Due to these minor differences in a bar's pricing, a strategy can and will produce signals that don't match a backtest on historical bars. For this reason, it's recommended to trade streaming charts only with an appropriate tick-by-tick feed like those provided by IQFeed, Tradier, or Alpaca's paid data service.
For more about intraday data feeds available for WealthLab, see All About WealthLab Intraday and Realtime Data Providers.
The video below shows a stop-and-reverse auto-trading sequence for a Nasdaq E-mini contract using a Streaming Strategy Window. At the start, the strategy is long 1 MNQ contract and has a limit order profit target activated. When the new bar is added to the chart, the strategy performs 3 actions very quickly:
- Cancels the sell at limit order
- Sells the long position at market
- Opens a new short position at market (see the position change in the Accounts tool)
|Stop-and-reverse Auto-Trade sequence from a Streaming Strategy Window|
When you need realtime scanning for intraday strategies that execute on large watchlists like the Nasdaq 100, S&P 100, or S&P 500, then you'll need WealthLab's Strategy Monitor to collect and crunch the data in a matter of seconds to generate and automatically send trading signals to your broker. Managing a task of that size would quickly overwhelm any trader and would be impossible without auto-trading!
You can configure the Strategy Monitor with many strategies, each with their own data interval, DataSet (symbol universe), and parameter values. When trading Daily bars (or even longer intervals), a polling option is available, which creates one-time requests to update Daily bars from a preferred data feed.
Apart from the streaming option discussed above for trading intraday intervals, the Strategy Monitor has a Streaming Bar option. Streaming Bars are partial or even complete interval bars that are "pushed" into WealthLab by the streaming provider. Interactive Brokers, for example, implements Streaming Bar by sending summaries of trading activity every 5 seconds. Instead of processing hundreds or thousands of trades to build a 1-minute bar, for example, WealthLab only needs to combine the 12 5-second Streaming Bars.
The advantage of using Streaming Bars are two-fold. First, it cuts down on the bandwidth and internal processing required to build intraday bars. But best of all, the bar summaries are nearly an exact replica of the data used in historical charts. The result is the ability to trade using almost precisely the same data in real time that you backtest with (corrections may be applied later) at the expense of a few extra seconds of delay.
|Strategy Monitor: Multiple trades from 2 strategies, 1 and 5-min intervals|
More Auto Trading Considerations
Auto Paper Trading
Before putting real money to work consider Paper Trading. In the old days (not too long ago) a trader would practice trading by keeping track of trades and their results on a piece of paper. Nowadays, Paper Trading is fully electronic and uses ficticious broker accounts to simulate a live trading environment. It's an excellent idea to spend at least few days working with a "paper account" to familiarize yourself with the auto-trade workflow in order to prevent costly errors before trading your live account. (Maybe it's just me, but why is it that trading errors almost never go in your favor?)
From your Interactive Brokers account's settings you can set up a paper trading account that you can use to auto-trade with zero risk. Once you have access to the paper account, you can log in to the simulated TWS environment and connect WealthLab to it for trading. Even more, you'll be able to log in to your paper trading account through IB website portal to see your results, just as if it were a real account.
If you're a customer with a broker other than IB, Alpaca offers a free no-obligation paper account. You can use all the same techniques discussed here to trade a simulated account at Alpaca without cost. Just install WealthLab's Alpaca extension, sign up for the account, and start paper trading with no risk!
Semi-Automatic Trading: Staging Orders
While it's always a good idea to monitor automated trading, if you want to stay in the loop and have the final say before placing an order, Auto-Staging orders is the answer. When an order is Auto-Staged, it is sent to the Order Manager with a Staged status. Orders that are staged need to be selected and Placed with the broker manually. Although there are other subtle differences between Auto-Stage and Auto-Place, the main difference is the trader's acknowledgement before sending order(s) to the broker.
By staging orders, a trader may be able improve an execution price by delaying order entry. However, the delay can work for and against you. Some of the best trades can quickly become missed opportunities if not acted upon immediately.
Other Auto-Trade Factors
Attributes of historical data/Polling, Streaming, and Streaming Bars were briefly discussed above. However, something that many traders don't think about is "how much" data to load. If you're running intraday strategies with the same amount of data you used to backtest, you're introducing a lot of trading delay due to the extra processing required. Your trading workspace should be set up to load the least amount of seed data, but a sufficient amount that:
- makes the "longest" indicator used by your strategy valid (plus one day), and,
- hypothetically creates any trade entry that could still be active today. In other words, a strategy must be aware of active positions so that it can signal to exit them.
Assigning a proper size to positions is an integral part of most trading strategies. It's not the same to buy 100 shares of AAPL today at $160/share with a $25,000 account as it was to buy 100 shares 20 years ago when AAPL traded around $14.50/share in September 2002. Most sizing strategies are based on a percentage of an account's total value. In this way, position sizing increases and decreases proportionally with the account.
Instead of calculating size using the value of a hypothetical portfolio at the end of a backtest, the live account's value needs to be reflected in the position size of trading signals. In WealthLab, you can choose to Use Broker-reported Account Value on the Trading Preferences page. This option tells WealthLab to use the live account's value for auto-trade sizing.
Synchronizing Account Positions
Keeping a strategy synchronized with the live account is paramount. When WealthLab generates an auto-trade exit signal, the Order Manager automatically checks the live account's positions to be sure one exists before auto-placing a sell or cover order. If it does not, the order is suppressed.
Also WealthLab's Trading Preferences give you the option to reduce or increase the size of an exit signal to match the Position shares held in the account. This eliminates the chance that day-to-day changes in account value can lead to an "over or under-sold" position.
An "orphan" is a position in the live account that is not currently owned by strategy's backtest and are another possibility especially when auto-trading limit order systems. When the live account has an orphan the strategy is not actively managing it.
While there are a number of scenarios that can lead to ophan positions, the most common is when the market reaches the price of an exit limit order but the live order is not filled due to market depth. Instead of leaving an orphan position unmanaged during auto-trading, with the "Exit Orphans" Trading Preference selected, WealthLab will detect and eliminate an orphan position at market.
Use Live Positions
Strategies traded in a Streaming Window or in the Strategy Monitor can synchronize with all live account positions when using the Use Live Positions Trading Preference, which is mutually exclusive with the Orphan Positions option. Use Live Positions always puts the strategy in an exit mode for the positions held in the account, and likewise forces a strategy to use entry logic for watchlist symbols that are not held in the account.
What's the cost to Auto-Trade at Interactive Brokers?
There is no additional cost to Auto-Trade strategies at any broker with a WealthLab 8 subscription. Auto-trading fees with other platforms could range from $50/month up to $100/month - per strategy. Compare that to WealthLab's Premium Annual Plan, which comes in at only $33.33/month - less than the fee some sites charge for auto-trading a single strategy! In addition to that savings, WealthLab takes full advantage of brokers' APIs to access historical and streaming data, also for no extra fees.
Trading is a difficult business, and you should treat it like business by doing research, taking risks or reducing risk when it makes sense. Following a mechanical trading strategy that you designed and understand how it works can keep you on the path to reach your financial goals by taking programmed actions when opportunities present themselves. Because trading even just a handful of positions simultaneously can be overwhelming, auto-trading is recommended to reduce a trader's workload, stress, and emotional involvement that could lead to bad trading decisions at precisely the wrong time.