如何用Python从无标签的Bitfinex JSON API提取指定交易对?
Got it, let's break this down. Bitfinex's /v2/tickers?symbols=ALL endpoint returns an array of arrays—no key-value labels, which can feel a bit tricky if you're used to working with labeled JSON. But it's totally manageable with Python, and I'll walk you through exactly how to do it.
First, let's recall how the API response is structured: every entry in the top-level list is a list where the first element is the trading pair symbol (like tBTCUSD or tLTCUSD). The rest of the elements are metrics like bid price, ask price, last trade price, etc.—but we'll focus on filtering the symbols first.
Step 1: Fetch the API Data
First, we'll use the requests library to pull the data. If you don't have it installed yet, run pip install requests in your terminal.
Step 2: Filter for Valid Trading Pairs
We need to keep symbols that:
- Start with
t(Bitfinex uses this prefix for spot trading pairs) - Contain no numeric characters (so we exclude pairs like
tBTCUSD0with numeric suffixes)
Here's a complete code example:
import requests # Fetch raw data from Bitfinex API response = requests.get("https://api.bitfinex.com/v2/tickers?symbols=ALL") tickers = response.json() # Filter for the trading pairs you want valid_trading_pairs = [] for ticker_entry in tickers: symbol = ticker_entry[0] # Check if symbol starts with 't' and has no digits if symbol.startswith('t') and not any(char.isdigit() for char in symbol): # Optional: Package the symbol with useful data (e.g., last trade price at index 7) valid_trading_pairs.append({ "symbol": symbol, "last_price": ticker_entry[7] }) # Print or use your filtered pairs for pair in valid_trading_pairs: print(f"Pair: {pair['symbol']} | Last Price: {pair['last_price']}")
Simplified Version (If You Only Need Symbols)
If you just want a list of the valid symbols without extra metrics, a list comprehension makes this super concise:
valid_symbols = [ ticker[0] for ticker in tickers if ticker[0].startswith('t') and not any(char.isdigit() for char in ticker[0]) ] print(valid_symbols)
Key Notes
- The
ticker_entry[0]is how we access the symbol since there are no labels—we rely on the fixed position of elements in each sub-list (Bitfinex's API docs confirm this structure is consistent). - The
any(char.isdigit()...)check ensures we only keep pairs with letters only, no numbers mixed in.
内容的提问来源于stack exchange,提问作者johnn trann

