0vergeared commited on
Commit
79dc24a
Β·
verified Β·
1 Parent(s): 0ccdb21

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -83
app.py CHANGED
@@ -1,47 +1,40 @@
1
- import gradio as gr
2
- import requests
3
  import pandas as pd
4
- import numpy as np
5
  import matplotlib.pyplot as plt
6
  import matplotlib.dates as mdates
7
  from io import BytesIO
8
- from datetime import datetime
9
  from PIL import Image
 
10
 
11
- def get_price_data(symbol="BTCUSDT", interval="1h", limit=100):
12
- url = f"https://api.mexc.com/api/v3/klines?symbol={symbol}&interval={interval}&limit={limit}"
13
- response = requests.get(url)
14
- data = response.json()
15
- df = pd.DataFrame(data, columns=[
16
- 'timestamp', 'open', 'high', 'low', 'close', 'volume',
17
- 'close_time', 'quote_asset_volume', 'number_of_trades',
18
- 'taker_buy_base_vol', 'taker_buy_quote_vol', 'ignore'
19
- ])
20
  df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
21
- df = df[['timestamp', 'open', 'high', 'low', 'close', 'volume']].astype(float)
22
  return df
23
 
24
- def calculate_ema(df, period=20):
 
25
  return df['close'].ewm(span=period, adjust=False).mean()
26
 
 
27
  def calculate_supertrend(df, period=10, multiplier=3):
28
  hl2 = (df['high'] + df['low']) / 2
29
- atr = df['high'].rolling(period).max() - df['low'].rolling(period).min()
30
- atr = atr.rolling(period).mean()
31
- upper_band = hl2 + (multiplier * atr)
32
- lower_band = hl2 - (multiplier * atr)
33
- supertrend = [True] * len(df)
34
-
35
  for i in range(1, len(df)):
36
- if df['close'][i] > upper_band[i - 1]:
37
- supertrend[i] = True
38
- elif df['close'][i] < lower_band[i - 1]:
39
- supertrend[i] = False
40
  else:
41
- supertrend[i] = supertrend[i - 1]
42
-
43
- return pd.Series(supertrend)
44
 
 
45
  def calculate_rsi(df, period=14):
46
  delta = df['close'].diff()
47
  gain = delta.clip(lower=0)
@@ -55,71 +48,70 @@ def detect_rsi_divergence(df):
55
  df['rsi'] = calculate_rsi(df)
56
  df['bullish_div'] = False
57
  df['bearish_div'] = False
58
-
59
  for i in range(2, len(df)):
60
- if (
61
- df['close'].iloc[i] < df['close'].iloc[i - 1] < df['close'].iloc[i - 2] and
62
- df['rsi'].iloc[i] > df['rsi'].iloc[i - 1] > df['rsi'].iloc[i - 2]
63
- ):
64
  df.at[df.index[i], 'bullish_div'] = True
65
-
66
- if (
67
- df['close'].iloc[i] > df['close'].iloc[i - 1] > df['close'].iloc[i - 2] and
68
- df['rsi'].iloc[i] < df['rsi'].iloc[i - 1] < df['rsi'].iloc[i - 2]
69
- ):
70
  df.at[df.index[i], 'bearish_div'] = True
71
  return df
72
 
73
- def generate_combined_signal(df):
 
74
  df['ema_50'] = calculate_ema(df, 50)
75
  df['ema_200'] = calculate_ema(df, 200)
76
  df['supertrend'] = calculate_supertrend(df)
77
  df = detect_rsi_divergence(df)
78
 
79
  if df[['ema_50', 'ema_200']].isna().any().any():
80
- return "⚠️ Not enough data for EMAs"
81
-
82
- ema_signal = 'BULLISH' if df['ema_50'].iloc[-1] > df['ema_200'].iloc[-1] else 'BEARISH'
83
- supertrend_signal = 'BULLISH' if df['supertrend'].iloc[-1] else 'BEARISH'
84
-
85
- signal = ""
86
- if ema_signal == 'BULLISH' and supertrend_signal == 'BULLISH':
87
- signal = "πŸ”₯ STRONG BUY"
88
- elif ema_signal == 'BEARISH' and supertrend_signal == 'BEARISH':
89
- signal = "πŸ’€ STRONG SELL"
90
- elif ema_signal == supertrend_signal:
91
- signal = f"⚠️ {ema_signal}"
92
  else:
93
- signal = "πŸ€” NEUTRAL / HOLD"
94
 
95
  if df['bullish_div'].iloc[-1]:
96
- signal += " + πŸ“ˆ Bullish RSI Divergence"
97
  if df['bearish_div'].iloc[-1]:
98
- signal += " + πŸ“‰ Bearish RSI Divergence"
99
- return signal
100
 
 
101
  def plot_chart(df):
