📱

Get Our Mobile App

Take your business learning on the go!

Download on the App StoreGet it on Google Play

Claude + IBKR API: Complete AI Trading Bot Guide

Humbled Trader23:27

Transcription

Imagine this. Every morning you wake up, your AI trading bot has already scanned the market and sent you a list of gappers that fit your strategy. After the market opens, it triggers buy and sell orders for you autonomously. And it continues to run the cycle every 30 minutes through the entire trading day.

This is the power of connecting Interactive Brokers API with Cloud Code. And I'll show you how to do that in this video. So, this is what you're going to learn.

How to set up a broker API and connect Cloud Code to it safely.

How to create your strategy with the help of AI.

The full pipeline I've built from universe scan, decision loop, executions, and exit logic.

And finally, setting up Telegram alerts like this, so you get notifications every 30 minutes from your bot.

Last but not least, we're also going to build a dashboard [music] that tracks the R multiples per trade.

In my last video, I showed you how I use Cloud and TradingView together to build a pre-market trade planning process with a high win rate and backtested strategy. But the one thing that TradingView and Cloud connection couldn't do was actually pull the trigger to buy and sell. So, in this video, I'm going to show you how to go from a backtested strategy to an actual trading bot that places its own orders, manages all the stops, takes partials, trails the winners, and force closes everything before the market closes. All of this pipeline is running on my computer with Interactive Brokers API and Cloud, [music] and I'm completely hands-off.

I want to give you the same disclaimer as last time. AI is simply a multiplier. You still need to know how to trade first. I'm not a developer. I have no background in coding, but I am a trader. >> [music] >> So, if I can do this, then so can you. So, buckle up. Make sure to like this video and subscribe down below to see more step-by-step video lessons on using AI to optimize your trading.

Okay, let's get started with setting up Interactive Brokers API. There's three things you need to install. I'll keep this one really short. The full steps and the details are on my blog. You can use that article as a video companion to follow along here and copy all the prompts from that blog. The link is down below.

Before we do anything with Claude and AI, you need to have these things installed on your computer. First is Trader Workstation TWS, which is Interactive Brokers' trading platform. And you also need Python. Again, no coding experience is necessary here because we have Claude. So, I already have Python installed and I'm just going to start running my Interactive Brokers. I'm going to be using a paper trading account on TWS because we're not putting in real money on this yet until it runs clean for weeks. So, I'm going to log in to my paper trading account. Uh, make sure you go through the process. You can download TWS on the Interactive Brokers website. I'll leave the link down below. And you can open up a free paper trading account even if you don't have a market data subscription.

All right, we're in. You can see now we're in the Interactive Brokers TWS platform. I've done video lessons and tutorials on how to optimize and make it look prettier. I tried my best, but it still looks like this. I know. So, what you want to do is to set up the API access. Go to file up here and go to global configuration. And once you're in here, you want to go to API, go to settings, and you want to enable ActiveX and socket clients. And over here, the next part is you want to make sure the socket port here is labeled as 7497. This is the paper port. If you're changing this up to a live account later, you just need to change a number to 7496. Next, scroll all the way down, um, uncheck that, and create a trusted IP. You want to add 127.0.0.1 to the trusted IPs. I've already done this one, so I'm just redoing this again with a new paper trading account for this demo. So, once you have that ready, you want to click apply, but I want to check one thing. One more thing, up here on the general, you want to check off read-only API because you want the API to actually be able to execute trades for you. So, make sure you have these things enabled and the trusted IP, and you want to click apply and and okay and okay.

Okay, and after that, you don't really need your TWS anymore, so I'm going to minimize it. Another thing you want to make sure you have is you need to have Python tools installed on your PC. I already have Python installed. If you don't, just download Python 3.12 or newer. Claude or Codex can walk you through that easily. And oh, and I forgot to mention you obviously also need either Claude or Codex on desktop. Um, so, if you don't, make sure you go to their website and at least get the, I think the $20 per month minimum max plan, the paid subscription, um, then that should be enough to get you started.

