Skip to main content

Historical tick-by-tick L2 orderbook reconstruction and backtesting primitives for Polymarket. Spread, impact, imbalance, and every trade, delivered as a DataFrame.

Project description

MarketLens Python SDK

Historical and real-time prediction market data — full L2 orderbook reconstruction, microstructure analytics, and backtesting primitives for Polymarket.

pip install marketlens
from marketlens import MarketLens

client = MarketLens(api_key="mk_...")  # or set MARKETLENS_API_KEY env var

Orderbook Walk — Series Backtesting

Replay full L2 book state across every market in a rolling series. Each tick yields (Market, OrderBook) — one line to go from series slug to book-level backtest.

from datetime import datetime, timezone
from marketlens import MarketLens

client = MarketLens()

for market, book in client.orderbook.walk(
    "btc-up-or-down-5m", status="resolved",
    after=datetime(2026, 3, 5, 8, 40, tzinfo=timezone.utc),
    before=datetime(2026, 3, 5, 8, 45, tzinfo=timezone.utc),
):
    if (spread := book.spread_bps()) and spread < 200:
        entry = book.impact("BUY", "100")
        # ...

Or get everything as a DataFrame:

df = client.orderbook.walk(
    "btc-up-or-down-5m", status="resolved",
    after=start, before=end,
).to_dataframe()
# Columns: midpoint, spread, spread_bps, imbalance, weighted_midpoint,
#          bid_depth, ask_depth, market_id, winning_outcome

L2 Orderbook Replay

Reconstruct tick-by-tick book state from the raw snapshot + delta stream for a single market.

from marketlens import OrderBookReplay

history = client.orderbook.history(market_id, after=start, before=end)

for event, book in OrderBookReplay(history, market_id=market_id):
    print(f"t={event.t}  mid={book.midpoint}  spread={book.spread_bps():.0f}bps")

# Or as a DataFrame
df = OrderBookReplay(history, market_id=market_id).to_dataframe()

OrderBook Analytics

Every OrderBook — live snapshot or replayed — carries the same analytical methods:

book = client.orderbook.get(market_id)

book.microprice()              # size-weighted mid from best level
book.weighted_midpoint(n=3)    # n-level weighted mid
book.spread_bps()              # spread in basis points
book.imbalance()               # full-book bid/ask imbalance [-1, 1]
book.imbalance(levels=3)       # top-of-book imbalance
book.impact("BUY", "1000")     # VWAP execution price for $1k market buy
book.slippage("BUY", "1000")   # slippage from mid for $1k order
book.depth_within("0.02")      # (bid_depth, ask_depth) within 2c of mid

Resources

Namespace Methods
client.markets list() get() trades() candles()
client.events list() get() markets()
client.series list() get() markets() walk()
client.orderbook get() history() metrics() walk()

All list methods return auto-paginating iterators with .to_list() and .to_dataframe().

df = client.markets.candles(market_id, resolution="1h").to_dataframe()
trades = client.markets.trades(market_id, after=start, before=end).to_list()
top = client.markets.list(status="active", sort="-liquidity", limit=5).first_page()

Async

Every resource, iterator, and replay helper has an async counterpart.

from marketlens import AsyncMarketLens

async with AsyncMarketLens() as client:
    async for market, book in client.orderbook.walk("btc-up-or-down-5m", status="resolved"):
        print(book.microprice(), book.imbalance(levels=3))

Examples

Example Description
microstructure.py Feature matrix from L2 replay — imbalance vs outcome signal
series_backtest.py Spread-timing strategy with per-trade P&L
execution_cost.py Live book depth, spread, impact/slippage across order sizes

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

marketlens-0.2.0.tar.gz (22.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

marketlens-0.2.0-py3-none-any.whl (23.1 kB view details)

Uploaded Python 3

File details

Details for the file marketlens-0.2.0.tar.gz.

File metadata

  • Download URL: marketlens-0.2.0.tar.gz
  • Upload date:
  • Size: 22.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for marketlens-0.2.0.tar.gz
Algorithm Hash digest
SHA256 407325beb431fda6b97be7b3c34b9a88c79dad32f5f144d79d0877b363c2f9a3
MD5 25bcc39a2b74f1751d0620b0b2067cdb
BLAKE2b-256 949d9475fae4fe5eb29a4c249a04abb824304802b5197aa036fa1ac110794c96

See more details on using hashes here.

File details

Details for the file marketlens-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: marketlens-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 23.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for marketlens-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8a29375d9aeadcdc59340f0ccca7194b28f95f484667996883a55df9cc38ddd5
MD5 0eddafea8a94f632bf442cee5ecf55ea
BLAKE2b-256 2f2ca289483a3f54bece694bb0cddcdfeed353f9ee90dba84ff678a1c6800828

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page