forked from manoflearning/jane-street-etc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfair-conversion.py
292 lines (242 loc) · 9.38 KB
/
fair-conversion.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
#!/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
# python fair-conversion.py --production
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 = "yeouidostreet"
# ~~~~~============== 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!
cnt =100
def main():
global cnt
args = parse_arguments()
exchange = ExchangeConnection(args=args)
hello_message = exchange.read_message()
print("First message from exchange:", hello_message)
delta = 1
# bid_price, ask_price, last_time = {}, {}, {}
last_price = {}
order_list = {}
sell_list = {}
buy_list = {}
#cnt = 100
def buy(sym, sz=1):
global cnt
cnt += 1
if sym in buy_list:
print('cancel buy', sym)
exchange.send_cancel_message(order_id=buy_list[sym])
if sym == 'VALBZ':
return
if sym == 'VALE':
return
price = last_price[sym] - 2
if sym == 'BOND':
price = last_price[sym] - 1
exchange.send_add_message(cnt, sym, Dir.BUY, price, sz)
print('buy', sym, price)
order_list[cnt] = sym + " buy"
buy_list[sym] = cnt
def sell(sym, sz=1):
global cnt
cnt += 1
if sym == 'VALBZ':
return
if sym == 'VALE':
return
if sym in sell_list:
print('cancel sell', sym)
exchange.send_cancel_message(order_id=sell_list[sym])
price = last_price[sym] + 2
if sym == 'BOND':
price = last_price[sym] + 1
exchange.send_add_message(cnt, sym, Dir.SELL, price, sz)
print('sell', sym, price)
order_list[cnt] = sym + " sell"
sell_list[sym] = cnt
def calc_price():
sym = ['BOND', 'GS', 'MS', 'WFC']
for i in sym:
if i not in last_price:
return -1
res = 0
res += 3 * last_price['BOND']
res += 2 * last_price['GS']
res += 3 * last_price['MS']
res += 2 * last_price['WFC']
return res / 10
while True:
msg = exchange.read_message()
if msg["type"] == "trade":
sym = msg["symbol"]
last_price[sym] = msg['price']
if msg["symbol"] == 'XLF' and calc_price() != -1:
bundle = calc_price()
xlf = last_price['XLF']
print(bundle, xlf, bundle- xlf)
if bundle > xlf + 50:
buy('XLF', 10)
cnt += 1
exchange.send_convert_message(cnt, 'XLF', Dir.SELL, 10)
print('convert: sell xlf', calc_price(), last_price['XLF'], calc_price() - last_price['XLF'])
sell('BOND', 3)
sell('GS', 2)
sell('MS', 3)
sell('WFC', 2)
if xlf > bundle + 50:
buy('BOND', 3)
buy('GS', 2)
buy('MS', 3)
buy('WFC', 2)
cnt += 1
exchange.send_convert_message(cnt, 'XLF', Dir.BUY, 10)
print('convert: buy xlf', calc_price(), last_price['XLF'], calc_price() - last_price['XLF'])
sell('XLF', 10)
last_price['BOND'] = 1000
# print('price', sym, last_price[sym])
if sym not in sell_list: sell(sym)
if sym not in buy_list: buy(sym)
if msg["type"] in ['reject', 'error']: print(msg)
if msg["type"] == 'ok':
print('new order', order_list[msg['order_id']])
if msg["type"] == 'out':
sym, method = order_list[msg['order_id']].split()
if method == 'sell':
del sell_list[sym]
sell(sym)
else:
del buy_list[sym]
buy(sym)
# ~~~~~============== 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
exchange_socket = self._connect(add_socket_timeout=args.add_socket_timeout)
self.reader = exchange_socket.makefile("r", 1)
self.writer = exchange_socket
self._write_message({"type": "hello", "team": team_name.upper()})
def read_message(self):
"""Read a single message from the exchange"""
message = json.loads(self.reader.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
def _write_message(self, message):
what_to_write = json.dumps(message)
if not what_to_write.endswith("\n"):
what_to_write = what_to_write + "\n"
length_to_send = len(what_to_write)
total_sent = 0
while total_sent < length_to_send:
sent_this_time = self.writer.send(
what_to_write[total_sent:].encode("utf-8")
)
if sent_this_time == 0:
raise Exception("Unable to send data to exchange")
total_sent += sent_this_time
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 != "REPLAC" + "EME"
), "Please put your team name in the variable [team_name]."
main()