-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathmarket_data.py
More file actions
206 lines (171 loc) · 7.54 KB
/
Copy pathmarket_data.py
File metadata and controls
206 lines (171 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""
Market data module - Binance API integration
"""
import requests
import time
from typing import Dict, List
class MarketDataFetcher:
"""Fetch real-time market data from Binance API"""
def __init__(self):
self.binance_base_url = "https://api.binance.com/api/v3"
self.coingecko_base_url = "https://api.coingecko.com/api/v3"
# Binance symbol mapping
self.binance_symbols = {
'BTC': 'BTCUSDT',
'ETH': 'ETHUSDT',
'SOL': 'SOLUSDT',
'BNB': 'BNBUSDT',
'XRP': 'XRPUSDT',
'DOGE': 'DOGEUSDT'
}
# CoinGecko mapping for technical indicators
self.coingecko_mapping = {
'BTC': 'bitcoin',
'ETH': 'ethereum',
'SOL': 'solana',
'BNB': 'binancecoin',
'XRP': 'ripple',
'DOGE': 'dogecoin'
}
self._cache = {}
self._cache_time = {}
self._cache_duration = 5 # Cache for 5 seconds
def get_current_prices(self, coins: List[str]) -> Dict[str, float]:
"""Get current prices from Binance API"""
# Check cache
cache_key = 'prices_' + '_'.join(sorted(coins))
if cache_key in self._cache:
if time.time() - self._cache_time[cache_key] < self._cache_duration:
return self._cache[cache_key]
prices = {}
try:
# Batch fetch Binance 24h ticker data
symbols = [self.binance_symbols.get(coin) for coin in coins if coin in self.binance_symbols]
if symbols:
# Build symbols parameter
symbols_param = '[' + ','.join([f'"{s}"' for s in symbols]) + ']'
response = requests.get(
f"{self.binance_base_url}/ticker/24hr",
params={'symbols': symbols_param},
timeout=5
)
response.raise_for_status()
data = response.json()
# Parse data
for item in data:
symbol = item['symbol']
# Find corresponding coin
for coin, binance_symbol in self.binance_symbols.items():
if binance_symbol == symbol:
prices[coin] = {
'price': float(item['lastPrice']),
'change_24h': float(item['priceChangePercent'])
}
break
# Update cache
self._cache[cache_key] = prices
self._cache_time[cache_key] = time.time()
return prices
except Exception as e:
print(f"[ERROR] Binance API failed: {e}")
# Fallback to CoinGecko
return self._get_prices_from_coingecko(coins)
def _get_prices_from_coingecko(self, coins: List[str]) -> Dict[str, float]:
"""Fallback: Fetch prices from CoinGecko"""
try:
coin_ids = [self.coingecko_mapping.get(coin, coin.lower()) for coin in coins]
response = requests.get(
f"{self.coingecko_base_url}/simple/price",
params={
'ids': ','.join(coin_ids),
'vs_currencies': 'usd',
'include_24hr_change': 'true'
},
timeout=10
)
response.raise_for_status()
data = response.json()
prices = {}
for coin in coins:
coin_id = self.coingecko_mapping.get(coin, coin.lower())
if coin_id in data:
prices[coin] = {
'price': data[coin_id]['usd'],
'change_24h': data[coin_id].get('usd_24h_change', 0)
}
return prices
except Exception as e:
print(f"[ERROR] CoinGecko fallback also failed: {e}")
return {coin: {'price': 0, 'change_24h': 0} for coin in coins}
def get_market_data(self, coin: str) -> Dict:
"""Get detailed market data from CoinGecko"""
coin_id = self.coingecko_mapping.get(coin, coin.lower())
try:
response = requests.get(
f"{self.coingecko_base_url}/coins/{coin_id}",
params={'localization': 'false', 'tickers': 'false', 'community_data': 'false'},
timeout=10
)
response.raise_for_status()
data = response.json()
market_data = data.get('market_data', {})
return {
'current_price': market_data.get('current_price', {}).get('usd', 0),
'market_cap': market_data.get('market_cap', {}).get('usd', 0),
'total_volume': market_data.get('total_volume', {}).get('usd', 0),
'price_change_24h': market_data.get('price_change_percentage_24h', 0),
'price_change_7d': market_data.get('price_change_percentage_7d', 0),
'high_24h': market_data.get('high_24h', {}).get('usd', 0),
'low_24h': market_data.get('low_24h', {}).get('usd', 0),
}
except Exception as e:
print(f"[ERROR] Failed to get market data for {coin}: {e}")
return {}
def get_historical_prices(self, coin: str, days: int = 7) -> List[Dict]:
"""Get historical prices from CoinGecko"""
coin_id = self.coingecko_mapping.get(coin, coin.lower())
try:
response = requests.get(
f"{self.coingecko_base_url}/coins/{coin_id}/market_chart",
params={'vs_currency': 'usd', 'days': days},
timeout=10
)
response.raise_for_status()
data = response.json()
prices = []
for price_data in data.get('prices', []):
prices.append({
'timestamp': price_data[0],
'price': price_data[1]
})
return prices
except Exception as e:
print(f"[ERROR] Failed to get historical prices for {coin}: {e}")
return []
def calculate_technical_indicators(self, coin: str) -> Dict:
"""Calculate technical indicators"""
historical = self.get_historical_prices(coin, days=14)
if not historical or len(historical) < 14:
return {}
prices = [p['price'] for p in historical]
# Simple Moving Average
sma_7 = sum(prices[-7:]) / 7 if len(prices) >= 7 else prices[-1]
sma_14 = sum(prices[-14:]) / 14 if len(prices) >= 14 else prices[-1]
# Simple RSI calculation
changes = [prices[i] - prices[i-1] for i in range(1, len(prices))]
gains = [c if c > 0 else 0 for c in changes]
losses = [-c if c < 0 else 0 for c in changes]
avg_gain = sum(gains[-14:]) / 14 if gains else 0
avg_loss = sum(losses[-14:]) / 14 if losses else 0
if avg_loss == 0:
rsi = 100
else:
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return {
'sma_7': sma_7,
'sma_14': sma_14,
'rsi_14': rsi,
'current_price': prices[-1],
'price_change_7d': ((prices[-1] - prices[0]) / prices[0]) * 100 if prices[0] > 0 else 0
}