@shmidtqq: https://x.com/shmidtqq/status/2074177517150224402
Summary
A guide on using Claude AI to automate stock trading via the Interactive Brokers API, running on a loop every 30 minutes. It covers setup, installation, and strategy execution for paper trading.
View Cached Full Text
Cached at: 07/07/26, 01:22 AM
Claude AI Now Trades Stocks on Its Own. Zero Clicks, Every 30 Minutes.
It is a quiet morning. No charts are open, no coffee is even poured, yet a short list of hand-picked stocks is already waiting on the screen. The opening bell rings. Orders fire on their own. Stops slide up behind the price. Partial profits get booked. And long before the close, every position is flat again. Not a single button was clicked.
That is not a fantasy, and it is not magic. It is what happens when Claude is plugged straight into the Interactive Brokers API and taught exactly how a strategy trades. What follows is the full path from an empty screen to a bot that scans, decides, buys, sells, and reports back every 30 minutes, all running quietly on one computer.
One blunt truth before the fun begins: AI is a multiplier, not a money printer. It can build scanners, crunch filters, and pull triggers faster than any human, but it cannot invent an edge that is not there. Feed it a losing strategy and it will simply lose faster and more consistently. Feed it a real edge, and this is where things get interesting.
This is educational material, not individual investment advice. Automated trading can lose money, so everything below is done first on a paper account with virtual funds.
The code in this guide illustrates what Claude builds under the hood. You do not have to write any of it by hand, but it helps to understand what is happening and to be able to check the result. Examples use the ib_async library, the maintained successor to the older ib_insync.
Part 1. How it works and a quick glossary
The whole system is one loop that repeats itself. It scans the market for stocks that fit the strategy, filters them down to a shortlist, and waits. When a setup triggers, it buys. Then it manages the trade: moving the stop, taking partials, trailing the winner, and closing everything before the bell. Thirty minutes later, it does the entire thing again.
The missing piece that most setups never solve is the trigger. Plenty of tools can plan a trade and even backtest it beautifully, but they stop right at the moment of truth and leave the clicking to a human. Connecting Claude to the broker API removes that last bottleneck, so the plan and the execution finally live in the same place.
A short glossary to make the rest easy:
-
Gap: an open that jumps well above the previous day close.
-
Gapper: a stock that opens with a big gap, usually upward.
-
R: the risk of one trade in money; 0.75R is 0.75 of that risk.
-
Swing low: a local low on the chart, an anchor point for the stop.
-
**Profit factor: **total profit divided by total loss, above 1 is good.
-
SMA 200: the average price over 200 days, a long-trend reference.
-
Limit order: buy or sell no worse than a set price.
-
Stop: the level where a position closes to cap the loss.
-
**Trailing stop: **a stop that crawls behind price to lock in profit.
Part 2. What to install
Nothing moves until three pieces of software are installed and one account is open. Step by step:
-
Open the Interactive Brokers website and create a free paper (demo) account. It works even without a market data subscription.
-
Download and install Trader Workstation (TWS), the Interactive Brokers trading platform.
-
Download Python 3.12 or newer from python.org. On Windows, tick Add Python to PATH during install.
-
Install Claude Code from the official Claude site and sign in with your paid plan (from about 20 dollars a month).
**The golden rule: **paper first. Real money stays out until the bot has run clean for weeks. No coding background is required, since Claude handles the technical wiring.
Part 3. Opening the API door in TWS
One wrong checkbox and the bot can watch but never trade. Step by step:
-
Log into your paper account in TWS.
-
Open Global Configuration from the File or Edit menu (depending on the version), then go to API and Settings.
-
Turn on Enable ActiveX and Socket Clients.
-
Set the socket port to 7497 for paper (it becomes 7496 for a live account later).
-
Add 127.0.0.1 to the Trusted IPs list.
-
Uncheck Read-Only API, or the bot can only read data and will never place an order.
-
Click Apply, then OK, and minimize TWS. From here it runs quietly in the background.
Part 4. Connecting Claude to the broker
-
Start a fresh project in Claude for this bot.
-
Hand it a prompt like this: “I am connecting Interactive Brokers, Python, and Claude together. I already have an Interactive Brokers paper trading account set up in global configuration. Walk me through the connection process.”
-
Claude guides you step by step, installs the ib_async library for the broker link, and asks whether to allow order placement or stay read-only. Choose full trading on the paper account.
Auto mode lets Claude keep working without stopping for approval at every step. Prefer a tighter leash, leave permissions on, but expect a question roughly every ten seconds. And keep the reality check close: the wiring is the easy part, the edge lives in the strategy, not in the plumbing.
Part 5. The smoke test and the first robot trade
Before trusting the bot with anything, prove the pipe is really open. The first test is an account snapshot. Under the hood it looks like this:
pythonfrom ib_async import IB
ib = IB() ib.connect(“127.0.0.1”, 7497, clientId=1) # 7497 = paper account
print(“Positions:”, ib.positions()) # empty on a fresh account
for row in ib.accountSummary(): if row.tag == “BuyingPower”: print(“Buying power:”, row.value)
ib.disconnect()
Tip: a brand-new paper account can start with an absurd balance like a million. Reset it to something realistic, such as 10,000, so the numbers actually mean something.
The second test is a real test order. Set a limit far below the market so it cannot fill, but the act of sending it still proves the link:
pythonfrom ib_async import IB, Stock, LimitOrder
ib = IB() ib.connect(“127.0.0.1”, 7497, clientId=1)
contract = Stock(“NVDA”, “SMART”, “USD”) ib.qualifyContracts(contract)
order = LimitOrder(“BUY”, 1, 50) # limit 50, deliberately below market trade = ib.placeOrder(contract, order) ib.sleep(2) print(“Status:”, trade.orderStatus.status) # Submitted, but never filled
ib.cancelOrder(order) ib.disconnect()
On the first order, TWS pops up a simulated-trading warning about API orders, which you confirm. The order sits unfilled because the price is unrealistic, yet the connection is already proven. Cancel it and move on.
Part 6. The strategy as rules.json
A bot is only as smart as the rules it is given. The example setup is a long-only momentum play: buy on the 5-minute chart when price is above the previous day high and the previous close is above the 200-day moving average. Exits: initial stop 1 percent below the low of day, partial at 0.75R, break even at 1R, then trail under the 5-minute swing lows. Risk 1 percent of the account per trade, at most 10 percent of the account in one position.
Backtested, that example showed a profitable rate of 64 percent, a profit factor of 2.48, a maximum drawdown of 7 percent, and total P&L of 12 percent. Treat those numbers as an illustration, not a guarantee.
Claude turns the rules into a rules.json file:
json{ “strategy_name”: “trend_join_long”, “direction”: “long_only”, “timeframe”: “5min”, “daily_filters”: { “price_above_prev_day_high”: true, “prev_close_above_sma”: 200 }, “entry”: { “min_gap_up_percent”: 3 }, “exits”: { “initial_stop”: “1_percent_below_low_of_day”, “partial_take_profit_R”: 0.75, “move_to_break_even_R”: 1.0, “trail”: “under_5min_swing_lows” }, “risk”: { “risk_per_trade_percent”: 1, “max_position_size_percent”: 10 }, “universe”: “SP500” }
The most important thing for a beginner is to see how the rules turn into a position size. Here is the same logic in code, where 1R becomes obvious:
pythonimport json rules = json.load(open(“rules.json”))
account_value = 10_000 risk_dollars = account_value * rules[“risk”][“risk_per_trade_percent”] / 100 # 100 dollars = 1R
entry = 20.00 stop = 19.80 # about 1% below the low of day per_share_risk = entry - stop # 0.20 per share shares = int(risk_dollars / per_share_risk) # 500 shares
the 0.75R partial triggers at entry + 0.75 * per_share_risk = 20.15
In the demo the universe is simplified to the S&P 500. A fuller version screens everything above 3 dollars a share and a billion in market cap. Change the universe line and the whole pool changes.
Part 7. The settings file and token safety
The settings file stores the port, client id, account number, limits, and Telegram tokens:
json{ “ib_host”: “127.0.0.1”, “ib_port”: 7497, “ib_client_id”: 1, “account”: “DU1234567”, “max_open_positions”: 5, “telegram_bot_token”: “PASTE_YOUR_TOKEN_HERE”, “telegram_chat_id”: “PASTE_YOUR_CHAT_ID_HERE” }
**Safety rule: **this file holds access to your bot and channel, so never post it anywhere, never send it in chats, and never push it to a public repository. If a Telegram token ever leaks, revoke it in BotFather and generate a new one.
Part 8. The universe scanner and the gap-up filter
First the bot needs a universe, then a filter that leaves only candidates on each pass. The gap logic and the top-20 selection look like this:
pythonfrom ib_async import IB, Stock
ib = IB() ib.connect(“127.0.0.1”, 7497, clientId=1)
def gap_percent(ticker): c = Stock(ticker, “SMART”, “USD”) ib.qualifyContracts(c) bars = ib.reqHistoricalData( c, endDateTime=“”, durationStr=“2 D”, barSizeSetting=“1 day”, whatToShow=“TRADES”, useRTH=True) prev_close, today_open = bars[-2].close, bars[-1].open return (today_open - prev_close) / prev_close * 100
scored = [(t, gap_percent(t)) for t in sp500_tickers] top20 = sorted([s for s in scored if s[1] > 3], key=lambda s: s[1], reverse=True)[:20]
In testing, a scanner like this runs through the whole S&P 500 in about 14 seconds and returns the top 20 gappers above 3 percent. That same list later gets pushed to your phone every 30 minutes, so you see the picks before the bot acts on them.
Part 9. The brain cycle: automating every 30 minutes
The cycle is what makes this a bot instead of a toolbox. It runs the scanner, checks the rules, and takes entries every 30 minutes during market hours. The skeleton:
pythonimport time from datetime import datetime from zoneinfo import ZoneInfo
def market_open_now(): now = datetime.now(ZoneInfo(“America/New_York”)) minutes = now.hour * 60 + now.minute return now.weekday() < 5 and 9 * 60 + 30 <= minutes < 16 * 60
while True: if market_open_now(): run_cycle() # scan, filter, decide, execute, alert time.sleep(30 * 60) # wait 30 minutes; you can set 5 minutes
Alongside it, the bot keeps a watches file that refreshes every cycle:
json{ “updated”: “2026-07-05T13:30:00-04:00”, “candidates”: [ { “ticker”: “NVDA”, “gap_percent”: 4.2 }, { “ticker”: “AVGO”, “gap_percent”: 3.6 } ] }
One practical point people forget. The bot lives on your computer, not in the broker cloud, so it only runs while the computer is on and TWS is logged in. Once a day, TWS logs itself out and restarts, so turn on TWS auto-restart and keep the machine on during market hours, or the loop will stall.
Part 10. Telegram alerts
First create a bot and get the credentials:
-
Open a chat with @ BotFather in Telegram, create a bot, and get a token. The token is a long string with a colon in it; keep it like a password.
-
Find your chat_id: message your new bot once, then read the chat_id through a helper bot (such as @ userinfobot) or through the getUpdates method of the Telegram Bot API.
-
Paste the token and chat_id into the settings file from Part 7.
Sending a message is a simple Telegram Bot API call:
pythonimport requests
def send_telegram(token, chat_id, text): url = f“https://api.telegram.org/bot{token}/sendMessage“ requests.post(url, data={“chat_id”: chat_id, “text”: text})
send_telegram(TOKEN, CHAT_ID, “Scan 13:30: 12 gappers, top pick NVDA +4.2%”)
The bot sends the scan list every 30 minutes, entry and exit signals, partials, trailing stops, and an end-of-day summary. In the feed it looks roughly like this:
09:30 Pre-market scan: top 20 gappers ready 10:00 BUY NVDA 500 @ 20.05 stop 19.80 risk 1R 11:30 NVDA partial +0.75R booked, stop to break even 15:55 Force close: NVDA +1.8R | Day: +2.3R, 3 trades
Part 11. The dashboard and the honest scoreboard
Ask Claude to build a dashboard that tracks R for each trade, meaning the result in units of risk rather than raw dollars. That way wins and losses are measured against what was risked.
And here is the honest bit: a strategy that shines in a backtest can land as thoroughly mediocre once it trades live. Two reasons explain most of the gap:
-
The backtest was narrow, run on a limited set of tickers over a limited window.
-
Discretionary judgment is hard to fully encode, since not every manual decision maps cleanly onto indicators and fixed parameters.
The takeaway is not discouraging, just realistic. Backtest numbers rarely transfer one to one, and skilled manual trading of the same setup can still beat the automated version. Treat this build as a strong foundation to iterate on, not a finished money machine.
Part 12. Common problems and how to fix them
Almost every early stumble is one of the points below.
-
Will not connect, Connection refused: TWS not running, wrong port, IP not trusted, or API off. Check TWS is open, port 7497 for paper, 127.0.0.1 in Trusted IPs, ActiveX and Socket Clients on.
-
Orders rejected, read-only: Read-Only API is checked. Uncheck it and click Apply.
-
Empty scanner, no prices: no market data subscription. Enable delayed data or subscribe to market data.
-
Bot goes silent at night: TWS logs out and restarts once a day. Turn on TWS auto-restart and keep the computer on in market hours.
-
Order will not fill: the limit price is far from market, which is normal for a test. Use a realistic price for a real trade.
-
Account mix-up: paper and live ports swapped. 7497 is paper, 7496 is live.
-
No Telegram messages: wrong token or chat_id, or the bot was never messaged first. Verify token and chat_id, and send the bot a message by hand.
Part 13. Cheat sheet
-
Install: TWS, Python 3.12 or newer, paid Claude Code, open a paper account.
-
Configure the API: ActiveX and Socket Clients on, port 7497 or 7496, IP 127.0.0.1, Read-Only off.
-
Connect and test: prompt to connect, check buying power and a one-share order.
-
Write the rules: rules.json plus a settings file with tokens.
-
Build the scanner: ticker universe plus the gap-up filter.
-
Automate: start the 30-minute brain cycle, enable TWS auto-restart.
-
Wire alerts: bot in BotFather, token and chat_id, test message.
-
Monitor: the R dashboard and honest stats.
Disclaimer
-
AI multiplies an edge, it cannot create one.
-
Paper trade for weeks before risking a single dollar.
-
Set a realistic demo balance so the results tell the truth.
-
A pretty backtest is a hypothesis, not a promise of live profit.
-
This is educational material, not individual investment advice; trading carries the risk of losing capital.
One last thing
An automated bot is not the finish line, it is the starting block. The interesting work begins right after: tuning the filters, reading the honest R stats, and testing new timeframes and stock universes until live results start to catch up with the backtest.
Don’t forget to subscribe to my tg channel, more setups, prompts and breakdowns there: https://t.me/shmidtai
Build the bot, run it on paper.
If you liked this article, don’t forget to save it and follow me.
@shmidtqq
Similar Articles
@leopardracer: https://x.com/leopardracer/status/2058949350315667829
This guide explains how finance professionals can set up Claude Code, an AI coding assistant, to perform investment research tasks.
@DamiDefi: https://x.com/DamiDefi/status/2058137074595750242
The author builds a stripped-down three-agent version of a 50-agent AI portfolio system described in a BlackRock paper, using Claude. The system produces a surprising regime analysis and adversarial critique that leads to a real portfolio adjustment.
@RohOnChain: https://x.com/RohOnChain/status/2069056530960490835
The author explains how to build a self-improving quant trading system using AI loop engineering, where the AI runs loops to prompt, verify, and act autonomously, contrasting with manual prompting.
@tom_doerr: Generates and rigorously validates algorithmic trading strategies using Claude https://github.com/zostaff/ai-quant-rese…
ai-quant-lab is an open-source Python framework that uses Claude to generate algorithmic trading strategies and rigorously validates them with statistical tests to avoid overfitting.
@shmidtqq: https://x.com/shmidtqq/status/2072334081128358188
A detailed guide explaining three underrated methods to make money using Claude AI: selling custom travel plans on Etsy, driving traffic via Pinterest, and building an email list. The system is illustrated with the travel niche and includes prompts and business strategies.