alianilikhaniA1 commited on
Commit
5feadff
·
verified ·
1 Parent(s): fedbdef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -80
app.py CHANGED
@@ -1,16 +1,15 @@
1
  import ccxt
2
  import pandas as pd
3
- import numpy as np
4
  import asyncio
5
  import logging
6
- from datetime import datetime
 
7
  from telegram import Bot
8
  from telegram.error import TelegramError
9
  from ta.momentum import RSIIndicator
10
  from ta.trend import EMAIndicator
11
  import config
12
 
13
- # تنظیمات لاگینگ
14
  logging.basicConfig(
15
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
16
  level=logging.INFO
@@ -19,40 +18,36 @@ logger = logging.getLogger(__name__)
19
 
20
  class LBankMonitor:
21
  def __init__(self):
 
 
 
 
 
 
 
 
22
  self.exchange = ccxt.lbank({
23
  'apiKey': config.API_CONFIG['apiKey'],
24
  'secret': config.API_CONFIG['secret'],
25
- 'enableRateLimit': True
 
26
  })
 
27
  self.bot = Bot(token=config.TELEGRAM_CONFIG['bot_token'])
 
28
  self.connected = False
29
 
30
- async def check_connection(self):
31
- try:
32
- await asyncio.to_thread(self.exchange.fetch_balance)
33
- if not self.connected:
34
- await self.send_telegram("✅ اتصال به صرافی LBank با موفقیت برقرار شد!")
35
- self.connected = True
36
- return True
37
- except Exception as e:
38
- if self.connected:
39
- await self.send_telegram(f"⚠️ اتصال قطع شد! خطا: {str(e)}")
40
- self.connected = False
41
- return False
42
-
43
  async def fetch_ohlcv(self, symbol, timeframe):
44
- try:
45
- ohlcv = await asyncio.to_thread(
46
- self.exchange.fetch_ohlcv,
47
- symbol,
48
- timeframe
49
- )
50
- df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
51
- df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
52
- return df
53
- except Exception as e:
54
- logger.error(f"Error fetching data for {symbol}: {str(e)}")
55
- return None
56
 
57
  def calculate_indicators(self, df):
58
  df['rsi'] = RSIIndicator(df['close']).rsi()
@@ -61,38 +56,40 @@ class LBankMonitor:
61
  return df
62
 
63
  async def analyze_symbol(self, symbol):
64
- signals = []
65
- for tf in config.TIMEFRAMES:
66
- df = await self.fetch_ohlcv(symbol, tf)
67
- if df is not None and len(df) > 0:
68
- df = self.calculate_indicators(df)
69
- current_close = df['close'].iloc[-1]
70
- rsi = df['rsi'].iloc[-1]
71
-
72
- # منطق پیشرفته تحلیل (نمونه)
73
- if rsi < config.THRESHOLDS['rsi_oversold']:
74
- signals.append({
75
- 'symbol': symbol,
76
- 'timeframe': tf,
77
- 'signal': 'خرید',
78
- 'confidence': 95,
79
- 'price': current_close
80
- })
81
- return signals
 
 
 
 
82
 
83
  async def send_telegram(self, message):
84
- emoji_map = {
85
- 'خرید': '🟢💰',
86
- 'فروش': '🔴📉',
87
- 'اتصال': '🌐',
88
- 'خطا': '❌'
89
- }
90
- for key, emoji in emoji_map.items():
91
- if key in message:
92
- message = f"{emoji} {message}"
93
- break
94
-
95
  try:
 
 
 
 
 
 
 
 
 
96
  await self.bot.send_message(
97
  chat_id=config.TELEGRAM_CONFIG['chat_id'],
98
  text=message,
@@ -101,34 +98,67 @@ class LBankMonitor:
101
  except TelegramError as e:
102
  logger.error(f"Telegram error: {str(e)}")
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  async def run_analysis(self):
105
  if await self.check_connection():
106
- tasks = []
107
- for symbol in config.SYMBOLS:
108
- tasks.append(self.analyze_symbol(symbol))
109
 
110
- results = await asyncio.gather(*tasks)
111
- for signals in results:
112
- for signal in signals:
113
- if signal['confidence'] >= config.THRESHOLDS['min_confidence']:
114
- message = (
115
- f"🚨 <b>سیگنال معاملاتی شناسایی شد!</b> 🚨\n\n"
116
- f"🔹 ارز: {signal['symbol']}\n"
117
- f"🔹 نوع سیگنال: {signal['signal']}\n"
118
- f"🔹 اعتبار: {signal['confidence']}%\n"
119
- f"🔹 قیمت فعلی: {signal['price']:.4f}\n"
120
- f"🔹 حد سود: {signal['price'] * 1.03:.4f}\n"
121
- f"🔹 حد ضرر: {signal['price'] * 0.97:.4f}\n"
122
- f"⏳ اعتبار سیگنال: 6 ساعت"
123
- )
124
- await self.send_telegram(message)
 
 
 
 
 
 
 
 
 
 
125
 
126
  async def main(self):
127
- await self.send_telegram("🤖 ربات مانیتورینگ LBank راه‌اندازی شد!")
128
  while True:
129
- await self.run_analysis()
130
- await asyncio.sleep(1800) # هر 30 دقیقه
 
 
 
 
 
 
 
 
131
 
132
  if __name__ == "__main__":
133
  monitor = LBankMonitor()
134
- asyncio.run(monitor.main())
 
 
 
 
1
  import ccxt
2
  import pandas as pd
 
3
  import asyncio
4
  import logging
5
+ import httpx
6
+ from tenacity import retry, wait_exponential, stop_after_attempt
7
  from telegram import Bot
8
  from telegram.error import TelegramError
9
  from ta.momentum import RSIIndicator
10
  from ta.trend import EMAIndicator
11
  import config
12
 
 
13
  logging.basicConfig(
14
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
15
  level=logging.INFO
 
18
 
19
  class LBankMonitor:
20
  def __init__(self):
21
+ self.http_client = httpx.AsyncClient(
22
+ limits=httpx.Limits(
23
+ max_connections=config.HTTP_CONFIG['max_connections'],
24
+ max_keepalive_connections=config.HTTP_CONFIG['max_keepalive']
25
+ ),
26
+ timeout=config.HTTP_CONFIG['timeout']
27
+ )
28
+
29
  self.exchange = ccxt.lbank({
30
  'apiKey': config.API_CONFIG['apiKey'],
31
  'secret': config.API_CONFIG['secret'],
32
+ 'enableRateLimit': True,
33
+ 'session': self.http_client
34
  })
35
+
36
  self.bot = Bot(token=config.TELEGRAM_CONFIG['bot_token'])
37
+ self.semaphore = asyncio.Semaphore(config.THROTTLING['max_parallel'])
38
  self.connected = False
39
 
40
+ @retry(wait=wait_exponential(multiplier=1, min=2, max=10), stop=stop_after_attempt(3))
 
 
 
 
 
 
 
 
 
 
 
 
41
  async def fetch_ohlcv(self, symbol, timeframe):
42
+ async with self.semaphore:
43
+ try:
44
+ ohlcv = await self.exchange.fetch_ohlcv(symbol, timeframe)
45
+ df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
46
+ df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
47
+ return df
48
+ except Exception as e:
49
+ logger.error(f"Error fetching {symbol} ({timeframe}): {str(e)}")
50
+ raise
 
 
 
51
 
52
  def calculate_indicators(self, df):
53
  df['rsi'] = RSIIndicator(df['close']).rsi()
 
56
  return df
57
 
58
  async def analyze_symbol(self, symbol):
59
+ try:
60
+ signals = []
61
+ for tf in config.TIMEFRAMES:
62
+ df = await self.fetch_ohlcv(symbol, tf)
63
+ if df is not None and not df.empty:
64
+ df = self.calculate_indicators(df)
65
+ current_close = df['close'].iloc[-1]
66
+ rsi = df['rsi'].iloc[-1]
67
+
68
+ # منطق پیشرفته تحلیل (نمونه)
69
+ if rsi < config.THRESHOLDS['rsi_oversold']:
70
+ signals.append({
71
+ 'symbol': symbol,
72
+ 'timeframe': tf,
73
+ 'signal': 'خرید',
74
+ 'confidence': 95,
75
+ 'price': current_close
76
+ })
77
+ return signals
78
+ except Exception as e:
79
+ logger.error(f"Analysis failed for {symbol}: {str(e)}")
80
+ return []
81
 
82
  async def send_telegram(self, message):
 
 
 
 
 
 
 
 
 
 
 
83
  try:
84
+ emojis = {
85
+ 'خرید': '🟢💰', 'فروش': '🔴📉',
86
+ 'اتصال': '🌐', 'خطا': '❌'
87
+ }
88
+ for k, v in emojis.items():
89
+ if k in message:
90
+ message = f"{v} {message}"
91
+ break
92
+
93
  await self.bot.send_message(
94
  chat_id=config.TELEGRAM_CONFIG['chat_id'],
95
  text=message,
 
98
  except TelegramError as e:
99
  logger.error(f"Telegram error: {str(e)}")
100
 
101
+ async def check_connection(self):
102
+ try:
103
+ await self.exchange.fetch_balance()
104
+ if not self.connected:
105
+ await self.send_telegram("✅ اتصال به صرافی با موفقیت برقرار شد")
106
+ self.connected = True
107
+ return True
108
+ except Exception as e:
109
+ if self.connected:
110
+ await self.send_telegram(f"⚠️ اتصال قطع شد! خطا: {str(e)}")
111
+ self.connected = False
112
+ return False
113
+
114
  async def run_analysis(self):
115
  if await self.check_connection():
116
+ symbols = config.SYMBOLS
117
+ batch_size = config.THROTTLING['batch_size']
 
118
 
119
+ for i in range(0, len(symbols), batch_size):
120
+ batch = symbols[i:i+batch_size]
121
+ tasks = [self.analyze_symbol(symbol) for symbol in batch]
122
+ results = await asyncio.gather(*tasks)
123
+
124
+ for signals in results:
125
+ for signal in signals:
126
+ if signal['confidence'] >= config.THRESHOLDS['min_confidence']:
127
+ await self.generate_signal_message(signal)
128
+
129
+ await asyncio.sleep(config.THROTTLING['delay_between_batches'])
130
+
131
+ async def generate_signal_message(self, signal):
132
+ message = (
133
+ f"🚨 <b>سیگنال معاملاتی!</b> 🚨\n\n"
134
+ f"🏷 ارز: {signal['symbol']}\n"
135
+ f"📊 تایم فریم: {signal['timeframe']}\n"
136
+ f"🔢 نوع سیگنال: {signal['signal']}\n"
137
+ f"📈 قیمت فعلی: {signal['price']:.4f}\n"
138
+ f"✅ اعتبار: {signal['confidence']}%\n"
139
+ f"🎯 حد سود: {signal['price'] * 1.03:.4f}\n"
140
+ f"🛑 حد ضرر: {signal['price'] * 0.97:.4f}\n"
141
+ f"⏳ مدت اعتبار: ۶ ساعت"
142
+ )
143
+ await self.send_telegram(message)
144
 
145
  async def main(self):
146
+ await self.send_telegram("🤖 ربات مانیتورینگ LBank فعال شد!")
147
  while True:
148
+ try:
149
+ await self.run_analysis()
150
+ await asyncio.sleep(1800)
151
+ except Exception as e:
152
+ logger.error(f"Critical error: {str(e)}")
153
+ await self.send_telegram(f"🔥 خطای سیستمی: {str(e)}")
154
+ await asyncio.sleep(60)
155
+
156
+ async def close(self):
157
+ await self.http_client.aclose()
158
 
159
  if __name__ == "__main__":
160
  monitor = LBankMonitor()
161
+ try:
162
+ asyncio.run(monitor.main())
163
+ except KeyboardInterrupt:
164
+ asyncio.run(monitor.close())