-
Notifications
You must be signed in to change notification settings - Fork 2
/
arb_btc_ars_usdc.py
302 lines (244 loc) · 9.98 KB
/
arb_btc_ars_usdc.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
import time
import os
import json
import ssl
import logging
import asyncio
from asyncio.subprocess import Process
import requests
import websockets
from dotenv import load_dotenv
#todo kluge
#HIGHLY INSECURE
ssl_context = ssl.SSLContext()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
#HIGHLY INSECURE
#todo kluge
load_dotenv()
MIN_ORDER_AMOUNT = 0.0001
MAX_ORDER_AMOUNT = 0.01
CONTEXT = {
'orders': []
}
CURRENT_SELL = None
CURRENT_BUY = None
RUNNING = True
def get_balance():
r = requests.get("https://api.ripiotrade.co/v4/wallets/balance", headers={'Authorization': os.environ['API_KEY_V4']})
balance = {}
for currency in r.json()['data']:
balance[currency['currency_code']] = currency['available_amount']
return balance
def rebalance_buy(order_data):
""" Rebalance BTC/ARS buy order by doing two trades one sell BTC/USDC and another USDC/ARS sell order """
print(f'rebalance_buy {order_data}')
balance = get_balance()
btc_amount = order_data['executed_amount']
btc_usdc_sell = {
'pair': 'BTC_USDC',
'side': 'sell',
'amount': min(btc_amount, balance['BTC']),
'price': 0,
'type': 'market'
}
r = requests.post("https://api.ripiotrade.co/v4/orders", headers={'Authorization': os.environ['API_KEY_V4']}, json=btc_usdc_sell)
if r.status_code != 200:
logging.error(f"Error placing BTC_USDC sell order: {r.text}")
return
time.sleep(1)
r = requests.get(f"https://api.ripiotrade.co/v4/orders/{r.json()['data']['id']}", headers={'Authorization': os.environ['API_KEY_V4']})
if r.status_code != 200:
logging.error(f"Error getting BTC_USDC sell order: {r.text}")
return
usdc_amount = r.json()['data']['total_value']
# sell usdc for ars
usdc_ars_sell = {
'pair': 'USDC_ARS',
'side': 'sell',
'amount': usdc_amount,
'price': 0,
'type': 'market'
}
r = requests.post("https://api.ripiotrade.co/v4/orders", headers={'Authorization': os.environ['API_KEY_V4']}, json=usdc_ars_sell)
if r.status_code != 200:
logging.error(f"Error placing USDC_ARS sell order: {r.text}")
return
return
def rebalance_sell(order_data):
""" rebalance BTC/ARS sell order by doing two trades one buy USDC/ARS and another BTC/USDC buy order """
balance = get_balance()
ars_amount = order_data['total_value']
usd_ars_price = CONTEXT['USDC_ARS']['asks'][0]['price']
usdc_amount = min(ars_amount, balance['ARS']) / usd_ars_price
usdc_ars_buy = {
'pair': 'USDC_ARS',
'side': 'buy',
'amount': usdc_amount,
'price': 0,
'type': 'market'
}
r = requests.post("https://api.ripiotrade.co/v4/orders", headers={'Authorization': os.environ['API_KEY_V4']}, json=usdc_ars_buy)
if r.status_code != 200:
logging.error(f"Error placing USDC_ARS buy order: {r.text}")
return
time.sleep(1)
r = requests.get(f"https://api.ripiotrade.co/v4/orders/{r.json()['data']['id']}", headers={'Authorization': os.environ['API_KEY_V4']})
if r.status_code != 200:
logging.error(f"Error getting USDC_ARS buy order: {r.text}")
return
usdc_amount = r.json()['data']['executed_amount']
btc_usdc_price = CONTEXT['BTC_USDC']['asks'][0]['price']
btc_amount = usdc_amount / btc_usdc_price
print(r.json()['data'])
print(usdc_amount, btc_usdc_price, btc_amount)
btc_usdc_buy = {
'pair': 'BTC_USDC',
'side': 'buy',
'amount': btc_amount,
'price': 0,
'type': 'market'
}
r = requests.post("https://api.ripiotrade.co/v4/orders", headers={'Authorization': os.environ['API_KEY_V4']}, json=btc_usdc_buy)
if r.status_code != 200:
logging.error(f"Error placing BTC_USDC buy order: {r.text}")
return
return
async def listen_orderboook(pair):
global CONTEXT, RUNNING
print(f"start listen_orderboook({pair})")
r = requests.get(f"https://api.ripiotrade.co/v4/book/orders/level-2?pair={pair}", headers={'Authorization': os.environ['API_KEY_V4']})
if r.status_code != 200:
raise Exception('wrong code')
data = r.json()
CONTEXT[pair] = {
'bids': data['data']['bids'],
'asks': data['data']['asks']
}
while RUNNING:
try:
async with websockets.connect("wss://ws.ripiotrade.co", ssl=ssl_context) as ws:
msg = json.dumps({
"method": "subscribe",
"topics": [
f"orderbook/level_2@{pair}"
]})
# print(msg)
await ws.send(msg)
msg = json.loads(await ws.recv()) #ignore subscription
# print(msg)
while RUNNING:
msg = json.loads(await ws.recv())
# print(f'got updated {pair}')
if 'body' in msg:
CONTEXT[pair] = msg['body']
except asyncio.exceptions.CancelledError:
raise
except:
# log all exceptions
logging.exception("webscoket error")
await asyncio.sleep(5)
async def trader():
global CONTEXT, CURRENT_BUY, CURRENT_SELL, RUNNING
await asyncio.sleep(2)
def calc_price_diff(p1, p2):
return abs((p1 - p2) / p2)
while RUNNING:
# check ticker connection
try:
r = requests.get("https://api.ripiotrade.co/v4/public/tickers/BTC_ARS", headers={'Authorization': os.environ['API_KEY_V4']})
if r.status_code != 200:
print('wrong code')
await asyncio.sleep(5)
continue
except:
logging.exception("get ticker error")
await asyncio.sleep(5)
continue
BUY_PRICE = CONTEXT['USDC_ARS']['bids'][0]['price'] * CONTEXT['BTC_USDC']['bids'][0]['price'] * 0.9975
SELL_PRICE = CONTEXT['USDC_ARS']['asks'][0]['price'] * CONTEXT['BTC_USDC']['asks'][0]['price'] * 1.0025
print(f'BUY PRICE {BUY_PRICE} - SELL PRICE {SELL_PRICE}')
if CURRENT_BUY:
r = requests.get(f"https://api.ripiotrade.co/v4/orders/{CURRENT_BUY['id']}", headers={'Authorization': os.environ['API_KEY_V4']})
# print(f'current buy order {r.text}')
if r.status_code == 200 and r.json()['data']['executed_amount'] > 0:
print('rebalancing buy order')
rebalance_buy(r.json()['data'])
CURRENT_BUY = None
elif calc_price_diff(CURRENT_BUY['price'],BUY_PRICE) > 0.005:
# cancel if need to update
r = requests.delete("https://api.ripiotrade.co/v4/orders", data={
'id': CURRENT_BUY['id']
}, headers={'Authorization': os.environ['API_KEY_V4']})
print('cancel buy', r.json())
CURRENT_BUY = None
if CURRENT_SELL:
r = requests.get(f"https://api.ripiotrade.co/v4/orders/{CURRENT_SELL['id']}", headers={'Authorization': os.environ['API_KEY_V4']})
# print(f'current sell {r.text}')
if r.status_code == 200 and r.json()['data']['executed_amount'] > 0:
print('rebalancing sell order')
rebalance_sell(r.json()['data'])
CURRENT_SELL = None
elif calc_price_diff(CURRENT_SELL['price'],SELL_PRICE) > 0.005:
# cancel if need to update
r = requests.delete("https://api.ripiotrade.co/v4/orders", data={
'id': CURRENT_SELL['id']
}, headers={'Authorization': os.environ['API_KEY_V4']})
print('cancel sell', r.json())
CURRENT_SELL = None
balance = get_balance()
if not CURRENT_BUY and (balance['ARS'] / BUY_PRICE) > MIN_ORDER_AMOUNT:
r = requests.post("https://api.ripiotrade.co/v4/orders", data={
"pair": "BTC_ARS",
"side": "buy",
"type": "limit",
"amount": min(MAX_ORDER_AMOUNT, balance['ARS'] / BUY_PRICE),
"price": BUY_PRICE
}, headers={'Authorization': os.environ['API_KEY_V4']})
rdata = r.json()
if not 'error_code' in rdata:
print('create buy', rdata)
CURRENT_BUY = {
'price': BUY_PRICE,
'id': rdata['data']['id']
}
CONTEXT['orders'].append(rdata['data']['id'])
if not CURRENT_SELL and balance['BTC'] > MIN_ORDER_AMOUNT:
r = requests.post("https://api.ripiotrade.co/v4/orders", data={
"pair": "BTC_ARS",
"side": "sell",
"type": "limit",
"amount": min(MAX_ORDER_AMOUNT, balance['BTC']),
"price": SELL_PRICE
}, headers={'Authorization': os.environ['API_KEY_V4']})
rdata = r.json()
if not 'error_code' in rdata:
print('create sell', rdata)
CURRENT_SELL = {
'price': SELL_PRICE,
'id': rdata['data']['id']
}
CONTEXT['orders'].append(rdata['data']['id'])
await asyncio.sleep(5)
async def main():
t1 = asyncio.create_task(listen_orderboook('USDC_ARS'))
t2 = asyncio.create_task(listen_orderboook('BTC_USDC'))
t3 = asyncio.create_task(trader())
await t1
await t2
await t3
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
RUNNING = False
print('shooting down!')
if CURRENT_BUY:
r = requests.delete("https://api.ripiotrade.co/v4/orders", data={
'id': CURRENT_BUY['id']
}, headers={'Authorization': os.environ['API_KEY_V4']})
if CURRENT_SELL:
# cancel if need to update
r = requests.delete("https://api.ripiotrade.co/v4/orders", data={
'id': CURRENT_SELL['id']
}, headers={'Authorization': os.environ['API_KEY_V4']})