I used your code: import time import requests import hmac import hashlib import datetime…
- User
I used your code: import time import requests import hmac import hashlib import datetime as dt import pandas as pd API_KEY = '' API_SECRET = ''
symbol = 'BCH/USDT' interval = '1m' lookback = 43200
def generate_signature(api_key, api_secret, endpoint, params): params_string = '&'.join([f'{key}={params[key]}' for key in params]) payload = f'{endpoint}?{params_string}' signature = hmac.new(api_secret.encode('utf-8'), payload.encode('utf-8'), hashlib.sha256).hexdigest() return signature
def get_historical_data(symbol, interval, start_time, end_time): url = 'https://www.mexc.com/open/api/v2/market/kline' params = { 'symbol': symbol, 'interval': interval, 'start_time': start_time, 'end_time': end_time } signature = generate_signature(API_KEY, API_SECRET, '/open/api/v2/market/kline', params) params['api_key'] = API_KEY params['sign'] = signature
response = requests.get(url, params=params, timeout=10) if response.status_code == 200: data = response.json()['data'] df = pd.DataFrame(data, columns=['time', 'open', 'high', 'low', 'close', 'volume']) df['time'] = pd.to_datetime(df['time'], unit='ms') return dfdef 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] > df['EMA100'].iloc[-1] > df['EMA200'].iloc[-1] and df['EMA5'].iloc[-2] < df['EMA20'].iloc[-2] < df['EMA100'].iloc[-2] < df['EMA200'].iloc[-2] ): ema_analysis.append('golden_cross') elif ( df['EMA5'].iloc[-1] < df['EMA20'].iloc[-1] < df['EMA100'].iloc[-1] < df['EMA200'].iloc[-1] and df['EMA5'].iloc[-2] > df['EMA20'].iloc[-2] > 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') if 'golden_cross' in ema_analysis and 'bullish_engulfing' in candle_analysis: return 'buy' elif 'death_cross' in ema_analysis and 'bearish_engulfing' in candle_analysis: return 'sell' else: return ''end_time = int(time.time() * 1000) start_time = end_time - lookback * 60 * 1000
while True: df = get_historical_data(symbol, interval, None, None) signal = signal_generator(df) print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {signal}")
- Assistant
To print the DataFrame
df, you can addprint(df)after calling theget_historical_datafunction. Here's the modified code:while True: df = get_historical_data(symbol, interval, None, None) print(df) # Print the DataFrame signal = signal_generator(df) print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {signal}") time.sleep(1) # Wait for 1 minute before checking againThis will print the DataFrame
dfevery time it is fetched from theget_historical_datafunction. - User
But I doesn't want to print it eevery second
- Assistant
If you don't want to print the DataFrame
dfevery second, you can modify the code to print it only once or at specific intervals. Here's an example that prints the DataFrame every 5 minutes:interval_minutes = 5 # Print interval in minutes interval_seconds = interval_minutes * 60 # Convert interval to seconds next_print_time = time.time() + interval_seconds while True: current_time = time.time() if current_time >= next_print_time: df = get_historical_data(symbol, interval, None, None) print(df) # Print the DataFrame next_print_time = current_time + interval_seconds signal = signal_generator(df) print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {signal}") time.sleep(1) # Wait for 1 second before checking againIn this example, the DataFrame will be printed every 5 minutes (or the specified interval) by checking the current time and comparing it to the
next_print_time. - User
- Assistant
The problem is that your
while Trueloop is placed inside theget_historical_datafunction. As a result, it is not executed and the program gets stuck in theget_historical_datafunction.To fix this, you need to remove the
while Trueloop from theget_historical_datafunction and keep it outside, in the main body of your code. Here's the corrected code: - User
How I can import historical data from MEXC ?
- Assistant
To import historical data from MEXC, you can use their API to retrieve the data. Here's an example code that fetches historical data for a specified symbol and time interval using the MEXC API:
import requests import pandas as pd API_KEY = '' # Add your API key here API_SECRET = '' # Add your API secret here symbol = 'BCH/USDT' interval = '1m' lookback = 43200 def generate_signature(api_key, api_secret, endpoint, params): params_string = '&'.join([f'{key}={params[key]}' for key in params]) payload = f'{endpoint}?{params_string}' signature = hmac.new(api_secret.encode('utf-8'), payload.encode('utf-8'), hashlib.sha256).hexdigest() return signature def get_historical_data(symbol, interval, start_time, end_time): url = 'https://www.mexc.com/open/api/v2/market/kline' params = { 'symbol': symbol, 'interval': interval, 'start_time': start_time, 'end_time': end_time } signature = generate_signature(API_KEY, API_SECRET, '/open/api/v2/market/kline', params) params['api_key'] = API_KEY params['sign'] = signature response = requests.get(url, params=params, timeout=10) if response.status_code == 200: data = response.json()['data'] df = pd.DataFrame(data, columns=['time', 'open', 'high', 'low', 'close', 'volume']) df['time'] = pd.to_datetime(df['time'], unit='ms') return df end_time = int(time.time() * 1000) start_time = end_time - lookback * 60 * 1000 df = get_historical_data(symbol, interval, start_time, end_time) print(df)