Я хочу написать скрипт на python, который будет получать данные о волатильности о объёмах торгов для конкретных монет на разных криптобиржах, я написал две функции, но данные которые они выдают очень неточные. Может быть можно каким-нибудь другим способом получить эти данные?
Вот что получилось у меня:
async def get_volatility(exchange_id, coins):
exchange_class = getattr(ccxt, exchange_id)
exchange = exchange_class()
await exchange.load_markets()
symbols = exchange.symbols
volatilities = {}
since = exchange.milliseconds() - 60 * 60 * 1000 # последний час
for coin in coins:
symbol = next((s for s in symbols if coin in s and 'USDT' in s), None)
if symbol is None:
logger.error(f"{exchange_id} does not have market symbol {coin}/USDT")
volatilities[coin] = 0
continue
try:
ohlcv = await exchange.fetch_ohlcv(symbol, '30m', since)
prices = [candle[4] for candle in ohlcv]
if prices:
avg_price = np.mean(prices, dtype=np.float64)
std_dev = np.std(prices, dtype=np.float64)
volatility = (std_dev / avg_price) * 100
else:
volatility = 0
logger.info(f"Volatility for {coin} on {exchange_id}: {volatility:.2f}%")
volatilities[coin] = volatility
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
logger.error(f"Error fetching OHLCV for volatility calculation for {coin} on {exchange_id}: {e}")
volatilities[coin] = 0
await exchange.close()
return volatilities
async def fetch_trade_volumes(exchange_id, coins):
logger.info(f"Fetching trade volumes for {coins} on {exchange_id}")
exchange_class = getattr(ccxt, exchange_id)
exchange = exchange_class()
await exchange.load_markets()
symbols = exchange.symbols
trade_volumes = {}
since = exchange.milliseconds() - 30 * 60 * 1000 # последние 30 минут
for coin in coins:
symbol = next((s for s in symbols if coin in s and 'USDT' in s), None)
if symbol is None:
logger.error(f"{exchange_id} does not have market symbol {coin}/USDT")
trade_volumes[coin] = 0
continue
logger.info(f"Fetching OHLCV data for {symbol} on {exchange_id} since {since}")
try:
ohlcv = await exchange.fetch_ohlcv(symbol, '1m', since)
if not ohlcv:
logger.warning(f"No OHLCV data returned for {symbol} on {exchange_id}")
trade_volumes[coin] = 0
continue
volumes = [candle[5] for candle in ohlcv if candle[5] is not None]
close_prices = [candle[4] for candle in ohlcv if candle[4] is not None]
if not volumes or not close_prices:
logger.warning(f"No valid volumes or close prices in OHLCV data for {symbol} on {exchange_id}")
trade_volumes[coin] = 0
continue
trade_volume = sum(volume * price for volume, price in zip(volumes, close_prices))
logger.info(f"Calculated trade volume for {symbol} on {exchange_id}: {trade_volume}")
trade_volumes[coin] = trade_volume
except (NetworkError, ExchangeError) as e:
logger.error(f"Error fetching OHLCV for trade volume calculation for {coin} on {exchange_id}: {e}")
trade_volumes[coin] = 0
await exchange.close()
return trade_volumes