# Python Trading Bot Tutorial: Build and Test It Offline

URL: https://fincodelabs.com/en/blog/python-trading-bot-tutorial · Publisher: Fincode (Fincode Yazılım ve Teknoloji A.Ş.), Istanbul, Turkey · Category: Trading bots · Published: 2026-11-26 · Updated: 2026-11-26

Python trading bot tutorial that runs offline: synthetic data, risk limits outside the rule, a mock exchange, idempotent order IDs and tests that pass.

**Short answer:** This **Python trading bot tutorial** builds a bot that runs with no account, keys or money: synthetic prices, a placeholder rule, risk limits outside the rule, a mock exchange, idempotent order IDs and a JSON log. All of it ran on 26 November 2026 in a Python 3.11.3 virtual environment with the standard library only. The rule is deliberately not a strategy, and nothing here suggests a bot makes money.

Connecting to a live account is the last step here. Bad price rows, a lost order reply, a restart and a missed limit are handled and tested before any network call exists, and no exchange, broker or data vendor is used.

## How to make a trading bot with Python: six parts

A trading bot is six small parts with one job each, and keeping them apart is what makes the bot testable.

**Bot parts**

| Part | Job | Here |
| --- | --- | --- |
| Data loader | Reads prices, rejects bad rows | `load_candles()` on a synthetic CSV |
| Rule | Says BUY, SELL or nothing | `placeholder_rule()` |
| Risk limits | Can veto any order | `RiskLimits.check()`: kill file, order count, notional, position |
| Order client | Sends orders, survives lost replies | Retry loop that reuses one client order ID |
| Venue | Accepts and fills orders | `MockExchange`, in memory |
| Log | Records every decision | JSON lines in `bot.jsonl` |

The rule never calls the venue; every order passes `RiskLimits.check()` first. Prices are `Decimal`, not `float`: `float("1e400")` silently becomes infinity, and binary floats cannot hold most decimal prices exactly. `Decimal` still accepts `inf` and `nan`, so the loader also checks `is_finite()`.

## The complete Python trading bot, standard library only

This file is the whole bot; it ran on Python 3.11.3 in a fresh virtual environment, nothing from pip.

Save it as `bot.py` in an empty folder, run `python -m venv .venv`, activate it (`.venv\Scripts\activate` on Windows, `source .venv/bin/activate` elsewhere) and run `python bot.py`.

