lets apply this requirement to my code:
Sequence numbers: We must check each order's previous and current ID to ensure the integrity of the order book data we receive from the exchange. If there is any inconsistency, we need to request a data snapshot and update the order book data so it is in the correct order.
Timestamp synchronization: We need to verify the timestamps to ensure there are no inconsistencies or interruptions in the data stream. This will help us detect any timing discrepancies between the order book updates and the actual market events.
Once we have the data recorder and data integrity check system in place, we can focus on developing a logging system. This system will allow us to identify any errors detected in the data streams and recordings.
CODE : # collector.py
import yaml
import threading
import time
from redis_client import RedisClient
from exchanges import handle_binance, handle_bitstamp
def load_config(config_path='config.yaml'):
with open(config_path, 'r') as file:
return yaml.safe_load(file)
def main():
config = load_config()
code
# Initialize Redis client
redis_conf = config['redis']
redis_client = RedisClient(
host=redis_conf.get('host', 'localhost'),
port=redis_conf.get('port', 6379),
db=redis_conf.get('db', 0)
)
# Define threads for each exchange
threads = []
universal_symbols = config['symbols']
symbol_mappings = config.get('symbol_mappings', {})
if 'binance' in config['exchanges']:
binance_config = config['exchanges']['binance']
binance_symbols = [
symbol_mappings['binance'][sym] for sym in universal_symbols
if sym in symbol_mappings['binance']
]
thread_binance = threading.Thread(
target=handle_binance,
args=(redis_client, binance_symbols, binance_config)
)
threads.append(thread_binance)
if 'bitstamp' in config['exchanges']:
bitstamp_config = config['exchanges']['bitstamp']
bitstamp_symbols = [
symbol_mappings['bitstamp'][sym] for sym in universal_symbols
if sym in symbol_mappings['bitstamp']
]
thread_bitstamp = threading.Thread(
target=handle_bitstamp,
args=(redis_client, bitstamp_symbols, bitstamp_config)
)
threads.append(thread_bitstamp)
# Start all threads
for thread in threads:
thread.start()
# Run for the specified duration
duration = config['collection'].get('duration_seconds', 604800) # Default to 1 week
print(f"Data collection started. Running for {duration} seconds.")
end_time = time.time() + duration
try:
while time.time() < end_time:
time.sleep(1)
except KeyboardInterrupt:
print("Data collection interrupted by user.")
finally:
print("Data collection completed. Stopping threads.")
# Threads will close when their WebSocket connections are closed
def on_message(ws, message):
data = json.loads(message)
if data.get('event') == 'data':
channel = data.get('channel', '')
# Extract symbol from channel name
symbol = channel.replace('order_book_', '')
order_data = data.get('data', {})
#print("BITSTAMP DATA : ===================================")
#print(order_data)
# Limit the depth
bids = order_data.get('bids', [])[:depth_level]
asks = order_data.get('asks', [])[:depth_level]
order_book = {
'bids': bids,
'asks': asks,
'timestamp': order_data.get('microtimestamp', int(time.time() * 1000))
}
redis_client.store_order_book(exchange, symbol, order_book)
if terminal_callback:
print(f"[{exchange}] {symbol} Order book stored at {order_book['timestamp']} \n" f"Human Readable time: {datetime.fromtimestamp(time.time()).strftime('%Y %m %d %H:%M:%S')} \n")
print("--------------------------------------------------------------------------------")
def on_error(ws, error):
print(f"[{exchange}] Error: {error}")
def on_close(ws):
print(f"[{exchange}] WebSocket connection closed.")
def on_open(ws):
print(f"[{exchange}] Connected to WebSocket.")
# Subscribe to the order book channels for each symbol
for symbol in symbols:
subscribe_message = json.dumps({
"event": "bts:subscribe",
"data": {
"channel": f"order_book_{symbol}"
}
})
ws.send(subscribe_message)
print(f"[{exchange}] Subscription message sent for {symbol}.")
ws = WebSocketApp(ws_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever() # redis_client.py
import redis
import json
class RedisClient:
def init(self, host='localhost', port=6379, db=0):
try:
self.client = redis.Redis(host=host, port=port, db=db)
# Test the connection
self.client.ping()
print(f"Connected to Redis at {host}:{port}, DB: {db}")
except redis.exceptions.ConnectionError as e:
print(f"Failed to connect to Redis: {e}")
exit(1)
code
def store_order_book(self, exchange, symbol, data, terminal_callback=False):
try:
timestamp = int(data.get('timestamp'))
key = f"orderbook:{exchange}:{symbol}:{timestamp}"
# Convert the order book to a JSON string for storage
value = json.dumps(data)
self.client.set(key, value)
if terminal_callback:
print(f"Stored {exchange} order book for {symbol} at {timestamp}")
except TypeError as e:
print(f"[{exchange}] Error: {e}")
except Exception as e:
print(f"[{exchange}] Unexpected error: {e}")
To meet your requirements for sequence number checks, timestamp synchronization, data integrity, and error logging, we'll need to modify your existing code, particularly in the exchanges.py file where you handle the exchange data streams.
Below is a step-by-step guide on how to modify your code to incorporate these features:
1. Modify handle_binance Function
The Binance exchange provides sequence numbers (lastUpdateId, U, and u) in its order book updates. We can use these to check for data integrity.
Steps:
Fetch Initial Snapshot:
Before starting the WebSocket connection, fetch the initial order book snapshot using Binance's REST API. This will give you the starting point (lastUpdateId) for sequence number tracking.
Store lastUpdateId:
Keep track of the lastUpdateId from the snapshot for each symbol.
Check Sequence Numbers in on_message:
In the on_message callback, compare the incoming update IDs with the expected sequence numbers to ensure no updates are missing.
Handle Inconsistencies:
If a gap is detected in the sequence numbers, log an error, request a new snapshot, and update the local order book.
Code Modification:
Here's how you can modify your handle_binance function:
python
import json
import time
import requests
from websocket import WebSocketApp
from datetime import datetime
def handle_binance(redis_client, symbols, config):
exchange = "binance"
depth_level = config.get('depth_level', 20)
upload_speed = config.get('upload_speed', 100)
terminal_callback = config.get('terminal_callback', False)
# Initialize variables to store lastUpdateId for each symbol
last_update_ids = {}
# Fetch initial snapshots for each symbol
for symbol in symbols:
snapshot = requests.get(
f'https://api.binance.com/api/v3/depth',
params={'symbol': symbol.upper(), 'limit': depth_level}
).json()
last_update_id = snapshot['lastUpdateId']
last_update_ids[symbol] = last_update_id
# Store the initial order book in Redis
order_book = {
'bids': snapshot.get('bids', []),
'asks': snapshot.get('asks', []),
'timestamp': int(time.time() * 1000000) # microseconds
}
redis_client.store_order_book(exchange, symbol.upper(), order_book)
# Prepare streams
streams = [f"{symbol}@depth{depth_level}@{upload_speed}ms" for symbol in symbols]
ws_url = f"wss://stream.binance.com:9443/stream?streams={'/'.join(streams)}"
def on_message(ws, message):
data = json.loads(message)
if 'data' in data:
stream = data['stream']
stream_symbol = stream.split('@')[0]
symbol = stream_symbol.upper()
order_book_data = data['data']
first_update_id = order_book_data['U']
final_update_id = order_book_data['u']
last_update_id = last_update_ids.get(symbol.lower())
# Check if updates are sequential
if last_update_id and first_update_id <= last_update_id + 1 <= final_update_id:
# Update lastUpdateId
last_update_ids[symbol.lower()] = final_update_id
order_book = {
'bids': order_book_data.get('b'),
'asks': order_book_data.get('a'),
'timestamp': order_book_data.get('E') * 1000 # Convert to microseconds
}
redis_client.store_order_book(exchange, symbol, order_book)
if terminal_callback:
print(f"[{exchange}] {symbol} Order book stored at {order_book['timestamp']} \n"
f"Human Readable time: {datetime.fromtimestamp(order_book['timestamp'] / 1e6).strftime('%Y-%m-%d %H:%M:%S.%f')} \n")
print("===========================================================================")
else:
# Sequence gap detected
error_message = f"[{exchange}] Sequence gap detected for {symbol}. Expected update IDs between {last_update_id + 1} and {final_update_id}, received {first_update_id} to {final_update_id}."
print(error_message)
redis_client.log_error(exchange, symbol, error_message)
# Fetch a new snapshot to resynchronize
snapshot = requests.get(
f'https://api.binance.com/api/v3/depth',
params={'symbol': symbol.upper(), 'limit': depth_level}
).json()
last_update_id = snapshot['lastUpdateId']
last_update_ids[symbol.lower()] = last_update_id
# Store the new order book in Redis
order_book = {
'bids': snapshot.get('bids', []),
'asks': snapshot.get('asks', []),
'timestamp': int(time.time() * 1000000) # microseconds
}
redis_client.store_order_book(exchange, symbol.upper(), order_book)
def on_error(ws, error):
print(f"[{exchange}] Error: {error}")
redis_client.log_error(exchange, 'general', str(error))
def on_close(ws):
print(f"[{exchange}] WebSocket connection closed.")
def on_open(ws):
print(f"[{exchange}] Connected to WebSocket.")
ws = WebSocketApp(ws_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever()
Explanation:
Fetching Initial Snapshot:
We use requests to fetch the initial order book snapshot for each symbol and store it in Redis.
Sequence Number Tracking:
We keep track of lastUpdateId for each symbol to ensure the continuity of the data stream.
Handling Updates:
When a new message arrives, we check the sequence numbers. If they're in order, we update the lastUpdateId and store the data. If not, we log the error and resynchronize by fetching a new snapshot.
Logging Errors:
We added a log_error method in redis_client to record any inconsistencies.
2. Modify handle_bitstamp Function
Bitstamp does not provide sequence numbers in its WebSocket feed. However, we can monitor the microtimestamp to ensure that the data stream is continuous.
Steps:
Track Last Timestamp:
Keep track of the last received microtimestamp for each symbol.
Check Timestamp Increments:
Ensure that each new microtimestamp is greater than the previous one.
Handle Inconsistencies:
If a timestamp is out of order or duplicates are detected, log an error.
Code Modification:
Here's how you can modify your handle_bitstamp function:
python
import json
import time
from websocket import WebSocketApp
from datetime import datetime
def handle_bitstamp(redis_client, symbols, config):
exchange = "bitstamp"
depth_level = config.get('depth_level', 20)
terminal_callback = config.get('terminal_callback', False)
ws_url = "wss://ws.bitstamp.net"
# Initialize variables to store last timestamp for each symbol
last_timestamps = {}
def on_message(ws, message):
data = json.loads(message)
if data.get('event') == 'data':
channel = data.get('channel', '')
# Extract symbol from channel name
symbol = channel.replace('order_book_', '')
order_data = data.get('data', {})
current_timestamp = int(order_data.get('microtimestamp'))
last_timestamp = last_timestamps.get(symbol)
# Check if timestamps are in order
if last_timestamp and current_timestamp <= last_timestamp:
# Timestamp inconsistency detected
error_message = f"[{exchange}] Timestamp inconsistency detected for {symbol}. Last timestamp: {last_timestamp}, current timestamp: {current_timestamp}."
print(error_message)
redis_client.log_error(exchange, symbol, error_message)
else:
last_timestamps[symbol] = current_timestamp
# Limit the depth
bids = order_data.get('bids', [])[:depth_level]
asks = order_data.get('asks', [])[:depth_level]
order_book = {
'bids': bids,
'asks': asks,
'timestamp': current_timestamp # microseconds
}
redis_client.store_order_book(exchange, symbol, order_book)
if terminal_callback:
print(f"[{exchange}] {symbol} Order book stored at {order_book['timestamp']} \n"
f"Human Readable time: {datetime.fromtimestamp(order_book['timestamp'] / 1e6).strftime('%Y-%m-%d %H:%M:%S.%f')} \n")
print("--------------------------------------------------------------------------------")
def on_error(ws, error):
print(f"[{exchange}] Error: {error}")
redis_client.log_error(exchange, 'general', str(error))
def on_close(ws):
print(f"[{exchange}] WebSocket connection closed.")
def on_open(ws):
print(f"[{exchange}] Connected to WebSocket.")
# Subscribe to the order book channels for each symbol
for symbol in symbols:
subscribe_message = json.dumps({
"event": "bts:subscribe",
"data": {
"channel": f"order_book_{symbol}"
}
})
ws.send(subscribe_message)
print(f"[{exchange}] Subscription message sent for {symbol}.")
ws = WebSocketApp(ws_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever()
Explanation:
Timestamp Tracking:
We keep track of the last received microtimestamp for each symbol.
Handling Updates:
Compare the current timestamp with the last one to detect any inconsistencies.
Logging Errors:
If we detect a timestamp inconsistency, we log the error using redis_client.log_error.
3. Modify RedisClient Class
To facilitate error logging and data integrity checks, we'll add a log_error method to your RedisClient class.
Code Modification:
python
import redis
import json
class RedisClient:
def __init__(self, host='localhost', port=6379, db=0):
try:
self.client = redis.Redis(host=host, port=port, db=db)
# Test the connection
self.client.ping()
print(f"Connected to Redis at {host}:{port}, DB: {db}")
except redis.exceptions.ConnectionError as e:
print(f"Failed to connect to Redis: {e}")
exit(1)
def store_order_book(self, exchange, symbol, data, terminal_callback=False):
try:
timestamp = int(data.get('timestamp'))
key = f"orderbook:{exchange}:{symbol}:{timestamp}"
# Convert the order book to a JSON string for storage
value = json.dumps(data)
self.client.set(key, value)
if terminal_callback:
print(f"Stored {exchange} order book for {symbol} at {timestamp}")
except TypeError as e:
print(f"[{exchange}] Error: {e}")
self.log_error(exchange, symbol, str(e))
except Exception as e:
print(f"[{exchange}] Unexpected error: {e}")
self.log_error(exchange, symbol, str(e))
def log_error(self, exchange, symbol, message):
error_key = f"errors:{exchange}:{symbol}"
error_message = f"{int(time.time() * 1000000)}: {message}"
self.client.rpush(error_key, error_message)
Explanation:
log_error Method:
Adds errors to a Redis list for each exchange and symbol. This helps in tracking and reviewing all the errors that occur during data collection.
4. Implement Timestamp Synchronization
To meet the requirement of timestamp synchronization, ensure that all timestamps are stored in the same format (microseconds since epoch) and that your system clock is synchronized using NTP.
Additional Steps:
System Clock Synchronization:
Ensure that the machine running this code has accurate system time. For Linux systems, you can use ntpd or chronyd for time synchronization.
Convert All Timestamps:
Make sure all timestamps from different exchanges are converted to a common format (e.g., microseconds since epoch) when storing.
5. Enhance Logging System
To develop a robust logging system:
Use Python's Logging Module:
Instead of printing to the console, use the logging module to log messages with different severity levels (INFO, WARNING, ERROR).
Configure Log Formatting:
Include timestamps, exchange names, symbols, and error messages in your log entries.
Log to File:
Configure the logger to write logs to a file for persistent storage and analysis.
Code Example:
python
import logging
# Configure the logger at the beginning of your script
logging.basicConfig(
filename='data_collector.log',
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Replace print statements with logging calls
logging.info(f"[{exchange}] Connected to WebSocket.")
logging.error(f"[{exchange}] Error: {error}")
Note:
Replace all print statements in your code with appropriate logging calls.
Ensure that error logging captures enough context to diagnose issues.
6. Final Adjustments
Exception Handling:
Ensure all exceptions are caught and logged appropriately to prevent the application from crashing unexpectedly.
Data Recorder:
Your existing Redis storage mechanism serves as the data recorder. Ensure that it's robust and can handle reconnections and data persistence.
By applying these modifications, your code will now:
Check sequence numbers and ensure data integrity for Binance.
Monitor timestamps for Bitstamp to detect any inconsistencies.
Synchronize timestamps across exchanges.
Log any errors or inconsistencies for later analysis.
Maintain a robust data recording system using Redis.
Feel free to reach out if you have any questions or need further assistance with these changes!