Back Testing on IBKR with BackTrader – Part I

headshot Jogi Narain

Back Testing on <a href=IBKR with BackTrader – Part I" width="" />

This post is a part of the series “Building Your Automated Strategy with IBKR: From Back Testing to Paper Trading to Live Execution”.

Back Testing Basics

Backtesting assesses the viability of a trading strategy by discovering how it performed using historical data.

Backtrader – An Open Source Backtesting Framework

Backtrader is a Python library that allows backtesting and strategy development before live trading. (see: https://www.backtrader.com/docu/) .

It is an open-source framework that enables strategy testing using historical data. Furthermore, it can be used to optimize strategies, create visual plots, and can also be used as a trading engine for actual trading in the market. It has an active community providing support and help for people using the platform (see: https://community.backtrader.com)

Backtrader and Interactive Brokers

Backtrader has a robust integration with Interactive Brokers for historical data, paper trading and live trading. But the current implementation has not been updated for many years.

An Updated Integration for Interactive Brokers

This article presents an updated integration, and describes how it can be seamlessly installed into Backtrader so that it can be used with the latest version of the IB Native API.

What is the IB TWS API?

The Interactive Brokers Python TWS API allows you to trade via a running TWS (or IB Gateway) using Python code.

Acting as a bridge, the API allows for sending of orders from custom software or scripts, receiving live or historical data. Note that all the orders are reflected in the TWS frontend.

System Workflow

Getting Started

There are four basic steps to getting started:

  1. Open an account with IB and setup the trading frontend (TWS or IB Gateway)
  2. Download and install the IB TWS API
  3. Down and install BackTrader
  4. Update default IB integration built into Backtrader

Signup, Download and Install the IB TWS Frontend/TWS API

Open the account at Interactive Brokers (using https://www.interactivebrokers.com/en/pagemap/pagemap_newaccounts_v3.php) and download and install TWS.

You can download the TWS API by navigating to TechnologyTrading APIsGet API Software, or by following this link – http://interactivebrokers.github.io/

Installing the TWS API

Create a directory named back_testing, and copy the downloaded file twsapi_macunix.1016.10.zip into this directory, unzip and it will create the IBJts directory.

Create And Enable A Python Virtual Environment within the back_testing directory

python3 -m venv ./env source ./env/bin/activate 

Drill down to the directory back_testing/IBJts/source/pythonclient and run:

 python setup.py install

To check if it is installed correctly, open a Python terminal and type:

Python 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0] on linux 
Type "help", "copyright", "credits" or "license" for more information.
>>> import ibapi >>> 

If no errors appear, the install was successful!

Download and Install BackTrader

There is no special requirement for installing the BackTrader library. It also doesn’t have any dependencies. You can install this library by using the package manager “pip”.

 pip install backtrader

Now you can use backtrader with its full functionality.

To check if it is installed correctly open a Python terminal and type:

Python 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> Import backtrader as bt

If no errors appear, the install was successful.

Download and Install the updated IB TWS integration

Either clone the github repo:

git clone https://github.com/atreyuxtrading/atreyu-backtrader-api.git 

Or download a released version:

wget https://github.com/atreyuxtrading/atreyu-backtrader-api/archive/refs/tags/v1.0.zip

Unzip file, and install the Atreyu Backtrader API.

unzip v1.0.zip
cd atreyu-backtrader-api-1.0 ; python setup.py install

Check Settings of Locally Running TWS

Example: Download Realtime Bar Data from TWS

Stay tuned for the next installment in this series to learn how to set up Backtrader with the latest TWS API.

Related Tags
Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from Atreyu Trading Services and is being posted with its permission. The views expressed in this material are solely those of the author and/or Atreyu Trading Services and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. 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.

Disclosure: Order Types / TWS

The order types available through Interactive Brokers LLC's Trader Workstation are designed to help you limit your loss and/or lock in a profit. Market conditions and other factors may affect execution. In general, orders guarantee a fill or guarantee a price, but not both. In extreme market conditions, an order may either be executed at a different price than anticipated or may not be filled in the marketplace.

Disclosure: API Examples Discussed

Throughout the lesson, please keep in mind that the examples discussed are purely for technical demonstration purposes, and do not constitute trading advice. Also, it is important to remember that placing trades in a paper account is recommended before any live trading.

Related Quant Topics
IBKR-API Training Courses

API Training Courses

IBKR-API Documentation

ForecastEx by IBKR

Trade Your View on Economic and Climate Indicators

IBKR ForecastTrader lets you use exchange-listed Forecast Contracts1 to trade your opinion on Yes or No questions on economic and climate indicators, plus you’ll earn 4.83% APY 2 on your investment with an incentive coupon.

IBKR Campus Newsletters

Bi-Weekly Newsletter

Get updates on podcasts, webinars, courses, and more from our IBKR pillars.

Daily Newsletter

View the latest financial news articles from the top voices in the industry.

Weekly Newsletter

Get updates on podcasts, webinars, courses, and more from our IBKR pillars.

Weekly Newsletter

For those wanting to trade markets using computer-power by coders and developers.

Monthly Newsletter

Hear about the latest tools and techniques from our own IBKR API staff.

© 2024 Interactive Brokers, LLC

The risk of loss in online trading of stocks, options, futures, forex, foreign equities, and fixed income can be substantial. Before trading, clients must read the relevant risk disclosure statements on IBKR's Warnings and Disclosures page.

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.

Securities or other financial instruments mentioned in the material posted are not suitable for all investors. The material posted does not take into account your particular investment objectives, financial situations or needs and is not intended as a recommendation to you of any particular securities, financial instruments or strategies. Before making any investment or trade, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice. Past performance is no guarantee of future results.

Any information provided by third parties has been obtained from sources believed to be reliable and accurate; however, IBKR does not warrant its accuracy and assumes no responsibility for any errors or omissions.

Any information posted by employees of IBKR or an affiliated company is based upon information that is believed to be reliable. However, neither IBKR nor its affiliates warrant its completeness, accuracy or adequacy. IBKR does not make any representations or warranties concerning the past or future performance of any financial instrument. By posting material on IBKR Campus, IBKR is not representing that any particular financial instrument or trading strategy is appropriate for you.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.

Please note that any advertisement has not been reviewed by the Monetary Authority of Singapore.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply. If you have any questions or comments, or are interested in becoming a contributor to the IBKR Campus, please contact us here.

Interactive Brokers LLC

Is a member NYSE - FINRA - SIPC and regulated by the US Securities and Exchange Commission and the Commodity Futures Trading Commission. Headquarters: One Pickwick Plaza, Greenwich, CT 06830 USA.
Website: www.interactivebrokers.com

Information on Other Interactive Brokers Affiliates

Interactive Brokers Canada Inc.

Is a member of the Investment Industry Regulatory Organization of Canada (CIRO) and Member - Canadian Investor Protection Fund. Registered Office: 1800 McGill College Avenue, Suite 2106, Montreal, Quebec, H3A 3J6, Canada.
Website: www.interactivebrokers.ca

Interactive Brokers Australia Pty. Ltd.

ABN 98 166 929 568 is licensed and regulated by the Australian Securities and Investments Commission (AFSL: 453554) and is a participant of ASX, ASX 24 and Cboe Australia. Registered Office: Level 11, 175 Pitt Street, Sydney, New South Wales 2000, Australia.
Website: www.interactivebrokers.com.au

Interactive Brokers Hong Kong Limited

Is regulated by the Hong Kong Securities and Futures Commission, and is a member of the SEHK and the HKFE. Registered Office: Suite 1512, Two Pacific Place, 88 Queensway, Admiralty, Hong Kong SAR.
Website: www.interactivebrokers.com.hk

Interactive Brokers India Pvt. Ltd.

Is a trading member of NSE, BSE, and depository participant of NSDL. SEBI Registration No. INZ000217730; NSDL: IN-DP-602-2021. CIN-U67120MH2007FTC170004. Registered Office: 502/A, Times Square, Andheri Kurla Road, Andheri East, Mumbai 400059, India. Phone: +91-22-61289888 | Fax: +91-22-61289898.
Website: www.interactivebrokers.co.in

Interactive Brokers Securities Japan Inc.

Is regulated by Kanto Local Finance Bureau (Registration No.187) and is a member of Japan Securities Dealers Association and The Commodity Futures Association of Japan. Registered Office: Kasumigaseki Building 25F, 2-5 Kasumigaseki 3-chome, Chiyoda-ku, Tokyo, 100-6025 Japan. Phone: +81 (0)3-4588-9700 (On business days from 8:30-17:30 JST).
Website: www.interactivebrokers.co.jp

Interactive Brokers Singapore Pte. Ltd.

Is licensed and regulated by the Monetary Authority of Singapore (Licence No. CMS100917). Registered Office: #40-02A, Asia Square Tower 1, 8 Marina View, Singapore 018960.
Website: www.interactivebrokers.com.sg

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.