Tutorials Get the App

Home · Learn · Build a trading bot in Python

How to Build a Trading Bot in Python (With Tested Code)

Updated November 22, 2026 · By Moby

A Python trading bot is a loop that reads prices, applies rules, sizes the trade, sends an order and logs the result. The professional part is not the signal; it is fees, risk caps, testing and monitoring. Start with a backtest that includes fees, then paper trade, then go live small.

What a professional trading bot needs

A Python trading bot is a loop. It reads prices, applies a rule, sizes the trade, sends an order and writes down what happened. The professional part is not the signal. It is the five pieces around the signal: data you can trust, a rule you can read, a risk check that can say no, an execution path that does not double orders, and a log you actually open.

Add four habits before any of that touches money. Keep settings in a config file, not buried in the loop. Keep secrets in environment variables, never in the script. Write a test that runs without a network. Make each order idempotent, so a retry does not buy twice, and cap the retries. A loop that retries forever is a machine for doubling size.

Step 1: a backtest with fees

The script below is a moving average crossover on a CSV of dates and closes. It buys a fixed dollar size when the short average crosses above the long one, and it sells on the cross back down. The fee settings mirror Moby's fee as an example. A 0.75% swap fee (minimum $0.90 per swap), plus onchain fees. Set both numbers to your own venue. There is no exchange key and no live order in this file.

"""Moving-average crossover backtest with fees. Educational only, not advice.
Reads a CSV with columns: date,close (oldest first). No exchange keys, no live orders."""
import csv
import sys

FAST, SLOW = 10, 30            # moving-average lengths (bars)
START_CASH = 1000.0            # starting balance in USD
TRADE_SIZE = 100.0             # USD per buy (your per-trade cap)
FEE_PCT = 0.0075               # 0.75% fee per trade, set to your venue's fee
FEE_MIN = 0.90                 # minimum fee per trade in USD, set to your venue's minimum


def fee(notional):
    return max(notional * FEE_PCT, FEE_MIN)


def sma(values, n):
    return sum(values[-n:]) / n if len(values) >= n else None


def run(path):
    closes, cash, qty, trades = [], START_CASH, 0.0, []
    with open(path) as f:
        for row in csv.DictReader(f):
            price = float(row["close"])
            prev_fast, prev_slow = sma(closes, FAST), sma(closes, SLOW)
            closes.append(price)
            fast, slow = sma(closes, FAST), sma(closes, SLOW)
            if None in (prev_fast, prev_slow, fast, slow):
                continue
            crossed_up = prev_fast <= prev_slow and fast > slow
            crossed_down = prev_fast >= prev_slow and fast < slow
            if crossed_up and qty == 0 and cash >= TRADE_SIZE:
                f_ = fee(TRADE_SIZE)
                qty = (TRADE_SIZE - f_) / price
                cash -= TRADE_SIZE
                trades.append((row["date"], "BUY", price, round(f_, 2)))
            elif crossed_down and qty > 0:
                proceeds = qty * price
                f_ = fee(proceeds)
                cash += proceeds - f_
                qty = 0.0
                trades.append((row["date"], "SELL", price, round(f_, 2)))
    equity = cash + qty * closes[-1]
    fees_paid = sum(t[3] for t in trades)
    for t in trades:
        print(*t, sep=",")
    print(f"trades={len(trades)} fees_paid={fees_paid:.2f} final_equity={equity:.2f} "
          f"buy_and_hold={START_CASH / closes[0] * closes[-1]:.2f}")


if __name__ == "__main__":
    run(sys.argv[1] if len(sys.argv) > 1 else "prices.csv")

The generator below writes the 200 rows the worked example uses. Same seed, same series, or your numbers will not match the table.

import random, math, datetime
random.seed(7); p = 100.0; d = datetime.date(2026, 1, 1)
with open("prices.csv", "w") as f:
    f.write("date,close\n")
    for i in range(200):
        p *= math.exp(random.gauss(0.0005, 0.03))
        f.write(f"{d + datetime.timedelta(days=i)},{p:.4f}\n")

