Home/ Guides/ Building Betfair Bots
Advanced · Developer Guide

Building Betfair Bots: A Developer's Blueprint

Most people who try to build a Betfair bot give up at one of three points: API authentication, order-state management, or the moment their backtest doesn't survive contact with live markets. This guide walks through the architecture that actually ships — the way working bots are structured, the libraries that save weeks of work, the failure modes nobody warns you about, and the boring infrastructure that makes the difference between a script and a production trading system.

Updated May 202622 min readAdvancedPython / C# / Node

Why Build a Bot Instead of Trading Manually

The honest answer: most people shouldn't. Manual trading on the Betfair Exchange is hard enough — automation multiplies the difficulty by adding software engineering, infrastructure, and an entirely new category of bugs that can drain a bank in seconds. But there are three legitimate reasons to build:

  • Strategy mechanics that require speed humans don't have. Pre-race horse racing scalping involves 4-12 ticks of price movement in a 30-minute window with sub-second decision cycles. A bot can react in 50-150ms. A human takes 300-800ms minimum.
  • Volume that's impossible by hand. If your edge is 0.4% per trade and you need 200 trades per day to make the strategy meaningful, a bot is the only way you'll execute the volume without errors creeping in.
  • Strategies that depend on data the brain can't process. Real-time correlation across 40 simultaneous racing markets, in-running football models reading 15 inputs per second, or scanning 800 markets for a single pricing anomaly — these are bot-only strategies.

If your edge is "I can read the in-running tennis market a bit better than most" — don't build a bot. Trade manually. The bot is appropriate when speed, volume, or breadth of attention is the binding constraint, not when judgement is.

If you're new to the exchange entirely, work through How Betfair Exchange Works, What Is Betfair Trading, and Scalping on Betfair first. The bot is a tool — the strategy is the product.

Prerequisites

Before you write a single line of bot code, have these in place:

  • An active verified Betfair Exchange account with deposit history and at least 30 days of trading activity.
  • A bank you can afford to lose — bot bugs sometimes cost you the bank before you can stop them. Start at £200-£500.
  • Intermediate programming skill: classes, async/await, HTTP clients, JSON parsing, basic networking. If you can't write a working REST client from scratch, you're not ready.
  • A working strategy you've already manually traded for at least 100 sessions with a documented edge. Don't automate something you haven't proven by hand first.
  • A plan for what the bot does on every error path — disconnections, partial fills, stale prices, exchange suspensions.
  • A second machine (or VPS) the bot can run on. Consumer laptops are not production trading infrastructure.

If you don't have all of these, fix the gaps before continuing. The bot multiplies whatever you've built — including the gaps.

Bot Architecture

Every working Betfair bot has the same five components, regardless of language. Build them in this order, isolated from each other, with clear interfaces.

  1. Auth/session manager — handles login, keeps the session token fresh, retries on 401.
  2. Market data feed — receives streaming prices and updates an in-memory market book.
  3. Strategy engine — reads the market book, applies rules, emits trade intents.
  4. Order manager — converts intents into placed/cancelled orders, tracks state, handles fills.
  5. Risk and logging layer — bank checks, position limits, persistent logs of every action and price.

Keep these components separated. The strategy engine should not call the HTTP client directly — it talks to the order manager. The order manager should not parse the streaming feed — it reads from the market book. Coupling kills bots because every bug becomes harder to isolate.

Real-world note

The first version is always too coupled

Almost every bot ever shipped started as a single script that did everything in one event loop. After the first major bug — usually a position-sizing error that lost real money — it gets refactored into separate components. Save yourself the lesson by separating from day one.

Getting Your API Keys

