From 9229b87b7042dddc14ad7663e016c47d3b0e6f4a Mon Sep 17 00:00:00 2001 From: Shroominic Date: Sat, 10 Jan 2026 17:37:05 +0800 Subject: [PATCH] optimize price fetching --- routstr/payment/price.py | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/routstr/payment/price.py b/routstr/payment/price.py index 9011ce1d..ad614322 100644 --- a/routstr/payment/price.py +++ b/routstr/payment/price.py @@ -79,15 +79,29 @@ async def _fetch_btc_usd_price() -> float: """Fetch the lowest BTC/USD price from multiple exchanges.""" async with httpx.AsyncClient(timeout=30.0) as client: try: - prices = await asyncio.gather( - _kraken_btc_usd(client), - _coinbase_btc_usd(client), - _binance_btc_usdt(client), - ) - valid_prices = [price for price in prices if price is not None] + tasks = [ + asyncio.create_task(_kraken_btc_usd(client)), + asyncio.create_task(_coinbase_btc_usd(client)), + asyncio.create_task(_binance_btc_usdt(client)), + ] + valid_prices: list[float] = [] + + for future in asyncio.as_completed(tasks): + price = await future + if price is not None: + valid_prices.append(price) + + if len(valid_prices) >= 2: + break + + for task in tasks: + if not task.done(): + task.cancel() + if not valid_prices: logger.error("No valid BTC prices obtained from any exchange") raise ValueError("Unable to fetch BTC price from any exchange") + return min(valid_prices) except Exception as e: logger.error(