From Definition to Deployment: Laying the Foundation for a Live Trading Bot!
Why Process Matters?
This article will define a trading bot, automated trading strategy and elaborate on what has to be done to make and test the strategy before taking it live. At the end of the article, you will have a live trading bot with a strategy. It may or may not be profitable. Giving a profitable strategy is not the focus. The focus of the article is on the actual building process of the strategy for your live trading bot. The process is messy and that is what I have endeavoured to demonstrate.
Note: This article is geared towards retail traders.
About the Author

Pranav Lal is a seasoned information-security professional with more than two decades of experience designing and managing cyber-defence programmes for global organisations such as Lloyds Technology Center, Ernst & Young, Vodafone and the Mahindra Group. He holds an MBA from the International Management Institute, a B.Com (Hons.) from Delhi University and the CISSP certification. Visually impaired since birth, Pranav embraced assistive technology early, taught himself programming and now mentors other visually-impaired students in networking and Linux.
Away from his role as Principal Cyber Security Engineer, Pranav pursues photography, long-form writing and quantitative finance.
A long-time EPAT® alumnus, he exemplifies QuantInsti’s mission of making algorithmic-trading knowledge accessible to everyone. His EPAT success story shows how determination, adaptive tools and disciplined study can transform perceived barriers into advantages and has inspired thousands of aspiring quants worldwide. Pranav continues to give back by publishing detailed projects on the QuantInsti blog, including a machine-learning long-only equity strategy complete with production-ready code for retail traders.
Why learn from him? Pranav blends enterprise-grade security expertise with self-taught Python skills and a trader’s mindset rooted in rigorous risk management. He favours clarity, modular code and reproducible research, making his tutorials approachable for beginners yet robust for seasoned professionals. His career demonstrates that inclusive design, methodical thinking and community spirit can unlock sophisticated trading for any learner, while showing how resilience and clear communication accelerate growth across the quantitative-finance ecosystem.
Section 1: Introduction & Foundations: What Is a Trading Bot, and Why Build One?
What is a Trading Bot?
A trading bot is a piece of software that automatically places trades in financial markets based on a defined set of rules. These rules can range from simple moving averages to more complex algorithms driven by price patterns or economic data. The bot connects to a broker’s platform, such as Interactive Brokers, and executes trades directly without requiring manual input.
Over time, trading bots have evolved from institutional-only tools to systems that retail traders can build and run themselves. With Python and APIs now more accessible, building a trading bot is no longer out of reach, even if you're just starting out.
Why Would Someone Want to Build a Trading Bot?
If you've ever missed a trade because you were away from your screen, or if you’ve placed trades based on emotion rather than logic, a trading bot can help. Bots don’t get tired, they don’t second-guess, and they don’t panic.
Here are a few practical reasons to consider building one:
- They react faster than humans can, especially in volatile markets
- They follow rules exactly as written, every time
- They monitor the market even when you're not around
- They allow you to test a strategy on historical data before risking real money
- They make it easier to scale by trading multiple instruments at once
Whether you want to trade stocks, crypto, or forex, a bot can help you stick to your plan and remove the noise that often comes with discretionary trading.
What Types of Strategies Can Trading Bots Execute?
A trading bot is software that automates a strategy, if you can define the logic, access the data, and code the rules, you can turn it into a bot.
Common Strategies Bots can Automate:
- Technical + Statistical: Based on moving averages, RSI, MACD, or mean-reversion signals like Z-score.
- ML-Based: Predictive models trained on price, volume, or engineered features.
- Sentiment & News: GenAI/NLP bots that react to headlines, earnings, or social trends.
- Multi-timeframe: Intraday, swing, or high-frequency depending on your setup and latency tolerance.
They work across stocks, futures, crypto, and forex, as long as data and liquidity are sufficient.
Where Do Humans Fit In?
Think of humans as hunters managing a pack of hunting dogs (bots). The key is picking the right breed for the right terrain, the right bot for the right market. That subjective role, strategy design, market selection, and context is increasingly being augmented (and sometimes replaced) by AI.
Today, the human role is shifting to:
- Creating strategies
- Backtesting ideas
- Deploying and monitoring infrastructure
- Handling exceptions and edge cases
As AI evolves, even strategy creation and tuning are becoming semi-automated but judgment, creativity, and system oversight still matter.
What Are the Risks of Using a Trading Bot?
Trading bots can improve speed and discipline, but they also come with their own set of challenges. It’s important to be aware of them before going live:
- Your strategy might look good on paper but fail in real-time markets
- A bug in the code could result in unexpected losses
If your internet connection drops or your broker's API changes, the bot may stop working - Sudden market shocks, like political news or earnings surprises, can lead to losses that the bot isn’t equipped to handle
- Regulations vary depending on your country, especially if you're trading frequently
These are not reasons to avoid using a bot, but they are reminders to test carefully and build safeguards into your system.
Do You Need to Know How to Code?
Not necessarily. Some platforms offer low-code or no-code solutions, but if you're serious about customising your strategy or integrating with brokers like Interactive Brokers, learning Python will go a long way.
At a basic level, you’ll want to be comfortable with:
- Python programming
- Working with data in pandas
- Understanding how APIs work
- Reading documentation and troubleshooting
You don’t need to be an expert, but a foundational understanding will help you avoid common mistakes and make better decisions. Tools like ChatGPT can help generate code and explain concepts, but they are not substitutes for your own judgment. They are best used as guides, not drivers.
Even Though Trading Bots Exist
There are hundreds of trading bots already out there. You’ll find commercial ones, open-source ones, and tools that promise to automate your entire portfolio. So then, why go through the trouble of building your own?
Because a bot is only as good as the strategy it follows, and the strategy must match your capital, your objectives, and your risk tolerance. Copy-paste bots may work for someone else, but without understanding how and why they work, you're handing your capital to a black box.
This guide is about building your own system, step by step. Not to find the perfect bot, but to learn how to turn a trading idea into a working process. Because once you understand that process, you can test, adapt, and evolve your strategy instead of relying on someone else’s.
Section 2: Building and Backtesting the Strategy
Quick Overview
- Identify core elements of a trading strategy, market, timeframe, entry/exit, sizing, risk, metrics.
- Code a modular GoldenCross class in Python using 50/200-day SMAs.
- Validate incoming OHLC data to avoid “garbage-in, garbage-out.”
- Run two back-tests:
- Signal-based (long/short) snapshot.
- Long-only version aligned with NSE rules.
- Review key outputs: capital curve, Sharpe, Sortino, max drawdown, profit per trade.
Let’s get started.
We begin at the beginning, what is a trading strategy? A trading strategy is a systematic plan or set of rules designed to guide buying and selling decisions in financial markets. It’s used by traders and investors to maximise profits and minimise risks.
Key Components of a Trading Strategy:
- Market: The asset class (e.g., stocks, forex, crypto, futures).
- Timeframe: Intraday, daily, weekly, etc.
- Entry Criteria: When to buy or sell (based on indicators, patterns, news, etc.).
- Exit Criteria: When to close a trade (take profit, stop loss, time-based exits).
- Position Sizing: How much capital to allocate to each trade.
- Risk Management: Techniques to control losses (e.g., stop-loss, portfolio diversification).
- Performance Metrics: Tools to evaluate the strategy (e.g., Sharpe ratio, win rate, drawdown).
There are plenty of articles on this blog that define the types of trading strategies etc., and that will not be covered here. If you need that information, see the below links.
Factors That Determine Your Trading Approach
This is all very well as far as definitions go. However, what kind of strategy do you choose? The sad truth is that it depends. There are various factors that come into play when deciding which security you will trade in.
- Capital:
How much capital do you have? It is cheaper to buy individual stocks as opposed to buying derivative products like options and/or futures. - Knowledge:
What are you comfortable trading in? Remember, you will set the rules, therefore, you should know what they are and how to do risk management. - Broker Rules:
Brokers have their own rules with respect to margin requirements to trade certain securities. This is usually a factor of how much money you can put in into your trading account. The more the money, the more you can trade. - Objectives:
What do you want to achieve by trading? For example, you may want to generate daily cash flow in which case, intraday trading will work. However, if you want to focus on long-term returns, then following the trend and holding stocks for a year may work. - Regulations:
Government and broker considerations If you trade too much, then you may be charged more tax since you will be charged on the profits. Also, some brokers restrict day trading based on how much money you put in.
How to Select Instruments and Find a Strategy
Choosing the right instrument to trade is foundational to building a successful strategy. Your decision depends on several factors such as available capital, trading goals, personal expertise, and broker constraints. Once you've determined what to trade, the next step is identifying how to trade it and that brings us to strategy discovery.
Finding Trading Strategies
How do you find a trading strategy? The literature will always say that the best strategy is one you have developed. That is all very well, but how do you even begin to think about this? Yes, you can just ask your favourite large language model to generate one for you. However, these models have their limitations in terms of how updated they are. We will, however, use them to generate code snippets. In addition, you should follow your own code structure as opposed to using what the model gives you because the model can change the structure.
Sources for Trading Strategies
One question that arises is how to find trading strategies. The textbook answer is to study the markets and derive the strategy. Alternatively, trade manually, keep a journal and then in 3 to 6 months, study the journal and then build a strategy on that. The above approaches are valid but if you want to accelerate the game, see the following sources. On medium, you will need to search for strategies like trend following strategy or momentum strategy. You will need to do something similar on quantified strategies. However, feel free to browse both sites and pick what you want.
A Simple Trend-Following Strategy: The Golden Cross
We will pick a simple trend following strategy for our example. This is your traditional golden cross. This approach is best used in trending markets over a long-term time horizon say one year. See the below blog post for details. Momentum Trading: Types, Strategies and More
In many cases, people use the 50-day simple moving average for the short period moving average and the 200-day simple moving average for the long period moving average. Therefore, our strategy becomes:
- Buy when the 50-day SMA crosses above the 200-day SMA.
- Sell when the 50-day SMA crosses below the 200-day SMA.
We are going to test this strategy before we go live with it.
A note on rules: Remember risk management? We will factor that into the test as well by putting a trailing stop loss.
A word on code: We will keep the code modular that is, each functionality will be kept in its own unit. The advantage of this approach is that you can plug the code into whatever framework you need. We will put the strategy into its own class. The testing code into a procedure and will do the same for the data fetching code.
Basic Strategy Implementation in Python (Golden Cross Class)
We will need the following libraries which you can install using pip.
This is the basic strategy class. The problem at the moment is that there is no error checking. Do we know if the data frame that we take in actually has the relevant columns we need?
Enhancing the Strategy with AI Support
Using ChatGPT to validate logic, fix bugs, and improve precision.
This is where large language models come in handy. You can feed in the code to your favourite chat bot and get an answer. I am using ChatGPT You can use whatever you like.
"Analyse the below code. Does it match with the golden cross strategy? Add a routine to validate the data frame coming from the broker."
ChatGPT's response is interesting and is below. I am not duplicating my entire prompt because all I did was to paste the code of the class into the prompt box.
I also put in the backtesting routine which we have not covered. I will come to that as well as the mechanism for fetching the data from interactive brokers.
✅ Code Analysis
1. Does the strategy match the Golden Cross?
Yes, mostly - but there's a key mistake.
The Golden Cross is when the 50-day SMA crosses above the 200-day SMA, but in your code:
You pass long_period = 200 and short_period = 50, which is correct.
BUT...
and
are ineffective, because ffill() and bfill() are not assigned back to the DataFrame. You should write:
Also, the generate_signals method assigns signals every time the short MA is above or below the long MA, instead of only on the crossover points, which would be more precise. That said, this approximation is still widely used.
🛠 Suggested Fix: DataFrame Validation Routine
Before calculating indicators, it's good to validate the structure and content of the DataFrame received from Interactive Brokers. Here’s a validation routine you can add inside the goldenCross class or as a separate function.
✅ Add this to the top of __init__():
✅ Define this method inside the goldenCross class:
✅ Optional Improvements
- Add crossover detection for precise signals:
Replace generate_signals() with:
2. Fix the moving average fill logic:
We make the suggested modifications and run the code. One minor point to note is that MM is indeed a valid symbol. It is the ticker symbol for Mahindra and Mahindra Limited. AI is not correct all the time.
Improved Version of the Strategy Class with Error Checks
Fixing ffill/bfill and crossover logic.
We now turn to fetching data from the broker. This is interactive brokers. Once again, the routine is simple. I am running the interactive brokers gateway. I'll talk more about the setup below.
Section 3: Going Live: Connecting to Interactive Brokers
Quick Overview
- Set up Interactive Brokers Gateway (or TWS) and confirm port, client ID, authentication.
- Pull five years of daily OHLC data through ib_async for each symbol or ISIN.
- Separate paper and live environments via multiple gateway instances.
- Schedule the script to run near market close (15:28 IST) with ib.schedule().
- Ensure timezone safety and log every connection step for troubleshooting.
Lets Get Started.
Setting Up Your IB Gateway / ib_async Connection
You have several mechanisms to talk to interactive brokers. There are a plethora of APIs. In most cases, you do need the TWS workstation program running or the gateway program running. These programs provide authentication and low-level connection support to you. The advantage of the TWS workstation is that you can see what your algorithm is doing by watching the various trades.
This is the primary desktop client for interactive brokers. Howevere, there is another client namely the gateway which is meant for headless systems. This is what I am running.
A key program that you may need to run with the gateway is ibc. This allows you to control it headlessly. This is what I am doing. I have the gateway on my linux server which I ssh 2 over my local area network (lan).
You can also run multiple gateways. I run one instance for live trading while the other instance is used for paper trading. Each instance runs at its own port. I change the port in my script and connect to the appropriate instance. The ibc documentation is comprehensive and its mailing list is an excellent source of support. See the below link for details. IbcAlpha/IBC
Fetching Historical Data Programmatically
We now come back to fetching data. The above digression is needed to ensure that you can run the below code.
In the above code we connect to interactive brokers. We are pulling data for 5 years at an interval of 1 day. This means that for each trading day, we will get the bar at the close of trading. We start fetching data from today and go five years back. Once the connection has been established, we define our security which is a stock in this case.
Once we know that the API client is ready, we fetch the historical data into a data frame. We do not need to stay connected to interactive brokers therefore we disconnect. We then ensure that the date in the data frame is a date time value and return the data frame.
This is not a necessary step in this case because we are not doing anything with the date. However, it is crucial if we use the date column for plotting graphs or in machine learning models as a feature.
Backtesting the Strategy: A Realistic Simulation
Tracking capital, drawdowns, Sharpe, Sortino, and more.
How do we know that this strategy works? We write the code and simulate the running of the strategy. We can calculate various matrix to determine how well the strategy does. The below routine does calculate a number of common matrix. For this author, 2 matrix are most important as a retail trader, the final capital at the end of the run and also the maximum drawdown. The maximum drawdown tells us the maximum amount of money the strategy we lost if we had followed this strategy in the past 5 years. In addition, we compute the sharpe and sortino ratios. The final matrix is the profit per trade. How much profit do we make on each trade?
Once again, we turn to ChatGPT and give it the following prompt. Please note, this is a realistic simulation of the strategy inline with Indian markets. If trading in stocks, at the time of this writing, you cannot short for more than a day. This is a positional trading strategy therefore we will configure the test accordingly.
write a routine to backtest this strategy. Assume that this is a long only strategy where we do not buy if we already hold the stock. We can however close the position if we hold the stock and buy it again once the conditions are right. Compute the sharpe ratio, the sortino ratio, the capital at the end of the strategy, the maximum drawdown and the profit per trade. Print all relevant values. Accept the data frame containing the processed signals and the initial capital.
Here is the code that has been generated.
Validating Results vs. Reality
We run this for the symbol SBIN which is the State Bank of India and get the following results.
Initial Capital : ₹100,000.00 Final Capital : ₹134,865.00 Total Trades : 4 Profit per Trade : ₹8,716.25 Maximum Drawdown : -0.10% Sharpe Ratio : 13.66 Sortino Ratio : nan
Improving the Backtest with Real-World Constraints
Long-only implementation to reflect retail market rules in India.
The code above works but is not easy-to-read. Let us see what happens when we write our backtest manually and help the AI generate the code in the way we want. I send the following code block to ChatGPT.
You're on the right track! Here's how to complete your strategy backtest to compute:
• Cumulative returns
• Final capital
• Sharpe ratio
• Sortino ratio
✅ Completed Version of test_strategy:
✅ Notes:
• .shift(1) ensures signals don't use today's return to make today's decision (avoids lookahead bias).
• cumprod() gives cumulative returns over time.
• Max drawdown uses peak capital tracking.
• You can plot df["capital"] vs. time to visualise equity curve.
Would you like this to track individual trades (entry/exit prices, returns) or generate performance charts (like equity curve or drawdown plot)?
Here are our results. Examine them closely.
Initial Capital : ₹100,000.00 Final Capital : ₹98,528.05 Sharpe Ratio : -0.20 Sortino Ratio : -0.03 Maximum Drawdown : -1.98%
So, what is missing? One item is the long only component. Remember in the above section we had the rule where we could not short except for a day? That has not been accounted for in the above backtest. Let us do that now, see how the code changes and see the results.
Final Execution Block: Tying Everything Together
Putting the strategy class, fetcher, and backtests into a unified run.
We can now put everything together and test our strategy. I am going to show you the execution block first and then put the final code in place.
It is easy to test for multiple stocks. All we need to do is to change the symbol and rerun the script.
Here is the full final running code.
Section 4: Executing Live Trades with Risk Management
This section turns the back-tested idea into a production script that can run unattended on Interactive Brokers:
- Connection & Scheduling - Spin up an ib_async Gateway/TWS session, qualify contracts by ISIN, and schedule execution near market close.
- Capital & Sizing Logic - Pull real-time “Available Funds,” cap risk at 3 % per trade, and round quantities to IB’s lot/tick rules.
- Order Stack - Send a parent limit order for entry plus a child ATR-based trailing stop that moves with the trend and caps downside.
- Error Handling - Catch API disconnects, partial fills, or rejected orders; log everything and cancel gracefully if protection isn’t live.
- Audit Trail - Persist logs and (optionally) journal each trade—symbol, size, P&L: for post-trade analytics.
We are now in a position to take our strategy live. This requires deep knowledge of the broker's platform because this is where the integration with the broker begins. For backtesting, we can use any data provider as long as we get the data frame in the OHLC (open, high, low and close) format. However, once we commit to a broker, a number of things need to fall in place.
Capital Allocation & Order Types
- Cash management: The first thing is cash management. You need to determine how much capital you can risk per trade. You can choose any percentage or absolute amount. We will assume 2% of capital for now.
- When to run the trade: We are dealing with end-of-day data. Therefore, it is better to run the script near market closing. Our entire strategy is based on end-of-day values.
- What kind of orders to use: If you are an aggressive trader, then use market orders. This means that you will buy the stock at prevailing prices. However, if you want more control, then you will need to use limit orders. The kinds of orders to use is an entire book in itself. We will stick to limit orders for now.
- Which securities to trade: This is guided by your backtests. It is possible to use scanners to guide this selection as well. To keep things simple, we will use a hard coded list but the procedure will be the same.
- Handling connection errors: In the real world, internet connections do break and other things happens. We need to handle them gracefully.
- Other capital protection measures: We are using a trend following system. Therefore, we should use stop losses to prevent losing our money.
We are going to separate the running logic from the testing logic. The class remains unchanged.
We will be using the ib_async framework. This simplifies working with this broker. Interactive Brokers have their own apis but they are more complex to use that is, in many cases like connection handling, they need more lines of code to get the same thing done.
Note the ib.run() routine. This routine starts an event loop so that our script can keep running. We have also scheduled the process_securities routine to execute at the time of our choosing which is 15:28 IST.
Another thing, we will not be using stock symbols. This is because they vary across Indian exchanges. We will use the International Securities Identification Number or ISIN. This is a universal identifier for securities.
We now come to the process_stocks routine.
It is time to look at placing orders. We will first write logic for a buy order because we are focusing on creating a long only strategy. This is because the Indian markets allow the short selling of stocks only in intraday trades.
We first need to write some supporting functions.
We are now ready to add these functions to our script and begin placing orders.
Note on code organisation: I could have combined the function to place buy and sell orders into a single routine but I have not done that to allow to better see the differences between the buying and selling logic.
Dynamic Sizing & ATR-Based Trailing Stops
We are following a trend therefore need to protect our capital. Towards, we will use a trailing stop loss using the average true range as a measure of volatility to set our stop loss.
The idea here is to give the stock enough room to move so that we do not exit too early.
Fetch historical data and calculate ATR
Full Production Script Walk-Through
We have come a long way. We started by developing a strategy, backtesting it and have finally run it on interactive brokers. There is plenty more to do. You could add logic to optimise the time period of the averages based on a criterian like profit per trade. Order execution methodologies could be altered. More confirmations can be taken using multiple indicators or a combination of price action and indicators. The basic principles however remain exactly the same.
The Final Script: Next Steps & Expansion Ideas
This is our full and final running code.
The getClientId module
This is a custom module that I have written to get unique client id values for interactive brokers. You can substitute your own logic instead of using what I have written. The client ids must be unique.
References
The ib_insync project has been archived because the originator died. However, the ib_async project has grown from it. As of this writing, it is actively maintained though updates are slow. The documentation remains the same. Ib_async Interactive Brokers order types Average True Range.
Closing Thought
And finally, don’t just copy and paste this strategy or the code you see here and expect it to work for you. Use it to learn. Backtest it. Modify it. Break it and fix it. The point of this guide is not to give you a finished solution, but to help you understand the process of building one.
Because once you learn how to do that, you won’t need to rely on someone else’s bot. You’ll be able to build and trust your own.
Next Steps
Pranav’s journey from research to live trading is one that many aspiring quants can follow with the right tools, concepts, and support. If you're ready to build your own trading system, these curated resources will help you scale efficiently and confidently:
1. Learn the Logic Behind Indicators and Patterns
Move beyond surface-level technical analysis with the Learning Track on Technical Analysis & Quantitative Methods. Learn how indicators behave statistically and how to engineer rule-based strategies grounded in quantitative logic.
2. Learn Portfolio Construction and Risk Controls
Scaling from a single strategy to a multi-asset portfolio demands solid risk management. Quantitative Portfolio Management covers drawdown control, asset allocation, and metrics like VaR/CVaR to make your strategy institutional-ready.
3. Apply Proven Strategy Frameworks from Experts
Take inspiration from strategies that work in the real world:
- Mean Reversion Strategies with Dr. Ernest Chan: Learn how to identify and backtest mean-reverting opportunities using Python.
- Volatility Trading Strategies: Understand how volatility can be used as a core signal across different regimes.
- Deep Reinforcement Learning for Trading with Dr. Thomas Starke: Train agents that adapt and learn in real-time environments, simulating institutional AI trading pipelines.
4. Integrate Advanced ML and Macro Contexts
As your strategy sophistication grows, explore how AI adapts across market regimes. The Artificial Intelligence in Trading – Advanced Learning Track helps you develop models that evolve with changing market data and behavior.
5. Go All In with EPAT®: From Code to Live Strategy
The Executive Programme in Algorithmic Trading (EPAT) equips professionals to become fully self-sufficient quant traders. Covering machine learning, time series forecasting, trading APIs, and live deployment, EPAT has helped thousands (including Pranav) launch and scale live strategies with confidence.
Contribute & Collaborate
QuantInsti’s mission is to make algorithmic-trading knowledge and technology accessible to every market participant, with a vision of empowering individuals and institutions to harness cutting-edge tools for long-term success. Inspired by contributors like Pranav Lal, whose Golden-Cross walkthrough you’ve just read, we invite you to strengthen the global quant community by publishing your own research, code modules, case studies, or tutorials. Review our Blog Contribution Guidelines, fork the public repo, add your draft or enhancement, and submit a pull request, every insight you share expands the collective knowledge base and propels quantitative finance forward.
Connect with an EPAT career counsellor to discuss the right quant role for your background.
Disclaimer: This blog post is for informational and educational purposes only. It does not constitute financial advice or a recommendation to trade any specific assets or employ any specific strategy. All trading and investment activities involve significant risk. Always conduct your own thorough research, evaluate your personal risk tolerance, and consider seeking advice from a qualified financial professional before making any investment decisions.