-
Notifications
You must be signed in to change notification settings - Fork 174
/
Backtester.py
666 lines (616 loc) · 34.5 KB
/
Backtester.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
from collections import deque
import pprint
from joblib import load
from binance.client import Client
import matplotlib.pyplot as plt
from binance.exceptions import BinanceAPIException
import pandas as pd
import numpy as np
import Helper
import API_keys
from copy import copy
trades = deque(maxlen=100000) ##keep track of shorts/Longs for graphing
cashout = deque(maxlen=100000) ##keep track of Winning trades/ Losing trades
signals= deque(maxlen=100000) ##when a siganl occured , NOT IN USE
symbol = ['RAYUSDT', 'NEARUSDT', 'AUDIOUSDT']
'''[, 'HNTUSDT', 'DGBUSDT', 'ZRXUSDT', 'BCHUSDT', 'HOTUSDT', 'ARUSDT', 'FLMUSDT',
'SFPUSDT', 'BELUSDT', 'RENUSDT', 'ADAUSDT', 'STORJUSDT', 'CHRUSDT', 'WAVESUSDT', 'CHZUSDT', 'XRPUSDT',
'SANDUSDT', 'OCEANUSDT', 'ENJUSDT', 'GRTUSDT', 'UNIUSDT', 'TLMUSDT', 'XTZUSDT', 'LUNAUSDT', 'EOSUSDT',
'SKLUSDT', 'GTCUSDT', 'DOTUSDT', '1INCHUSDT', 'UNFIUSDT', 'FTMUSDT', 'RLCUSDT', 'ATOMUSDT', 'BLZUSDT', 'SNXUSDT',
'SOLUSDT', 'ETCUSDT', 'BNBUSDT', 'CELRUSDT', 'OGNUSDT', 'ETHUSDT', 'NEOUSDT', 'TOMOUSDT', 'CELOUSDT', 'KLAYUSDT',
'TRBUSDT', 'TRXUSDT', 'EGLDUSDT', 'CRVUSDT', 'BAKEUSDT', 'NUUSDT', 'SRMUSDT', 'ALICEUSDT', 'CTKUSDT', 'ARPAUSDT',
'MATICUSDT', 'IOTXUSDT', 'DENTUSDT', 'IOSTUSDT', 'OMGUSDT', 'BANDUSDT', 'BTCUSDT', 'NKNUSDT', 'RSRUSDT', 'IOTAUSDT',
'CVCUSDT', 'REEFUSDT', 'BTSUSDT', 'BTTUSDT', 'ONEUSDT', 'ANKRUSDT', 'SUSHIUSDT', 'ALGOUSDT', 'SCUSDT', 'ONTUSDT',
'MANAUSDT', 'ATAUSDT', 'MKRUSDT', 'DODOUSDT', 'LITUSDT', 'ICPUSDT', 'ZECUSDT', 'ICXUSDT', 'ZENUSDT', 'DOGEUSDT',
'ALPHAUSDT', 'SXPUSDT', 'HBARUSDT', 'RVNUSDT', 'CTSIUSDT', 'KAVAUSDT', 'C98USDT', 'THETAUSDT', 'MASKUSDT', 'AAVEUSDT',
'AXSUSDT', 'ZILUSDT', 'XEMUSDT', 'COMPUSDT', 'RUNEUSDT', 'AVAXUSDT', 'KNCUSDT', 'LPTUSDT', 'LRCUSDT',
'MTLUSDT', 'VETUSDT', 'DASHUSDT', 'KEEPUSDT', 'LTCUSDT', 'DYDXUSDT', 'LINAUSDT', 'XLMUSDT', 'LINKUSDT', 'QTUMUSDT',
'KSMUSDT', 'FILUSDT', 'STMXUSDT', 'BALUSDT', 'GALAUSDT', 'BATUSDT', 'AKROUSDT', 'XMRUSDT', 'COTIUSDT']'''
client = Client(API_keys.api_key,API_keys.api_secret)
##################### Run on all USDT pairs or else comment out and specify a list like above ####################################
x = client.futures_ticker() # [0]
##get all symbols
for y in x:
symbol.append(y['symbol'])
symbol = [x for x in symbol if 'USDT' in x] ##filter for usdt futures
symbol = [x for x in symbol if not '_' in x] ##remove invalid symbols
###################################################################################################################################
####################################### SETTINGS ###########################################################
###################################################################################################################################
OrderSIZE = .05 ## Amount of effective account balance to use per trade
AccountBalance = 1000
leverage = 10 ##leverage being used
fee = .00036
start = '01-12-21' ##start of backtest dd/mm/yy
end = '01-03-22' ##end of backtest dd/mm/yy
TIME_INTERVAL = '1m' ##Candlestick interval in minutes, valid options: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M I think...
use_trailing_stop = 0 ##(NOT IN USE Causing rounding error I think) flag to use trailing stop, If on when the takeprofitval margin is reached a trailing stop will be set with the below percentage distance
trailing_stop_distance = .01 ## 1% trailing stop activated by hitting the takeprofitval for a coin
##################################################################################################################################
##################################################################################################################################
######### flags/variables: #######################
Highest_lowest = 0
Type = -99
stoplossval = -99
takeprofitval = -99
CurrentPos = -99
positionSize = -99
positionPrice = -99
PrevPos = -99
Trade_Direction = -99
Trading_index = -99 ##index of coin we are trading
Trade_Stage = 0 ##flag to say in a trade
Close_pos = 0
Open=[]
High=[]
Low=[]
Close=[]
Volume=[]
Date=[]
OpenStream=[]
HighStream=[]
LowStream=[]
CloseStream=[]
VolumeStream=[]
DateStream = []
Profit=0 ##Keep track of profit by flipping a single coin
correct=0 ##winning trades
profitgraph=[] #for graphing the profit change over time
pp = pprint.PrettyPrinter()
Sleep=0
tradeNO=0 ##number of trades
fees_paid = 0
High_1min = []
Low_1min = []
Close_1min= []
Open_1min = []
Date_1min = []
profitgraph.append(AccountBalance)
count = 0
percent = .01 ##percentage to hold out for
originalBalance = copy(AccountBalance)
trailing_stop_value = -99 ##gets set automatically depending on the trailing stop percent, if used above
EffectiveAccountBalance = -99 ##set later
#####################################################################################################################
#####################################################################################################################
trade_data = {}
time_CAGR = Helper.get_CAGR(start, end)
print("Loading Price Data")
i = 0
while i < len(symbol):
path = f"{Helper.desktop_path}\\price_data\\{symbol[i]}_{TIME_INTERVAL}_{start}_{end}.joblib"
try:
price_data = load(path)
Date.append(price_data['Date'])
Open.append(price_data['Open'])
Close.append(price_data['Close'])
High.append(price_data['High'])
Low.append(price_data['Low'])
Volume.append(price_data['Volume'])
High_1min.append(price_data['High_1min'])
Low_1min.append(price_data['Low_1min'])
Close_1min.append(price_data['Close_1min'])
Open_1min.append(price_data['Open_1min'])
Date_1min.append(price_data['Date_1min'])
i += 1
except:
try:
print(f"Data doesnt exist in path: {path}, Downloading Data to specified path now...")
Helper.get_Klines(TIME_INTERVAL,symbol[i],start,end,path)
price_data = load(path)
Date.append(price_data['Date'])
Open.append(price_data['Open'])
Close.append(price_data['Close'])
High.append(price_data['High'])
Low.append(price_data['Low'])
Volume.append(price_data['Volume'])
High_1min.append(price_data['High_1min'])
Low_1min.append(price_data['Low_1min'])
Close_1min.append(price_data['Close_1min'])
Open_1min.append(price_data['Open_1min'])
Date_1min.append(price_data['Date_1min'])
print("Download Successful, Loading Data now")
i += 1
except BinanceAPIException as e:
if str(e) == 'APIError(code=-1121): Invalid symbol.':
print(f"Invalid Symbol: {symbol[i]}, removing from data set")
symbol.pop(i)
else:
print(f"Wrong path specified in Helper.py,error: {e}")
symbol.pop(i)
print("Fix path issue or else turn off load_data")
print("Contact me if still stuck @ wconor539@gmail.com")
print("Symbols:", symbol, "Start Balance:", AccountBalance,"fee:",fee)
start_equity = AccountBalance
i = 0
while i < len(Close):
if len(Close[i]) == 0:
Date.pop(i)
Open.pop(i)
Close.pop(i)
High.pop(i)
Low.pop(i)
Volume.pop(i)
High_1min.pop(i)
Low_1min.pop(i)
Close_1min.pop(i)
Open_1min.pop(i)
Date_1min.pop(i)
print(f"Not enough candleStick data for {symbol[i]} removing from dataset...")
symbol.pop(i)
i -= 1
i += 1
print("Aligning Data Sets... This may take a few minutes")
Date_1min, High_1min, Low_1min, Close_1min, Open_1min, Date, Open, Close, High, Low, Volume = Helper.align_Datasets(
Date_1min, High_1min, Low_1min, Close_1min, Open_1min, Date, Open, Close, High, Low, Volume)
Open_H = []
Close_H = []
High_H = []
Low_H = []
OpenStream_H = []
CloseStream_H = []
HighStream_H = []
LowStream_H = []
print("Generating Heikin ashi candles will take a while")
Open_H, Close_H, High_H, Low_H = Helper.get_heikin_ashi(Open, Close, High, Low)
print("Finished")
for i in range(len(symbol)):
CloseStream.append([])
OpenStream.append([])
HighStream.append([])
LowStream.append([])
VolumeStream.append([])
DateStream.append([])
OpenStream_H.append([])
CloseStream_H.append([])
HighStream_H.append([])
LowStream_H.append([])
##variables for sharpe ratio
day_start_equity = AccountBalance
month_return = 0
monthly_return = []
Daily_return = []
Strategy = []
Trade_start = []
winning_trades = []
losing_trades = []
print(f"{TIME_INTERVAL} OHLC Candle Sticks from a {start} to {end}")
original_time_interval = copy(TIME_INTERVAL)
TIME_INTERVAL = Helper.get_TIME_INTERVAL(TIME_INTERVAL) ##Convert string to an integer for the rest of the script
for i in range(len(High_1min[0])-1):
if (i%TIME_INTERVAL==0 and i!=0) or TIME_INTERVAL==1:
for j in range(len(High_1min)):
DateStream[j].append(Date[j][int(i/TIME_INTERVAL)-1])
OpenStream[j].append(float(Open[j][int(i/TIME_INTERVAL)-1]))
CloseStream[j].append(float(Close[j][int(i/TIME_INTERVAL)-1]))
HighStream[j].append(float(High[j][int(i/TIME_INTERVAL)-1]))
LowStream[j].append(float(Low[j][int(i/TIME_INTERVAL)-1]))
VolumeStream[j].append(float(Volume[j][int(i/TIME_INTERVAL)-1]))
OpenStream_H[j].append(float(Open_H[j][int(i / TIME_INTERVAL)-1]))
CloseStream_H[j].append(float(Close_H[j][int(i / TIME_INTERVAL)-1]))
HighStream_H[j].append(float(High_H[j][int(i / TIME_INTERVAL)-1]))
LowStream_H[j].append(float(Low_H[j][int(i / TIME_INTERVAL)-1]))
#print(len(OpenStream))
if len(OpenStream[0])>=300:
#print(DateStream)
for j in range(len(High_1min)):
DateStream[j].pop(0)
OpenStream[j].pop(0)
CloseStream[j].pop(0)
HighStream[j].pop(0)
LowStream[j].pop(0)
VolumeStream[j].pop(0)
OpenStream_H[j].pop(0)
CloseStream_H[j].pop(0)
HighStream_H[j].pop(0)
LowStream_H[j].pop(0)
prev_Account_Bal=copy(AccountBalance)
EffectiveAccountBalance = AccountBalance*leverage
if Trade_Stage == 0:
for j in range(len(symbol)):
if i % TIME_INTERVAL == 0 and (i != 0 or TIME_INTERVAL == 1):
break_even_flag = 0
##Public Strats :) :
if CurrentPos == -99:
#Trade_Direction,stoplossval, takeprofitval = TS.StochRSIMACD(Trade_Direction, CloseStream[j],HighStream[j],LowStream[j]) ###########################################
# Trade_Direction,stoplossval, takeprofitval = TS.tripleEMAStochasticRSIATR(CloseStream[j],HighStream[j],LowStream[j],Trade_Direction)
# Trade_Direction,stoplossval, takeprofitval=TS.tripleEMA(CloseStream[j],HighStream[j],LowStream[j],Trade_Direction)
# Trade_Direction, stoplossval, takeprofitval = TS.breakout(Trade_Direction,CloseStream[j],VolumeStream[j],HighStream[j], LowStream[j])
# Trade_Direction,stoplossval,takeprofitval = TS.stochBB(Trade_Direction,CloseStream[j], HighStream[j], LowStream[j])
# Trade_Direction, stoplossval, takeprofitval = TS.goldenCross(Trade_Direction,CloseStream[j], HighStream[j], LowStream[j])
# Trade_Direction , stoplossval, takeprofitval = TS.candle_wick(Trade_Direction,CloseStream[j],OpenStream[j],HighStream[j],LowStream[j])
# Trade_Direction,stoplossval,takeprofitval = TS.fibMACD(Trade_Direction, CloseStream[j], OpenStream[j],HighStream[j],LowStream[j])
# Trade_Direction, stoplossval, takeprofitval, Close_pos = TS.heikin_ashi_ema2(CloseStream[j], OpenStream_H[j], HighStream_H[j], LowStream_H[j], CloseStream_H[j], Trade_Direction, stoplossval, takeprofitval, CurrentPos, Close_pos)
# Trade_Direction,stoplossval,takeprofitval,Close_pos = TS.heikin_ashi_ema(CloseStream[j], OpenStream_H[j], CloseStream_H[j], Trade_Direction, stoplossval,takeprofitval, CurrentPos, Close_pos)
##must be unhighlighted below in the else clause also as it returns the Close_pos var
# Trade_Direction,Close_pos,count,stoplossval = TS.single_candle_swing_pump(Trade_Direction,CloseStream[j],HighStream[j],LowStream[j],CurrentPos,Close_pos,count,stoplossval)
pass
if CurrentPos == -99 and Trade_Direction == 0:
Trading_index = j
positionPrice = Open_1min[Trading_index][i] ##next open candle #CloseStream[j][len(CloseStream[j]) - 1]
positionSize = (OrderSIZE * EffectiveAccountBalance) / positionPrice
CurrentPos = 0
Trade_Stage = 1 ##In a trade
trades.append({'x': i, 'y': positionPrice, 'type': "sell", 'current_price': positionPrice})
Profit -= Open_1min[Trading_index][i] * fee
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
Trade_Direction = -99
if CurrentPos:
Trade_start = [symbol[Trading_index], f"{Date_1min[Trading_index][i]}",
'Long'] ##we enter trade on next candle
else:
Trade_start = [symbol[Trading_index], f"{Date_1min[Trading_index][i]}", 'Short']
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
# print("Time Max",DateStream[max_pos])
# print("Time Min", DateStream[min_pos])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
tradeNO += 1
break
elif CurrentPos == -99 and Trade_Direction == 1:
Trading_index = j
positionPrice = Open_1min[Trading_index][i] ##next open candle
positionSize = (OrderSIZE * EffectiveAccountBalance) / positionPrice
CurrentPos = 1
Trade_Stage = 1 ##In a trade
trades.append({'x': i, 'y': positionPrice, 'type': "buy", 'current_price': positionPrice})
Profit -= Open_1min[Trading_index][i] * fee
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
Trade_Direction = -99
if CurrentPos:
Trade_start = [symbol[Trading_index], f"{Date_1min[Trading_index][i]}",
'Long'] ##we enter trade on next candle
else:
Trade_start = [symbol[Trading_index], f"{Date_1min[Trading_index][i]}", 'Short']
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
# print("Time Max",DateStream[max_pos])
# print("Time Min", DateStream[min_pos])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
tradeNO += 1
break
elif Trade_Stage == 1:
if positionPrice - High_1min[Trading_index][i] < -stoplossval and CurrentPos == 0: # and not Hold_pos:
Profit += -stoplossval
month_return -= positionSize * stoplossval
AccountBalance += positionSize * -stoplossval
Profit -= Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "loss", 'position': 'short',
'Profit': -stoplossval * positionSize})
profitgraph.append(AccountBalance)
CurrentPos = -99
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
losing_trades.append(Trade_start)
Trade_Stage = 0
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
# print("Time Max",DateStream[max_pos])
# print("Time Min", DateStream[min_pos])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
Trading_index = -99
elif Low_1min[Trading_index][i] - positionPrice < -stoplossval and CurrentPos == 1: # and not Hold_pos:
Profit += -stoplossval
month_return -= positionSize * stoplossval
AccountBalance += positionSize * -stoplossval
Profit -= Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "loss", 'position': 'long',
'Profit': -stoplossval * positionSize})
# CurrentPos = -99
profitgraph.append(AccountBalance)
CurrentPos = -99
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
losing_trades.append(Trade_start)
Trade_Stage = 0
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
# print("Time Max",DateStream[max_pos])
# print("Time Min", DateStream[min_pos])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
Trading_index = -99
elif positionPrice - Low_1min[Trading_index][i] > takeprofitval and CurrentPos == 0 and not use_trailing_stop: # and not Hold_pos:
Profit += takeprofitval
month_return += positionSize * takeprofitval
AccountBalance += positionSize * takeprofitval
correct += 1
Profit -= Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "win", 'position': 'short',
'Profit': takeprofitval * positionSize})
CurrentPos = -99
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
profitgraph.append(AccountBalance)
Trade_Stage = 0
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
winning_trades.append(Trade_start)
Trading_index = -99
elif High_1min[Trading_index][i] - positionPrice > takeprofitval and CurrentPos == 1 and not use_trailing_stop: # and not Hold_pos:
Profit += takeprofitval
month_return += positionSize * takeprofitval
AccountBalance += positionSize * takeprofitval
correct += 1
Profit -= Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "win", 'position': 'long',
'Profit': takeprofitval * positionSize})
CurrentPos = -99
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
profitgraph.append(AccountBalance)
Trade_Stage = 0
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
winning_trades.append(Trade_start)
Trading_index = -99
elif Close_pos == 1 and CurrentPos == 1:
prev_val = copy(AccountBalance)
prev_Profit = copy(Profit)
Profit += Open_1min[Trading_index][i] - positionPrice ##sell at next open candle
month_return += positionSize * (Open_1min[Trading_index][i] - positionPrice)
AccountBalance += positionSize * (Open_1min[Trading_index][i] - positionPrice)
if prev_Profit < Profit:
correct += 1
winning_trades.append(Trade_start)
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "win", 'position': 'long',
'Profit': (Open_1min[Trading_index][i] - positionPrice) * positionSize})
else:
losing_trades.append(Trade_start)
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "loss", 'position': 'long',
'Profit': (Open_1min[Trading_index][i] - positionPrice) * positionSize})
Profit -= Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
CurrentPos = -99
profitgraph.append(AccountBalance)
Trade_Stage = 0
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
Close_pos = 0
Trading_index = -99
print("Position Closed")
elif Close_pos == 1 and CurrentPos == 0:
prev_val = copy(AccountBalance)
prev_Profit = copy(Profit)
Profit += positionPrice - Open_1min[Trading_index][i]
month_return += positionSize * (positionPrice - Open_1min[Trading_index][i])
AccountBalance += positionSize * (positionPrice - Open_1min[Trading_index][i])
if prev_Profit < Profit:
correct += 1
winning_trades.append(Trade_start)
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "win", 'position': 'short',
'Profit': (positionPrice - Open_1min[Trading_index][i]) * positionSize})
else:
losing_trades.append(Trade_start)
cashout.append({'x': i, 'y': Open_1min[Trading_index][i], 'type': "loss", 'position': 'short',
'Profit': (positionPrice - Open_1min[Trading_index][i]) * positionSize})
Profit -= Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * Open_1min[Trading_index][i] * fee
month_return -= positionSize * Open_1min[Trading_index][i] * fee
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
CurrentPos = -99
profitgraph.append(AccountBalance)
Close_pos = 0
Trade_Stage = 0
print(f"\nCurrent Position {symbol[Trading_index]}:", CurrentPos)
print("Time:", Date_1min[Trading_index][i])
try:
print("Account Balance: ", AccountBalance, "Order Size:", positionSize, "PV:",
(Profit * 100) / (tradeNO * CloseStream[Trading_index][-1]), "Stoploss:", stoplossval,
"TakeProfit:",
takeprofitval)
except Exception as e:
pass
Trading_index = -99
print("Position Closed")
elif use_trailing_stop and CurrentPos == 0:
# trailing_stop_value
if Open_1min[Trading_index][i] < positionPrice - takeprofitval and trailing_stop_value == -99:
##takeprofit reached so set trailing_stop_value
trailing_stop_value = (positionPrice - takeprofitval) * (1 + trailing_stop_distance) ##price at which we will sell if moved up to
print("Trailing Stop: ", trailing_stop_value)
elif Open_1min[Trading_index][i] > trailing_stop_value and trailing_stop_value != -99:
prev_val = copy(AccountBalance)
##trailing stop has been hit
Profit += positionPrice - trailing_stop_value
month_return += positionSize * (positionPrice - trailing_stop_value)
AccountBalance += positionSize * (positionPrice - trailing_stop_value)
print("Trailing Stop Profit", positionSize * (positionPrice - trailing_stop_value))
correct += 1
Profit -= trailing_stop_value * fee
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * trailing_stop_value * fee
month_return -= positionSize * trailing_stop_value * fee
cashout.append({'x': i, 'y': trailing_stop_value, 'type': "win", 'position': 'short',
'Profit': positionSize * (positionPrice - trailing_stop_value)})
CurrentPos = -99
profitgraph.append(AccountBalance)
trailing_stop_value = -99
winning_trades.append(Trade_start)
Trade_Stage = 0
elif Open_1min[Trading_index][i] * (
1 + trailing_stop_distance) < trailing_stop_value and trailing_stop_value != -99:
trailing_stop_value = Open_1min[Trading_index][i] * (
1 + trailing_stop_distance) ##move trailing stop as a new low was reached
print("Trailing Stop: ", trailing_stop_value)
elif use_trailing_stop and CurrentPos == 1:
# trailing_stop_value
if Open_1min[Trading_index][i] > positionPrice + takeprofitval and trailing_stop_value == -99:
##takeprofit reached so set trailing_stop_value
trailing_stop_value = (positionPrice + takeprofitval) * (
1 - trailing_stop_distance) ##price at which we will sell if moved up to
print("Trailing Stop: ", trailing_stop_value)
elif Open_1min[Trading_index][i] < trailing_stop_value and trailing_stop_value != -99:
##trailing stop has been hit
prev_val = copy(AccountBalance)
Profit += trailing_stop_value - positionPrice
month_return += positionSize * (trailing_stop_value - positionPrice)
AccountBalance += positionSize * (trailing_stop_value - positionPrice)
print("Trailing Stop Profit", positionSize * (trailing_stop_value - positionPrice))
correct += 1
Profit -= trailing_stop_value * fee
fees_paid += positionSize * Open_1min[Trading_index][i] * fee
AccountBalance -= positionSize * trailing_stop_value * fee
month_return -= positionSize * trailing_stop_value * fee
cashout.append({'x': i, 'y': trailing_stop_value, 'type': "win", 'position': 'short',
'Profit': positionSize * (trailing_stop_value - positionPrice)})
CurrentPos = -99
profitgraph.append(AccountBalance)
trailing_stop_value = -99
winning_trades.append(Trade_start)
Trade_Stage = 0
elif Open_1min[Trading_index][i] * (
1 - trailing_stop_distance) > trailing_stop_value and trailing_stop_value != -99:
trailing_stop_value = Open_1min[Trading_index][i] * (
1 - trailing_stop_distance) ##move trailing stop as a new high was reached
print("Trailing Stop: ", trailing_stop_value)
if i%1440==0 and i!=0:
Daily_return.append(AccountBalance)
elif i==len(High_1min[0])-1:
Daily_return.append(AccountBalance)
risk_free_rate = 1.41 ##10 year treasury rate
df=pd.DataFrame({'Account_Balance':Daily_return})
df['daily_return'] = df['Account_Balance'].pct_change()
df['cum_return'] = (1+df['daily_return']).cumprod()
df['cum_roll_max'] = df['cum_return'].cummax()
df['drawdown'] = df['cum_roll_max'] - df['cum_return']
df['drawdown %'] = df['drawdown']/df['cum_roll_max']
max_dd = df['drawdown %'].max()*100
CAGR = ((df['cum_return'].iloc[-1])**(1/time_CAGR)-1)*100
vol = (df['daily_return'].std() * np.sqrt(365))*100
neg_vol = (df[df['daily_return']<0]['daily_return'].std()* np.sqrt(365))*100
Sharpe_ratio = (CAGR-risk_free_rate)/vol
sortino_ratio = (CAGR - risk_free_rate)/neg_vol
calmar_ratio = CAGR/max_dd
print("\nSettings:")
print('leverage:',leverage)
print('order_Size:',OrderSIZE)
print('fee:',fee)
print("\nSymbol(s):", symbol, "fee:", fee)
print(f"{original_time_interval} OHLC Candle Sticks from {start} to {end}")
print("Account Balance:", AccountBalance)
print("% Gain on Account:", ((AccountBalance - originalBalance) * 100) / originalBalance)
print("Total Returns:",AccountBalance-start_equity,"\n")
print(f"Annualized Volatility: {round(vol,4)}%")
print(f"CAGR: {round(CAGR,4)}%")
print("Sharpe Ratio:",round(Sharpe_ratio,4))
print("Sortino Ratio:",round(sortino_ratio,4))
print("Calmar Ratio:",round(calmar_ratio,4))
print(f"Max Drawdown: {round(max_dd,4)}%")
longwins=0
longlosses=0
shortwins=0
shortlosses=0
longCash = 0
shortCash = 0
for trade in cashout:
if trade['position']=='long' and trade['type'] == 'win':
longwins+=1
elif trade['position']=='long' and trade['type'] == 'loss':
longlosses+=1
elif trade['position']=='short' and trade['type'] == 'win':
shortwins+=1
elif trade['position']=='short' and trade['type'] == 'loss':
shortlosses+=1
if trade['position'] == 'long':
longCash+=float(trade['Profit'])
else:
shortCash+=float(trade['Profit'])
print("Trades Made: ",len(trades))
print("Successful Trades:",correct)
print("Accuracy: ",(correct/tradeNO)*100)
print("Win/Loss Ratio: ",{correct/(tradeNO-correct)})
print("Profit before fees: ",shortCash+longCash)
print("Trading fees paid: ",fees_paid)
try:
print("# Shorts:", shortwins + shortlosses)
print("Short W/L ratio:",shortwins/shortlosses)
print("Profit from Shorts:",shortCash)
except Exception as E:
pass
try:
print("# Longs:",longwins+longlosses)
print("Long W/L ratio:", longwins / longlosses)
print("Profit from Longs:", longCash)
except Exception as E:
pass
print("Winning Trades: ",winning_trades,"\n","Losing Trades: ",losing_trades)
plt.plot(profitgraph)
plt.title(f"{symbol}: {original_time_interval} from {start} to {end}")
plt.ylabel('Dollars')
plt.xlabel('# Trades')
plt.show()