маю код який має допомагати моєму телеграм боту import aiohttp import requests import…
- User
маю код який має допомагати моєму телеграм боту
import aiohttp import requests import time from typing import Tuple, Dict
=== Simple TTL-кеш (2 хвилини)
_cache: Dict[Tuple[str, str], Tuple[float, str]] = {} TTL_SECONDS = 120
async def get_deepseek_prediction_async(symbol: str, interval: str = "4h") -> str: key = (symbol.lower(), interval) now = time.time() if key in _cache and now - _cache[key][0] < TTL_SECONDS: return _cache[key][1] url = "https://api.deepseek.io/v1/predict" payload = {"market": symbol.upper(), "interval": interval} try: async with aiohttp.ClientSession() as session: async with session.post(url, json=payload) as resp: if resp.status == 200: data = await resp.json() trend = data.get("trend", "unknown") _cache[key] = (now, trend) return trend except Exception as e: logger.error(f"DeepSeek API error: {e}") return "unknown"
async def confirm_trend(symbol: str, direction: str) -> bool: """Check if DeepSeek confirms the expected trend direction ('bullish' or 'bearish').""" interval1, interval2 = "1h", "4h" # Паралельно отримуємо два прогнози, щоб не чекати послідовно trend1, trend4 = await asyncio.gather( get_deepseek_prediction_async(symbol, interval1), get_deepseek_prediction_async(symbol, interval2) ) if direction == "bullish": return trend1 == "bullish" and trend4 == "bullish" elif direction == "bearish": return trend1 == "bearish" and trend4 == "bearish" return False
def validate_trend_with_deepseek(symbol: str) -> bool: """ Перевіряє, чи сигнал підтверджений по 1h та 4h інтервалу. """ t1 = get_deepseek_prediction(symbol, "1h") t4 = get_deepseek_prediction(symbol, "4h") return t1 == "bullish" and t4 == "bullish"
Assistant
I'll help you analyze this code for your Telegram bot. Let me break down the key components and provide some observations:
Code Overview
This is an asynchronous Python script for fetching trading trend predictions from the DeepSeek API, with a built-in caching mechanism.
Key Features
-
Caching Mechanism
- Uses a simple in-memory cache (
_cache) - Cache duration is set to 2 minutes (120 seconds)
- Prevents repeated API calls for the same symbol and interval within the TTL
- Uses a simple in-memory cache (
-
Async API Request Function
async def get_deepseek_prediction_async(symbol: str, interval: str = "4h") -> str:- Fetches trend prediction for a given symbol and time interval
- Supports async operations with
aiohttp - Returns trend as "bullish", "bearish", or "unknown"
-
Trend Confirmation Function
async def confirm_trend(symbol: str, direction: str) -> bool:- Checks trend predictions across multiple time intervals (1h and 4h)
- Uses
asyncio.gather()for parallel API calls - Validates if the trend matches the expected direction
Potential Improvements/Observations
-
There's a
loggerreferenced but not imported. You'll need to add:import logging logger = logging.getLogger(__name__) -
The
validate_trend_with_deepseek()function seems synchronous and might need updating to match the async pattern. -
Error handling is basic - consider more robust error management.
Recommended Enhancements
- Add more comprehensive error handling
- Implement more sophisticated caching (e.g., with expiration)
- Add type hints and docstrings for better code documentation
Sample Usage in Telegram Bot
async def check_trading_signal(symbol): try: is_bullish = await confirm_trend(symbol, "bullish") if is_bullish: # Send bullish signal message await bot.send_message(chat_id, f"{symbol} looks bullish!") except Exception as e: # Handle potential errors await bot.send_message(chat_id, f"Error checking trend: {e}")Would you like me to elaborate on any specific part of the code or discuss potential improvements?
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.