Joel Grunbaum
2022-01-11 0594ac9ba0f38944ef810b5ac48a2067b1ce5a09
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
""".#book.py package for handling book."""
import decimal
import heapq
from enum import Enum
import time
 
decimal.getcontext().prec = 3
 
 
class OrderSide(Enum):
    """Order side enum."""
 
    Buy = "BUY",
    Sell = "SELL"
 
 
class ProductTypeEnum(Enum):
    """Product type enum."""
 
    TEST = 0,
    FUTURE = 1,
    SPREAD = 2,
    CALL = 3,
    PUT = 4
 
 
class UnknownProductTypeError(Exception):
    """Exception for unknown product type."""
 
    pass
 
 
class Order:
    """Order class."""
 
    price: decimal.Decimal
    side: OrderSide
    remaining_volume: int
    filled_volume: int
    timestamp: float
    id: str
 
    def __init__(self, price: decimal.Decimal(3), side: OrderSide,
                 volume: int, timestamp: float, id: str):
        """Initialise class."""
        self.price = price
        self.side = side
        self.remaining_volume = volume
        self.filled_volume = 0
        self.timestamp = timestamp
        self.id = id
 
 
class Level:
    """Level class."""
 
    price: decimal.Decimal
    volume: int
    side: OrderSide
    timestamp: float
    id: str
 
    def __init__(self, order: Order):
        """Initialise class."""
        self.price = order.price
        self.volume = order.remaining_volume
        self.side = order.side
        self.timestamp = order.timestamp
        self.id = order.id
 
    def __lt__(self, other):
        """Less than comparator."""
        if (self.side == OrderSide.Sell):
            if (self.price < other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp < other.timestamp):
                return True
            else:
                return False
        else:
            if (self.price > other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp < other.timestamp):
                return True
            else:
                return False
 
    def __gt__(self, other):
        """Greater than comparator."""
        if (self.side == OrderSide.Sell):
            if (self.price > other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp < other.timestamp):
                return True
            else:
                return False
        else:
            if (self.price < other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp < other.timestamp):
                return True
            else:
                return False
 
    def __le__(self, other):
        """Less than or equal compatator."""
        if (self.side == OrderSide.Sell):
            if (self.price <= other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp <= other.timestamp):
                return True
            else:
                return False
        else:
            if (self.price >= other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp <= other.timestamp):
                return True
            else:
                return False
 
    def __ge__(self, other):
        """Greater than or equal comparator."""
        if (self.side == OrderSide.Sell):
            if (self.price >= other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp <= other.timestamp):
                return True
            else:
                return False
        else:
            if (self.price <= other.price):
                return True
            elif (self.price == other.price and
                  self.timestamp <= other.timestamp):
                return True
            else:
                return False
 
    def __eq__(self, other):
        """Equalty compatator."""
        if (self.price == other.price and self.timestamp == other.timestamp):
            return True
        else:
            return False
 
    def addVolume(self, volume: int):
        """Add volume to price level."""
        self.volume += volume
 
    def __str__(self):
        """Turn into str for printing."""
        return ("Price: " + str(self.price) + ", volume: " + str(self.volume) +
                ", time: " + str(self.timestamp) + ", id: " + self.id)
 
 
class Side:
    """Side class."""
 
    levels: [Level]
 
    def __init__(self):
        """Initialise class."""
        self.levels = []
 
    def delete(self, orderId: str):
        """Delete order from side."""
        for i in self.levels:
            if (i.id == orderId):
                self.levels.remove(i)
                heapq.heapify(self.levels)
 
 
class Book:
    """Book class."""
 
    bidSide: Side
    askSide: Side
    productType: ProductTypeEnum
    product: str
    stationId: str
    unit: str
    expiry: time.struct_time
    aggFee: decimal.Decimal
    pasFee: decimal.Decimal
    broFee: decimal.Decimal
 
    def __init__(self, productType: str = "TEST", product: str = "a",
                 stationId: str = "b", unit: str = "c",
                 expiry: str = time.strftime("%Y-%m-%d %H:%M%z",
                                             time.localtime(0)),
                 aggFee: decimal.Decimal = 1, pasFee: decimal.Decimal = -1,
                 broFee: decimal.Decimal = 2):
        """Initialise module."""
        self.bidSide = Side()
        self.askSide = Side()
        if productType == "FUTURE":
            self.productType = ProductTypeEnum.FUTURE
        elif productType == "SPREAD":
            self.productType = ProductTypeEnum.SPREAD
        elif productType == "CALL":
            self.productType = ProductTypeEnum.CALL
        elif productType == "PUT":
            self.productType = ProductTypeEnum.PUT
        elif productType == "TEST":
            self.productType = ProductTypeEnum.TEST
        else:
            raise UnknownProductTypeError(productType)
        self.product = product
        self.stationId = stationId
        self.unit = unit
        self.expiry = time.strptime(expiry, "%Y-%m-%d %H:%M%z")
        self.aggFee = aggFee
        self.pasFee = pasFee
        self.broFee = broFee
 
    def addOrder(self, order: Order):
        """Add order to book."""
        if (order.side == OrderSide.Buy):
            self.bid(order)
        else:
            self.ask(order)
 
    def ask(self, order: Order):
        """Add ask to book."""
        while(len(self.bidSide.levels) > 0 and
              self.bidSide.levels[0].price >= order.price):
            if (self.bidSide.levels[0].volume > order.remaining_volume):
                temp = self.bidSide.levels[0].volume
                order.filled_volume += self.bidSide.levels[0].volume
                self.bidSide.levels[0].volume -= order.remaining_volume
                order.remaining_volume -= temp
                break
            else:
                order.remaining_volume -= self.bidSide.levels[0].volume
                order.filled_volume += self.bidSide.levels[0].volume
                heapq.heappop(self.bidSide.levels)
        if (order.remaining_volume > 0):
            heapq.heappush(self.askSide.levels, Level(order))
 
    def bid(self, order: Order):
        """Add bid to book."""
        while(len(self.askSide.levels) > 0 and
              self.askSide.levels[0].price <= order.price):
            if (self.askSide.levels[0].volume > order.remaining_volume):
                temp = self.askSide.levels[0].volume
                order.filled_volume += self.askSide.levels[0].volume
                self.askSide.levels[0].volume -= order.remaining_volume
                order.remaining_volume -= temp
                break
            else:
                order.remaining_volume -= self.askSide.levels[0].volume
                order.filled_volume -= self.askSide.levels[0].volume
                heapq.heappop(self.askSide.levels)
        if (order.remaining_volume > 0):
            heapq.heappush(self.bidSide.levels, Level(order))
 
    def printBook(self):
        """Test print book. Book is a heap so not strictly sorted."""
        print("Sell side")
        for i in sorted(self.askSide.levels, reverse=True)[-10:]:
            print(i)
        print("Buy side")
        for i in sorted(self.bidSide.levels)[:10]:
            print(str(i))
 
 
def testBook(orders: int = 10, printBook=True):
    """Test an example book."""
    b = Book()
    time = 1
    for i in range(1, orders):
        b.addOrder(Order(price=i, side=OrderSide.Buy, volume=10,
                         timestamp=time, id="a"))
        time += 1
    for i in range(orders + 1, 2 * orders):
        b.addOrder(Order(i, OrderSide.Sell, 10, time, "a"))
        time += 1
    if (printBook):
        b.printBook()
    return b