forked from shuail0/aevoTrading
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aevo.py
515 lines (458 loc) · 14.8 KB
/
aevo.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import asyncio
import json
import random
import time
import traceback
import requests
import websockets
from eth_account import Account
from eth_hash.auto import keccak
from loguru import logger
from web3 import Web3
from eip712_structs import Address, Boolean, EIP712Struct, Uint, make_domain
CONFIG = {
"testnet": {
"rest_url": "https://api-testnet.aevo.xyz",
"ws_url": "wss://ws-testnet.aevo.xyz",
"signing_domain": {
"name": "Aevo Testnet",
"version": "1",
"chainId": "11155111",
},
},
"mainnet": {
"rest_url": "https://api.aevo.xyz",
"ws_url": "wss://ws.aevo.xyz",
"signing_domain": {
"name": "Aevo Mainnet",
"version": "1",
"chainId": "1",
},
},
}
class Order(EIP712Struct):
maker = Address()
isBuy = Boolean()
limitPrice = Uint(256)
amount = Uint(256)
salt = Uint(256)
instrument = Uint(256)
timestamp = Uint(256)
class AevoClient:
def __init__(
self,
signing_key="",
wallet_address="",
api_key="",
api_secret="",
env="testnet",
rest_headers={},
):
self.signing_key = signing_key
self.wallet_address = wallet_address
self.api_key = api_key
self.api_secret = api_secret
self.connection = None
self.client = requests
self.rest_headers = {
"AEVO-KEY": api_key,
"AEVO-SECRET": api_secret,
}
self.extra_headers = None
self.rest_headers.update(rest_headers)
if (env != "testnet") and (env != "mainnet"):
raise ValueError("env must either be 'testnet' or 'mainnet'")
self.env = env
@property
def address(self):
return Account.from_key(self.signing_key).address
@property
def rest_url(self):
return CONFIG[self.env]["rest_url"]
@property
def ws_url(self):
return CONFIG[self.env]["ws_url"]
@property
def signing_domain(self):
return CONFIG[self.env]["signing_domain"]
async def open_connection(self, extra_headers={}):
try:
logger.info("Opening Aevo websocket connection...")
self.connection = await websockets.connect(
self.ws_url, ping_interval=None, extra_headers=extra_headers
)
if not self.extra_headers:
self.extra_headers = extra_headers
if self.api_key and self.wallet_address:
logger.debug(f"Connecting to {self.ws_url}...")
await self.connection.send(
json.dumps(
{
"id": 1,
"op": "auth",
"data": {
"key": self.api_key,
"secret": self.api_secret,
},
}
)
)
# Sleep as authentication takes some time, especially slower on testnet
await asyncio.sleep(1)
except Exception as e:
logger.error("Error thrown when opening connection")
logger.error(e)
logger.error(traceback.format_exc())
await asyncio.sleep(10) # Don't retry straight away
async def reconnect(self):
logger.info("Trying to reconnect Aevo websocket...")
await self.close_connection()
await self.open_connection(self.extra_headers)
async def close_connection(self):
try:
logger.info("Closing connection...")
await self.connection.close()
logger.info("Connection closed")
except Exception as e:
logger.error("Error thrown when closing connection")
logger.error(e)
logger.error(traceback.format_exc())
async def read_messages(self, read_timeout=0.1, backoff=0.1, on_disconnect=None):
while True:
try:
message = await asyncio.wait_for(
self.connection.recv(), timeout=read_timeout
)
yield message
except (
websockets.exceptions.ConnectionClosedError,
websockets.exceptions.ConnectionClosedOK,
) as e:
if on_disconnect:
on_disconnect()
logger.error("Aevo websocket connection close")
logger.error(e)
logger.error(traceback.format_exc())
await self.reconnect()
except asyncio.TimeoutError:
await asyncio.sleep(backoff)
except Exception as e:
logger.error(e)
logger.error(traceback.format_exc())
await asyncio.sleep(1)
async def send(self, data):
try:
await self.connection.send(data)
except websockets.exceptions.ConnectionClosedError as e:
logger.debug("Restarted Aevo websocket connection")
await self.reconnect()
await self.connection.send(data)
except:
await self.reconnect()
# Public REST API
def get_index(self, asset):
req = self.client.get(f"{self.rest_url}/index?symbol={asset}")
data = req.json()
return data
def get_markets(self, asset):
req = self.client.get(f"{self.rest_url}/markets?asset={asset}")
data = req.json()
return data
# Private REST API
def rest_create_order(
self, instrument_id, is_buy, limit_price, quantity, post_only=True
):
data, order_id = self.create_order_rest_json(
int(instrument_id), is_buy, limit_price, quantity, post_only
)
logger.info(data)
req = self.client.post(
f"{self.rest_url}/orders", json=data, headers=self.rest_headers
)
try:
return req.json()
except:
return req.text()
def rest_create_market_order(self, instrument_id, is_buy, quantity):
limit_price = 0
if is_buy:
limit_price = 2**256 - 1
data, order_id = self.create_order_rest_json(
int(instrument_id),
is_buy,
limit_price,
quantity,
decimals=1,
post_only=False,
)
req = self.client.post(
f"{self.rest_url}/orders", json=data, headers=self.rest_headers
)
return req.json()
def rest_cancel_order(self, order_id):
req = self.client.delete(
f"{self.rest_url}/orders/{order_id}", headers=self.rest_headers
)
logger.info(req.json())
return req.json()
def rest_get_account(self):
req = self.client.get(f"{self.rest_url}/account", headers=self.rest_headers)
return req.json()
def rest_get_portfolio(self):
req = self.client.get(f"{self.rest_url}/portfolio", headers=self.rest_headers)
return req.json()
def rest_get_open_orders(self):
req = self.client.get(
f"{self.rest_url}/orders", json={}, headers=self.rest_headers
)
return req.json()
def rest_cancel_all_orders(
self,
instrument_type=None,
asset=None,
):
body = {}
if instrument_type:
body["instrument_type"] = instrument_type
if asset:
body["asset"] = asset
req = self.client.delete(
f"{self.rest_url}/orders-all", json=body, headers=self.rest_headers
)
return req.json()
# Public WS Subscriptions
async def subscribe_tickers(self, asset):
await self.send(
json.dumps(
{
"op": "subscribe",
"data": [f"ticker:{asset}:OPTION"],
}
)
)
async def subscribe_ticker(self, channel):
msg = json.dumps(
{
"op": "subscribe",
"data": [channel],
}
)
await self.send(msg)
async def subscribe_markprice(self, asset):
await self.send(
json.dumps(
{
"op": "subscribe",
"data": [f"markprice:{asset}:OPTION"],
}
)
)
async def subscribe_orderbook(self, instrument_name):
await self.send(
json.dumps(
{
"op": "subscribe",
"data": [f"orderbook:{instrument_name}"],
}
)
)
async def subscribe_trades(self, instrument_name):
await self.send(
json.dumps(
{
"op": "subscribe",
"data": [f"trades:{instrument_name}"],
}
)
)
async def subscribe_index(self, asset):
await self.send(json.dumps({"op": "subscribe", "data": [f"index:{asset}"]}))
# Private WS Subscriptions
async def subscribe_orders(self):
payload = {
"op": "subscribe",
"data": ["orders"],
}
await self.send(json.dumps(payload))
async def subscribe_fills(self):
payload = {
"op": "subscribe",
"data": ["fills"],
}
await self.send(json.dumps(payload))
# Private WS Commands
def create_order_ws_json(
self,
instrument_id,
is_buy,
limit_price,
quantity,
post_only=True,
mmp=True,
price_decimals=10**6,
amount_decimals=10**6,
):
timestamp = int(time.time())
salt, signature, order_id = self.sign_order(
instrument_id=instrument_id,
is_buy=is_buy,
limit_price=limit_price,
quantity=quantity,
timestamp=timestamp,
price_decimals=price_decimals,
)
payload = {
"instrument": instrument_id,
"maker": self.wallet_address,
"is_buy": is_buy,
"amount": str(int(round(quantity * amount_decimals, is_buy))),
"limit_price": str(int(round(limit_price * price_decimals, is_buy))),
"salt": str(salt),
"signature": signature,
"post_only": post_only,
"mmp": mmp,
"timestamp": timestamp,
}
return payload, order_id
def create_order_rest_json(
self,
instrument_id,
is_buy,
limit_price,
quantity,
post_only=True,
reduce_only=False,
close_position=False,
price_decimals=10**6,
amount_decimals=10**6,
trigger=None,
stop=None,
):
timestamp = int(time.time())
salt, signature, order_id = self.sign_order(
instrument_id=instrument_id,
is_buy=is_buy,
limit_price=limit_price,
quantity=quantity,
timestamp=timestamp,
price_decimals=price_decimals,
)
payload = {
"maker": self.wallet_address,
"is_buy": is_buy,
"instrument": instrument_id,
"limit_price": str(int(round(limit_price * price_decimals, is_buy))),
"amount": str(int(round(quantity * amount_decimals, is_buy))),
"salt": str(salt),
"signature": signature,
"post_only": post_only,
"reduce_only": reduce_only,
"close_position": close_position,
"timestamp": timestamp,
}
if trigger and stop:
payload["trigger"] = trigger
payload["stop"] = stop
return payload, order_id
async def create_order(
self,
instrument_id,
is_buy,
limit_price,
quantity,
post_only=True,
id=None,
mmp=True,
):
data, order_id = self.create_order_ws_json(
instrument_id=int(instrument_id),
is_buy=is_buy,
limit_price=limit_price,
quantity=quantity,
post_only=post_only,
mmp=mmp,
)
payload = {"op": "create_order", "data": data}
if id:
payload["id"] = id
logger.info(payload)
await self.send(json.dumps(payload))
return order_id
async def edit_order(
self,
order_id,
instrument_id,
is_buy,
limit_price,
quantity,
id=None,
post_only=True,
mmp=True,
):
timestamp = int(time.time())
instrument_id = int(instrument_id)
salt, signature, new_order_id = self.sign_order(
instrument_id=instrument_id,
is_buy=is_buy,
limit_price=limit_price,
quantity=quantity,
timestamp=timestamp,
)
payload = {
"op": "edit_order",
"data": {
"order_id": order_id,
"instrument": instrument_id,
"maker": self.wallet_address,
"is_buy": is_buy,
"amount": str(int(round(quantity * 10**6, is_buy))),
"limit_price": str(int(round(limit_price * 10**6, is_buy))),
"salt": str(salt),
"signature": signature,
"post_only": post_only,
"mmp": mmp,
"timestamp": timestamp,
},
}
if id:
payload["id"] = id
logger.info(payload)
await self.send(json.dumps(payload))
return new_order_id
async def cancel_order(self, order_id):
if not order_id:
return
payload = {"op": "cancel_order", "data": {"order_id": order_id}}
logger.info(payload)
await self.send(json.dumps(payload))
async def cancel_all_orders(self):
payload = {"op": "cancel_all_orders", "data": {}}
await self.send(json.dumps(payload))
def sign_order(
self,
instrument_id,
is_buy,
limit_price,
quantity,
timestamp,
price_decimals=10**6,
amount_decimals=10**6,
):
salt = random.randint(0, 10**10) # We just need a large enough number
order_struct = Order(
maker=self.wallet_address, # The wallet"s main address
isBuy=is_buy,
limitPrice=int(round(limit_price * price_decimals, is_buy)),
amount=int(round(quantity * amount_decimals, is_buy)),
salt=salt,
instrument=instrument_id,
timestamp=timestamp,
)
logger.info(self.signing_domain)
domain = make_domain(**self.signing_domain)
signable_bytes = keccak(order_struct.signable_bytes(domain=domain))
return (
salt,
Account._sign_hash(signable_bytes, self.signing_key).signature.hex(),
f"0x{signable_bytes.hex()}",
)