You need two things: an Application Key and a session token. The Application Key is permanent and identifies your bot. The session token expires every 4 hours and proves you're logged in.

  1. Log in to your Betfair account in a browser.
  2. Visit the API setup page (developer.betfair.com) and follow the API approval flow. Betfair wants to know what your bot does — answer truthfully.
  3. Pay the one-off Application Key fee (£299 for the live key). Betfair issues two keys: a live key (real money) and a delayed key (free, 1-3 minute delay, perfect for testing).
  4. Generate a non-interactive login certificate (more on this in the auth section).
  5. Save the Application Key and certificate paths to a config file. Never hard-code them.

Use the delayed key for development. It's free. The market data is delayed 1-3 minutes, which is useless for trading but perfectly fine for unit-testing parsing logic, order placement on simulated markets, and recovery code.

For a deeper walkthrough of the API surface, see the Betfair API: Build Your Own Tools reference.

Authentication — Login and Session Tokens

There are two login flows. The interactive flow uses username + password and is fine for desktop apps but unsuitable for unattended bots. The non-interactive flow uses a client-side certificate and is what every production bot uses.

Non-interactive certificate login

  1. Generate a self-signed certificate locally (OpenSSL, 2048-bit RSA).
  2. Upload the public key to your Betfair security settings.
  3. Send a POST to https://identitysso-cert.betfair.com/api/certlogin with your username, password, and the certificate. Receive a session token back.
  4. Add the session token and Application Key to every subsequent request as headers.
  5. Keep the session alive by hitting the /keepAlive endpoint every 20 minutes — the token expires after 4 hours of idle, but keepAlive resets the timer.
# Python example using betfairlightweight import betfairlightweight as bfl trading = bfl.APIClient( username="your_username", password="your_password", app_key="your_app_key", certs="/path/to/certs/", ) trading.login() # trading.session_token is now valid for 4 hours

The Python betfairlightweight library handles certificate login, retries, and keepAlive automatically. For C#, use BetfairClientLib. For Node, betfair-stream-api covers the streaming side and you'll write a thin auth wrapper yourself.

Common auth failure

If your bot keeps getting INVALID_SESSION_INFORMATION, the issue is almost always one of: (a) clock skew on your server vs Betfair (sync NTP), (b) certificate not uploaded to your Betfair account, or (c) wrong endpoint — auth lives on a different host than the rest of the API.

Streaming Prices vs Polling

Two ways to get prices from Betfair:

  • REST polling: Call listMarketBook every X seconds. Easy to implement. Limited to ~5 calls/sec without throttling. Suitable only for slow strategies and prototyping.
  • Stream API: A persistent TCP connection over TLS. The exchange pushes price updates to you as they happen, with deltas to keep bandwidth low. The only realistic option for any bot that trades faster than minute-by-minute.

Streaming is harder to implement but mandatory for almost any real strategy. Use the streaming library for your language — don't try to write the protocol from scratch unless you have a specific reason.

ApproachLatencyImplementationRight for
REST poll 5s2-7s avgTrivialPrototyping, static markets
REST poll 1s0.5-1.5sEasySlow strategies (LTD hedge)
Stream API30-150msHardScalping, in-running
Stream + colocation10-40msVery hardPre-race scalp at scale

Order Management — the Hard Part

The strategy engine is the obvious place where the edge lives — but the bug that loses you money usually lives in the order manager. Order management has to handle:

  • Placement: back/lay, market vs limit, persistence (lapse, persist, market-on-close).
  • Cancellation: cancel-by-id, cancel-all-for-market, partial cancellations.
  • Updates: change price (which Betfair implements as cancel-and-replace, not modify-in-place).
  • State tracking: EXECUTABLE → PARTIALLY_MATCHED → MATCHED, and the failure cases (CANCELLED, EXPIRED, LAPSED).
  • Reconciliation: what the exchange thinks you have vs what your local state thinks you have. They will disagree at some point. The exchange wins.

Single most important rule: the exchange's view of your orders is the source of truth, not your local state. Build a reconciliation loop that periodically queries listCurrentOrders and corrects your local view. Every bot that's lost serious money in production has had a bug where local state and exchange state diverged and the strategy engine kept trading against a phantom position.