```python
"""Offline trading bot: synthetic data, mock exchange, no keys. The rule is not a strategy."""
import csv, json, random
from collections import Counter
from decimal import Decimal, InvalidOperation
from pathlib import Path

class DataError(ValueError): pass
class Timeout(Exception): pass

def make_synthetic_csv(path, n=40, seed=7):
    rng, price = random.Random(seed), Decimal("100")
    with open(path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["ts", "close"])
        for i in range(n):
            price = max(Decimal("1"), price + Decimal(rng.randint(-150, 150)) / 100)
            w.writerow([1_700_000_000 + 60 * i, price])

def load_candles(path):
    rows, last_ts = [], None
    with open(path, newline="") as f:
        for n, row in enumerate(csv.DictReader(f), start=2):
            try:
                ts, close = int(row["ts"]), Decimal(row["close"])
            except (KeyError, TypeError, ValueError, InvalidOperation) as e:
                raise DataError(f"line {n}: unreadable row {repr(row)}") from e
            if not close.is_finite() or close <= 0:
                raise DataError(f"line {n}: bad price {repr(row['close'])}")
            if last_ts is not None and ts <= last_ts:
                raise DataError(f"line {n}: timestamp {ts} not after {last_ts}")
            rows.append((ts, close))
            last_ts = ts
    if not rows:
        raise DataError("no rows")
    return rows

def placeholder_rule(i, close):     # replace with your own rule; this only cycles
    return {0: "BUY", 1: "BUY", 3: "SELL"}.get(i % 5)

class RiskLimits:
    def __init__(self, max_position, max_notional, max_orders, kill_file):
        self.max_position, self.max_notional = max_position, max_notional
        self.max_orders, self.kill_file = max_orders, Path(kill_file)

    def check(self, side, qty, price, position, orders_sent):
        if self.kill_file.exists():
            return "kill switch file present"
        if orders_sent >= self.max_orders:
            return "order count limit"
        if qty * price > self.max_notional:
            return "notional limit"
        new = position + qty if side == "BUY" else position - qty
        if not 0 <= new <= self.max_position:
            return "position limit"
        return None

class MockExchange:                 # fills at the given price: no fees, slippage, book
    def __init__(self, drop_reply_for=()):
        self.orders, self.drop = {}, set(drop_reply_for)

    def place(self, client_id, side, qty, price):
        if not client_id:
            return {"status": "rejected", "reason": "empty client order id"}
        if client_id in self.orders:        # same ID again: return the first order
            return self.orders[client_id]
        order = {"status": "filled", "id": len(self.orders) + 1, "client_id": client_id,
                 "side": side, "qty": str(qty), "price": str(price)}
        self.orders[client_id] = order
        if client_id in self.drop:          # accepted, but the reply is lost
            self.drop.discard(client_id)
            raise Timeout(client_id)
        return order

def client_order_id(run_id, ts, side):
    return f"{run_id}-{ts}-{side}"          # a restart rebuilds the same ID

def run(csv_path, exchange, limits, run_id="demo1", qty=Decimal("1"), log_path="bot.jsonl"):
    position, sent = Decimal("0"), 0
    with open(log_path, "w") as log:
        def event(**e):
            log.write(json.dumps(e, default=str) + "\n")
        for i, (ts, close) in enumerate(load_candles(csv_path)):
            side = placeholder_rule(i, close)
            if side is None:
                continue
            reason = limits.check(side, qty, close, position, sent)
            if reason:
                event(ts=ts, event="blocked", side=side, reason=reason)
                continue
            cid = client_order_id(run_id, ts, side)
            for attempt in (1, 2, 3):
                try:
                    reply = exchange.place(cid, side, qty, close)
                    break
                except Timeout:
                    event(ts=ts, event="timeout_retry_same_id", cid=cid, attempt=attempt)
            else:
                event(ts=ts, event="stopped_state_unknown", cid=cid)
                break
            sent += 1
            if reply.get("status") == "filled":
                position += qty if side == "BUY" else -qty
                event(ts=ts, event="filled", cid=cid, side=side, price=close, position=position)
            else:
                event(ts=ts, event="rejected", cid=cid, reason=reply.get("reason", "unknown"))
    return position, sent

if __name__ == "__main__":
    make_synthetic_csv("candles.csv")
    ex = MockExchange(drop_reply_for={"demo1-1700000000-BUY"})
    limits = RiskLimits(Decimal("2"), Decimal("150"), max_orders=8, kill_file="STOP")
    position, sent = run("candles.csv", ex, limits)
    with open("bot.jsonl") as f:
        events = Counter(json.loads(line)["event"] for line in f)
    print(f"orders at exchange: {len(ex.orders)}, accepted calls: {sent}, position: {position}")
    print(dict(events))
```

> **Output, run on 26 November 2026** (Windows 11, Python 3.11.3, synthetic data):
>
> ```
> orders at exchange: 8, accepted calls: 8, position: 2
> {'timeout_retry_same_id': 1, 'filled': 8, 'blocked': 16}
> ```
>
> The seeded generator writes the same 40 one-minute rows every run. The mock dropped the reply to the first BUY on purpose; the bot retried with the same ID, and the venue holds 8 orders, not 9. Of 16 blocked orders, 2 hit the 2-unit position limit and 14 the 8-order limit. This describes plumbing, not a trading result.

Each line of `bot.jsonl` is one decision. A file named `STOP` in the folder blocks every later order.

## Why order IDs matter more than the rule

A timeout does not tell you whether the order was placed, so a retry must reuse an ID that makes a second copy impossible.

`client_order_id()` builds the ID from run name, bar timestamp and side, so a restart rebuilds the same ID. Running `run()` twice against one mock left 8 orders, not 16.

