From b077c9335131972f8d73226eed3c762db471fbb8 Mon Sep 17 00:00:00 2001 From: counterweight Date: Mon, 22 Dec 2025 15:42:59 +0100 Subject: [PATCH] feat: add Bitfinex price fetcher for BTC/EUR --- backend/price_fetcher.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 backend/price_fetcher.py diff --git a/backend/price_fetcher.py b/backend/price_fetcher.py new file mode 100644 index 0000000..954e6a3 --- /dev/null +++ b/backend/price_fetcher.py @@ -0,0 +1,38 @@ +"""Bitfinex price fetcher for BTC/EUR pair.""" + +from datetime import UTC, datetime + +import httpx + +BITFINEX_TICKER_URL = "https://api-pub.bitfinex.com/v2/ticker/tBTCEUR" +LAST_PRICE_INDEX = 6 + + +async def fetch_btc_eur_price() -> tuple[float, datetime]: + """ + Fetch the current BTC/EUR price from Bitfinex. + + Returns: + Tuple of (price, timestamp) where timestamp is the current UTC time. + + Raises: + httpx.HTTPStatusError: If the API returns a non-2xx status code. + httpx.RequestError: If a network error occurs. + ValueError: If the response format is unexpected. + """ + async with httpx.AsyncClient() as client: + response = await client.get(BITFINEX_TICKER_URL) + response.raise_for_status() + + data = response.json() + + # Bitfinex ticker response is an array: + # [BID, BID_SIZE, ASK, ASK_SIZE, DAILY_CHANGE, DAILY_CHANGE_RELATIVE, + # LAST_PRICE, VOLUME, HIGH, LOW] + if not isinstance(data, list) or len(data) <= LAST_PRICE_INDEX: + raise ValueError(f"Unexpected response format: {data}") + + price = float(data[LAST_PRICE_INDEX]) + timestamp = datetime.now(UTC) + + return price, timestamp