Home › Guides › Trading bots & code
How to build a trading bot: from rules to running code
A trading bot is a written rule that a computer follows. The code is the easy part. The rule, the testing and the safety switches are the real work — here's the whole path, in order.
Start with a sentence, not code
Every bot starts the same way. Not with Python. With a sentence.
"When price closes above the last place it turned down, buy. Put the stop below the last place it turned up. Risk 1% of the account."
If you can't write the rule in one or two plain sentences, a computer can't follow it either. Code only makes a vague rule fail faster.
What a bot actually is
A bot is a loop. Every few seconds or minutes, it does the same 5 jobs:
- Get the latest prices.
- Check the rule.
- Work out the size from the stop.
- Place the order (or do nothing).
- Write down what it did.
That's it. A bot doesn't "know" the market. It follows your rule exactly, including the parts of your rule that are wrong.
Step 1: Write the rules down, fully
A rule a human can follow often has gaps a computer can't fill. Answer each of these in writing:
- Market and chart: which market, which Timeframe (candle size)?
- Entry: what exact event triggers a trade? "Looks strong" is not a rule. "A candle body closes above X" is.
- Stop: where does the exit go if you're wrong? Set it from the chart, not from a dollar amount you'd like to lose.
- Target or exit: a fixed Take profit, a trailing exit, or a time limit?
- Size: how much of the account is at risk on one trade? Many beginners use about 1%.
- Daily limit: after how many losses, or how much loss, does the bot stop for the day?
- When not to trade: news times, the first minutes of the session, weekends.
Our pre-trade checklist and trading plan guide are good templates. A bot rule is a trading plan with no wiggle room.
Step 2: Pick where the bot will run
Where you trade decides the language. You don't pick a language first.
| If you trade on… | You'll likely use | Read next |
|---|---|---|
| TradingView charts | Pine Script (alerts, tests) | Pine Script vs Python |
| MetaTrader 5 (many forex brokers) | MQL5 | MQL5 for beginners |
| A stock broker with an API | Python | Alpaca API basics |
| Interactive Brokers | Python (or Java, C++, C#) | IBKR API basics |
| Crypto exchanges | Python with ccxt | CCXT bot guide |
An API (application programming interface) is simply a door a broker opens so programs can read prices and send orders.
Step 3: Get clean price data
Your bot needs candles: time, open, high, low, close and volume. Brokers and exchanges give this through their API. You can also export it from your charting platform.
Two checks before you trust any data:
- Gaps: missing candles make indicators wrong.
- Time zone: know whether times are in your zone, the exchange's, or UTC.
Step 4: Test it on the past
A Backtesting run replays old prices and asks: "If the bot had followed this rule, what would have happened?" See how to backtest in Python.
Two traps make old results look better than they were:
- Look-ahead bias: the test uses information the bot couldn't have had yet. Example: deciding on a candle using its close, but buying at that same candle's open.
- Overfitting: tweaking settings until the past looks perfect. It fits old noise, not a real pattern. Test on a second chunk of data you never tuned on.
Count costs too: commissions, Spread and Slippage (getting a worse price than you asked for).
Step 5: Build the skeleton
Here's the shape of a bot loop in Python. It's a skeleton: broker stands for your broker connection and find_setup is your written rule turned into code. The other pages in this section fill those in.
Example code for learning — test it on paper first; it is not a ready-made trading system.
import logging, time
logging.basicConfig(filename="bot.log", level=logging.INFO, format="%(asctime)s %(message)s")
RISK_PCT = 1.0 # risk per trade, % of account
MAX_DAILY_LOSS_PCT = 2.0 # stop for the day after this
def position_size(equity, entry, stop):
risk_money = equity * RISK_PCT / 100
per_share = abs(entry - stop)
return int(risk_money // per_share) if per_share > 0 else 0
def run_once(broker, start_equity):
equity = broker.equity()
if equity <= start_equity * (1 - MAX_DAILY_LOSS_PCT / 100):
logging.info("Daily loss limit hit. No new trades.")
return
candles = broker.candles("SPY", "15m", 100)
setup = find_setup(candles) # your rule; returns None or entry/stop/target
if setup is None:
return
qty = position_size(equity, setup["entry"], setup["stop"])
if qty < 1:
logging.info("Stop too wide for the risk limit. Skipped.")
return
order = broker.bracket_order("SPY", qty, setup["entry"], setup["stop"], setup["target"])
logging.info("ORDER %s qty=%s %s", order, qty, setup)
def main(broker):
start_equity = broker.equity() # reset this each new trading day
while True:
try:
run_once(broker, start_equity)
except Exception:
logging.exception("Error. Pausing 5 minutes.")
time.sleep(300)
time.sleep(60)
What each part does, in plain words:
- RISK_PCT and MAX_DAILY_LOSS_PCT are your two most important rules, set at the top where you can see them.
- position_size turns the stop distance into a share count, so a wide stop means a smaller trade. Same idea as our position size calculator.
- run_once checks the daily limit first, then the rule, then the size, then sends one bracket order (entry, stop and target together).
- The try / except catches errors so one bad response doesn't crash the bot mid-trade. It logs the error and waits.
- Every decision is logged, including the trades it skipped. The log is how you find bugs.
Step 6: Add the safety switches
These aren't extras. A bot without them isn't finished.
- Size from the stop, never a fixed number of shares.
- A daily loss limit and a kill switch you can flip by hand (a file, a setting, a button).
- Order checks: after sending, confirm the order exists. After a disconnect, check open positions before doing anything new.
- Limits on the obvious: a maximum order size and a maximum number of trades per day, so a bug can't fire 500 orders.
- API keys in environment variables, never in the code, with withdrawals turned off. See API key security for trading bots.
More detail: trading bot risk controls.
Step 7: Paper trade, then go small
Run the bot with fake money for weeks. Paper trading shows the things a backtest can't: missed fills, slow responses, a server that restarts at 3 am. See paper trading a bot.
Compare its paper trades with what your rule should have done. When they match, and you've seen losing streaks, consider real money at the smallest size your broker allows. Losses are still possible at any size.
A bot doesn't remove risk. It repeats your rule. If the rule is good, the bot is consistent. If the rule has a hole, the bot finds it again and again, faster than you would.
Common mistakes
- Coding before the rule is written. You end up coding guesses.
- Trusting one great backtest. See the common trading bot mistakes.
- No stop because "the bot watches it". Bots crash. Servers lose internet. Put the stop at the broker.
- Buying a "proven" bot. If it worked as sold, it wouldn't be for sale. Read AI trading bots explained.
Try it today: write your rule in 2 sentences. Then hand it to a friend and ask them to mark the trades on a past chart. Every question they ask is a gap your code would hit.
Questions
Can a beginner build a trading bot?
Yes. A simple bot is a short loop: get prices, check a rule, size the trade, place an order, log it. The hard part is a clear rule and honest testing, not the code.
What do I need to build a trading bot?
A written rule, a broker or exchange with an API, price data, a language that platform supports (often Python), a way to backtest, and a paper trading account to test it live without real money.
How long does it take to build a trading bot?
A first working version on paper can take a few days to a few weeks. Testing it properly — on past data and then on paper through different market conditions — takes longer, and that's the part not to rush.
Do trading bots actually work?
A bot works in the sense that it follows rules; it doesn't create an edge. Many bots lose money, especially after costs. Treat any bot, including your own, as unproven until it has been tested on past data and on paper.
Is it legal to use a trading bot?
In the US, automated trading is generally allowed on your own account if your broker permits API trading. Check your broker's terms; some limit how many orders you can send.
Want the next step? We'll walk you through it.
Four free lessons by email, one every few days — each with a 10-minute exercise on a real chart.
Send Me the Free Lessons 4 short emails · No spam · Unsubscribe anytimeOr see the whole method, step by step:
See What’s Inside the Course Try everything free first. Decide when you're ready. · Open the free chart tool (works in the TradingView phone app)One chart idea a day, in plain English. Follow along: