Download bot.py from Anoar2025/Trading: direct link, hf CLI and curl.
- Browser
- Download file 8.15 kB
-
https://huggingface.co/spaces/Anoar2025/Trading/resolve/main/bot.py
- Command line
-
hf download hf://spaces/Anoar2025/Trading/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/Anoar2025/Trading/resolve/main/bot.py
8.15 kB
| #!/usr/bin/env python3 | |
| """ | |
| ุจูุช ุชุฏุงูู ุฐูู ูุนุชู ุฏ ุญุตุฑููุง ุนูู Gemini 2.5 Flash | |
| - ูุง ูุณุชุฎุฏู ุฃู ู ุตุฏุฑ ุจูุงูุงุช ุฎุงุฑุฌู (yfinance/binance) | |
| - ูุฑุณู ุฅุดุงุฑุงุช ุฅูู ุชูููุฌุฑุงู ููุท | |
| """ | |
| import os | |
| import sys | |
| import time | |
| import json | |
| import logging | |
| import requests | |
| from datetime import datetime | |
| from typing import Dict, Optional | |
| # ==================== ุฅุนุฏุงุฏุงุช ุงููุธุงู ==================== | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s', | |
| datefmt='%H:%M:%S' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # ุงูู ูุงุชูุญ ู ู ู ุชุบูุฑุงุช ุงูุจูุฆุฉ | |
| GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "") | |
| TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "") | |
| TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "") | |
| # ูุงุฆู ุฉ ุงูุฃุตูู ุงูู ุฑุงูุจุฉ (ูู ูู ุชุนุฏูููุง) | |
| SYMBOLS = ["BTC/USD", "ETH/USD", "AAPL", "EUR/USD", "GOLD"] | |
| CHECK_INTERVAL_MINUTES = 15 | |
| # ุฑุงุจุท Gemini 2.5 Flash API (ุญุณุจ ุทูุจู) | |
| GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" | |
| # ==================== ุฃุฏูุงุช ุชูููุฌุฑุงู ==================== | |
| def send_telegram(message: str) -> bool: | |
| """ุฅุฑุณุงู ุฑุณุงูุฉ ุฅูู ููุงุฉ/ู ุฌู ูุนุฉ ุชูููุฌุฑุงู """ | |
| if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID: | |
| return False | |
| try: | |
| url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" | |
| payload = {"chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "Markdown"} | |
| resp = requests.post(url, json=payload, timeout=10) | |
| return resp.status_code == 200 | |
| except Exception as e: | |
| logger.error(f"Telegram error: {e}") | |
| return False | |
| # ==================== ู ุญุฑู ุงูุฐูุงุก ุงูุงุตุทูุงุนู (Gemini ููุท) ==================== | |
| class GeminiBrain: | |
| def __init__(self, api_key: str): | |
| self.api_key = api_key | |
| def analyze(self, symbol: str) -> Optional[Dict]: | |
| """ | |
| ูุฑุณู ุจุฑูู ุจุช ุฎุจูุฑ ุฅูู Gemini 2.5 Flash ููุนูุฏ ุงูุชุญููู. | |
| """ | |
| prompt = self._build_expert_prompt(symbol) | |
| url = f"{GEMINI_URL}?key={self.api_key}" | |
| try: | |
| payload = { | |
| "contents": [{"parts": [{"text": prompt}]}], | |
| "generationConfig": { | |
| "temperature": 0.2, | |
| "topP": 0.9, | |
| "maxOutputTokens": 400 | |
| } | |
| } | |
| response = requests.post(url, json=payload, timeout=25) | |
| if response.status_code != 200: | |
| logger.error(f"Gemini API error {response.status_code}: {response.text}") | |
| return None | |
| result = response.json() | |
| text = result['candidates'][0]['content']['parts'][0]['text'] | |
| return self._extract_json(text) | |
| except Exception as e: | |
| logger.error(f"Gemini exception: {e}") | |
| return None | |
| def _build_expert_prompt(self, symbol: str) -> str: | |
| """ | |
| ุงูุจุฑูู ุจุช ุงูุฐู ูุฌุนู Gemini ูุชุตุฑู ูู ุญูู ู ุงูู ุฎุจูุฑ. | |
| """ | |
| return f""" | |
| You are a veteran financial markets analyst with 30 years of experience in stocks, forex, and cryptocurrencies. Provide a precise trading signal for {symbol}. | |
| Follow these steps internally: | |
| 1. Determine the current live market price for {symbol} (use your latest knowledge). | |
| 2. Conduct a rapid technical analysis considering RSI, MACD, Bollinger Bands, and key support/resistance levels. | |
| 3. Assess overall market sentiment from recent financial news. | |
| 4. Based on your veteran instinct, decide whether to BUY, SELL, or HOLD. | |
| Respond with a single JSON object containing: | |
| {{ | |
| "current_price": <float, actual price>, | |
| "action": "BUY" or "SELL" or "HOLD", | |
| "confidence": <float between 0.0 and 1.0>, | |
| "reasoning": "<brief explanation in English>", | |
| "risk_level": "LOW" or "MEDIUM" or "HIGH" | |
| }} | |
| Output ONLY the JSON. No extra text. | |
| """ | |
| def _extract_json(self, text: str) -> Optional[Dict]: | |
| """ูุณุชุฎุฑุฌ JSON ู ู ุฑุฏ Gemini ุญุชู ูู ูุงู ู ุญุงุทูุง ุจูุต.""" | |
| try: | |
| start = text.find('{') | |
| end = text.rfind('}') | |
| if start != -1 and end != -1: | |
| json_str = text[start:end+1] | |
| data = json.loads(json_str) | |
| required = ['current_price', 'action', 'confidence', 'reasoning', 'risk_level'] | |
| if all(k in data for k in required): | |
| return data | |
| logger.warning(f"ุฑุฏ ุบูุฑ ุตุงูุญ: {text[:100]}...") | |
| return None | |
| except Exception as e: | |
| logger.error(f"JSON parse error: {e}") | |
| return None | |
| # ==================== ุงูุจูุช ุงูุฑุฆูุณู ==================== | |
| class TradingSignalBot: | |
| def __init__(self, gemini_key: str): | |
| self.brain = GeminiBrain(gemini_key) | |
| def process_symbol(self, symbol: str) -> Optional[Dict]: | |
| logger.info(f"ุชุญููู {symbol} ุนุจุฑ Gemini 2.5 Flash...") | |
| analysis = self.brain.analyze(symbol) | |
| if not analysis: | |
| return None | |
| # ุชุฌุงูู ุงูุฅุดุงุฑุงุช ุฐุงุช ุงูุซูุฉ ุงูู ูุฎูุถุฉ | |
| conf = analysis.get('confidence', 0) | |
| if conf < 0.6: | |
| logger.info(f"ุฅุดุงุฑุฉ {symbol} ุถุนููุฉ ({conf:.0%}) โ ุชู ุงูุชุฌุงูู.") | |
| return None | |
| # ุฅุถุงูุฉ ุทุงุจุน ุฒู ูู | |
| analysis['timestamp'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| analysis['symbol'] = symbol | |
| return analysis | |
| def format_signal(self, signal: Dict) -> str: | |
| action = signal['action'] | |
| emoji = "๐ข" if action == "BUY" else ("๐ด" if action == "SELL" else "โช") | |
| return f""" | |
| {emoji} *ุฅุดุงุฑุฉ ุชุฏุงูู - Gemini 2.5 Flash* | |
| *ุงูุฃุตู:* `{signal['symbol']}` | |
| *ุงูุณุนุฑ ุงูุญุงูู:* {signal['current_price']} | |
| *ุงูุชูุตูุฉ:* {action} | |
| *ูุณุจุฉ ุงูุซูุฉ:* {signal['confidence']:.0%} | |
| *ุงูู ุฎุงุทุฑุฉ:* {signal['risk_level']} | |
| *ุงูุชุญููู:* _{signal['reasoning']}_ | |
| โฐ {signal['timestamp']} | |
| """ | |
| def run_forever(self): | |
| logger.info("๐ ุจุฏุก ุชุดุบูู ุจูุช Gemini 2.5 Flash (ุจุฏูู ู ุตุงุฏุฑ ุฎุงุฑุฌูุฉ)") | |
| send_telegram("๐ฎ *ุจูุช Gemini 2.5 Flash ููุฏ ุงูุชุดุบูู*") | |
| while True: | |
| try: | |
| for symbol in SYMBOLS: | |
| signal = self.process_symbol(symbol) | |
| if signal: | |
| msg = self.format_signal(signal) | |
| if send_telegram(msg): | |
| logger.info(f"โ ุฅุดุงุฑุฉ {symbol} ุฃูุฑุณูุช") | |
| else: | |
| logger.error(f"ูุดู ุฅุฑุณุงู {symbol}") | |
| time.sleep(5) # ุชุฌูุจ ุชุฌุงูุฒ ุญุฏูุฏ API | |
| wait = CHECK_INTERVAL_MINUTES * 60 | |
| logger.info(f"ุงูุชุธุงุฑ {CHECK_INTERVAL_MINUTES} ุฏูููุฉ...") | |
| time.sleep(wait) | |
| except KeyboardInterrupt: | |
| logger.info("ุฅููุงู ูุฏูู") | |
| send_telegram("๐ด *ุชู ุฅููุงู ุงูุจูุช*") | |
| break | |
| except Exception as e: | |
| logger.error(f"ุฎุทุฃ ุบูุฑ ู ุชููุน: {e}") | |
| time.sleep(60) | |
| # ==================== ููุทุฉ ุงูุจุฏุงูุฉ ==================== | |
| def main(): | |
| print(""" | |
| โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| โ ๐ฎ ุจูุช ุงูุชุฏุงูู - Gemini 2.5 Flash โ | |
| โ ูุง ูุนุชู ุฏ ุนูู ุฃู ู ุตุงุฏุฑ ุฎุงุฑุฌูุฉ โ | |
| โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| """) | |
| if not GEMINI_API_KEY: | |
| logger.error("โ GEMINI_API_KEY ุบูุฑ ู ูุฌูุฏ ูู ู ุชุบูุฑุงุช ุงูุจูุฆุฉ.") | |
| sys.exit(1) | |
| bot = TradingSignalBot(GEMINI_API_KEY) | |
| bot.run_forever() | |
| if __name__ == "__main__": | |
| main() |