forked from xmd79/trading-bot-using-time-series
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autobotz11.py
2150 lines (1592 loc) · 82.5 KB
/
autobotz11.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 hashlib
import requests
import hmac
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
import gc
from discord_webhook import DiscordWebhook
##################################################
##################################################
# 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)
print()
##################################################
##################################################
# 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)
return dist_from_close_to_min, dist_from_close_to_max, current_sine
# Iterate over each timeframe and call the scale_to_sine function
for timeframe in timeframes:
dist_from_close_to_min, dist_from_close_to_max, current_sine = scale_to_sine(timeframe)
# Print the results for each timeframe
print(f"For {timeframe} timeframe:")
print(f"Distance to min: {dist_from_close_to_min:.2f}%")
print(f"Distance to max: {dist_from_close_to_max:.2f}%")
print(f"Current Sine value: {current_sine}\n")
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])
# Determine which threshold is closest to the current close
closest_threshold = min(min_threshold, max_threshold, key=lambda x: abs(x - close[-1]))
if closest_threshold == min_threshold:
print("The last minimum value is closest to the current close.")
elif closest_threshold == max_threshold:
print("The last maximum value is closest to the current close.")
else:
print("No threshold value found.")
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
momentum_values = {}
for timeframe in timeframes:
momentum = get_momentum(timeframe)
momentum_values[timeframe] = momentum
print(f"Momentum for {timeframe}: {momentum}")
# Convert momentum to a normalized scale and determine if it's positive or negative
normalized_momentum = {}
for timeframe, momentum in momentum_values.items():
normalized_value = (momentum + 100) / 2 # Normalize to a scale between 0 and 100
normalized_momentum[timeframe] = normalized_value
print(f"Normalized Momentum for {timeframe}: {normalized_value:.2f}%")
# Calculate dominant ratio
positive_count = sum(1 for value in normalized_momentum.values() if value > 50)
negative_count = len(normalized_momentum) - positive_count
print(f"Positive momentum timeframes: {positive_count}/{len(normalized_momentum)}")
print(f"Negative momentum timeframes: {negative_count}/{len(normalized_momentum)}")
if positive_count > negative_count:
print("Overall dominant momentum: Positive")
elif positive_count < negative_count:
print("Overall dominant momentum: Negative")
else:
print("Overall dominant momentum: Balanced")
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"
else:
market_mood = "Bearish"
# Calculate fast cycle targets
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
# Calculate other targets
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()
current_close = closes[-1]
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()
##################################################
##################################################
from sklearn.linear_model import LinearRegression
def price_regression(close):
# Convert 'close' to a numpy array
close_data = np.array(close)
# Create timestamps based on the index (assuming each close price corresponds to a single time unit)
timestamps = np.arange(len(close_data))
# Fit a linear regression model
model = LinearRegression()
model.fit(timestamps.reshape(-1, 1), close_data)
# Predict future prices using the regression model
num_targets = 1
future_timestamps = np.arange(len(close_data), len(close_data) + num_targets)
future_prices = model.predict(future_timestamps.reshape(-1, 1))
return future_timestamps, future_prices
##################################################
##################################################
def calculate_reversal_and_forecast(close):
# Initialize variables
current_reversal = None
next_reversal = None
last_reversal = None
forecast_dip = None
forecast_top = None
# Calculate minimum and maximum values
min_value = np.min(close)
max_value = np.max(close)
# Calculate forecast direction and price using FFT
fft = fftpack.rfft(close)
frequencies = fftpack.rfftfreq(len(close))
idx = np.argsort(np.abs(fft))[::-1][:10]
top_frequencies = frequencies[idx]
filtered_fft = np.zeros_like(fft)
filtered_fft[idx] = fft[idx]
filtered_signal = fftpack.irfft(filtered_fft)
if len(close) > 1:
if filtered_signal[-1] > filtered_signal[-2]:
forecast_direction = "Up"
forecast_price_fft = filtered_signal[-1] + (filtered_signal[-1] - filtered_signal[-2]) * 0.5
else:
forecast_direction = "Down"
forecast_price_fft = filtered_signal[-1] - (filtered_signal[-2] - filtered_signal[-1]) * 0.5
else:
forecast_direction = "Neutral"
forecast_price_fft = close[-1]
# Check the relationship between the last value and min/max
last_value = close[-1]
if min_value <= last_value <= max_value:
if last_value == min_value:
current_reversal = "DIP"
next_reversal = "TOP"
elif last_value == max_value:
current_reversal = "TOP"
next_reversal = "DIP"
else:
forecast_direction = "Up" if close[-1] > close[-2] else "Down"
forecast_price_fft = price_regression(close)
# Initialize variables for last reversal and distance
distance = None
last_reversal = None
# Calculate the distance between the last reversal and the last value
reversal_idx = None
for i in range(len(close) - 2, -1, -1):
if current_reversal == "DIP" and close[i] == min_value:
reversal_idx = i
break
elif current_reversal == "TOP" and close[i] == max_value:
reversal_idx = i
break
if reversal_idx is not None:
distance = len(close) - 1 - reversal_idx
if current_reversal == "DIP":
last_reversal = "DIP"
elif current_reversal == "TOP":
last_reversal = "TOP"
# Calculate forecast DIP and TOP
if last_reversal == "DIP":
forecast_dip = close[-1] - (distance * 0.1)
forecast_top = forecast_dip + (forecast_dip - close[-1]) * 2
elif last_reversal == "TOP":
forecast_top = close[-1] + (distance * 0.1)
forecast_dip = forecast_top - (close[-1] - forecast_top) * 2
future_price_regression = price_regression(close)
return current_reversal, next_reversal, forecast_direction, forecast_price_fft, future_price_regression, last_reversal, forecast_dip, forecast_top
# Call the calculate_reversal_and_forecast function with the example data
(current_reversal, next_reversal, forecast_direction, forecast_price_fft, future_price_regression, last_reversal, forecast_dip, forecast_top) = calculate_reversal_and_forecast(close)
print()
##################################################
##################################################
def calculate_elements():
# Define PHI constant with 15 decimals
PHI = 1.6180339887498948482045868343656381177
# Calculate the Brun constant from the phi ratio and sqrt(5)
brun_constant = math.sqrt(PHI * math.sqrt(5))
# Define PI constant with 15 decimals
PI = 3.1415926535897932384626433832795028842
# Define e constant with 15 decimals
e = 2.718281828459045235360287471352662498
# Calculate sacred frequency
sacred_freq = (432 * PHI ** 2) / 360
# Calculate Alpha and Omega ratios
alpha_ratio = PHI / PI
omega_ratio = PI / PHI
# Calculate Alpha and Omega spiral angle rates
alpha_spiral = (2 * math.pi * sacred_freq) / alpha_ratio
omega_spiral = (2 * math.pi * sacred_freq) / omega_ratio
# Calculate inverse powers of PHI and fractional reciprocals
inverse_phi = 1 / PHI
inverse_phi_squared = 1 / (PHI ** 2)
inverse_phi_cubed = 1 / (PHI ** 3)
reciprocal_phi = PHI ** -1
reciprocal_phi_squared = PHI ** -2
reciprocal_phi_cubed = PHI ** -3
# Calculate unit circle degrees for each quadrant, including dip reversal up and top reversal down cycles
unit_circle_degrees = {
1: {'angle': 135, 'polarity': ('-', '-'), 'cycle': 'dip_to_top'}, # Quadrant 1 (Dip to Top)
2: {'angle': 45, 'polarity': ('+', '+'), 'cycle': 'top_to_dip'}, # Quadrant 2 (Top to Dip)
3: {'angle': 315, 'polarity': ('+', '-'), 'cycle': 'dip_to_top'}, # Quadrant 3 (Dip to Top)
4: {'angle': 225, 'polarity': ('-', '+'), 'cycle': 'top_to_dip'}, # Quadrant 4 (Top to Dip)
}
# Calculate ratios up to 12 ratio degrees
ratios = [math.atan(math.radians(degrees)) for degrees in range(1, 13)]
# Calculate arctanh values
arctanh_values = {
0: 0,
1: float('inf'),
-1: float('-inf')
}
# Calculate imaginary number
imaginary_number = 1j
return PHI, sacred_freq, unit_circle_degrees, ratios, arctanh_values, imaginary_number, brun_constant, PI, e, alpha_ratio, omega_ratio, inverse_phi, inverse_phi_squared, inverse_phi_cubed, reciprocal_phi, reciprocal_phi_squared, reciprocal_phi_cubed
print()
def forecast_sma_targets(price):
(PHI, sacred_freq, unit_circle_degrees, ratios, arctanh_values, imaginary_number, brun_constant, PI, e, alpha_ratio, omega_ratio, inverse_phi, inverse_phi_squared, inverse_phi_cubed, reciprocal_phi, reciprocal_phi_squared, reciprocal_phi_cubed) = calculate_elements()
output_data = []
output_data.append(f"Given Close Price (Center of Unit Circle): {price}\n")
for quadrant, _ in unit_circle_degrees.items():
# Calculate the forecast price using sacred_freq and square of 9 for the quadrant
target = price + (sacred_freq * math.pow(9, (quadrant * 0.25)))
# Adjust the target price with a 45-degree angle (using trigonometry)
angle_adjustment = sacred_freq * math.cos(math.radians(45)) * (quadrant * 0.25)
target_45 = price + angle_adjustment
distance = ((target - price) / price) * 100
output_data.append(f"Quadrant: {quadrant}")
output_data.append(f"Forecasted Target_Quad_{quadrant}: Price - {target:.2f}, Distance Percentage - {distance:.2f}%")
output_data.append(f"Forecasted 45Degree_Target_Quad_{quadrant}: Price - {target_45:.2f}")
output_data.append("-" * 50)
return output_data
results = forecast_sma_targets(price)
# Print each output string separately
for result in results:
print(result)
print()
##################################################
##################################################
def entry_long(symbol):
try:
# Get balance and leverage
account_balance = get_account_balance()
trade_leverage = 20
# Get symbol price
symbol_price = client.futures_symbol_ticker(symbol=symbol)['price']
# Get step size from exchange info
info = client.futures_exchange_info()
filters = [f for f in info['symbols'] if f['symbol'] == symbol][0]['filters']
step_size = [f['stepSize'] for f in filters if f['filterType']=='LOT_SIZE'][0]
# Calculate max quantity based on balance, leverage, and price
max_qty = int(account_balance * trade_leverage / float(symbol_price) / float(step_size)) * float(step_size)
# Create buy market order
order = client.futures_create_order(
symbol=symbol,
side='BUY',
type='MARKET',
quantity=max_qty)
if 'orderId' in order:
return True
else:
print("Error creating long order.")
return False
except BinanceAPIException as e:
print(f"Error creating long order: {e}")
return False
def entry_short(symbol):
try:
# Get balance and leverage
account_balance = get_account_balance()
trade_leverage = 20
# Get symbol price
symbol_price = client.futures_symbol_ticker(symbol=symbol)['price']
# Get step size from exchange info
info = client.futures_exchange_info()
filters = [f for f in info['symbols'] if f['symbol'] == symbol][0]['filters']
step_size = [f['stepSize'] for f in filters if f['filterType']=='LOT_SIZE'][0]
# Calculate max quantity based on balance, leverage, and price
max_qty = int(account_balance * trade_leverage / float(symbol_price) / float(step_size)) * float(step_size)
# Create sell market order
order = client.futures_create_order(
symbol=symbol,
side='SELL',
type='MARKET',
quantity=max_qty)
if 'orderId' in order:
return True
else:
print("Error creating short order.")
return False
except BinanceAPIException as e:
print(f"Error creating short order: {e}")
return False
def exit_trade():
try:
# Get account information including available margin
account_info = client.futures_account()
# Check if 'availableBalance' is present in the response
if 'availableBalance' in account_info:
available_margin = float(account_info['availableBalance'])
# Check available margin before proceeding
if available_margin < 0:
print("Insufficient available margin to exit trades.")
return
# Get all open positions
positions = client.futures_position_information()
# Loop through each position
for position in positions:
symbol = position['symbol']
position_amount = float(position['positionAmt'])
# Determine order side
if position_amount > 0:
order_side = 'SELL'
elif position_amount < 0:
order_side = 'BUY'
else:
continue # Skip positions with zero amount
# Place order to exit position
order = client.futures_create_order(
symbol=symbol,
side=order_side,
type='MARKET',
quantity=abs(position_amount))
print(f"{order_side} order created to exit {abs(position_amount)} {symbol}.")
print("All positions exited!")
else:
print("Error: 'availableBalance' not found in account_info.")
except BinanceAPIException as e:
print(f"Error exiting trade: {e}")
print()
##################################################
##################################################
import numpy as np
import talib
def market_reversals(close):
gradients = np.gradient(close)
reversals = np.where(np.diff(np.sign(gradients)))[0]
return reversals
def calculate_marketdata_mood(close):
reversals = market_reversals(close)
if len(reversals) < 2:
return "Neutral", None
last_reversal = close[reversals[-2]]
current_reversal = close[reversals[-1]]
if current_reversal > last_reversal:
return "Bullish", current_reversal
elif current_reversal < last_reversal:
return "Bearish", current_reversal
else:
return "Neutral", current_reversal
def forecast_sine_price(close):
mood, current_price = calculate_marketdata_mood(close)
if mood == "Bullish":
forecasted_price = current_price + (current_price - close[-1]) # Real forecast based on the last price difference
return "Up", forecasted_price
elif mood == "Bearish":
forecasted_price = current_price - (close[-1] - current_price) # Real forecast based on the last price difference
return "Down", forecasted_price
else:
return "Stable", current_price
# Generate a sine wave data for demonstration
t = np.linspace(0, 4 * np.pi, 1000)
sine_wave = np.sin(t)
sine_wave = -sine_wave
# Example usage:
reversals = market_reversals(sine_wave)
last_reversal_price = sine_wave[reversals[-2]] if len(reversals) >= 2 else None
current_reversal_price = sine_wave[reversals[-1]] if len(reversals) >= 1 else None
sine_forecast_direction, real_forecasted_price = forecast_sine_price(sine_wave)
print(f"Last Reversal Price: {last_reversal_price}")
print(f"Current Reversal Price: {current_reversal_price}")
print(f"Forecasted Price on Sine Direction: {sine_forecast_direction}")
print()
##################################################
##################################################
def calculate_normalized_distance(price, close):
min_price = np.min(close)
max_price = np.max(close)
distance_to_min = price - min_price
distance_to_max = max_price - price
normalized_distance_to_min = distance_to_min / (distance_to_min + distance_to_max) * 100
normalized_distance_to_max = distance_to_max / (distance_to_min + distance_to_max) * 100
return normalized_distance_to_min, normalized_distance_to_max
def calculate_price_distance_and_wave(price, close):
normalized_distance_to_min, normalized_distance_to_max = calculate_normalized_distance(price, close)
# Calculate HT_SINE using talib
ht_sine, _ = talib.HT_SINE(close)
#ht_sine = -ht_sine
# Initialize market_mood
market_mood = None
# Determine market mood based on HT_SINE crossings and closest reversal
closest_to_min = np.abs(close - np.min(close)).argmin()
closest_to_max = np.abs(close - np.max(close)).argmin()
# Check if any of the elements in the close array up to the last value is the minimum or maximum
if np.any(close[:len(close)-1] == np.min(close[:len(close)-1])):
market_mood = "Uptrend"
elif np.any(close[:len(close)-1] == np.max(close[:len(close)-1])):
market_mood = "Downtrend"
result = {
"price": price,
"ht_sine_value": ht_sine[-1],
"normalized_distance_to_min": normalized_distance_to_min,
"normalized_distance_to_max": normalized_distance_to_max,
"min_price": np.min(close),
"max_price": np.max(close),
"market_mood": market_mood
}
return result
# Example close prices
close_prices = np.array(close) # Insert your actual close prices here
result = calculate_price_distance_and_wave(price, close_prices)
# Print the detailed information for the given price
print(f"Price: {result['price']:.2f}")
print(f"HT_SINE Value: {result['ht_sine_value']:.2f}")
print(f"Normalized Distance to Min: {result['normalized_distance_to_min']:.2f}%")
print(f"Normalized Distance to Max: {result['normalized_distance_to_max']:.2f}%")
print(f"Min Price: {result['min_price']:.2f}")
print(f"Max Price: {result['max_price']:.2f}")
print(f"Market Mood: {result['market_mood']}")
print()