Python SDK#
uselayer is one Python interface for trading prediction markets on Kalshi and Polymarket US with your own venue keys. Matches also cover polymarket.com and Hyperliquid's outcome markets, and client.whales reads traders on Polymarket and Kalshi. The code is on GitHub at uselayer/uselayer-sdk, under the MIT license.
| Call | What it does | Where it runs |
|---|---|---|
client.matches(), client.match() |
Which markets are the same bet: Kalshi with Polymarket US, polymarket.com or Hyperliquid | Asks Layer |
client.prices() |
Both venues' best bids and asks, with sizes | Your machine, your keys |
client.buy(), client.trade() |
Orders on one venue, or both legs of a match | Your machine, your keys |
client.positions() |
What you hold; fills() and balances() too |
Your machine, your keys |
client.pnl() |
Profit and loss per market and in total | Your machine, your keys |
client.reconcile() |
Checks your local record against what each venue reports | Your machine, your keys |
client.whales |
Traders' records, holdings and scores, and what buying their trade costs now (trader data guide) | Your machine, public venue data |
Only the match lookup reaches Layer. It sends your Layer key, the market ids and your filters, and nothing else: your venue keys, prices and orders never leave your machine.
- Paper mode (the default) fills orders against the venues' real order books with simulated money. Nothing is sent to a venue.
- Live mode sends orders with your own Kalshi or Polymarket US key, for your own account.
- Backtest mode replays books you saved.
Every venue and mode takes the same order shape. Guardrails check every order before it's sent. Fees come from each venue's published schedule in force at the time of the trade, and match Layer's API (POST /v0/profit, POST /v0/size) to the millionth of a dollar. Everything stays on your machine: a local SQLite file per mode, no telemetry.
Install#
pip install uselayerPython 3.11 or newer. The package is on PyPI.
Reading Polymarket traders needs 0.18.0 or later (pip install -U uselayer). Polymarket retired its Data API v1 on Oct 24, 2026, and older versions can't read its traders. Trading and matches aren't affected.
Paper trade#
from uselayer import Client
client = Client() # paper mode: real books, simulated fills
m = client.markets(limit=20)[0] # open Polymarket US markets, no key needed
book = client.book(m.slug)
order = client.order(
venue="polymarket_us", market=m.slug, side="yes", price=book.outcome("yes").best_ask.price, size=5
)
print(client.preview(order)) # fill, fees, every rule's decision
print(client.send(order)) # the order, filled against the bookpreview() shows what an order would do and sends nothing. client.positions(), client.fills() and client.orders() read the local store. Every paper fill is a SimulatedFill with simulated=True.
Live mode#
from uselayer import Client, PolymarketUS
client = Client(mode="live", polymarket_us=PolymarketUS(key_id="...", secret_key_path="~/.pmus/secret"))
client.balances()["polymarket_us"].cash
order = client.buy(venue="polymarket_us", market="<slug>", side="yes", price=0.42, size=5)
client.positions() # from the venueCreate the key at polymarket.us/developer. It stays on your machine: requests are signed with it locally and only the signature is sent.
- Books in live mode come from the venue's WebSocket, so they aren't cached.
- An order whose answer never arrives raises
outcome_unknown. It is never sent again on its own: callclient.sync()and checkclient.orders(). - If the local store is new but your account already has open orders or positions, live mode starts with the kill switch on, until you run
python -m uselayer resume --mode live.
Profit and loss#
p = client.pnl()
p.net, p.realized, p.unrealized, p.fees # dollars, in total
p.resolution_mismatch_loss # of realized: lost to pairs the venues settled differently
for r in p.rows: # one row per side of each market you've held
r.market, r.side, r.contracts, r.realized, r.unrealized, r.fees, r.outcomerealized: profit from contracts sold or settled, before fees.unrealized: the contracts you hold at the best bid, what you could sell them for now, minus what they cost.max_daily_lossvalues positions at the same bid.fees: every fee paid.net:realized + unrealized - fees.resolution_mismatch_loss: how much ofrealizedhedged pairs lost because the two venues settled them differently, against the $1 per contract they should have paid (see When the venues settle a pair differently). It's a breakdown, already insiderealizedandnet, not subtracted again.
A position with no bid to value it at shows unrealized=None, is listed in p.missing_marks and is left out of the total.
In paper and backtest mode, positions settle when their market does:
- Payout. Each contract pays $1 if its side won and $0 if it lost. On a
void, it pays the venue's price when the venue gives one (Kalshi's fair price for a canceled game), or else what the contract cost. Fees aren't refunded. - What happens next. The position closes, and resting orders on the market are canceled. Payouts are in
client.settlements(). - Paper mode asks the venue whether a market you hold has settled, at most once a minute per market, whenever you call
positions(),pnl()ormonitor().client.settle()asks now. - A backtest settles at each
resolutionevent it replays, and the market takes no more orders.
In live mode, pnl() reports what each venue says about your positions, including closed and settled ones, and values the contracts you hold at the bid. fees is what each venue charged: Kalshi reports it on each position. For Polymarket US it comes from your account's trade history, and so do positions Polymarket US has settled, which drop off its positions list.
Reconcile with the venues#
In live mode, the SDK keeps its own record of your orders and fills on your machine, and the guardrails count your positions from it. client.reconcile() reads each venue's fills, positions and open orders with your key and lists every difference:
r = client.reconcile()
r.ok # your record and every venue agree
for m in r.mismatches:
print(m.kind, m.venue, m.market, m.message)missed_fill: the venue filled an order the SDK sent, and your record doesn't have that fill (say, the process stopped mid-order).unknown_fill: your record has a fill for an SDK order that the venue doesn't show.outside_fill: a fill of an order the SDK didn't send, such as a trade on the venue's website or from another bot.position: the contracts you hold in a market, per your record, differ from the venue's. Holding NO shows as a negative number of YES contracts.outside_order: an open order on the venue that the SDK didn't send.stale_order: your record says an order is open, and the venue doesn't list it as open.
It only reads: your record doesn't change. client.reconcile(repair=True) also adds the fills the venue reported for orders the SDK sent. Fills of orders it didn't send are never added, only reported. Markets the venue has settled aren't compared. From a terminal, python -m uselayer reconcile prints the same list and exits 1 when anything differs, so you can run it on a schedule.
Guardrails#
client = Client(
rules={
"max_position": {"per_market": 200}, # $ at risk in one market
"budget": 1000, # $ at risk in total
"max_daily_loss": {"amount": 150}, # stop opening positions after this loss today
"approve_above": 100, # ask before orders above $100
"stop_loss": {"pct": 25}, # exits sent by client.monitor()
}
)Rules can also come from a YAML or JSON file: Client(rules="guardrails.yaml"). YAML needs pip install "uselayer[yaml]". Rules are fixed when the client is created.
Rules cover position size, budget, daily loss, allowed markets, approvals, stop-loss and take-profit. A price collar, an order throttle and a kill switch are always on.
Kill switch#
python -m uselayer kill # from any terminal on this machine
python -m uselayer status
python -m uselayer resume # a person turns it offclient.kill() does the same from code: it cancels resting orders and blocks new ones. The switch stays on, even after a restart, until a person runs python -m uselayer resume. The client a strategy or agent holds can't resume.
Pairs#
When two markets are the same bet, buying YES on one and NO on the other pays $1 per contract either way. quote() prices that after both fees. trade() places both legs.
q = client.quote(pair) # pair: a Match from client.matches(), or two (venue, market)
t = client.trade(pair, size=100, min_edge=0.01)
t.status # "hedged" | "missed" | "unwound" | "exposed"A quote reads as three numbers for the contracts that clear min_edge:
q = client.quote(pair, size=100, min_edge=0.01)
q.gross_spread # $1 a contract at settlement minus what they cost, before fees
q.fees # both venues' taker fees on them
q.net_profit # gross_spread - fees: what they lock in
q.gross_at_best, q.edge_at_best # the gap per contract at the best asks, before and after feesWhen fees close the gap, q.contracts is 0 and so are the three totals, but q.gross_at_best still shows the gap before fees.
The money is tied up until both markets pay out, so a quote also gives the return per day:
q.return_pct # net profit over what the contracts cost with fees, in percent
q.settles_at # when the money is expected back: the later of the two markets' payouts
q.days_held # days from now until then (at least 1)
q.return_per_day_pct # return_pct spread over days_heldsettles_at follows the same rule as client.profit(), from each venue's own market times, so the two agree on the same pair. When neither venue gives a time, all three are None: the SDK never guesses a date. A backtest has no venue times, so pass one: quote(pair, settles_at="2026-10-05").
client.matches(q="...") needs a Layer API key. It sends Layer your key, the market ids Layer gave you and your filters, and nothing else: no prices, orders, positions or venue keys.
polymarket.com and Hyperliquid#
Matches are with Polymarket US by default. venue="polymarket" gives polymarket.com, and venue="hyperliquid" gives Hyperliquid's outcome markets, both paired with Kalshi:
for m in client.matches(venue="hyperliquid", q="nba"):
m.kalshi.market_id, m.hyperliquid.market_id # a Kalshi ticker, "#14960"
m.hyperliquid.question, m.hyperliquid.event_time
client.match("<Kalshi ticker>", venue="kalshi", with_="hyperliquid")["matched_market"]- Hyperliquid matches are sports games only: game winners, soccer results (each team and the draw), and a game's totals and spreads. No season winners or player props.
- A Hyperliquid
market_idis the coin of one side of an outcome:"#14960"is side 0 of outcome 1496. Itsurlis Hyperliquid's Outcomes page. - Each market's event, question, outcome, times and rules are read from Hyperliquid's public API on your machine: two reads per client, however many matches.
- Matches only:
book(),prices()andquote()on a Hyperliquid market raisevenue_switched_off. A Hyperliquid market's twin is always on Kalshi, sowith_naming a Polymarket raisesinvalid_orderbefore anything is sent. - Novig's sports game lines (
venue=novigin the API) aren't in the SDK yet: ask the API for them directly. - When Layer isn't serving a venue's matches, it answers 403
venue_not_served, and the SDK raisesVenueError("venue_switched_off")(your key is fine).
Rule-flag notes#
m.caveats says which rules differ between the two markets, as codes (source_differs, definition_differs, ...). Layer's API sends the codes only, and the SDK writes a note for each from the rules it read:
m.caveats # ["definition_differs"]
m.caveat_notes # {"definition_differs": "Kalshi's rules don't say. Hyperliquid's rules: \"The Counted Play is the full game including overtime. ...\""}
m.caveat_notes_from # "venues": the SDK wrote them; "layer": Layer sent them; None: no notes
m.kalshi.rules, m.kalshi.resolution_sources- Each note quotes the two sentences of each venue's rules that use that code's words most, word for word (cut at 400 characters). When none do, it says so: "Kalshi's rules don't say."
- For
source_differs, when both venues name a settlement source and they differ, the note names both instead. - A code that neither venue's rules speak to gets no note. Nothing is guessed, no AI is involved, and nothing is sent to Layer.
- Matches with polymarket.com get no notes yet.
titles=Falseskips the venue reads, and the notes with them.
The leg-risk guard#
- The thinner leg goes first, immediate-or-cancel.
- The other leg goes for what filled, up to its break-even price.
- If it can't be completed within
chase_s, the first leg is sold back, never below its entry price minusmax_unwind_loss(on_miss="unwind", the default). Withon_miss="hold", the open contracts are reported instead. - Both legs pass the guardrails together before either is sent.
trade() runs in paper, backtest and live mode. Live, each leg goes to its venue with your own key. A Kalshi ↔ Polymarket US pair needs both keys, and both are checked before anything is sent:
client = Client(mode="live", kalshi=Kalshi.from_env(), polymarket_us=PolymarketUS.from_env())
t = client.trade(pair, size=10, min_edge=0.01)
if t.status == "exposed":
print(t.exposure, t.notes) # contracts left on one sideIf a venue answers with an error mid-pair, the open leg is still sold back or reported. If a venue can't say whether an order went through, nothing is sold back: the trade comes back exposed, and its notes say to run client.sync() before trading those markets again.
When the venues settle a pair differently#
A hedged pair pays $1 per contract only if both venues settle the bet the same way. They don't always: their rules can differ, one can void a market the other settles, or one can settle days after the other. This is a real risk of trading pairs, and the SDK tracks it:
for m in client.resolution_mismatches():
m.kind # "both_lost" | "both_won" | "void_one_leg" | "settle_gap"
m.impact # what the pair paid minus the $1 per contract expected (negative: lost)
m.a.venue, m.a.outcome, m.a.payout # each venue's resultA pair is flagged when both legs lost, both won, one venue voided or refunded its market and the other didn't, or one leg was still open 48 hours after the other settled. Each one is saved on your machine with both venues' results, and pnl() shows how much of realized they lost as resolution_mismatch_loss. Paper, backtest and live mode. In live mode the SDK asks each venue what the pair's markets paid, with your keys. Nothing is sent to Layer.
One order, on the cheaper venue#
When you know the bet and only need to decide where to place it, buy_best() places the order on whichever venue of a matched pair is cheaper for that size, after fees, at the moment you call it.
p = client.preview_best(pair, "yes", 10, max_price=0.55) # the comparison; sends nothing
r = client.buy_best(pair, "yes", 10, max_price=0.55)
r.why.reason # "Kalshi is $0.06 cheaper all-in for 10 contracts: $4.35 vs $4.41 on Polymarket US."
[(v.venue, v.all_in, v.skip) for v in r.why.venues]For each venue it walks the book for your size, level by level, and adds that venue's fees, the way a paper fill is priced. The lower all-in cost wins; on a tie, the venue with more contracts on offer at its price. side is the same outcome on both venues: each market id in a match already names it. sell_best(pair, side, size, min_price=) sells contracts you hold where they pay more after fees, only on a venue where you hold them.
A buy can also be given in dollars, the way people bet (uselayer 0.4.3 or later):
r = client.buy_best(pair, "yes", spend=50) # $50 on YES, fees included
r.order.size # the most whole contracts $50 buys on the chosen venue
r.why.reason # "Kalshi wins $3.00 more if you're right: $50.00 buys 69 contracts there for $49.32 all-in, vs 66 for $49.80 on Polymarket US."The same money buys a different number of contracts on each venue, so each gets its own size: the most whole contracts whose cost plus fees fits in spend, within max_price and the price collar, from one read of its book. The venue where they pay more if you're right ($1 a contract) wins; the same number on both is compared on cost, as above. Give size or spend, not both. spend is for buys, and preview_best(pair, "yes", spend=50) takes it too.
The order is an immediate-or-cancel limit at the deepest price the walk reached, sent through send(), so every guardrail, the price collar and the kill switch apply. The comparison is a snapshot: a book can move before the order arrives, and the limit, never past max_price or the price collar, caps what it can pay. A venue is left out, with the reason in r.why.venues, when it's switched off, you gave no key for it, your venues or markets rules don't allow it, its market is closed, its book is stale, it can't fill the size within your limit, or spend doesn't buy one contract there. If neither venue can take the order, nothing is sent. Paper, backtest and live mode; live, you choose to call it, on your own account and keys.
Prices, fees and profit#
prices() reads both sides of a match from each venue's order book, with your own keys. An empty side is None.
pair = client.matches(venue="polymarket_us", q="nfl")[0]
p = client.prices(pair) # or [("kalshi", ticker), ("polymarket_us", slug)]
k, u = p.leg("kalshi"), p.leg("polymarket_us")
k.yes_ask, k.yes_ask_size, u.no_ask, u.no_ask_size, k.as_offees() reads each market's fee settings, and how long your money would be held, from the venues (Kalshi ↔ Polymarket US pairs, paper and live mode):
client.fees(pair)
# {"kalshi": {"fee_type": "...", "fee_multiplier": 1.0},
# "polymarket_us": {"fee_coefficient": 0.0695}, "days_held": 6.76, "match": {...}}profit() takes the same body as POST /v0/profit and gives the same answer, on your machine. With pair=, it fills in each market's fees and days_held from the venues; anything you send wins. With a kalshi.market_id in the body instead, it asks Layer for the Polymarket US twin, its only call to Layer.
if k.yes_ask and u.no_ask: # an empty side is None, and profit() needs both prices
body = {"contracts": 100, "kalshi": {"price": k.yes_ask}, "polymarket_us": {"price": u.no_ask}}
r = client.profit(body, pair=pair)
r["net_profit"], r["filled_in"], r.get("return_per_day_pct") # only when days_held is knownuselayer.calc.profit() and uselayer.calc.size() are the same math with nothing read: you send every number, and calc.size() answers like POST /v0/size from the books you pass.
One strategy, every mode#
run() calls your strategy for each pair on each new book. The same function runs in every mode.
def strategy(client, pair, quote):
if quote.net_profit_per_contract >= 0.02:
client.trade(pair, size=100)
Client(mode="backtest", books=saved_books).run(strategy, [pair]) # the past
Client().run(strategy, [pair], iterations=60) # now, paperIn paper and live mode it runs every interval_s (1 second by default) until iterations rounds, stop() or the kill switch.
Backtest#
from uselayer import Client
from uselayer.backtest import load_books, record_books
record_books(Client(), ["<slug>"], "books.jsonl") # run on a schedule to build a history
bt = Client(mode="backtest", books=load_books("books.jsonl"))
bt.replay(lambda client, book: ...) # place orders as each book arrivesrecord_books() saves one snapshot per call. The replay uses the same fill model, fees and rules as paper mode, on the replayed clock. Trades in the data fill resting orders once the estimated line ahead of them at their price is used up.
To backtest on history you already have (CSV, Parquet, raw venue stream messages or PMXT files), see Backtest data.
Fees by date#
from datetime import UTC, datetime
from uselayer import FeeSettings, calculate_fee, rules_at
rules_at("polymarket_us", datetime.now(UTC)).source # the schedule's page
calculate_fee(
FeeSettings(venue="polymarket_us"), contracts=100, price=0.5, role="taker", at=datetime.now(UTC)
)Before the earliest schedule the SDK knows, it raises no_venue_rules instead of guessing.
What paper mode can't tell you#
- Your exact place in line. A resting paper order joins the back of the line at its price: everything already there is ahead of it. Trades at its price use up that line first, and only what's left fills your order. A trade through its price, or a book whose other side reaches it, fills it too, and the same contracts never fill it twice. Venues publish the total at each price, not single orders, so the line is an estimate: when a level shrinks by more than its trades explain, the difference counts as cancels, spread through the line (
Client(queue_cancels="behind")puts them all behind you, the worst case). With books alone (monitor()in paper mode, orrecord_books()snapshots), a resting order fills only when a book crosses its price. - How fast the venue answers. A paper order reaches the book the moment you send it.
- When a market settles. Paper mode learns that a market settled when it next asks the venue (at most once a minute per market). On Kalshi, a result counts only once it's final, not while it can still be disputed.
- Freshness without a key. In paper mode, Polymarket US's public book is cached for up to 30 seconds. The SDK stamps each book with the venue's time. When a copy is older than
max_quote_age_s(10 seconds by default), it waits for a fresh one before using it.
For AI agents#
AGENTS.mdandllms.txtship inside the package.- Every public method has a docstring with an example.
- Every object has
.to_dict(). - Every error is a
VenueErrorwithcode,hintandnext. - Without the SDK: Layer's hosted MCP server hands an agent the API's calls, and
/llms.txtlists these docs as Markdown.
from uselayer import VenueError
try:
client.send(order)
except VenueError as e:
print(e.code, e.hint, e.next)Kalshi#
Kalshi's books are read with your own Kalshi API key, on your machine. Paper mode fills Kalshi orders against them with Kalshi's fee schedule and each series' fee multiplier.
from uselayer import Client, Kalshi
client = Client(kalshi=Kalshi(key_id="...", private_key_path="~/.kalshi/key.pem")) # or KALSHI_KEY_ID + KALSHI_PRIVATE_KEY_PATH
client.book("<TICKER>", venue="kalshi").outcome("yes").best_ask
client.buy(venue="kalshi", market="<TICKER>", side="yes", price=0.42, size=5) # paper fillTo price a buy on a Kalshi market without a key, client.whales.preview_kalshi() reads Kalshi's public book (trader data guide).
Create the key in your Kalshi account settings; Ed25519 and RSA keys both work. Market ids are Kalshi tickers. Kalshi(..., environment="demo") uses Kalshi's demo exchange. Backtest mode replays Kalshi books you saved without a key.
Live Kalshi orders. Client(mode="live", kalshi=...) places, cancels and tracks Kalshi orders with your own key, for your own account, as it does on Polymarket US. Your guardrails and the kill switch check every order first. Pairs across the two venues (trade()) run live too, with both keys.
trade() also runs on Kalshi ↔ Polymarket US pairs, in every mode:
client = Client(kalshi=Kalshi.from_env(), layer_key="lyr_...")
pair = client.matches(venue="polymarket_us", q="nfl")[0] # m.kalshi and m.polymarket_us
client.quote(pair).net_profit_per_contractOne more thing paper mode can't tell you: Kalshi's sub-cent billing. The SDK rounds each Kalshi fee up to the cent, from the published schedule, as Layer's API does. Kalshi bills fees to fractions of a cent, so a paper fee can be up to a cent higher than what Kalshi would charge.
Record every tick#
record_stream() keeps each venue's live stream open and saves every book change and trade, for Kalshi and Polymarket US in one call, one file and one event format, with the venue's time (as_of) and your machine's (received_at). Kalshi tickers (in capitals) and Polymarket US slugs can be mixed; venue= reads every id as one venue's. It reconnects on its own and writes a gap event for each market while its venue was disconnected. Kalshi numbers its messages, so a lost one is a gap too, followed by a fresh book. In backtest mode a market has no book during a gap. Each venue's stream needs your key for it, though nothing is traded: KALSHI_KEY_ID and KALSHI_PRIVATE_KEY_PATH (a read-only Kalshi key is enough), and POLYMARKET_US_KEY_ID and POLYMARKET_US_SECRET_KEY.
from uselayer import Client
from uselayer.backtest import load_books, record_stream
record_stream(["<TICKER>", "<slug>"], "ticks.jsonl", duration_s=3600) # Kalshi + Polymarket US, or until Ctrl-C
Client(mode="backtest", books=load_books("ticks.jsonl")).replay(on_book)In paper mode, pass on_event=client.feed so the stream's trades fill your resting orders as they print: record_stream(["<slug>"], "ticks.jsonl", on_event=client.feed).
From a terminal, with progress:
python -m uselayer record <TICKER> <slug> --out ticks.jsonl --minutes 60Import your own data#
import_events() turns history you already have (CSV, Parquet, raw venue stream messages or PMXT files) into backtest events, and checks it first. Backtests also replay polymarket.com data. See Backtest data.
Trader data#
client.whales reads traders on Polymarket and Kalshi from the venues' public data, on your machine, with no venue key. It covers:
- Leaderboards, search by username, and big trades
- A trader's holdings, trades and wallet
- Their track record: positions closed, hourly profit history, and profit by category
- A score of whether their edge is real
- What buying one of their trades would cost now, on Polymarket or Kalshi
- Copies in paper mode
who = client.whales.search_traders("<username>")[0]
client.whales.completed_positions(who.id).summary # their record in one line, or why it can't be given
buy = next(t for t in client.whales.trades("polymarket", who.id) if t.action == "buy")
client.whales.preview_copy(buy, spend=50) # what $50 of it costs nowEvery call is in the trader data guide on GitHub.