-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathFIX44.py
287 lines (225 loc) · 10.3 KB
/
FIX44.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
import Field
import Message
from Message import Base as BaseMessage
import Symbol
import asyncore
import socket
import logging
import logging.handlers
import datetime
PROTOCOL = 'FIX.4.4'
SOH = chr(1)
class Session:
def __init__(self, sender_id: str, target_id: str, target_sub=None, sender_sub=None):
self.sender_id = sender_id
self.target_sub = target_sub
self.target_id = target_id
self.sender_sub = sender_sub
self.__sequence_number = 0
if sender_id.split('.')[0] in Symbol.SETTINGS:
self.symbol_table = Symbol.SETTINGS[sender_id.split('.')[0]]
else:
self.symbol_table = Symbol.SETTINGS['default']
def next_sequence_number(self):
self.__sequence_number += 1
return self.__sequence_number
class LogonMessage(BaseMessage):
def __init__(self, username, password, heartbeat=3, session=None):
BaseMessage.__init__(self, [
(Field.EncryptMethod, 0),
(Field.HeartBtInt, heartbeat),
(Field.ResetSeqNum, 'Y'),
(Field.Username, username),
(Field.Password, password)
], session)
self.msg_type = Message.Types.Logon
class HeartbeatMessage(BaseMessage):
def __init__(self, session=None):
BaseMessage.__init__(self, [], session)
self.msg_type = Message.Types.Heartbeat
class TestResponseMessage(BaseMessage):
def __init__(self, text, session=None):
BaseMessage.__init__(self, [(Field.TestReqID, text)], session)
self.msg_type = Message.Types.Heartbeat
class MarketDataRequestMessage(BaseMessage):
def __init__(self, request_id, symbol, unsubscribe=False, refresh=False, session=None):
BaseMessage.__init__(self, [
(Field.MDReqID, request_id),
(Field.SubscriptionRequestType, 2 if unsubscribe else 1),
(Field.MarketDepth, 0 if refresh else 1),
(Field.MDUpdateType, 1),
(Field.NoRelatedSym, 1),
(Field.Symbol, symbol),
(Field.NoMDEntryTypes, 2),
(Field.MDEntryType, 0),
(Field.MDEntryType, 1),
], session)
self.msg_type = Message.Types.MarketDataRequest
class CreateOrder(BaseMessage):
def __init__(self, order_id, symbol, side, size, session=None):
BaseMessage.__init__(self, [
(Field.ClOrdID, order_id),
(Field.Symbol, symbol),
(Field.Side, side),
(Field.TransactTime, get_time()),
(Field.OrderQty, 10000),
(Field.OrdType, 1),
(Field.TimeInForce, 1),
], session)
self.msg_type = Message.Types.NewOrder
class Client(asyncore.dispatcher):
logging_level = logging.INFO
def __init__(self, address: tuple, user, password, session, log_file=None):
asyncore.dispatcher.__init__(self)
self.session = session
self.user = user
self.password = password
self.authorized = False
self.symbol_requests = []
self.market_last_request = 1
if log_file is None:
log_file = 'messages_' + self.session.sender_id + '.log'
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=self.logging_level)
self.logger = logging.getLogger('fix-client.' + self.session.sender_id)
log_handler = logging.handlers.TimedRotatingFileHandler(log_file, 'h', 1)
log_handler.setFormatter(logging.Formatter('%(asctime)s: %(message)s'))
self.message_logger = logging.getLogger('fix-messages.' + self.session.sender_id)
self.message_logger.addHandler(log_handler)
self.message_logger.info("\nNEW SESSION\n")
self.handlers = {
Message.Types.Logon: [self.logon_handler],
Message.Types.Logout: [self.logout_handler],
Message.Types.Heartbeat: [self.heartbeat_handler],
Message.Types.TestRequest: [self.test_request_handled],
Message.Types.Reject: [self.reject_handler],
Message.Types.MessageReject: [self.reject_handler],
Message.Types.MarketDataSnapshot: [self.market_data_snapshot_handler],
Message.Types.MarketDataRefresh: [self.market_data_refresh_handler],
}
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect(address)
def add_handler(self, h_type, h_callback):
if h_type not in self.handlers:
self.handlers[h_type] = []
self.handlers[h_type].insert(0, h_callback)
def send(self, data: BaseMessage):
# self.logger.debug('Initiated request')
result = asyncore.dispatcher.send(self, data=bytes(data))
# self.logger.debug('Request complete, sent {0} bytes'.format(result))
self.message_logger.debug('OUT >>> ' + str(data).replace('\x01', '|'))
return result
def handle_connect(self):
self.send(LogonMessage(self.user, self.password, 3, self.session))
def handle_close(self):
self.close()
def handle_read(self):
message_str = self.recv(1048576).decode('ASCII')
if len(message_str) == 0:
self.logger.info(self.session.sender_id + ' disconnected.')
return
header = '8=' + PROTOCOL
if message_str.find(header) == -1:
self.logger.warn('Unknown message: ' + message_str)
return
parts = message_str.split(header)[1:]
for msg in parts:
msg = header + msg
self.message_logger.debug('IN <<< ' + msg.replace('\x01', '|'))
message = Message.from_string(msg, self.session)
handlers = self.get_message_handler(message)
if handlers is not None:
for h in handlers:
h(message)
def get_message_handler(self, message: BaseMessage):
if message.get_type() is None:
self.logger.warn("Can't handle message: can't find message type")
return None
elif message.get_type() in self.handlers:
return self.handlers[message.get_type()]
else:
self.logger.warn("Can't handle message: handler {0} not registered".format(message.get_type()))
return None
def writable(self):
return self.connecting
def logon_handler(self, message: BaseMessage):
self.authorized = True
self.logger.info("Logged in at {0} as {1}".format(message.get_field(Field.SendingTime), self.session.sender_id))
def heartbeat_handler(self, message: BaseMessage):
self.logger.debug(
"Received heartbeat, sending it back. Server time: {0}.".format(message.get_field(Field.SendingTime))
)
self.send(HeartbeatMessage(self.session))
def test_request_handled(self, message: BaseMessage):
self.send(TestResponseMessage(message.get_field(Field.TestReqID), self.session))
def reject_handler(self, message: BaseMessage):
self.logger.warn("MESSAGE REJECTED: {0}".format(message.get_field(Field.Text)))
def market_data_snapshot_handler(self, message: BaseMessage):
prices = message.get_group(Field.Groups.MDEntry_Snapshot)
if len(prices) < 2:
self.logger.warn("No ask or bid in price update.")
return
ask_idx = 1 if prices[0][Field.MDEntryType] == '0' else 0
bid_idx = (ask_idx + 1) % 2
spread = calculate_spread(
prices[bid_idx][Field.MDEntryPx],
prices[ask_idx][Field.MDEntryPx],
self.session.symbol_table[int(message.get_field(Field.Symbol))]['pip_position']
)
name = self.session.symbol_table[int(message.get_field(Field.Symbol))]['name']
self.logger.info("Symbol: {0: <7}\tServer Time: {1}\tBID: {2: <10}\tASK: {3: <10}\tSPREAD: {4}".format(
name,
message.get_field(Field.SendingTime),
prices[bid_idx][Field.MDEntryPx],
prices[ask_idx][Field.MDEntryPx],
spread
))
def market_data_refresh_handler(self, message: BaseMessage):
results = message.get_group(Field.Groups.MDEntry_Refresh)
actions = {'0': 'New', '2': 'Delete'}
types = {'0': 'BID', '1': 'ASK'}
message = "Price Update:"
for r in results:
if actions[r[Field.MDUpdateAction]] == 'New':
if Field.MDEntryPx in r:
name = self.session.symbol_table[int(r[Field.Symbol])]['name']
message += "\n\t\t\tSymbol: {0: <7}, Type: {1}, ID: {2}, Price: {3: <10}, Size: {4}, Action: {5}".format(
name, types[r[Field.MDEntryType]], r[Field.MDEntryID], r[Field.MDEntryPx], r[Field.MDEntrySize],
actions[r[Field.MDUpdateAction]]
)
else:
message += "\n\t\t\tSymbol: {0: <7}, ID: {1}, Action: {2}".format(
'none', r[Field.MDEntryID], actions[r[Field.MDUpdateAction]]
)
self.logger.info(message)
def logout_handler(self, message: BaseMessage):
self.logger.critical('Logout reason: {0}'.format(message.get_field(Field.Text)))
self.close()
def symbol_subscribe(self, symbol_id, refresh=False):
self.market_last_request += 1
self.symbol_requests.append({'symbol': symbol_id, 'request_id': self.market_last_request})
self.send(MarketDataRequestMessage(self.market_last_request, symbol_id, False, refresh, self.session))
def symbol_unsubscribe(self, symbol_id):
try:
symbol_idx = next(i for (i, d) in enumerate(self.symbol_requests) if d['symbol'] == symbol_id)
except StopIteration:
self.logger.warn("Can't find subscription for symbol {0}".format(Symbol.NAME[symbol_id]))
return
self.send(MarketDataRequestMessage(
self.symbol_requests[symbol_idx]['request_id'],
symbol_id,
True,
False,
self.session
))
def run():
asyncore.loop(3)
def calculate_spread(bid: str, ask: str, pip_position: int) -> int:
spread = float(ask) - float(bid)
spread = '{:.{}f}'.format(spread, pip_position + 1)
return int(spread.replace('.', ''))
def calculate_pip_value(price: str, size: int, pip_position: int) -> str:
pip = (pow(1 / 10, pip_position) * size) / float(price)
pip = '{:.5f}'.format(pip)
return pip
def get_time():
return datetime.datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f")[:-3]