Spaces:
Sleeping
Sleeping
Update ai/service.py
Browse files- ai/service.py +91 -81
ai/service.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import json
|
| 2 |
import openai
|
| 3 |
import requests
|
| 4 |
-
from
|
| 5 |
from models.market_data import MarketData
|
| 6 |
from models.suggestion import (
|
| 7 |
TradeSuggestion,
|
|
@@ -12,113 +12,123 @@ from models.suggestion import (
|
|
| 12 |
|
| 13 |
|
| 14 |
class AIService:
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
symbol:
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
return f"""
|
| 66 |
-
You are an
|
| 67 |
-
|
| 68 |
Current Price: ${current_price}
|
| 69 |
-
Leverage: {leverage}
|
| 70 |
-
|
| 71 |
-
Candles: {json.dumps(candles, indent=2)}
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
| 74 |
{{
|
| 75 |
-
"direction": "long
|
| 76 |
"entry_price": float,
|
| 77 |
-
"recommended_leverage": 10-75,
|
| 78 |
"take_profit": {{
|
| 79 |
"first": float,
|
| 80 |
"second": float,
|
| 81 |
"third": float
|
| 82 |
}},
|
| 83 |
-
"recommendation": "
|
| 84 |
}}
|
| 85 |
-
|
| 86 |
|
| 87 |
-
def
|
| 88 |
-
self,
|
| 89 |
-
)
|
| 90 |
try:
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
|
| 97 |
-
|
| 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"]
|
| 113 |
entry_price=float(data["entry_price"]),
|
| 114 |
recommended_leverage=int(data["recommended_leverage"]),
|
| 115 |
-
take_profit=take_profit,
|
| 116 |
-
recommendation=
|
| 117 |
data["recommendation"], RecommendationType.CAUTIOUS
|
| 118 |
),
|
| 119 |
current_price=current_price,
|
| 120 |
trade_amount=trade_amount,
|
| 121 |
)
|
| 122 |
except Exception as e:
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import openai
|
| 3 |
import requests
|
| 4 |
+
from pydantic import ValidationError
|
| 5 |
from models.market_data import MarketData
|
| 6 |
from models.suggestion import (
|
| 7 |
TradeSuggestion,
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
class AIService:
|
| 15 |
+
@staticmethod
|
| 16 |
+
def _prepare_prompt(
|
| 17 |
+
symbol, leverage, trade_amount, market_data: MarketData, current_price: float
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
):
|
| 19 |
+
klines = [
|
| 20 |
+
{
|
| 21 |
+
"timestamp": k.timestamp,
|
| 22 |
+
"open": k.open,
|
| 23 |
+
"high": k.high,
|
| 24 |
+
"low": k.low,
|
| 25 |
+
"close": k.close,
|
| 26 |
+
"volume": k.volume,
|
| 27 |
+
}
|
| 28 |
+
for k in market_data.klines
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
return f"""
|
| 32 |
+
You are an expert crypto futures trader. Based on market data, suggest a trade for {symbol}.
|
| 33 |
+
|
| 34 |
Current Price: ${current_price}
|
| 35 |
+
Leverage: {leverage}x
|
| 36 |
+
Amount: ${trade_amount}
|
|
|
|
| 37 |
|
| 38 |
+
Market Data:
|
| 39 |
+
{json.dumps(klines, indent=2)}
|
| 40 |
+
|
| 41 |
+
Only return valid JSON:
|
| 42 |
{{
|
| 43 |
+
"direction": "long" or "short",
|
| 44 |
"entry_price": float,
|
| 45 |
+
"recommended_leverage": int (10-75),
|
| 46 |
"take_profit": {{
|
| 47 |
"first": float,
|
| 48 |
"second": float,
|
| 49 |
"third": float
|
| 50 |
}},
|
| 51 |
+
"recommendation": "It is recommended to enter the transaction." or "It is not recommended to enter into a transaction." or "Entering the trade with caution"
|
| 52 |
}}
|
| 53 |
+
"""
|
| 54 |
|
| 55 |
+
def _parse_response(
|
| 56 |
+
self, response: str, symbol: str, current_price: float, trade_amount: float
|
| 57 |
+
):
|
| 58 |
try:
|
| 59 |
+
if response.startswith("```json"):
|
| 60 |
+
response = response[7:]
|
| 61 |
+
if response.endswith("```"):
|
| 62 |
+
response = response[:-3]
|
| 63 |
+
data = json.loads(response)
|
| 64 |
|
| 65 |
+
rec_map = {
|
|
|
|
| 66 |
"It is recommended to enter the transaction.": RecommendationType.RECOMMENDED,
|
| 67 |
"It is not recommended to enter into a transaction.": RecommendationType.NOT_RECOMMENDED,
|
| 68 |
"Entering the trade with caution": RecommendationType.CAUTIOUS,
|
| 69 |
}
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
return TradeSuggestion(
|
| 72 |
symbol=symbol,
|
| 73 |
+
direction=TradeDirection(data["direction"]),
|
| 74 |
entry_price=float(data["entry_price"]),
|
| 75 |
recommended_leverage=int(data["recommended_leverage"]),
|
| 76 |
+
take_profit=TakeProfitPoints(**data["take_profit"]),
|
| 77 |
+
recommendation=rec_map.get(
|
| 78 |
data["recommendation"], RecommendationType.CAUTIOUS
|
| 79 |
),
|
| 80 |
current_price=current_price,
|
| 81 |
trade_amount=trade_amount,
|
| 82 |
)
|
| 83 |
except Exception as e:
|
| 84 |
+
raise ValueError(f"Failed to parse AI response: {e}\nRaw: {response}")
|
| 85 |
+
|
| 86 |
+
def generate(
|
| 87 |
+
self,
|
| 88 |
+
symbol,
|
| 89 |
+
leverage,
|
| 90 |
+
trade_amount,
|
| 91 |
+
market_data,
|
| 92 |
+
current_price,
|
| 93 |
+
provider,
|
| 94 |
+
openai_key,
|
| 95 |
+
hf_token,
|
| 96 |
+
):
|
| 97 |
+
prompt = self._prepare_prompt(
|
| 98 |
+
symbol, leverage, trade_amount, market_data, current_price
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
if provider == "OpenAI":
|
| 102 |
+
openai.api_key = openai_key
|
| 103 |
+
try:
|
| 104 |
+
res = openai.ChatCompletion.create(
|
| 105 |
+
model="gpt-3.5-turbo",
|
| 106 |
+
messages=[
|
| 107 |
+
{
|
| 108 |
+
"role": "system",
|
| 109 |
+
"content": "You are a crypto trading expert.",
|
| 110 |
+
},
|
| 111 |
+
{"role": "user", "content": prompt},
|
| 112 |
+
],
|
| 113 |
+
temperature=0.2,
|
| 114 |
+
)
|
| 115 |
+
content = res.choices[0].message.content
|
| 116 |
+
return self._parse_response(
|
| 117 |
+
content, symbol, current_price, trade_amount
|
| 118 |
+
)
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"OpenAI Error: {e}")
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
elif provider == "HuggingFace":
|
| 124 |
+
try:
|
| 125 |
+
headers = {"Authorization": f"Bearer {hf_token}"}
|
| 126 |
+
data = {"inputs": prompt}
|
| 127 |
+
url = "https://api-inference.huggingface.co/models/tiiuae/falcon-7b"
|
| 128 |
+
res = requests.post(url, headers=headers, json=data)
|
| 129 |
+
response = res.json()
|
| 130 |
+
text = response[0]["generated_text"]
|
| 131 |
+
return self._parse_response(text, symbol, current_price, trade_amount)
|
| 132 |
+
except Exception as e:
|
| 133 |
+
print(f"HuggingFace Error: {e}")
|
| 134 |
+
return None
|