pymmdrza commited on
Commit
8731e23
·
verified ·
1 Parent(s): ede9de8

Create ai/service.py

Browse files
Files changed (1) hide show
  1. ai/service.py +124 -0
ai/service.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import openai
3
+ import requests
4
+ from typing import Optional
5
+ from models.market_data import MarketData
6
+ from models.suggestion import (
7
+ TradeSuggestion,
8
+ TradeDirection,
9
+ TakeProfitPoints,
10
+ RecommendationType,
11
+ )
12
+
13
+
14
+ class AIService:
15
+ def generate(
16
+ self,
17
+ symbol: str,
18
+ leverage: int,
19
+ trade_amount: float,
20
+ current_price: float,
21
+ market_data: MarketData,
22
+ provider: str,
23
+ openai_key: Optional[str] = None,
24
+ hf_token: Optional[str] = None,
25
+ ) -> Optional[TradeSuggestion]:
26
+ prompt = self._build_prompt(
27
+ symbol, leverage, trade_amount, current_price, market_data
28
+ )
29
+
30
+ try:
31
+ if provider == "OpenAI":
32
+ openai.api_key = openai_key
33
+ response = openai.ChatCompletion.create(
34
+ model="gpt-4",
35
+ messages=[
36
+ {
37
+ "role": "system",
38
+ "content": "You are an expert crypto futures trader.",
39
+ },
40
+ {"role": "user", "content": prompt},
41
+ ],
42
+ temperature=0.2,
43
+ max_tokens=600,
44
+ )
45
+ content = response["choices"][0]["message"]["content"]
46
+ else:
47
+ headers = {"Authorization": f"Bearer {hf_token}"}
48
+ body = {"inputs": prompt}
49
+ response = requests.post(
50
+ "https://api-inference.huggingface.co/models/tiiuae/falcon-7b",
51
+ headers=headers,
52
+ json=body,
53
+ )
54
+ content = response.json().get("generated_text", "")
55
+
56
+ return self._parse(content, symbol, current_price, trade_amount)
57
+ except Exception as e:
58
+ print(f"AI error: {e}")
59
+ return None
60
+
61
+ def _build_prompt(
62
+ self, symbol, leverage, trade_amount, current_price, market_data: MarketData
63
+ ):
64
+ candles = [vars(c) for c in market_data.klines]
65
+ return f"""
66
+ You are an experienced crypto futures trader. Analyze the following:
67
+ Symbol: {symbol}
68
+ Current Price: ${current_price}
69
+ Leverage: {leverage}
70
+ Trade Amount: ${trade_amount}
71
+ Candles: {json.dumps(candles, indent=2)}
72
+
73
+ Provide output JSON:
74
+ {{
75
+ "direction": "long OR short",
76
+ "entry_price": float,
77
+ "recommended_leverage": 10-75,
78
+ "take_profit": {{
79
+ "first": float,
80
+ "second": float,
81
+ "third": float
82
+ }},
83
+ "recommendation": "... one of: Recommended / Not recommended / Caution ..."
84
+ }}
85
+ """
86
+
87
+ def _parse(
88
+ self, raw: str, symbol: str, current_price: float, trade_amount: float
89
+ ) -> TradeSuggestion:
90
+ try:
91
+ raw = raw.strip()
92
+ if raw.startswith("```json"):
93
+ raw = raw[7:]
94
+ if raw.endswith("```"):
95
+ raw = raw[:-3]
96
+
97
+ data = json.loads(raw)
98
+ recommendation_map = {
99
+ "It is recommended to enter the transaction.": RecommendationType.RECOMMENDED,
100
+ "It is not recommended to enter into a transaction.": RecommendationType.NOT_RECOMMENDED,
101
+ "Entering the trade with caution": RecommendationType.CAUTIOUS,
102
+ }
103
+
104
+ take_profit = TakeProfitPoints(
105
+ first=float(data["take_profit"]["first"]),
106
+ second=float(data["take_profit"]["second"]),
107
+ third=float(data["take_profit"]["third"]),
108
+ )
109
+
110
+ return TradeSuggestion(
111
+ symbol=symbol,
112
+ direction=TradeDirection(data["direction"].lower()),
113
+ entry_price=float(data["entry_price"]),
114
+ recommended_leverage=int(data["recommended_leverage"]),
115
+ take_profit=take_profit,
116
+ recommendation=recommendation_map.get(
117
+ data["recommendation"], RecommendationType.CAUTIOUS
118
+ ),
119
+ current_price=current_price,
120
+ trade_amount=trade_amount,
121
+ )
122
+ except Exception as e:
123
+ print(f"Parse error: {e}")
124
+ return None