102
- df['timestamp'] = pd.to_datetime(df['timestamp'])
103
- fig, ax = plt.subplots(figsize=(10, 5))
 
 
 
104
 
105
- for i in range(len(df)):
106
- color = 'green' if df['close'].iloc[i] >= df['open'].iloc[i] else 'red'
107
- ax.plot([df['timestamp'].iloc[i]] * 2, [df['low'].iloc[i], df['high'].iloc[i]], color='black')
108
- ax.plot([df['timestamp'].iloc[i]] * 2, [df['open'].iloc[i], df['close'].iloc[i]], color=color, linewidth=5)
 
109
 
110
- ax.plot(df['timestamp'], calculate_ema(df, 50), label="EMA 50", color='blue')
111
- ax.plot(df['timestamp'], calculate_ema(df, 200), label="EMA 200", color='orange')
112
 
113
  for i in range(len(df)):
114
- if 'bullish_div' in df.columns and df['bullish_div'].iloc[i]:
115
- ax.annotate('↑', (df['timestamp'].iloc[i], df['low'].iloc[i] - 1), color='green', fontsize=12, ha='center')
116
- if 'bearish_div' in df.columns and df['bearish_div'].iloc[i]:
117
- ax.annotate('↓', (df['timestamp'].iloc[i], df['high'].iloc[i] + 1), color='red', fontsize=12, ha='center')
118
 
119
  ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
120
- ax.legend()
121
  plt.xticks(rotation=45)
122
- plt.title("MEXC Price Chart")
 
123
  plt.tight_layout()
124
 
125
  buf = BytesIO()
@@ -128,25 +120,25 @@ def plot_chart(df):
128
  plt.close(fig)
129
  return Image.open(buf)
130
 
131
- def analyze(symbol, interval):
 
132
  try:
133
- df = get_price_data(symbol.upper(), interval)
134
- signal = generate_combined_signal(df)
 
 
135
  chart = plot_chart(df)
136
  return signal, chart
137
  except Exception as e:
138
  return f"❌ Error: {e}", None
139
 
140
- symbol_input = gr.Textbox(label="Symbol", value="BTCUSDT")
141
- interval_input = gr.Dropdown(["1m", "5m", "15m", "1h", "4h", "1d"], label="Interval", value="1h")
142
 
143
- iface = gr.Interface(
144
  fn=analyze,
145
- inputs=[symbol_input, interval_input],
146
- outputs=["text", "image"],
147
- title="πŸ“Š Crypto Signal Generator",
148
- description="EMA + SuperTrend + RSI Divergence on MEXC Data"
149
- )
150
-
151
- if __name__ == "__main__":
152
- iface.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
  from PIL import Image
7
+ import gradio as gr
8
 
9
+ # Fetch OHLCV from MEXC
10
+ def fetch_ohlcv(symbol='BTC/USDT', timeframe='1h', limit=150):
11
+ exchange = ccxt.mexc()
12
+ ohlcv = exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
13
+ df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
 
 
 
 
14
  df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
 
15
  return df
16
 
17
+ # EMA calculation
18
+ def calculate_ema(df, period):
19
  return df['close'].ewm(span=period, adjust=False).mean()
20
 
21
+ # SuperTrend indicator
22
  def calculate_supertrend(df, period=10, multiplier=3):
23
  hl2 = (df['high'] + df['low']) / 2
24
+ atr = (df['high'] - df['low']).rolling(period).mean()
25
+ upper = hl2 + multiplier * atr
26
+ lower = hl2 - multiplier * atr
27
+ st = [True] * len(df)
 
 
28
  for i in range(1, len(df)):
29
+ if df['close'].iloc[i] > upper.iloc[i - 1]:
30
+ st[i] = True
31
+ elif df['close'].iloc[i] < lower.iloc[i - 1]:
32
+ st[i] = False
33
  else:
34
+ st[i] = st[i - 1]
35
+ return pd.Series(st, index=df.index)
 
36
 
37
+ # RSI + divergence detection
38
  def calculate_rsi(df, period=14):
39
  delta = df['close'].diff()
40
  gain = delta.clip(lower=0)
 
48
  df['rsi'] = calculate_rsi(df)
49
  df['bullish_div'] = False
50
  df['bearish_div'] = False
 
51
  for i in range(2, len(df)):
52
+ if (df['close'].iloc[i] < df['close'].iloc[i-1] < df['close'].iloc[i-2] and
53
+ df['rsi'].iloc[i] > df['rsi'].iloc[i-1] > df['rsi'].iloc[i-2]):
 
 
54
  df.at[df.index[i], 'bullish_div'] = True