So, after we're done with TWS and Python, we want to create a new environment for us to work in. So, I'm just going to copy this prompt um from my blog here. So, next we want to start a fresh project um in Claude. You can see I named this one Interactive Brokers Claude demo. So, I want to make sure that Claude can now talk to Interactive Brokers. I'm working on connecting Interactive Brokers Python and Claude together. I have an Interactive Brokers paper trading account in global configuration setup already. Can you walk me through the connection process?

Okay, so you can see that Claude is walking me through the process. Um, do you want to place order placement label or read only? We want to do full trading, which is with paper. So, now I think about it, you can start at the very beginning of the video just asking Claude to walk you through as well. And really important, I'd like to use auto mode because, you know, it allows Claude to kind of proceed without asking all the permissions. I hate that. But obviously, if you're more careful, you can use ask permissions, but you just got to be here and you'll have questions for you like every 10 seconds. I've been doing a lot of projects and tasks on Claude, so that's why I'm comfortable using the auto mode.

As you can see, Claude just did a whole connection pipe for us with Python and Interactive Brokers. Now we can test the connections. Like I mentioned at the beginning of the video, AI won't magically make you profitable. Claude can help you build scanners, analyze news, and even automate parts of your trading process. But if the underlying strategy has no edge, the bot will only help you lose money faster and more consistently. At the end of the day, the edge is still in your strategy and in your ability to identify opportunities in the market.

For the momentum day trading strategies I personally trade, I tend to focus on sectors showing outsized relative strength. And this year, one of the biggest themes has been semiconductors and all the companies powering the AI boom. If your strategy also rides momentum in that sector, BetaPro offers a 3x leveraged semiconductor bull ETF that can potentially provide amplified exposure to the semiconductor market movements. On the other hand, if the strength fades and the sector turns bearish, there are also inverse semiconductor ETFs designed to provide inverse exposure to declines in the sector. Just remember, leveraged ETFs are trading tools, not investing products. They reset daily and in volatile markets, losses can add up just as fast. They're built for daily short-term trading and aren't typically meant to be held long-term. Make sure you understand the risks before trading leverage products. You can learn more about BetaShares lineup of leveraged ETFs using the link down below.

Now, let's get back to building the trading bot with the help of AI. As you can see, Claude just did a whole connection pipe for us um with Python and Interactive Brokers. Now, we can test the connections. Now, I'm going to ask you some questions. Tell me if I have any open positions in this paper trading account on Interactive Brokers TWS. And also give me my buying power.

All right, let's see if it can. This is how you test the connections. Oh, wow. Okay. So, you can see the snapshot for my paper account. There's a million in paper money. Um, you know, the pro tip, don't start paper trading with a million. I would reset this to like 10,000 or something. Uh, I just, it's like I said, it's a brand new paper trading account I just set up yesterday, so I did, I forgot to do that. Next, let's see. So, you can see in this that's, this is the account that's pulling. Um, let's see what else can it do. So, this is the account that is pulling data from. You can see um the cash is, you know, the paper trading cash is a million. That's great. Let's see if we can try to place an order for us. Can you place a buy order on Nvidia with a limit price of $100? I want to buy just one share.

All right. So, let's test the connection if and see if Claude can now place the order for us. So, this is the first paper trade I'm placing on Interactive Brokers TWS here. So, you can see there's a pop-up for simulated trading. You can enable API orders. There's a precautions. This basically just telling you that you are placing trades via an API, which yes, that's what we're doing. So, I'm going to click yes. So, you can see they just tried, or Claude just tried to buy one share of, you know, quantity right here if you zoom in. Quantity one share of Nvidia with a limit price of $100. So, obviously that's not going to get filled, but you can see now the connection is working because Nvidia's trading at $219 right now. But, that's just a test. Okay. >> Order cancelled. >> So, I just cancelled the order.

Now, we can move on to part two, building the Interactive Brokers API bot. And we're going to start with building the strategy. In the previous video, we already have a backtested strategy from TradingView and Claude. And these were the results on the last video. You can see this is pretty good. Profitable 64% of the time. Profit factor is 2.48. And the max drawdown is 7%. Total P&L is 12%. And you can see the list of trades. Um, you can see the entire detail actually in the last video. So, this is a simple um trend join long setup that we created in the last video using Claude and TradingView to do the backtest and creating the Pine Script strategy over here. So, what we're going to do now is to turn this exact trading strategy, the Trend Join Long setup, into one that can be read by the new Interactive Brokers API bot. So, the bot is going to read all the rules, all the entry and exit criteria that we created here, and it's going to run it on every single cycle, and we're going to build that right now.

