-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdisorderBook_book.py
More file actions
584 lines (450 loc) · 19.8 KB
/
disorderBook_book.py
File metadata and controls
584 lines (450 loc) · 19.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
import bisect
import datetime
import json
from disorderBook_ws import WebsocketMessage, WS_Messages, TICKER, EXECUTION
EXECUTION_TEMPLATE = '''
{{
"ok": true,
"account": "{}",
"venue": "{}",
"symbol": "{}",
"order": {},
"standingId": {},
"incomingId": {},
"price": {},
"filled": {},
"filledAt": "{}",
"standingComplete": {},
"incomingComplete": {}
}}
'''
def current_timestamp():
ts = str(datetime.datetime.utcnow().isoformat()) + 'Z' # Thanks to medecau for this
return ts
class Position():
def __init__(self):
self.cents = 0
self._shares = 0
self._min = 0
self._max = 0
@property
def shares(self):
return self._shares
@shares.setter
def shares(self, shares):
self._shares = shares
if shares < self._min:
self._min = shares
if shares > self._max:
self._max = shares
@property
def minimum(self):
return self._min
@property
def maximum(self):
return self._max
class Order (dict):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# All the comparisons are just for bisection insorting. Order should compare lower if it has higher
# priority, which is confusing but whatever. It means high priority orders are sorted first.
def __eq__(self, other):
if self["price"] == other["price"] and self["ts"] == other["ts"]:
return True
else:
return False
def __lt__(self, other):
if self["direction"] == "buy":
if self["price"] > other["price"]: # We beat the other price, so we are "less" (low is better)
return True
elif self["price"] < other["price"]: # Other price beats us, so we are "more" (high is worse)
return False
elif self["ts"] < other["ts"]: # Our order was first, so we are "less" (low is better)
return True
else:
return False
else:
if self["price"] < other["price"]: # We beat the other price, so we are "less" (low is better)
return True
elif self["price"] > other["price"]: # Other price beats us, so we are "more" (high is worse)
return False
elif self["ts"] < other["ts"]: # Our order was first, so we are "less" (low is better)
return True
else:
return False
def __le__(self, other):
if self < other or self == other:
return True
else:
return False
def __gt__(self, other):
if self <= other:
return False
else:
return True
def __ge__(self, other):
if self > other or self == other:
return True
else:
return False
def __ne__(self, other):
if not self == other:
return True
else:
return False
# For the orderbook itself, the general plan is to keep a list of bids and a list of asks,
# always *kept* sorted (never sorted as a whole), with the top priority order first in line.
# Incoming orders can then just iterate through the list until they're finished crossing.
class OrderBook ():
def __init__(self, venue, symbol, websockets_flag):
self.venue = str(venue)
self.symbol = str(symbol)
self.websockets_flag = websockets_flag
self.starttime = current_timestamp()
self.bids = []
self.asks = []
self.id_lookup_table = dict() # order id ---> order object
self.account_order_lists = dict() # account name ---> list of order objects
self.next_id = 0
self.quote = dict()
self.positions = dict()
self.init_quote()
def account_from_order_id(self, id):
try:
return self.id_lookup_table[id]["account"]
except KeyError:
return None
def cleanup_closed_bids(self):
self.bids = [bid for bid in self.bids if bid["open"]]
def cleanup_closed_asks(self):
self.asks = [ask for ask in self.asks if ask["open"]]
def cleanup_closed_orders(self):
self.cleanup_closed_bids()
self.cleanup_closed_asks()
def get_book(self):
ret = dict()
ret["ok"] = True
ret["venue"] = self.venue
ret["symbol"] = self.symbol
ret["bids"] = [{"price": order["price"], "qty": order["qty"], "isBuy": True} for order in self.bids]
ret["asks"] = [{"price": order["price"], "qty": order["qty"], "isBuy": False} for order in self.asks]
ret["ts"] = current_timestamp()
return ret
def get_status(self, id):
return self.id_lookup_table[id]
def get_all_orders(self, account):
if account in self.account_order_lists:
return {"ok": True, "venue": self.venue, "orders": self.account_order_lists[account]}
else:
return {"ok": True, "venue": self.venue, "orders": []}
def get_quote(self): # Used by the frontend for historical reasons
return self.quote
def init_quote(self):
self.quote["ok"] = True
self.quote["venue"] = self.venue
self.quote["symbol"] = self.symbol
self.quote["bidDepth"] = 0
self.quote["bidSize"] = 0
self.quote["askDepth"] = 0
self.quote["askSize"] = 0
self.quote["quoteTime"] = current_timestamp()
def bid_size(self):
if len(self.bids) == 0:
return 0
ret = 0
bestprice = self.bids[0]["price"]
for order in self.bids:
if order["price"] == bestprice:
ret += order["qty"]
else:
break
return ret
def ask_size(self):
if len(self.asks) == 0:
return 0
ret = 0
bestprice = self.asks[0]["price"]
for order in self.asks:
if order["price"] == bestprice:
ret += order["qty"]
else:
break
return ret
def fok_can_buy(self, price, qty):
avail = 0
for standing in self.asks:
if standing["price"] <= price:
avail += standing["qty"]
if avail >= qty:
break
else:
break # Taking advantage of list sortedness
if avail >= qty:
return True
else:
return False
def fok_can_sell(self, price, qty):
avail = 0
for standing in self.bids:
if standing["price"] >= price:
avail += standing["qty"]
if avail >= qty:
break
else:
break # Taking advantage of list sortedness
if avail >= qty:
return True
else:
return False
def cancel_order(self, id):
order = self.id_lookup_table[id]
if order["open"]:
qty_outstanding = order["qty"]
order["qty"] = 0
order["open"] = False
self.cleanup_closed_orders()
# Fix the quote...
self.quote["quoteTime"] = current_timestamp()
if order["direction"] == "buy":
if self.bids:
self.quote["bidDepth"] -= qty_outstanding
bestprice = self.bids[0]["price"]
if order["price"] == bestprice:
self.quote["bidSize"] -= qty_outstanding
elif order["price"] > bestprice: # Best order was cancelled
self.quote["bidSize"] = self.bid_size()
self.quote["bid"] = self.bids[0]["price"]
else:
self.quote["bidDepth"] = 0
self.quote["bidSize"] = 0
if "bid" in self.quote:
self.quote.pop("bid")
else:
if self.asks:
self.quote["askDepth"] -= qty_outstanding
bestprice = self.asks[0]["price"]
if order["price"] == bestprice:
self.quote["askSize"] -= qty_outstanding
elif order["price"] < bestprice: # Best order was cancelled
self.quote["askSize"] = self.ask_size()
self.quote["ask"] = self.asks[0]["price"]
else:
self.quote["askDepth"] = 0
self.quote["askSize"] = 0
if "ask" in self.quote:
self.quote.pop("ask")
if self.websockets_flag:
self.create_ticker_message()
return order
def create_ticker_message(self):
msg = '{"ok": true, "quote": ' + json.dumps(self.quote) + '}'
ticker_msg_obj = WebsocketMessage(account = "NONE", venue = self.venue, symbol = self.symbol, msgtype = TICKER, msg = msg)
WS_Messages.put(ticker_msg_obj)
def parse_order(self, data):
# We now assume symbol and venue are correct for this book. Caller's responsibility.
# The caller should be prepared to handle KeyError, TypeError and ValueError
# Official Stockfighter recognises lowercase ordertype:
try:
orderType = data["orderType"]
except KeyError:
orderType = data["ordertype"] # Could re-raise KeyError
# Official stockfighter accepts "fok" and "ioc" as legit orderType:
if orderType == "fok":
orderType = "fill-or-kill"
elif orderType == "ioc":
orderType = "immediate-or-cancel"
# The following can raise KeyError:
account = data["account"]
price = data["price"]
qty = data["qty"]
direction = data["direction"]
# Official SF sets price to 0 on market orders:
if orderType == "market":
price = 0
price = int(price) # Could raise TypeError
qty = int(qty) # Could raise TypeError
if price < 0:
raise ValueError
if qty <= 0:
raise ValueError
if direction not in ("buy", "sell"):
raise ValueError
if orderType not in ("limit", "market", "fill-or-kill", "immediate-or-cancel"):
raise ValueError
id = self.next_id
self.next_id += 1
order = Order(
ok = True,
venue = self.venue,
symbol = self.symbol,
direction = direction,
originalQty = qty,
qty = qty,
price = price,
orderType = orderType,
id = id,
account = account,
ts = current_timestamp(),
fills = list(),
totalFilled = 0,
open = True
)
self.id_lookup_table[id] = order # So we can find it for status/cancel
if account not in self.account_order_lists:
self.account_order_lists[account] = list()
self.account_order_lists[account].append(order) # So we can list all an account's orders
# Limit, Market, and IOC orders are easy...
if orderType in ("limit", "immediate-or-cancel", "market"):
self.run_order(order)
# FOK orders are slightly tricky...
elif orderType == "fill-or-kill":
if direction == "buy":
if self.fok_can_buy(price = price, qty = qty):
self.run_order(order)
else:
if self.fok_can_sell(price = price, qty = qty):
self.run_order(order)
# Limit orders may have been placed on the book, the rest may need to be closed...
if order["orderType"] != "limit":
order["qty"] = 0
order["open"] = False
return order
def run_order(self, incoming):
incomingprice = incoming["price"]
timestamp = current_timestamp()
lastprice = 0
lastqty = 0
if incoming["direction"] == "sell":
for standing in self.bids:
if standing["price"] >= incomingprice or incoming["orderType"] == "market":
lastprice, lastqty = self.order_cross(standing = standing, incoming = incoming, timestamp = timestamp)
if incoming["qty"] == 0:
break
else:
break # Taking advantage of the sortedness of the book's lists
self.cleanup_closed_bids()
else:
for standing in self.asks:
if standing["price"] <= incomingprice or incoming["orderType"] == "market":
lastprice, lastqty = self.order_cross(standing = standing, incoming = incoming, timestamp = timestamp)
if incoming["qty"] == 0:
break
else:
break # Taking advantage of the sortedness of the book's lists
self.cleanup_closed_asks()
# Limit orders rest on the book (also must adjust quote for their half of the book)....
if incoming["orderType"] == "limit":
if incoming["open"]:
if incoming["direction"] == "buy":
if self.bids:
old_bestprice = self.bids[0]["price"]
else:
old_bestprice = None
bisect.insort(self.bids, incoming)
self.quote["bidDepth"] += incoming["qty"]
if incoming["price"] == old_bestprice:
self.quote["bidSize"] += incoming["qty"]
elif old_bestprice is None or incoming["price"] > old_bestprice: # New order is best
self.quote["bidSize"] = incoming["qty"]
self.quote["bid"] = incoming["price"]
else:
if self.asks:
old_bestprice = self.asks[0]["price"]
else:
old_bestprice = None
bisect.insort(self.asks, incoming)
self.quote["askDepth"] += incoming["qty"]
if incoming["price"] == old_bestprice:
self.quote["askSize"] += incoming["qty"]
elif old_bestprice is None or incoming["price"] < old_bestprice: # New order is best
self.quote["askSize"] = incoming["qty"]
self.quote["ask"] = incoming["price"]
self.quote["quoteTime"] = timestamp # Always do this
# Check if there were any crosses; if so we need to do more quote setting...
if incoming["totalFilled"]:
if incoming["direction"] == "sell":
if self.bids:
self.quote["bid"] = self.bids[0]["price"]
self.quote["bidSize"] = self.bid_size()
self.quote["bidDepth"] -= incoming["totalFilled"]
else:
if "bid" in self.quote:
self.quote.pop("bid")
self.quote["bidSize"] = 0
self.quote["bidDepth"] = 0
else:
if self.asks:
self.quote["ask"] = self.asks[0]["price"]
self.quote["askSize"] = self.ask_size()
self.quote["askDepth"] -= incoming["totalFilled"]
else:
if "ask" in self.quote:
self.quote.pop("ask")
self.quote["askSize"] = 0
self.quote["askDepth"] = 0
self.quote["last"] = lastprice
self.quote["lastSize"] = lastqty
self.quote["lastTrade"] = timestamp
# And fire off a websocket message...
if self.websockets_flag:
self.create_ticker_message()
return incoming
def update_scores_from_cross(self, standing, incoming, quantity, price):
s_account = standing["account"]
i_account = incoming["account"]
if s_account not in self.positions:
self.positions[s_account] = Position()
if i_account not in self.positions:
self.positions[i_account] = Position()
if s_account != i_account: # Buying one's own shares does nothing
s_pos = self.positions[s_account]
i_pos = self.positions[i_account]
if standing["direction"] == "buy":
s_pos.shares += quantity
s_pos.cents -= quantity * price
i_pos.shares -= quantity
i_pos.cents += quantity * price
else:
s_pos.shares -= quantity
s_pos.cents += quantity * price
i_pos.shares += quantity
i_pos.cents -= quantity * price
def create_execution_messages(self, standing, incoming, quantity, price, timestamp):
standing_execution_msg = EXECUTION_TEMPLATE.format(
standing["account"], self.venue, self.symbol, json.dumps(standing),
standing["id"], incoming["id"], price, quantity, timestamp,
"false" if standing["open"] else "true", "false" if incoming["open"] else "true")
incoming_execution_msg = EXECUTION_TEMPLATE.format(
incoming["account"], self.venue, self.symbol, json.dumps(incoming),
standing["id"], incoming["id"], price, quantity, timestamp,
"false" if standing["open"] else "true", "false" if incoming["open"] else "true")
standing_msg_obj = WebsocketMessage(
account = standing["account"],
venue = self.venue,
symbol = self.symbol,
msgtype = EXECUTION,
msg = standing_execution_msg)
incoming_msg_obj = WebsocketMessage(
account = incoming["account"],
venue = self.venue,
symbol = self.symbol,
msgtype = EXECUTION,
msg = incoming_execution_msg)
WS_Messages.put(standing_msg_obj)
WS_Messages.put(incoming_msg_obj)
def order_cross(self, standing, incoming, timestamp):
quantity = min(standing["qty"], incoming["qty"])
standing["qty"] -= quantity
standing["totalFilled"] += quantity
incoming["qty"] -= quantity
incoming["totalFilled"] += quantity
price = standing["price"]
fill = dict(price = price, qty = quantity, ts = timestamp)
for o in standing, incoming:
o["fills"].append(fill)
if o["qty"] == 0:
o["open"] = False
self.update_scores_from_cross(standing, incoming, quantity, price)
if self.websockets_flag:
self.create_execution_messages(standing, incoming, quantity, price, timestamp)
return (price, quantity)