import matplotlib.pyplot as plt import matplotlib.dates as mdates from io import BytesIO import pandas as pd def plot_candlestick(df): try: df = df.tail(50).copy() df['timestamp'] = pd.to_datetime(df['timestamp']) fig, ax = plt.subplots(figsize=(8, 4)) for _, row in df.iterrows(): color = 'green' if row['close'] >= row['open'] else 'red' ax.plot([row['timestamp'], row['timestamp']], [row['low'], row['high']], color='black') ax.plot([row['timestamp'], row['timestamp']], [row['open'], row['close']], color=color, linewidth=5) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) ax.xaxis.set_major_locator(mdates.AutoDateLocator()) plt.xticks(rotation=45) plt.title('Candlestick Chart (MEXC)') plt.tight_layout() buf = BytesIO() plt.savefig(buf, format='png') buf.seek(0) plt.close(fig) return buf except Exception as e: print("Chart error:", e) raise e