So, what we'll need to do now is to create a strategy rules file called rules.json, and we can ask Claude to do that for us. Hey Claude, build me a rules.json file for the trading bot. The strategy name is Trend Join Long. This is a long-only strategy. Um, it's going to be traded on the 5-minute chart, and here are the daily filters. The stock needs to be above the previous day's high. The previous day's close also needs to close above the 200-day. Here's the exit criteria. The initial stop is 1% below the low of day. Partial take profit is at 0.75R. Then you set the break-even at 1R. Then trail under the 5-minute swing lows. Here is the risk. 1% account size per trade. Maximum 10% position size of the entire account.

So, I know that was a long prompt, but you can just go to him on my blog [clears throat] again and just go to the strategy file here. You can see I listed all the daily filters here. You can just copy this here. You can just copy the prompt, so it'll be a lot less work for you. So, let me see if everything's correct. I'm just going to clean this up really quick. So, we're inputting the prompt into uh Claude right now to build that rules.json file. So, you can see Claude is working its magic right now. This is amazing. So, you can see it created the file um strategy name long only index. So, one thing I forgot to mention is that when I did the strategy demo and the backtesting in the previous video, I only did it on the S&P 500 stocks just to keep it simple. But, obviously when I trade day-to-day, the trend joining long setup, I'll trade it on all the stocks over a billion market cap and over $3 per share. So, just a caveat here. You can add any stock universe that you want.

Before we move on, just a reminder that if you're enjoying step-by-step videos like this that are really easy to follow along, then make sure to drop a like down below and subscribe if you want to see more like this.

Now that we have the strategy file ready, next we need to build a settings file that tells the bot our Interactive Brokers port, position limit, account information, um, and Telegram tokens for later. This is really boring, but necessary. So, what I'm going to just going to do here is to go to my blog and copy the prompt here and then going back to Claude and paste. So, what this prompt does is that it builds the bot that actually talks to Interactive Brokers, reads the rules, and decides if we should trade. And also orchestrates everything and places the orders on the back end. And the connection and everything is all firing correctly. That's what we want to see.

Okay, amazing. Like this is so much easier than our last video with TradingView connection to Cloud. So, what we just did is we set up Interactive Brokers API and Cloud connection. We also built the trading bot with our backtested strategy. Now, we can actually have Cloud take the trades for us. So, what's next is the fun part. We're going to build out the rest of the trading pipeline and create a brain for the bot.

So, now the bot will have a way to scan the market for you for all the potential stocks that fit your strategy. It'll filter through the gappers and repeat this process every 30 minutes. And if there are potential trades to take every 30 minutes, it'll pull the trigger and execute on the entries and exits. So, we're going to identify the kind of stocks we want to trade. For the trend following long strategy specifically, like I mentioned earlier, I want to trade bigger cap stocks. So, for this demo, we're going to limit the stock universe to all the stocks in the S&P 500. Hey Claude, create a Python list called um SP500_tickers and put all the stocks, all the tickers from the current S&P 500 listings in there.

Okay, great. You can see Claude created the list for us of all the stocks in our universe that the bot is going to trade. But now you need to give that bot a filter. So, to create the filter, I'm going to enter this prompt here. What this prompt does is to further narrow down the list of the 500 tickers. So, what we're filtering for top 20 stocks that gapped up more than 3% on the day. Remember, that's the criteria for this trend following long strategy. So, you can see Claude is working its magic. You can see I asked me earlier to move the 500 tickers list we created to somewhere else. So, I said yes, and now it's working in the background. Okay, so now it created a morning pre-filter. Let's see what that filter looks like. Okay, that's what it looks like. So, you can see now it created a morning pre-filter based on the criteria we just told it. Um, the top 20 stocks that's gapped up uh more than 3% on the day. We can run a test. You can see it's asking it run a test. So, I'm just going to do that. So, okay. So, let's run the test to see the pre-filter stocks that spits out.

