-
Notifications
You must be signed in to change notification settings - Fork 1
/
run.py
254 lines (199 loc) · 7.11 KB
/
run.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
import datetime
import requests
import urllib
import websocket
import threading
import time
import os
import pyjson5
from dydx3 import Client
from dydx3.constants import *
from dydx3.helpers.request_helpers import generate_now_iso
from config import config, tokens
# Global Vars
xchange = None
signature = None
signature_time = None
account = None
# Constants
GOOD_TILL = 31536000
def log(msg):
def _log(_msg):
conf = config()
keys = tokens()
_msg = conf['main']['name'] + ':' + _msg
print(datetime.datetime.now().isoformat(), _msg)
if keys['telegram']['chatid'] == '' or keys['telegram']['bottoken'] == '':
return
params = {
'chat_id': keys['telegram']['chatid'],
'text': _msg
}
payload_str = urllib.parse.urlencode(params, safe='@')
requests.get(
'https://api.telegram.org/bot' +
keys['telegram']['bottoken'] + '/sendMessage',
params=payload_str
)
threading.Thread(target=_log, args=[msg]).start()
def save_state():
# Save state of bot so that it can resume in case it dies for some reason (which it does often!)
global order_id
global orders
save_data = {
'order_id':order_id,
'orders':orders,
}
with open("data/state.json", "wt") as f:
pyjson5.encode_io(save_data, f, supply_bytes=False)
def load_state():
global order_id
global orders
log('Check for saved state.')
if not os.path.isfile('data/state.json'):
log('No state saved. Start new.')
return False
with open("data/state.json", "rt") as f:
load_data = pyjson5.decode_io(f)
order_id = load_data['order_id']
orders = load_data['orders'].copy()
log('State loaded.')
return True
def place_order(side, size, price):
global xchange
global account
conf = config()
order = xchange.private.create_order(
position_id=account['positionId'],
market=conf['main']['market'],
side=side,
order_type=ORDER_TYPE_LIMIT,
post_only=True,
size=str(size),
price=str(price),
limit_fee='0.1',
expiration_epoch_seconds=int(time.time()) + GOOD_TILL,
).data['order']
log(f'{side} order size {size} placed @ {price}')
return order
def ws_open(ws):
global signature
global signature_time
# Subscribe to order book updates
log('Subscribing to order changes')
ws.send(pyjson5.encode({
'type': 'subscribe',
'channel': 'v3_accounts',
'accountNumber': '0',
'apiKey': xchange.api_key_credentials['key'],
'passphrase': xchange.api_key_credentials['passphrase'],
'timestamp': signature_time,
'signature': signature,
}))
def ws_message(ws, message):
global orders
global order_id
conf = config()
# Check only for order messages
message = pyjson5.decode(message)
if message['type'] != 'channel_data':
# Not an order book update
return
if len(message['contents']['orders']) == 0:
# No orders to process
return
print(orders)
for i in range(len(orders)):
print(i)
for exchange_order in message['contents']['orders']:
if orders[i]['exchange_order']['id'] == exchange_order['id']:
if exchange_order['status'] == 'CANCELED':
# Reinstate ALL cancelled orders (CANCELED is mis-spelt smh Americans!!)
log(f'Recreate order 😡 {exchange_order["side"]} order at {exchange_order["price"]}')
orders[i]['exchange_order'] = place_order(exchange_order['side'], exchange_order['size'], exchange_order['price'])
# Save replacement order info
save_state()
if exchange_order['status'] == 'FILLED':
# Cancel all other orders
log(f'{exchange_order["side"]} order @ {exchange_order["price"]} size {exchange_order["size"]} filled')
for j in range(len(orders)):
try:
xchange.private.cancel_order(orders[j]['exchange_order']['id'])
log(f'Cancel {orders[j]["exchange_order"]["side"]} order at {orders[j]["exchange_order"]["price"]}')
except:
pass
order_id = orders[i]['config_order']['next']
log(f'Order ID {order_id}')
if order_id == -1:
log('ID -1 exit')
ws.close()
return
orders = []
for order_creator in conf['orders']:
if order_creator['id'] == order_id:
new_order = place_order(ORDER_SIDE_BUY if order_creator['side']=='buy' else ORDER_SIDE_SELL,order_creator['size'],order_creator['price'])
orders.append(orders.append({"exchange_order":new_order, "config_order":order_creator}))
# Save new state
save_state()
def ws_close(ws, p2, p3):
log('Asked to stop some reason')
save_state()
def on_ping(ws, message):
global account
global xchange
# To keep connection API active
account = xchange.private.get_account().data['account']
def main():
global orders
global order_id
global signature_time
global signature
global account
global xchange
startTime = datetime.datetime.now()
# Load configuration
conf = config()
keys = tokens()
log(f'Start {startTime.isoformat()}')
log('DEX connect.')
xchange = Client(
network_id=NETWORK_ID_MAINNET,
host=API_HOST_MAINNET,
api_key_credentials={
'key': keys['dydx']['APIkey'],
'secret': keys['dydx']['APIsecret'],
'passphrase': keys['dydx']['APIpassphrase'],
},
stark_private_key=keys['dydx']['stark_private_key'],
default_ethereum_address=keys['dydx']['default_ethereum_address'],
)
signature_time = generate_now_iso()
signature = xchange.private.sign(
request_path='/ws/accounts',
method='GET',
iso_timestamp=signature_time,
data={},
)
account = xchange.private.get_account().data['account']
if not load_state():
orders = []
order_id = 0
log(f'Order ID {order_id}')
for order_creator in conf['orders']:
if order_creator['id'] == order_id:
new_order = place_order(ORDER_SIDE_BUY if order_creator['side']=='buy' else ORDER_SIDE_SELL,order_creator['size'],order_creator['price'])
orders.append({"exchange_order":new_order, "config_order":order_creator})
# Save new state
save_state()
log('Starting bot loop')
# websocket.enableTrace(True)
wsapp = websocket.WebSocketApp(
WS_HOST_MAINNET,
on_open=ws_open,
on_message=ws_message,
on_close=ws_close,
on_ping=on_ping
)
wsapp.run_forever(ping_interval=60, ping_timeout=20)
if __name__ == "__main__":
main()