0vergeared commited on
Commit
7e6ef8d
Β·
verified Β·
1 Parent(s): 8cd849d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -10
app.py CHANGED
@@ -1,22 +1,94 @@
 
 
 
 
 
1
  import gradio as gr
2
- from data import fetch_ohlcv
3
- from indicators import generate_signal
4
- from charts import plot_candlestick
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  def analyze(pair, timeframe):
7
  try:
8
  df = fetch_ohlcv(symbol=pair, timeframe=timeframe)
9
- if df is None or df.empty:
10
- return "❌ Failed to fetch data", None
11
 
12
  signal = generate_signal(df)
13
- chart_img = plot_candlestick(df)
14
- return f"πŸ“Š Signal: {signal}", chart_img
15
-
16
  except Exception as e:
17
  return f"❌ Error: {str(e)}", None
18
 
19
- # MEXC pairs only
20
  pairs = ['BTC/USDT', 'ETH/USDT', 'MX/USDT', 'SOL/USDT']
21
  timeframes = ['1m', '5m', '15m', '1h', '4h']
22
 
@@ -31,5 +103,5 @@ gr.Interface(
31
  gr.Image(label="Candlestick Chart")
32
  ],
33
  title="🧠 Crypto Signal Generator (MEXC)",
34
- description="Generates BUY / SELL / HOLD signals using RSI + MACD indicators."
35
  ).launch()
 
1
+ import ccxt
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ import matplotlib.dates as mdates
5
+ from io import BytesIO
6
  import gradio as gr
 
 
 
7
 
8
+ # Fetch MEXC OHLCV data
9
+ def fetch_ohlcv(symbol='BTC/USDT', timeframe='1h', limit=100):
10
+ exchange = ccxt.mexc()
11
+ ohlcv = exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
12
+ df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
13
+ df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
14
+ return df
15
+
16
+ # Calculate indicators
17
+ def calculate_rsi(df, period=14):
18
+ delta = df['close'].diff()
19
+ gain = delta.clip(lower=0)
20
+ loss = -delta.clip(upper=0)
21
+
22
+ avg_gain = gain.rolling(window=period).mean()
23
+ avg_loss = loss.rolling(window=period).mean()
24
+
25
+ rs = avg_gain / avg_loss
26
+ rsi = 100 - (100 / (1 + rs))
27
+ return rsi
28
+
29
+ def calculate_macd(df):
30
+ ema12 = df['close'].ewm(span=12, adjust=False).mean()
31
+ ema26 = df['close'].ewm(span=26, adjust=False).mean()
32
+ macd = ema12 - ema26
33
+ signal = macd.ewm(span=9, adjust=False).mean()
34
+ return macd, signal
35
+
36
+ def generate_signal(df):
37
+ rsi = calculate_rsi(df)
38
+ macd, signal = calculate_macd(df)
39
+
40
+ if len(rsi) < 1 or len(macd) < 1 or len(signal) < 1:
41
+ return "Not enough data"
42
+
43
+ latest_rsi = rsi.iloc[-1]
44
+ latest_macd = macd.iloc[-1]
45
+ latest_signal = signal.iloc[-1]
46
+
47
+ if latest_rsi < 30 and latest_macd > latest_signal:
48
+ return "BUY"
49
+ elif latest_rsi > 70 and latest_macd < latest_signal:
50
+ return "SELL"
51
+ else:
52
+ return "HOLD"
53
+
54
+ # Plot candlestick chart
55
+ def plot_candlestick(df):
56
+ df = df.tail(50).copy()
57
+ df['timestamp'] = pd.to_datetime(df['timestamp'])
58
+
59
+ fig, ax = plt.subplots(figsize=(8, 4))
60
+
61
+ for _, row in df.iterrows():
62
+ color = 'green' if row['close'] >= row['open'] else 'red'
63
+ ax.plot([row['timestamp'], row['timestamp']], [row['low'], row['high']], color='black')
64
+ ax.plot([row['timestamp'], row['timestamp']], [row['open'], row['close']], color=color, linewidth=5)
65
+
66
+ ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
67
+ ax.xaxis.set_major_locator(mdates.AutoDateLocator())
68
+ plt.xticks(rotation=45)
69
+ plt.title('Candlestick Chart (MEXC)')
70
+ plt.tight_layout()
71
+
72
+ buf = BytesIO()
73
+ plt.savefig(buf, format='png')
74
+ buf.seek(0)
75
+ plt.close(fig)
76
+ return buf
77
+
78
+ # Main function
79
  def analyze(pair, timeframe):
80
  try:
81
  df = fetch_ohlcv(symbol=pair, timeframe=timeframe)
82
+ if df.empty:
83
+ return "❌ No data returned from MEXC", None
84
 
85
  signal = generate_signal(df)
86
+ chart = plot_candlestick(df)
87
+ return f"πŸ“Š Signal: {signal}", chart
 
88
  except Exception as e:
89
  return f"❌ Error: {str(e)}", None
90
 
91
+ # Gradio UI
92
  pairs = ['BTC/USDT', 'ETH/USDT', 'MX/USDT', 'SOL/USDT']
93
  timeframes = ['1m', '5m', '15m', '1h', '4h']
94
 
 
103
  gr.Image(label="Candlestick Chart")
104
  ],
105
  title="🧠 Crypto Signal Generator (MEXC)",
106
+ description="Live BUY / SELL / HOLD signals based on RSI & MACD indicators using MEXC data."
107
  ).launch()