Joel Grunbaum
2022-01-20 441abf1e6a15a39f1ef7bf5e4ee2a4a43bff327b
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
""".#protocol.py handling protocol."""
import book
from enum import Enum
import httpx
import json
 
test = True
 
HOST: str = "sytev070"
if (test):
    PORT = "9005"
else:
    PORT = "9000"
 
USER: str = "jgrunbau"
PASS: str = "b7d630945a0854581d9f86ba147f34a5"
 
 
def handleMessage(bs: {str, book.Book}, message: {str, str}):
    """Handle message from exchange."""
    if (message["type"] in {"FUTURE", "SPREAD", "CALL", "PUT"}):
        announce(bs, message)
    elif (message["type"] == "SETTLEMENT"):
        settle(bs, message)
    elif (message["type"] == "ADDED"):
        addOrder(bs, message)
    elif (message["type"] == "DELETED"):
        deleteOrder(bs, message)
    elif (message["type"] == "TRADE"):
        tradeOrder(bs, message)
    elif (message["type"] in {"BROKER_REQUEST", "BROKER_ACK",
                              "BROKER_CONFIRM"}):
        broker(bs, message)
 
 
def announce(bs: {str, book.Book}, message: {str, str}):
    """Announce message."""
    # print(message)
    bs[message["product"]] = book.Book(message["type"], message["product"],
                                       message["stationId"], message["unit"],
                                       message["expiry"],
                                       message["aggressiveFee"],
                                       message["passiveFee"],
                                       message["brokerFee"])
 
 
def settle(bs: {str, book.Book}, message: {str, str}):
    """Settle order."""
    b = bs.pop(message["product"])
    if (False):
        b.printBook()
        print()
        if (len(b.askSide.levels) > 0):
            print(b.askSide.levels[0])
        if (len(b.bidSide.levels)):
            print(b.bidSide.levels[0])
        print()
 
 
def addOrder(bs: {str, book.Book}, message: {str, str}):
    """Order added to exchange."""
    if (message["side"] == "BUY"):
        bs[message["product"]].bid(
            book.Order(message["price"], book.OrderSide.Buy,
                       message["resting"],
                       message["timestamp"], message["id"]))
    else:
        bs[message["product"]].ask(
            book.Order(message["price"], book.OrderSide.Sell,
                       message["resting"],
                       message["timestamp"], message["id"]))
 
 
def deleteOrder(bs: {str, book.Book}, message: {str, str}):
    """Delete order from market."""
    if (message["side"] == "BUY"):
        bs[message["product"]].bidSide.delete(message["id"])
    else:
        bs[message["product"]].askSide.delete(message["id"])
 
 
def tradeOrder(bs: {str, book.Book}, message: {str, str}):
    """Order traded."""
    if (message["tradeType"] == "BUY_AGGRESSOR"):
        bs[message["product"]].bidSide.delete(message["passiveOrder"])
    elif (message["tradeType"] == "SELL_AGGRESSOR"):
        bs[message["product"]].askSide.delete(message["passiveOrder"])
 
 
def broker(bs: {str, book.Book}, message: {str, str}):
    """Broker trades."""
    pass
 
 
def send(message):
    """Send message with exchange."""
    return httpx.post(f"http://{HOST}:{PORT}/execution",
                      data={"message": json.dumps(message),
                            "username": USER,
                            "password": PASS}).json()
 
 
class OrderEnum(Enum):
    """Enum for ordering from the exchange."""
 
    ADD = 0,
    DELETE = 1,
    BROKER_REQUEST = 2,
    BROKER_CONFIRM = 3
 
 
def order(orderType: OrderEnum, product: str, price: float = 0,
          side: book.OrderSide = book.OrderSide.Buy,
          volume: int = 0, orderId: str = "", counterparty: str = ""):
    """Order from exchange."""
    if (orderType == OrderEnum.ADD):
        resp = send({"type": "ADD",
                     "product": product,
                     "price": price,
                     "side": side,
                     "volume": volume})
    elif (orderType == OrderEnum.DELETE):
        resp = send({"type": "DELETE",
                     "product": product,
                     "id": id})
    elif (orderType == OrderEnum.BROKER_REQUEST):
        pass
    elif (orderType == OrderEnum.BROKER_CONFIRM):
        pass
    return resp