forked from davecliff/BristolStockExchange
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnashall2019.py
2197 lines (1843 loc) · 106 KB
/
snashall2019.py
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# BSE: The Bristol Stock Exchange
#
# Version 1.3; July 21st, 2018.
# Version 1.2; November 17th, 2012.
#
# Copyright (c) 2012-2018, Dave Cliff
#
#
# ------------------------
#
# MIT Open-Source License:
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# ------------------------
#
#
#
# BSE is a very simple simulation of automated execution traders
# operating on a very simple model of a limit order book (LOB) exchange
#
# major simplifications in this version:
# (a) only one financial instrument being traded
# (b) traders can only trade contracts of size 1 (will add variable quantities later)
# (c) each trader can have max of one order per single orderbook.
# (d) traders can replace/overwrite earlier orders, and/or can cancel
# (d) simply processes each order in sequence and republishes LOB to all traders
# => no issues with exchange processing latency/delays or simultaneously issued orders.
#
# NB this code has been written to be readable/intelligible, not efficient!
# could import pylab here for graphing etc
import sys
import math
import random
bse_sys_minprice = 1 # minimum price in the system, in cents/pennies
bse_sys_maxprice = 1000 # maximum price in the system, in cents/pennies
ticksize = 1 # minimum change in price, in cents/pennies
# an Order/quote has a trader id, a type (buy/sell) price, quantity, timestamp, and unique i.d.
class Order:
def __init__(self, tid, otype, price, qty, time, qid):
self.tid = tid # trader i.d.
self.otype = otype # order type
self.price = price # price
self.qty = qty # quantity
self.time = time # timestamp
self.qid = qid # quote i.d. (unique to each quote)
def __str__(self):
return '[%s %s P=%03d Q=%s T=%5.2f QID:%d]' % \
(self.tid, self.otype, self.price, self.qty, self.time, self.qid)
# Orderbook_half is one side of the book: a list of bids or a list of asks, each sorted best-first
class Orderbook_half:
def __init__(self, booktype, worstprice):
# booktype: bids or asks?
self.booktype = booktype
# dictionary of orders received, indexed by Trader ID
self.orders = {}
# limit order book, dictionary indexed by price, with order info
self.lob = {}
# anonymized LOB, lists, with only price/qty info
self.lob_anon = []
# summary stats
self.best_price = None
self.best_tid = None
self.worstprice = worstprice
self.n_orders = 0 # how many orders?
self.lob_depth = 0 # how many different prices on lob?
def anonymize_lob(self):
# anonymize a lob, strip out order details, format as a sorted list
# NB for asks, the sorting should be reversed
self.lob_anon = []
for price in sorted(self.lob):
qty = self.lob[price][0]
self.lob_anon.append([price, qty])
def build_lob(self):
lob_verbose = False
# take a list of orders and build a limit-order-book (lob) from it
# NB the exchange needs to know arrival times and trader-id associated with each order
# returns lob as a dictionary (i.e., unsorted)
# also builds anonymized version (just price/quantity, sorted, as a list) for publishing to traders
self.lob = {}
for tid in self.orders:
order = self.orders.get(tid)
price = order.price
if price in self.lob:
# update existing entry
qty = self.lob[price][0]
orderlist = self.lob[price][1]
orderlist.append([order.time, order.qty, order.tid, order.qid])
self.lob[price] = [qty + order.qty, orderlist]
else:
# create a new dictionary entry
self.lob[price] = [order.qty, [[order.time, order.qty, order.tid, order.qid]]]
# create anonymized version
self.anonymize_lob()
# record best price and associated trader-id
if len(self.lob) > 0 :
if self.booktype == 'Bid':
self.best_price = self.lob_anon[-1][0]
else :
self.best_price = self.lob_anon[0][0]
self.best_tid = self.lob[self.best_price][1][0][2]
else :
self.best_price = None
self.best_tid = None
if lob_verbose : print self.lob
def book_add(self, order):
# add order to the dictionary holding the list of orders
# either overwrites old order from this trader
# or dynamically creates new entry in the dictionary
# so, max of one order per trader per list
# checks whether length or order list has changed, to distinguish addition/overwrite
#print('book_add > %s %s' % (order, self.orders))
n_orders = self.n_orders
self.orders[order.tid] = order
self.n_orders = len(self.orders)
self.build_lob()
#print('book_add < %s %s' % (order, self.orders))
if n_orders != self.n_orders :
return('Addition')
else:
return('Overwrite')
def book_del(self, order):
# delete order from the dictionary holding the orders
# assumes max of one order per trader per list
# checks that the Trader ID does actually exist in the dict before deletion
# print('book_del %s',self.orders)
if self.orders.get(order.tid) != None :
del(self.orders[order.tid])
self.n_orders = len(self.orders)
self.build_lob()
# print('book_del %s', self.orders)
def delete_best(self):
# delete order: when the best bid/ask has been hit, delete it from the book
# the TraderID of the deleted order is return-value, as counterparty to the trade
best_price_orders = self.lob[self.best_price]
best_price_qty = best_price_orders[0]
best_price_counterparty = best_price_orders[1][0][2]
if best_price_qty == 1:
# here the order deletes the best price
del(self.lob[self.best_price])
del(self.orders[best_price_counterparty])
self.n_orders = self.n_orders - 1
if self.n_orders > 0:
if self.booktype == 'Bid':
self.best_price = max(self.lob.keys())
else:
self.best_price = min(self.lob.keys())
self.lob_depth = len(self.lob.keys())
else:
self.best_price = self.worstprice
self.lob_depth = 0
else:
# best_bid_qty>1 so the order decrements the quantity of the best bid
# update the lob with the decremented order data
self.lob[self.best_price] = [best_price_qty - 1, best_price_orders[1][1:]]
# update the bid list: counterparty's bid has been deleted
del(self.orders[best_price_counterparty])
self.n_orders = self.n_orders - 1
self.build_lob()
return best_price_counterparty
# Orderbook for a single instrument: list of bids and list of asks
class Orderbook(Orderbook_half):
def __init__(self):
self.bids = Orderbook_half('Bid', bse_sys_minprice)
self.asks = Orderbook_half('Ask', bse_sys_maxprice)
self.tape = []
self.quote_id = 0 #unique ID code for each quote accepted onto the book
# Exchange's internal orderbook
class Exchange(Orderbook):
def add_order(self, order, verbose):
# add a quote/order to the exchange and update all internal records; return unique i.d.
order.qid = self.quote_id
self.quote_id = order.qid + 1
# if verbose : print('QUID: order.quid=%d self.quote.id=%d' % (order.qid, self.quote_id))
tid = order.tid
if order.otype == 'Bid':
response=self.bids.book_add(order)
best_price = self.bids.lob_anon[-1][0]
self.bids.best_price = best_price
self.bids.best_tid = self.bids.lob[best_price][1][0][2]
else:
response=self.asks.book_add(order)
best_price = self.asks.lob_anon[0][0]
self.asks.best_price = best_price
self.asks.best_tid = self.asks.lob[best_price][1][0][2]
return [order.qid, response]
def del_order(self, time, order, verbose):
# delete a trader's quot/order from the exchange, update all internal records
tid = order.tid
if order.otype == 'Bid':
self.bids.book_del(order)
if self.bids.n_orders > 0 :
best_price = self.bids.lob_anon[-1][0]
self.bids.best_price = best_price
self.bids.best_tid = self.bids.lob[best_price][1][0][2]
else: # this side of book is empty
self.bids.best_price = None
self.bids.best_tid = None
cancel_record = { 'type': 'Cancel', 'time': time, 'order': order }
self.tape.append(cancel_record)
elif order.otype == 'Ask':
self.asks.book_del(order)
if self.asks.n_orders > 0 :
best_price = self.asks.lob_anon[0][0]
self.asks.best_price = best_price
self.asks.best_tid = self.asks.lob[best_price][1][0][2]
else: # this side of book is empty
self.asks.best_price = None
self.asks.best_tid = None
cancel_record = { 'type': 'Cancel', 'time': time, 'order': order }
self.tape.append(cancel_record)
else:
# neither bid nor ask?
sys.exit('bad order type in del_quote()')
def process_order2(self, time, order, verbose):
# receive an order and either add it to the relevant LOB (ie treat as limit order)
# or if it crosses the best counterparty offer, execute it (treat as a market order)
oprice = order.price
counterparty = None
[qid, response] = self.add_order(order, verbose) # add it to the order lists -- overwriting any previous order
order.qid = qid
if verbose :
print('QUID: order.quid=%d' % order.qid)
print('RESPONSE: %s' % response)
best_ask = self.asks.best_price
best_ask_tid = self.asks.best_tid
best_bid = self.bids.best_price
best_bid_tid = self.bids.best_tid
if order.otype == 'Bid':
if self.asks.n_orders > 0 and best_bid >= best_ask:
# bid lifts the best ask
if verbose: print("Bid $%s lifts best ask" % oprice)
counterparty = best_ask_tid
price = best_ask # bid crossed ask, so use ask price
if verbose: print('counterparty, price', counterparty, price)
# delete the ask just crossed
self.asks.delete_best()
# delete the bid that was the latest order
self.bids.delete_best()
elif order.otype == 'Ask':
if self.bids.n_orders > 0 and best_ask <= best_bid:
# ask hits the best bid
if verbose: print("Ask $%s hits best bid" % oprice)
# remove the best bid
counterparty = best_bid_tid
price = best_bid # ask crossed bid, so use bid price
if verbose: print('counterparty, price', counterparty, price)
# delete the bid just crossed, from the exchange's records
self.bids.delete_best()
# delete the ask that was the latest order, from the exchange's records
self.asks.delete_best()
else:
# we should never get here
sys.exit('process_order() given neither Bid nor Ask')
# NB at this point we have deleted the order from the exchange's records
# but the two traders concerned still have to be notified
if verbose: print('counterparty %s' % counterparty)
if counterparty != None:
# process the trade
if verbose: print('>>>>>>>>>>>>>>>>>TRADE t=%5.2f $%d %s %s' % (time, price, counterparty, order.tid))
transaction_record = { 'type': 'Trade',
'time': time,
'price': price,
'party1':counterparty,
'party2':order.tid,
'qty': order.qty
}
self.tape.append(transaction_record)
return transaction_record
else:
return None
def tape_dump(self, fname, fmode, tmode):
dumpfile = open(fname, fmode)
for tapeitem in self.tape:
if tapeitem['type'] == 'Trade' :
dumpfile.write('%s, %s\n' % (tapeitem['time'], tapeitem['price']))
dumpfile.close()
if tmode == 'wipe':
self.tape = []
# this returns the LOB data "published" by the exchange,
# i.e., what is accessible to the traders
def publish_lob(self, time, verbose):
public_data = {}
public_data['time'] = time
public_data['bids'] = {'best':self.bids.best_price,
'worst':self.bids.worstprice,
'n': self.bids.n_orders,
'lob':self.bids.lob_anon}
public_data['asks'] = {'best':self.asks.best_price,
'worst':self.asks.worstprice,
'n': self.asks.n_orders,
'lob':self.asks.lob_anon}
public_data['QID'] = self.quote_id
public_data['tape'] = self.tape
if verbose:
print('publish_lob: t=%d' % time)
print('BID_lob=%s' % public_data['bids']['lob'])
# print('best=%s; worst=%s; n=%s ' % (self.bids.best_price, self.bids.worstprice, self.bids.n_orders))
print('ASK_lob=%s' % public_data['asks']['lob'])
# print('qid=%d' % self.quote_id)
return public_data
##################--Traders below here--#############
# Trader superclass
# all Traders have a trader id, bank balance, blotter, and list of orders to execute
class Trader:
def __init__(self, ttype, tid, balance, time):
self.ttype = ttype # what type / strategy this trader is
self.tid = tid # trader unique ID code
self.balance = balance # money in the bank
self.blotter = [] # record of trades executed
self.orders = [] # customer orders currently being worked (fixed at 1)
self.n_quotes = 0 # number of quotes live on LOB
self.willing = 1 # used in ZIP etc
self.able = 1 # used in ZIP etc
self.birthtime = time # used when calculating age of a trader/strategy
self.profitpertime = 0 # profit per unit time
self.n_trades = 0 # how many trades has this trader done?
self.lastquote = None # record of what its last quote was
def __str__(self):
return '[TID %s type %s balance %s blotter %s orders %s n_trades %s profitpertime %s]' \
% (self.tid, self.ttype, self.balance, self.blotter, self.orders, self.n_trades, self.profitpertime)
def add_order(self, order, verbose):
# in this version, trader has at most one order,
# if allow more than one, this needs to be self.orders.append(order)
if self.n_quotes > 0 :
# this trader has a live quote on the LOB, from a previous customer order
# need response to signal cancellation/withdrawal of that quote
response = 'LOB_Cancel'
else:
response = 'Proceed'
self.orders = [order]
if verbose : print('add_order < response=%s' % response)
return response
def del_order(self, order):
# this is lazy: assumes each trader has only one customer order with quantity=1, so deleting sole order
# CHANGE TO DELETE THE HEAD OF THE LIST AND KEEP THE TAIL
self.orders = []
def bookkeep(self, trade, order, verbose, time):
outstr=""
for order in self.orders: outstr = outstr + str(order)
self.blotter.append(trade) # add trade record to trader's blotter
# NB What follows is **LAZY** -- assumes all orders are quantity=1
transactionprice = trade['price']
if self.orders[0].otype == 'Bid':
profit = self.orders[0].price - transactionprice
else:
profit = transactionprice - self.orders[0].price
self.balance += profit
self.n_trades += 1
self.profitpertime = self.balance/(time - self.birthtime)
if profit < 0 :
print profit
print trade
print order
sys.exit()
if verbose: print('%s profit=%d balance=%d profit/time=%d' % (outstr, profit, self.balance, self.profitpertime))
self.del_order(order) # delete the order
# specify how trader responds to events in the market
# this is a null action, expect it to be overloaded by specific algos
def respond(self, time, lob, trade, verbose):
return None
# specify how trader mutates its parameter values
# this is a null action, expect it to be overloaded by specific algos
def mutate(self, time, lob, trade, verbose):
return None
# Trader subclass Giveaway
# even dumber than a ZI-U: just give the deal away
# (but never makes a loss)
class Trader_Giveaway(Trader):
def getorder(self, time, countdown, lob):
if len(self.orders) < 1:
order = None
else:
quoteprice = self.orders[0].price
order = Order(self.tid,
self.orders[0].otype,
quoteprice,
self.orders[0].qty,
time, lob['QID'])
self.lastquote=order
return order
# Trader subclass AA
class Trader_AA(Trader):
def __init__(self, ttype, tid, balance, time):
# Stuff about trader
self.ttype = ttype
self.tid = tid
self.balance = balance
self.birthtime = time
self.profitpertime = 0
self.n_trades = 0
self.blotter = []
self.orders = []
self.n_quotes = 0
self.lastquote = None
self.limit = None
self.job = None
# learning variables
self.r_shout_change_relative = 0.05
self.r_shout_change_absolute = 0.05
self.short_term_learning_rate = random.uniform(0.1, 0.5)
self.long_term_learning_rate = random.uniform(0.1, 0.5)
self.moving_average_weight_decay = 0.95 # how fast weight decays with time, lower is quicker, 0.9 in vytelingum
self.moving_average_window_size = 5
self.offer_change_rate = 3.0
self.theta = -2.0
self.theta_max = 2.0
self.theta_min = -8.0
self.marketMax = bse_sys_maxprice
# Variables to describe the market
self.previous_transactions = []
self.moving_average_weights = []
for i in range(self.moving_average_window_size):
self.moving_average_weights.append(self.moving_average_weight_decay**i)
self.estimated_equilibrium = []
self.smiths_alpha = []
self.prev_best_bid_p = None
self.prev_best_bid_q = None
self.prev_best_ask_p = None
self.prev_best_ask_q = None
# Trading Variables
self.r_shout = None
self.buy_target = None
self.sell_target = None
self.buy_r = -1.0 * (0.3 * random.random())
self.sell_r = -1.0 * (0.3 * random.random())
def calcEq(self):
# Slightly modified from paper, it is unclear inpaper
# N previous transactions * weights / N in vytelingum, swap N denominator for sum of weights to be correct?
if len(self.previous_transactions) == 0:
return
elif len(self.previous_transactions) < self.moving_average_window_size:
# Not enough transactions
self.estimated_equilibrium.append(float(sum(self.previous_transactions)) / max(len(self.previous_transactions), 1))
else:
N_previous_transactions = self.previous_transactions[-self.moving_average_window_size:]
thing = [N_previous_transactions[i]*self.moving_average_weights[i] for i in range(self.moving_average_window_size)]
eq = sum( thing ) / sum(self.moving_average_weights)
self.estimated_equilibrium.append(eq)
def calcAlpha(self):
alpha = 0.0
for p in self.estimated_equilibrium:
alpha += (p - self.estimated_equilibrium[-1])**2
alpha = math.sqrt(alpha/len(self.estimated_equilibrium))
self.smiths_alpha.append( alpha/self.estimated_equilibrium[-1] )
def calcTheta(self):
gamma = 2.0 #not sensitive apparently so choose to be whatever
# necessary for intialisation, div by 0
if min(self.smiths_alpha) == max(self.smiths_alpha):
alpha_range = 0.4 #starting value i guess
else:
alpha_range = (self.smiths_alpha[-1] - min(self.smiths_alpha)) / (max(self.smiths_alpha) - min(self.smiths_alpha))
theta_range = self.theta_max - self.theta_min
desired_theta = self.theta_min + (theta_range) * (1 - (alpha_range * math.exp(gamma * (alpha_range - 1))))
self.theta = self.theta + self.long_term_learning_rate * (desired_theta - self.theta)
def calcRshout(self):
p = self.estimated_equilibrium[-1]
l = self.limit
theta = self.theta
if self.job == 'Bid':
# Currently a buyer
if l <= p: #extramarginal!
self.r_shout = 0.0
else: #intramarginal :(
if self.buy_target > self.estimated_equilibrium[-1]:
#r[0,1]
self.r_shout = math.log(((self.buy_target - p) * (math.exp(theta) - 1) / (l - p)) + 1) / theta
else:
#r[-1,0]
self.r_shout = math.log((1 - (self.buy_target/p)) * (math.exp(theta) - 1) + 1) / theta
if self.job == 'Ask':
# Currently a seller
if l >= p: #extramarginal!
self.r_shout = 0
else: #intramarginal :(
if self.sell_target > self.estimated_equilibrium[-1]:
# r[-1,0]
self.r_shout = math.log((self.sell_target - p) * (math.exp(theta) - 1) / (self.marketMax - p) + 1) / theta
else:
# r[0,1]
a = (self.sell_target-l)/(p-l)
self.r_shout = (math.log((1 - a) * (math.exp(theta) - 1) + 1)) / theta
def calcAgg(self):
delta = 0
if self.job == 'Bid':
# BUYER
if self.buy_target >= self.previous_transactions[-1] :
# must be more aggressive
delta = (1+self.r_shout_change_relative)*self.r_shout + self.r_shout_change_absolute
else :
delta = (1-self.r_shout_change_relative)*self.r_shout - self.r_shout_change_absolute
self.buy_r = self.buy_r + self.short_term_learning_rate * (delta - self.buy_r)
if self.job == 'Ask':
# SELLER
if self.sell_target > self.previous_transactions[-1] :
delta = (1+self.r_shout_change_relative)*self.r_shout + self.r_shout_change_absolute
else :
delta = (1-self.r_shout_change_relative)*self.r_shout - self.r_shout_change_absolute
self.sell_r = self.sell_r + self.short_term_learning_rate * (delta - self.sell_r)
def calcTarget(self):
if len(self.estimated_equilibrium) > 0:
p = self.estimated_equilibrium[-1]
if self.limit == p:
p = p * 1.000001 # to prevent theta_bar = 0
elif self.job == 'Bid':
p = self.limit - self.limit * 0.2 ## Initial guess for eq if no deals yet!!....
elif self.job == 'Ask':
p = self.limit + self.limit * 0.2
l = self.limit
theta = self.theta
if self.job == 'Bid':
#BUYER
minus_thing = (math.exp(-self.buy_r * theta) - 1) / (math.exp(theta) - 1)
plus_thing = (math.exp(self.buy_r * theta) - 1) / (math.exp(theta) - 1)
theta_bar = (theta * l - theta * p) / p
if theta_bar == 0:
theta_bar = 0.0001
if math.exp(theta_bar) - 1 == 0:
theta_bar = 0.0001
bar_thing = (math.exp(-self.buy_r * theta_bar) - 1) / (math.exp(theta_bar) - 1)
if l <= p: #Extramarginal
if self.buy_r >= 0:
self.buy_target = l
else:
self.buy_target = l * (1 - minus_thing)
else: #intramarginal
if self.buy_r >= 0:
self.buy_target = p + (l-p)*plus_thing
else:
self.buy_target = p*(1-bar_thing)
if self.buy_target > l:
self.buy_target = l
if self.job == 'Ask':
#SELLER
minus_thing = (math.exp(-self.sell_r * theta) - 1) / (math.exp(theta) - 1)
plus_thing = (math.exp(self.sell_r * theta) - 1) / (math.exp(theta) - 1)
theta_bar = (theta * l - theta * p) / p
if theta_bar == 0:
theta_bar = 0.0001
if math.exp(theta_bar) - 1 == 0:
theta_bar = 0.0001
bar_thing = (math.exp(-self.sell_r * theta_bar) - 1) / (math.exp(theta_bar) - 1) #div 0 sometimes what!?
if l <= p: #Extramarginal
if self.buy_r >= 0:
self.buy_target = l
else:
self.buy_target = l + (self.marketMax - l)*(minus_thing)
else: #intramarginal
if self.buy_r >= 0:
self.buy_target = l + (p-l)*(1-plus_thing)
else:
self.buy_target = p + (self.marketMax - p)*(bar_thing)
if self.sell_target < l:
self.sell_target = l
def getorder(self, time, countdown, lob):
if len(self.orders) < 1:
self.active = False
return None
else:
self.active = True
self.limit = self.orders[0].price
self.job = self.orders[0].otype
self.calcTarget()
if self.prev_best_bid_p == None:
o_bid = 0
else:
o_bid = self.prev_best_bid_p
if self.prev_best_ask_p == None:
o_ask = self.marketMax
else:
o_ask = self.prev_best_ask_p
if self.job == 'Bid': #BUYER
if self.limit <= o_bid:
return None
else:
if len(self.previous_transactions) > 0: ## has been at least one transaction
o_ask_plus = (1+self.r_shout_change_relative)*o_ask + self.r_shout_change_absolute
quoteprice = o_bid + ((min(self.limit, o_ask_plus) - o_bid) / self.offer_change_rate)
else:
if o_ask <= self.buy_target:
quoteprice = o_ask
else:
quoteprice = o_bid + ((self.buy_target - o_bid) / self.offer_change_rate)
if self.job == 'Ask':
if self.limit >= o_ask:
return None
else:
if len(self.previous_transactions) > 0: ## has been at least one transaction
o_bid_minus = (1-self.r_shout_change_relative) * o_bid - self.r_shout_change_absolute
quoteprice = o_ask - ((o_ask - max(self.limit, o_bid_minus)) / self.offer_change_rate)
else:
if o_bid >= self.sell_target:
quoteprice = o_bid
else:
quoteprice = o_ask - ((o_ask - self.sell_target) / self.offer_change_rate)
order = Order(self.tid,
self.orders[0].otype,
quoteprice,
self.orders[0].qty,
time, lob['QID'])
self.lastquote=order
return order
def respond(self, time, lob, trade, verbose):
## Begin nicked from ZIP
# what, if anything, has happened on the bid LOB? Nicked from ZIP..
bid_improved = False
bid_hit = False
lob_best_bid_p = lob['bids']['best']
lob_best_bid_q = None
if lob_best_bid_p != None:
# non-empty bid LOB
lob_best_bid_q = lob['bids']['lob'][-1][1]
if self.prev_best_bid_p < lob_best_bid_p :
# best bid has improved
# NB doesn't check if the improvement was by self
bid_improved = True
elif trade != None and ((self.prev_best_bid_p > lob_best_bid_p) or ((self.prev_best_bid_p == lob_best_bid_p) and (self.prev_best_bid_q > lob_best_bid_q))):
# previous best bid was hit
bid_hit = True
elif self.prev_best_bid_p != None:
# the bid LOB has been emptied: was it cancelled or hit?
last_tape_item = lob['tape'][-1]
if last_tape_item['type'] == 'Cancel' :
bid_hit = False
else:
bid_hit = True
# what, if anything, has happened on the ask LOB?
ask_improved = False
ask_lifted = False
lob_best_ask_p = lob['asks']['best']
lob_best_ask_q = None
if lob_best_ask_p != None:
# non-empty ask LOB
lob_best_ask_q = lob['asks']['lob'][0][1]
if self.prev_best_ask_p > lob_best_ask_p :
# best ask has improved -- NB doesn't check if the improvement was by self
ask_improved = True
elif trade != None and ((self.prev_best_ask_p < lob_best_ask_p) or ((self.prev_best_ask_p == lob_best_ask_p) and (self.prev_best_ask_q > lob_best_ask_q))):
# trade happened and best ask price has got worse, or stayed same but quantity reduced -- assume previous best ask was lifted
ask_lifted = True
elif self.prev_best_ask_p != None:
# the ask LOB is empty now but was not previously: canceled or lifted?
last_tape_item = lob['tape'][-1]
if last_tape_item['type'] == 'Cancel' :
ask_lifted = False
else:
ask_lifted = True
self.prev_best_bid_p = lob_best_bid_p
self.prev_best_bid_q = lob_best_bid_q
self.prev_best_ask_p = lob_best_ask_p
self.prev_best_ask_q = lob_best_ask_q
deal = bid_hit or ask_lifted
## End nicked from ZIP
if deal:
self.previous_transactions.append(trade['price'])
if self.sell_target == None:
self.sell_target = trade['price']
if self.buy_target == None:
self.buy_target = trade['price']
self.calcEq()
self.calcAlpha()
self.calcTheta()
self.calcRshout()
self.calcAgg()
self.calcTarget()
#print 'sell: ', self.sell_target, 'buy: ', self.buy_target, 'limit:', self.limit, 'eq: ', self.estimated_equilibrium[-1], 'sell_r: ', self.sell_r, 'buy_r: ', self.buy_r, '\n'
# Trader subclass ZI-C
# After Gode & Sunder 1993
class Trader_ZIC(Trader):
def getorder(self, time, countdown, lob):
if len(self.orders) < 1:
# no orders: return NULL
order = None
else:
minprice = lob['bids']['worst']
maxprice = lob['asks']['worst']
qid = lob['QID']
limit = self.orders[0].price
otype = self.orders[0].otype
if otype == 'Bid':
quoteprice = random.randint(minprice, limit)
else:
quoteprice = random.randint(limit, maxprice)
# NB should check it == 'Ask' and barf if not
order = Order(self.tid, otype, quoteprice, self.orders[0].qty, time, qid)
self.lastquote = order
return order
# Trader subclass Shaver
# shaves a penny off the best price
# if there is no best price, creates "stub quote" at system max/min
class Trader_Shaver(Trader):
def getorder(self, time, countdown, lob):
if len(self.orders) < 1:
order = None
else:
limitprice = self.orders[0].price
otype = self.orders[0].otype
if otype == 'Bid':
if lob['bids']['n'] > 0:
quoteprice = lob['bids']['best'] + 1
if quoteprice > limitprice :
quoteprice = limitprice
else:
quoteprice = lob['bids']['worst']
else:
if lob['asks']['n'] > 0:
quoteprice = lob['asks']['best'] - 1
if quoteprice < limitprice:
quoteprice = limitprice
else:
quoteprice = lob['asks']['worst']
order = Order(self.tid, otype, quoteprice, self.orders[0].qty, time, lob['QID'])
self.lastquote = order
return order
# Trader subclass Sniper
# Based on Shaver,
# "lurks" until time remaining < threshold% of the trading session
# then gets increasing aggressive, increasing "shave thickness" as time runs out
class Trader_Sniper(Trader):
def getorder(self, time, countdown, lob):
lurk_threshold = 0.2
shavegrowthrate = 3
shave = int(1.0 / (0.01 + countdown / (shavegrowthrate * lurk_threshold)))
if (len(self.orders) < 1) or (countdown > lurk_threshold):
order = None
else:
limitprice = self.orders[0].price
otype = self.orders[0].otype
if otype == 'Bid':
if lob['bids']['n'] > 0:
quoteprice = lob['bids']['best'] + shave
if quoteprice > limitprice :
quoteprice = limitprice
else:
quoteprice = lob['bids']['worst']
else:
if lob['asks']['n'] > 0:
quoteprice = lob['asks']['best'] - shave
if quoteprice < limitprice:
quoteprice = limitprice
else:
quoteprice = lob['asks']['worst']
order = Order(self.tid, otype, quoteprice, self.orders[0].qty, time, lob['QID'])
self.lastquote = order
return order
# Trader subclass ZIP
# After Cliff 1997
class Trader_ASAD(Trader):
# ZIP init key param-values are those used in Cliff's 1997 original HP Labs tech report
# NB this implementation keeps separate margin values for buying & selling,
# so a single trader can both buy AND sell
# -- in the original, traders were either buyers OR sellers
def __init__(self, ttype, tid, balance, time):
self.ttype = ttype
self.tid = tid
self.balance = balance
self.birthtime = time
self.profitpertime = 0
self.n_trades = 0
self.blotter = []
self.orders = []
self.prev_orders = []
self.n_quotes = 0
self.lastquote = None
self.job = None # this gets switched to 'Bid' or 'Ask' depending on order-type
self.active = False # gets switched to True while actively working an order
self.prev_change = 0 # this was called last_d in Cliff'97
self.beta = 0.1 + 0.4 * random.random()
self.momntm = 0.1 * random.random()
self.ca = 0.05 # self.ca & .cr were hard-coded in '97 but parameterised later
self.cr = 0.05
self.margin = None # this was called profit in Cliff'97
self.margin_buy = -1.0 * (0.05 + 0.3 * random.random())
self.margin_sell = 0.05 + 0.3 * random.random()
self.price = None
self.limit = None
self.phi = 0 #measure of market shock for ASAD
# memory of best price & quantity of best bid and ask, on LOB on previous update
self.prev_best_bid_p = None
self.prev_best_bid_q = None
self.prev_best_ask_p = None
self.prev_best_ask_q = None
def getorder(self, time, countdown, lob):
if len(self.orders) < 1:
self.active = False
order = None
else:
self.active = True
self.limit = self.orders[0].price
self.job = self.orders[0].otype
if self.job == 'Bid':
# currently a buyer (working a bid order)
self.margin = self.margin_buy
else:
# currently a seller (working a sell order)
self.margin = self.margin_sell
quoteprice = int(self.limit * (1 + self.margin))
self.price = quoteprice
order = Order(self.tid, self.job, quoteprice, self.orders[0].qty, time, lob['QID'])
self.lastquote = order
self.prev_orders.append(order)
return order
# update margin on basis of what happened in market
def respond(self, time, lob, trade, verbose):
# ZIP trader responds to market events, altering its margin
# does this whether it currently has an order to work or not
def target_up(price):
# generate a higher target price by randomly perturbing given price
ptrb_abs = self.ca * random.random() # absolute shift
ptrb_rel = price * (1.0 + (self.cr * random.random())) # relative shift
target = int(round(ptrb_rel + ptrb_abs, 0))
# # print('TargetUp: %d %d\n' % (price,target))
return(target)
def target_down(price):
# generate a lower target price by randomly perturbing given price
ptrb_abs = self.ca * random.random() # absolute shift
ptrb_rel = price * (1.0 - (self.cr * random.random())) # relative shift
target = int(round(ptrb_rel - ptrb_abs, 0))
# # print('TargetDn: %d %d\n' % (price,target))
return(target)
def willing_to_trade(price):
# am I willing to trade at this price?
willing = False
if self.job == 'Bid' and self.active and self.price >= price:
willing = True
if self.job == 'Ask' and self.active and self.price <= price:
willing = True
return willing
def profit_alter(price):
oldprice = self.price
diff = price - oldprice
change = ((1.0 - self.momntm) * (self.beta * diff)) + (self.momntm * self.prev_change)
self.prev_change = change
newmargin = ((self.price + change) / self.limit) - 1.0
if self.job == 'Bid':
if newmargin < 0.0 :
self.margin_buy = newmargin
self.margin = newmargin
else :
if newmargin > 0.0 :
self.margin_sell = newmargin
self.margin = newmargin
# set the price from limit and profit-margin
self.price = int(round(self.limit * (1.0 + self.margin), 0))
# # print('old=%d diff=%d change=%d price = %d\n' % (oldprice, diff, change, self.price))