The state machine you actually need

Every order in your bot should track:

  • Internal ID (yours, before the exchange returns one).
  • Betfair Bet ID (returned by placeOrders).
  • Market ID, selection ID, side (BACK/LAY), price, size.
  • Status: SUBMITTED, EXECUTABLE, PARTIALLY_MATCHED, MATCHED, CANCELLED, FAILED.
  • Size matched, size remaining, average price matched.
  • Timestamps for every state transition.

Strategy Engine

The strategy engine reads from the market book, applies rules, and emits intents. Common pattern:

def on_market_update(market_book): if not self.is_market_active(market_book): return runners = self.get_top_runners(market_book, n=3) for r in runners: signal = self.compute_signal(r, market_book) if signal.entry and not self.has_position(r.id): self.order_manager.place( market=market_book.market_id, selection=r.id, side="BACK", price=signal.target_price, size=self.position_sizer.size(signal), persistence="LAPSE", )

Three rules to keep the engine sane:

  1. The engine is stateless per tick. Every market update produces a decision based only on the current state, not on cumulative side-effects. Cumulative state goes in the order manager and the position book — not in the engine.
  2. Every signal has an exit condition. If the strategy says "back at 3.40", the same code knows the exit (e.g. "lay at 3.35 within 8 seconds, otherwise cancel and walk"). No hopeful holds.
  3. Position size is not a free parameter. Wire position size to bank, current open risk, and a max-drawdown circuit-breaker. The strategy engine should never be allowed to ask for a £500 stake when the rules say £40.

Backtesting on Historical Data

Betfair sells historical data — millisecond-level price updates for every market — through the historic data service. It's not free, but it's how you backtest properly.

  1. Buy 6-12 months of data for your sport(s) of interest. Pricing is per-month-per-sport.
  2. Build a replay engine that reads the data files and produces market updates in the same format your live streaming feed produces.
  3. Point your strategy engine at the replay engine. The engine should not know whether it's live or replayed.
  4. Simulate fills realistically — assume you only get matched at the price the market actually traded at, with realistic slippage on bigger size. Optimistic backtests assume every limit order matches; reality is much worse.
  5. Account for commission (2-7% depending on your market base rate) and the Premium Charge if your sim hits the thresholds.

If your backtest doesn't include realistic slippage and full commission, the results are fiction. Most "amazing strategies" in retail forums fall apart at this step.

Latency, Hosting and Co-location

For most bots, hosting in a UK data centre — close to Betfair's exchange servers — is enough. Round-trip latency from a London VPS is ~10-25ms. From a US East datacentre it's ~70-90ms. From your home Wi-Fi it's typically 30-200ms with high jitter.

  • Hobbyist tier: £8-£20/month VPS in London (Hetzner, OVH, Linode). Sufficient for 99% of strategies.
  • Serious tier: dedicated server, UK or Ireland, 1Gbit network. £80-£200/month.
  • Co-location tier: rack space in Equinix LD4 (where Betfair lives). Real money required, suitable only for high-frequency strategies. Sub-1ms to the exchange.

Don't overthink this. If your strategy needs sub-10ms execution, you have a much harder business problem than hosting choice. Most retail bots run on a £15 VPS and are bottlenecked by their strategy, not their network.

Deployment, Monitoring and Recovery

A bot is software. Treat it like software:

  • Source control: git. Every config change committed. No "I edited the live file" in production.
  • Process supervision: systemd, supervisor, or pm2. Auto-restart on crash. The bot must come back up if the host reboots.
  • Logging: structured JSON logs of every market update consumed, every order intent, every order placement, every fill. Ship to a log store you can query (CloudWatch, Loki, or even a flat file you grep).
  • Metrics: at minimum — orders placed/sec, latency p50/p99, current open positions, current P&L, current bank. Render to a dashboard you actually look at.
  • Kill switch: a single command (or a button on a phone-friendly URL) that cancels all orders and stops trading. You will need it.

