-
Notifications
You must be signed in to change notification settings - Fork 0
/
T32_v5.py
1376 lines (1213 loc) · 61.6 KB
/
T32_v5.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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import matplotlib.pyplot as plt
import random, shutil, pickle, sys
import numpy as np
from collections import deque
from keras import Sequential
from keras.optimizers import RMSprop
from IPython.display import display
from PIL import Image
import pandas as pd
from keras import Model
import keras, os, glob
import tensorflow as tf
from keras.layers import Layer, Dense, Conv2D, Flatten, RepeatVector,Dropout, LayerNormalization, MultiHeadAttention, GlobalAveragePooling1D
from keras.layers import Activation, LSTM, Bidirectional , Dropout
from keras import layers
# import cv2
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
import codecs
import csv
import secrets
import sqlite3
from IPython.display import display
from IPython.display import clear_output
import time
from tabulate import tabulate
import json
import datetime
from tensorflow.keras.optimizers import Adam
import math, datetime
# log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
class ChartDecorator:
def __init__(self):
self.balance_limit = 300
self.standard_balance = 1000
self.prev_trade = None
def add_top_bottom_bar(self, img, draw_context):
# Define the coordinates of the black bar
x1, y1 = 0, 204
x2, y2 = 200, 224
# Draw the black bar bottom bar
draw_context.rectangle([x1, y1, x2, y2], fill=(0, 0, 0))
# Draw the black bar top bar
x1, y1 = 0, 0
x2, y2 = 224, 14
draw_context.rectangle([x1, y1, x2, y2], fill=(0, 0, 0))
def draw_account_balance(self, img, draw_context, account_balance = 1000):
balance = self.balance_limit + (account_balance - self.standard_balance)
if balance == self.balance_limit:
x1, y1 = 3, 204
x2, y2 = 75 , 224
# Draw the green bar for account
draw_context.rectangle([x1, y1, x2, y2], fill=(110, 235, 131))
elif balance < self.balance_limit:
health_bar = int((balance * 75) / self.balance_limit )
lost_bar = 75 - health_bar
#issue 1
# print(f"issue 1 balance {balance}")
# print(f"health bar {health_bar}")
# print(f"lost bar {lost_bar}")
#current_balnace
x1, y1 = 3, 204
x2, y2 = health_bar, 224
draw_context.rectangle([x1, y1, x2, y2], fill=(110, 235, 131))
#lost bar
x1, y1 = health_bar, 204
x2, y2 = 75 , 224
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 0, 0))
elif balance > self.balance_limit:
x1, y1 = 3, 204
x2, y2 = 75 , 224
# Draw the green bar for account
draw_context.rectangle([x1, y1, x2, y2], fill=(110, 235, 131))
#Draw the profit section on account_bar
profit = int(((balance - self.balance_limit) * 75) / self.balance_limit)
x1, y1 = 80, 204
x2, y2 = 80 + profit , 224
# Draw the green bar for account
draw_context.rectangle([x1, y1, x2, y2], fill=(0,0,255))# fill=(71, 44, 27))
#draw start separator
#draw Account Separator and end separator
x1, y1 = 0, 204
x2, y2 = 3 , 224
# Draw the green bar for account
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 87, 20))
#draw Account Separator and end separator
x1, y1 = 76, 204
x2, y2 = 80 , 224
# Draw the green bar for account
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 87, 20))
#draw Account Separator and end separator
x1, y1 = 155, 204
x2, y2 = 160 , 224
# Draw the green bar for account
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 87, 20))
def draw_current_trade(self,img, draw_context, position=None):
if position == "buy":
x1, y1 = 160, 204
x2, y2 = 175, 224
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 255, 0))
elif position == "sell":
x1, y1 = 180, 204
x2, y2 = 195, 224
draw_context.rectangle([x1, y1, x2, y2], fill=(0, 255, 0))
else:
x1, y1 = 200, 204
x2, y2 = 215, 224
draw_context.rectangle([x1, y1, x2, y2], fill=(255,0,255))
#Draw position separator icons
x1, y1 = 175, 204
x2, y2 = 180, 224
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 255, 255))
x1, y1 = 195, 204
x2, y2 = 200, 224
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 255, 255))
x1, y1 = 215, 204
x2, y2 = 220, 224
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 255, 255))
def draw_profit_bar(self, img, draw_context, profit = 0, account_balance = 1000, position = None):
pnl_parts = int(abs(profit) / 10)
for segment in range(0, 200, 10):
f = segment + 10
x1, y1 = segment+10, 0
x2, y2 = f + 1, 9
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 255, 255))
#display profit on the chart
if profit > 0 and pnl_parts > 0 and segment >= 100:
if segment < pnl_parts * 10 + 100:
x1, y1 = segment, 0
x2, y2 = segment + 10, 9
draw_context.rectangle([x1, y1, x2, y2], fill=(27, 152, 224))
elif profit < 0 and pnl_parts > 0 and segment <= 90 and segment >= 100 - abs(profit):
x1, y1 = segment, 0
x2, y2 = segment + 10, 9
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 0, 0))
#draw progressive account balance below profit bar
account_balance_bar = (200*account_balance)/2000
x1, y1 = 0, 10
x2, y2 = account_balance_bar, 14
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 119, 0))
#Add a closing indication at the top of the
if position == "close" and profit > 0 and self.prev_trade[2] == 1:
x1, y1 = 200, 0
x2, y2 = 224, 14
draw_context.rectangle([x1, y1, x2, y2], fill=(255, 255, 0))
elif position == "close" and profit > 0 and self.prev_trade == 2:
x1, y1 = 200, 0
x2, y2 = 224, 14
draw_context.rectangle([x1, y1, x2, y2], fill=(0, 255, 0))
elif position == "close" and profit < 0 and self.prev_trade in [2,1]:
x1, y1 = 200, 0
x2, y2 = 224, 14
draw_context.rectangle([x1, y1, x2, y2], fill=(255,0, 0))
def draw_buy_bar(self, img2, start_lines, end_lines, position = None, profit = 0, prev_trade=None, account_balance = 1100 ):
self.prev_trade = prev_trade
from PIL import Image, ImageDraw
d = ImageDraw.Draw(img2)
self.add_top_bottom_bar(img2, d)
self.draw_account_balance(img2, d, account_balance)
if position == "sell" and 2 in [self.prev_trade[3]]:
#draw icon for trade setup
self.draw_current_trade(img2, d, "sell")
fixed_ratio = False
#issue fix bug
#a situation where there is profit but since the trade was entered there were pertuabations of zooming and changing of window prices indicated on the subwindow
#fix this by giving a ratio use profit to check if we are profitable, then check if end lines are lower than start lines , use a ratio of 1px for 3 points
#when scaling the bar check the distance remaining behind you at the top of the window. start from index 14 your calculations
if profit >= 0 and start_lines["ask_line"] > end_lines["ask_line"] :
# print(f"\nRatio bug found {end_lines}\n")
ratio = 15 #int((start_lines["ask_line"] - end_lines["ask_line"] ) / 3)
if end_lines["ask_line"] - ratio < 14:
start_lines["ask_line"] = 14
start_lines["bid_line"] = 18
else:
start_lines["ask_line"] = end_lines["ask_line"] - ratio
start_lines["bid_line"] = end_lines["bid_line"] - ratio
fixed_ratio = True
# Draw indicator of trade start
line_color = (200,200,200)
top = (200, end_lines["ask_line"])
bottom = (200, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=20)
#Draw start marker for the trade
line_color = (0, 255, 0)
top = (200, start_lines["ask_line"])
bottom = (200, start_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=30)
#Draw start line for trade entry
line_color = (0, 255, 0)#(252, 81, 48)
top = (50, start_lines["ask_line"])
bottom = (50, start_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=250)
#Draw profit indicator of sell
if profit < 0:
#Draw the main bar of the trade position
if fixed_ratio:
line_color = (255, int(ratio/2+10), 0)
top = (200, start_lines["ask_line"])
bottom = (200,end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=int(ration/5)+10)
fixed_ratio = False
else:
line_color = (255, 0, 0)
top = (200, start_lines["ask_line"])
bottom = (200,end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
else:
line_color = (0, 255, 0)
top = (200, start_lines["ask_line"])
bottom = (200,end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
#Draw loss indicator for sell
self.draw_profit_bar(img2, d, profit)
elif position == "buy" and 1 in [self.prev_trade[3]]:
#issue fix bug 2
if profit >= 0 and end_lines["ask_line"] > start_lines["ask_line"]:
ratio = 15
if end_lines["bid_line"] + ratio > 204:
start_lines["ask_line"] = 200
start_lines["bid_line"] = 204
else:
start_lines["ask_line"] = end_lines["ask_line"] + ratio
start_lines["bid_line"] = end_lines["bid_line"] + ratio
#draw bottom right trade status sell , buy , close
self.draw_current_trade(img2, d, "buy") #
#Draw indicator of trade start
#Draw end marker
line_color = (65, 64, 102)
top = (200, end_lines["ask_line"])
bottom = (200, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=20)
#Draw start marker for buy
line_color = (255, 255, 0)
top = (200, start_lines["ask_line"])
bottom = (200, start_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=30)
#Draw start buy line across the chart
line_color = (255, 255, 0)#(255,0,200)
top = (50, start_lines["ask_line"])
bottom = (50, start_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=250)
if profit < 0:
line_color = (255, 0, 0)
top = (200, start_lines["ask_line"])
bottom = (200, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
else:
line_color = (255, 255, 0)
top = (200, start_lines["ask_line"])
bottom = (200, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
self.draw_profit_bar(img2, d, profit)
elif position in ["buy", "sell"] and self.prev_trade[3] == 0:
# print(f"Draw buy bar \n\nElse{position}\n\n:")
#draw main vertical bar
self.draw_current_trade(img2, d, "close")
line_color = (255,0,255)
top = (200, start_lines["ask_line"])
bottom = (200, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=15)
#draw end bar
line_color = (255,0,255)
top = (200, end_lines["ask_line"])
bottom = (200, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=30)
#Draw start marker and line
line_color = (255,0,255)
top = (200, start_lines["ask_line"])
bottom = (200, start_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=30)
line_color = (2, 8, 135)
top = (50, start_lines["ask_line"])
bottom = (50, start_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=250)
# self.draw_profit_bar(img2, d, profit)
if self.prev_trade[2] == 2 and profit > 0:
#print right bar for the trade that has closed
line_color = (0, 255, 0)
top = (213, start_lines["ask_line"])
bottom = (213, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
line_color = (241, 254, 198)
top = (190, start_lines["ask_line"])
bottom = (190, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
elif self.prev_trade[2] == 2 and profit < 0:
line_color = (0, 255, 0)
top = (213, start_lines["ask_line"])
bottom = (213, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
line_color = (255,0,0)
top = (190, start_lines["ask_line"])
bottom = (190, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
elif self.prev_trade[2] == 1 and profit > 0:
# print(f"\n\nHey I was here\n\n{self.prev_trade}")
line_color = (255, 255, 0)
top = (213, start_lines["ask_line"])
bottom = (213, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
line_color = (241, 254, 198)
top = (190, start_lines["ask_line"])
bottom = (190, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
elif self.prev_trade[2] == 1 and profit < 0:
line_color = (255, 255, 0)
top = (213, start_lines["ask_line"])
bottom = (213, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
line_color = (255,0,0)
top = (190, start_lines["ask_line"])
bottom = (190, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=10)
else :#:position == "close" and self.prev_trade[2] == 0:
self.draw_current_trade(img2, d, "close")
# print("I run for position Close")
line_color = (255,0,255)
top = (200, end_lines["ask_line"])
bottom = (200, end_lines["bid_line"])
d.line([top, bottom], fill=line_color, width=30)
self.draw_profit_bar(img2, d, profit, account_balance, position)
return img2
class ForexCustomEnv:
def __init__(self, m1short, m5short,chart_decorator):
self.m1short = m1short
self.m5short = m5short
self.trade_queue = deque(maxlen=4)
self.image_queue = deque(maxlen=4)
self.trade_queue_m5 = deque(maxlen=4)
self.image_queue_m5 = deque(maxlen=4)
self.dataset_directory = "colabM1M5/episode2/"
self.account_balance = 1000
self.env_draw = False
self.chart_decorator = chart_decorator
self.prev_trade = deque(maxlen=4)
self.prev_trade.append(0)
self.prev_trade.append(0)
self.prev_trade.append(0)
self.prev_trade.append(0)
self.current_step = 4
self.action = 0
self.position = "close"
def get_ask_bid_lines(self, image_path):
ask_bid_lines = {"ask_line":None, "bid_line":None, "key": 0}
img = Image.open(f"{self.dataset_directory}{image_path}")
img_data = np.array(img)
last_part = Image.fromarray(img_data[:,200:201,:])
img1_pixels = last_part.load()
ask_color = (255,0,0)
bid_color = (119, 136, 153)
for y in range(224):
if img1_pixels[0,y] == ask_color:
ask_bid_lines["ask_line"] = y
if img1_pixels[0,y] == bid_color:
ask_bid_lines["bid_line"] = y
if ask_bid_lines["ask_line"] == None:
# print("Gotcha")
ask_bid_lines["ask_line"] = ask_bid_lines["bid_line"] + 3
ask_bid_lines["bid_line"] = ask_bid_lines["bid_line"] + 6
return ask_bid_lines , img
def reset(self, current_step = 4):
self.current_step = current_step
linesq, imageq = self.get_ask_bid_lines(f"{self.m1short.iloc[self.current_step - 4]['image_path']}")
linesq["key"] = current_step - 4
linest, imaget = self.get_ask_bid_lines(f"{self.m1short.iloc[self.current_step - 3]['image_path']}")
linest["key"] = current_step - 3
liness, images = self.get_ask_bid_lines(f"{self.m1short.iloc[self.current_step - 2]['image_path']}")
liness["key"] = current_step - 2
linesc, imagec = self.get_ask_bid_lines(f"{self.m1short.iloc[self.current_step - 1]['image_path']}")
linesc["key"] = current_step - 1
linesq_m5, imageq_m5 = self.get_ask_bid_lines(f"{self.m5short.iloc[self.current_step - 4]['image_path']}")
linesq_m5["key"] = current_step - 4
linest_m5, imaget_m5 = self.get_ask_bid_lines(f"{self.m5short.iloc[self.current_step - 3]['image_path']}")
linest_m5["key"] = current_step - 3
liness_m5, images_m5 = self.get_ask_bid_lines(f"{self.m5short.iloc[self.current_step - 2]['image_path']}")
liness_m5["key"] = current_step - 2
linesc_m5, imagec_m5 = self.get_ask_bid_lines(f"{self.m5short.iloc[self.current_step - 1]['image_path']}")
linesc_m5["key"] = current_step - 1
self.trade_queue.append(linesq)
self.trade_queue.append(linest)
self.trade_queue.append(liness)
self.trade_queue.append(linesc)
self.image_queue.append(imageq)
self.image_queue.append(imaget)
self.image_queue.append(images)
self.image_queue.append(imagec)
self.trade_queue_m5.append(linesq_m5)
self.trade_queue_m5.append(linest_m5)
self.trade_queue_m5.append(liness_m5)
self.trade_queue_m5.append(linesc_m5)
self.image_queue_m5.append(imageq_m5)
self.image_queue_m5.append(imaget_m5)
self.image_queue_m5.append(images_m5)
self.image_queue_m5.append(imagec_m5)
self.done = 0
self.reward = 0
self.position = "close"
self.reset_current_trade()
self.account_balance = 1000
next_state = self.get_obs()
self.episode_profit = 0
self.prev_trade = deque(maxlen=4)
self.prev_trade.append(0)
self.prev_trade.append(0)
self.prev_trade.append(0)
self.prev_trade.append(0)
self.action = 0
#reset standard limit in chart decorator
self.chart_decorator.standard_limit = self.account_balance
return next_state, self.reward, self.done, self.current_trade
def reset_current_trade(self):
self.current_trade = {}
self.current_trade["current_step"] = self.current_step
self.current_trade["ask_bid_lines"] = None
self.current_trade["ask_bid_lines_m5"] = None
self.current_trade["entry_price"] = None
self.current_trade["current_price"] = None
self.current_trade["timesteps"] = 0
self.current_trade["position"] = "close"
self.current_trade["profit"] = 0
self.current_trade["position"] = None
self.current_trade["parent_ask_bid_lines"] = None
self.current_trade["reward"] = 0
self.current_trade["balance"] = self.account_balance
self.current_trade["episode_profit"] = 0
#this code is to add dimensions to 8 of them 4 for m1short 4 for m5short remaining to draw on m5 charts
self.current_trade["ask_bid_lines_m5"] = None
self.current_trade["parent_ask_bid_lines_m5"] = None
self.current_trade["highest"] = 0
def display_stacked_horizontally(self,imageq, imaget,images,imagec):
# # Calculate the required dimensions for the new image
new_width = imageq.width * 4
new_height = imageq.height
# # Create a new image with the required dimensions
new_image = Image.new("RGB", (new_width, new_height))
# # Paste the individual images side by side
new_image.paste(imageq, (0, 0))
new_image.paste(imaget, (imageq.width, 0))
new_image.paste(images, (imageq.width + imaget.width, 0))
new_image.paste(imagec, (imageq.width + imaget.width + images.width, 0))
def reset_collection(self, t_q, i_q):
_queue = deque(maxlen=4)
for i in range(0, 4):
_lines_c, _image_c = self.get_ask_bid_lines(f"{self.dataset_directory}{self.m1short.iloc[t_q[i]['key']]['image_path']}")
_image_c = self.draw_buy_bar(_image_c, _lines_c, _lines_c, position="close", profit = 0)
_queue.append(_image_c)
return t_q, _queue
def draw_collection(self,q):
# # Calculate the required dimensions for the new image
new_width = q[0].width * 4
new_height =q[0].height
# # Create a new image with the required dimensions
new_image = Image.new("RGB", (new_width, new_height))
# # Paste the individual images side by side
new_image.paste(q[0], (0, 0))
new_image.paste(q[1], (q[0].width, 0))
new_image.paste(q[2], (q[0].width + q[0].width, 0))
new_image.paste(q[3], (q[0].width + q[0].width + q[0].width, 0))
display(new_image)
def draw_buy_bar(self, current_image, start_lines, end_lines, position = None, profit = 0, prev_trade=None):
# self.position = position
# self.profit = profit
return self.chart_decorator.draw_buy_bar(current_image, start_lines, end_lines, self.position, profit, prev_trade, self.account_balance)
'''
@description: Enters a trade in the forex environment
Enters the trade in the current time step, sets the position of the trade. sets the ask bid lines for the current frame
sets the entry price for the trade, and profit = 0. Then draws on the image the entry icon on the chart
and saves the updated current_image with modifications to the image queue with its corresponding ask and bid lines.
then initializes the timesteps of the current trade to 0. sets the reward to 0.2
@params
@position = None the position of the current_trade
@ask_bid_lines of the current_image
@current_image the current frame of the environment
'''
def softplus_reward(self, profit, time_step, max_profit=0.1,position = "close",threshold=0.8):
loss = -min(profit,0)
#=============added but will delete============
threshold = 0.75 * max_profit if profit > 0 else 0.8 #=
if time_step <= 3 and (profit >= 0 and profit <= 10 and position in ["sell", "buy"]):
time_step = 3
profit = 4
#==============================================
reward = np.log(1 + np.exp((profit - loss - threshold) /2 )) - np.log(2) + np.log(1 + np.exp(-time_step/40))
return reward/10 if profit > 0 else reward*10
def get_reward(self, c_trade):
return self.softplus_reward(c_trade["profit"], c_trade["timesteps"], c_trade["highest"], c_trade["position"])
def enter_trade(self, ask_bid_lines, ask_bid_lines_m5,current_image, current_image_m5):
self.current_trade["position"] = self.position
self.current_trade["ask_bid_lines"] = ask_bid_lines
self.current_trade["ask_bid_lines_m5"] = ask_bid_lines_m5
self.current_trade["entry_price"] = float(f"{self.m1short.iloc[self.current_step]['Ask']}") if self.position == "buy" else float(f"{self.m1short.iloc[self.current_step]['Bid']}")
self.current_trade["profit"] = 0.05
self.current_trade["current_price"] = float(f"{self.m1short.iloc[self.current_step]['Ask']}")
self.current_trade["timesteps"] = 2
self.current_trade["parent_ask_bid_lines"] = ask_bid_lines
self.current_trade["parent_ask_bid_lines_m5"] = ask_bid_lines_m5
self.current_trade["balance"] = self.account_balance
self.current_trade["highest"] = 0.01
#self.current_trade["highest"] += 5
current_image = self.draw_buy_bar(current_image, ask_bid_lines, ask_bid_lines, self.position , self.current_trade["profit"], self.prev_trade )
current_image_m5 = self.draw_buy_bar(current_image_m5, ask_bid_lines_m5, ask_bid_lines_m5, self.position, self.current_trade["profit"], self.prev_trade)
self.trade_queue.append(ask_bid_lines)
self.trade_queue_m5.append(ask_bid_lines_m5)
self.image_queue.append(current_image)
self.image_queue_m5.append(current_image_m5)
if self.env_draw:
self.draw_collection(self.image_queue)
self.draw_collection(self.image_queue_m5)
self.reward = self.get_reward(self.current_trade) #self.account_balance/self.account_balance
self.current_trade["reward"] = self.reward
def enter_idle_mode(self, ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5 ):
self.current_trade["ask_bid_lines"] = ask_bid_lines
self.current_trade["ask_bid_lines_m5"] = ask_bid_lines_m5
self.current_trade["entry_price"] = float(f"{self.m1short.iloc[self.current_step]['Ask']}")
self.current_trade["current_price"] = float(f"{self.m1short.iloc[self.current_step]['Ask']}")
self.current_trade["position"] = self.position
self.current_trade["reward"] = -0.5
self.current_trade["timesteps"] = 2
self.current_trade["profit"] = -3
self.current_trade["parent_ask_bid_lines"] = None
self.current_trade["parent_ask_bid_lines_m5"] = None
self.current_trade["balance"] = self.account_balance
current_image = self.draw_buy_bar(current_image, ask_bid_lines, ask_bid_lines, self.position, self.current_trade["profit"], self.prev_trade)
current_image_m5 = self.draw_buy_bar(current_image_m5, ask_bid_lines_m5, ask_bid_lines_m5, self.position, self.current_trade["profit"], self.prev_trade)
self.trade_queue.append(ask_bid_lines)
self.trade_queue_m5.append(ask_bid_lines_m5)
self.image_queue.append(current_image)
self.image_queue_m5.append(current_image_m5)
if self.env_draw:
self.draw_collection(self.image_queue)
self.draw_collection(self.image_queue_m5)
self.reward = self.get_reward(self.current_trade)
self.current_trade["reward"] = self.reward
def hold_position(self,ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5):
self.current_trade["current_price"] = float(f"{self.m1short.iloc[self.current_step]['Bid']}") if self.position == "buy" else float(f"{self.m1short.iloc[self.current_step]['Ask']}")
self.current_trade["profit"] = self.current_trade["current_price"] - self.current_trade["entry_price"] if self.position == "buy" else self.current_trade["entry_price"] - self.current_trade["current_price"]
self.current_trade["timesteps"] += 1
self.current_trade["balance"] = self.account_balance
self.current_trade["highest"] = self.current_trade["profit"] if self.current_trade["profit"] > self.current_trade["highest"] else self.current_trade["highest"]
#self.current_trade["highest"] -= 15
current_image = self.draw_buy_bar(current_image, self.current_trade["parent_ask_bid_lines"], ask_bid_lines, self.position , self.current_trade["profit"], self.prev_trade)
current_image_m5 = self.draw_buy_bar(current_image_m5, self.current_trade["parent_ask_bid_lines_m5"], ask_bid_lines_m5, self.position, self.current_trade["profit"], self.prev_trade)
self.trade_queue.append(ask_bid_lines)
self.trade_queue_m5.append(ask_bid_lines_m5)
self.image_queue.append(current_image)
self.image_queue_m5.append(current_image_m5)
if self.env_draw:
self.draw_collection(self.image_queue)
self.draw_collection(self.image_queue_m5)
if self.current_trade["profit"] >= 0:
self.reward = self.get_reward(self.current_trade)#(self.account_balance + self.current_trade["profit"])/self.account_balance
self.current_trade["reward"] = self.reward
else:
self.reward = self.get_reward(self.current_trade)#-1 - (self.account_balance + self.current_trade["profit"])/self.account_balance
self.current_trade["reward"] = self.reward
def close_position(self, ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5, prev_trade = None):
# print(f"self.position {self.position}")
self.current_trade["current_price"] = float(f"{self.m1short.iloc[self.current_step]['Bid']}") if self.position == "buy" else float(f"{self.m1short.iloc[self.current_step]['Ask']}")
self.current_trade["profit"] = self.current_trade["current_price"] - self.current_trade["entry_price"] if self.position == "buy" else self.current_trade["entry_price"] - self.current_trade["current_price"]
self.current_trade["highest"] = self.current_trade["profit"] if self.current_trade["profit"] > self.current_trade["highest"] else self.current_trade["highest"]
#self.current_trade["highest"] += 5
current_image = self.draw_buy_bar(current_image, self.parent_ask_bid_lines, ask_bid_lines, self.position, self.current_trade["profit"] , prev_trade)
current_image_m5 = self.draw_buy_bar(current_image_m5, self.parent_ask_bid_lines_m5, ask_bid_lines_m5, self.position, self.current_trade["profit"], prev_trade)
self.trade_queue.append(ask_bid_lines)
self.trade_queue_m5.append(ask_bid_lines_m5)
self.image_queue.append(current_image)
self.image_queue_m5.append(current_image_m5)
self.account_balance += self.current_trade["profit"]
if self.env_draw:
self.draw_collection(self.image_queue)
self.draw_collection(self.image_queue_m5)
if self.current_trade["profit"] >= 0:
self.reward = self.get_reward(self.current_trade)##(self.account_balance + self.current_trade["profit"])/self.account_balance
else:
self.reward = self.get_reward(self.current_trade)#-1 - (self.account_balance + self.current_trade["profit"])/self.account_balance
#self.trade_queue, self.image_queue = self.reset_collection(self.trade_queue,self.image_queue)
# self.account_balance += self.current_trade["profit"]
self.current_trade["current_timestep"] = self.current_step
self.current_trade["timesteps"] += 1
self.current_trade["position"] = "close"
self.current_trade["balance"] = self.account_balance
self.current_trade["episode_profit"] = self.episode_profit
self.position = "close"
self.parent_ask_bid = None
def step(self, action):
self.reward = 0
self.done = 0
self.action = action
self.old_balance = self.account_balance
ask_bid_lines, current_image = self.get_ask_bid_lines(f"{self.m1short.iloc[self.current_step]['image_path']}")
ask_bid_lines_m5, current_image_m5 = self.get_ask_bid_lines(f"{self.m5short.iloc[self.current_step]['image_path']}")
ask_bid_lines["key"] = self.current_step
ask_bid_lines_m5["key"] = self.current_step
if self.position == "close":
if action == 1:
self.position = "buy"
self.prev_trade.append(1)
self.parent_ask_bid_lines = ask_bid_lines
self.parent_ask_bid_lines_m5 = ask_bid_lines_m5
self.enter_trade(ask_bid_lines, ask_bid_lines_m5,current_image, current_image_m5)
elif action == 2:
self.position = "sell"
self.prev_trade.append(2)
self.parent_ask_bid_lines = ask_bid_lines
self.parent_ask_bid_lines_m5 = ask_bid_lines_m5
self.enter_trade(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5)
elif action == 0:
self.position = "close"
self.prev_trade.append(0)
self.parent_ask_bid_lines = ask_bid_lines
self.parent_ask_bid_lines_m5 = ask_bid_lines_m5
self.enter_idle_mode(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5)
elif self.position == "buy":
if action == 1:
self.prev_trade.append(1)
self.hold_position(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5)
elif action in [2]:
self.prev_trade.append(0)
self.close_position(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5, self.prev_trade)
#fix standard limit and standard balance on chart
if self.account_balance > int((2/3) * self.chart_decorator.balance_limit) + self.chart_decorator.standard_balance:
# print("\n\nReseting the account balance in closing buy trade using 2\n\n the if statement\n\n\n")
self.chart_decorator.standard_balance = self.account_balance
# elif self.chart_decorator.standard_balance * (2/3) > self.account_balance :
# print("\n\nReseting the account balance in closing buy trade using 2\n\n the elif statement\n\n\n")
# self.chart_decorator.standard_balance -= self.chart_decorator.balance_limit
# self.reward = (self.account_balance + self.current_trade["profit"])/1000
# self.current_trade["reward"] = (self.account_balance + self.current_trade["profit"])/1000
elif action in [0]:
self.prev_trade.append(0)
self.close_position(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5, self.prev_trade)
#fix standard limit and standard balance on chart
if self.account_balance > int((2/3) * self.chart_decorator.balance_limit) + self.chart_decorator.standard_balance:
# print("\n\nReseting the account balance in closing buy trade using 0\n\n the if statement\n\n\n")
self.chart_decorator.standard_balance = self.account_balance
# elif self.chart_decorator.standard_balance * (2/3) > self.account_balance :
# print("\n\nReseting the account balance in closing buy trade using 0\n\n the elif statement\n\n\n")
# self.chart_decorator.standard_balance -= self.chart_decorator.balance_limit
elif self.position == "sell":
if action == 2:
self.prev_trade.append(2)
self.hold_position(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5)
#this reward is to penalize it not to change the position without closing the position
elif action in [1]:
self.prev_trade.append(0)
self.close_position(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5, self.prev_trade)
#fix standard limit and standard balance on chart
if self.account_balance > int((2/3) * self.chart_decorator.balance_limit) + self.chart_decorator.standard_balance:
# print("\n\nReseting the account balance in closing sell trade using 1\n\n the if statement\n\n\n")
self.chart_decorator.standard_balance = self.account_balance
# elif self.chart_decorator.standard_balance * (2/3) > self.account_balance :
# print("\n\nReseting the account balance in closing sell trade using 1\n\n the elif statement\n\n\n")
# self.chart_decorator.standard_balance -= self.chart_decorator.balance_limit
# self.reward = (self.account_balance + self.current_trade["profit"])/1000
# self.current_trade["reward"] = (self.account_balance + self.current_trade["profit"])/1000
elif action == 0:
self.prev_trade.append(0)
self.close_position(ask_bid_lines, ask_bid_lines_m5, current_image, current_image_m5, self.prev_trade)
# self.prev_trade.append(0)
#fix standard limit and standard balance on chart
if self.account_balance > int((2/3) * self.chart_decorator.balance_limit) + self.chart_decorator.standard_balance:
# print("\n\nReseting the account balance in closing sell trade using 0\n\n the if statement\n\n\n")
# print(f"Account Balance == {self.account_balance} chart decorator standard_balance {self.chart_decorator.standard_balance}")
self.chart_decorator.standard_balance = self.account_balance
# print(f"updated standard balance == {self.chart_decorator.standard_balance}")
# elif self.chart_decorator.standard_balance * (2/3) > self.account_balance :
# print("\n\nReseting the account balance in closing sell trade using 0\n\n the elif statement\n\n\n")
# self.chart_decorator.standard_balance -= self.chart_decorator.balance_limit
self.current_step+=1
next_state = self.get_obs()
if self.account_balance < 800:
self.done = 1
# print(self.trade_queue)
self.old_balance = self.account_balance
return next_state, self.reward, self.done, self.current_trade
def get_obs(self):
stacked_obs = np.expand_dims(np.stack([
np.asarray(self.image_queue_m5[0])/255,
np.asarray(self.image_queue_m5[1])/255,
np.asarray(self.image_queue_m5[2])/255,
np.asarray(self.image_queue_m5[3])/255,
np.asarray(self.image_queue[0])/255,
np.asarray(self.image_queue[1])/255,
np.asarray(self.image_queue[2])/255,
np.asarray(self.image_queue[3])/255
]), axis=0)
# stacked_obs_m5 = np.expand_dims(np.stack([np.asarray(self.image_queue_m5[0])/255, np.asarray(self.image_queue_m5[1])/255, np.asarray(self.image_queue_m5[2])/255, np.asarray(self.image_queue_m5[3])/255]), axis=0)
# stacked = np.concatenate([stacked_obs_m5, stacked_obs], axis=0)
return np.expand_dims(stacked_obs, axis=0)
class TimeSformerBlock(tf.keras.layers.Layer):
def __init__(self, hidden_dim, num_heads):
super(TimeSformerBlock, self).__init__()
# Define the self-attention layer
self.self_attention = tf.keras.layers.MultiHeadAttention(num_heads=num_heads, key_dim=hidden_dim)
# Define the feedforward layer
self.feedforward = tf.keras.Sequential([
tf.keras.layers.Dense(hidden_dim * 4, activation='relu'),
tf.keras.layers.Dense(hidden_dim)
])
# Define the layer normalization layers
self.norm1 = tf.keras.layers.LayerNormalization()
self.norm2 = tf.keras.layers.LayerNormalization()
def call(self, x):
# Apply layer normalization and self-attention
norm_x = self.norm1(x)
attention_output = self.self_attention(norm_x, norm_x)
x = x + attention_output
# Apply layer normalization and feedforward layer
norm_x = self.norm2(x)
feedforward_output = self.feedforward(norm_x)
x = x + feedforward_output
return x
class Agent:
def __init__(self, state_size, action_size, env, learning_rate=0.001):
self.state_size = state_size
self.action_size = action_size
self.learning_rate = learning_rate
self.epsilon = 0.001
self.epsilon_min = 0.01
self.epsilon_decay = 0.99
self.gamma = 0.1
self.env = env
self.actor = self._actor_model()
self.critic = self._critic_model()
# self.critic.set_weights(self.actor.get_weights())
self.models_dir = "models/attention/"
self.actor_model_name = "256_T32_v5AdvantageR_att_actor.h5"
self.critic_model_name = "256_T32_v5AdvantageR_att_critic.h5"
self.actor.summary()
#self.log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
#self.callback = tf.keras.callbacks.TensorBoard(log_dir=self.log_dir, histogram_freq = 1)
def _actor_model(self):
cnn = Sequential()
cnn.add(tf.keras.layers.Conv3D(32, (3,3,3), strides=(1,4,4), padding="same"))
cnn.add(Activation('relu'))
cnn.add(tf.keras.layers.MaxPooling3D(pool_size=(1,2,2), strides=(1,2,2), padding='same'))
cnn.add(tf.keras.layers.Conv3D(64, (3,3,3), padding="same"))
cnn.add(Activation('relu'))
cnn.add(tf.keras.layers.MaxPooling3D(pool_size=(1,2,2), strides=(1,2,2), padding='same'))
cnn.add(tf.keras.layers.Conv3D(64, (3,3,3), padding="same"))
cnn.add(Activation('relu'))
cnn.add(Flatten())
cnn.add(Dense(256, activation='relu'))
transformer = TimeSformerBlock( num_heads=8, hidden_dim=256)
model=Sequential()
model.add(tf.keras.layers.TimeDistributed(cnn,input_shape=self.state_size))
model.add(transformer)
model.add(Dense(256, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(self.action_size, activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer=Adam(learning_rate=1e-5))
return model
def _critic_model(self):
cnn = Sequential()
cnn.add(tf.keras.layers.Conv3D(32, (3,3,3), strides=(1,4,4), padding="same"))
cnn.add(Activation('relu'))
cnn.add(tf.keras.layers.MaxPooling3D(pool_size=(1,2,2), strides=(1,2,2), padding='same'))
cnn.add(tf.keras.layers.Conv3D(64, (3,3,3), padding="same"))
cnn.add(Activation('relu'))
cnn.add(tf.keras.layers.MaxPooling3D(pool_size=(1,2,2), strides=(1,2,2), padding='same'))
cnn.add(tf.keras.layers.Conv3D(64, (3,3,3), padding="same"))
cnn.add(Activation('relu'))
cnn.add(Flatten())
cnn.add(Dense(256, activation='relu'))
transformer = TimeSformerBlock( num_heads=8, hidden_dim=256)
model=Sequential()
model.add(tf.keras.layers.TimeDistributed(cnn,input_shape=self.state_size))
model.add(transformer)
model.add(Dense(256, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(self.action_size, activation='softmax'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mse',optimizer=Adam(learning_rate=1e-5))
return model
def predict(self, state):
return self.actor.predict(state)
def save(self):
self.actor.save(f"{self.models_dir}{self.actor_model_name}")
self.critic.save(f"{self.models_dir}{self.critic_model_name}")
def act(self, state):
if np.random.rand() <= self.epsilon:
return secrets.randbelow(self.action_size) if np.random.choice(20) % 2 == 0 else np.random.choice(self.action_size) , [[0,0,0]]
else:
pred = self.actor.predict(state)
return np.argmax(pred[0][0]), pred
def load(self):
self.actor.load_weights(f"{self.models_dir}{self.actor_model_name}")
self.critic.load_weights(f"{self.models_dir}{self.critic_model_name}")
def test_agent(self, draw=False):
header = ["step","action", "reward", "done","profit", "Episode Profit", "balance", "Eprice", "Cprice", ]
state, reward, done, current_trade = self.env.reset(800)
profits = 0
clear_output(wait=True)
chart_decorator = ChartDecorator()
env = ForexCustomEnv(m1short,m5short, chart_decorator)
self.env = env
self.env.env_draw = draw
# agent = Agent(state_size, action, env)
self.env.account_balance = 1000
self.epsilon = 0.001#1.0
state, reward, done, _ = self.env.reset(4)
for step in range(600, 1200, 1):
rows = []
action, pred = self.act(state)
value = self.critic.predict(state)[0][0]
next_state, reward, done, current_trade = self.env.step(action)
_next_value = self.critic.predict(next_state)[0][0]
print(f"reward {reward}")
advantage = reward + self.gamma * (1-done) * _next_value
if action == 0:
profits += current_trade["profit"]
row = [step, action, reward,done, current_trade["profit"], profits , current_trade["balance"], current_trade["entry_price"], current_trade["current_price"]]
rows.append(row)
print(tabulate(rows, headers=header, tablefmt='grid'))
print(f"actor {pred} critic {value}")
# print(f"current_trade {current_trade}\n")
pred[0][0][action] = advantage
self.actor.fit(state, pred)
self.critic.fit(state, [[[ reward + self.gamma * (1-done) * _next_value ]]])
state = next_state
# profits.append(current_trade["profit"])
def train(self, num_episodes, draw = False, epsilon = 0.001):
header = ["episode","epsilon", "counter","action", "done" ,"profit", "balance","Eprice","Cprice", "critic target_f_values","advantage", "actor pred qvls", "fit actor q_values"]
self.episode_rewards = []
target_f_values = []
for episode in range(num_episodes):
clear_output(wait=True)
chart_decorator = ChartDecorator()
env = ForexCustomEnv(m1short,m5short, chart_decorator)
self.env = env
self.env.account_balance = 1000
self.epsilon = epsilon
self.env.env_draw = draw
state, reward, done, _ = self.env.reset(20)
total_rewards = 0
counter = 20
total_profits = 0
while not done:
rows = []
action, pred = self.act(state)
next_state, reward, done, current_trade = self.env.step(action)
total_rewards += reward
total_profits += current_trade["profit"]
#v_current = self.critic.predict(state)[0][0]
target_f_values = self.critic.predict(next_state)[0][0]
advantage = reward + self.gamma * ( 1 - done ) * target_f_values
q_values = self.actor.predict(state)
q_values_copy = np.array(q_values, copy=True)
q_values_copy[0][0][action] = advantage
row = [episode,self.epsilon,counter, action, done, current_trade["profit"], current_trade["balance"],current_trade["entry_price"], current_trade["current_price"], target_f_values, advantage, ",".join(str("{:.2f}".format(x)) for x in list(q_values)[0][0]),",".join(str("{:.2f}".format(x)) for x in list(q_values_copy)[0][0])]
rows.append(row)
print(tabulate(rows,headers = header, tablefmt="grid"))
# except Exception as e:
# print(f"Exception {e}")
#PPO optimization done later after model training fitting critic on the action space of the actor resulted in a data leakage of the model
self.critic.fit(state, np.array(reward + self.gamma * (1-done) * target_f_values ).reshape(1,1,1) , verbose=0)
q_values[0][0][action] = advantage
self.actor.fit(state, q_values, verbose=0)
state = next_state
if counter % 100 == 0 and counter > 0:
self.save()
# Decay the exploration rate
if self.epsilon > self.epsilon_min and counter % 40 == 0:
self.epsilon *= self.epsilon_decay
if counter > 600:
done = True
counter += 1
clear_output(wait=True)
if episode % 3 == 0: