I used your code: import time
from binance.client import Client
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
import ta.volatility
API_KEY = ‘’
API_SECRET = ‘’
API_KEY_MEXC = ‘’
API_SECRET_MEXC = ‘’

client = Client(API_KEY, API_SECRET)

def sync_time():
server_time = requests.get(‘https://api.binance.com/api/v3/time’).json()['serverTime’]
local_time = int(time.time() * 1000)
time_difference = server_time - local_time
# Set the system clock to the new time
os.system(f’sudo date -s @{int(server_time/1000)}‘)
print(f’New time: {dt.datetime.now()}’)

# Sync your local time with the server time
sync_time()

# Set the endpoint and parameters for the request
url = “https://fapi.binance.com/fapi/v1/klines”
symbol = ‘BCH/USDT’
interval = ‘1m’
lookback = 44640
timestamp = int(time.time() * 1000) - 500 # subtract 500ms from local time to account for clock-drift
recv_window = 60000 # increased recv_window value
params = {
“symbol”: symbol.replace(“/”, “”),
“interval”: interval,
“startTime”: int((time.time() - lookback * 60) * 1000),
“endTime”: int(time.time() * 1000),
“timestamp”: timestamp,
“recvWindow”: recv_window
}

# Sign the message using the Client’s secret key
message = “&”.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params[signature] = signature

# Send the request using the requests library
response = requests.get(url, params=params, headers={‘X-MBX-APIKEY’: API_KEY})

# Check for errors in the response
response.raise_for_status()


# Initialize MEXC client
mexc_futures = ccxt.mexc({
‘apiKey’: API_KEY_MEXC,
‘secret’: API_SECRET_MEXC,
‘enableRateLimit’: True,
‘options’: {
‘defaultType’: ‘future’,
}
})
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = “https://fapi.binance.com/fapi/v1/klines”
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace(“/”, “”) # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}“
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36’
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print(‘No data found for the given timeframe and symbol’)
return None
ohlcv = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime(‘%Y-%m-%d %H:%M:%S’)
ohlcv.append({
‘Open time’: timestamp,
‘Open’: float(d[1]),
‘High’: float(d[2]),
‘Low’: float(d[3]),
‘Close’: float(d[4]),
‘Volume’: float(d[5])
})
df = pd.DataFrame(ohlcv)
df.set_index(‘Open time’, inplace=True)
return df
df = get_klines(symbol, interval, lookback)

def signal_generator(df):
if df is None:
return ‘’
ema_analysis = []
candle_analysis = []

df[‘EMA5’] = df[‘Close’].ewm(span=5, adjust=False).mean()
df[‘EMA20’] = df[‘Close’].ewm(span=20, adjust=False).mean()
df[‘EMA100’] = df[‘Close’].ewm(span=100, adjust=False).mean()
df[‘EMA200’] = df[‘Close’].ewm(span=200, adjust=False).mean()

if (
df[‘EMA5’].iloc[-1] > df[‘EMA20’].iloc[-1] and
df[‘EMA20’].iloc[-1] > df[‘EMA100’].iloc[-1] and
df[‘EMA100’].iloc[-1] > df[‘EMA200’].iloc[-1] and
df[‘EMA5’].iloc[-2] < df[‘EMA20’].iloc[-2] and
df[‘EMA20’].iloc[-2] < df[‘EMA100’].iloc[-2] and
df[‘EMA100’].iloc[-2] < df[‘EMA200’].iloc[-2]
):
ema_analysis.append(‘golden_cross’)

elif (
df[‘EMA5’].iloc[-1] < df[‘EMA20’].iloc[-1] and
df[‘EMA20’].iloc[-1] < df[‘EMA100’].iloc[-1] and
df[‘EMA100’].iloc[-1] < df[‘EMA200’].iloc[-1] and
df[‘EMA5’].iloc[-2] > df[‘EMA20’].iloc[-2] and
df[‘EMA20’].iloc[-2] > df[‘EMA100’].iloc[-2] and
df[‘EMA100’].iloc[-2] > df[‘EMA200’].iloc[-2]
):
ema_analysis.append(‘death_cross’)

if (
df[‘Close’].iloc[-1] > df[‘Open’].iloc[-1] and
df[‘Open’].iloc[-1] > df[‘Low’].iloc[-1] and
df[‘High’].iloc[-1] > df[‘Close’].iloc[-1]
):
candle_analysis.append(‘bullish_engulfing’)
elif (
df[‘Close’].iloc[-1] < df[‘Open’].iloc[-1] and
df[‘Open’].iloc[-1] < df[‘High’].iloc[-1] and
df[‘Low’].iloc[-1] > df[‘Close’].iloc[-1]
):
candle_analysis.append(‘bearish_engulfing’)

bollinger_std = df[‘Close’].rolling(window=20).std()
df[‘UpperBand’] = df[‘EMA20’] + (bollinger_std * 2)
df[‘LowerBand’] = df[‘EMA20’] - (bollinger_std * 2)

if (
df[‘Close’].iloc[-1] > df[‘UpperBand’].iloc[-1] and
df[‘Close’].iloc[-2] < df[‘UpperBand’].iloc[-2]
):
candle_analysis.append(‘upper_band_breakout’)
elif (
df[‘Close’].iloc[-1] < df[‘LowerBand’].iloc[-1] and
df[‘Close’].iloc[-2] > df[‘LowerBand’].iloc[-2]
):
candle_analysis.append(‘lower_band_breakout’)

if (‘golden_cross’ in ema_analysis and ‘bullish_engulfing’ in candle_analysis) or ‘upper_band_breakout’ in candle_analysis:
return ‘buy’
elif (‘death_cross’ in ema_analysis and ‘bearish_engulfing’ in candle_analysis) or ‘lower_band_breakout’ in candle_analysis:
return ‘sell’
else:
return ‘’

end_time = int(time.time() * 1000)
start_time = end_time - lookback * 60 * 1000

def get_futures_balance(symbol):
try:
balance = mexc_futures.fetch_balance()
print(balance) # Add this line to inspect the balance variable
futures_balance = balance[‘info’][‘data’][symbol]
return futures_balance[‘total’]
except Exception as e:
print(f"Error getting futures balance: {e}”)
return 0


futures_balance = get_futures_balance(symbol)
quantity = futures_balance * 0.5
print(f"Quantity: {quantity}“)


def execute_order(symbol, order_type, side, quantity):
try:
order = client.create_order(
symbol=symbol,
side=side,
type=order_type,
quantity=quantity
)
return order
except Exception as e:
print(f"Error executing order: {e}”)
return None

def get_open_orders(symbol):
try:
orders = client.get_open_orders(symbol=symbol)
return orders
except Exception as e:
print(f"Error getting open orders: {e}“)
return []

def close_position(symbol):
try:
open_orders = get_open_orders(symbol)
if open_orders:
for order in open_orders:
client.cancel_order(
symbol=symbol,
origClientOrderId=order[‘orderId’]
)
print(“Position closed successfully.”)
except Exception as e:
print(f"Error closing position: {e}”)

# Rest of the code…
order_type = ‘MARKET’

while True:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S’)} - Signal: {signal}“)

if signal == ‘buy’:
open_orders = get_open_orders(symbol)
if not open_orders:
# Open Long position
order = execute_order(symbol, order_type, ‘BUY’, quantity)
if order:
print(f"Opened Long position. Order ID: {order[‘orderId’]}”)
else:
# Close all open orders
close_position(symbol)

elif signal == ‘sell’:
open_orders = get_open_orders(symbol)
if not open_orders:
# Open Short position
order = execute_order(symbol, order_type, ‘SELL’, quantity)
if order:
print(f"Opened Short position. Order ID: {order[‘orderId’]}")
else:
# Close all open orders
close_position(symbol)
time.sleep(1)
But it doesn’t give me my any signals, give me code which will give me signals

Your advices: The code you provided seems to have all the necessary functions and logic to generate trading signals based on the EMA crossover and candlestick patterns. However, there might be some issues with the data source or the parameters being used.

Here are a few possible improvements you can make to the code:

1. Check data source: Ensure that the get_klines function is correctly fetching the historical data for the specified symbol and interval. You can add print statements or debug the code to see if the data is being retrieved successfully.

2. Adjust lookback period: The lookback parameter determines the number of minutes of historical data to fetch. Make sure the value is appropriate for your trading strategy. You can also experiment with different lookback periods to see if it affects the generation of signals.

3. Verify signal conditions: Double-check the conditions for generating buy and sell signals in the signal_generator function. Ensure that the conditions are correctly evaluating the moving averages and candlestick patterns.

4. Test on different symbols and intervals: Try running the code on different symbols and intervals to see if it generates signals for them. It’s possible that the current symbol and interval combination is not producing any signals due to specific market conditions.

5. Verify account balance and quantity: Double-check your account balance and ensure that you have enough funds available to place orders. Also, verify the calculation of the quantity variable to ensure that it is being set correctly for opening positions.

6. Monitor error messages: Check for any error messages or exceptions being printed in the console. These messages can provide valuable information about any issues or errors that might be occurring.

Make these adjustments and run the code again to see if it successfully generates trading signals. If you encounter any specific error messages or issues, please provide those details so that I can assist you further.