Worked example: what the script printed

Synthetic random walk prices from the seeded generator above, not market data. Example, not a recommendation. The run on November 22, 2026, with Python 3, printed seven trades. The last buy is still open, which is why the row count and the summary both say seven.

DateSidePriceFee
2026-02-05BUY102.10890.90
2026-02-16SELL93.86340.90
2026-03-04BUY95.59430.90
2026-03-08SELL91.64040.90
2026-03-31BUY93.39540.90
2026-06-13SELL114.65850.91
2026-07-05BUY124.45470.90

Summary line: trades=7, fees_paid=6.31, final_equity=999.21, buy_and_hold=1191.08. Three lessons sit in that line. On $100 trades the $0.90 minimum is almost 1% per side, so seven trades cost $6.31. The rule ended slightly below its $1,000 start while simply holding the series ended at $1,191, so a rule that sounds smart can lose to doing nothing. One random series proves nothing. Test many seeds and real data, and expect worse live results. The fee constants mirror the fee line on this site as an example. Readers should set their own venue's fees. A longer tour of the traps is on backtesting with AI, and a small in browser version is the backtest demo.

Step 2: add risk caps

The backtest above will buy whenever the cross happens and cash is there. A live loop needs a function that can refuse. The block below is 15 lines. It checks a per trade cap, a daily spend, a max number of open positions, and a kill switch file. If a file named KILL exists in the working directory, every buy returns kill_switch. Delete the file and the loop may buy again. Run on November 22, 2026, the cases printed: a $100 buy with nothing spent is ok; a second $100 the same day is ok because 200 is not over the cap; $150 already spent plus $100 returns daily_spend; one open position returns max_open; a $250 buy returns max_trade; the same $100 buy after the file is created returns kill_switch.

import os

MAX_TRADE = 100.0
DAILY_SPEND = 200.0
MAX_OPEN = 1
KILL = "KILL"

def allow(day_spent, open_n, notional):
    if os.path.exists(KILL):
        return "kill_switch"
    if notional > MAX_TRADE:
        return "max_trade"
    if day_spent + notional > DAILY_SPEND:
        return "daily_spend"
    if open_n >= MAX_OPEN:
        return "max_open"
    return "ok"

Step 3: paper trade before real money

Keep the same code and change the fill. Instead of sending an order, record a fill at the next bar's price and log every decision, including the ones the risk function refused. A paper fill is kinder than a live fill. That is the point of doing it first, and the reason you should not trust it as the last test. The log is the product of this step. If you cannot explain a line in the log, you are not ready to connect a key.

Step 4: connect to an exchange

ccxt is an open source library, MIT license, checked on GitHub November 22, 2026, that wraps many exchange APIs. Use API keys with withdrawals disabled. Store the keys in environment variables. The snippet on this page is read only on purpose: it shows where a key would be read, and it does not place an order.

A ccxt example

import os
import ccxt
exchange = ccxt.binance({"apiKey": os.environ["EXCHANGE_KEY"], "secret": os.environ["EXCHANGE_SECRET"]})
print(exchange.fetch_ticker("BTC/USDT")["last"])

If that import fails, you have not installed the library. If the call fails, you do not have a working key. Neither failure is a reason to paste a withdrawal enabled key into the file to "just test."

Step 5: run and monitor it

A laptop that sleeps will miss the exit. If the loop must stay up, it needs a machine that stays up, plus an alert when the process dies, a daily log of profit and loss, and a stop when errors repeat. The kill switch file from step 2 is the manual version of that stop. Look at the log every day you claim the bot is running. A bot you do not look at is a bot you have already abandoned.

What usually goes wrong

Five failures show up more often than a bad indicator. Overfitting, because the rule was tuned on the only data you had. Ignoring fees, because the backtest used zero and the live venue did not. Look ahead bias, because the signal used the close of the bar it then traded. No position cap, because the loop bought again on every retry. Retry loops that double orders, because a timeout was treated as "it did not happen" when it had. The script on this page avoids the last one by never sending an order at all. Live code has to be more careful than that, not less.

