Guide: Python
Build an AFL arbitrage scanner in Python
By the end of this guide you will have one Python file, about 130 lines, that reads every AFL market at the bookmakers you bet with, finds any set of prices that adds up to less than 100%, and prints the stake for each side. It takes about twenty minutes, and the free plan runs it.
Before you start
What you need
- Python
- 3.9 or later, with
requestsinstalled. - A key
- The free Developer plan covers the AFL in season with every listed book but bet365, which is enough to build and test this. More scans need more credits: Starter has 30,000 a month, and Pro adds bet365.
- Time
- About twenty minutes to read and run.
This goes further than the arbitrage use case, which checks head to head prices only. Here every two-way market counts: lines, totals, halves, quarters and player props, each compared at the same number.
Status, 13 Oct 2026. /v1 opens to keys shortly; until then requests are redirected to the docs, and the script stops with a message that says so. Written against the SockOdds v1 contract and tested against its schemas, on a mock that serves the v1 shape. A run against the live feed is pending; its date and league will be added here when it has run. The AFL is off season until March, so that first run will use the NFL or MLB, which the same code reads unchanged.
Step 1
Name the books you can bet with
import os
import sys
import time
from datetime import datetime, timedelta, timezone
from urllib.parse import urljoin
import requests
API = "https://api.sockodds.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SOCKODDS_KEY']}"}
# Books you hold an account with. Every plan reads each listed book but bet365.
BOOKS = ["sportsbet", "tab", "ladbrokes"]
# Exchanges charge on net winnings: {"betfair_exchange": 0.05}, at your own rate.
COMMISSION = {}
# Skip anything under half a percent: rounding and the next price move eat it.
MIN_RETURN = 0.005
# The coming round. Each game returned is one object of your quota, and each price on it one more.
LOOKAHEAD = timedelta(days=7)
# The side pairs that make a two-way market, checked against the catalogue's list for each market.
PAIRS = [{"home", "away"}, {"over", "under"}, {"yes", "no"}, {"competitor_1", "competitor_2"}]
An arbitrage at a bookmaker you have no account with is not one you can take, so BOOKS comes first. It goes to the API as the bookmakers filter, which trims the response to those books. The feed also carries Pinnacle, the Betfair Exchange, Kalshi and Polymarket as reference prices; whether you can bet with any of them depends on where you live, so they stay out until you add them.
COMMISSIONis for exchanges, which take a share of net winnings. A 2.70 back price at 5% commission is really 2.615, and the scanner compares that.MIN_RETURNdrops anything under half a percent. Rounding stakes to whole dollars and the next price move can each cost that much.LOOKAHEADlimits the read to the coming week. Every plan counts credits, as SockOdds's pricing page reads on 18 November 2026, and a game outside the window costs nothing.PAIRSlists the side pairs that make a two-way market. Which sides a market has comes from the league's catalogue, for the reason in step 4.
Step 2
Read the round in one request
def get(url, params=None):
"""GET with the key. Waits when the API says to (over the per-minute limit, or briefly
busy); stops with the API's own reason on any other refusal, a used-up month included."""
for _ in range(5):
r = requests.get(url, params=params, headers=HEADERS, timeout=30)
problem = r.json() if "problem+json" in r.headers.get("content-type", "") else {}
if r.status_code in (429, 503) and problem.get("title") != "Monthly allowance reached":
time.sleep(max(1.0, float(r.headers.get("retry-after", 60))))
continue
if r.status_code >= 500:
r.raise_for_status() # a server error: the caller decides whether to try again
if problem:
raise SystemExit(f'{problem["status"]} {problem["title"]}: {problem["detail"]}')
if r.status_code != 200 or "json" not in r.headers.get("content-type", ""):
raise SystemExit(f"{r.status_code} from {r.url}: not a JSON answer from the API")
return r.json()
raise SystemExit(f"{url}: still asked to wait after five tries")
def every(url, params):
"""Every item of a listing, following links.next (which may be relative) across pages."""
while url:
page = get(url, params)
yield from page["data"]
url, params = (urljoin(url, page["links"]["next"]) if page["links"]["next"] else None), None
def fetch_events(league):
"""Every game in the window, every market at your books, across all pages."""
now = datetime.now(timezone.utc)
return list(every(f"{API}/odds", {
"league": league,
"bookmakers": ",".join(BOOKS),
"starts_after": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
"starts_before": (now + LOOKAHEAD).strftime("%Y-%m-%dT%H:%M:%SZ"),
}))
def two_way_markets(league):
"""Market keys whose sides, by the league's catalogue, are exactly one of PAIRS. A market
with a third side, such as a draw, never qualifies, even when no book is pricing that side."""
return {m["key"] for m in every(f"{API}/markets", {"league": league, "limit": 100})
if isinstance(m.get("sides"), list) and set(m["sides"]) in PAIRS}
One call to /v1/odds returns every game in the window, each with every market at every book you named. No markets filter is sent, because an arbitrage is as likely in a quarter total or a disposals line as in the head to head, though every market read adds to the credits a scan uses.
starts_after set to now leaves out games already under way: this is not an in-play feed, and a started game is no use to a pre-game scanner. A big league comes back in pages: every follows links.next until it is null, resolving it against the current address in case it is relative.
get reads what the API says when it refuses. A 429 usually means the per-minute limit; the answer carries retry-after, so it waits that long, at least a second, and tries again, up to five times. A 429 whose title is "Monthly allowance reached" is different: the credits for this month are spent and no wait will fix that, so it stops and prints the API's reason, as it does for a wrong key or something your plan does not include. An answer that is not JSON, such as a web page after a redirect, stops it too.
two_way_markets reads the league's market catalogue once a run, GET /v1/markets?league=afl, which lists the sides each market has. Step 4 uses it.
Step 3
Keep the best price on every outcome
def net_price(price, book):
"""The price after an exchange's commission on winnings."""
return 1 + (price - 1) * (1 - COMMISSION.get(book, 0))
def best_prices(event):
"""Per market (one line, one period, one player), the best price on each outcome."""
markets = {} # market ID -> {"market": ..., "best": {outcome ID: (price, book, outcome, seen)}}
for market in event["markets"]:
best = {}
for o in market["outcomes"]:
for p in o["prices"]: # best first, but commission can change the order
if not p.get("available") or not p["decimal_odds"]:
continue
price = net_price(p["decimal_odds"], p["bookmaker"])
if price > best.get(o["id"], (0,))[0]:
best[o["id"]] = (price, p["bookmaker"], o, p["observed_at"])
markets[market["id"]] = {"market": market, "best": best}
return markets
The response is already grouped by market, so there is no matching to do. A market is one market at one line, for one period and, on a prop, one player, and it appears once. Each outcome is one side of it, and its prices hold every book's price, best first. So Carlton at -12.5 from Sportsbet and Carlton at -12.5 from TAB sit under the same outcome without any team-name matching, while Carlton at -14.5 is a different market and is never compared with them.
Quotes with available false are skipped: the book has suspended them or they have not been seen recently. Exchange prices are reduced by your commission before they are compared, so a slightly better exchange price that loses its edge to commission does not win the slot. That is why every price is checked rather than only prices[0].
Step 4
The 100% test
def arbitrage(entry, two_way):
"""The guaranteed return if the best prices add up to under 100%, else None."""
legs = entry["best"].values()
if entry["market"]["key"] not in two_way or len(legs) != 2:
return None # not a two-way market, or one side has no price at your books
implied = sum(1 / price for price, *_ in legs)
edge = 1 / implied - 1
return edge if edge >= MIN_RETURN else None
Turn each best price into an implied chance and add them up. Under 100% means backing every side in the right proportions returns more than you staked, whichever side wins:
return = 1 ÷ Σ(1/best price) − 1
The sum only means that if the outcomes cover every result. Home and away on a handicap do; over and under at one line do. An anytime goalkicker market does not: it has a single side, so its one price always adds up to under 100% and would look like free money on every player. And the sides a response happens to contain prove nothing: if every book had suspended the draw in a three-way soccer result, the home and away prices alone would look two-way. So a market is only checked when the catalogue says its sides are exactly one of PAIRS and both are priced at your books. Three-way markets are left out of this scanner.
Step 5
Split the stake
def stakes(prices, bankroll):
"""Whole-dollar stakes that pay about the same either way, and the least they return."""
implied = sum(1 / p for p in prices)
split = [round(bankroll / p / implied) for p in prices]
return split, min(s * p for s, p in zip(split, prices))
Each side's stake is the bankroll times its share of the implied total, which makes every side pay the same. Real stakes are whole dollars, so the function rounds them and reports the smaller of the payouts, which is the amount you can count on:
stakeᵢ = bankroll × (1/priceᵢ) ÷ Σ(1/price)
The arbitrage calculator does the same sum in the browser if you want to check one by hand.
Step 6
Print what to check
def label(market):
"""'Winner', 'Patrick Cripps: Player disposals over/under', 'Total points (half_1)'."""
name = market["name"]
if market["subject"]:
name = f'{market["subject"]["name"]}: {name}'
return name if market["period"] == "full" else f'{name} ({market["period"]})'
def outcome_text(o):
"""'Carlton', 'Carlton -12.5', 'Over 165.5'."""
if o["line"] is None:
return o["name"]
if o["side"] in ("home", "away", "competitor_1", "competitor_2"):
return f'{o["name"]} {o["line"]:+g}'
return f'{o["name"]} {o["line"]:g}'
def main(league="afl", bankroll=100):
events, two_way = fetch_events(league), two_way_markets(league)
found = 0
for event in events:
for entry in best_prices(event).values():
edge = arbitrage(entry, two_way)
if edge is None:
continue
found += 1
legs = list(entry["best"].values())
split, payout = stakes([price for price, *_ in legs], bankroll)
print(f'{event["name"]} | {label(entry["market"])}: {edge:.2%} return')
for (price, book, o, seen), stake in zip(legs, split):
print(f" {outcome_text(o):<14} {price:>5.2f} at {book:<10} ${stake:<4} seen {seen[11:16]} UTC")
print(f" ${sum(split)} staked returns at least ${payout:.2f}")
print(f"{found} found. {league.upper()} games checked: {len(events)}. Books: {', '.join(BOOKS)}")
Each line is something you would check at the bookmaker before betting: the market, the side with its line, the price, the book, the stake and the time the price was seen. observed_at is per quote, so when the two legs were seen minutes apart you know to look harder.
The whole file
afl_arb_scanner.py
Save it, install requests, set your key and run it:
python3 -m pip install requests
export SOCKODDS_KEY="paste-your-key-here"
python3 afl_arb_scanner.py
"""AFL arbitrage scanner: every two-way market at every book you bet with.
export SOCKODDS_KEY="your-key"
python afl_arb_scanner.py # AFL, split $100
python afl_arb_scanner.py nfl 500 # another league, split $500
A price can be up to ten minutes old before it is withheld, so whatever this prints is a candidate:
check both prices at the bookmakers before you stake anything.
"""
import os
import sys
import time
from datetime import datetime, timedelta, timezone
from urllib.parse import urljoin
import requests
API = "https://api.sockodds.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SOCKODDS_KEY']}"}
# Books you hold an account with. Every plan reads each listed book but bet365.
BOOKS = ["sportsbet", "tab", "ladbrokes"]
# Exchanges charge on net winnings: {"betfair_exchange": 0.05}, at your own rate.
COMMISSION = {}
# Skip anything under half a percent: rounding and the next price move eat it.
MIN_RETURN = 0.005
# The coming round. Each game returned is one object of your quota, and each price on it one more.
LOOKAHEAD = timedelta(days=7)
# The side pairs that make a two-way market, checked against the catalogue's list for each market.
PAIRS = [{"home", "away"}, {"over", "under"}, {"yes", "no"}, {"competitor_1", "competitor_2"}]
def get(url, params=None):
"""GET with the key. Waits when the API says to (over the per-minute limit, or briefly
busy); stops with the API's own reason on any other refusal, a used-up month included."""
for _ in range(5):
r = requests.get(url, params=params, headers=HEADERS, timeout=30)
problem = r.json() if "problem+json" in r.headers.get("content-type", "") else {}
if r.status_code in (429, 503) and problem.get("title") != "Monthly allowance reached":
time.sleep(max(1.0, float(r.headers.get("retry-after", 60))))
continue
if r.status_code >= 500:
r.raise_for_status() # a server error: the caller decides whether to try again
if problem:
raise SystemExit(f'{problem["status"]} {problem["title"]}: {problem["detail"]}')
if r.status_code != 200 or "json" not in r.headers.get("content-type", ""):
raise SystemExit(f"{r.status_code} from {r.url}: not a JSON answer from the API")
return r.json()
raise SystemExit(f"{url}: still asked to wait after five tries")
def every(url, params):
"""Every item of a listing, following links.next (which may be relative) across pages."""
while url:
page = get(url, params)
yield from page["data"]
url, params = (urljoin(url, page["links"]["next"]) if page["links"]["next"] else None), None
def fetch_events(league):
"""Every game in the window, every market at your books, across all pages."""
now = datetime.now(timezone.utc)
return list(every(f"{API}/odds", {
"league": league,
"bookmakers": ",".join(BOOKS),
"starts_after": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
"starts_before": (now + LOOKAHEAD).strftime("%Y-%m-%dT%H:%M:%SZ"),
}))
def two_way_markets(league):
"""Market keys whose sides, by the league's catalogue, are exactly one of PAIRS. A market
with a third side, such as a draw, never qualifies, even when no book is pricing that side."""
return {m["key"] for m in every(f"{API}/markets", {"league": league, "limit": 100})
if isinstance(m.get("sides"), list) and set(m["sides"]) in PAIRS}
def net_price(price, book):
"""The price after an exchange's commission on winnings."""
return 1 + (price - 1) * (1 - COMMISSION.get(book, 0))
def best_prices(event):
"""Per market (one line, one period, one player), the best price on each outcome."""
markets = {} # market ID -> {"market": ..., "best": {outcome ID: (price, book, outcome, seen)}}
for market in event["markets"]:
best = {}
for o in market["outcomes"]:
for p in o["prices"]: # best first, but commission can change the order
if not p.get("available") or not p["decimal_odds"]:
continue
price = net_price(p["decimal_odds"], p["bookmaker"])
if price > best.get(o["id"], (0,))[0]:
best[o["id"]] = (price, p["bookmaker"], o, p["observed_at"])
markets[market["id"]] = {"market": market, "best": best}
return markets
def arbitrage(entry, two_way):
"""The guaranteed return if the best prices add up to under 100%, else None."""
legs = entry["best"].values()
if entry["market"]["key"] not in two_way or len(legs) != 2:
return None # not a two-way market, or one side has no price at your books
implied = sum(1 / price for price, *_ in legs)
edge = 1 / implied - 1
return edge if edge >= MIN_RETURN else None
def stakes(prices, bankroll):
"""Whole-dollar stakes that pay about the same either way, and the least they return."""
implied = sum(1 / p for p in prices)
split = [round(bankroll / p / implied) for p in prices]
return split, min(s * p for s, p in zip(split, prices))
def label(market):
"""'Winner', 'Patrick Cripps: Player disposals over/under', 'Total points (half_1)'."""
name = market["name"]
if market["subject"]:
name = f'{market["subject"]["name"]}: {name}'
return name if market["period"] == "full" else f'{name} ({market["period"]})'
def outcome_text(o):
"""'Carlton', 'Carlton -12.5', 'Over 165.5'."""
if o["line"] is None:
return o["name"]
if o["side"] in ("home", "away", "competitor_1", "competitor_2"):
return f'{o["name"]} {o["line"]:+g}'
return f'{o["name"]} {o["line"]:g}'
def main(league="afl", bankroll=100):
events, two_way = fetch_events(league), two_way_markets(league)
found = 0
for event in events:
for entry in best_prices(event).values():
edge = arbitrage(entry, two_way)
if edge is None:
continue
found += 1
legs = list(entry["best"].values())
split, payout = stakes([price for price, *_ in legs], bankroll)
print(f'{event["name"]} | {label(entry["market"])}: {edge:.2%} return')
for (price, book, o, seen), stake in zip(legs, split):
print(f" {outcome_text(o):<14} {price:>5.2f} at {book:<10} ${stake:<4} seen {seen[11:16]} UTC")
print(f" ${sum(split)} staked returns at least ${payout:.2f}")
print(f"{found} found. {league.upper()} games checked: {len(events)}. Books: {', '.join(BOOKS)}")
if __name__ == "__main__":
league = sys.argv[1] if len(sys.argv) > 1 else "afl"
main(league, float(sys.argv[2]) if len(sys.argv) > 2 else 100)
This file and its tests are going into a public repository; the link goes here when it exists. Until then, the file above is the one the tests run.
A run
What it prints
Run on 13 Oct 2026 against the v1 schema mock, whose one illustrative AFL game has made-up prices. It shows the output's shape, not real prices or a real arbitrage.
Carlton v Richmond | Winner: 5.07% return
Carlton 1.72 at sportsbet $61 seen 06:58 UTC
Richmond 2.70 at tab $39 seen 06:58 UTC
$100 staked returns at least $104.92
1 found. AFL games checked: 1. Books: sportsbet, tab, ladbrokes
Reading it
Where the numbers come from
1/1.72 + 1/2.70 = 58.14% + 37.04% = 95.18%
That is under 100%, so the return is 1 ÷ 0.9518 − 1 = 5.07%. The exact split of $100 is $61.09 and $38.91; rounded to $61 and $39, a Carlton win pays $104.92 and a Richmond win $105.30, so the scanner reports the smaller. The handicap, total and disposals markets in the same game were checked too and came to more than 100% at these two books.
AFL rules
What happens if the game is drawn
A two-way head to head has no draw side, so a draw looks like the hole in the arbitrage. In practice Australian bookmakers usually settle a drawn AFL head to head as a dead heat: the stake is cut in two, one half settled as a win at the quoted odds and the other as a loss. The API grades it the same way, a dead_heat verdict with a dead_heat_factor of 0.5 in /v1/results.
If both books settle it that way, the arbitrage still holds. Each leg returns half its full payout, and the full payouts are equal by design:
½ × $104.92 + ½ × $105.30 = $105.11
Check each book's rules for the market you bet, because a book that voids instead, or a three-way market with its own draw price, changes the sum.
Changing it
Other leagues, books and lines
- Another league:
python3 afl_arb_scanner.py nrl. On the free plan that isnfl,nba,nblorepl, andafl,nrlormlbin season; every league key works on paid plans. - More books: add their keys to
BOOKS, such asneds,pointsbetorbetr. The bookmakers page lists every key and the plan that includes it, and notes the brands that share one price board, which are one opinion, not two. - Alternate lines: add
"alternates": "true"to the parameters infetch_events. Every alternate line comes back as its own market, and the scanner checks each one with no other change. - An exchange: add
betfair_exchangetoBOOKS(every plan) and your rate toCOMMISSION.
The limits, said plainly.
- A price can be up to ten minutes old before it is withheld, so an arbitrage on screen can be gone at the bookmaker. Treat every result as a candidate and check both prices there first.
- Bookmakers can limit accounts that bet this way, and can void bets taken at an obvious pricing error. Read each book's terms.
- Big books rarely disagree by enough. Most of what a scanner finds sits at the smaller books, which every plan reads: add them to
BOOKS.
Fast Odds API supplies data only. Whether and how you bet is your call.
How often should the scanner run?
As often as your month's credits allow. Every plan counts credits, as SockOdds's pricing page reads on 18 November 2026: the market list is free, and an odds call costs a credit per market returned, per region billed, with a league's featured markets counted once for each page of up to 25 games and any other market once for each game. A scan that reads props and quarter lines across a full round therefore costs far more than one that reads the head to head. Run one scan, read the x-credits-last header, and set the timer so a month of scans fits your plan: the free 1,000, Starter's 30,000 or Pro's 5,000,000.
Does it check player props?
Yes. Over and under on a player's disposals at one line is a two-way market like any other, so it is checked. Books often hang different numbers on the same player; those are different markets and are never mixed. Single-sided props such as anytime goalkicker are skipped, for the reason in step 4.
Why does it find nothing?
Usually because there is nothing to find. Big books on a busy market rarely disagree by enough, and three books give few chances. Gaps show up with more books, on alternate lines, and when one book has moved and another has not, such as just after teams are named. Lowering MIN_RETURN shows near misses if you want to see the scanner working.
Can it place the bets?
No. The API is a read-only data feed. A person places any bet at the bookmaker, under that bookmaker's rules.
Start now
Your first Australian price is one request away.
Free key, no card, AFL and NRL included. Keys are issued on sockodds.com.