The recovery question

What does the bot do when it restarts? It should:

  1. Re-authenticate.
  2. Query listCurrentOrders for every market it might have positions in.
  3. Reconstruct local state from exchange truth — not from local memory or last-saved cache alone.
  4. Decide for each open position: hedge out (safe default), continue managing (only if you trust your state), or cancel and exit.

A bot that crashes mid-trade and "doesn't know" what positions it has is one that will compound losses. Build the recovery path before you go live.

Mistakes Bot Builders Make

  • Optimistic backtests. Assuming every limit order matches at touch. The real world only matches a fraction.
  • Ignoring commission. A "5% edge per trade" with 2% commission and 0.5% slippage is a 2.5% edge. Big strategies rarely survive the trip from spreadsheet to live.
  • Skipping the Premium Charge. See Premium Charge explained — a winning bot can hit 20-50% additional charges.
  • Position sizing untied to bank. Bot keeps trading at fixed stakes after a 30% drawdown, accelerating ruin.
  • No kill switch. When the strategy goes wrong, you need to stop it in seconds, not minutes.
  • Trusting local state over exchange state. The exchange is the source of truth. Reconcile constantly.
  • Single bot, no second eye. Run a "watchdog" process that reads the exchange independently and screams if it sees positions or P&L diverging from what the bot reports.
  • Trading on a delayed key in production. Every developer does this once. Check your config.

Regulation, Premium Charge and Account Health

Betfair's API is open to retail traders, but Betfair reserves the right to apply the Premium Charge to consistently profitable accounts. If your bot hits 60% market base rate gross profits over a 60-week qualifying threshold, expect to be charged. Build the charge into your P&L model from day one.

Also: Betfair's terms of service prohibit certain abusive patterns — repeated micro-orders designed to manipulate price, accounts coordinating activity, or activity attempting to mask an underlying account. Stay well clear. Account closures are real and final.

For broader context on commission, see Betfair Commission Explained and the related exchange mechanics guide.

Alternatives Before You Commit

Before writing 4,000 lines of bot code, evaluate these:

  • Bet Angel Guardian: rule-based automation. Strategies you can describe with "if/then" rules can run in Guardian without code. Excellent for scalping templates, automated dutching, time-based exits.
  • BetTrader auto-bots: simpler rule editor, lower price point. Suitable for static strategies on a small number of markets.
  • Cymatic Trader: free, with a basic automation layer. Good for proof-of-concept strategies before you commit to a code build.
  • Fairbot: straightforward auto-trading with a simpler interface. Useful for traders who want light automation without a full bot project.

If your strategy fits any of those tools, you'll save 6-12 weeks of build time and ship the same edge.

If it doesn't — for example, if you need cross-market scanning, custom data sources, or sub-50ms reaction — then a custom bot is the right answer. Just go in with realistic expectations: most bots take 2-3 calendar months to reach production stability, and most lose money in the first version.

Final Build Checklist

  • Manually-traded strategy with documented edge over 100+ sessions.
  • Verified Betfair account with active trading history.
  • Live Application Key purchased; delayed key for development.
  • Certificate-based non-interactive auth working.
  • Streaming feed connected; market book in memory updates correctly.
  • Order manager: place, cancel, replace, and reconcile against exchange.
  • Strategy engine: stateless per tick; every entry has an exit.
  • Position sizer wired to bank; max-drawdown circuit-breaker.
  • Backtest with realistic slippage and commission; results survive transaction costs.
  • Hosted in UK or Ireland; auto-restart configured; logs centralised.
  • Watchdog process running independently.
  • Kill switch reachable from your phone.
  • P&L model includes Premium Charge.
Get Started

Ready to Build Your Bot?

Open a verified Betfair Exchange account first — you'll need it for both the live key and the historical data subscription. Then plan the strategy before the code.