#!/usr/bin/env python import asyncio import logging import sys import platform import ccxt.async_support as ccxt import os import datetime # Fix for Windows asyncio issues with aiodns if platform.system() == 'Windows': try: import asyncio asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) print("Using Windows SelectorEventLoopPolicy to fix aiodns issue") except Exception as e: print(f"Failed to set WindowsSelectorEventLoopPolicy: {e}") # Setup direct console logging for immediate feedback logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.StreamHandler(sys.stdout) ] ) logger = logging.getLogger(__name__) async def initialize_exchange(): """Initialize the exchange with API credentials from environment variables""" exchange_id = 'mexc' try: # Get API credentials from environment variables api_key = os.getenv('MEXC_API_KEY', '') secret_key = os.getenv('MEXC_SECRET_KEY', '') # Initialize the exchange exchange_class = getattr(ccxt, exchange_id) exchange = exchange_class({ 'apiKey': api_key, 'secret': secret_key, 'enableRateLimit': True, }) logger.info(f"Exchange initialized with standard CCXT: {exchange_id}") return exchange except Exception as e: logger.error(f"Error initializing exchange: {e}") raise async def fetch_ohlcv_data(exchange, symbol, timeframe, limit=1000): """Fetch OHLCV data from the exchange""" logger.info(f"Fetching {limit} {timeframe} candles for {symbol} (attempt 1/3)") try: candles = await exchange.fetch_ohlcv(symbol, timeframe, limit=limit) if not candles or len(candles) == 0: logger.warning(f"No candles returned for {symbol} on {timeframe}") return None logger.info(f"Successfully fetched {len(candles)} candles") return candles except Exception as e: logger.error(f"Error fetching candle data: {e}") return None async def main(): """Main function to test live data fetching""" symbol = "ETH/USDT" timeframe = "1m" logger.info(f"Starting simplified live training test for {symbol} on {timeframe}") try: # Initialize exchange exchange = await initialize_exchange() # Fetch data every 10 seconds for i in range(5): logger.info(f"Fetch attempt {i+1}/5") candles = await fetch_ohlcv_data(exchange, symbol, timeframe) if candles: # Print the latest candle latest = candles[-1] timestamp, open_price, high, low, close, volume = latest dt = datetime.datetime.fromtimestamp(timestamp/1000).strftime('%Y-%m-%d %H:%M:%S') logger.info(f"Latest candle: Time={dt}, Open={open_price}, High={high}, Low={low}, Close={close}, Volume={volume}") # Wait 10 seconds before next fetch if i < 4: # Don't wait after the last fetch logger.info("Waiting 10 seconds before next fetch...") await asyncio.sleep(10) # Close exchange connection await exchange.close() logger.info("Exchange connection closed") except Exception as e: logger.error(f"Error in simplified live training test: {e}") import traceback logger.error(traceback.format_exc()) finally: try: await exchange.close() except: pass logger.info("Test completed") if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: logger.info("Test stopped by user") except Exception as e: logger.error(f"Error in main function: {e}") import traceback logger.error(traceback.format_exc())