forked from nautechsystems/nautilus_trader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolymarket_simple_quoter.py
More file actions
173 lines (142 loc) · 5.46 KB
/
Copy pathpolymarket_simple_quoter.py
File metadata and controls
173 lines (142 loc) · 5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python3
# -------------------------------------------------------------------------------------------------
# Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
# https://nautechsystems.io
#
# Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -------------------------------------------------------------------------------------------------
"""
Example script demonstrating how to fetch and use historical Polymarket data for
backtesting.
This example uses an active Polymarket market for demonstration.
You can find active markets at: https://polymarket.com
Data sources:
- Markets API: https://gamma-api.polymarket.com/markets
- Order book history: https://clob.polymarket.com/orderbook-history
- Trades/Prices: https://clob.polymarket.com/prices-history
"""
import asyncio
from decimal import Decimal
import pandas as pd
from nautilus_trader.adapters.polymarket import POLYMARKET_VENUE
from nautilus_trader.adapters.polymarket import PolymarketDataLoader
from nautilus_trader.backtest.config import BacktestEngineConfig
from nautilus_trader.backtest.engine import BacktestEngine
from nautilus_trader.examples.strategies.orderbook_imbalance import OrderBookImbalance
from nautilus_trader.examples.strategies.orderbook_imbalance import OrderBookImbalanceConfig
from nautilus_trader.model.currencies import USDC_POS
from nautilus_trader.model.enums import AccountType
from nautilus_trader.model.enums import BookType
from nautilus_trader.model.enums import OmsType
from nautilus_trader.model.identifiers import TraderId
from nautilus_trader.model.objects import Money
# Market slug to fetch data for
# To find active markets, run:
# python nautilus_trader/adapters/polymarket/scripts/active_markets.py
# To find BTC/ETH UpDown markets specifically, run:
# python nautilus_trader/adapters/polymarket/scripts/list_updown_markets.py
MARKET_SLUG = "gta-vi-released-before-june-2026"
async def run_backtest(
market_slug: str,
lookback_hours: int = 24,
) -> None:
"""
Run a backtest using historical Polymarket data.
Parameters
----------
market_slug : str
The Polymarket market slug.
lookback_hours : int
How many hours of historical data to fetch.
"""
# Create loader by market slug (automatically fetches and parses instrument)
loader = await PolymarketDataLoader.from_market_slug(market_slug)
instrument = loader.instrument
print(f"\nMarket loaded: {instrument.description or market_slug}")
print(f"Instrument ID: {instrument.id}")
print(f"Outcome: {instrument.outcome}\n")
# Calculate time range for historical data (last N hours)
end = pd.Timestamp.now(tz="UTC")
start = end - pd.Timedelta(hours=lookback_hours)
print(f"Fetching data from {start} to {end}")
# Load historical data using convenience methods
print("Loading orderbook snapshots...")
deltas = await loader.load_orderbook_snapshots(
start=start,
end=end,
)
print(f"Loaded {len(deltas)} OrderBookDeltas")
print("Loading trade ticks...")
trades = await loader.load_trades(
start=start,
end=end,
)
print(f"Loaded {len(trades)} TradeTicks")
if not deltas and not trades:
raise ValueError("No historical data available for the specified time range")
# Configure backtest engine
config = BacktestEngineConfig(trader_id=TraderId("BACKTESTER-001"))
engine = BacktestEngine(config=config)
# Add venue
engine.add_venue(
venue=POLYMARKET_VENUE,
oms_type=OmsType.NETTING,
account_type=AccountType.CASH,
base_currency=USDC_POS,
starting_balances=[Money(10_000, USDC_POS)],
book_type=BookType.L2_MBP,
)
# Add instrument
engine.add_instrument(instrument)
# Add data
if deltas:
engine.add_data(deltas)
if trades:
engine.add_data(trades)
# Configure strategy
strategy_config = OrderBookImbalanceConfig(
instrument_id=instrument.id,
max_trade_size=Decimal(20),
min_seconds_between_triggers=1.0,
)
strategy = OrderBookImbalance(config=strategy_config)
engine.add_strategy(strategy=strategy)
print("\nStarting backtest...")
await asyncio.sleep(0.1)
# Run backtest
engine.run()
with pd.option_context(
"display.max_rows",
100,
"display.max_columns",
None,
"display.width",
300,
):
print(engine.trader.generate_account_report(POLYMARKET_VENUE))
print("\n")
print(engine.trader.generate_order_fills_report())
print("\n")
print(engine.trader.generate_positions_report())
# Cleanup
engine.reset()
engine.dispose()
if __name__ == "__main__":
try:
asyncio.run(
run_backtest(
market_slug=MARKET_SLUG,
lookback_hours=24, # Fetch last 24 hours of data
),
)
except Exception as e:
print(f"Error running backtest: {e}")
raise