55
+ if (df['close'].iloc[i] > df['close'].iloc[i-1] > df['close'].iloc[i-2] and
56
+ df['rsi'].iloc[i] < df['rsi'].iloc[i-1] < df['rsi'].iloc[i-2]):
 
 
 
57
  df.at[df.index[i], 'bearish_div'] = True
58
  return df
59
 
60
+ # Combined signal logic
61
+ def generate_signal(df):
62
  df['ema_50'] = calculate_ema(df, 50)
63
  df['ema_200'] = calculate_ema(df, 200)
64
  df['supertrend'] = calculate_supertrend(df)
65
  df = detect_rsi_divergence(df)
66
 
67
  if df[['ema_50', 'ema_200']].isna().any().any():
68
+ return "⚠️ Not enough data for EMA"
69
+
70
+ ema_sig = 'BULLISH' if df['ema_50'].iloc[-1] > df['ema_200'].iloc[-1] else 'BEARISH'
71
+ st_sig = 'BULLISH' if df['supertrend'].iloc[-1] else 'BEARISH'
72
+
73
+ if ema_sig == 'BULLISH' and st_sig == 'BULLISH':
74
+ label = "πŸ”₯ STRONG BUY"
75
+ elif ema_sig == 'BEARISH' and st_sig == 'BEARISH':
76
+ label = "πŸ’€ STRONG SELL"
77
+ elif ema_sig == st_sig:
78
+ label = f"⚠️ {ema_sig}"
 
79
  else:
80
+ label = "πŸ€” NEUTRAL / HOLD"
81
 
82
  if df['bullish_div'].iloc[-1]:
83
+ label += " + πŸ“ˆ Bullish RSI Divergence"
84
  if df['bearish_div'].iloc[-1]:
85
+ label += " + πŸ“‰ Bearish RSI Divergence"
86
+ return label
87
 
88
+ # Plot chart and overlays
89
  def plot_chart(df):
90
+ df = df.tail(100).copy()
91
+ df['ema_50'] = calculate_ema(df, 50)
92
+ df['ema_200'] = calculate_ema(df, 200)
93
+ df['supertrend'] = calculate_supertrend(df)
94
+ df = detect_rsi_divergence(df)
95
 
96
+ fig, ax = plt.subplots(figsize=(10, 5))
97
+ for _, row in df.iterrows():
98
+ color = 'green' if row['close'] >= row['open'] else 'red'
99
+ ax.plot([row['timestamp'], row['timestamp']], [row['low'], row['high']], color='black', linewidth=1)
100
+ ax.plot([row['timestamp'], row['timestamp']], [row['open'], row['close']], color=color, linewidth=4)
101
 
102
+ ax.plot(df['timestamp'], df['ema_50'], label='EMA 50', color='orange')
103
+ ax.plot(df['timestamp'], df['ema_200'], label='EMA 200', color='purple')
104
 
105
  for i in range(len(df)):
106
+ if df['bullish_div'].iloc[i]:
107
+ ax.annotate('↑', (df['timestamp'].iloc[i], df['low'].iloc[i] - 1), color='green', ha='center')
108
+ if df['bearish_div'].iloc[i]:
109
+ ax.annotate('↓', (df['timestamp'].iloc[i], df['high'].iloc[i] + 1), color='red', ha='center')
110
 
111
  ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
 
112
  plt.xticks(rotation=45)
113
+ ax.legend()
114
+ plt.title("Price - EMA, SuperTrend & RSI Divergence")
115
  plt.tight_layout()
116
 
117
  buf = BytesIO()
 
120
  plt.close(fig)
121
  return Image.open(buf)
122
 
123
+ # Gradio interface
124
+ def analyze(pair, timeframe):
125
  try:
126
+ df = fetch_ohlcv(pair, timeframe)
127
+ if df.empty or len(df) < 60:
128
+ return "❌ Not enough data", None
129
+ signal = generate_signal(df)
130
  chart = plot_chart(df)
131
  return signal, chart
132
  except Exception as e:
133
  return f"❌ Error: {e}", None
134
 
135
+ pairs = ['BTC/USDT', 'ETH/USDT', 'MX/USDT', 'SOL/USDT']
136
+ timeframes = ['1m', '5m', '15m', '1h', '4h']
137
 
138
+ gr.Interface(
139
  fn=analyze,
140
+ inputs=[gr.Dropdown(pairs, label="Trading Pair"), gr.Dropdown(timeframes, label="Timeframe")],
141
+ outputs=[gr.Text(label="Signal"), gr.Image(label="Chart")],
142
+ title="Crypto Signal Generator (MEXC EMA + SuperTrend + RSI Div)",
143
+ description="Select a pair and timeframe to view technical signal and chart."
144
+ ).launch()