Riy777 commited on
Commit
4e74d88
·
verified ·
1 Parent(s): 56d514f

Create llm.py

Browse files
Files changed (1) hide show
  1. llm.py +102 -0
llm.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import ccxt
4
+ import pandas as pd
5
+ import pandas_ta as ta
6
+ from openai import OpenAI
7
+ from duckduckgo_search import DDGS
8
+
9
+ class MarketBrain:
10
+ def __init__(self):
11
+ self.client = OpenAI(
12
+ base_url="https://integrate.api.nvidia.com/v1",
13
+ api_key=os.environ.get("NVIDIA_API_KEY")
14
+ )
15
+ self.exchange = ccxt.okx()
16
+
17
+ def get_market_data(self, symbol="BTC/USDT", timeframe='1h', limit=50):
18
+ try:
19
+ ohlcv = self.exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
20
+ df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
21
+ df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
22
+
23
+ # المؤشرات الفنية
24
+ df['rsi'] = ta.rsi(df['close'], length=14)
25
+ bb = ta.bbands(df['close'], length=20)
26
+ df = pd.concat([df, bb], axis=1)
27
+ df['ema_50'] = ta.ema(df['close'], length=50)
28
+
29
+ # إرجاع آخر صف كبيانات حالية والسجل كامل للرسم
30
+ return df.iloc[-1].to_dict(), df
31
+ except Exception as e:
32
+ print(f"Error fetching market data: {e}")
33
+ return None, None
34
+
35
+ def get_news(self, symbol):
36
+ # البحث عن أخبار العملة
37
+ query = f"{symbol} crypto news analysis today"
38
+ results = []
39
+ try:
40
+ with DDGS() as ddgs:
41
+ for r in ddgs.text(query, max_results=5):
42
+ results.append(f"- {r['title']}: {r['body']}")
43
+ except Exception as e:
44
+ print(f"News scraping error: {e}")
45
+ results.append("No news available currently.")
46
+ return "\n".join(results)
47
+
48
+ def analyze_and_decide(self, symbol, current_position=None):
49
+ market_stats, df = self.get_market_data(symbol)
50
+ if not market_stats:
51
+ return {"action": "HOLD", "reason": "Data fetch error"}
52
+
53
+ news_summary = self.get_news(symbol)
54
+ price = market_stats['close']
55
+
56
+ # صياغة البرومبت
57
+ system_prompt = f"""
58
+ You are an elite crypto quantitative trader. Analyze the data below for {symbol}.
59
+
60
+ Technical Data:
61
+ - Price: {price}
62
+ - RSI (14): {market_stats.get('rsi', 50)}
63
+ - Bollinger Upper: {market_stats.get('BBU_20_2.0')}
64
+ - Bollinger Lower: {market_stats.get('BBL_20_2.0')}
65
+ - EMA 50: {market_stats.get('ema_50')}
66
+
67
+ Recent News/Sentiment:
68
+ {news_summary}
69
+
70
+ Current Status: {"WE HAVE A POSITION" if current_position else "NO POSITION"}
71
+
72
+ Task:
73
+ 1. Analyze trend, volatility, and sentiment.
74
+ 2. Decide ACTION: BUY, SELL (if we have position), or HOLD.
75
+ 3. If BUY, provide Take Profit (TP) and Stop Loss (SL).
76
+
77
+ OUTPUT MUST BE STRICT JSON ONLY:
78
+ {{
79
+ "reasoning": "short explanation",
80
+ "action": "BUY" or "SELL" or "HOLD",
81
+ "confidence": 0-100,
82
+ "tp_target": number or null,
83
+ "sl_target": number or null
84
+ }}
85
+ """
86
+
87
+ try:
88
+ completion = self.client.chat.completions.create(
89
+ model="qwen/qwen3-next-80b-a3b-thinking",
90
+ messages=[{"role": "user", "content": system_prompt}],
91
+ temperature=0.5,
92
+ max_tokens=1024,
93
+ response_format={"type": "json_object"}
94
+ )
95
+
96
+ # التعامل مع الرد (قد يكون الـ reasoning منفصل في نماذج التفكير)
97
+ response_content = completion.choices[0].message.content
98
+ return json.loads(response_content), df
99
+
100
+ except Exception as e:
101
+ print(f"LLM Error: {e}")
102
+ return {"action": "HOLD", "reason": "LLM Error"}, df