StructureX

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.

Beginner guide · 9-minute read · Updated 2026-10-21

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:

  1. Get the latest prices.
  2. Check the rule.
  3. Work out the size from the stop.
  4. Place the order (or do nothing).
  5. 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:

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 useRead next
TradingView chartsPine Script (alerts, tests)Pine Script vs Python
MetaTrader 5 (many forex brokers)MQL5MQL5 for beginners
A stock broker with an APIPythonAlpaca API basics
Interactive BrokersPython (or Java, C++, C#)IBKR API basics
Crypto exchangesPython with ccxtCCXT 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:

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:

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:

Step 6: Add the safety switches

These aren't extras. A bot without them isn't finished.

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

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 anytime

Or 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:

Follow on XFollow on TradingView