Duration: 2:23
Level: Intermediate

In this lesson, we will see how to construct and execute a sample trading strategy on TWS.

Study Notes:

In this lesson, you would:

  • Learn how to construct and execute a trading strategy
  • Precautions to be taken in automated trading

Sample Trading Strategy

The strategy first connects to the TWS. In the next step, we source the snapshot script which holds the custom callback function.

On line 6, we create a contract using the tws stock function.

From lines 8 to 11, we set the parameters for the two simple moving averages and the initial current position to zero.

Next, we pull the initial require market data using the custom callback.

The strategy then enters a while loop on line 19. On line 20, we use the rbind function to combine the data frames by row. On line 22, we use the unique function to eliminate the duplicate rows from the data frame.

The If statement block starting on line 23, keeps checking the data until there is enough data for the strategy to proceed further. From line 31 to 34, we define the logic for buy and sell signals based on the two simple moving averages.

Once a signal is obtained, an order is constructed using the twsOrder function and is place using the placeOrder function. The current position is updated on every buy or sell position filled.

On execution, the strategy produces the following output:

Initially there is not enough data for the signals to generate. Once the data is collected, signals are placed and you can see the orders getting executed in the R console and also on the trader workstation orders window. Since the trading logic is placed in the while loop with a true value, the strategy will keep placing orders until it is stopped.


Following are the precautions that the trades have to keep in mind when they are trading algorithmically using the trading APIs.

  • Traders should have a robust risk management in place in case the default TWS risk management does not catch all the strategy specific risks.
  • Code block to ensure order price and order quantity sanity.
  • Write test case to ensure that the strategy does not run into order sending loops.
  • Write test cases to run on every API upgrade to ensure that nothing is broken.
  • Write robust codes to handle socket connection losses, error messages from Interactive Brokers, and network errors.


The functions from the IBrokers package are easy to use and can be implemented to construct various kinds of trading strategies for automated trading on TWS. This concludes the final lesson in the “Trading Using R” Online Course. We hope that you liked it. Thank You!

Note – The IBrokers package provides native R access to Interactive Brokers Trader Workstation API

Leave a Reply

Your email address will not be published. Required fields are marked *

Disclosure: Interactive Brokers

The analysis in this material is provided for information only and is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad-based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation by IBKR to buy, sell or hold such investments. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

The views and opinions expressed herein are those of the author and do not necessarily reflect the views of Interactive Brokers, its affiliates, or its employees.

Disclosure: R API Disclosure

This software is in no way affiliated, endorsed, or approved by Interactive Brokers or any of its affiliates. It comes with absolutely no warranty and should not be used in actual trading unless the user can read and understand the source. IBrokers is a pure R implementation of the TWS API.