-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplestrat.py
255 lines (212 loc) · 9.49 KB
/
simplestrat.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
import datetime
import traceback
import plotly.plotly as py
import plotly.graph_objs as go
class SimpleStrat:
def __init__(self, broker):
self.broker=broker
self.mva_frame_count=60
self.gmva_frame_count=360
self.max_frames_required=self.gmva_frame_count #required
self.mva=0
self.gmva=0
self.tick_time=datetime.timedelta(minutes=1) #frame frequency by minute, required
self.ticks_between_buys=7
self.ticks_between_buys_count=self.ticks_between_buys
self.buy_order_expiration=datetime.timedelta(hours=4) #buy order expiration time
self.sell_order_expiration=datetime.timedelta(hours=24) #buy order expiration time
self.sell_order_expiration_reprice_ratio=1.01 #mva ratio to reprice expired sell orders
self.resell_price_ratio=1.015 #resell ratio for creating sell order after buy limit order fulfilled
self.max_orders=20
self.buy_amount=1
self.buy_amount_toggle=True #sets the buy amount only once on tick
self.plot_price= []
self.plot_time=[]
self.plot_buy_time=[]
self.plot_sell_time=[]
self.plot_buy_price=[]
self.plot_sell_price=[]
self.plot_cash=[] #cash on hand
self.plot_value=[] #total value of cash + position
self.plot_mva=[]
self.plot_gmva=[]
self.ticks_per_plot=10
self.ticks_per_plot_count=0
def tick(self): #required
#calculate MVA
self.mva= self.broker.get_mva(self.mva_frame_count)
self.gmva= self.broker.get_mva(self.gmva_frame_count)
if self.buy_amount_toggle:
self.buy_amount=round((self.broker.cash / (self.max_orders)) / self.broker.get_market_price(),2)
self.buy_amount_toggle=False
self.plot_price.append(self.broker.market_price)
self.plot_time.append(self.broker.frame_time.isoformat())
self.plot_mva.append(self.mva)
self.plot_gmva.append(self.gmva)
print("{} price: {:.2f} mva: {:.2f} gmva:{:.2f}".format(self.broker.frame_time.isoformat(), self.broker.market_price, self.mva, self.gmva))
#delete buy orders that last for longer than a certain time
for o in self.broker.limit_orders:
if o['side'] == 'buy' and (o['created_at'] < (self.broker.frame_time-self.buy_order_expiration).isoformat()):
self.broker.cancel_order(o['id'])
print("Canceling buy order of {} on {}".format(o['price'],self.broker.frame_time.isoformat()))
#reprice sell orders that last longer than a certain time
for o in self.broker.limit_orders:
if o['side'] == 'sell' and (o['created_at'] < (self.broker.frame_time-self.sell_order_expiration).isoformat()):
ret=self.broker.cancel_order(o['id'])
#make sure the order is canceled before doing another buy order
if ret[0] == o['id']:
new_price=round(self.mva*self.sell_order_expiration_reprice_ratio,2)
print("Repricing sell order from {} to {} on {}".format(o['price'],new_price, self.broker.frame_time.isoformat()))
self.broker.create_order(limit_price=new_price, amount=o['size'], direction='sell')
#Create buy orders
if len(self.broker.limit_orders) < self.max_orders and self.ticks_between_buys_count >= self.ticks_between_buys:
if (
(self.broker.market_price < self.mva*.99 and self.broker.market_price > self.mva*.965 and
self.broker.market_price > self.gmva*0.93) or
(self.broker.market_price < self.gmva*0.98 and self.broker.market_price > self.gmva*0.93)
): #buy if less than average by a %, less than greater average by a %, but when the less is no more than 1.75%
new_price=round(self.broker.market_price - 0.02,2)
print("Created buy limit order at {} on {}".format(new_price, self.broker.frame_time.isoformat()))
order=self.broker.create_order(limit_price=new_price, amount=self.buy_amount, direction='buy')
if order != 0:
self.ticks_between_buys_count=0
# self.plot_buy_price.append(new_price)
# self.plot_buy_time.append(self.broker.frame_time)
else:
print("Error Creating buy order on {}. Message: {}".format(self.broker.frame_time.isoformat(), order['message']))
#If a buy order is completed, then make a sell order from average price of all completed orders
for o in self.broker.recently_filled_orders:
self.broker.completed_orders+=o
bought_total=0.0 #cash spent buying (position bought *price)
bought_position=0.0 #amount of crypto bought
sold_total= 0.0
sold_position= 0.0
if o['side'] == 'buy':
bought_position+=float(o['size'])
bought_total+=(float(o['size'])* float(o['price']))
if o['side'] == 'sell':
sold_position+=float(o['size'])
sold_total+=(float(o['size'])* float(o['price']))
if bought_total > 0.0:
avg_price=bought_total/bought_position
self.plot_buy_price.append(avg_price)
self.plot_buy_time.append(self.broker.frame_time.isoformat())
#create sell order
new_price=round(avg_price*self.resell_price_ratio, 2)
order=self.broker.create_order(limit_price=new_price, amount=bought_position, direction='sell')
if order != 0:
print("Created reselling buy limit order at {}. (Total: {}) on {}".format(new_price,
new_price*bought_position, self.broker.frame_time.isoformat()))
if sold_total >0.0:
avg_price=sold_total/sold_position
print("SOLD at {} (Total:{}) on {}.".format(avg_price, (avg_price*sold_position),self.broker.frame_time.isoformat()))
self.plot_sell_price.append(avg_price)
self.plot_sell_time.append(self.broker.frame_time.isoformat())
self.ticks_between_buys_count+=1
self.plot_cash.append(self.broker.cash)
self.plot_value.append(self.broker.get_account_value())
#plot every so often
if not self.broker.simulation:
if self.ticks_per_plot_count >= self.ticks_per_plot:
self.plot()
self.ticks_per_plot_count=0
else:
self.ticks_per_plot_count+=1
def complete(self):
''' closes out and plots'''
print("End Total Assets:{}".format(self.broker.get_account_value()))
orders=self.broker.get_active_orders()
sell_count=len(list(filter(lambda x: x['side'] =='sell', orders)))
buy_count=len(list(filter(lambda x: x['side'] =='buy', orders)))
print("Sell orders outstanding: {}. Buy orders outstanding: {}".format(sell_count, buy_count))
self.plot()
def plot(self):
pricePlot = go.Scatter(
x=self.plot_time,
y=self.plot_price,
mode='lines',
name='Price'
)
mvaPlot = go.Scatter(
x=self.plot_time,
y=self.plot_mva,
mode='lines',
name='MVA'
)
gmvaPlot = go.Scatter(
x=self.plot_time,
y=self.plot_gmva,
mode='lines',
name='gMVA'
)
buyPlot = go.Scatter(
x=self.plot_buy_time,
y=self.plot_buy_price,
mode='markers',
name="Buy",
marker=dict(
size=10,
color='rgba(0, 190, 0, .8)',
)
)
sellPlot = go.Scatter(
x=self.plot_sell_time,
y=self.plot_sell_price,
mode='markers',
name="Sell",
marker=dict(
size=10,
color='rgba(190, 0, 0, .8)',
)
)
cashPlot = go.Scatter(
x=self.plot_time,
y=self.plot_cash,
mode='lines',
name="Cash",
marker=dict(
size=10,
color='rgba(190, 0, 0, .8)',
),
xaxis='x2',
yaxis='y2'
)
valuePlot = go.Scatter(
x=self.plot_time,
y=self.plot_value,
mode='lines',
name="Total Value",
marker=dict(
size=10,
color='rgba(0, 0, 190, .8)',
),
xaxis='x2',
yaxis='y2'
)
data = [pricePlot, mvaPlot, gmvaPlot, buyPlot,sellPlot, cashPlot,valuePlot]
layout = dict(
title='Crypto Simulation',
xaxis=dict(
rangeslider=dict(),
type='date',
domain=[0,1]
),
yaxis=dict(
domain=[0,0.8]
),
xaxis2=dict(
domain=[0,1],
anchor='y2'
),
yaxis2=dict(
domain=[0.8,1],
anchor='x2'
)
)
fig = dict(data=data, layout=layout)
try:
py.plot(fig, filename='crypto-stuff', auto_open=False)
except Exception as ex:
print("Error plotting the graph")
print(ex)
traceback.print_exc()