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,
)
import requests
import json
import websocket
import time
import pandas as pd
# MEXC API Endpoints
MEXC_BASE_URL = "https://contract.mexc.com/api/v1/contract"
MEXC_WS_URL = "wss://contract.mexc.com/edge"
# Strategy parameters
SMA_SHORT_PERIOD = 5 # Short-term SMA period (5-minute candles)
SMA_LONG_PERIOD = 20 # Long-term SMA period (5-minute candles)
# Global cache for historical data
historical_data_cache = {}
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()
data = response.json()
if data["success"]:
usdt_futures = [
item["symbol"]
for item in data["data"]
if item["quoteCoin"] == "USDT" and item["displayNameEn"].endswith("SWAP")
]
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.rename(columns={
't': 'time',
'o': 'open',
'c': 'close',
'h': 'high',
'l': 'low',
'v': 'volume',
}, inplace=True)
df["time"] = pd.to_datetime(df["time"], unit="s")
df[['open', 'high', 'low', 'close', 'volume']] = df[['open', 'high', 'low', 'close', 'volume']].astype(float)
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 None
def 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"]
# Retrieve historical data from cache
historical_data = historical_data_cache.get(symbol)
if historical_data is None:
print(f"No historical data for {symbol}")
return
# Convert the incoming candle data to a DataFrame
new_candle_df = pd.DataFrame([{
'time': pd.to_datetime(candle_data['t'], unit='s'),
'open': float(candle_data['o']),
'high': float(candle_data['h']),
'low': float(candle_data['l']),
'close': float(candle_data['c']),
'volume': float(candle_data['v'])
}])
# Append and keep only the last 100 entries
historical_data = pd.concat([historical_data, new_candle_df], ignore_index=True)
historical_data = historical_data.tail(100)
historical_data.reset_index(drop=True, inplace=True)
# Update the cached data
historical_data_cache[symbol] = historical_data
# Calculate SMAs
if len(historical_data) >= SMA_LONG_PERIOD:
historical_data["SMA_short"] = historical_data["close"].rolling(window=SMA_SHORT_PERIOD).mean()
historical_data["SMA_long"] = historical_data["close"].rolling(window=SMA_LONG_PERIOD).mean()
# Avoid errors if SMAs have NaN values
if pd.notna(historical_data["SMA_short"].iloc[-2]) and pd.notna(historical_data["SMA_long"].iloc[-2]):
prev_short = historical_data["SMA_short"].iloc[-2]
prev_long = historical_data["SMA_long"].iloc[-2]
curr_short = historical_data["SMA_short"].iloc[-1]
curr_long = historical_data["SMA_long"].iloc[-1]
# Generate signals
if prev_short < prev_long and curr_short > curr_long:
print(f"BUY signal for {symbol} at price {candle_data['c']}")
elif prev_short > prev_long and curr_short < curr_long:
print(f"SELL signal for {symbol} at price {candle_data['c']}")
else:
print(f"Not enough data to calculate SMAs for {symbol}")
def 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:
# Fetch and store historical data
historical_data = fetch_historical_data(symbol, interval="Min5", limit=100)
if historical_data is not None:
historical_data_cache[symbol] = historical_data
else:
print(f"Failed to fetch historical data for {symbol}")
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,
)
while True:
try:
ws.run_forever(
ping_interval=60,
ping_timeout=10,
reconnect=5
)
except KeyboardInterrupt:
print("Program interrupted by user")
ws.close()
break
except Exception as e:
print(f"An error occurred: {e}")
time.sleep(5)
if __name__ == "__main__":
main()