xmd79

algo trading bot using time series

May 9th, 2023 (edited)
1,931
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 28.12 KB | Cryptocurrency | 0 0
  1. import math
  2. import time
  3. import numpy as np
  4. import requests
  5. import talib
  6. import json
  7. import datetime
  8. from datetime import timedelta
  9. from decimal import Decimal
  10. import decimal
  11.  
  12. # binance module imports
  13. from binance.client import Client as BinanceClient
  14. from binance.exceptions import BinanceAPIException, BinanceOrderException
  15. from binance.enums import *
  16.  
  17. # Load credentials from file
  18. with open("credentials.txt", "r") as f:
  19.     lines = f.readlines()
  20.     api_key = lines[0].strip()
  21.     api_secret = lines[1].strip()
  22.  
  23. # Instantiate Binance client
  24. client = BinanceClient(api_key, api_secret)
  25.  
  26. # Define a function to get the account balance in BUSD
  27. def get_account_balance():
  28.     accounts = client.futures_account_balance()
  29.     for account in accounts:
  30.         if account['asset'] == 'BUSD':
  31.             bUSD_balance = float(account['balance'])
  32.             return bUSD_balance
  33.  
  34. # Get the USDT balance of the futures account
  35. bUSD_balance = float(get_account_balance())
  36.  
  37. # Calculate the trade size based on the USDT balance with 20x leverage
  38. TRADE_SIZE = bUSD_balance * 20
  39.  
  40. # Global variables
  41. TRADE_SYMBOL = 'BTCUSDT'
  42. TRADE_TYPE = 'LONG'
  43. TRADE_LVRG = 20
  44. STOP_LOSS_THRESHOLD = 0.0112 # define 1.12% for stoploss
  45. TAKE_PROFIT_THRESHOLD = 0.0336 # define 3.36% for stoploss
  46. BUY_THRESHOLD = -10
  47. SELL_THRESHOLD = 10
  48. EMA_SLOW_PERIOD = 56
  49. EMA_FAST_PERIOD = 12
  50. closed_positions = []
  51. OPPOSITE_SIDE = {'long': 'SELL', 'short': 'BUY'}
  52.  
  53. # Initialize variables for tracking trade state
  54. trade_open = False
  55. trade_side = None
  56. trade_entry_pnl = 0
  57. trade_exit_pnl = 0
  58. trade_entry_time = 0
  59. trade_percentage = 0
  60.  
  61. print()
  62.  
  63. # Print account balance
  64. print("BUSD Futures balance:", bUSD_balance)
  65.  
  66. # Define timeframes
  67. timeframes = ['1m', '3m', '5m']
  68. print(timeframes)
  69.  
  70. print()
  71.  
  72. # Define start and end time for historical data
  73. start_time = int(time.time()) - (86400 * 30)  # 30 days ago
  74. end_time = int(time.time())
  75.  
  76. # Fetch historical data for BTCBUSD pair
  77. candles = {}
  78. for interval in timeframes:
  79.     tf_candles = client.futures_klines(symbol=TRADE_SYMBOL, interval=interval, startTime=start_time * 1000, endTime=end_time * 1000)
  80.     candles[interval] = []
  81.     for candle in tf_candles:
  82.         candles[interval].append({
  83.             'timestamp': candle[0],
  84.             'open': float(candle[1]),
  85.             'high': float(candle[2]),
  86.             'low': float(candle[3]),
  87.             'close': float(candle[4]),
  88.             'volume': float(candle[5])
  89.         })
  90.  
  91. # Print the historical data for BTCUSDT pair
  92. #for interval in timeframes:
  93. #    print(f"Data for {interval} interval:")
  94. #    print(candles[interval])
  95.  
  96. print()
  97.  
  98.  
  99. # Create close prices array for each time frame
  100. close_prices = {}
  101. for interval in timeframes:
  102.     close_prices[interval] = np.array([c['close'] for c in candles[interval]], dtype=np.double)
  103.     print(f"Close prices for {interval} time frame:")
  104.     print(close_prices[interval])
  105.     print()
  106.  
  107. print()
  108.  
  109. # Global variables
  110. closed_positions = []
  111.  
  112. print()
  113.  
  114. def get_mtf_signal(candles, timeframes, percent_to_min=5, percent_to_max=5):
  115.     signals = {}
  116.  
  117.     # Get the OHLCV data for the 1-minute timeframe
  118.     data = np.array([[c['open'], c['high'], c['low'], c['close'], c['volume']] for c in candles['1m']], dtype=np.double)
  119.  
  120.     # Get the HT sine wave indicator for the 1-minute timeframe
  121.     sine, leadsine = talib.HT_SINE(data[:, 3])
  122.  
  123.     # Normalize the HT sine wave indicator to the minimum and maximum prices in the market data
  124.     min_price = np.nanmin(data[:, 3])
  125.     max_price = np.nanmax(data[:, 3])
  126.     norm_sine = (sine - min_price) / (max_price - min_price)
  127.  
  128.     # Get the minimum and maximum values of the normalized HT Sine Wave indicator
  129.     min_sine = np.nanmin(norm_sine)
  130.     max_sine = np.nanmax(norm_sine)
  131.  
  132.     # Calculate the percentage distance from the current close on sine to the minimum and maximum values of the normalized HT Sine Wave indicator
  133.     close = data[-1][-2]
  134.     percent_to_min_val = (max_sine - norm_sine[-1]) / (max_sine - min_sine) * 100
  135.     percent_to_max_val = (norm_sine[-1] - min_sine) / (max_sine - min_sine) * 100
  136.  
  137.     # Print percentages
  138.     print(f"Current close on sine is {percent_to_min_val:.2f}% away from the minimum value")
  139.     print(f"Current close on sine is {percent_to_max_val:.2f}% away from the maximum value")
  140.     print()
  141.  
  142.     # Calculate the distance from the current momentum to the closest reversal keypoint
  143.     if norm_sine[-1] >= max_sine - (max_sine - min_sine) * percent_to_max / 100:
  144.         mtf_signal = "bearish"
  145.         reversal_keypoint = max_sine
  146.         momentum_distance_min = 100 * ((close - max_sine) / (max_price - min_price))
  147.         momentum_distance_max = 100 * ((close - min_sine) / (max_price - min_price))
  148.     elif norm_sine[-1] <= min_sine + (max_sine - min_sine) * percent_to_min / 100:
  149.         mtf_signal = "bullish"
  150.         reversal_keypoint = min_sine
  151.         momentum_distance_min = 100 * ((min_sine - close) / (max_price - min_price))
  152.         momentum_distance_max = 100 * ((max_sine - close) / (max_price - min_price))
  153.     else:
  154.         # Calculate the average percentage across all timeframes
  155.         if signals and len(signals) > 0:
  156.             avg_percent = sum([signals[tf] for tf in signals]) / len(signals)
  157.         else:
  158.             avg_percent = 0.0
  159.  
  160.         # Calculate the distance between the average percentage and the minimum and maximum percentages
  161.         dist_to_min = abs(avg_percent - percent_to_min_val)
  162.         dist_to_max = abs(avg_percent - percent_to_max_val)
  163.  
  164.         if dist_to_min < dist_to_max:
  165.             mtf_signal = "bullish"
  166.         else:
  167.             mtf_signal = "bearish"
  168.  
  169.         reversal_keypoint = None
  170.         momentum_distance_min = None
  171.         momentum_distance_max = None
  172.  
  173.     # Store the percentage distance for each timeframe in the signals dictionary
  174.     for tf in timeframes:
  175.         # Get the OHLCV data for the specified timeframe
  176.         tf_data = np.array([[c['open'], c['high'], c['low'], c['close'], c['volume']] for c in candles[tf]], dtype=np.double)
  177.  
  178.         # Get the HT sine wave indicator for the specified timeframe
  179.         tf_sine, tf_leadsine = talib.HT_SINE(tf_data[:, 3])
  180.  
  181.         # Normalize the HT sine wave indicator to the minimum and maximum prices in the market data
  182.         tf_min_price = np.nanmin(tf_data[:, 3])
  183.         tf_max_price = np.nanmax(tf_data[:, 3])
  184.         tf_norm_sine = (tf_sine - tf_min_price) / (tf_max_price - tf_min_price)
  185.  
  186.         # Get the minimum and maximum values of the normalized HT Sine Wave indicator
  187.         tf_min_sine = np.nanmin(tf_norm_sine)
  188.         tf_max_sine = np.nanmax(tf_norm_sine)
  189.  
  190.         # Calculate the percentage distance from the current close on the sine wave to the minimum and maximum values of the normalized HT Sine Wave indicator
  191.         tf_close = tf_data[-1][-2]
  192.         tf_percent_to_min = (tf_max_sine - tf_norm_sine[-1]) / (tf_max_sine - tf_min_sine) * 100
  193.         tf_percent_to_max = (tf_norm_sine[-1] - tf_min_sine) / (tf_max_sine - tf_min_sine) * 100
  194.  
  195.         # Store the percentage distance in the signals dictionary
  196.         signals[tf] = tf_percent_to_min if mtf_signal == "bullish" else tf_percent_to_max
  197.  
  198.     return signals, mtf_signal
  199.  
  200. # Get the MTF signals
  201. signals, mtf_signal = get_mtf_signal(candles, timeframes, percent_to_min=5, percent_to_max=5)
  202.  
  203. # Print the signals for all timeframes
  204. print("MTF signals:")
  205.  
  206. print()
  207. for tf, signal in signals.items():
  208.     print(f"{tf} - {signal}")
  209.  
  210. print()
  211. # Print the buy/sell signal based on the MTF signals
  212. print("MTF buy/sell signal:", mtf_signal)
  213.  
  214. print()
  215.  
  216. def check_mtf_signal(candles, timeframes, mtf_signal):
  217.     signal = "No Signal"
  218.     # Get the OHLCV data for the 1-minute timeframe
  219.     data = np.array([[c['open'], c['high'], c['low'], c['close'], c['volume']] for c in candles['1m']], dtype=np.double)
  220.  
  221.     # Get the HT sine wave indicator for the 1-minute timeframe
  222.     sine, leadsine = talib.HT_SINE(data[:, 3])
  223.  
  224.     # Normalize the HT sine wave indicator to the minimum and maximum prices in the market data
  225.     min_price = np.nanmin(data[:, 3])
  226.     max_price = np.nanmax(data[:, 3])
  227.     norm_sine = (sine - min_price) / (max_price - min_price)
  228.     norm_leadsine = (leadsine - min_price) / (max_price - min_price)
  229.  
  230.     # Get the minimum and maximum values of the normalized HT Sine Wave indicator
  231.     min_sine = np.nanmin(norm_sine)
  232.     max_sine = np.nanmax(norm_sine)
  233.  
  234.     # Calculate the time difference between the minimum and maximum values
  235.     if np.isnan(min_sine) or np.isnan(max_sine):
  236.         cycle_time_str = "N/A"
  237.     else:
  238.         cycle_time = int(abs(np.nanargmax(norm_sine) - np.nanargmin(norm_sine)) * 0.25)
  239.         cycle_time_str = str(timedelta(minutes=cycle_time, seconds=0)).split(".")[0]
  240.  
  241.         # Calculate the time remaining until the cycle completes
  242.         remaining_time = cycle_time % 30
  243.         if remaining_time == 0:
  244.             remaining_time = 30
  245.  
  246.     # Check if the sine wave fits the market cycle
  247.     close = data[-1][-2]
  248.     if norm_sine[-1] == min_sine and close <= np.nanmin(data[-timeframes['1m']*30:, 3]):
  249.         print("Close is near the last low on price. Sine wave fits the market cycle.")
  250.     elif norm_sine[-1] == max_sine and close >= np.nanmax(data[-timeframes['1m']*30:, 3]):
  251.         print("Close is near the last high on price. Sine wave fits the market cycle.")
  252.     else:
  253.         print("Sine wave momentum 1min tf does not fit the market cycle reversals but in range between key points...seeking reversal")
  254.  
  255.     print()
  256.  
  257.     # Calculate the percentage distance from the current close on sine to the minimum and maximum values of the normalized HT Sine Wave indicator
  258.     percent_to_min = 100 * ((max_sine - norm_sine[-1]) / (max_sine - min_sine))
  259.     percent_to_max = 100 * ((norm_sine[-1] - min_sine) / (max_sine - min_sine))
  260.  
  261.     # Print percentages
  262.     print(f"Current close on sine is {percent_to_min:.2f}% away from the minimum value")
  263.     print(f"Current close on sine is {percent_to_max:.2f}% away from the maximum value")
  264.     print()
  265.  
  266.     # Calculate the distance from the current momentum to the closest reversal keypoint
  267.     if mtf_signal == "bearish":
  268.         reversal_keypoint = max_sine
  269.         momentum_distance_min = 100 * ((close - max_sine) / (max_price - min_price))
  270.         momentum_distance_max = 100 * ((close - min_sine) / (max_price - min_price))
  271.     else:
  272.         reversal_keypoint = min_sine
  273.         momentum_distance_min = 100 * ((min_sine - close) / (max_price - min_price))
  274.         momentum_distance_max = 100 * ((max_sine - close) / (max_price - min_price))
  275.  
  276.     # Calculate the range between 0 to 100% from close to first reversal incoming closest to current value of close on sine
  277.     if mtf_signal == "bearish":
  278.         momentum_range = np.arange(norm_sine[-1], max_sine + 0.0001, (max_sine - norm_sine[-1]) / 100)
  279.     else:
  280.         momentum_range = np.arange(min_sine - 0.0001, norm_sine[-1], (norm_sine[-1] - min_sine) / 100)
  281.  
  282.     # Determine the trade signal based on momentum and trend signals
  283.     if mtf_signal == "bearish" and norm_sine[-1] >= reversal_keypoint:
  284.         signal = "bearish"
  285.     elif mtf_signal == "bullish" and norm_sine[-1] <= reversal_keypoint:
  286.         signal = "bullish"
  287.     else:
  288.         if percent_to_min > 80:
  289.             signal = "Momentum Bearish"
  290.         elif percent_to_max > 80:
  291.             signal = "Momentum Bullish"
  292.    
  293.     print()
  294.     return signal, momentum_distance_min, momentum_distance_max, momentum_range, cycle_time_str, remaining_time, percent_to_min, percent_to_max
  295.  
  296. mtf = check_mtf_signal(candles, timeframes, mtf_signal)
  297. print(mtf[0])
  298. print()
  299.  
  300. def forecast_price(candles, timeframes, mtf_signal):
  301.     signal, momentum_distance_min, momentum_distance_max, momentum_range, cycle_time_str, remaining_time, percent_to_min, percent_to_max = check_mtf_signal(candles, timeframes, mtf_signal)
  302.     close = candles['1m'][-1]['close']
  303.     if signal == "bearish":
  304.         target_percent = percent_to_min - 10
  305.         if target_percent < 0:
  306.             target_percent = 0
  307.         target_price = norm_sine[-1] - (target_percent/100) * (max_sine - min_sine)
  308.     elif signal == "bullish":
  309.         target_percent = percent_to_max + 10
  310.         if target_percent > 100:
  311.             target_percent = 100
  312.         target_price = norm_sine[-1] + (target_percent/100) * (max_sine - min_sine)
  313.     else:
  314.         target_price = close
  315.     #target_price += 1000  # add 1000 to the target price
  316.     return round(target_price, 2)
  317.  
  318. forecast = forecast_price(candles, timeframes, mtf_signal)
  319. print(forecast)
  320. print()
  321.  
  322. def get_mtf_signal_v2(candles, timeframes, percent_to_min=5, percent_to_max=5):
  323.     signals = {}
  324.    
  325.     # Get the OHLCV data for the 1-minute timeframe
  326.     data_1m = np.array([[c['open'], c['high'], c['low'], c['close'], c['volume']] for c in candles['1m']], dtype=np.double)
  327.    
  328.     # Get the HT sine wave indicator for the 1-minute timeframe
  329.     sine, leadsine = talib.HT_SINE(data_1m[:, 3])
  330.    
  331.     # Normalize the HT sine wave indicator to the minimum and maximum prices in the market data
  332.     min_price = np.nanmin(data_1m[:, 3])
  333.     max_price = np.nanmax(data_1m[:, 3])
  334.     norm_sine = (sine - min_price) / (max_price - min_price)
  335.    
  336.     # Get the minimum and maximum values of the normalized HT Sine Wave indicator
  337.     min_sine = np.nanmin(norm_sine)
  338.     max_sine = np.nanmax(norm_sine)
  339.    
  340.     # Calculate the percentage distance from the current close on sine to the minimum and maximum values of the normalized HT Sine Wave indicator
  341.     close = data_1m[-1][-2]
  342.     percent_to_min_val = (max_sine - norm_sine[-1]) / (max_sine - min_sine) * 100
  343.     percent_to_max_val = (norm_sine[-1] - min_sine) / (max_sine - min_sine) * 100
  344.    
  345.     for timeframe in timeframes:
  346.         # Get the OHLCV data for the given timeframe
  347.         ohlc_data = np.array([[c['open'], c['high'], c['low'], c['close'], c['volume']] for c in candles[timeframe]], dtype=np.double)
  348.        
  349.         # Calculate the momentum signal for the given timeframe
  350.         close_prices = ohlc_data[:, 3]
  351.         momentum = talib.MOM(close_prices, timeperiod=14)
  352.        
  353.         # Calculate the minimum and maximum values for the momentum signal
  354.         min_momentum = np.nanmin(momentum)
  355.         max_momentum = np.nanmax(momentum)
  356.        
  357.         # Calculate the percentage distance from the current momentum to the minimum and maximum values of the momentum signal
  358.         current_momentum = momentum[-1]
  359.         percent_to_min_momentum = (max_momentum - current_momentum) / (max_momentum - min_momentum) * 100
  360.         percent_to_max_momentum = (current_momentum - min_momentum) / (max_momentum - min_momentum) * 100
  361.        
  362.         # Calculate the new momentum signal based on percentages from the MTF signal and the initial momentum signal
  363.         percent_to_min_combined = (percent_to_min_val + percent_to_min_momentum) / 2
  364.         percent_to_max_combined = (percent_to_max_val + percent_to_max_momentum) / 2
  365.         momentum_signal = percent_to_max_combined - percent_to_min_combined
  366.        
  367.         # Calculate the new average for the MTF signal based on the percentage distance from the current close to the minimum and maximu values of the normalized HT Sine Wave indicator, and the given percentage thresholds
  368.         min_mtf = np.nanmin(ohlc_data[:, 3])
  369.         max_mtf = np.nanmax(ohlc_data[:, 3])
  370.         percent_to_min_custom = percent_to_min / 100
  371.         percent_to_max_custom = percent_to_max / 100
  372.         min_threshold = min_mtf + (max_mtf - min_mtf) * percent_to_min_custom
  373.         max_threshold = max_mtf - (max_mtf - min_mtf) * percent_to_max_custom
  374.         filtered_close = np.where(ohlc_data[:, 3] < min_threshold, min_threshold, ohlc_data[:, 3])
  375.         filtered_close = np.where(filtered_close > max_threshold, max_threshold, filtered_close)
  376.         avg_mtf = np.nanmean(filtered_close)
  377.        
  378.         # Store the signals for the given timeframe
  379.         signals[timeframe] = {'momentum': momentum_signal, 'ht_sine_percent_to_min': percent_to_min_val, 'ht_sine_percent_to_max': percent_to_max_val, 'mtf_average': avg_mtf, 'min_threshold': min_threshold, 'max_threshold': max_threshold}
  380.    
  381.     current_time = datetime.datetime.utcnow() + datetime.timedelta(hours=3)
  382.  
  383.     # Print the results
  384.     print("Current time:", current_time.strftime('%Y-%m-%d %H:%M:%S'))
  385.     print(f"HT Sine Wave Percent to Min: {percent_to_min_val:.2f}%")
  386.     print(f"HT Sine Wave Percent to Max: {percent_to_max_val:.2f}%")
  387.     print(f"Momentum Percent to Min: {percent_to_min_momentum:.2f}%")
  388.     print(f"Momentum Percent to Max: {percent_to_max_momentum:.2f}%")
  389.     print(f"Combined Percent to Min: {percent_to_min_combined:.2f}%")
  390.     print(f"Combined Percent to Max: {percent_to_max_combined:.2f}%")
  391.     print(f"New Momentum Signal: {momentum_signal:.2f}")
  392.     print(f"New MTF Average:")
  393.     for timeframe in timeframes:
  394.         print(f"{timeframe}: {signals[timeframe]['mtf_average']:.2f} (min threshold: {signals[timeframe]['min_threshold']:.2f}, max threshold: {signals[timeframe]['max_threshold']:.2f})")
  395.     print()
  396.  
  397.     return signals
  398.  
  399. get_mtf_signal_v2(candles, timeframes, percent_to_min=5, percent_to_max=5)
  400.  
  401. def get_historical_candles(symbol, start_time, end_time, timeframe):
  402.     candles = client.futures_klines(symbol=symbol, interval=timeframe, startTime=start_time * 1000, endTime=end_time * 1000)
  403.     candles_by_timeframe = {}
  404.     for tf in ['1m', '3m', '5m']:
  405.         if tf == timeframe:
  406.             candles_by_timeframe[tf] = [ {'open': float(candle[1]), 'high': float(candle[2]), 'low': float(candle[3]), 'close': float(candle[4]), 'volume': float(candle[5])} for candle in candles ]
  407.         else:
  408.             resampled_candles = []
  409.             for i in range(0, len(candles), int(tf[:-1])):
  410.                 candles_chunk = candles[i:i+int(tf[:-1])]
  411.                 if len(candles_chunk) == int(tf[:-1]):
  412.                     open_price = float(candles_chunk[0][1])
  413.                     high_price = max([float(candle[2]) for candle in candles_chunk])
  414.                     low_price = min([float(candle[3]) for candle in candles_chunk])
  415.                     close_price = float(candles_chunk[-1][4])
  416.                     total_volume = sum([float(candle[5]) for candle in candles_chunk])
  417.                     resampled_candles.append({'open': open_price, 'high': high_price, 'low': low_price, 'close': close_price, 'volume': total_volume})
  418.             candles_by_timeframe[tf] = resampled_candles
  419.  
  420.     return candles_by_timeframe
  421.  
  422. def get_current_price(symbol):
  423.     ticker = client.futures_symbol_ticker(symbol=symbol)
  424.     return float(ticker['price'])
  425.  
  426. def get_min_order_quantity(symbol):
  427.     try:
  428.         exchange_info = client.futures_exchange_info()
  429.         symbol_info = next(filter(lambda x: x['symbol'] == symbol, exchange_info['symbols']))
  430.         min_qty = float(symbol_info['filters'][2]['minQty'])
  431.         return min_qty
  432.     except Exception as e:
  433.         print(f"Error getting minimum order quantity for {symbol}: {e}")
  434.         return None
  435.  
  436. def entry_long(symbol):
  437.     try:
  438.         # Get the available account balance and set the leverage to 20x
  439.         bUSD_balance = float(get_account_balance())
  440.         TRADE_LVRG = 20
  441.  
  442.         # Calculate the maximum order quantity based on the current price
  443.         symbol_price = float(client.futures_symbol_ticker(symbol=symbol)['price'])
  444.  
  445.         # Calculate the order quantity as the entire available balance
  446.         quantity = round((bUSD_balance / symbol_price), 6)
  447.  
  448.         # Check that the resulting quantity meets the minimum order quantity for the asset
  449.         min_quantity = float(get_min_order_quantity(symbol))
  450.         if quantity < min_quantity:
  451.             print(f"Order quantity is less than the minimum quantity: {quantity} < {min_quantity}")
  452.             return False
  453.  
  454.         # Create the long order at market price
  455.         order = client.futures_create_order(
  456.             symbol=symbol,
  457.             side=client.SIDE_BUY,
  458.             type=client.ORDER_TYPE_MARKET,
  459.             quantity=quantity)
  460.  
  461.         print(f"Long order created for {quantity} {symbol} at market price.")
  462.         return True
  463.  
  464.     except BinanceAPIException as e:
  465.         print(f"Error creating long order: {e}")
  466.         return False
  467.  
  468. def entry_short(symbol):
  469.     try:
  470.         # Get the available account balance and set the leverage to 20x
  471.         bUSD_balance = float(get_account_balance())
  472.         TRADE_LVRG = 20
  473.  
  474.         # Calculate the maximum order quantity based on the current price
  475.         symbol_price = float(client.futures_symbol_ticker(symbol=symbol)['price'])
  476.  
  477.         # Calculate the order quantity as the entire available balance
  478.         quantity = round((bUSD_balance / symbol_price), 6)
  479.  
  480.         # Check that the resulting quantity meets the minimum order quantity for the asset
  481.         min_quantity = float(get_min_order_quantity(symbol))
  482.         if quantity < min_quantity:
  483.             print(f"Order quantity is less than the minimum quantity: {quantity} < {min_quantity}")
  484.             return False
  485.  
  486.         # Create the short order at market price
  487.         order = client.futures_create_order(
  488.             symbol=symbol,
  489.             side=client.SIDE_SELL,
  490.             type=client.ORDER_TYPE_MARKET,
  491.             quantity=quantity)
  492.  
  493.         print(f"Short order created for {quantity} {symbol} at market price.")
  494.         return True
  495.  
  496.     except BinanceAPIException as e:
  497.         print(f"Error creating short order: {e}")
  498.         return False
  499.  
  500. def exit_trade(symbol):
  501.     try:
  502.         total_quantity = 0
  503.         positions = client.futures_position_information(symbol=symbol)
  504.  
  505.         for position in positions:
  506.             if float(position['positionAmt']) != 0:
  507.                 side = 'SELL' if position['positionSide'] == 'LONG' else 'BUY'
  508.                 quantity = abs(float(position['positionAmt']))
  509.                 order = client.futures_create_order(
  510.                     symbol=symbol,
  511.                     side=side,
  512.                     type=client.ORDER_TYPE_MARKET,
  513.                     quantity=quantity)
  514.  
  515.                 total_quantity += quantity
  516.                 print(f"Closed {quantity} {symbol} position with {side} order at market price.")
  517.  
  518.         print(f"Total of {total_quantity} {symbol} positions closed.")
  519.         return True
  520.  
  521.     except BinanceAPIException as e:
  522.         print(f"Error closing positions: {e}")
  523.         return False
  524.  
  525. def calculate_ema(candles, period):
  526.     prices = [float(candle['close']) for candle in candles]
  527.     ema = []
  528.     sma = sum(prices[:period]) / period
  529.     multiplier = 2 / (period + 1)
  530.     ema.append(sma)
  531.     for price in prices[period:]:
  532.         ema.append((price - ema[-1]) * multiplier + ema[-1])
  533.     return ema
  534.  
  535. def main():
  536.     global TRADE_SYMBOL
  537.     global EMA_SLOW_PERIOD
  538.     global EMA_FAST_PERIOD
  539.  
  540.     momentum = {}
  541.  
  542.     print("Starting main loop...")
  543.  
  544.     while True:
  545.         print("Looping...")
  546.         print()
  547.         try:
  548.             # Check if balance is zero
  549.             #account_balance = float(get_account_balance())
  550.             #if account_balance == 0:
  551.                 #print("Balance is zero. Exiting program.")
  552.                 #break
  553.  
  554.             # Define electromagnetic field variables
  555.             em_field = 0.1  # Tesla
  556.             em_amp = 10  # Amperes
  557.             em_phase = 0  # Radians
  558.  
  559.             # Define sine wave variables
  560.             wave_len = 30 * 60  # 30 minutes in seconds
  561.             wave_freq = 1 / wave_len
  562.             time_period = 2 * math.pi / wave_freq
  563.             time_step = 1
  564.             num_cycles = 1
  565.             t = np.arange(0, num_cycles * time_period, time_step)
  566.             sine_wave = em_field * np.sin(2 * math.pi * wave_freq * t + em_phase)
  567.  
  568.             # Print electromagnetic spectrum pulse with waves frequencies
  569.             print("Electromagnetic Spectrum Pulse:")
  570.             print()
  571.             print("Gamma waves (30-100 Hz):", np.linspace(30, 100, num=10))
  572.             print("Beta waves (12-30 Hz):", np.linspace(12, 30, num=10))
  573.             print("Alpha waves (8-12 Hz):", np.linspace(8, 12, num=10))
  574.             print("Theta waves (4-8 Hz):", np.linspace(4, 8, num=10))
  575.             print("Delta waves (0.1-4 Hz):", np.linspace(0.1, 4, num=10))
  576.             print()
  577.             print()
  578.  
  579.             # Print sine wave variables and values
  580.             print("Sine Wave Variables:")
  581.             print()
  582.             print("Wave Length (seconds):", wave_len)
  583.             print("Wave Frequency (Hz):", wave_freq)
  584.             print("Time Period (seconds):", time_period)
  585.             print("Time Step (seconds):", time_step)
  586.             print("Number of Cycles:", num_cycles)
  587.             print("Sine Wave Values:", sine_wave)
  588.             print()
  589.             print()
  590.  
  591.             # Define start and end time for historical data
  592.             start_time = int(time.time()) - (1800 * 4)  # 60-minute interval (4 candles)
  593.             end_time = int(time.time())
  594.  
  595.             # Define the candles and timeframes to use for the signals
  596.             candles = get_historical_candles(TRADE_SYMBOL, start_time, end_time, '1m')
  597.             timeframes = ['1m', '3m', '5m']
  598.             #print(candles)
  599.  
  600.             # Check if candles is empty
  601.             if not candles:
  602.                 print("Error: No historical candles found.")
  603.  
  604.             # Get the MTF signal
  605.             signals = get_mtf_signal_v2(candles, timeframes, percent_to_min=1, percent_to_max=1)
  606.  
  607.             print(signals)
  608.             print()
  609.  
  610.             # Check if the '1m' key exists in the signals dictionary
  611.             if '1m' in signals:
  612.                 # Check if the percent to min/max signal keys exist in the '1m' dictionary
  613.                 if 'ht_sine_percent_to_min' in signals['1m'] and 'ht_sine_percent_to_max' in signals['1m']:
  614.                     print("Reached the '1m' signals check.")
  615.  
  616.                     percent_to_min_val = signals['1m']['ht_sine_percent_to_min']
  617.                     percent_to_max_val = signals['1m']['ht_sine_percent_to_max']
  618.                     mtf_average = signals['1m']['mtf_average']
  619.                     close_prices = np.array([candle['close'] for candle in candles['1m']])
  620.  
  621.                     print("Close price:", close_prices[-1])
  622.                     print("MTF average:", mtf_average)
  623.                     print("Percent to min:", percent_to_min_val)
  624.                     print("Percent to max:", percent_to_max_val)
  625.  
  626.                     # Check if EMA periods have been set
  627.                     if EMA_SLOW_PERIOD and EMA_FAST_PERIOD:
  628.                         #print("EMA Slow Period:", EMA_SLOW_PERIOD)
  629.                         #print("EMA Fast Period:", EMA_FAST_PERIOD)
  630.  
  631.                         # Calculate the EMA signals
  632.                         ema_slow = talib.EMA(close_prices, EMA_SLOW_PERIOD)[-1]
  633.                         ema_fast = talib.EMA(close_prices, EMA_FAST_PERIOD)[-1]
  634.  
  635.                         print("EMA Slow:", ema_slow)
  636.                         print("EMA Fast:", ema_fast)
  637.  
  638.                         # Check if the EMA cross signal has been generated
  639.                         if close_prices[-1] < ema_fast < ema_slow and TRADE_SYMBOL not in momentum:
  640.                             print("BUY signal")
  641.  
  642.                         elif close_prices[-1] > ema_fast > ema_slow and TRADE_SYMBOL in momentum:
  643.                             print("SELL signal")
  644.  
  645.             # Flush all data after each iteration
  646.             account_balance = None
  647.             em_field = None
  648.             em_amp = None
  649.             em_phase = None
  650.             wave_len = None
  651.             wave_freq = None
  652.             time_period = None
  653.             time_step = None
  654.             num_cycles = None
  655.             t = None
  656.             sine_wave = None
  657.             start_time = None
  658.             end_time = None
  659.             candles = None
  660.             timeframes = None
  661.             signals = None
  662.             percent_to_min_val = None
  663.             percent_to_max_val = None
  664.             mtf_average = None
  665.             close_prices = None
  666.             ema_slow = None
  667.             ema_fast = None
  668.  
  669.             # Sleep for 5sec
  670.             time.sleep(5)
  671.  
  672.         except Exception as e:
  673.             print("Error:", e)
  674.             break
  675.  
  676. # Run the main function
  677. if __name__ == '__main__':
  678.     main()
Advertisement
Comments
Add Comment
Please, Sign In to add comment