Bentley Markets Book a call
Free guide

How to build a crypto trading bot with Claude Code

Claude Code can write nearly all of a crypto trading bot for you. The hard parts are deciding what the bot should do, keeping it safe, and finding out honestly whether it works. This guide walks through the build in the order we would use if we started again, from an empty folder to a bot that paper trades around the clock and messages your phone.

By the Bentley Markets teamUpdated 10 min read

Education only. Everything here runs on paper or on an exchange demo account. Nothing in this guide is financial advice, and no bot is guaranteed to make money.

What you are building

A trading bot is a few small programs that each do one job. Built that way, every piece can be tested on its own, and Claude Code can work on one piece at a time without breaking the others.

  1. Data collectorFetches prices, funding and open interest on a schedule, saves them with timestamps and knows when they are stale.
  2. Plan writerTurns the data into trade plans: entry, stop, targets and what would cancel the idea. Rules, an AI read, or both.
  3. Risk gatesHard-coded checks every plan must pass, whatever the plan writer says.
  4. Paper traderFills approved plans against live prices, with fees and funding, and logs every result in R.
  5. Alerts and a status checkMessages your phone when something happens, and tells you when something breaks.

That is the shape of Bentley, the AI co-pilot we run every day: it reads the market, writes plans and knows when to sit out, and a trader makes the calls. Your first version can be much simpler.

What you need

Claude Code
On your computer, with a Claude plan. It writes the code; you review it.
A terminal
Mac or Linux is easiest. You will run commands and read what they print.
Python
The examples here use it. Claude Code can set it up for you.
A small server
Later on, a Linux VPS so the bot keeps running when your laptop sleeps.
An exchange
One with a public market data API and a demo or testnet account.
Your phone
Telegram is the simplest way to get alerts. Optional.
Time
A few evenings for a first version, then weeks of paper trading before you judge it.

Step 1: Write the brief before any code

Claude Code is fast, which makes it easy to build the wrong thing quickly. Start with a one-page brief in plain words: what the bot trades, what it looks at, what a plan must contain, how big each trade is, and what it is never allowed to do. That page is what you will point Claude Code at again and again.

BRIEF.md
# Trading bot brief

Goal: watch BTC and ETH perpetual futures, write a trade plan when the
rules line up, and paper trade that plan. It never places a real order.

Markets: BTC and ETH perpetuals. 4 hour chart for direction, 1 hour for entries.
Data: candles, funding rate and open interest every 5 minutes, public endpoints.
Entry rule: (one sentence, in plain words)
Every plan has: entry zone, stop, one or two targets, reward to risk,
  and what cancels the idea before entry.
Size: risk 1% of the paper account per trade, worked out from the stop.
Limits: at most 2 open trades. Stop for the day after losing 3% of the account.
Not allowed: real orders, withdrawal permissions, changing a limit without asking.
Done looks like: 30 paper trades logged with results in R, and every
  rejected plan logged with the reason.

Two lines matter more than they look. "Done looks like" gives the project an end you can check. "Not allowed" is where safety starts: a bot that can't place a real order can't lose real money while you learn.

No entry rule yet? Leave the gap and build the data collector first; staring at clean data is how most rules start. The free Bentley Academy lesson on writing a trade plan covers what every plan needs.

Step 2: Set up the project and give Claude Code its rules

Make a folder, start a git repository so every change can be undone, and add a file called CLAUDE.md. Claude Code reads it at the start of every session, so it is the place for the rules you never want to repeat.

CLAUDE.md
# Rules for this project

- Paper trading only. Never write code that places a real order
  or asks for withdrawal permission.
- Secrets live in .env, never in code and never committed.
- Every function that decides a trade gets tests, including the edge
  cases: stop on the wrong side, missing data, a size of zero.
- Log every decision as one JSON line: time, coin, what the bot saw,
  what it decided and why.
- Data older than 10 minutes is stale: skip the decision and log why.
- Ask before adding a dependency, changing a risk limit or deleting data.
- Explain any change to trading logic in plain words before making it.

Working with Claude Code

  • Ask for a plan before any code. Read it, push back, then say go.
  • One piece per session: the collector, then the plan writer, then the gates. Small briefs get better code than one giant prompt.
  • Ask for tests with every change, and run them yourself.
  • Read the diff. If you can't explain a change in one sentence, ask Claude Code to explain it before you keep it.
  • Commit each piece once it works, so a bad change is one command away from undone.

Step 3: Collect clean market data

Everything later depends on this step. Candles, funding rates and open interest are free from exchanges' public market data endpoints, with no API key. Fetch them on a schedule, save every reading with its time, and treat old data as missing instead of quietly using it.

Prompt for Claude Code
Read BRIEF.md and CLAUDE.md. Plan first, no code yet.

Build the data collector. Every 5 minutes, fetch 1 hour and 4 hour candles,
the funding rate and open interest for BTC and ETH perpetuals from the
exchange's public market data API (no API key). Save each reading with its
timestamp to SQLite. If a fetch fails, keep the last good reading and log
the error. Add a function that says whether the latest data is fresh
(under 10 minutes old).

Show me the plan, the table layout and the tests you will write.

Check the result by hand once: pick a candle and compare it with a chart. To see what these numbers look like across many exchanges, our live funding rates and open interest pages show the same kind of feed, refreshed every 5 minutes.

Step 4: Turn the data into a trade plan

A plan is not a buy button. It says where to get in, where the idea is wrong, where to take profit, whether that is worth it, and what would cancel it before entry. Start with a rule simple enough to write in one sentence, because a rule you can't state is a rule you can't test.

You can add an AI read on top: give a model the data and ask for plans in a strict format. If you do, treat its output as a suggestion. Ask for JSON with fixed fields, and have code check every number: the stop is on the right side, reward to risk is worked out again from the prices, nothing is missing.