All right. Amazing. You can see Claude is doing all the hard work for us right now. Okay. So, here's the summary. They screened the 503 tickers from the S&P 500 in 14 seconds and gave us the top 20 stocks um that have gapped up above 3%. So, here are the results. Over here, you can see it listed it out. Uh, and by the way, this is a list that we're going to wire through to our Telegram notifications later on. So, I want to see this list of the pre-filtered stocks every 30 minutes. So, I'll show you how to set that up later as well. So, this is pretty cool. You can see it also gave us some um observations. Heavy semiconductor and um memory stocks today, which is the case today. Today, all the all those stocks are flying to the moon.

Speaking of watchlists, I send out a free weekend watchlist every single Sunday, which include three to four stocks I'm watching for the week for day trading and swing trading. You can sign up for free with the link down below.

Okay. So, now that we have the API bot, the strategy, the scanner, everything in place, we just need to automate it and set up the alerts. Let's set up the brain cycle now. This is the key to automating the entire trading bot cycle every single day. And this is a prompt I'm going to use. So, I'm going to copy and paste. So, what this is doing that it's asking Claude to set up the cycle of scanning and taking the the order entries every 30 minutes during the market hours. You can change this to 5 minutes if you want. Um, but for trend during long, I think 30 minutes is fine. So, you can see we missed a step earlier. We need to create the watchlist file. Um, and this is the file that's updated every 30 minutes. So, Claude is going to do that for us.

All right. So, that took about a couple minutes. Not bad, not bad. So, this is the cycle that's created. So, you can read through this over here. Uh, all different cycles and timing on with Eastern time and what it created with all the files and the project tree. Um, I just want to say that I have no coding or tech background. So, as long as it's doing what I told asked it to do, which is I'm the trader, I created a strategy, I gave it to Claude, um, and with API and Python it wrote me this cycle. As long as it's executing the trades and running the cycles and scanners like I asked it to do, then it's perfect. Like I already said, I came here with no technical background.

Next, let's move on to Telegram alerts like the ones I showed you on screen earlier. As part of automation, I want to set that these alerts to be sent to my phone. So, you're notified during the scanning process every 30 minutes. When a bot takes a trade, you are notified as well or even when it gets out or take, you know, losses or profit. And I also wanted to create an end of the day summary. This can be done easily with Telegram notifications. I showed you the step-by-step process in the last TradingView video, so you can check out the full breakdown if you need more details. But for this demo, I just want to set up this prompt.

All right. So, it looks done. Let's do a test right now. Okay. So, you can see that it sent some examples cleanly on our Telegram. You can see the pre-market filters, the pre-filters sent at 9:32 um, a.m. You can see the top 20 list of stocks. You can see some examples of a buying a stock, selling a stock, partials, trailing stops. And uh, it doesn't have a good example of the end of the day summary, but you can see Claude is explaining how you don't have a real P&L summary right now. But, if it does take some trades, it's supposed to look like this.

I'm not going to lie, building this automated trading system hasn't been the simplest thing. Well, yes, the strategy was already backtested on TradingView to be really high win rate and really profitable. Once it's transported to Interactive Brokers API for actual executions, the results are just very meh. This is a dashboard I asked Claude to build. You can do the same as well. Just use the prompt on my website. I think there are many reasons why there's a huge discrepancy between the two trading performance. The backtest was limited. We ran an unlimited number of tickers with limited timeframe on TradingView. Second is, I haven't quite figured out how to translate all the executions I do manually as a human to be 100% defined as a code with indicators and all the technical parameters. That's the part I'm still testing out, and I'll make future video updates on this. The honest result so far, the backtested numbers don't perfectly translate to live execution. Right now, my own performance as an actual human being trading a trend join long setup is still much better than any of these bots um automations. But, I do think this TradingView and Interactive Brokers API system is a solid starting point. So, I'm going to keep working on this. It's not finished yet. So, make sure to follow along because I'm going to make a lot more videos on how I'm optimizing my strategy, performance, and trading executions with AI, cloud, and all the tools out there.

Special thanks to BetaPro ETFs for sponsoring this video. Make sure to check out their leverage ETF products with a link down below. If you haven't seen the video on how I'm using cloud and TradingView to backtest my strategies and create a premarket scanner, then you should check out this video over here.