How to Set Up Algorithmic Trading with Interactive Brokers and Open Source Python
- Bryan Downing
- 37 minutes ago
- 18 min read
A Complete Beginner's Guide to Configuring Your Algo Trading Environment
Introduction
This will be part of a course package soon to be released on https://hftcode.com/
Algorithmic trading — the practice of using computer programs to execute trades based on predefined rules and strategies — has become increasingly accessible to retail traders and hobbyist developers alike. What was once the exclusive domain of hedge funds and institutional trading desks can now be explored from your home computer using free, open-source tools and a demo brokerage account.
This guide walks you through the complete setup process for an algorithmic trading environment built on Interactive Brokers (IBKR), Python, Redis, and Visual Studio Code (VS Code). The system described here uses a server-client architecture where a central Python server connects to Interactive Brokers' Trader Workstation (TWS), and individual trading bots communicate with that server through Redis, an open-source in-memory data store acting as a message bus. The bots themselves are Python scripts implementing various trading strategies across asset classes including US equities, cryptocurrency, and retail forex.

By the end of this guide, you will understand how to install and configure every component of the system, how to launch the server and individual trading bots, and how to use AI-assisted coding tools to modify or create new trading strategies. This guide assumes you are working on a Windows machine, though notes for macOS and Linux users are included where relevant.
Important Disclaimer: This software package is provided strictly for educational and demonstration purposes. There are no guarantees of trading results, profitability, or performance. The Python scripts included in this package contain live order-placing capabilities. You must run all scripts in demo (paper trading) mode only until you fully understand the mechanics of every trading script. Proceeding to live trading with real money is done entirely at your own risk.
Prerequisites and System Overview for Algorithmic Trading with Interactive Brokers
Before diving into the installation steps, it is important to understand the overall architecture of the system and what software components you will need to install. The algo trading environment consists of four primary components that work together.
The first component is Interactive Brokers Trader Workstation (TWS). This is the brokerage platform provided by Interactive Brokers. TWS serves as the bridge between your trading bots and the financial markets. It provides the API endpoint that your Python scripts connect to in order to retrieve market data and submit orders. You will need to create an Interactive Brokers account and configure TWS to accept API connections. Critically, you do not need to fund your account with real money to get started — Interactive Brokers provides a paper trading (demo) environment that simulates live market conditions without any financial risk.
The second component is Python. Python is the programming language in which all the trading bots and the server are written. The project uses Python 3.13, though Python 3.14 is the most recent release as of early 2026. You will need Python installed on your system along with pip, the Python package installer, which is used to install the required third-party libraries.
The third component is Redis. Redis is a lightweight, open-source, in-memory data structure store that the system uses as a message bus. It sits between the central TWS server script and the individual trading bot scripts, facilitating communication between them. Redis is extremely stable, free to use, and easy to maintain, making it an ideal choice for this kind of inter-process communication.
The fourth component is Visual Studio Code (VS Code). VS Code is the recommended code editor for working with this project. It provides an integrated terminal (PowerShell on Windows), file browsing, syntax highlighting, and extension support that makes it easy to navigate the project files, edit scripts, and run commands. While VS Code is not strictly required — you could use any text editor and run commands from a standalone terminal — it streamlines the workflow considerably for algorithmic trading with Interactive Brokers
An optional fifth component is Kilo Code (referred to as "Kimmy" in the project). This is a free VS Code extension that provides an AI-powered agentic coding assistant. Once configured with an AI model provider, you can use it to prompt changes to existing trading scripts, generate new strategies, or ask questions about the codebase. The extension itself is free, though you may incur costs depending on which AI model provider you choose to use with it.
Step 1: Installing Python
Python is the foundation of the entire project, so it must be installed first. Navigate to the official Python website at python.org and download the latest installer for your operating system. For Windows users, the installer is a standard executable (.exe) file that walks you through the setup process.
During installation on Windows, there is a critically important checkbox on the first screen of the installer that says "Add Python to PATH." Make sure this box is checked. When Python is added to your system's PATH environment variable, it means that you can type "python" and "pip" in any terminal or PowerShell window and the system will know where to find those programs. If you skip this step, you will encounter errors later when trying to run Python scripts from the terminal because the system will not be able to locate the Python executable.
If you have already installed Python but are encountering errors where the terminal says it cannot find Python, the issue is almost certainly that Python's installation directory has not been added to your Windows PATH environment variable. To fix this, you can either reinstall Python and check the PATH box, or manually add the Python installation directory (typically something like C:\Users\YourName\AppData\Local\Programs\Python\Python313\ and its Scripts subdirectory) to your system's PATH through the Windows Environment Variables settings panel.
On macOS and Linux, Python installation varies slightly. macOS users can install Python through the official installer from python.org or through the Homebrew package manager using the command "brew install python." Linux users typically install Python through their distribution's package manager, for example "sudo apt install python3 python3-pip" on Ubuntu or Debian-based systems. The PATH is usually configured automatically on these platforms, but if you encounter issues, consult your operating system's documentation on setting environment variables.
To verify that Python is correctly installed and accessible, open a new PowerShell (Windows) or terminal (macOS/Linux) window and type "python --version." You should see output indicating Python 3.13 or later. Similarly, type "pip --version" to confirm that pip is available. Both commands should return version information without errors.
Step 2: Installing Visual Studio Code
Visual Studio Code is a free, open-source code editor developed by Microsoft. It is available for Windows, macOS, and Linux. Download the installer from code.visualstudio.com and follow the standard installation procedure for your operating system.
Once VS Code is installed, open it and familiarize yourself with the interface. The left-hand sidebar contains the Explorer panel, which shows the files and folders of your project. The bottom panel contains the integrated terminal, which is where you will run commands. On Windows, this terminal defaults to PowerShell. While PowerShell may feel unfamiliar if you are used to other command-line interfaces, it works well for this project and all commands in this guide are compatible with it.
The project folder includes a dedicated document that provides an introduction to using VS Code for those who are completely new to the editor. It covers the basics of navigating files, opening the terminal, and using key features. If you have never used VS Code before, reading that document before proceeding is strongly recommended.
After installing VS Code, open the project folder by going to File, then Open Folder, and selecting the root directory of the algo trading project. You should see the full project structure in the Explorer panel on the left, including the "bots" directory, the "server" directory, the "documents" directory, and various configuration files.
Step 3: Understanding the Project Structure
With the project open in VS Code, take a moment to understand how the files and folders are organized. The project contains several key directories and files that each serve a specific purpose.
The "documents" folder contains all of the supporting documentation for the project. This includes the terms of service document, the Interactive Brokers setup guide, the Redis installation guide, the VS Code introduction, the Kilo Code setup guide, the build and deploy instructions, and a breakdown of the trading bot suite. These documents are provided in markdown format (some may eventually be converted to PDF) and should be read carefully before attempting to run any scripts. The terms of service document is particularly important — it reiterates that the software is for educational and demonstration purposes only and that the scripts contain live order-placing capabilities.
The "bots" folder contains the individual trading bot scripts. There are approximately five example bots included in the package. Two of them trade US equities — one for Apple (AAPL) and one for IBM. One bot trades Bitcoin. The remaining two bots trade retail forex pairs: EUR/USD (Euro vs. US Dollar) and GBP/USD (British Pound vs. US Dollar). Each bot is a standalone Python script that implements a specific trading strategy for its respective instrument.
The "server" folder contains the central TWS server script. This is the Python script that establishes and maintains the connection to Interactive Brokers' Trader Workstation. It acts as a gateway between the trading bots and the brokerage — the bots send their trade signals and order requests through Redis to this server, which then forwards them to TWS for execution.
At the root level of the project, you will find several important files. The "requirements.txt" file lists all the Python packages and their specific versions that the project depends on. The "config.yaml" file (or similar configuration file) contains settings for Redis connectivity, TWS connection parameters, and other environment-specific configuration. There are also readme files that provide quick-start information.
Additionally, the project includes diagnostic utility scripts. These are helper tools that allow you to test individual components of the system in isolation. For example, there is an IBKR client test script that verifies the connection to TWS, a test order script that confirms order submission is working, and a basic configuration test script that validates your Python-to-TWS connectivity. These utilities are invaluable for troubleshooting when something is not working correctly.
Step 4: Setting Up an Interactive Brokers Account and Trader Workstation
Interactive Brokers is the brokerage that provides market access for this algo trading system. To get started, you need to create an account and install the Trader Workstation software.
Visit the Interactive Brokers website at interactivebrokers.com and sign up for an account. The key point to understand here is that you do not need to deposit any real money to begin using this system. Interactive Brokers provides a paper trading environment that allows you to simulate trades using virtual money with real market data. Your sole objective at this stage is to set up a demo account and stay in that demo account for the entirety of your learning process.
Once your account is created, download and install the Trader Workstation (TWS) application. TWS is available for Windows, macOS, and Linux. Follow the installation prompts and log in using your demo account credentials. The project's documents folder contains a dedicated guide for Interactive Brokers setup that walks through this process in detail. There are also numerous video tutorials available on YouTube that cover TWS installation and configuration if you need additional guidance.
After logging into TWS with your paper trading account, you must configure it to accept API connections from your Python scripts. This is a critical step — without this configuration, your Python server will not be able to communicate with TWS. To do this, navigate within TWS to File, then Global Configuration, then API, then Settings. In this settings panel, you need to make several adjustments.
First, enable the ActiveX and Socket Client option. This is the setting that allows external programs (like your Python scripts) to connect to TWS through a network socket. Without this enabled, TWS will refuse all incoming API connections.
Second, consider enabling the "Read Only API" option initially. When this option is checked, TWS will accept API connections for data retrieval purposes but will reject any order submissions. This provides an extra layer of safety while you are learning. You can see market data flowing through your scripts without any risk of accidentally placing trades. Once you are comfortable and ready to test order placement in paper trading mode, you can uncheck this option.
Third, confirm the API port number. For paper trading (demo) accounts, the default port is 7497. For live trading accounts, the default port is 7496. Since you are starting in demo mode, make sure the port is set to 7497. This port number must match the port specified in your project's configuration file (config.yaml), so make a note of it. If there is a mismatch between the port TWS is listening on and the port your Python scripts are trying to connect to, the connection will fail.
Leave TWS running after completing this configuration. It must remain open and running in the background for the entire time you want your trading bots to operate, as it serves as the live connection to the markets.
Step 5: Installing and Configuring Redis
Redis is used in this project as a message bus — a lightweight communication layer between the central TWS server and the individual trading bots. When a trading bot decides to place an order, it publishes a message to Redis. The TWS server subscribes to these messages, picks them up, and forwards them to Interactive Brokers for execution. This architecture allows you to run multiple independent trading bots simultaneously, each operating on its own schedule and strategy, while sharing a single connection to the brokerage.
On Windows, Redis can be installed through the Windows Subsystem for Linux (WSL), through a native Windows port, or through Docker. The project's documents folder contains a dedicated Redis installation guide that walks through the recommended approach for each operating system. On Linux, Redis is typically available through the system package manager (for example, "sudo apt install redis-server" on Ubuntu). On macOS, it can be installed through Homebrew with "brew install redis."
After installation, Redis runs as a background service that listens on a default port of 6379. This is the standard port and the one used in the project's configuration. If you need to change the port for any reason, you will need to update both the Redis configuration and the project's config.yaml file to match.
Redis also supports optional password authentication and remote access configuration. For a local development and testing setup, the default configuration with no password on localhost is sufficient. However, if you plan to run Redis on a separate machine or expose it to a network, you should configure password security. The Redis document in the project provides guidance on these optional configurations.
To verify that Redis is running correctly, you can open a terminal and type "redis-cli ping." If Redis is operational, it will respond with "PONG." This simple test confirms that the Redis server is running and accepting connections on the expected port.
Step 6: Installing Python Dependencies
With Python installed on your system, you now need to install the specific third-party packages that the trading scripts depend on. These dependencies are listed in the "requirements.txt" file located in the root of the project directory.
Open a terminal or PowerShell window and navigate to the project's root directory. If you are using VS Code's integrated terminal, it should already be in the correct directory. If not, you can use the "cd" command followed by the path to the project folder. A helpful trick in VS Code is to right-click on a folder in the Explorer panel and select "Copy Path," then paste that path after the "cd" command in the terminal to navigate directly to it without typing the full path manually.
Once you are in the project's root directory, run the following command to install all required packages: "pip install -r requirements.txt." This command tells pip to read the requirements.txt file and install every package listed in it at the specified version.
The requirements.txt file includes several key packages. The "ib_insync" package is the Python library for communicating with Interactive Brokers' TWS API. It provides a high-level, Pythonic interface for placing orders, requesting market data, and managing positions. The "redis" package is the Python client for connecting to the Redis server. "PyYAML" is used for reading the project's YAML configuration files. "Pandas" is a widely-used data analysis library that the scripts use for handling time-series market data and organizing trade information. "NumPy" is a numerical computing library that Pandas depends on and that may be used directly in some calculations within the trading strategies. Finally, "python-dateutil" is a utility library that simplifies date and time formatting and parsing.
One important note about package versions: the requirements.txt file specifies exact version numbers for each package. These versions are known to be compatible with the project's source code. If you upgrade any of these packages to newer versions, there is a risk that breaking changes in the newer versions will cause the code to fail. While you are learning and getting familiar with the system, it is strongly recommended that you keep the package versions exactly as specified. You can always experiment with newer versions later once you have a solid understanding of how everything works and are comfortable debugging potential compatibility issues.
Step 7: Configuring the Project
The project uses a YAML configuration file (config.yaml) to centralize all environment-specific settings. This file contains connection parameters for both Redis and TWS, and it is where you specify ports, hostnames, and other relevant settings.
Open the config.yaml file in VS Code and review its contents. The TWS section should contain the hostname (typically "127.0.0.1" or "localhost" for a local installation) and the port number (7497 for paper trading, as configured in Step 4). The Redis section should similarly contain the hostname and port (default 6379). If you configured Redis with a password, you would add that here as well.
Ensure that the port numbers in this configuration file match the actual ports that TWS and Redis are listening on. A mismatch is one of the most common causes of connection failures, and the diagnostic utilities described below can help you identify such issues.
Step 8: Running the System
With all components installed and configured, you are now ready to launch the system. The startup sequence follows a specific order that must be respected: first TWS, then Redis, then the Python TWS server, and finally the individual trading bots.
Make sure Interactive Brokers Trader Workstation is running and that you are logged into your paper trading account. Confirm that the API settings are configured as described in Step 4. TWS must remain running for the duration of your trading session.
Confirm that Redis is running by executing "redis-cli ping" in a terminal. If it responds with "PONG," you are good to proceed. If Redis is not running, start it according to the instructions in the Redis document for your operating system.
Next, open a PowerShell or terminal window and navigate to the server directory within the project. You can do this by right-clicking the server folder in VS Code's Explorer, selecting "Copy Path," and then using "cd" followed by the pasted path. Once in the server directory, launch the TWS server by typing "python tws_server.py" (or whatever the exact filename is as specified in the project). This script will initialize and attempt to connect to TWS through the configured port. If the connection is successful, you will see output in the terminal indicating that the server is running and connected.
The TWS server must remain running in its own terminal window. Do not close it or interrupt it while you want to trade. This server is the persistent bridge between your bots and the brokerage.
Now, open a separate PowerShell or terminal window (or a new terminal tab in VS Code) and navigate to the bots directory. To run a specific trading bot, type "python" followed by the name of the bot script. For example, to run the Apple trading bot, you would type "python apple_bot.py" (using the actual filename). The bot will start up, connect to Redis, and begin executing its trading strategy. You will see output in the terminal showing the bot's activity — market data retrieval, signal generation, and trade execution (in paper trading mode).
You can run multiple bots simultaneously by opening additional terminal windows and launching each bot in its own session. Each bot operates independently and communicates with the central TWS server through Redis. This architecture makes it easy to experiment with different strategies across different instruments at the same time.
Step 9: Using Diagnostic Utilities
If you encounter problems during setup or operation, the project includes several diagnostic utility scripts that can help you isolate the issue.
The IBKR client test utility tests the connection between Python and TWS. If this test fails, the problem lies either in your TWS configuration (API not enabled, wrong port) or in your Python environment (ib_insync not installed, network issue). The test order utility attempts to submit a test order through the API, verifying that order placement is functioning correctly. The basic configuration test script validates that your config.yaml settings are correct and that the Python environment can read them properly.
Run these utilities one at a time from the terminal to systematically verify each component. Start with the configuration test, then the connection test, and finally the order test. This progression helps you narrow down problems from the simplest (configuration file parsing) to the most complex (live order submission).
Step 10: Installing and Using Kilo Code (AI Coding Assistant)
Kilo Code is an optional but powerful addition to your workflow. It is a VS Code extension that provides an AI-powered coding assistant capable of understanding your codebase and helping you modify or create trading scripts through natural language prompts.
To install Kilo Code, open VS Code and navigate to the Extensions panel (the square icon on the left sidebar, or press Ctrl+Shift+X). Search for "Kilo Code" and click Install. The extension itself is free. However, to use it, you need to configure it with an AI model provider. In the extension's settings, you will find a provider list where you can select and configure your preferred AI model. The costs associated with using AI models vary by provider and are separate from the Kilo Code extension itself.
Once configured, you can use Kilo Code by opening the extension panel and typing natural language prompts. For example, you could ask it to modify the Apple trading bot to use a different moving average period, create a new trading bot for a different instrument, explain how a particular section of code works, or add additional risk management logic to an existing strategy. The AI assistant understands the context of your project and can generate or modify code accordingly.
The project's documents folder includes a guide specifically for setting up and using Kilo Code, which provides more detailed instructions and example prompts.
Step 11: Understanding the Trading Bots
The project includes approximately five example trading bots that demonstrate algo trading across different asset classes and instruments. Understanding what each bot does and how it is structured will help you modify existing strategies or build new ones.
The two equity bots trade Apple (AAPL) and IBM stocks respectively. These bots connect to the US stock market through Interactive Brokers, receive real-time price data, and apply their trading rules to determine when to buy and sell shares. They serve as the simplest examples in the suite and are good starting points for understanding the codebase.
The Bitcoin bot trades cryptocurrency, demonstrating how the same architecture can be applied to digital assets. Cryptocurrency markets operate 24/7, which introduces different considerations compared to equity markets that have defined trading hours.
The two forex bots trade EUR/USD and GBP/USD currency pairs. Foreign exchange trading involves its own set of conventions around lot sizes, pip values, and market hours. These bots illustrate how the system handles the specifics of retail forex trading.
Each bot follows a similar structural pattern: it connects to Redis, subscribes to relevant market data, applies its trading logic (which may include technical indicators, price thresholds, or other algorithmic rules), and publishes order requests when its conditions are met. The dedicated document on the trading bot suite provides a detailed breakdown of each bot's strategy and code structure.
Troubleshooting Common Issues
Several common problems can arise during setup, and most of them have straightforward solutions.
If you receive an error saying Python is not recognized as a command, it means Python is not in your system's PATH. On Windows, reinstall Python and ensure the "Add to PATH" checkbox is selected. On macOS or Linux, verify your shell configuration file includes the Python installation directory.
If the TWS server script fails to connect to Trader Workstation, verify that TWS is running, that you are logged in, that API connections are enabled in the Global Configuration, and that the port number in your config.yaml matches the port displayed in TWS's API settings (7497 for paper trading).
If the trading bots cannot communicate with the server, check that Redis is running by using the "redis-cli ping" command. Verify that the Redis port in your config.yaml matches the actual Redis port (default 6379). Ensure the TWS server script is running in its own terminal before launching any bots.
If pip install fails for any of the required packages, make sure you are using a compatible version of Python (3.13 is recommended) and that pip itself is up to date. You can update pip by running "python -m pip install --upgrade pip."
Safety Reminders and Best Practices
This section bears repeating given the nature of the software. The trading scripts included in this package have real, live order-placing capabilities. When connected to a live (funded) Interactive Brokers account, they will execute real trades with real money. Always begin by using the paper trading (demo) account. Familiarize yourself thoroughly with how each bot behaves, what triggers it places orders, how it manages positions, and what its risk parameters are. Only after you have a deep and complete understanding of a bot's behavior should you even consider running it against a live account, and doing so is entirely your own responsibility.
It is good practice to enable the "Read Only API" setting in TWS while you are still learning. This allows data to flow through the system while preventing any orders from being placed, giving you a completely risk-free observation mode. When you are ready to test order placement, disable read-only mode but remain in the paper trading environment.
Keep your Python package versions pinned to those specified in requirements.txt until you are confident in your ability to troubleshoot compatibility issues. Upgrading packages can introduce breaking changes that are difficult to diagnose if you are not yet familiar with the codebase.
Conclusion
Setting up an algorithmic trading environment involves coordinating several software components, but each individual step is manageable. By following this guide in sequence — installing Python, setting up VS Code, configuring Interactive Brokers TWS for API access, installing Redis, installing Python dependencies, configuring the project, and launching the server and bots — you will have a fully functional algo trading development environment running on your local machine.
The beauty of this system lies in its modularity. The server handles the brokerage connection, Redis handles inter-process communication, and each bot operates independently with its own trading logic. This architecture makes it easy to add new strategies, modify existing ones, or swap out components as your needs evolve. Combined with an AI coding assistant like Kilo Code, even traders with modest programming experience can experiment with algorithmic strategies and learn how professional-grade trading systems are structured.
Take the time to read all the documents included in the project's documents folder. Run the diagnostic utilities to verify each component. Start with the simplest bot (the Apple equity bot is a good choice) and watch how it operates in paper trading mode before exploring the more complex examples. Algorithmic trading is a deep and rewarding field, and this package provides a solid, accessible foundation on which to build your understanding.


Comments