I went through the APIs of both exchanges and identified a few challenges we need to address moving forward. Specifically, we need to design a system where we can define all trading symbols, order book (OB) depth, and upload speed for recordings through the configuration file.
BINANCE
For Binance, this process is relatively straightforward. We can use a structure like this in the configuration file:
"symbols": ["btcusdt"],
// List of trading pairs for which data streams are subscribed.
// This will change as different exchanges use different symbols for the same trading pairs.
// We need a simple way to update and add symbols through the configuration file.
"wss_callback": {
"terminal_callback": true
// Enable or disable printing WebSocket data to the terminal.
// This is essential for development and testing.
// Later, we will implement a logging system for production.
},
"ob_stream_settings": {
"depth_level": 20,
// Binance allows adjustable OB depths (5, 10, or 20), so we will use this settings for benchmark also for Bitstamp and other exhcanges (if needed) in future
"upload_speed": 100
// We'll use 100ms as the benchmark.
// While Binance allows upload speeds between 100ms and 1000ms
// maintaining 100ms as our benchmark ensures consistency.
}
}
BITSTAMP
We need to modify the Bitstamp order book stream to match our benchmarks:
Upload Speed: Bitstamp's real-time updates already align with a 100ms benchmark (as shown in the demo file you sent).
Order Book Depth:
We'll need to modify the system to allow selecting between depths of 5, 10, and 20, similar to Binance, For analytical purposes, having flexibility with OB depth is critical. For example, depth 5 might suffice for certain use cases.
Next Steps for minor updates!
Implement a unified configuration file that allows adding and modifying symbols, depth, and upload speeds for both exchanges.
Assistant
Establish consistent benchmarks (upload speed 100 (super, this is done already), let's make flexibility in depth levels as wel. We will use Binance as example, we only have to implement this for Bitstamp!
Develop functionality to enable or disable terminal outputs for WebSocket data during development.
Explore ways to dynamically manage symbol mapping between exchanges since asset pair names vary (e.g., "BTC/USD" vs. "BTCUSDT") - This would be chellange, I didn't figured out myself, what should be the best and most flexibla approch to met this without hardcoding!
in short, we have to modify bitsmap ob stream, so it fetch data similar to Binance (and we can change depth 5,10 or 20) and unified syatem, so we can control and add diferent symbols through the config file! MAKE THESE CHANGES PERFECTLY. CURRENT CODE : # collector.py
import yaml
import threading
import time
from datetime import datetime, timedelta
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 = []
if 'binance' in config['exchanges']:
thread_binance = threading.Thread(target=handle_binance, args=(redis_client,))
threads.append(thread_binance)
if 'bitstamp' in config['exchanges']:
thread_bitstamp = threading.Thread(target=handle_bitstamp, args=(redis_client,))
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
if name == "main":
main() # config.yaml
exchanges:
binance:
ws_url: "wss://stream.binance.com:9443/ws/btcusdt@depth"
bitstamp:
ws_url: "wss://ws.bitstamp.net"
redis:
host: "localhost"
port: 6379
db: 0
collection:
duration_seconds: 100 # 1 week in seconds # exchanges.py
import json
import threading
import time
from websocket import create_connection
try:
ws = create_connection(ws_url)
print(f"[{exchange}] Connected to WebSocket.")
# Subscribe to the order book channel
subscribe_message = json.dumps({
"event": "bts:subscribe",
"data": {
"channel": f"order_book_{symbol}"
}
})
ws.send(subscribe_message)
print(f"[{exchange}] Subscription message sent.")
while True:
message = ws.recv()
data = json.loads(message)
if data.get('event') == 'data':
order_data = data.get('data', {})
order_book = {
'bids': order_data.get('bids', []),
'asks': order_data.get('asks', []),
'timestamp': order_data.get('microtimestamp', int(time.time() * 1000))
}
#print(order_book)
redis_client.store_order_book(exchange, symbol, order_book)
print(f"[{exchange}] Order book stored at {order_book['timestamp']}")
except Exception as e:
print(f"[{exchange}] Error: {e}")
finally:
ws.close()
print(f"[{exchange}] WebSocket connection closed.")
from datetime import datetime
import redis
import json
import time
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):
try:
timestamp = datetime.fromtimestamp( (int(data.get('timestamp')) ) /1000000)
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)
print(f"Stored {exchange} order book at {timestamp}")
except TypeError as e:
print(f"[{exchange}] Error: {e}")
except Exception as e:
print(f"[{exchange}] Unexpected error: {e}")
Sure, I'll make the necessary changes to the code to meet your requirements perfectly.
Updated Configuration File (config.yaml)
First, we'll update the configuration file to include the symbols, depth levels, upload speeds, and terminal callback settings for both exchanges. We'll also implement a symbol mapping to handle the different symbol formats across exchanges.
We'll modify collector.py to read the updated configuration and initialize the threads for each exchange with the appropriate settings.
python
# 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()
# 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
if __name__ == "__main__":
main()
Updated exchanges.py
We'll update the exchange handlers to use the configurations and handle multiple symbols. For Bitstamp, we'll implement the depth limit by slicing the order book data.
python
Updated redis_client.py
We'll adjust the Redis client to handle different timestamp formats and ensure consistent storage.
python
# redis_client.py
from datetime import datetime
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):
try:
timestamp = int(data.get('timestamp'))
if len(str(timestamp)) > 13:
# Assume microseconds, convert to milliseconds
timestamp = timestamp // 1000
timestamp_dt = datetime.fromtimestamp(timestamp / 1000.0)
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)
# Optionally, print or log the action
# print(f"Stored {exchange} order book for {symbol} at {timestamp_dt}")
except TypeError as e:
print(f"[{exchange}] Error: {e}")
except Exception as e:
print(f"[{exchange}] Unexpected error: {e}")
Handling Symbol Mapping Between Exchanges
In the configuration file, we introduced a symbol_mappings section to handle the different symbol formats across exchanges. This allows us to refer to symbols using a universal name and map them to the exchange-specific symbols.
Since Bitstamp doesn't provide an option to set the order book depth through the API, we adjust the depth by slicing the bids and asks lists after receiving the data.