forked from ccyanxyz/dydxbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
250 lines (225 loc) · 9.17 KB
/
app.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
import time
import json
import decimal
import requests
import statistics
from dydx3 import Client
from dydx3.constants import ORDER_SIDE_BUY
from dydx3.constants import ORDER_SIDE_SELL
from dydx3.constants import ORDER_TYPE_LIMIT
from dydx3.constants import ORDER_STATUS_OPEN
from dydx3.constants import POSITION_STATUS_OPEN
from config import (
HOST,
ETHEREUM_ADDRESS,
API_KEY_CREDENTIALS,
STARK_PRIVATE_KEY,
QUOTATION_ASSET,
BASE_ASSETS,
)
class Bot:
def __init__(
self,
num_samples=20,
num_std=3,
take_profit_multiplier=1.001,
stop_loss_multiplier=.98,
records_fname='records',
):
self.client = Client(
host=HOST,
default_ethereum_address=ETHEREUM_ADDRESS,
api_key_credentials=API_KEY_CREDENTIALS
)
self.client.stark_private_key = STARK_PRIVATE_KEY
self.coinbase_api = 'https://api.pro.coinbase.com'
self.market = None
self.num_samples = num_samples
self.num_std = num_std
self.take_profit_multiplier = take_profit_multiplier
self.stop_loss_multiplier = stop_loss_multiplier
self.records_fname = records_fname
self.candles = {}
self.price_history = []
self.mean_price = None
self.mean_std = None
self.market_info = {}
self.orderbook = {}
self.account = {}
self.positions = {}
self.buy_orders = []
self.sell_orders = []
self.get_account()
def load_all_histories(self):
with open(self.histories_fname + '.json', 'r') as f:
histories = json.load(f)
return histories
def load_market_history(self):
histories = self.load_all_histories()
return histories[self.market] if histories.get(self.market) else []
def save_market_history(self, data):
histories = self.load_all_histories()
histories[self.market] = data
with open(self.histories_fname + '.json', 'w') as f:
json.dump(histories, f)
def get_price_history(self):
endpoint = f'/products/{self.market}/candles'
r = requests.get(self.coinbase_api + endpoint)
data = r.json()[:self.num_samples][::-1]
self.price_history = [float(x[4]) for x in data]
def calculate_price_stats(self):
self.mean_price = statistics.mean(self.price_history)
self.mean_std = statistics.stdev(self.price_history)
def get_entry_signal(self, price):
return price < self.mean_price - self.num_std * self.mean_std
def get_take_profit_signal(self, entry_price, price):
return entry_price * self.take_profit_multiplier < price
def get_stop_signal(self, entry_price, price):
return price < entry_price * self.stop_loss_multiplier
def get_market_info(self):
r = self.client.public.get_markets(self.market)
self.market_info = r['markets'][self.market]
def get_orderbook(self):
self.orderbook = self.client.public.get_orderbook(market=self.market)
def get_account(self):
account = self.client.private.get_account()
self.account = account['account']
self.positions = self.account['openPositions']
def get_buy_orders(self):
orders = self.client.private.get_orders(
market=self.market,
status=ORDER_STATUS_OPEN,
side=ORDER_SIDE_BUY,
limit=1,
)
self.buy_orders = orders['orders']
def get_sell_orders(self):
orders = self.client.private.get_orders(
market=self.market,
status=ORDER_STATUS_OPEN,
side=ORDER_SIDE_SELL,
limit=1,
)
self.sell_orders = orders['orders']
def get_positions(self):
positions = self.client.private.get_positions(
market=self.market,
status=POSITION_STATUS_OPEN,
)['positions']
self.positions = {
'long': [x for x in positions if x['side'] == 'LONG'],
'short': [x for x in positions if x['side'] == 'SHORT'],
}
def calculate_mid_market_price(self):
bid_price = float(self.orderbook['bids'][0]['price'])
ask_price = float(self.orderbook['asks'][0]['price'])
return bid_price + (ask_price - bid_price) * .5
"""
STRATEGIES
"""
def run_meanreversion_strategy(self):
for market in [b + '-' + QUOTATION_ASSET for b in BASE_ASSETS]:
self.market = market
self.get_market_info()
self.get_price_history()
self.calculate_price_stats()
self.get_orderbook()
self.get_buy_orders()
self.get_sell_orders()
self.get_positions()
step_size = self.market_info['stepSize']
step_exp = abs(decimal.Decimal(step_size).as_tuple().exponent)
buy_orders = self.client.private.get_orders(
market=market,
status=ORDER_STATUS_OPEN,
side=ORDER_SIDE_BUY,
order_type=ORDER_TYPE_LIMIT,
limit=1,
)
buy_order = buy_orders['orders'][0]\
if buy_orders['orders']\
else None
sell_orders = self.client.private.get_orders(
market=market,
status=ORDER_STATUS_OPEN,
side=ORDER_SIDE_SELL,
order_type=ORDER_TYPE_LIMIT,
limit=1,
)
sell_order = sell_orders['orders'][0]\
if sell_orders['orders']\
else None
if not self.positions['long']:
price = self.orderbook['bids'][0]['price']
if self.get_entry_signal(float(price)):
if not buy_order:
equity = float(self.account['equity'])
size = min(equity, 10000)
size = size / float(self.market_info['indexPrice'])
size = round(size - size % float(step_size), step_exp)
size = str(
max(size, float(self.market_info['minOrderSize']))
)
order_params = {
'position_id': self.account['positionId'],
'market': market,
'side': ORDER_SIDE_BUY,
'order_type': ORDER_TYPE_LIMIT,
'post_only': True,
'size': size,
'price': price,
'limit_fee': '0.0005',
'expiration_epoch_seconds': time.time() + 3600,
}
self.client.private.create_order(**order_params)
else:
entry_price = float(self.positions['long'][0]['entryPrice'])
price = self.orderbook['asks'][0]['price']
size = self.positions['long'][0]['sumOpen']
order_params = {
'position_id': self.account['positionId'],
'market': market,
'side': ORDER_SIDE_SELL,
'order_type': ORDER_TYPE_LIMIT,
'post_only': True,
'size': size,
'price': price,
'limit_fee': '0.0005',
'expiration_epoch_seconds': time.time() + 3600,
}
if float(size) < float(self.market_info['minOrderSize']):
order_params.update(
{
'side': ORDER_SIDE_BUY,
'size': self.market_info['minOrderSize'],
'price': self.orderbook['bids'][0]['price'],
}
)
if buy_order:
order_params.update({'cancel_id': buy_order['id']})
self.client.private.create_order(**order_params)
elif self.get_take_profit_signal(entry_price, float(price)):
if not sell_order:
self.client.private.create_order(**order_params)
if self.get_stop_signal(entry_price, float(price)):
if buy_order:
self.client.private.cancel_order(
order_id=buy_order['id']
)
if sell_order:
self.client.private.cancel_order(
order_id=sell_order['id']
)
order_params = {
'position_id': self.account['positionId'],
'market': market,
'side': ORDER_SIDE_SELL,
'order_type': 'MARKET',
'post_only': False,
'size': size,
'price': str(self.orderbook['bids'][10]['price']),
'limit_fee': '0.002',
'time_in_force': 'FOK',
'expiration_epoch_seconds': time.time() + 3600,
}
self.client.private.create_order(**order_params)