-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEMA_Shift_Multi_Strategy.py
More file actions
1441 lines (1191 loc) · 60 KB
/
EMA_Shift_Multi_Strategy.py
File metadata and controls
1441 lines (1191 loc) · 60 KB
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 random
import sys
import time
import os
import json
import requests
import backtrader as bt
from backtrader.utils import date2num, num2date
import pickle
from datetime import datetime
from types import SimpleNamespace
import threading
import pandas as pd
import numpy as np
import math
import pprint
from binance.helpers import round_step_size
from binance import Client
from bt_tools import Logger, TaskScheduler, GoogleDriveConnect, get_asset_balance, get_futures_positions
from binance_excel_saver import BinanceExcelSaver
from candlestick_chart import CandlestickChart
class CollectData:
def __init__(self, length, is_live_run,
init_price=69250.0,
worker_no=0,
symbol="",
total_data_len=100000,
set_life_signal=object):
self.symbol = symbol
self.length = length
self.worker_no = worker_no
self.open_history = np.full(length, init_price, dtype=np.float64)
self.high_history = np.full(length, init_price, dtype=np.float64)
self.low_history = np.full(length, init_price, dtype=np.float64)
self.close_history = np.full(length, init_price, dtype=np.float64)
self.ema_fast_long_data_history = np.full(length, init_price, dtype=np.float64)
self.ema_fast_long_down_shift_data_history = np.full(length, init_price, dtype=np.float64)
self.ema_slow_long_data_history = np.full(length, init_price, dtype=np.float64)
self.ema_fast_short_data_history = np.full(length, init_price, dtype=np.float64)
self.ema_fast_short_up_shift_data_history = np.full(length, init_price, dtype=np.float64)
self.ema_slow_short_data_history = np.full(length, init_price, dtype=np.float64)
# ennek nem elég a length ennek a teljes futást rögzíteni kell
# TODO: megkapja a DF.sahapét
self.portfolio_value = np.full(total_data_len, 0.0, dtype=np.float64)
self.long_signal = np.full(length, 0, dtype=np.int8)
self.short_signal = np.full(length, 0, dtype=np.int8)
# záróár
self.open = 0
self.high = 0
self.low = 0
self.close = 0
self.decision = np.full(length, 0, dtype=np.int8)
self.meta = {}
self.is_live_run = is_live_run
self.logger = Logger()
self.log = self.logger.log
if self.is_live_run:
self.set_life_signal = set_life_signal
@staticmethod
def s_round(value):
decimal = 8
return round(value, decimal)
def add_que(self, array, data):
# array = np.append(array, data)
# if len(array) > self.length:
# array = array[1:-1]
alen = len(array)
array[1:] = array[0:alen - 1]
array[0] = self.s_round(data)
def add_signal(self, long_signal, short_signal):
long_signal = int(long_signal)
short_signal = int(short_signal)
self.add_que(self.long_signal, long_signal)
self.add_que(self.short_signal, short_signal)
if self.is_live_run:
self.set_life_signal(key="CollectData_1" + str(self.symbol),
cclass="CollectData",
method="add_signal",
msg1=str(self.symbol),
msg2="",
msg3=""
)
def add_data(self, data,
ema_fast_long_data,
ema_fast_long_down_shift_data,
ema_slow_long_data,
ema_fast_short_data,
ema_fast_short_up_shift_data,
ema_slow_short_data,
portfolio_value
):
self.add_que(self.open_history, float(data.open[0]))
self.add_que(self.high_history, float(data.high[0]))
self.add_que(self.low_history, float(data.low[0]))
self.add_que(self.close_history, round(float(data.close[0]), 8))
self.add_que(self.ema_fast_long_data_history, float(ema_fast_long_data))
self.add_que(self.ema_fast_long_down_shift_data_history, float(ema_fast_long_down_shift_data))
self.add_que(self.ema_slow_long_data_history, float(ema_slow_long_data))
self.add_que(self.ema_fast_short_data_history, float(ema_fast_short_data))
self.add_que(self.ema_fast_short_up_shift_data_history, float(ema_fast_short_up_shift_data))
self.add_que(self.ema_slow_short_data_history, float(ema_slow_short_data))
self.add_que(self.portfolio_value, float(portfolio_value))
self.open = float(data.open[0])
self.high = float(data.high[0])
self.low = float(data.low[0])
self.close = round(float(data.close[0]), 1)
self.add_que(self.decision, int(0))
# if self.is_live_run:
# self.set_life_signal(key="CollectData_2" + str(self.symbol),
# cclass="CollectData",
# method="add_data",
# msg1=str(self.symbol),
# msg2="",
# msg3=""
# )
def add_meta(self, field, value):
if self.is_live_run:
self.meta[field] = str(value)
# def get_save_meta(self):
# return self.meta
def get_save_data(self):
save_data = {
'symbol': self.symbol,
'open_history': tuple(self.open_history),
'high_history': tuple(self.high_history),
'low_history': tuple(self.low_history),
'close_history': tuple(self.close_history),
'ema_fast_long_data_history': tuple(self.ema_fast_long_data_history),
'ema_fast_long_down_shift_data_history': tuple(self.ema_fast_long_down_shift_data_history),
'ema_slow_long_data_history': tuple(self.ema_slow_long_data_history),
'ema_fast_short_data_history': tuple(self.ema_fast_short_data_history),
'ema_fast_short_up_shift_data_history': tuple(self.ema_fast_short_up_shift_data_history),
'ema_slow_short_data_history': tuple(self.ema_slow_short_data_history),
'decision': tuple(self.decision),
'meta': self.meta
}
return save_data
# with open('data_transfer_for_process.pickle', 'wb') as handle:
# pickle.dump(save_data_form, handle, protocol=pickle.HIGHEST_PROTOCOL)
class OnePositionSizer(bt.Sizer):
def __init__(self, symbols, percent=80, start_cash=100000, is_live_run=False):
self.percent = percent / 100
self.start_cash = start_cash
self.is_live_run = is_live_run
self.logger = Logger()
self.log = self.logger.log
self.min_qty = {}
self.max_qty = {}
self.step_size = {}
self.min_notional = {}
self.symbol_info = {}
self.symbols = symbols
self.num_of_symbols = len(self.symbols)
self.set_life_signal = object
def has_open_position(self):
# Check if there is any open position across all assets
for idata, position in self.broker.positions.items():
# for position in self.broker.positions:
if position.size != 0:
return True
return False
def is_valid_quantity(self, symbol, qty):
if not (self.min_qty[symbol] <= abs(qty) <= self.max_qty[symbol]):
return False
return True
def round_to_step(self, symbol, qty):
return round(qty / self.step_size[symbol]) * self.step_size[symbol]
def round_down_to_step(self, symbol, qty):
round_down = (qty // self.step_size[symbol]) * self.step_size[symbol]
return round_step_size(round_down, self.step_size[symbol])
def start(self):
if self.is_live_run:
for symbol in self.symbols:
self.log(f"Get market info: {symbol}", level=10)
self.symbol_info[symbol] = self.broker.futures_symbol_info(symbol)
filter_params = [f for f in self.symbol_info[symbol]['filters'] if f.get('filterType') == 'MARKET_LOT_SIZE'][0]
self.min_qty[symbol] = float(filter_params.get('minQty', 0))
self.max_qty[symbol] = float(filter_params.get('maxQty', float('inf')))
self.step_size[symbol] = float(filter_params.get('stepSize', 1))
filter_params = [f for f in self.symbol_info[symbol]['filters'] if f.get('filterType') == 'MIN_NOTIONAL'][0]
self.min_notional[symbol] = float(filter_params.get('notional', 0))
def _getsizing(self, comminfo, cash, data, isbuy):
symbol = data._name
# if self.has_open_position():
# return 0
if self.is_live_run:
# size = (cash * self.percent) / data.close[0]
size = self.start_cash / data.close[0]
size = self.round_to_step(symbol, size)
if size == 0:
self.log(f"Sizer: Trade failed {symbol} Size 0")
print(f"Sizer: Trade failed {symbol} Size 0")
size = 0
elif not self.is_valid_quantity(symbol, size):
self.log(f"Sizer: Trade failed {symbol} invalid size (min, max, stepsize)")
size = None
elif self.min_notional[symbol] > (abs(size) * data.close[0]):
self.log(f"Sizer: Trade failed {symbol} min_notional")
size = None
else:
size = int((cash * self.percent) / 4) // data.close[0]
return size
def set(self, strategy, broker):
self.strategy = strategy
self.broker = broker
if self.is_live_run:
self.set_life_signal = self.broker.set_life_signal
self.start()
class ESMSizer(bt.Sizer):
def __init__(self, symbols, max_percent=70, start_cash=100000, force_num_of_symbols=None, is_live_run=False):
self.is_live_run = is_live_run
self.start_cash = start_cash
self.force_num_of_symbols = force_num_of_symbols
self.max_percent = max_percent
self.symbols = symbols
self.num_of_symbols = len(self.symbols)
self.min_qty = {}
self.max_qty = {}
self.step_size = {}
self.symbol_info = {}
self.symbols_position = {}
self.symbol_info = {}
self.min_notional = {}
for sy in self.symbols:
self.symbols_position[sy] = 0.0
self.logger = Logger()
self.log = self.logger.log
if self.is_live_run:
self.set_life_signal = object
def start(self):
if self.is_live_run:
for symbol in self.symbols:
self.log(f"Get market info: {symbol}", level=10)
if self.is_live_run:
self.symbol_info[symbol] = self.broker.futures_symbol_info(symbol)
else:
self.symbol_info[symbol] = self.get_symbol_info(symbol)
filter_params = [f for f in self.symbol_info[symbol]['filters'] if f.get('filterType') == 'MARKET_LOT_SIZE'][0]
self.min_qty[symbol] = float(filter_params.get('minQty', 0))
self.max_qty[symbol] = float(filter_params.get('maxQty', float('inf')))
self.step_size[symbol] = float(filter_params.get('stepSize', 1))
filter_params = [f for f in self.symbol_info[symbol]['filters'] if f.get('filterType') == 'MIN_NOTIONAL'][0]
self.min_notional[symbol] = float(filter_params.get('notional', 0))
def get_symbol_info(self, ssymbol):
# print(self.binance.get_symbol_info(symbol))
exchange_info = self.strategy.bclient.futures_exchange_info()
symbol_info = next((symbol for symbol in exchange_info['symbols'] if symbol['symbol'] == ssymbol), None)
# print(symbol_info)
return symbol_info
def is_valid_quantity(self, symbol, qty):
# print("")
# print(f"{self.min_qty[symbol]} <= {abs(qty)} <= {self.max_qty[symbol]})")
if not (self.min_qty[symbol] <= abs(qty) <= self.max_qty[symbol]):
return False
# print(f"({abs(qty)} - {self.min_qty[symbol]}) % {self.step_size[symbol]}) != 0")
# if ((abs(qty) - self.min_qty[symbol]) % self.step_size[symbol]) != 0:
# return False
# print("Retrurn True")
return True
def round_to_step(self, symbol, qty):
return round(qty / self.step_size[symbol]) * self.step_size[symbol]
def round_down_to_step(self, symbol, qty):
round_down = (qty // self.step_size[symbol]) * self.step_size[symbol]
return round_step_size(round_down, self.step_size[symbol])
#_getsizing
def _getsizing(self, comminfo, cash, data, isbuy):
self.log("_getsizing:", level=1)
symbol = data._name
if self.is_live_run:
# ha van befejezetlen order akkor nem enged rányitni.
save_pos = 0
for idata, position in self.broker.positions.items():
if symbol == idata:
save_pos = position.size
try_count_order = 0
order_detected = False
order_run_over = False
while try_count_order < 10:
order_detected = False
for order in self.broker.open_orders:
if order.data._name == symbol:
order_detected = True
order_run_over = True
self.log(f'Still open order symbol: {order.data._name} '
f'Open Order: ID={order.ref}, Status={order.getstatusname()}, '
f'Size={order.size}, Price={order.price}', level=1)
break
if order_detected:
time.sleep(.35)
try_count_order += 1
continue
else:
break
if order_detected:
self.log("Order is still aliven (x 10 try)", level=1)
return None
if order_run_over:
self.log(f"Order filled. Check Position. saved pos {save_pos}", level=1)
try_count_pos = 0
position_changed = False
sy_pos = 0
while try_count_pos < 5:
for idata, position in self.broker.positions.items():
if idata == symbol:
sy_pos = position.size
if position.size == save_pos:
print(f'Still in position.', position.size )
position_changed = False
break
else:
print('Position settled.')
position_changed = True
try_count_pos = 100
break
time.sleep(.35)
try_count_pos += 1
if not position_changed and sy_pos != 0:
return None
max_value = self.start_cash * (self.max_percent / 100)
if self.force_num_of_symbols is None:
one_symbol_max_value = max_value / self.num_of_symbols
else:
one_symbol_max_value = max_value / self.force_num_of_symbols
self.symbols_position = {key: 0 for key in self.symbols_position}
for idata, position in self.broker.positions.items():
if self.is_live_run:
self.symbols_position[idata] = position.size
else:
self.symbols_position[idata._name] = position.size
# print(self.symbols_position)
max_long_position = (one_symbol_max_value + self.strategy.symbol_profit[symbol]) / data.close[0]
max_short_position = -max_long_position
# ennyi db ilyen eszetel lehet + és - irányba is
if isbuy:
qty = max_long_position - self.symbols_position[symbol]
qty = 0 if qty < 0 else qty
else:
qty = max_short_position - self.symbols_position[symbol]
qty = 0 if qty > 0 else qty
# x x buy sell
# x x max long max short
# x x 2 -2
#
# position 0 2 -2
# position -1 3 -1
# position 1 1 -3
# position 2,5 -0,5 -4,5
# position -2,5 4,5 0,5
# ha shorba vagyok és longolni akarok akkor átfordul
# pozíció -1 short és longolni akkor akkor enged a maxi long ig kötni
# position = self.broker.getposition(data)
# print(f"{data._name} {one_symbol_max_value} {data.close[0]}")
# qty = ((one_symbol_max_value + self.strategy.symbol_profit[data._name]) / data.close[0]) - self.symbols_position[data._name]
ori_size = round(qty, 8)
if self.is_live_run:
size = self.round_down_to_step(symbol, ori_size)
self.log(f"symbol {symbol}", level=1)
self.log(f"side {'Buy' if isbuy else 'Sell'}", level=1)
self.log(f"size {size}", level=1)
self.log(f"qty {qty}", level=1)
self.log(f"ori_size {ori_size}", level=1)
self.log(f"max_long_position {max_long_position}", level=1)
self.log(f"max_short_position {max_short_position}", level=1)
self.log(f"stepsize {self.step_size[symbol]}", level=1)
self.log(f"self.start_cash {self.start_cash}", level=1)
self.log(f"max_value {max_value} {round(max_value / self.start_cash * 100, 2)}", level=1)
self.log(f"one_symbol_max_value {one_symbol_max_value}", level=1)
self.log(f"symbol_profit {self.strategy.symbol_profit[symbol]}", level=1)
self.log(f"symbols_position {self.symbols_position[symbol]}", level=1)
if size == 0:
print(f"Sizer: Trade failed {symbol} Size 0")
size = None
elif not self.is_valid_quantity(symbol, size):
print(f"Sizer: Trade failed {symbol} invalid size (min, max, stepsize)")
size = None
elif self.min_notional[symbol] > (abs(size) * data.close[0]):
print(f"Sizer: Trade failed {symbol} min_notional")
size = None
else:
size = ori_size
self.log(f"return size {size}", level=1)
self.log("", level=1)
# if isbuy:
# ib = "BUY"
# else:
# ib = "SELL"
#
# print(ib, "Cash:", cash,
# "Profit:", self.strategy.symbol_profit,
# "Position:", self.symbols_position,
# data._name,
# "return size: ", size,
# "price: ", data.close[0],
# "values: ", size * data.close[0],
# )
if self.is_live_run:
self.set_life_signal(key="ESMSizer_1" + str(symbol),
cclass="ESMSizer",
method="_getsizing",
msg1=str(symbol),
msg2=str(ori_size),
msg3=str(size)
)
return size
def set(self, strategy, broker):
self.strategy = strategy
self.broker = broker
if self.is_live_run:
self.set_life_signal = self.broker.set_life_signal
self.start()
class EmaShiftMultiStrategy(bt.Strategy):
def __init__(self, config, start_position={}, start_price={}, is_live_run=False, total_data_len=100000):
self.all_symbols = []
self.cc = config
self.start_position = start_position
self.start_price = start_price
self.is_live_run = is_live_run
self.closed_trade_count = 0
self.logger = Logger()
self.log = self.logger.log
if self.is_live_run:
self.set_life_signal = self.broker.set_life_signal
api_key, secure_key = self.get_api_key()
self.bclient = Client(api_key, secure_key, requests_params={'timeout': (10, 20)})
self.dt_array = []
for x in self.cc.keys():
self.dt_array.append(0)
# self.c.is_long = 1
# self.c.ema_fast_long = 27
# self.c.ema_slow_long = 408
# self.c.ema_fast_long_down_shift = 98
# self.c.is_stop_loss_long = 1
# self.c.stop_loss_percent_long = 20
#
# self.c.is_short = 1
# self.c.ema_fast_short = 19
# self.c.ema_slow_short = 494
# self.c.ema_fast_short_up_shift = 95
# self.c.is_stop_loss_short = 1
# self.c.stop_loss_percent_short = 20
# self.c.is_trailer_short = 1
# self.c.trailer_short_enter_percent = 20
# self.c.trailer_short_offset = 10
# Global variables - ezek symboltól függetlenül mindenkinél ugyan az
self.initial_cash = 100000
self.free_cash = self.initial_cash
# self.lot_percent = 70.0 # 70 = 70%
self.total_pnlcomm = 0.0
# self.comission_percen = 0.075 # 0.075 = 0.075 %
self.paid_comission = 0.0
self.steps_count = 0
# self.closed_trade_count = 1
self.end_close = False # futás végén lezárja a poziiciiót
# Symboltól függő változók
v_start = [
['long_stop_price', 0],
['short_stop_price', 1000000000000.0],
["trailer_long_activation_price", 0.0],
["trailer_long_active", False],
["trailer_long_highest_price", 0.0],
["trailer_long_stop_price", 0.0],
["trailer_short_activation_price", 0.0],
["trailer_short_active", False],
["trailer_short_lowest_price", 1000000000000.0],
["trailer_short_stop_price", 0.0],
["last_long_order", None],
["last_short_order", None],
["last_long_qty", 0.0],
["last_long_price", 0.0],
["last_short_qty", 0.0],
["last_short_price", 0.0],
["trade_steps", 0],
["dn_steps_count", 0],
["in_position", False],
]
kwargs = dict(v_start)
# v_start_obj = SimpleNamespace(**kwargs)
self.in_position = False
self.position_slots = 4
self.v = {}
self.cd = {}
self.symbol_profit = {}
self.start_market_prices = {}
for d in self.datas:
dn = d._name
self.start_market_prices[dn] = self.get_price(self.cc[dn].base + self.cc[dn].quote)
self.symbol_profit[dn] = 0.0
self.v[dn] = SimpleNamespace(**kwargs)
self.cd[dn] = CollectData(length=700,
is_live_run=self.is_live_run,
init_price=self.start_market_prices[dn],
worker_no=self.cc[dn].worker_no,
symbol=dn,
total_data_len=total_data_len + 10,
set_life_signal=self.set_life_signal if self.is_live_run else None
)
if self.is_live_run:
self.chart = CandlestickChart()
self.leverage = 1
for data in self.datas:
dn = data._name
self.log(f"Get symbol leverage: {dn} {self.leverage}")
self.broker.set_leverage(dn, self.leverage)
self.binance_excel_saver = BinanceExcelSaver
self.gdc = GoogleDriveConnect()
now = datetime.now()
self.tasks = []
for i in range(0, 24):
# for j in [5]:
for j in range(1, 59, 3):
self.tasks.append(
[datetime(now.year, now.month, now.day, hour=i, minute=j), self.scheduled_life_signals]
)
self.tasks.append(
[datetime(now.year, now.month, now.day, hour=i, minute=2), self.scheduled_account_info]
)
# self.tasks.append(
# [datetime(now.year, now.month, now.day, hour=now.hour, minute=now.minute + 1), self.scheduled_life_signals]
# )
# self.tasks.append(
# [datetime(now.year, now.month, now.day, hour=now.hour, minute=now.minute + 2), self.scheduled_account_info]
# )
# self.scheduler = TaskScheduler(self.tasks, set_life_signal=self.set_life_signal)
# self.scheduler.start()
def scheduled_life_signals(self):
self.broker.save_life_signals()
try:
self.gdc.delete_file_in_folder(file_name='life_signals.txt')
self.gdc.upload_file(file_name='/data_transfer/life_signals.txt')
except:
pass
def scheduled_account_info(self):
self.save_collected_data()
ret_array_balance = get_asset_balance(self.bclient, asset="USDC", is_print=False, is_return_array=True)
ret_array_position = get_futures_positions(self.bclient, is_print=False, is_return_array=True)
self.binance_excel_saver.save_balance_data(ret_array_balance)
self.binance_excel_saver.save_positions_data(ret_array_position)
self.gdc.delete_file_in_folder(file_name='ESM_settlement.xlsx')
self.gdc.upload_file(file_name='/data_transfer/ESM_settlement.xlsx')
for cd_key in self.cd:
fn0, fn1 = self.create_chart(cd_key, self.cc[cd_key])
try:
self.gdc.delete_file_in_folder(file_name=fn0)
self.gdc.upload_file(file_name='/data_transfer/' + fn0)
self.gdc.delete_file_in_folder(file_name=fn1)
self.gdc.upload_file(file_name='/data_transfer/' + fn1)
except:
pass
def create_chart(self, dn, c):
df = pd.DataFrame({
'open_history': self.cd[dn].open_history[::-1],
'high_history': self.cd[dn].high_history[::-1],
'low_history': self.cd[dn].low_history[::-1],
'close_history': self.cd[dn].close_history[::-1],
'ema_fast_long_data_history': self.cd[dn].ema_fast_long_data_history[::-1],
'ema_fast_long_down_shift_data_history': self.cd[dn].ema_fast_long_down_shift_data_history[::-1],
'ema_slow_long_data_history': self.cd[dn].ema_slow_long_data_history[::-1],
'ema_fast_short_data_history': self.cd[dn].ema_fast_short_data_history[::-1],
'ema_fast_short_up_shift_data_history': self.cd[dn].ema_fast_short_up_shift_data_history[::-1],
'ema_slow_short_data_history': self.cd[dn].ema_slow_short_data_history[::-1],
})
df0 = df.tail(500)
df0.index = range(0, 500)
self.chart.add(df0, dn + " PERPETUAL")
self.chart.add_config(c)
filename0 = "!" + dn + '.png'
self.chart.plot("data_transfer/" + filename0)
df1 = df.tail(24)
df1.index = range(0, 24)
self.chart.add(df1, dn + " PERPETUAL ZOOM")
self.chart.add_config(c)
filename1 = "!" + dn + '_zoom.png'
self.chart.plot("data_transfer/" + filename1)
return filename0, filename1
@staticmethod
def get_api_key():
# api_acces_key.json file is:
#
# {
# "api_key": "xxxxx",
# "secure_key": "yyyyy"
# }
json_file_path = 'tokens/api_acces_key.json'
with open(json_file_path, 'r') as file:
keys = json.load(file)
api_key = keys['api_key']
secure_key = keys['secure_key']
return api_key, secure_key
# def start_data_threads(self):
# if self.is_live_run:
# thread1 = threading.Thread(target=self.save_data_loop)
# thread1.start()
# # thread1.join()
def save_collected_data(self):
save_dict = {}
for cd_key in self.cd:
save_dict[cd_key] = self.cd[cd_key].get_save_data()
self.save_dict(save_dict)
def save_dict(self, ddict, file_path='data_transfer/data_transfer_for_process.pickle'):
try:
if os.path.exists(file_path):
os.remove(file_path)
with open(file_path, 'wb') as file:
pickle.dump(ddict, file)
except Exception as e:
self.log(f"An error occurred while saving the dictionary: {e}", level=1)
def get_price(self, symbol):
if self.is_live_run:
return float(self.broker.futures_symbol_ticker(symbol))
else:
self.bclient.futures_symbol_ticker(symbol=symbol)
def print_object(self, obj):
all_properties = dir(obj)
for prop in all_properties:
if callable(getattr(obj, prop)):
self.log(f"Method: {prop}", level=10)
else:
self.log(f"Attribute: {prop}", level=10)
def in_position_count(self):
ret = 0
for dn in self.all_symbols:
if self.v[dn].in_position:
ret += 1
return ret
def start(self):
self.all_symbols = []
for data in self.datas:
self.all_symbols.append(data._name)
if self.is_live_run:
# beállítom a kezdő portfolió értékeket
for data in self.datas:
dn = data._name
self.cd[dn].add_meta("cc", self.cc[dn])
if dn in self.start_position:
self.broker.update_position(data, self.start_position[dn], self.start_price[dn])
return
def position_value(self):
if self.is_live_run:
if self.is_live_data():
ret_value = self.broker.getvalue(refresh=True)
return ret_value
else:
ret_value = self.broker.getvalue(refresh=False)
return ret_value
else:
# print(self.broker.getcash())
# print(self.broker.getvalue())
ret_value = self.broker.getcash()
for data, position in self.broker.positions.items():
# print(data._name, position.size, position.size * data.close[0])
ret_value += position.size * data.low[0]
# return self.broker.getvalue()
return ret_value
# @staticmethod
# def exponential_scale(value, min_old, max_old, min_new, max_new, c=1):
# # Normalize the original value
# normalized_value = (value - min_old) / (max_old - min_old)
#
# # Apply the exponential function (using natural base e)
# exp_value = np.exp(c * normalized_value) - 1
#
# # Scale the exp value to the range [0, e-1], then to the desired range
# scaled_value = min_new + (exp_value / (np.e - 1)) * (max_new - min_new)
#
# return min(max(scaled_value, min_new), max_new)
def get_positon_text(self):
if self.is_live_run:
position = self.getposition(self.data)
return (f"{self.steps_count} Position: {self.data._name}: {position.size} "
f"AVG price:{round(position.price, 4)} "
f"Balance: {round(self.broker.getvalue(), 2)} "
f"Cash: {round(self.broker.getcash(), 2)} "
f"{self.c.base}: {self.broker.get_asset_balance(self.c.base)} "
f"{self.c.quote}: {self.broker.get_asset_balance(self.c.quote)} "
f"VALUE: {round(self.position_value(), 2)} "
)
else:
position = self.getposition(self.data)
return (f"{self.steps_count} Position: {self.data._name}: {position.size} "
f"AVG price:{round(position.price, 4)} "
f"Balance: {round(self.broker.getvalue(), 2)} "
f"Cash: {round(self.broker.getcash(), 2)} "
# f"BTC: {self.broker.get_asset_balance('BTC')} "
# f"FDUSD: {self.broker.get_asset_balance('FDUSD')} "
f"VALUE: {round(self.position_value(), 2)} "
)
# def is_live_data(self):
#
# status = self.datas[0]._state # 0 - Live data, 1 - History data, 2 - None
# if status in [0, 1]:
# if status:
# return False
# else:
# return True
#
# @staticmethod
# def dfloor(num, decimals=4):
# factor = 10 ** decimals
# return np.floor(num * factor) / factor
@staticmethod
def round_down(number, decimals=2):
factor = 10 ** decimals
return math.floor(number * factor) / factor
def rsrc(self, data):
return self.round_down(data.close[0], 8)
def s_close(self, data, stype):
dn = data._name
c = self.cc[dn]
if not self.v[dn].in_position:
return
self.log("", level=1)
self.log(datetime.now(), num2date(data.datetime[0]), "Close", dn, level=1)
self.log("-" * 80, level=1)
# for order in self.broker.open_orders:
# if order.data._name == dn:
# print(f'Open Order symbol: {order.data._name} Open Order: ID={order.ref}, Status={order.getstatusname()}, Size={order.size}, Price={order.price}')
# return None
# CLOSE PROTOCOL ---------------------------
# profit = 0.0
# if strategy.position_size < 0.0
# comission_short = math.round((last_short_qty * last_short_price) * (comission_percen / 100), 4)
# comission_short_stop = math.round((last_short_qty * rsrc) * (comission_percen / 100), 4)
# profit := math.round(last_short_qty * (last_short_price - rsrc), 2) - comission_short - comission_short_stop
# else if strategy.position_size > 0.0
# comission_long = math.round((last_long_qty * last_long_price) * (comission_percen / 100), 4)
# comission_long_stop = math.round((last_long_qty * rsrc) * (comission_percen / 100), 4)
# profit := math.round(last_long_qty * (rsrc - last_long_price), 2) - comission_long - comission_long_stop
#
# free_cash := free_cash + profit
# trailer_short_active := false
# long_stop_price := 0.0
# short_stop_price := 1000000000000.0
# rsrc = self.rsrc(data)
#
# profit = 0.0
# pstr = ""
# if self.getposition(data).size < 0:
# comission_short = round((self.v[dn].last_short_qty * self.v[dn].last_short_price) * (self.comission_percen / 100), 16)
# comission_short_stop = round((self.v[dn].last_short_qty * rsrc) * (self.comission_percen / 100), 16)
# profit = round(self.v[dn].last_short_qty * (self.v[dn].last_short_price - rsrc), 2) - comission_short - comission_short_stop
# self.paid_comission = self.paid_comission + comission_short + comission_short_stop
# self.free_cash = self.free_cash + profit
# pstr = (f"close, {dn},{data.datetime.datetime(0) + dt.timedelta(hours=1)}, {rsrc}, {self.v[dn].last_short_qty}, profit: {profit} cash:{self.free_cash} "
# f"total_comisson: {self.paid_comission} {stype} {self.broker.get_cash()}")
# elif self.getposition(data).size > 0:
# comission_long = round((self.v[dn].last_long_qty * self.v[dn].last_long_price) * (self.comission_percen / 100), 16)
# comission_long_stop = round((self.v[dn].last_long_qty * rsrc) * (self.comission_percen / 100), 16)
# profit = round(self.v[dn].last_long_qty * (rsrc - self.v[dn].last_long_price), 2) - comission_long - comission_long_stop
# self.paid_comission = self.paid_comission + comission_long + comission_long_stop
# self.free_cash = self.free_cash + profit
# pstr = (f"close, {dn},{data.datetime.datetime(0) + dt.timedelta(hours=1)}, {rsrc}, {self.v[dn].last_long_qty}, profit: {profit} cash:{self.free_cash} "
# f"total_comisson: {self.paid_comission} {stype} {self.broker.get_cash()}")
# else:
# print("Close nem lehet position size 0 esetén !!!!!!!", stype , "-" * 80)
self.v[dn].long_stop_price = 0.0
self.v[dn].long_take_price = 0.0
self.v[dn].short_stop_price = 1000000000000.0
self.v[dn].short_take_price = 1000000000000.0
self.v[dn].trailer_long_active = False
self.v[dn].trailer_long_activation_price = 0.0
self.v[dn].trailer_long_highest_price = 0.0
self.v[dn].trailer_long_stop_price = 0.0
self.v[dn].trailer_short_active = False
self.v[dn].trailer_short_activation_price = 0.0
self.v[dn].trailer_short_lowest_price = 1000000000000.0
self.v[dn].trailer_short_stop_price = 0.0
x_close = self.close(data)
print("CLOSE", dn, stype)
print(x_close)
print("-" * 80)
self.cd[dn].decision[0] = 2 # 2= Close Stop Loss
self.in_position = False
self.v[dn].in_position = False
self.v[dn].trade_steps = 0
# self.cd[dn].add_meta('line1', self.get_positon_text())
# if c.worker_no == 0:
# # print(self.closed_trade_count, self.v[dn].popen)
# print(self.closed_trade_count, pstr)
# self.closed_trade_count += 1
def s_buy(self, data):
dn = data._name
c = self.cc[dn]
if self.v[dn].in_position or self.in_position_count() >= self.position_slots:
return
self.log("", level=1)
self.log(datetime.now(), num2date(data.datetime[0]), "s_buy", dn, level=1)
self.log("-" * 80, level=1)
rsrc = self.rsrc(data)
# self.v[dn].last_long_qty = round((self.free_cash * (self.lot_percent / 100)) / rsrc, 2)
# # print(dn, self.v[dn].last_long_qty )
# self.v[dn].last_long_price = rsrc
# Stop loss price set
self.v[dn].long_stop_price = rsrc * (1 - (c.stop_loss_percent_long / 1000))
# self.v[dn].long_take_price = rsrc * (1 + (c.take_percent_long / 1000))
# Trailer sets
self.v[dn].trailer_long_activation_price = rsrc * (1 + (c.trailer_long_enter_percent / 1000))
self.v[dn].trailer_long_active = False
self.v[dn].trailer_long_highest_price = 0.0
# print("BUY SIZE:",self.v[dn].last_long_qty)
# self.v[dn].last_long_order = self.buy(data, size=self.v[dn].last_long_qty)
self.v[dn].last_long_order = self.buy(data)
print("BUY", dn)
print(self.v[dn].last_long_order)
print("-" * 80)
if self.v[dn].last_long_order:
self.v[dn].trade_steps = 0
self.cd[dn].decision[0] = 1 # 1= BUY
self.in_position = True
self.v[dn].in_position = True
# self.v[dn].popen = (f"long , {dn},{self.data.datetime.datetime(0) + dt.timedelta(hours=1)}, {data.close[0] * self.v[dn].last_long_qty}, "
# f"broker cash: {self.broker.get_cash()}")
def s_sell(self, data):
dn = data._name
c = self.cc[dn]
if self.v[dn].in_position or self.in_position_count() >= self.position_slots:
return
self.log("", level=1)
self.log(datetime.now(), num2date(data.datetime[0]), "s_sell", dn, level=1)
self.log("-" * 80, level=1)
rsrc = self.rsrc(data)
# self.v[dn].last_short_qty = round((self.free_cash * (self.lot_percent / 100)) / rsrc, 2)
# # print(dn, self.v[dn].last_short_qty)
# self.v[dn].last_short_price = rsrc
# Stop Loss price set
self.v[dn].short_stop_price = rsrc * (1 + (c.stop_loss_percent_short / 1000))
# self.v[dn].short_take_price = rsrc * (1 - (c.take_percent_short / 1000))
# Trailer sets
self.v[dn].trailer_short_activation_price = rsrc * (1 - (c.trailer_short_enter_percent / 1000))
self.v[dn].trailer_short_active = False
self.v[dn].trailer_short_lowest_price = 1000000000000.0