forked from WW-shan/poly_strategy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_realtime.py
More file actions
392 lines (344 loc) · 14.4 KB
/
test_realtime.py
File metadata and controls
392 lines (344 loc) · 14.4 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import json
import sys
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from poly_strategy.realtime import (
RealtimeOrderBookStore,
kalshi_orderbook_subscription_payload,
load_watchlist_markets,
monitor_polymarket_watchlist,
polymarket_subscription_payload,
token_ids_from_watchlist,
)
class RealtimeTests(unittest.TestCase):
def test_polymarket_subscription_payload_dedupes_asset_ids(self):
payload = polymarket_subscription_payload(["yes-token", "no-token", "yes-token"])
self.assertEqual(payload["assets_ids"], ["yes-token", "no-token"])
self.assertEqual(payload["type"], "market")
self.assertTrue(payload["custom_feature_enabled"])
def test_kalshi_orderbook_subscription_payload_uses_yes_price(self):
payload = kalshi_orderbook_subscription_payload(["KXTEST-YES", "KXTEST-NO"], command_id=7)
self.assertEqual(payload["id"], 7)
self.assertEqual(payload["cmd"], "subscribe")
self.assertEqual(payload["params"]["channels"], ["orderbook_delta"])
self.assertEqual(payload["params"]["market_tickers"], ["KXTEST-YES", "KXTEST-NO"])
self.assertTrue(payload["params"]["use_yes_price"])
def test_store_applies_polymarket_book_and_price_change(self):
store = RealtimeOrderBookStore()
rows = store.apply_polymarket_message(
{
"event_type": "book",
"asset_id": "yes-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.40", "size": "5"}],
"asks": [{"price": "0.50", "size": "7"}],
}
)
change_rows = store.apply_polymarket_message(
{
"event_type": "price_change",
"market": "market-1",
"timestamp": "1710000001",
"price_changes": [
{"asset_id": "yes-token", "side": "SELL", "price": "0.49", "size": "3"},
{"asset_id": "yes-token", "side": "BUY", "price": "0.41", "size": "2"},
{"asset_id": "yes-token", "side": "SELL", "price": "0.50", "size": "0"},
],
}
)
book = store.book("yes-token")
self.assertEqual(rows[0]["best_ask"], 0.5)
self.assertEqual(change_rows[-1]["best_ask"], 0.49)
self.assertEqual(book["asks"][0].price, 0.49)
self.assertEqual(book["bids"][0].price, 0.41)
self.assertEqual(store.last_update_ts, "2024-03-09T16:00:01Z")
def test_binary_snapshot_rows_from_watchlist_books(self):
store = RealtimeOrderBookStore()
store.apply_polymarket_message(
[
{
"event_type": "book",
"asset_id": "yes-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.43", "size": "4"}],
"asks": [{"price": "0.45", "size": "10"}],
},
{
"event_type": "book",
"asset_id": "no-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.52", "size": "5"}],
"asks": [{"price": "0.53", "size": "7"}],
},
]
)
rows = store.binary_snapshot_rows(
[
{
"market_id": "market-1",
"question": "Sample?",
"fee_rate": 0.03,
"yes_token_id": "yes-token",
"no_token_id": "no-token",
}
],
ts="2026-05-09T00:00:00Z",
)
self.assertEqual(len(rows), 1)
row = rows[0]
self.assertEqual(row["type"], "binary_snapshot")
self.assertEqual(row["fee_rate"], 0.03)
self.assertEqual(row["yes"]["asks"], [[0.45, 10.0]])
self.assertEqual(row["no"]["bids"], [[0.52, 5.0]])
def test_binary_snapshot_rows_keeps_one_sided_buyable_market(self):
store = RealtimeOrderBookStore()
store.apply_polymarket_message(
[
{
"event_type": "book",
"asset_id": "yes-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [],
"asks": [{"price": "0.99", "size": "10"}],
},
{
"event_type": "book",
"asset_id": "no-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.01", "size": "10"}],
"asks": [],
},
]
)
rows = store.binary_snapshot_rows(
[
{
"market_id": "market-1",
"question": "Sample?",
"yes_token_id": "yes-token",
"no_token_id": "no-token",
}
]
)
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["yes"]["asks"], [[0.99, 10.0]])
self.assertEqual(rows[0]["no"]["asks"], [])
def test_store_can_seed_polymarket_book_before_websocket_updates(self):
store = RealtimeOrderBookStore()
row = store.seed_polymarket_book(
"yes-token",
{
"bids": [{"price": "0.40", "size": "5"}],
"asks": [{"price": "0.50", "size": "7"}],
},
ts="2026-05-10T00:00:00Z",
)
self.assertEqual(row["event_type"], "seed_book")
self.assertEqual(store.token_count, 1)
self.assertEqual(store.book("yes-token")["asks"][0].price, 0.5)
self.assertEqual(store.last_update_ts, "2026-05-10T00:00:00Z")
def test_load_watchlist_markets_and_token_ids(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "watchlist.json"
path.write_text(
json.dumps(
{
"type": "polymarket_watchlist",
"markets": [
{"yes_token_id": "yes-token", "no_token_id": "no-token"},
{"yes_token_id": "yes-token", "no_token_id": "other-no"},
],
}
)
)
markets = load_watchlist_markets(path)
self.assertEqual(token_ids_from_watchlist(markets), ["yes-token", "no-token", "other-no"])
def test_monitor_polymarket_watchlist_scans_live_snapshots(self):
messages = [
[
{
"event_type": "book",
"asset_id": "yes-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.44", "size": "5"}],
"asks": [{"price": "0.45", "size": "10"}],
},
{
"event_type": "book",
"asset_id": "no-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.52", "size": "5"}],
"asks": [{"price": "0.53", "size": "7"}],
},
]
]
fake_socket = _FakeWebSocket(messages)
connect_kwargs = []
with tempfile.TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
watchlist = tmp_path / "watchlist.json"
rules = tmp_path / "rules.json"
report = tmp_path / "report.jsonl"
updates = tmp_path / "updates.ndjson"
snapshots = tmp_path / "snapshots.ndjson"
latest_snapshots = tmp_path / "latest-snapshots.ndjson"
watchlist.write_text(
json.dumps(
{
"type": "polymarket_watchlist",
"markets": [
{
"market_id": "market-1",
"question": "Sample?",
"fee_rate": 0.0,
"yes_token_id": "yes-token",
"no_token_id": "no-token",
}
],
}
)
)
rules.write_text(json.dumps({}))
progress_rows = []
def connect(url, **kwargs):
connect_kwargs.append(kwargs)
return fake_socket
with patch.dict(sys.modules, {"websockets": SimpleNamespace(connect=connect)}):
summary = monitor_polymarket_watchlist(
watchlist,
report,
rules_path=rules,
updates_out_path=updates,
snapshots_out_path=snapshots,
latest_snapshots_out_path=latest_snapshots,
max_messages=1,
snapshot_interval_seconds=0,
stale_timeout_seconds=30,
min_net_edge=0.0,
progress=progress_rows.append,
)
report_rows = [json.loads(line) for line in report.read_text().splitlines()]
update_rows = [json.loads(line) for line in updates.read_text().splitlines()]
snapshot_rows = [json.loads(line) for line in snapshots.read_text().splitlines()]
latest_snapshot_rows = [json.loads(line) for line in latest_snapshots.read_text().splitlines()]
self.assertEqual(summary["type"], "realtime_monitor_summary")
self.assertEqual(summary["iterations_completed"], 1)
self.assertEqual(summary["opportunity_count"], 1)
self.assertEqual(summary["connection_count"], 1)
self.assertEqual(summary["reconnect_count"], 0)
self.assertEqual(progress_rows[0]["current_opportunity_count"], 1)
self.assertEqual(report_rows[0]["type"], "realtime_monitor_connection_event")
self.assertEqual(report_rows[0]["event"], "connecting")
self.assertEqual(report_rows[1]["event"], "connected")
self.assertEqual(report_rows[2]["type"], "realtime_monitor_iteration")
self.assertIn("stable_paper_rejections", report_rows[2])
self.assertEqual(report_rows[3]["type"], "realtime_monitor_summary")
self.assertEqual(connect_kwargs[0]["max_size"], 4 * 1024 * 1024)
self.assertEqual(len(update_rows), 2)
self.assertEqual(snapshot_rows[0]["type"], "binary_snapshot")
self.assertEqual(latest_snapshot_rows, snapshot_rows)
self.assertEqual(json.loads(fake_socket.sent[0])["assets_ids"], ["yes-token", "no-token"])
def test_monitor_polymarket_watchlist_reconnects_after_recv_error(self):
good_messages = [
[
{
"event_type": "book",
"asset_id": "yes-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.44", "size": "5"}],
"asks": [{"price": "0.45", "size": "10"}],
},
{
"event_type": "book",
"asset_id": "no-token",
"market": "market-1",
"timestamp": "1710000000000",
"bids": [{"price": "0.52", "size": "5"}],
"asks": [{"price": "0.53", "size": "7"}],
},
]
]
sockets = [_FailingWebSocket(RuntimeError("boom")), _FakeWebSocket(good_messages)]
def connect(url, **kwargs):
return sockets.pop(0)
with tempfile.TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
watchlist = tmp_path / "watchlist.json"
rules = tmp_path / "rules.json"
report = tmp_path / "report.jsonl"
watchlist.write_text(
json.dumps(
{
"type": "polymarket_watchlist",
"markets": [
{
"market_id": "market-1",
"fee_rate": 0.0,
"yes_token_id": "yes-token",
"no_token_id": "no-token",
}
],
}
)
)
rules.write_text(json.dumps({}))
with patch.dict(sys.modules, {"websockets": SimpleNamespace(connect=connect)}):
summary = monitor_polymarket_watchlist(
watchlist,
report,
rules_path=rules,
max_messages=1,
snapshot_interval_seconds=0,
reconnect_delay_seconds=0,
max_reconnects=1,
)
rows = [json.loads(line) for line in report.read_text().splitlines()]
self.assertEqual(summary["connection_count"], 2)
self.assertEqual(summary["reconnect_count"], 1)
self.assertEqual(summary["opportunity_count"], 1)
self.assertEqual(
[row["event"] for row in rows if row["type"] == "realtime_monitor_connection_event"],
["connecting", "connected", "disconnected", "reconnect_sleep", "connecting", "connected"],
)
class _FakeWebSocket:
def __init__(self, messages):
self._messages = list(messages)
self.sent = []
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, traceback):
return False
async def send(self, payload):
self.sent.append(payload)
def __aiter__(self):
return self
async def __anext__(self):
return await self.recv()
async def recv(self):
if not self._messages:
raise StopAsyncIteration
return json.dumps(self._messages.pop(0))
class _FailingWebSocket:
def __init__(self, exc):
self._exc = exc
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, traceback):
return False
async def send(self, payload):
return None
async def recv(self):
raise self._exc
if __name__ == "__main__":
unittest.main()