-
Notifications
You must be signed in to change notification settings - Fork 8
/
hft109.py
1471 lines (1111 loc) · 52.4 KB
/
hft109.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
##################################################
##################################################
# Start code:
print()
##################################################
##################################################
print("Init code: ")
print()
##################################################
##################################################
print("Test")
print()
##################################################
##################################################
# Import modules:
import math
import time
import numpy as np
import requests
import talib
import json
import datetime
from datetime import timedelta
from decimal import Decimal
import decimal
import random
import statistics
from statistics import mean
import scipy.fftpack as fftpack
##################################################
##################################################
# binance module imports
from binance.client import Client as BinanceClient
from binance.exceptions import BinanceAPIException, BinanceOrderException
from binance.enums import *
##################################################
##################################################
# Load credentials from file
with open("credentials.txt", "r") as f:
lines = f.readlines()
api_key = lines[0].strip()
api_secret = lines[1].strip()
# Instantiate Binance client
client = BinanceClient(api_key, api_secret)
##################################################
##################################################
# Define a function to get the account balance in BUSD
def get_account_balance():
accounts = client.futures_account_balance()
for account in accounts:
if account['asset'] == 'USDT':
bUSD_balance = float(account['balance'])
return bUSD_balance
# Get the USDT balance of the futures account
bUSD_balance = float(get_account_balance())
# Print account balance
print("USDT Futures balance:", bUSD_balance)
print()
##################################################
##################################################
# Define Binance client reading api key and secret from local file:
def get_binance_client():
# Read credentials from file
with open("credentials.txt", "r") as f:
lines = f.readlines()
api_key = lines[0].strip()
api_secret = lines[1].strip()
# Instantiate client
client = BinanceClient(api_key, api_secret)
return client
# Call the function to get the client
client = get_binance_client()
##################################################
##################################################
# Initialize variables for tracking trade state:
TRADE_SYMBOL = "BTCUSDT"
##################################################
##################################################
# Define timeframes and get candles:
timeframes = ['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d']
def get_candles(symbol, timeframes):
candles = []
for timeframe in timeframes:
limit = 10000 # default limit
tf_value = int(timeframe[:-1]) # extract numeric value of timeframe
if tf_value >= 4: # check if timeframe is 4h or above
limit = 20000 # increase limit for 4h timeframe and above
klines = client.get_klines(
symbol=symbol,
interval=timeframe,
limit=limit
)
# Convert klines to candle dict
for k in klines:
candle = {
"time": k[0] / 1000,
"open": float(k[1]),
"high": float(k[2]),
"low": float(k[3]),
"close": float(k[4]),
"volume": float(k[5]),
"timeframe": timeframe
}
candles.append(candle)
return candles
# Get candles
candles = get_candles(TRADE_SYMBOL, timeframes)
#print(candles)
# Organize candles by timeframe
candle_map = {}
for candle in candles:
timeframe = candle["timeframe"]
candle_map.setdefault(timeframe, []).append(candle)
#print(candle_map)
##################################################
##################################################
def get_latest_candle(symbol, interval, start_time=None):
"""Retrieve the latest candle for a given symbol and interval"""
if start_time is None:
klines = client.futures_klines(symbol=symbol, interval=interval, limit=1)
else:
klines = client.futures_klines(symbol=symbol, interval=interval, startTime=start_time, limit=1)
candle = {
"time": klines[0][0],
"open": float(klines[0][1]),
"high": float(klines[0][2]),
"low": float(klines[0][3]),
"close": float(klines[0][4]),
"volume": float(klines[0][5]),
"timeframe": interval
}
return candle
##################################################
##################################################
##################################################
##################################################
# Get current price as <class 'float'>
def get_price(symbol):
try:
url = "https://fapi.binance.com/fapi/v1/ticker/price"
params = {
"symbol": symbol
}
response = requests.get(url, params=params)
data = response.json()
if "price" in data:
price = float(data["price"])
else:
raise KeyError("price key not found in API response")
return price
except (BinanceAPIException, KeyError) as e:
print(f"Error fetching price for {symbol}: {e}")
return 0
price = get_price("BTCUSDT")
print(price)
print()
##################################################
##################################################
# Get entire list of close prices as <class 'list'> type
def get_close(timeframe):
closes = []
candles = candle_map[timeframe]
for c in candles:
close = c['close']
if not np.isnan(close):
closes.append(close)
# Append current price to the list of closing prices
current_price = get_price(TRADE_SYMBOL)
closes.append(current_price)
return closes
close = get_close('1m')
#print(close)
##################################################
##################################################
# Get entire list of close prices as <class 'list'> type
def get_closes(timeframe):
closes = []
candles = candle_map[timeframe]
for c in candles:
close = c['close']
if not np.isnan(close):
closes.append(close)
return closes
closes = get_closes('1m')
#print(closes)
##################################################
##################################################
# Scale current close price to sine wave
def scale_to_sine(timeframe):
close_prices = np.array(get_close(timeframe))
# Get last close price
current_close = close_prices[-1]
# Calculate sine wave
sine_wave, leadsine = talib.HT_SINE(close_prices)
# Replace NaN values with 0
sine_wave = np.nan_to_num(sine_wave)
sine_wave = -sine_wave
# Get the sine value for last close
current_sine = sine_wave[-1]
# Calculate the min and max sine
sine_wave_min = np.min(sine_wave)
sine_wave_max = np.max(sine_wave)
# Calculate % distances
dist_min, dist_max = [], []
for close in close_prices:
# Calculate distances as percentages
dist_from_close_to_min = ((current_sine - sine_wave_min) /
(sine_wave_max - sine_wave_min)) * 100
dist_from_close_to_max = ((sine_wave_max - current_sine) /
(sine_wave_max - sine_wave_min)) * 100
dist_min.append(dist_from_close_to_min)
dist_max.append(dist_from_close_to_max)
# Take average % distances
avg_dist_min = sum(dist_min) / len(dist_min)
avg_dist_max = sum(dist_max) / len(dist_max)
#print(f"{timeframe} Close is now at "
#f"dist. to min: {dist_from_close_to_min:.2f}% "
#f"and at "
#f"dist. to max: {dist_from_close_to_max:.2f}%")
return dist_from_close_to_min, dist_from_close_to_max, current_sine
# Call function
for timeframe in timeframes:
scale_to_sine(timeframe)
print()
##################################################
##################################################
def get_momentum(timeframe):
"""Calculate momentum for a single timeframe"""
# Get candle data
candles = candle_map[timeframe][-100:]
# Calculate momentum using talib MOM
momentum = talib.MOM(np.array([c["close"] for c in candles]), timeperiod=14)
return momentum[-1]
# Calculate momentum for each timeframe
for timeframe in timeframes:
momentum = get_momentum(timeframe)
print(f"Momentum for {timeframe}: {momentum}")
print()
##################################################
##################################################
def generate_momentum_sinewave(timeframes):
# Initialize variables
momentum_sorter = []
market_mood = []
last_reversal = None
last_reversal_value_on_sine = None
last_reversal_value_on_price = None
next_reversal = None
next_reversal_value_on_sine = None
next_reversal_value_on_price = None
# Loop over timeframes
for timeframe in timeframes:
# Get close prices for current timeframe
close_prices = np.array(get_closes(timeframe))
# Get last close price
current_close = close_prices[-1]
# Calculate sine wave for current timeframe
sine_wave, leadsine = talib.HT_SINE(close_prices)
# Replace NaN values with 0
sine_wave = np.nan_to_num(sine_wave)
sine_wave = -sine_wave
# Get the sine value for last close
current_sine = sine_wave[-1]
# Calculate the min and max sine
sine_wave_min = np.nanmin(sine_wave) # Use nanmin to ignore NaN values
sine_wave_max = np.nanmax(sine_wave)
# Calculate price values at min and max sine
sine_wave_min_price = close_prices[sine_wave == sine_wave_min][0]
sine_wave_max_price = close_prices[sine_wave == sine_wave_max][0]
# Calculate the difference between the max and min sine
sine_wave_diff = sine_wave_max - sine_wave_min
# If last close was the lowest, set as last reversal
if current_sine == sine_wave_min:
last_reversal = 'dip'
last_reversal_value_on_sine = sine_wave_min
last_reversal_value_on_price = sine_wave_min_price
# If last close was the highest, set as last reversal
if current_sine == sine_wave_max:
last_reversal = 'top'
last_reversal_value_on_sine = sine_wave_max
last_reversal_value_on_price = sine_wave_max_price
# Calculate % distances
newsine_dist_min, newsine_dist_max = [], []
for close in close_prices:
# Calculate distances as percentages
dist_from_close_to_min = ((current_sine - sine_wave_min) /
sine_wave_diff) * 100
dist_from_close_to_max = ((sine_wave_max - current_sine) /
sine_wave_diff) * 100
newsine_dist_min.append(dist_from_close_to_min)
newsine_dist_max.append(dist_from_close_to_max)
# Take average % distances
avg_dist_min = sum(newsine_dist_min) / len(newsine_dist_min)
avg_dist_max = sum(newsine_dist_max) / len(newsine_dist_max)
# Determine market mood based on % distances
if avg_dist_min <= 15:
mood = "At DIP Reversal and Up to Bullish"
if last_reversal != 'dip':
next_reversal = 'dip'
next_reversal_value_on_sine = sine_wave_min
next_reversal_value_on_price = close_prices[sine_wave == sine_wave_min][0]
elif avg_dist_max <= 15:
mood = "At TOP Reversal and Down to Bearish"
if last_reversal != 'top':
next_reversal = 'top'
next_reversal_value_on_sine = sine_wave_max
next_reversal_value_on_price = close_prices[sine_wave == sine_wave_max][0]
elif avg_dist_min < avg_dist_max:
mood = "Bullish"
else:
mood = "Bearish"
# Append momentum score and market mood to lists
momentum_score = avg_dist_max - avg_dist_min
momentum_sorter.append(momentum_score)
market_mood.append(mood)
# Print distances and market mood
print(f"{timeframe} Close is now at "
f"dist. to min: {avg_dist_min:.2f}% "
f"and at "
f"dist. to max: {avg_dist_max:.2f}%. "
f"Market mood: {mood}")
# Update last and next reversal info
if next_reversal:
last_reversal = next_reversal
last_reversal_value_on_sine = next_reversal_value_on_sine
last_reversal_value_on_price = next_reversal_value_on_price
next_reversal = None
next_reversal_value_on_sine = None
next_reversal_value_on_price = None
# Get close prices for the 1-minute timeframe and last 3 closes
close_prices = np.array(get_closes('1m'))
# Calculate sine wave
sine_wave, leadsine = talib.HT_SINE(close_prices)
# Replace NaN values with 0
sine_wave = np.nan_to_num(sine_wave)
sine_wave = -sine_wave
# Get the sine value for last close
current_sine = sine_wave[-1]
# Get current date and time
now = datetime.datetime.now()
# Calculate the min and max sine
sine_wave_min = np.min(sine_wave)
sine_wave_max = np.max(sine_wave)
# Calculate the difference between the maxand min sine
sine_wave_diff = sine_wave_max - sine_wave_min
# Calculate % distances
dist_from_close_to_min = ((current_sine - sine_wave_min) /
sine_wave_diff) * 100
dist_from_close_to_max = ((sine_wave_max - current_sine) /
sine_wave_diff) * 100
# Determine market mood based on % distances
if dist_from_close_to_min <= 15:
mood = "At DIP Reversal and Up to Bullish"
if last_reversal != 'dip':
next_reversal = 'dip'
next_reversal_value_on_sine = sine_wave_min
elif dist_from_close_to_max <= 15:
mood = "At TOP Reversal and Down to Bearish"
if last_reversal != 'top':
next_reversal = 'top'
next_reversal_value_on_sine = sine_wave_max
elif dist_from_close_to_min < dist_from_close_to_max:
mood = "Bullish"
else:
mood = "Bearish"
# Get the close prices that correspond to the min and max sine values
close_prices_between_min_and_max = close_prices[(sine_wave >= sine_wave_min) & (sine_wave <= sine_wave_max)]
print()
# Print distances and market mood for 1-minute timeframe
print(f"On 1min timeframe,Close is now at "
f"dist. to min: {dist_from_close_to_min:.2f}% "
f"and at "
f"dist. to max:{dist_from_close_to_max:.2f}%. "
f"Market mood: {mood}")
min_val = min(close_prices_between_min_and_max)
max_val = max(close_prices_between_min_and_max)
print("The lowest value in the array is:", min_val)
print("The highest value in the array is:", max_val)
print()
# Update last and next reversal info
#if next_reversal:
#last_reversal = next_reversal
#last_reversal_value_on_sine = next_reversal_value_on_sine
#next_reversal = None
#next_reversal_value_on_sine = None
# Print last and next reversal info
#if last_reversal:
#print(f"Last reversal was at {last_reversal} on the sine wave at {last_reversal_value_on_sine:.2f} ")
# Return the momentum sorter, market mood, close prices between min and max sine, and reversal info
return momentum_sorter, market_mood, sine_wave_diff, dist_from_close_to_min, dist_from_close_to_max, now, close_prices, current_sine, close_prices_between_min_and_max
momentum_sorter, market_mood, sine_wave_diff, dist_from_close_to_min, dist_from_close_to_max, now, close_prices, current_sine, close_prices_between_min_and_max = generate_momentum_sinewave(timeframes)
print()
#print("Close price values between last reversals on sine: ")
#print(close_prices_between_min_and_max)
print()
print("Current close on sine value now at: ", current_sine)
print("distances as percentages from close to min: ", dist_from_close_to_min, "%")
print("distances as percentages from close to max: ", dist_from_close_to_max, "%")
print("Momentum on 1min timeframe is now at: ", momentum_sorter[-12])
print("Mood on 1min timeframe is now at: ", market_mood[-12])
print()
##################################################
##################################################
def generate_new_momentum_sinewave(close_prices, candles, percent_to_max_val=5, percent_to_min_val=5):
# Calculate the sine wave using HT_SINE
sine_wave, _ = talib.HT_SINE(close_prices)
# Replace NaN values with 0 using nan_to_num
sine_wave = np.nan_to_num(sine_wave)
sine_wave = -sine_wave
print("Current close on Sine wave:", sine_wave[-1])
# Calculate the minimum and maximum values of the sine wave
sine_wave_min = np.min(sine_wave)
sine_wave_max = np.max(sine_wave)
# Calculate the distance from close to min and max as percentages on a scale from 0 to 100%
dist_from_close_to_min = ((sine_wave[-1] - sine_wave_min) / (sine_wave_max - sine_wave_min)) * 100
dist_from_close_to_max = ((sine_wave_max - sine_wave[-1]) / (sine_wave_max - sine_wave_min)) * 100
print("Distance from close to min:", dist_from_close_to_min)
print("Distance from close to max:", dist_from_close_to_max)
# Calculate the range of values for each quadrant
range_q1 = (sine_wave_max - sine_wave_min) / 4
range_q2 = (sine_wave_max - sine_wave_min) / 4
range_q3 = (sine_wave_max - sine_wave_min) / 4
range_q4 = (sine_wave_max - sine_wave_min) / 4
# Set the EM amplitude for each quadrant based on the range of values
em_amp_q1 = range_q1 / percent_to_max_val
em_amp_q2 = range_q2 / percent_to_max_val
em_amp_q3 = range_q3 / percent_to_max_val
em_amp_q4 = range_q4 / percent_to_max_val
# Calculate the EM phase for each quadrant
em_phase_q1 = 0
em_phase_q2 = math.pi/2
em_phase_q3 = math.pi
em_phase_q4 = 3*math.pi/2
# Calculate the current position of the price on the sine wave
current_position = (sine_wave[-1] - sine_wave_min) / (sine_wave_max - sine_wave_min)
current_quadrant = 0
# Determine which quadrant the current position is in
if current_position < 0.25:
# In quadrant 1
em_amp = em_amp_q1
em_phase = em_phase_q1
current_quadrant = 1
print("Current position is in quadrant 1. Distance from 0% to 25% of range:", (current_position - 0.0) / 0.25 * 100, "%")
print("Current quadrant is: ", current_quadrant)
elif current_position < 0.5:
# In quadrant 2
em_amp = em_amp_q2
em_phase = em_phase_q2
current_quadrant = 2
print("Current position is in quadrant 2. Distance from 25% to 50% of range:", (current_position - 0.25) / 0.25 * 100, "%")
print("Current quadrant is: ", current_quadrant)
elif current_position < 0.75:
# In quadrant 3
em_amp = em_amp_q3
em_phase = em_phase_q3
current_quadrant = 3
print("Current position is in quadrant 3. Distance from 50% to 75% of range:", (current_position - 0.5) / 0.25 * 100, "%")
print("Current quadrant is: ", current_quadrant)
else:
# In quadrant 4
em_amp = em_amp_q4
em_phase = em_phase_q4
current_quadrant = 4
print("Current position is in quadrant 4. Distance from 75% to 100% of range:", (current_position - 0.75) / 0.25 * 100, "%")
print("Current quadrant is: ", current_quadrant)
print("EM amplitude:", em_amp)
print("EM phase:", em_phase)
# Calculate the EM value
em_value = em_amp * math.sin(em_phase)
print("EM value:", em_value)
# Calculate the percentage of the price range
price_range = candles[-1]["high"] - candles[-1]["low"]
price_range_percent = (close_prices[-1] - candles[-1]["low"]) / price_range * 100
print("Price range percent:", price_range_percent)
# Calculate the momentum value
momentum = em_value * price_range_percent / 100
print("Momentum value:", momentum)
print()
# Return a dictionary of all the features
return {
"current_close": sine_wave[-1],
"dist_from_close_to_min": dist_from_close_to_min,
"dist_from_close_to_max": dist_from_close_to_max,
"current_quadrant": current_quadrant,
"em_amplitude": em_amp,
"em_phase": em_phase,
"price_range_percent": price_range_percent,
"momentum": momentum,
"min": sine_wave_min,
"max": sine_wave_max
}
#sine_wave = generate_new_momentum_sinewave(close_prices, candles, percent_to_max_val=5, percent_to_min_val=5)
#print(sine_wave)
print()
##################################################
##################################################
def calculate_thresholds(close_prices, period=14, minimum_percentage=3, maximum_percentage=3, range_distance=0.05):
"""
Calculate thresholds and averages based on min and max percentages.
"""
# Get min/max close
min_close = np.nanmin(close_prices)
max_close = np.nanmax(close_prices)
# Convert close_prices to numpy array
close_prices = np.array(close_prices)
# Calculate momentum
momentum = talib.MOM(close_prices, timeperiod=period)
# Get min/max momentum
min_momentum = np.nanmin(momentum)
max_momentum = np.nanmax(momentum)
# Calculate custom percentages
min_percentage_custom = minimum_percentage / 100
max_percentage_custom = maximum_percentage / 100
# Calculate thresholds
min_threshold = np.minimum(min_close - (max_close - min_close) * min_percentage_custom, close_prices[-1])
max_threshold = np.maximum(max_close + (max_close - min_close) * max_percentage_custom, close_prices[-1])
# Calculate range of prices within a certain distance from the current close price
range_price = np.linspace(close_prices[-1] * (1 - range_distance), close_prices[-1] * (1 + range_distance), num=50)
# Filter close prices
with np.errstate(invalid='ignore'):
filtered_close = np.where(close_prices < min_threshold, min_threshold, close_prices)
filtered_close = np.where(filtered_close > max_threshold, max_threshold, filtered_close)
# Calculate avg
avg_mtf = np.nanmean(filtered_close)
# Get current momentum
current_momentum = momentum[-1]
# Calculate % to min/max momentum
with np.errstate(invalid='ignore', divide='ignore'):
percent_to_min_momentum = ((max_momentum - current_momentum) /
(max_momentum - min_momentum)) * 100 if max_momentum - min_momentum != 0 else np.nan
percent_to_max_momentum = ((current_momentum - min_momentum) /
(max_momentum - min_momentum)) * 100 if max_momentum - min_momentum != 0 else np.nan
# Calculate combined percentages
percent_to_min_combined = (minimum_percentage + percent_to_min_momentum) / 2
percent_to_max_combined = (maximum_percentage + percent_to_max_momentum) / 2
# Combined momentum signal
momentum_signal = percent_to_max_combined - percent_to_min_combined
return min_threshold, max_threshold, avg_mtf, momentum_signal, range_price
# Call function with minimum percentage of 2%, maximum percentage of 2%, and range distance of 5%
min_threshold, max_threshold, avg_mtf, momentum_signal, range_price = calculate_thresholds(closes, period=14, minimum_percentage=2, maximum_percentage=2, range_distance=0.05)
print("Momentum signal:", momentum_signal)
print()
print("Minimum threshold:", min_threshold)
print("Maximum threshold:", max_threshold)
print("Average MTF:", avg_mtf)
#print("Range of prices within distance from current close price:")
#print(range_price[-1])
print()
##################################################
##################################################
# Define the current time and close price
current_time = datetime.datetime.now()
current_close = closes[-1]
print("Current local Time is now at: ", current_time)
print("Current close price is at : ", current_close)
print()
##################################################
##################################################
def get_closes_last_n_minutes(interval, n):
"""Generate mock closing prices for the last n minutes"""
closes = []
for i in range(n):
closes.append(random.uniform(0, 100))
return closes
print()
##################################################
##################################################
import numpy as np
import scipy.fftpack as fftpack
import datetime
def get_target(closes, n_components, target_distance=0.01):
# Calculate FFT of closing prices
fft = fftpack.rfft(closes)
frequencies = fftpack.rfftfreq(len(closes))
# Sort frequencies by magnitude and keep only the top n_components
idx = np.argsort(np.abs(fft))[::-1][:n_components]
top_frequencies = frequencies[idx]
# Filter out the top frequencies and reconstruct the signal
filtered_fft = np.zeros_like(fft)
filtered_fft[idx] = fft[idx]
filtered_signal = fftpack.irfft(filtered_fft)
# Calculate the target price as the next value after the last closing price, plus a small constant
current_close = closes[-1]
target_price = filtered_signal[-1] + target_distance
# Get the current time
current_time = datetime.datetime.now()
# Calculate the market mood based on the predicted target price and the current close price
diff = target_price - current_close
if diff > 0:
market_mood = "Bullish"
fastest_target = current_close + target_distance/2
fast_target1 = current_close + target_distance/4
fast_target2 = current_close + target_distance/8
fast_target3 = current_close + target_distance/16
fast_target4 = current_close + target_distance/32
target1 = target_price + np.std(closes)/16
target2 = target_price + np.std(closes)/8
target3 = target_price + np.std(closes)/4
target4 = target_price + np.std(closes)/2
target5 = target_price + np.std(closes)
elif diff < 0:
market_mood = "Bearish"
fastest_target = current_close - target_distance/2
fast_target1 = current_close - target_distance/4
fast_target2 = current_close - target_distance/8
fast_target3 = current_close - target_distance/16
fast_target4 = current_close - target_distance/32
target1 = target_price - np.std(closes)/16
target2 = target_price - np.std(closes)/8
target3 = target_price - np.std(closes)/4
target4 = target_price - np.std(closes)/2
target5 = target_price - np.std(closes)
else:
market_mood = "Neutral"
fastest_target = current_close + target_distance/2
fast_target1 = current_close - target_distance/4
fast_target2 = current_close + target_distance/8
fast_target3 = current_close - target_distance/16
fast_target4 = current_close + target_distance/32
target1 = target_price + np.std(closes)/16
target2 = target_price - np.std(closes)/8
target3 = target_price + np.std(closes)/4
target4 = target_price - np.std(closes)/2
target5 = target_price + np.std(closes)
# Calculate the stop loss and target levels
entry_price = closes[-1]
stop_loss = entry_price - 3*np.std(closes)
target6 = target_price + np.std(closes)
target7 = target_price + 2*np.std(closes)
target8 = target_price + 3*np.std(closes)
target9 = target_price + 4*np.std(closes)
target10 = target_price + 5*np.std(closes)
return current_time, entry_price, stop_loss, fastest_target, fast_target1, fast_target2, fast_target3, fast_target4, target1, target2, target3, target4, target5, target6, target7, target8, target9, target10, filtered_signal, target_price, market_mood
closes = get_closes("1m")
n_components = 5
current_time, entry_price, stop_loss, fastest_target, fast_target1, fast_target2, fast_target3, fast_target4, target1, target2, target3, target4, target5, target6, target7, target8, target9, target10, filtered_signal, target_price, market_mood = get_target(closes, n_components, target_distance=56)
print("Current local Time is now at: ", current_time)
print("Market mood is: ", market_mood)
print()
print("Current close price is at : ", current_close)
print()
print("Fast target 1 is: ", fast_target4)
print("Fast target 2 is: ", fast_target3)
print("Fast target 3 is: ", fast_target2)
print("Fast target 4 is: ", fast_target1)
print()
print("Fastest target is: ", fastest_target)
print()
print("Target 1 is: ", target1)
print("Target 2 is: ", target2)
print("Target 3 is: ", target3)
print("Target 4 is: ", target4)
print("Target 5 is: ", target5)
print()
##################################################
##################################################
def get_current_price():
url = "https://fapi.binance.com/fapi/v1/ticker/price"
params = {
"symbol": "BTCUSDT"
}
response = requests.get(url, params=params)
data = response.json()
price = float(data["price"])
return price
# Get the current price
price = get_current_price()
print()
##################################################
##################################################
def get_support_resistance_levels(close):
# Convert close list to numpy array
close_prices = np.array(close)
# Calculate EMA50 and EMA200
ema50 = talib.EMA(close_prices, timeperiod=50)
ema200 = talib.EMA(close_prices, timeperiod=200)
# Check if ema50 and ema200 have at least one element
if len(ema50) == 0 or len(ema200) == 0:
return []
# Get the last element of ema50 and ema200
ema50 = ema50[-1]
ema200 = ema200[-1]
# Calculate Phi Ratio levels
range_ = ema200 - ema50
phi_levels = [ema50, ema50 + range_/1.618, ema50 + range_]
# Calculate Gann Square levels
current_price = close_prices[-1]
high_points = [current_price, ema200, max(phi_levels)]
low_points = [min(phi_levels), ema50, current_price]
gann_levels = []
for i in range(1, min(4, len(high_points))):
for j in range(1, min(4, len(low_points))):
gann_level = ((high_points[i-1] - low_points[j-1]) * 0.25 * (i + j)) + low_points[j-1]
gann_levels.append(gann_level)
# Combine levels and sort
levels = phi_levels + gann_levels
levels.sort()
return levels
print()
# Get the support and resistance levels
levels = get_support_resistance_levels(close_prices)
support_levels, resistance_levels = [], []
for level in levels:
if level < close_prices[-1]:
support_levels.append(level)
else:
resistance_levels.append(level)
# Determine the market mood
if len(levels) > 0:
support_levels = []
resistance_levels = []
for level in levels:
if level < close_prices[-1]:
support_levels.append(level)
else:
resistance_levels.append(level)
if len(support_levels) > 0 and len(resistance_levels) > 0:
market_mood_sr = "Neutral"
elif len(support_levels) > 0:
market_mood_sr = "Bullish"
elif len(resistance_levels) > 0:
market_mood_sr = "Bearish"
else:
market_mood_sr = "Undefined"
# Calculate support and resistance ranges
if len(support_levels) > 0:
support_range = max(support_levels) - min(support_levels)
print("Support range: {:.2f}".format(support_range))
else:
print("Support range: None")
if len(resistance_levels) > 0:
resistance_range = max(resistance_levels) - min(resistance_levels)
print("Resistance range: {:.2f}".format(resistance_range))
else:
print("Resistance range: None")
# Print the levels and market mood
print("Potential support levels:")
if len(support_levels) > 0:
for level in support_levels:
print(" - {:.2f}".format(level))
else:
print(" None found.")
print("Potential resistance levels:")
if len(resistance_levels) > 0:
for level in resistance_levels:
print(" - {:.2f}".format(level))
else:
print(" None found.")
incoming_bullish_reversal = None
incoming_bearish_reversal = None
if market_mood_sr == "Neutral":
print("Market mood: {}".format(market_mood_sr))
if len(support_levels) > 0:
support = max(support_levels)
support_percentage = round(abs(support - close_prices[-1]) / close_prices[-1] * 100, 12)
else:
support = None
support_percentage = None
if len(resistance_levels) > 0:
top = min(resistance_levels)
top_percentage = round(abs(top - close_prices[-1]) / close_prices[-1] * 100, 12)
else:
top = None
top_percentage = None
print("Best dip: {:.2f}% (Support level: {:.2f})".format(support_percentage, support))
if support_percentage >= 3.0:
incoming_bullish_reversal = True