-
Notifications
You must be signed in to change notification settings - Fork 0
/
trading-bot.py
executable file
·444 lines (341 loc) · 15.4 KB
/
trading-bot.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
#!/usr/bin/env python3
# ~~~~~============== HOW TO RUN ==============~~~~~
# 1) Configure things in CONFIGURATION section
# 2) Change permissions: chmod +x bot.py
# 3) Run in loop: while true; do ./bot.py --test prod-like; sleep 1; done
import argparse
from collections import deque
from enum import Enum
import time
import socket
import json
# ~~~~~============== CONFIGURATION ==============~~~~~
# Replace "REPLACEME" with your team name!
team_name = "SACRAMENTOSPLITTAILS"
# ~~~~~============== MAIN LOOP ==============~~~~~
# You should put your code here! We provide some starter code as an example,
# but feel free to change/remove/edit/update any of it as you'd like. If you
# have any questions about the starter code, or what to do next, please ask us!
#
# To help you get started, the sample code below tries to buy BOND for a low
# price, and it prints the current prices for VALE every second. The sample
# code is intended to be a working example, but it needs some improvement
# before it will start making good trades!
bond_pos = -100
gs_pos = 0
ms_pos = 0
usd_pos = 0
valbz_pos = 0
vale_pos = 0
xlf_pos = 0
xlf_fair_val = None
def main():
bond_val = None
gs_val = None
ms_val = None
wfc_val = None
args = parse_arguments()
exchange = ExchangeConnection(args=args)
# Store and print the "hello" message received from the exchange. This
# contains useful information about your positions. Normally you start with
# all positions at zero, but if you reconnect during a round, you might
# have already bought/sold symbols and have non-zero positions.
hello_message = exchange.read_message()
print("First message from exchange:", hello_message)
# Send an order for BOND at a good price, but it is low enough that it is
# unlikely it will be traded against. Maybe there is a better price to
# pick? Also, you will need to send more orders over time.
id = 1
# Set up some variables to track the bid and ask price of a symbol. Right
# now this doesn't track much information, but it's enough to get a sense
# of the VALE market.
vale_bid_price, vale_ask_price = None, None
vale_last_print_time = time.time()
valbz_bid_price, vale_ask_price = None, None
valbz_last_print_time = time.time()
bond_bid_price, bond_ask_price = None, None
bond_last_print_time = time.time()
# Here is the main loop of the program. It will continue to read and
# process messages in a loop until a "close" message is received. You
# should write to code handle more types of messages (and not just print
# the message). Feel free to modify any of the starter code below.
#
# Note: a common mistake people make is to call write_message() at least
# once for every read_message() response.
#
# Every message sent to the exchange generates at least one response
# message. Sending a message in response to every exchange message will
# cause a feedback loop where your bot's messages will quickly be
# rate-limited and ignored. Please, don't do that!
counter = 0
exchange.send_add_message(order_id=id, symbol="BOND", dir=Dir.BUY, price=999, size=100)
id = id + 1
exchange.send_add_message(order_id=id, symbol="BOND", dir=Dir.SELL, price=1001, size=100)
id = id + 1
while True:
if (counter % 100 == 0):
exchange.send_add_message(order_id=id, symbol="BOND", dir=Dir.BUY, price=999, size=100)
id = id + 1
exchange.send_add_message(order_id=id, symbol="BOND", dir=Dir.SELL, price=1001, size=100)
id = id + 1
counter += 1
message = exchange.read_message()
# Some of the message types below happen infrequently and contain
# important information to help you understand what your bot is doing,
# so they are printed in full. We recommend not always printing every
# message because it can be a lot of information to read. Instead, let
# your code handle the messages and just print the information
# important for you!
if message["type"] == "close":
print("The round has ended")
break
elif message["type"] == "error":
print(message)
elif message["type"] == "reject":
print(message)
elif message["type"] == "fill":
print(message)
elif message["type"] == "book":
if message["symbol"] == "BOND":
def best_price(side):
if message[side]:
return message[side][0][0]
bond_bid_price = best_price("buy")
bond_ask_price = best_price("sell")
if (bond_bid_price != None and bond_ask_price != None):
bond_val = (bond_bid_price + bond_ask_price) / 2
now = time.time()
if now > bond_last_print_time + 1:
bond_last_print_time = now
print(
{
"bond_bid_price": bond_bid_price,
"bond_ask_price": bond_ask_price
}
)
if message["symbol"] == "VALE":
def best_price(side):
if message[side]:
return message[side][0][0]
vale_bid_price = best_price("buy")
vale_ask_price = best_price("sell")
if (vale_ask_price != None and valbz_bid_price != None):
if (vale_ask_price < valbz_bid_price):
exchange.send_add_message(order_id=id, symbol="VALE", dir=Dir.BUY, price=vale_ask_price, size=10) #update size
id = id + 1
print(
{
"offered vale buy": vale_ask_price
}
)
exchange.send_convert_message(order_id=id, symbol="VALE", dir=Dir.SELL, size=10)
id = id + 1
print("converted VALE to VALBZ")
exchange.send_add_message(order_id=id, symbol="VALBZ", dir=Dir.SELL, price=valbz_bid_price, size=10) #update size
id = id + 1
print(
{
"offered valbz sell": valbz_bid_price
}
)
now = time.time()
if now > bond_last_print_time + 1:
vale_last_print_time = now
print(
{
"vale_bid_price": vale_bid_price,
"vale_ask_price": vale_ask_price,
}
)
now = time.time()
if now > bond_last_print_time + 1:
valbz_last_print_time = now
print(
{
"valbz_bid_price": valbz_bid_price,
"valbz_ask_price": valbz_ask_price,
}
)
if message["symbol"] == "GS":
def best_price(side):
if message[side]:
return message[side][0][0]
gs_bid_price = best_price("buy")
gs_ask_price = best_price("sell")
if (gs_bid_price != None and gs_ask_price != None):
gs_val = (gs_bid_price + gs_ask_price) / 2
if message["symbol"] == "MS":
def best_price(side):
if message[side]:
return message[side][0][0]
ms_bid_price = best_price("buy")
ms_ask_price = best_price("sell")
if (ms_bid_price != None and ms_ask_price != None):
ms_val = (ms_bid_price + ms_ask_price) / 2
if message["symbol"] == "WFC":
def best_price(side):
if message[side]:
return message[side][0][0]
wfc_bid_price = best_price("buy")
wfc_ask_price = best_price("sell")
<<<<<<< HEAD
if (wfc_bid_price != None and wfc_ask_price != None):
=======
if (wfc_bid_price != None and wfc_ask_price != None):
>>>>>>> 4d711a56cf1b3933cf873718c74e1534fbadb191
wfc_val = (wfc_bid_price + wfc_ask_price) / 2
if message["symbol"] == "XLF":
def best_price(side):
if message[side]:
return message[side][0][0]
xlf_bid_price = best_price("buy")
xlf_ask_price = best_price("sell")
if (bond_val != None and gs_val != None and ms_val != None and wfc_val != None):
xlf_fair_val = (3*bond_val + 2*gs_val + 3*ms_val + 2*wfc_val) / 10
xlf_order_buy = xlf_fair_val - 10
xlf_order_sell = xlf_fair_val + 10
# exchange.send_add_message(order_id=id, symbol="XLF", dir=Dir.BUY, price=xlf_order_buy, size=10) #update size
# id = id + 1
# print("offered xlf buy: ", valbz_ask_price)
# exchange.send_add_message(order_id=id, symbol="XLF", dir=Dir.SELL, price=xlf_order_sell, size=10) #update size
# id = id + 1
# print("offered xlf sell: ", valbz_ask_price)
if message["symbol"] == "VALBZ":
def best_price(side):
if message[side]:
return message[side][0][0]
valbz_bid_price = best_price("buy")
valbz_ask_price = best_price("sell")
if (valbz_ask_price != None and vale_bid_price != None):
if (valbz_ask_price < vale_bid_price):
exchange.send_add_message(order_id=id, symbol="VALBZ", dir=Dir.BUY, price=valbz_ask_price, size=10) #update size
id = id + 1
print(
{
"offered valbz buy": valbz_ask_price
}
)
exchange.send_convert_message(order_id=id, symbol="VALBZ", dir=Dir.SELL, size=10)
id = id + 1
print("converted VALBZ to VALE")
exchange.send_add_message(order_id=id, symbol="VALE", dir=Dir.SELL, price=vale_bid_price, size=10) #update size
id = id + 1
print(
{
"offered vale sell": vale_bid_price
}
)
now = time.time()
if now > bond_last_print_time + 1:
valbz_last_print_time = now
print(
{
"valbz_bid_price": valbz_bid_price,
"valbz_ask_price": valbz_ask_price,
}
)
# ~~~~~============== PROVIDED CODE ==============~~~~~
# You probably don't need to edit anything below this line, but feel free to
# ask if you have any questions about what it is doing or how it works. If you
# do need to change anything below this line, please feel free to
class Dir(str, Enum):
BUY = "BUY"
SELL = "SELL"
class ExchangeConnection:
def __init__(self, args):
self.message_timestamps = deque(maxlen=500)
self.exchange_hostname = args.exchange_hostname
self.port = args.port
self.exchange_socket = self._connect(add_socket_timeout=args.add_socket_timeout)
self._write_message({"type": "hello", "team": team_name.upper()})
def read_message(self):
"""Read a single message from the exchange"""
message = json.loads(self.exchange_socket.readline())
if "dir" in message:
message["dir"] = Dir(message["dir"])
return message
def send_add_message(
self, order_id: int, symbol: str, dir: Dir, price: int, size: int
):
"""Add a new order"""
self._write_message(
{
"type": "add",
"order_id": order_id,
"symbol": symbol,
"dir": dir,
"price": price,
"size": size,
}
)
def send_convert_message(self, order_id: int, symbol: str, dir: Dir, size: int):
"""Convert between related symbols"""
self._write_message(
{
"type": "convert",
"order_id": order_id,
"symbol": symbol,
"dir": dir,
"size": size,
}
)
def send_cancel_message(self, order_id: int):
"""Cancel an existing order"""
self._write_message({"type": "cancel", "order_id": order_id})
def _connect(self, add_socket_timeout):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if add_socket_timeout:
# Automatically raise an exception if no data has been recieved for
# multiple seconds. This should not be enabled on an "empty" test
# exchange.
s.settimeout(5)
s.connect((self.exchange_hostname, self.port))
return s.makefile("rw", 1)
def _write_message(self, message):
json.dump(message, self.exchange_socket)
self.exchange_socket.write("\n")
now = time.time()
self.message_timestamps.append(now)
if len(
self.message_timestamps
) == self.message_timestamps.maxlen and self.message_timestamps[0] > (now - 1):
print(
"WARNING: You are sending messages too frequently. The exchange will start ignoring your messages. Make sure you are not sending a message in response to every exchange message."
)
def parse_arguments():
test_exchange_port_offsets = {"prod-like": 0, "slower": 1, "empty": 2}
parser = argparse.ArgumentParser(description="Trade on an ETC exchange!")
exchange_address_group = parser.add_mutually_exclusive_group(required=True)
exchange_address_group.add_argument(
"--production", action="store_true", help="Connect to the production exchange."
)
exchange_address_group.add_argument(
"--test",
type=str,
choices=test_exchange_port_offsets.keys(),
help="Connect to a test exchange.",
)
# Connect to a specific host. This is only intended to be used for debugging.
exchange_address_group.add_argument(
"--specific-address", type=str, metavar="HOST:PORT", help=argparse.SUPPRESS
)
args = parser.parse_args()
args.add_socket_timeout = True
if args.production:
args.exchange_hostname = "production"
args.port = 25000
elif args.test:
args.exchange_hostname = "test-exch-" + team_name
args.port = 25000 + test_exchange_port_offsets[args.test]
if args.test == "empty":
args.add_socket_timeout = False
elif args.specific_address:
args.exchange_hostname, port = args.specific_address.split(":")
args.port = int(port)
return args
if __name__ == "__main__":
# Check that [team_name] has been updated.
assert (
team_name != "REPLACEME"
), "Please put your team name in the variable [team_name]."
main()