PERDYPTO commited on
Delete reasoning_client.py
Browse files- reasoning_client.py +0 -211
reasoning_client.py
DELETED
|
@@ -1,211 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import json
|
| 3 |
-
import re
|
| 4 |
-
import time
|
| 5 |
-
|
| 6 |
-
from openai import AsyncOpenAI
|
| 7 |
-
|
| 8 |
-
from constants import (
|
| 9 |
-
REASONING_MODEL, MAX_TOKENS, TEMPERATURE, TOP_P, THINKING
|
| 10 |
-
)
|
| 11 |
-
from models import ReasoningRequest, PredictionOutput
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
class ProviderRateLimitError(RuntimeError):
|
| 15 |
-
"""Raised when a reasoning provider API key has hit its rate limit."""
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
NimRateLimitError = ProviderRateLimitError
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
SYSTEM_PROMPT = """You are an expert crypto market analyst and price predictor. You receive current price data, technical analysis and latest market news for a cryptocurrency. Synthesize all three and produce short term price predictions. You MUST respond in this exact JSON format and nothing else. No explanation before or after. No markdown. No code fences. Raw JSON only:
|
| 22 |
-
{
|
| 23 |
-
"predicted_1m": <float price>,
|
| 24 |
-
"predicted_15m": <float price>,
|
| 25 |
-
"predicted_1h": <float price>,
|
| 26 |
-
"confidence_score": <float between 0.0 and 1.0>,
|
| 27 |
-
"reasoning": "<2-3 sentences combining TA + news + price action>",
|
| 28 |
-
"ta_summary": "<one sentence TA conclusion>",
|
| 29 |
-
"news_summary": "<one sentence news conclusion>"
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
CRITICAL TIMEFRAME WEIGHTING RULES — follow these strictly:
|
| 33 |
-
|
| 34 |
-
1. Timeframe weighting is prediction-horizon dependent and must be applied separately:
|
| 35 |
-
|
| 36 |
-
For the 15 minute prediction: weight 1m timeframe signals at 60% and 1h timeframe signals at 40%. Recent short term price action is more relevant for near term moves.
|
| 37 |
-
|
| 38 |
-
For the 1 hour prediction: weight 1h timeframe signals at 70% and 1m timeframe signals at 30%. The dominant hourly trend matters more for longer horizon predictions.
|
| 39 |
-
|
| 40 |
-
Never apply the same timeframe weighting to both predictions. They must be reasoned about independently using their respective weights.
|
| 41 |
-
2. If the 1h trend is bullish and 1m shows a small dip or bearish MACD, predict mild bullish continuation. A pullback within an uptrend is normal price action not a reversal signal.
|
| 42 |
-
|
| 43 |
-
3. If the 1h trend is bearish and 1m shows a small bounce, predict mild bearish continuation. A bounce within a downtrend is not a reversal signal.
|
| 44 |
-
|
| 45 |
-
4. Oversold RSI below 28 is a bullish reversal signal. If RSI is oversold do not predict further downside — predict a bounce or neutral. Never predict strong bearish movement when RSI is oversold.
|
| 46 |
-
|
| 47 |
-
5. Overbought RSI above 72 is a bearish reversal signal. If RSI is overbought do not predict further upside — predict a pullback or neutral.
|
| 48 |
-
|
| 49 |
-
6. When confidence score is below 40% (0.40 in the JSON field) do not make strong directional predictions. Predict price staying close to current price with minor movement in the direction of the 1h trend only.
|
| 50 |
-
|
| 51 |
-
7. Neutral news sentiment means no news catalyst exists. It does not mean bearish. Do not use neutral news as a reason to predict downward movement. Only negative news should add bearish bias.
|
| 52 |
-
|
| 53 |
-
8. When your own reasoning mentions a bullish higher timeframe signal your predicted prices MUST reflect that bullish bias. Never write bullish reasoning and predict bearish prices — that is contradictory and wrong."""
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def is_rate_limit_error(exc: Exception) -> bool:
|
| 57 |
-
status_code = getattr(exc, "status_code", None)
|
| 58 |
-
response = getattr(exc, "response", None)
|
| 59 |
-
response_status = getattr(response, "status_code", None)
|
| 60 |
-
if status_code == 429 or response_status == 429:
|
| 61 |
-
return True
|
| 62 |
-
|
| 63 |
-
message = str(exc).lower()
|
| 64 |
-
return (
|
| 65 |
-
"too many requests" in message
|
| 66 |
-
or "rate limit" in message
|
| 67 |
-
or "error code: 429" in message
|
| 68 |
-
or "status': 429" in message
|
| 69 |
-
or '"status": 429' in message
|
| 70 |
-
)
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def _build_user_message(req: ReasoningRequest) -> str:
|
| 74 |
-
ta = req.ta_result
|
| 75 |
-
news = req.news_summary
|
| 76 |
-
higher_tf_text = ""
|
| 77 |
-
if ta.higher_tf_trend:
|
| 78 |
-
higher_tf_text = f"""
|
| 79 |
-
Higher Timeframe TA (100 x 1h candles, about 4 days):
|
| 80 |
-
1H Trend: {ta.higher_tf_trend}
|
| 81 |
-
1H Confidence: {ta.higher_tf_confidence}
|
| 82 |
-
1H RSI Signal: {ta.higher_tf_rsi_signal}
|
| 83 |
-
1H MACD Direction: {ta.higher_tf_macd_signal_dir}
|
| 84 |
-
1H Bollinger Band Position: {ta.higher_tf_price_vs_bb}
|
| 85 |
-
"""
|
| 86 |
-
raw_candle_text = f"""
|
| 87 |
-
RAW CANDLE CONTEXT:
|
| 88 |
-
Recent 1m candles (last {len(req.raw_candles_1m)}; compact OHLCV):
|
| 89 |
-
{_format_candle_context(req.raw_candles_1m)}
|
| 90 |
-
|
| 91 |
-
Recent 1h candles (last {len(req.raw_candles_1h)}; compact OHLCV):
|
| 92 |
-
{_format_candle_context(req.raw_candles_1h)}
|
| 93 |
-
"""
|
| 94 |
-
return f"""COIN: {req.symbol} ({req.name})
|
| 95 |
-
CURRENT PRICE: {req.current_price}
|
| 96 |
-
24H CHANGE: {req.price_change_24h}%
|
| 97 |
-
24H VOLUME: {req.volume_24h}
|
| 98 |
-
|
| 99 |
-
SHORT-TERM TECHNICAL ANALYSIS (200 x 1m candles, about 200 minutes):
|
| 100 |
-
Trend: {ta.trend}
|
| 101 |
-
TA Confidence: {ta.confidence}
|
| 102 |
-
RSI Signal: {ta.rsi_signal}
|
| 103 |
-
MACD Direction: {ta.macd_signal_dir}
|
| 104 |
-
Bollinger Band Position: {ta.price_vs_bb}
|
| 105 |
-
TA AI Reasoning: {ta.ai_reasoning}
|
| 106 |
-
TA Summary: {ta.analysis_summary}
|
| 107 |
-
{higher_tf_text}
|
| 108 |
-
{raw_candle_text}
|
| 109 |
-
|
| 110 |
-
NEWS SENTIMENT: {news.overall_sentiment}
|
| 111 |
-
Bullish Articles: {news.bullish_count}
|
| 112 |
-
Bearish Articles: {news.bearish_count}
|
| 113 |
-
Neutral Articles: {news.neutral_count}
|
| 114 |
-
News Summary: {news.summary}"""
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
def _strip_markdown(text: str) -> str:
|
| 118 |
-
"""Remove markdown code fences from response."""
|
| 119 |
-
text = text.strip()
|
| 120 |
-
text = re.sub(r'^```json\s*', '', text, flags=re.MULTILINE)
|
| 121 |
-
text = re.sub(r'^```\s*', '', text, flags=re.MULTILINE)
|
| 122 |
-
text = re.sub(r'```$', '', text, flags=re.MULTILINE)
|
| 123 |
-
return text.strip()
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
def _format_candle_context(candles) -> str:
|
| 127 |
-
if not candles:
|
| 128 |
-
return "none"
|
| 129 |
-
return "\n".join(
|
| 130 |
-
f"{c.t}: O={c.o}, H={c.h}, L={c.l}, C={c.c}, V={c.v}"
|
| 131 |
-
for c in candles
|
| 132 |
-
)
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
async def get_prediction(
|
| 136 |
-
request: ReasoningRequest,
|
| 137 |
-
client: AsyncOpenAI,
|
| 138 |
-
model: str = REASONING_MODEL,
|
| 139 |
-
provider_name: str = "NVIDIA NIM",
|
| 140 |
-
enable_thinking: bool = THINKING
|
| 141 |
-
) -> PredictionOutput:
|
| 142 |
-
"""Call a reasoning model via AsyncOpenAI streaming for structured price prediction."""
|
| 143 |
-
if not client.api_key:
|
| 144 |
-
raise ValueError(f"{provider_name} API key not configured")
|
| 145 |
-
|
| 146 |
-
user_message = _build_user_message(request)
|
| 147 |
-
start = time.time()
|
| 148 |
-
|
| 149 |
-
# Retry loop wraps entire streaming + parsing to handle mid-stream failures
|
| 150 |
-
for attempt in range(2):
|
| 151 |
-
full_response = ""
|
| 152 |
-
try:
|
| 153 |
-
completion_kwargs = {
|
| 154 |
-
"model": model,
|
| 155 |
-
"messages": [
|
| 156 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 157 |
-
{"role": "user", "content": user_message}
|
| 158 |
-
],
|
| 159 |
-
"temperature": TEMPERATURE,
|
| 160 |
-
"top_p": TOP_P,
|
| 161 |
-
"max_tokens": MAX_TOKENS,
|
| 162 |
-
"stream": True
|
| 163 |
-
}
|
| 164 |
-
if enable_thinking:
|
| 165 |
-
completion_kwargs["extra_body"] = {"chat_template_kwargs": {"thinking": THINKING}}
|
| 166 |
-
|
| 167 |
-
completion = await client.chat.completions.create(**completion_kwargs)
|
| 168 |
-
|
| 169 |
-
# Collect full stream with interruption validation
|
| 170 |
-
try:
|
| 171 |
-
async for chunk in completion:
|
| 172 |
-
if not getattr(chunk, "choices", None):
|
| 173 |
-
continue
|
| 174 |
-
delta = chunk.choices[0].delta.content
|
| 175 |
-
if delta is not None:
|
| 176 |
-
full_response += delta
|
| 177 |
-
except Exception as e:
|
| 178 |
-
if is_rate_limit_error(e):
|
| 179 |
-
raise ProviderRateLimitError(str(e)) from e
|
| 180 |
-
raise ValueError(f"Stream interrupted after {len(full_response)} chars: {e}")
|
| 181 |
-
|
| 182 |
-
# Validate non-empty response
|
| 183 |
-
if not full_response.strip():
|
| 184 |
-
raise ValueError("Empty response received from model")
|
| 185 |
-
|
| 186 |
-
# Strip markdown and validate JSON structure before parsing
|
| 187 |
-
cleaned = _strip_markdown(full_response)
|
| 188 |
-
if not cleaned.strip().startswith("{") or not cleaned.strip().endswith("}"):
|
| 189 |
-
raise ValueError(f"Incomplete JSON received: {cleaned[:200]}")
|
| 190 |
-
|
| 191 |
-
parsed = json.loads(cleaned)
|
| 192 |
-
|
| 193 |
-
elapsed_ms = int((time.time() - start) * 1000)
|
| 194 |
-
print(f"[INFO] Prediction for {request.symbol} generated by {provider_name} ({model}) in {elapsed_ms}ms")
|
| 195 |
-
|
| 196 |
-
return PredictionOutput(**parsed)
|
| 197 |
-
|
| 198 |
-
except ProviderRateLimitError:
|
| 199 |
-
raise
|
| 200 |
-
except Exception as e:
|
| 201 |
-
if is_rate_limit_error(e):
|
| 202 |
-
raise ProviderRateLimitError(str(e)) from e
|
| 203 |
-
if attempt == 1:
|
| 204 |
-
print(f"[ERROR] {provider_name} call failed after retry for {request.symbol}: {e}")
|
| 205 |
-
raise ValueError(f"All retries exhausted. Last error: {e}. Raw response: {full_response[:500]}")
|
| 206 |
-
print(f"[WARN] Attempt {attempt + 1} failed: {e}, retrying...")
|
| 207 |
-
await asyncio.sleep(0.5 * (2 ** attempt))
|
| 208 |
-
# full_response reset at start of next loop iteration
|
| 209 |
-
|
| 210 |
-
# Should not reach here
|
| 211 |
-
raise ValueError("Prediction failed: unexpected retry loop exit")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|