Repository navigation
Expand file tree
/
Copy pathstudent_algorithm.py
More file actions
430 lines (351 loc) · 17.8 KB
/
Copy pathstudent_algorithm.py
File metadata and controls
430 lines (351 loc) · 17.8 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""
Student Trading Algorithm Template
===================================
Connect to the exchange simulator, receive market data, and submit orders.
python student_algorithm.py --host ip:host --scenario normal_market --name your_name --password your_password --secure
YOUR TASK:
Modify the `decide_order()` method to implement your trading strategy.
"""
import json
import websocket
import threading
import argparse
import time
import requests
import ssl
import urllib3
from typing import Dict, Optional
# Suppress SSL warnings for self-signed certificates
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class TradingBot:
"""
A trading bot that connects to the exchange simulator.
Students should modify the `decide_order()` method to implement their strategy.
"""
def __init__(self, student_id: str, host: str, scenario: str, password: str = None, secure: bool = False):
self.student_id = student_id
self.host = host
self.scenario = scenario
self.password = password
self.secure = secure
# Protocol configuration
self.http_proto = "https" if secure else "http"
self.ws_proto = "wss" if secure else "ws"
# Session info (set after registration)
self.token = None
self.run_id = None
# Trading state - track your position
self.inventory = 0 # Current position (positive = long, negative = short)
self.cash_flow = 0.0 # Cumulative cash from trades (negative when buying)
self.pnl = 0.0 # Mark-to-market PnL (cash_flow + inventory * mid_price)
self.current_step = 0 # Current simulation step
self.orders_sent = 0 # Number of orders sent
# Market data
self.last_bid = 0.0
self.last_ask = 0.0
self.last_mid = 0.0
# WebSocket connections
self.market_ws = None
self.order_ws = None
self.running = True
# Latency measurement
self.last_done_time = None # When we sent DONE
self.step_latencies = [] # Time between DONE and next market data
self.order_send_times = {} # order_id -> time sent
self.fill_latencies = [] # Time between order and fill
# =========================================================================
# REGISTRATION - Get a token to start trading
# =========================================================================
def register(self) -> bool:
"""Register with the server and get an auth token."""
print(f"[{self.student_id}] Registering for scenario '{self.scenario}'...")
try:
url = f"{self.http_proto}://{self.host}/api/replays/{self.scenario}/start"
headers = {"Authorization": f"Bearer {self.student_id}"}
if self.password:
headers["X-Team-Password"] = self.password
resp = requests.get(
url,
headers=headers,
timeout=10,
verify=not self.secure # Disable SSL verification for self-signed certs
)
if resp.status_code != 200:
print(f"[{self.student_id}] Registration FAILED: {resp.text}")
return False
data = resp.json()
self.token = data.get("token")
self.run_id = data.get("run_id")
if not self.token or not self.run_id:
print(f"[{self.student_id}] Missing token or run_id")
return False
print(f"[{self.student_id}] Registered! Run ID: {self.run_id}")
return True
except Exception as e:
print(f"[{self.student_id}] Registration error: {e}")
return False
# =========================================================================
# CONNECTION - Connect to WebSocket streams
# =========================================================================
def connect(self) -> bool:
"""Connect to market data and order entry WebSockets."""
try:
# SSL options for self-signed certificates
sslopt = {"cert_reqs": ssl.CERT_NONE} if self.secure else None
# Market Data WebSocket
market_url = f"{self.ws_proto}://{self.host}/api/ws/market?run_id={self.run_id}"
self.market_ws = websocket.WebSocketApp(
market_url,
on_message=self._on_market_data,
on_error=self._on_error,
on_close=self._on_close,
on_open=lambda ws: print(f"[{self.student_id}] Market data connected")
)
# Order Entry WebSocket
order_url = f"{self.ws_proto}://{self.host}/api/ws/orders?token={self.token}&run_id={self.run_id}"
self.order_ws = websocket.WebSocketApp(
order_url,
on_message=self._on_order_response,
on_error=self._on_error,
on_close=self._on_close,
on_open=lambda ws: print(f"[{self.student_id}] Order entry connected")
)
# Start WebSocket threads
threading.Thread(
target=lambda: self.market_ws.run_forever(sslopt=sslopt),
daemon=True
).start()
threading.Thread(
target=lambda: self.order_ws.run_forever(sslopt=sslopt),
daemon=True
).start()
# Wait for connections
time.sleep(1)
return True
except Exception as e:
print(f"[{self.student_id}] Connection error: {e}")
return False
# =========================================================================
# MARKET DATA HANDLER - Called when new market data arrives
# =========================================================================
def _on_market_data(self, ws, message: str):
"""Handle incoming market data snapshot."""
try:
recv_time = time.time()
data = json.loads(message)
# Skip connection confirmation messages
if data.get("type") == "CONNECTED":
return
# Measure step latency (time since we sent DONE)
if self.last_done_time is not None:
step_latency = (recv_time - self.last_done_time) * 1000 # ms
self.step_latencies.append(step_latency)
# Extract market data
self.current_step = data.get("step", 0)
self.last_bid = data.get("bid", 0.0)
self.last_ask = data.get("ask", 0.0)
# Log progress every 500 steps with latency stats
if self.current_step % 500 == 0 and self.step_latencies:
avg_lat = sum(self.step_latencies[-100:]) / min(len(self.step_latencies), 100)
print(f"[{self.student_id}] Step {self.current_step} | Orders: {self.orders_sent} | Inv: {self.inventory} | Avg Latency: {avg_lat:.1f}ms")
# Calculate mid price
if self.last_bid > 0 and self.last_ask > 0:
self.last_mid = (self.last_bid + self.last_ask) / 2
elif self.last_bid > 0:
self.last_mid = self.last_bid
elif self.last_ask > 0:
self.last_mid = self.last_ask
else:
self.last_mid = 0
# =============================================
# YOUR STRATEGY LOGIC GOES HERE
# =============================================
order = self.decide_order(self.last_bid, self.last_ask, self.last_mid)
if order and self.order_ws and self.order_ws.sock:
self._send_order(order)
# Signal DONE to advance to next step
self._send_done()
except Exception as e:
print(f"[{self.student_id}] Market data error: {e}")
# =========================================================================
# YOUR STRATEGY - MODIFY THIS METHOD!
# =========================================================================
def decide_order(self, bid: float, ask: float, mid: float) -> Optional[Dict]:
"""
╔══════════════════════════════════════════════════════════════════╗
║ YOUR STRATEGY GOES HERE! ║
╠══════════════════════════════════════════════════════════════════╣
║ Input: ║
║ - bid: Best bid price ║
║ - ask: Best ask price ║
║ - mid: Mid price (average of bid and ask) ║
║ ║
║ Available state: ║
║ - self.inventory: Your current position ║
║ - self.pnl: Your realized PnL ║
║ - self.current_step: Current simulation step ║
║ ║
║ Return: ║
║ - {"side": "BUY"|"SELL", "price": X, "qty": N} ║
║ - Or return None to not send an order ║
╚══════════════════════════════════════════════════════════════════╝
"""
# Skip if no valid prices
if mid <= 0 or bid <= 0 or ask <= 0:
return None
# =================================================================
# EXAMPLE STRATEGY: Conservative trading
#
# - Cross the spread aggressively to get fills
# - Manage inventory by alternating buy/sell
# =================================================================
# Only trade every 50 steps to avoid hitting order limits
if self.current_step % 50 != 0:
return None
# If we're too long, sell aggressively (hit the bid)
if self.inventory > 200:
return {"side": "SELL", "price": round(bid, 2), "qty": 100}
# If we're too short, buy aggressively (lift the offer)
elif self.inventory < -200:
return {"side": "BUY", "price": round(ask, 2), "qty": 100}
# Otherwise, alternate buy/sell to demonstrate trading
elif (self.current_step // 50) % 2 == 0:
# Buy aggressively (cross the spread)
return {"side": "BUY", "price": round(ask, 2), "qty": 100}
else:
# Sell aggressively (cross the spread)
return {"side": "SELL", "price": round(bid, 2), "qty": 100}
# =========================================================================
# ORDER HANDLING
# =========================================================================
def _send_order(self, order: Dict):
"""Send an order to the exchange."""
order_id = f"ORD_{self.student_id}_{self.current_step}_{self.orders_sent}"
msg = {
"order_id": order_id,
"side": order["side"],
"price": order["price"],
"qty": order["qty"]
}
try:
self.order_send_times[order_id] = time.time() # Track send time
self.order_ws.send(json.dumps(msg))
self.orders_sent += 1
except Exception as e:
print(f"[{self.student_id}] Send order error: {e}")
def _send_done(self):
"""Signal DONE to advance to the next simulation step."""
try:
self.order_ws.send(json.dumps({"action": "DONE"}))
self.last_done_time = time.time() # Track when we sent DONE
except:
pass
def _on_order_response(self, ws, message: str):
"""Handle order responses and fills."""
try:
recv_time = time.time()
data = json.loads(message)
msg_type = data.get("type")
if msg_type == "AUTHENTICATED":
print(f"[{self.student_id}] Authenticated - ready to trade!")
elif msg_type == "FILL":
qty = data.get("qty", 0)
price = data.get("price", 0)
side = data.get("side", "")
order_id = data.get("order_id", "")
# Measure fill latency
if order_id in self.order_send_times:
fill_latency = (recv_time - self.order_send_times[order_id]) * 1000 # ms
self.fill_latencies.append(fill_latency)
del self.order_send_times[order_id]
# Update inventory and cash flow
if side == "BUY":
self.inventory += qty
self.cash_flow -= qty * price # Spent cash to buy
else:
self.inventory -= qty
self.cash_flow += qty * price # Received cash from selling
# Calculate mark-to-market PnL using mid price
self.pnl = self.cash_flow + self.inventory * self.last_mid
print(f"[{self.student_id}] FILL: {side} {qty} @ {price:.2f} | Inventory: {self.inventory} | PnL: {self.pnl:.2f}")
elif msg_type == "ERROR":
print(f"[{self.student_id}] ERROR: {data.get('message')}")
except Exception as e:
print(f"[{self.student_id}] Order response error: {e}")
# =========================================================================
# ERROR HANDLING
# =========================================================================
def _on_error(self, ws, error):
if self.running:
print(f"[{self.student_id}] WebSocket error: {error}")
def _on_close(self, ws, close_status_code, close_msg):
self.running = False
print(f"[{self.student_id}] Connection closed (status: {close_status_code})")
# =========================================================================
# MAIN RUN LOOP
# =========================================================================
def run(self):
"""Main entry point - register, connect, and run."""
# Step 1: Register
if not self.register():
return
# Step 2: Connect
if not self.connect():
return
# Step 3: Run until complete
print(f"[{self.student_id}] Running... Press Ctrl+C to stop")
try:
while self.running:
time.sleep(1)
except KeyboardInterrupt:
print(f"\n[{self.student_id}] Stopped by user")
finally:
self.running = False
if self.market_ws:
self.market_ws.close()
if self.order_ws:
self.order_ws.close()
print(f"\n[{self.student_id}] Final Results:")
print(f" Orders Sent: {self.orders_sent}")
print(f" Inventory: {self.inventory}")
print(f" PnL: {self.pnl:.2f}")
# Print latency statistics
if self.step_latencies:
print(f"\n Step Latency (ms):")
print(f" Min: {min(self.step_latencies):.1f}")
print(f" Max: {max(self.step_latencies):.1f}")
print(f" Avg: {sum(self.step_latencies)/len(self.step_latencies):.1f}")
if self.fill_latencies:
print(f"\n Fill Latency (ms):")
print(f" Min: {min(self.fill_latencies):.1f}")
print(f" Max: {max(self.fill_latencies):.1f}")
print(f" Avg: {sum(self.fill_latencies)/len(self.fill_latencies):.1f}")
# =============================================================================
# MAIN ENTRY POINT
# =============================================================================
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Student Trading Algorithm",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
Local server:
python student_algorithm.py --name team_alpha --password secret123 --scenario normal_market
Deployed server (HTTPS):
python student_algorithm.py --name team_alpha --password secret123 --scenario normal_market --host 3.98.52.120:8433 --secure
"""
)
parser.add_argument("--name", required=True, help="Your team name")
parser.add_argument("--password", required=True, help="Your team password")
parser.add_argument("--scenario", default="normal_market", help="Scenario to run")
parser.add_argument("--host", default="localhost:8080", help="Server host:port")
parser.add_argument("--secure", action="store_true", help="Use HTTPS/WSS (for deployed servers)")
args = parser.parse_args()
bot = TradingBot(
student_id=args.name,
host=args.host,
scenario=args.scenario,
password=args.password,
secure=args.secure
)
bot.run()