Spaces:
Sleeping
Sleeping
Create services/market.py
Browse files- services/market.py +36 -0
services/market.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
from typing import Dict, List, Optional, Any
|
3 |
+
from api.kucoin import KuCoinClient
|
4 |
+
from models.market_data import MarketData
|
5 |
+
|
6 |
+
|
7 |
+
class MarketService:
|
8 |
+
def __init__(self):
|
9 |
+
self.kucoin = KuCoinClient()
|
10 |
+
self.cache: Dict[str, Dict[str, Any]] = {}
|
11 |
+
|
12 |
+
def get_market_data(
|
13 |
+
self, symbol: str, granularity: int, days: int = 2
|
14 |
+
) -> MarketData:
|
15 |
+
now = int(time.time() * 1000)
|
16 |
+
before = now - (days * 86400000)
|
17 |
+
return self.kucoin.get_kline_data(
|
18 |
+
symbol, granularity, from_time=before, to_time=now
|
19 |
+
)
|
20 |
+
|
21 |
+
def get_current_price(self, symbol: str) -> float:
|
22 |
+
if symbol in self.cache and time.time() - self.cache[symbol]["timestamp"] < 10:
|
23 |
+
return self.cache[symbol]["price"]
|
24 |
+
data = self.kucoin.get_ticker(symbol)
|
25 |
+
self.cache[symbol] = {"price": float(data["price"]), "timestamp": time.time()}
|
26 |
+
return self.cache[symbol]["price"]
|
27 |
+
|
28 |
+
|
29 |
+
def get_market_data(symbol: str, timeframe: str, session) -> MarketData:
|
30 |
+
tf_map = {"15m": 15, "1h": 60, "4h": 240, "1d": 1440}
|
31 |
+
ms = MarketService()
|
32 |
+
return ms.get_market_data(symbol, tf_map.get(timeframe, 15))
|
33 |
+
|
34 |
+
|
35 |
+
def get_current_price(symbol: str, session) -> float:
|
36 |
+
return MarketService().get_current_price(symbol)
|