- **Same ID, same order.** The mock returns the first order when an ID repeats; real venues document their own rules, see [the client order ID guide](https://fincodelabs.com/en/blog/client-order-id).
- **Empty ID is an error**, not a duplicate of an earlier empty ID.
- **Unknown state stops the bot.** After three lost replies it logs `stopped_state_unknown` and exits.

A real bot then asks the venue what happened before trading again. That reconciliation step is what [Fincode's order gateway reference](https://fincodelabs.com/en/reference/order-gateway) shows: an MIT-licensed teaching example with a SQLite journal, also standard library only. Real retries also need spacing; see [exponential backoff with jitter](https://fincodelabs.com/en/blog/exponential-backoff-jitter-python). This skeleton tracks position from replies; a live bot should read positions back from the venue.

## Tests for the failures that cost money

Six `unittest` cases cover bad data, lost replies, empty IDs, the kill switch and error bodies.

Save this as `test_bot.py` next to `bot.py` and run `python -m unittest -v`.

```python
import tempfile, unittest
from decimal import Decimal as D
from pathlib import Path
from bot import DataError, MockExchange, RiskLimits, Timeout, load_candles, run

def tmp(name, text=None):
    p = Path(tempfile.mkdtemp()) / name
    if text is not None:
        p.write_text(text)
    return p

def limits(kill=None):
    return RiskLimits(D(2), D(1000), 10, kill or tmp("STOP"))

TWO_ROWS = "ts,close\n1,10\n2,11\n"

class BotTests(unittest.TestCase):
    def test_bad_rows_rejected(self):
        self.assertEqual(float("1e400"), float("inf"))   # why prices are Decimal
        for text in ("1,inf", "1,nan", "1,-1", "1,0", "1,", "1,abc", "1,10\n1,11"):
            with self.subTest(text=text), self.assertRaises(DataError):
                load_candles(tmp("c.csv", "ts,close\n" + text + "\n"))

    def test_lost_reply_retry_makes_one_order(self):
        ex = MockExchange(drop_reply_for={"a"})
        with self.assertRaises(Timeout):
            ex.place("a", "BUY", D(1), D(10))
        self.assertEqual(ex.place("a", "BUY", D(1), D(10))["id"], 1)
        self.assertEqual(len(ex.orders), 1)

    def test_empty_id_rejected_not_treated_as_duplicate(self):
        ex = MockExchange()
        for _ in range(2):
            self.assertEqual(ex.place("", "BUY", D(1), D(10))["status"], "rejected")
        self.assertEqual(ex.orders, {})

    def test_kill_switch_blocks(self):
        lim = limits(tmp("STOP", ""))
        self.assertEqual(lim.check("BUY", D(1), D(10), D(0), 0), "kill switch file present")

    def test_error_body_without_reason_does_not_crash(self):
        class Rejecting:
            def place(self, *args):
                return {"status": "rejected"}
        result = run(tmp("c.csv", TWO_ROWS), Rejecting(), limits(), log_path=tmp("log"))
        self.assertEqual(result, (D(0), 2))

    def test_three_lost_replies_stop_the_bot(self):
        class Silent:
            def place(self, *args):
                raise Timeout()
        log = tmp("log.jsonl")
        run(tmp("c.csv", TWO_ROWS), Silent(), limits(), log_path=log)
        self.assertIn("stopped_state_unknown", log.read_text())
```

> **Result on 26 November 2026:** `Ran 6 tests in 0.066s`, `OK` (timing varies by machine). With three bugs put back on purpose (no `is_finite()` check, no empty-ID check, `reply["reason"]`), four checks failed.

A price of `1e400` is a finite `Decimal`, so the loader accepts it; the notional limit blocked that order when tried, which is why limits sit outside the rule. Reading `reply["reason"]` raises `KeyError` on a reply without that field and hides the original error. For a fuller plan, see [how to test trading bots](https://fincodelabs.com/en/blog/how-to-test-trading-bots); for the stop file, see [the kill switch guide](https://fincodelabs.com/en/blog/trading-bot-kill-switch).

## Should you use a framework like Freqtrade instead?

Use a framework when its venues, license and Python version fit your project; a small skeleton first shows what it handles for you.

**Four Python trading projects, read on GitHub on 26 November 2026**

| Project | License | Latest GitHub release | Venues, as the project states them | Python |
| --- | --- | --- | --- | --- |
| Freqtrade | GPL-3.0 | 2026.10, 30 October 2026 | Crypto exchanges listed in its README, with exchange-specific notes in its docs | 3.12 or newer, per README |
| Hummingbot | Apache-2.0 | v2.18.0, 18 November 2026 | Centralized and decentralized exchanges through three connector types | Not checked |
| NautilusTrader | LGPL-3.0 | v1.231.0, 2 August 2026; v2.0.0 release candidates are tagged | Adapters for crypto exchanges, traditional markets and betting exchanges | Stable 1.231.0 on PyPI: 3.12 to 3.14; README and v2 candidates: 3.13 to 3.15 |
| Backtrader | GPL-3.0 | None published; last commit on master 19 April 2023 | Backtesting, plus three live broker or data integrations in its README | Not checked |

The 3.11.3 environment used above meets neither Freqtrade's nor NautilusTrader's stated Python requirement. Freqtrade's README says it is for educational purposes. GPL-3.0 sets conditions on distributing modified copies; ask a lawyer before shipping one to a client. This is not a ranking, and none was installed for this page. The guides to [Freqtrade](https://fincodelabs.com/en/blog/freqtrade-tutorial), [Hummingbot](https://fincodelabs.com/en/blog/hummingbot-tutorial) and [NautilusTrader](https://fincodelabs.com/en/blog/nautilus-trader-python) record what ran when each was tested.

## How to build a stock trading bot from this skeleton

Replace the loader and the mock with a data source and a broker's paper account; keep the rest.

1. **Data.** Swap the CSV for a feed from a [stock market data API](https://fincodelabs.com/en/blog/stock-market-data-api) and keep the row checks. Store timestamps in UTC and expect no rows outside trading hours or on holidays.
2. **Venue.** Point the order client at a [paper trading API](https://fincodelabs.com/en/blog/paper-trading-api) first. Account types, API access and rules differ by broker and country.
3. **Keys.** Load them from environment variables, never the source file; skip withdrawal rights where offered.
4. **Error order.** Check for authentication and permission errors before the generic network-error branch, so a revoked key stops the bot instead of being retried as a timeout.
5. **Lookups.** When you find an instrument or an order by symbol, require exactly one match; a loop that keeps the last match picks one silently.

## What this tutorial leaves out, and the risk that remains

It shows plumbing, not a way to make money: the placeholder rule has no market logic, and the mock fills every order at the CSV price.

With no fees, slippage, partial fills or order book, the output says nothing about market results. A rule that looks good on history can fail live for the reasons in [the backtesting pitfalls guide](https://fincodelabs.com/en/blog/backtesting-trading-strategy-pitfalls). Automated trading can lose money, from market moves and from software faults alike. The US Commodity Futures Trading Commission's advisory of 25 January 2024 calls promises of high or guaranteed bot returns red flags of fraud and reminds readers that AI cannot predict the future.

Fincode offers a paid [trading bot code review](https://fincodelabs.com/en/services/trading-bot-code-review) that checks these failure paths in existing bots.

## Frequently asked questions

### Can I build a trading bot in Python without an exchange account?

Yes. Everything here runs on synthetic data against an in-memory mock exchange. An account is needed only for a testnet, a paper account or live trading.

### Can I trade with the placeholder rule?

No. It cycles BUY, BUY, SELL by row number to exercise the code and has no market logic. Replace it with a rule you wrote and tested yourself.

### What is a client order ID in a trading bot?

An ID your bot chooses and sends with an order, so a retry after a timeout is recognized as the same order. Each venue documents how long it remembers IDs.

### Is it legal to run a trading bot?

It depends on your country, the asset and the terms of the exchange or broker. Read those terms before automating anything and take legal advice where unclear.

## Sources

- [Python documentation: decimal, decimal fixed-point and floating-point arithmetic](https://docs.python.org/3/library/decimal.html)
- [Python tutorial: floating-point arithmetic, issues and limitations](https://docs.python.org/3/tutorial/floatingpoint.html)
- [Python documentation: venv, creation of virtual environments](https://docs.python.org/3/library/venv.html)
- [Python documentation: unittest, unit testing framework](https://docs.python.org/3/library/unittest.html)
- [Python documentation: csv, CSV file reading and writing](https://docs.python.org/3/library/csv.html)
- [Freqtrade repository and README (GPL-3.0, Python 3.12+, disclaimer)](https://github.com/freqtrade/freqtrade)
- [Hummingbot repository and README (Apache-2.0, connector types)](https://github.com/hummingbot/hummingbot)
- [NautilusTrader repository and README (LGPL-3.0, integrations, Python versions)](https://github.com/nautechsystems/nautilus_trader)
- [PyPI: nautilus-trader releases and Python requirement (1.231.0: 3.12 to 3.14)](https://pypi.org/project/nautilus-trader/)
- [Backtrader repository and README (GPL-3.0, live integrations)](https://github.com/mementum/backtrader)
- [CFTC release 8854-24: customer advisory on AI trading bot scams, 25 January 2024](https://www.cftc.gov/PressRoom/PressReleases/8854-24)

> This guide is general information about software and markets, not investment, legal or tax advice. Automated trading can lose money, past or backtested performance does not guarantee future results, and the rules that apply depend on your jurisdiction and your exchange's terms. Sources, checks and corrections: see the [editorial policy](https://fincodelabs.com/en/editorial-policy).

---

Published by Fincode (Fincode Yazılım ve Teknoloji A.Ş.), a software company in Istanbul, Turkey: https://fincodelabs.com/en/blog/python-trading-bot-tutorial

Cite as: Fincode, "Python Trading Bot Tutorial: Build and Test It Offline", updated November 26, 2026, https://fincodelabs.com/en/blog/python-trading-bot-tutorial