The wider build guide, with no-code and agent routes, is how to build a trading bot. Run your own fee math on the trading fee calculator. Rule bots that are not agents are on crypto trading bot, the agent comparison is AI trading bot, written plans are on agent strategies, and the difference between MCP and an exchange API is on MCP vs API.

Or skip the code: use an AI agent

You can describe rules in plain words and let an agent trade inside limits you set. One agent per user, with its own wallet. Agents trade Solana tokens only. The agent cannot withdraw, transfer or send funds. You set your agent's per-trade and daily spending limits and market-cap range; Moby blocks red-rated tokens. Limits are only as tight as you set them. Sells and exits skip the market-cap and safety checks, and tokens with no safety rating are not blocked. Supported hosts: Codex, Claude Code (CLI), Gemini CLI (with a paid Gemini API key or enterprise access) and Grok CLI. ChatGPT: works on Business, Enterprise and Edu workspaces that allow custom MCP servers (web). The credential is a Moby agent key. Rate limits protect against runaway loops and scale with the fees your agent pays; you set the spend limits. A 0.75% swap fee (minimum $0.90 per swap), plus onchain fees. Limit, take-profit, stop-loss and trailing orders carry the same flat 0.75% Moby fee as swaps, charged when the order fills. AI Trading and copy trading currently need an access pass in the app. The install is how to set up agentic trading. A Solana specific build is build a Solana trading agent. This path still needs the risk habits above. It only skips the part where you maintain the loop.

Build a copy trading bot in Python

People also search for a Python copy bot. The shape is short, and this page will not hand you a full script for it. Read a followed wallet's trades from a public data source. Apply your own size and market cap rules. Place your own trade. Log the skips as carefully as the fills. Do not assume a public feed is complete, and do not assume a copied buy is a good buy.

Moby does not offer a copy API. In the Moby app, copy trading follows a wallet you already follow on Solana. 2% ($1 minimum) on copy buys. The product explanation is on copy trading. A Python loop you host is a different system, with your keys and your uptime. If you build that loop, the risk caps from step 2 still apply, and withdrawals on any exchange key stay off.

Frequently asked questions

Can I build a trading bot in Python with no experience?

You can run the script on this page, because it is ordinary Python and a CSV. Building one you would fund is a different job. You need to read the log, change the fee numbers, and explain why a buy was refused. Start there before you add an exchange.

What Python libraries do trading bots use?

The standard library csv module is enough for the backtest on this page. pandas is common for larger files. ccxt, an MIT licensed project checked on GitHub November 22, 2026, wraps many exchange APIs. This page does not endorse a vendor.

How do I backtest a trading bot in Python?

Put prices in a CSV, oldest first, and run a loop that only uses the rows it has already seen. Charge a fee on every fill, including a minimum if your venue has one. Print the trades. If the output surprises you, the rule is not ready.

Why does my bot make money in a backtest but lose live?

The usual reasons are overfitting, missing fees, slippage, and look ahead bias. A backtest that fills at the signal price, with no spread, is a kinder world than a live book. Add costs and a delay before you believe the curve.

Is it safe to give a Python bot my exchange API keys?

Only with withdrawals disabled, an IP allowlist if the exchange offers one, and the secret in an environment variable. A key that can withdraw is a key that can empty the account if the file leaks. Read only first.

Can a Python bot trade on Solana?

Yes. solders, checked on GitHub November 22, 2026, is one Python library for Solana types. You can also skip the chain code and use an agent. One agent per user, with its own wallet. Agents trade Solana tokens only.

Do I need to code to automate trading?

No. An AI agent can follow plain language rules within limits you set. You set your agent's per-trade and daily spending limits and market-cap range; Moby blocks red-rated tokens. The code on this page is for people who want the loop in their own hands.