Cryptocurrency trading relies heavily on real-time price data. This guide demonstrates how to fetch live cryptocurrency prices using HTTP APIs and WebSocket subscriptions, focusing on BTC/USD (Bitcoin to USD) as an example.
Method 1: HTTP API for Real-Time Price Fetching
Step-by-Step Implementation
import requests
# API Configuration
headers = {'Content-Type': 'application/json'}
api_url = 'https://quote.aatest.online/quote-b-api/kline?token=YOUR_TOKEN&query=ENCODED_QUERY'
# Fetch BTC/USD price
response = requests.get(api_url, headers=headers)
price_data = response.json()
print(price_data)Key Parameters:
- Token: Replace
YOUR_TOKENwith your API key from Alltick. Query: URL-encoded JSON specifying:
{ "code": "BTCUSD", "kline_type": 1, "query_kline_num": 1 }
Advantages:
- Simple HTTP GET request.
- Suitable for one-time price checks.
Method 2: WebSocket for Continuous Price Updates
WebSocket Subscription Code
import websocket
import json
class CryptoPriceFeed:
def __init__(self):
self.ws_url = 'wss://quote.tradeswitcher.com/quote-b-ws-api?token=YOUR_TOKEN'
def on_message(self, ws, message):
data = json.loads(message)
print(f"BTC/USD Price Update: {data}")
def start_feed(self):
ws = websocket.WebSocketApp(
self.ws_url,
on_message=self.on_message
)
ws.run_forever()
# Usage
feed = CryptoPriceFeed()
feed.start_feed()Subscription Payload:
{
"cmd_id": 22002,
"data": {
"symbol_list": [{"code": "BTCUSD", "depth_level": 5}]
}
}Benefits:
- Real-time streaming data.
- Low latency (ideal for trading bots).
Core Keywords
- Cryptocurrency API
- Real-Time Price Data
- BTC/USD
- WebSocket Subscription
- HTTP API Integration
- Market Data Fetching
FAQ Section
Q1: How often should I refresh HTTP API data?
For active trading, poll every 1–5 seconds. For analytics, hourly updates may suffice.
Q2: Is WebSocket better than HTTP for crypto prices?
👉 Yes, WebSockets provide lower latency and continuous updates, critical for high-frequency trading.
Q3: How do I secure my API token?
Never expose tokens in client-side code. Use environment variables or server-side proxies.
Q4: Can I query historical prices with these APIs?
Some providers offer historical endpoints. Check documentation for kline_timestamp_end parameters.
Pro Tips
- Rate Limits: Monitor API quotas to avoid bans.
- Data Parsing: Use libraries like
pandasfor complex data analysis. - Fallback Plans: Implement HTTP retries if WebSocket disconnects.
👉 Explore advanced trading strategies with real-time data.
Note: Always comply with your API provider’s terms of service. Remove promotional links before production use.