A plan, as JSON
{
  "coin": "BTC",
  "side": "long",
  "entry_zone": [60000, 60300],
  "stop": 59200,
  "targets": [61800, 63000],
  "reward_to_risk": 1.7,
  "cancel_if": "4 hour close below 59,600 before entry",
  "reason": "Pullback to the rising 4 hour average after a higher low"
}

Size comes from the stop, never from confidence. Risk a fixed share of the account, 1% is a common choice, and work the position size out from the distance to the stop. The position size calculator and the risk reward calculator do the same math, which makes them handy for checking your bot by hand.

Step 5: Add risk gates the AI can't talk its way past

Rules in a prompt are requests. Rules in code are rules. Put every limit that protects the account in a plain function that each plan has to pass, and log the reason every time it says no.

risk_gates.py
def allowed(plan, account, open_trades, pnl_today, data_age_s):
    """Hard rules. A model can suggest a trade; only this can allow it."""
    if data_age_s > 600:
        return False, "data is stale"
    if plan.stop is None:
        return False, "no stop"
    if (plan.side == "long") != (plan.stop < plan.entry):
        return False, "stop is on the wrong side"
    risk = abs(plan.entry - plan.stop)
    reward = abs(plan.targets[0] - plan.entry)
    if reward / risk < 1.5:
        return False, "reward to risk below 1.5"
    if len(open_trades) >= 2:
        return False, "two trades already open"
    if pnl_today <= -0.03 * account:
        return False, "daily loss limit reached"
    return True, "ok"

Other gates worth adding: no new trades around major economic releases, liquidation well beyond the stop if you use leverage (the leverage calculator shows where that line sits), and nothing trades when the data check fails. Keep them boring and keep them tested.

Step 6: Paper trade it

The paper trader takes approved plans and fills them against live prices as if they were real: the entry when price reaches the zone, the stop or a target when it is hit, fees on both sides and funding while the trade is open. Every decision goes in the log, including the plans the gates rejected and why.

Measure results in R, the result divided by what the trade risked, so every trade compares with every other. Then wait for a batch: 20 to 30 closed trades tell you far more than the last one. Our free trading journal works the same way if you want to log a few trades by hand alongside the bot.

Step 7: Run it around the clock

A bot on a laptop stops when the lid closes. Once it works locally, move it to a small Linux server.

  • Run each piece as a service with a timer, so it comes back after a crash or a reboot.
  • Keep secrets in a .env file only your user can read, and never commit it.
  • Send alerts to a private Telegram bot that answers only your chat.
  • Add a morning status message: data fresh, last decision, open paper trades, errors. If the message doesn't arrive, that is your alert.
  • Lock the server down: key-only SSH, a firewall and automatic security updates.

Step 8: Test it honestly

This is where most bots fail, and it is far better to find out on paper. Watch for four traps:

  • Lookahead: the test uses a candle's close before that candle has closed. Make Claude Code show you it can't happen.
  • Overfitting: a rule tuned until it fits the past fits only the past. Keep a stretch of data the rule has never seen.
  • Costs: fees, slippage and funding turn many small winners into losers. Include all three.
  • No baseline: compare against doing nothing, or against a simple rule, over the same period.

We say this from experience. Several of our own ideas, including breakout rules and betting against crowded positioning, looked fine until costs were counted, and we threw them out. A test that kills a bad idea has done its job.

Step 9: Then a demo account, not real money

Once the paper results are honest and you understand every decision in the log, connect an exchange demo or testnet account. Create an API key with trading permission only, never withdrawal, and limit it to your server's IP address if the exchange allows it. Add a kill switch that closes everything and stops the bot with one command.

This guide stops there on purpose. A bot works best as a co-pilot you supervise: it watches the market around the clock and keeps to the rules, and you make the calls. Results depend on the plan, the market and how each trader manages trades, and nothing is guaranteed.

Mistakes we would skip

  • Building the dashboard before the data is right.
  • Letting a model decide the position size or move a stop.
  • Trusting the bot's own summary of what it did instead of reading the log.
  • Changing three things at once, so you never learn which one mattered.
  • Testing without fees and funding.
  • Keeping API keys in the code, or pasting them into a chat with the AI.
  • Judging a strategy on five trades.

Common questions

Can Claude Code build a crypto trading bot?

Yes. It can write the code for every part in this guide: the data collector, the plan writer, the risk gates, the paper trader and the alerts. What it can't do is decide what your bot should trade or tell you whether a strategy has an edge. That comes from your brief and your testing.

Do I need to know how to code?

Not to start. You need to be comfortable in a terminal, able to read a plan and a test result, and willing to say no to changes you don't understand. Bentley was built by a product designer directing Claude Code.

How much does it cost to run?

A Claude plan for Claude Code, a small server, and API costs if you add an AI read, with a spend limit set. Public market data costs nothing. Expect tens of dollars a month in total. Prices change, so check them before you start.

Will a trading bot make money?

Nobody can honestly promise that. Most simple rules we tested did not survive trading costs. A bot makes testing faster and keeps you to your own rules; whether it makes money depends on the plan, the market and how you manage it.

Which exchange should I use?

One with a documented API and a demo or testnet account that is available where you live. We don't recommend a particular exchange.

Is it legal to run a trading bot?

Most exchanges allow automated trading of your own account through their official API, within their terms. Check those terms and the rules where you live. This guide is education, not legal or financial advice.

This guide is education only. Nothing in it is financial, investment or tax advice, a trade signal, or a recommendation to buy or sell anything. Trading crypto carries a high risk of loss, and leverage makes losses bigger and faster. Build and test on paper first, and nothing is guaranteed.

Read the risk and education disclaimer.