import requests import json import websocket import time import pandas as pd import…
- User
import requests import json import websocket import time import pandas as pd import datetime
MEXC API Endpoints
MEXC_BASE_URL = "https://contract.mexc.com/api/v1/contract" MEXC_WS_URL = "wss://contract.mexc.com/edge"
Strategy parameters (example: simple moving average crossover)
SMA_SHORT_PERIOD = 5 # Short-term SMA period (5-minute candles) SMA_LONG_PERIOD = 20 # Long-term SMA period (5-minute candles)
def fetch_usdt_futures(): """Fetches all USDT perpetual futures contracts from MEXC.""" try: response = requests.get(f"{MEXC_BASE_URL}/detail") response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) data = response.json()
if data["success"]: usdt_futures = [ item["symbol"] for item in data["data"] if item["quoteCoin"] == "USDT" and item["displayNameEn"].endswith("SWAP") # Filter for USDT and Perpetual ] return usdt_futures else: print(f"Error fetching USDT futures: {data.get('message', 'Unknown error')}") return [] except requests.exceptions.RequestException as e: print(f"Error fetching USDT futures: {e}") return []def fetch_historical_data(symbol, interval="Min5", limit=100): """Fetches historical kline data for a given symbol.""" try: response = requests.get( f"{MEXC_BASE_URL}/kline/{symbol}", params={"interval": interval, "limit": limit} ) response.raise_for_status() data = response.json()
if data["success"]: df = pd.DataFrame(data["data"]) df["time"] = pd.to_datetime(df["time"], unit="s") # Convert to datetime objects return df else: print(f"Error fetching historical data for {symbol}: {data.get('message', 'Unknown error')}") return None except requests.exceptions.RequestException as e: print(f"Error fetching historical data for {symbol}: {e}") return Nonedef on_message(ws, message): """Handles incoming websocket messages.""" data = json.loads(message) if data.get("channel") == "push.kline": candle_data = data["data"] symbol = candle_data["symbol"]
# Fetch historical data (consider caching for efficiency) historical_data = fetch_historical_data(symbol, interval="Min5", limit=100) # Or retrieve from cache if historical_data is None: # Handle potential errors return # Convert the incoming candle data to a DataFrame and append it to the historical data: new_candle_df = pd.DataFrame([candle_data]) new_candle_df['time'] = pd.to_datetime(new_candle_df['t'], unit='s') historical_data = pd.concat([historical_data, new_candle_df], ignore_index=True) historical_data = historical_data.tail(100) # Keep only the last 100 # Calculate SMAs historical_data["SMA_short"] = historical_data["c"].rolling(window=SMA_SHORT_PERIOD).mean() historical_data["SMA_long"] = historical_data["c"].rolling(window=SMA_LONG_PERIOD).mean() # Generate signals (example SMA crossover) if ( historical_data["SMA_short"].iloc[-2] < historical_data["SMA_long"].iloc[-2] # Previous candle and historical_data["SMA_short"].iloc[-1] > historical_data["SMA_long"].iloc[-1] # Current candle ): print(f"BUY signal for {symbol} at price {candle_data['c']}") # Using closing price elif ( historical_data["SMA_short"].iloc[-2] > historical_data["SMA_long"].iloc[-2] # Previous candle and historical_data["SMA_short"].iloc[-1] < historical_data["SMA_long"].iloc[-1] # Current candle ): print(f"SELL signal for {symbol} at price {candle_data['c']}") # Using closing pricedef on_error(ws, error): """Handles websocket errors.""" print(f"Websocket error: {error}")
def on_close(ws, close_status_code, close_msg): """Handles websocket close events.""" print("Websocket connection closed")
def on_open(ws): """Handles websocket open events.""" print("Websocket connection opened")
usdt_futures = fetch_usdt_futures() if usdt_futures: for symbol in usdt_futures: subscribe_message = { "method": "sub.kline", "param": {"symbol": symbol, "interval": "Min5"}, } ws.send(json.dumps(subscribe_message))def main(): """Main function to run the bot.""" ws = websocket.WebSocketApp( MEXC_WS_URL, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close, )
# Keep the websocket connection alive while True: try: ws.run_forever() except Exception as e: # Catch general exceptions to prevent the bot from crashing print(f"An error occurred: {e}") time.sleep(10) # Reconnect after 10 seconds finally: ws.close() # Close the existing connection before retryingif name == "main": main()
- Assistant
Your script demonstrates a trading bot for the MEXC exchange using the REST API and WebSocket for real-time updates. Below are suggestions for improvements or fixes, tailored guidance, debugging pointers, and code highlights to help make your bot more robust and functional.
Highlights of Your Code
-
Dynamic Fetching of Futures Contracts (
fetch_usdt_futures):- Retrieves a list of USDT perpetual contracts dynamically instead of hardcoding, meaning the bot can adapt to changes in available trading pairs.
-
Historical Data Integration (
fetch_historical_data):- Pulls historical candlestick (kline) data for technical analysis, ensuring context when new live candles arrive via WebSocket.
-
SMA Crossover Strategy:
- Utilizes short-term and long-term Simple Moving Averages (SMA) to generate buy/sell signals upon crossovers.
-
WebSocket Subscription Management:
- Subscribes to real-time kline updates for multiple symbols automatically and processes incoming data.
-
Error Handling:
- Covers exception handling for both HTTP request failures and WebSocket connection failures to improve resiliency.
Potential Issues & Improvements
1. Historical Data Overlap
- The API-retrieved
historical_datamight overlap with the candle received in the WebSocket message. This could result in the same data being processed twice. - Solution:
Filter out overlapping timestamps before combining
historical_datawith the new candle:historical_data = historical_data[historical_data['time'] < new_candle_df['time'].iloc[0]] historical_data = pd.concat([historical_data, new_candle_df], ignore_index=True)
2. Data Types for Calculations
- The DataFrame columns (e.g.,
cfor closing prices) may come in as strings depending on the API. Calculations likerollingrequire numeric data. - Solution:
Ensure data is converted to the appropriate type:
df['c'] = pd.to_numeric(df['c'], errors='coerce')
3. Rate Limits
- Frequent API calls via
fetch_historical_datafor every WebSocket message may hit exchange rate limits. - Solution:
Cache historical data for each symbol and update dynamically:
Use the cached results instead:historical_cache = {} def fetch_historical_data_cached(symbol, interval="Min5", limit=100): if symbol not in historical_cache: historical_cache[symbol] = fetch_historical_data(symbol, interval, limit) return historical_cache[symbol]historical_data = fetch_historical_data_cached(symbol, interval="Min5", limit=100)
4. WebSocket Connectivity
- The
ws.run_foreverloop is prone to unresponsiveness or disconnection. Without a ping/pong mechanism, the connection may silently disconnect. - Solution:
Implement WebSocket pinging to maintain the connection:
ws = websocket.WebSocketApp( MEXC_WS_URL, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close, ) ws.run_forever(ping_interval=30) # Send a ping every 30 seconds
5. Handling Symbol Errors
- If one symbol's data fetch fails (e.g., unavailable or invalid symbol), it may terminate processing for other valid symbols.
- Solution:
Process valid symbols even if one fails, and log problematic symbols for debugging:
for symbol in usdt_futures: try: subscribe_message = { "method": "sub.kline", "param": {"symbol": symbol, "interval": "Min5"}, } ws.send(json.dumps(subscribe_message)) except Exception as e: print(f"Failed to subscribe to {symbol}: {e}")
6. Debugging Signal Conditions
- There’s no provision for validating the "last-but-one" (
iloc[-2]) and "current" candles (iloc[-1]) indices; errors may arise if the DataFrame is too small. - Solution:
Check the length of the DataFrame before trying to compute the SMA signals:
if len(historical_data) >= SMA_LONG_PERIOD: # Compute SMAs and generate signals...
Additional Enhancements
1. Log Trading Signals
- Save trade signals (BUY/SELL) to a log file for later evaluation and backtesting:
def log_signal(signal_type, symbol, price): timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open("signals_log.txt", "a") as log_file: log_file.write(f"{timestamp}, {signal_type}, {symbol}, {price}\n")
2. Parameter Configuration
- Use a configuration file (e.g.,
config.json) to store constants likeSMA_SHORT_PERIOD,SMA_LONG_PERIOD, etc., for flexibility:import json with open("config.json", "r") as config_file: config = json.load(config_file) SMA_SHORT_PERIOD = config["SMA_SHORT_PERIOD"] SMA_LONG_PERIOD = config["SMA_LONG_PERIOD"]
3. Threading/Async
- Move WebSocket and API calls to separate threads or use asyncio to parallelize tasks efficiently.
Final Thoughts
Your trading bot is a solid implementation of a real-time SMA crossover strategy. By addressing potential pitfalls like rate limits, connection stability, and data management, you can make the bot more robust and scalable. Consider integrating further enhancements like risk management (e.g., stop-loss limits) or automation of trade execution via the API.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.