-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathReversalAction.py
384 lines (287 loc) · 13.6 KB
/
ReversalAction.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
import backtrader as bt
import backtrader.indicators as btind
import numpy as np
import datetime
class ReversalAction(bt.Strategy):
params = (
('short_period',10),
('long_period',180),
('reversal_tol_factor',0.5),
('breakout_tol_factor',0.3),
('strike_at',"sr_price"),
('target_percentage',2),
('stop_percentage',0.5),
('closing_time',"15:10"),
('show_trades', False),
('execute_breakout',True),
('sr_levels',[]),
('order_time',"2:00"),
('order_at',"close_price"),
('show_trade_object',False),
('allow_shorting',False),
('cerebro', "")
)
def log(self,txt,dt=None):
if dt is None:
dt=self.datas[0].datetime.datetime()
print(dt,txt)
pass
############## Copied from Documenation #####################
def notify_order(self, order):
if self.params.show_trades:
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log('BUY EXECUTED, %.2f' % order.executed.price)
elif order.issell():
self.log('SELL EXECUTED, %.2f' % order.executed.price)
self.bar_executed = len(self)
elif order.status == order.Canceled:
self.log('Order Canceled')
elif order.status ==order.Margin:
self.log('Order Margin')
elif order.status ==order.Rejected:
self.log('Order Rejected')
# Write down: no pending order
self.order = None
#################################################################
def notify_trade(self, trade):
trade.historyon=True
dt = self.data.datetime.datetime()
if trade.isclosed:
dt=self.datas[0].datetime.datetime()
h1=["Date", 'Avg Price', 'Gross Profit', 'Net Profit', 'Len']
r1=[dt, trade.price, round(trade.pnl,2), round(trade.pnlcomm,2), trade.barlen]
table_values=[h1,r1]
from tabulate import tabulate
if self.params.show_trade_object:
print(tabulate(table_values,))
def __init__(self):
self.start_datetime=self.datas[0].p.fromdate
self.start_portfolio_value = self.params.cerebro.broker.getvalue()
self.brought_today=False
self.order =None
self.sma_short = btind.EMA(self.datas[0], period=self.params.short_period)
self.sma_long= btind.EMA(self.datas[0], period=self.params.long_period)
################# Printing Profit At end ################################
def stop(self):
from tabulate import tabulate
from babel.numbers import format_currency as inr
cerebro=self.params.cerebro
start_portfolio_value=self.start_portfolio_value
end_portfolio_value=int(cerebro.broker.getvalue())
pnl=end_portfolio_value-self.start_portfolio_value
start_portfolio_value = inr(start_portfolio_value, "INR", locale='en_IN')
end_portfolio_value = inr(end_portfolio_value, "INR", locale='en_IN')
pnl = inr(pnl, "INR", locale='en_IN')
start_datetime=self.start_datetime
end_datetime=self.datas[0].datetime.datetime()
start_date=start_datetime.date()
end_date=end_datetime.date()
time_delta=end_datetime-self.start_datetime
table_values= [
["Date Time",start_date, end_date, time_delta.days],
["Amount", start_portfolio_value, end_portfolio_value, pnl],
]
print (tabulate(table_values,
headers=["Values","Started","Ended","Delta"],
tablefmt="grid"))
###############################################
def tolerance(self, base_x,y,tol_factor, dt=None):
z=(base_x-y)/base_x
z=np.abs(z)*100
most_near_index=np.argmin(z)
most_near_number_percentage=z[most_near_index]
if most_near_number_percentage <tol_factor:
return most_near_index
else:
return ""
def next(self):
mid_bar_value= (self.datas[0].high[0] + self.datas[0].low[0] )/2
open_p=self.datas[0].open[0]
low_p=self.datas[0].low[0]
high_p=self.datas[0].high[0]
close_p=self.datas[0].close[0]
open_p1=self.datas[0].open[-1]
low_p1=self.datas[0].low[-1]
high_p1=self.datas[0].high[-1]
close_p1=self.datas[0].close[-1]
cerebro=self.params.cerebro
################# Long Trend ################################
if mid_bar_value>self.sma_long:
long_trend="Up"
else:
long_trend="Down"
##############################################################
################# Short Trend ################################
if mid_bar_value>self.sma_short:
short_trend="Up"
else:
short_trend="Down"
##############################################################
################# SR Area ################################
sr=self.params.sr_levels
tol_factor=self.params.reversal_tol_factor
area_of_value="Out"
area=""
z=""
if short_trend=="Up":
if high_p>0:
z=self.tolerance(base_x=high_p,y=sr,tol_factor=tol_factor)
else:
if low_p>0:
z=self.tolerance(base_x=low_p,y=sr,tol_factor=tol_factor)
if z!="":
area_of_value="In"
area=sr[z]
###############################################################
################# Volume Support ################################
if self.datas[0].volume[0]>self.datas[0].volume[-1]:
volume_support="yes"
else:
volume_support="no"
###############################################################
################# Bar Lenght Support ################################
bar_lenght_support=""
if np.abs(open_p-close_p) > np.abs(open_p1-close_p1):
bar_lenght_support="yes"
else:
bar_lenght_support="no"
###############################################################
################# Red Green Conversion ################################
# Current Bar Color
if close_p>open_p:
bar_color="green"
else:
bar_color="red"
# Previous Bar Color
if close_p1>open_p1:
previous_bar_color="green"
else:
previous_bar_color="red"
trend_change=""
if volume_support=="yes" and bar_lenght_support=="yes":
if previous_bar_color=="green" and bar_color=="red":
trend_change="green_to_red"
elif previous_bar_color=="red" and bar_color=="green":
trend_change="red_to_green"
elif previous_bar_color=="green" and bar_color=="green":
trend_change="green_to_green"
elif previous_bar_color=="red" and bar_color=="red":
trend_change="red_to_red"
########################################################################
################# To Buy/Sell/Wait ################################
############### Reversal
order_signal=""
if long_trend=="Up":
if short_trend=="Down":
if area_of_value=="In":
if trend_change=="red_to_green":
order_signal="Buy"
if long_trend=="Down":
if short_trend=="Up":
if area_of_value=="In":
if trend_change=="green_to_red":
order_signal="Sell"
############### Breakout
if self.params.execute_breakout:
breakout_tol=self.params.breakout_tol_factor
if long_trend=="Up":
if short_trend=="Up":
if area_of_value=="In":
if ((close_p-area)/close_p)*100 >breakout_tol:
if trend_change=="green_to_green":
order_signal="Buy"
if long_trend=="Down":
if short_trend=="Down":
if area_of_value=="In":
if ((close_p-area)/close_p)*100 <breakout_tol:
if trend_change=="red_to_red":
order_signal="Sell"
else:
pass
################# Placing Bracket Order ################################
strike_at=self.params.strike_at
if strike_at =="mid_bar_price":
strike_price=mid_bar_value
elif strike_at=="sr_price":
if area=="":
strike_price=0
else:
strike_price=area
###### Target
target_percentage=self.params.target_percentage
buy_target=strike_price*(1+(target_percentage/100))
sell_target=strike_price*(1-(target_percentage/100))
###### Stop Loss
stop_percentage=self.params.stop_percentage
buy_loss=strike_price*(1-(stop_percentage/100))
sell_loss=strike_price*(1+(stop_percentage/100))
################### Placing Order ######################################
order_hour=self.params.order_time.split(":")[0]
order_hour=int(order_hour)
order_minute=self.params.order_time.split(":")[1]
order_minute=int(order_minute)
# cash=cerebro.broker.getvalue()
# print("\nCASH\n",cash)
if self.data.datetime.time() < datetime.time(order_hour,order_minute) \
and not self.position.size and (order_signal=="Buy" or order_signal=="Sell"):
order_at=self.params.order_at
if order_at=="close_price":
order_price=close_p
elif order_at=="mid_bar_price":
order_price=mid_bar_value
elif order_at=="sr_price":
order_price=area
cash=cerebro.broker.getvalue()
cash=cash*(1-0.05)
no_of_shares=int(cash/order_price)
lots=int(no_of_shares/100)
size=lots*100
if order_signal=="Buy" and size>0:
if self.params.show_trades:
print("-------------------Buyed---------------:",size)
self.order = self.buy_bracket(limitprice=buy_target,
price=order_price,
stopprice=buy_loss,
size=size)
if order_signal=="Sell" and self.params.allow_shorting and size>0:
if self.params.show_trades:
print("-------------------Sold---------------",size)
self.order = self.sell_bracket(limitprice=sell_target,
price=order_price,
stopprice=sell_loss,
size=size)
########################################################################
################# Closing all Postion before 3:10 ################################
close_hour=self.params.closing_time.split(":")[0]
close_hour=int(close_hour)
close_minute=self.params.closing_time.split(":")[1]
close_minute=int(close_minute)
if self.position.size != 0:
if self.data.datetime.time() > datetime.time(close_hour,close_minute):
self.close(exectype=bt.Order.Market, size=self.position.size)
########################################################################
def notify_data(self,data, status, *args, **kwargs):
if status==data.LIVE:
print("Data: Live")
elif status==data.DELAYED:
print("Data: Delayed, Backfilling")
if status==data.CONNECTED:
print("Data: Conncected")
elif status==data.DISCONNECTED:
print("Data: Disconncected")
if status==data.CONNBROKEN:
print("Data: Connection Broken")
if status==data.NOTSUBSCRIBED:
print("Data: NOt Subscribed")
# self.log("Close: "+str(close_p))
# " Long Trend:"+long_trend+
# " Short Trend:"+short_trend+
# " Area :"+area_of_value+str(area)+
# " Trend Change: "+trend_change+
# " Order Signal: "+ order_signal)