class DataFetcher:
def init(self, symbols, timeframes=['1m', '5m', '15m', '1h']):
self.symbols = symbols
self.timeframes = [tf.lower() for tf in timeframes]
self.exchange = ccxt.binanceusdm({'enableRateLimit': True})
self.data_lock = asyncio.Lock()
self.symbol_map = {}
self.streams = []
self.stream_urls = []
self.max_streams_per_connection = 100 # Adjust based on testing
logger.debug(f"Initialized DataFetcher with symbols: {self.symbols}, timeframes: {self.timeframes}")
code
async def initialize_exchange(self):
await self.exchange.load_markets()
for symbol in self.symbols:
market = self.exchange.market(symbol)
ws_symbol = market['id'].lower() # e.g., 'btcusdt'
self.symbol_map[ws_symbol] = symbol
for timeframe in self.timeframes:
self.streams.append(f"{ws_symbol}@kline_{timeframe}")
# Add order book streams (assuming depth=5 for this example)
self.streams.append(f"{ws_symbol}@depth5@100ms") # Adjust depth and update speed as needed
# Create WebSocket URLs with limited streams per connection
for i in range(0, len(self.streams), self.max_streams_per_connection):
stream_subset = self.streams[i:i + self.max_streams_per_connection]
url = f"wss://fstream.binance.com/stream?streams={'/'.join(stream_subset)}"
self.stream_urls.append(url)
logger.debug(f"WebSocket URLs: {self.stream_urls}")
async def fetch_historical_data(self):
semaphore = asyncio.Semaphore(5) # Adjusted semaphore for optimal concurrency
tasks = []
for symbol in self.symbols:
for timeframe in self.timeframes:
tasks.append(self.fetch_symbol_historical_data(symbol, timeframe, semaphore))
await asyncio.gather(*tasks)
async def fetch_symbol_historical_data(self, symbol, timeframe, semaphore):
async with semaphore:
try:
limit = 1000 # Binance allows up to 1000 bars per request
# Get the most recent timestamp from the database
latest_timestamp = await self.get_latest_kline_timestamp(symbol, timeframe)
if latest_timestamp:
since = int(latest_timestamp.timestamp() * 1000) + 1 # Convert to milliseconds and add 1ms
else:
since = None # Fetch all available data
all_bars = []
while True:
bars = await self.exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=limit)
if not bars:
break
all_bars += bars
since = bars[-1][0] + 1 # Prevent fetching the last bar again
if len(bars) < limit:
break
if all_bars:
df = pd.DataFrame(all_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['timestamp'] = df['timestamp'].dt.tz_convert('Africa/Nairobi')
logger.info(f"Fetched {len(df)} new bars for {symbol} {timeframe}")
# Save to database
await self.save_klines(symbol, timeframe, df)
else:
logger.info(f"No new data to fetch for {symbol} {timeframe}")
except ccxt.NetworkError as e:
logger.error(f"Network error while fetching data for {symbol} {timeframe}: {str(e)}")
except ccxt.ExchangeError as e:
logger.error(f"Exchange error while fetching data for {symbol} {timeframe}: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error fetching data for {symbol} {timeframe}: {str(e)}\n{traceback.format_exc()}")
@sync_to_async
def get_latest_kline_timestamp(self, symbol, timeframe):
try:
latest_kline = Kline.objects.filter(symbol=symbol, timeframe=timeframe).order_by('-timestamp').first()
if latest_kline:
return latest_kline.timestamp
else:
return None
except Exception as e:
logger.error(f"Error getting latest kline timestamp for {symbol} {timeframe}: {str(e)}")
return None
@sync_to_async
def save_klines(self, symbol, timeframe, df):
# Validate and clean data before saving
df.dropna(inplace=True)
if df.empty:
logger.warning(f"No valid data to save for {symbol} {timeframe}")
return
klines_to_create = []
for _, row in df.iterrows():
klines_to_create.append(Kline(
symbol=symbol,
timeframe=timeframe,
timestamp=row['timestamp'],
open=row['open'],
high=row['high'],
low=row['low'],
close=row['close'],
volume=row['volume']
))
Kline.objects.bulk_create(klines_to_create, ignore_conflicts=True)
logger.info(f"Saved {len(klines_to_create)} klines for {symbol} {timeframe} to the database.")
async def handle_websocket(self, url):
retry_count = 0
max_retries = 5
backoff = 1
while retry_count < max_retries:
try:
async with websockets.connect(
url,
ping_interval=20,
ping_timeout=20,
close_timeout=10
) as websocket:
logger.info(f"Connected to WebSocket: {url}")
retry_count = 0 # Reset on successful connection
async for message in websocket:
data = json.loads(message)
if 'data' not in data:
continue
stream_type = data['stream'].split('@')[1] # Extract stream type (e.g., 'kline_1m', 'depth5')
if stream_type.startswith('kline'):
await self.process_kline_data(data)
elif stream_type.startswith('depth'):
await self.process_order_book_data(data)
except websockets.exceptions.ConnectionClosed as e:
logger.warning(f"WebSocket connection closed: {str(e)}")
except websockets.exceptions.InvalidStatusCode as e:
logger.error(f"Invalid status code when connecting to WebSocket: {str(e)}")
break
except Exception as e:
logger.error(f"Unexpected WebSocket error: {str(e)}\n{traceback.format_exc()}")
retry_count += 1
sleep_time = backoff * retry_count
logger.info(f"Retrying WebSocket connection in {sleep_time} seconds (Attempt {retry_count}/{max_retries})")
await asyncio.sleep(sleep_time)
async def process_kline_data(self, data):
kline_data = data['data']['k']
if not kline_data['x']:
return # Only process closed klines
ws_symbol = kline_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timeframe = kline_data['i']
if timeframe not in self.timeframes:
return
timestamp = pd.to_datetime(kline_data['t'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
kline = Kline(
symbol=symbol,
timeframe=timeframe,
timestamp=timestamp,
open=float(kline_data['o']),
high=float(kline_data['h']),
low=float(kline_data['l']),
close=float(kline_data['c']),
volume=float(kline_data['v'])
)
# Save or update the kline in the database
await self.save_kline(kline)
async def process_order_book_data(self, data):
order_book_data = data['data']
ws_symbol = order_book_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timestamp = pd.to_datetime(order_book_data['T'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
# Process and save order book data
bids = [[float(price), float(qty)] for price, qty in order_book_data['b']]
asks = [[float(price), float(qty)] for price, qty in order_book_data['a']]
order_book = OrderBook(
symbol=symbol,
timestamp=timestamp,
bids=bids,
asks=asks
)
await self.save_order_book(order_book)
@sync_to_async
def save_kline(self, kline):
# Data validation and cleansing
if any(val is None for val in [kline.open, kline.high, kline.low, kline.close, kline.volume]):
logger.warning(f"Invalid data encountered for {kline.symbol} {kline.timeframe} at {kline.timestamp}")
return
Kline.objects.update_or_create(
symbol=kline.symbol,
timeframe=kline.timeframe,
timestamp=kline.timestamp,
defaults={
'open': kline.open,
'high': kline.high,
'low': kline.low,
'close': kline.close,
'volume': kline.volume,
}
)
logger.debug(f"Saved kline for {kline.symbol} {kline.timeframe} at {kline.timestamp}")
@sync_to_async
def save_order_book(self, order_book):
OrderBook.objects.update_or_create(
symbol=order_book.symbol,
timestamp=order_book.timestamp,
defaults={
'bids': order_book.bids,
'asks': order_book.asks,
}
)
logger.debug(f"Saved order book for {order_book.symbol} at {order_book.timestamp}")
async def start_websockets(self):
tasks = []
for url in self.stream_urls:
tasks.append(asyncio.create_task(self.handle_websocket(url)))
await asyncio.gather(*tasks)
async def run(self):
try:
logger.info("Initializing exchange...")
await self.initialize_exchange()
logger.info("Fetching historical data...")
await self.fetch_historical_data()
logger.info("Starting WebSocket connections...")
await self.start_websockets()
finally:
await self.exchange.close()
logger.info("Exchange connection closed.")
# Filter for USDT perpetual futures pairs
usdt_pairs = []
for symbol, market in markets.items():
if market.get('active') and market.get('contract') and market.get('type') == 'swap' and market.get('linear') and market.get('quote') == 'USDT':
usdt_pairs.append(symbol)
usdt_pairs = list(set(usdt_pairs))
logger.info(f"Total Futures USDT Pairs: {len(usdt_pairs)}")
if not usdt_pairs:
logger.warning("No USDT pairs found after filtering. Please check the filtering criteria.")
return
fetcher = DataFetcher(symbols=usdt_pairs, timeframes=['1m', '5m', '15m', '1h'])
await fetcher.run()
if name == "main":
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
Between above code and the one below, wic is better
#fetch_data.py
import asyncio
import json
import os
import sys
import websockets
import ccxt.async_support as ccxt
import pandas as pd
import traceback
from datetime import datetime
from asgiref.sync import sync_to_async
import django
from loguru import logger
# Filter for USDT perpetual futures pairs
usdt_pairs = []
for symbol, market in markets.items():
if market.get('active') and market.get('contract') and market.get('type') == 'swap' and market.get('linear') and market.get('quote') == 'USDT':
usdt_pairs.append(symbol)
usdt_pairs = list(set(usdt_pairs))
logger.info(f"Total Futures USDT Pairs: {len(usdt_pairs)}")
if not usdt_pairs:
logger.warning("No USDT pairs found after filtering. Please check the filtering criteria.")
return
fetcher = DataFetch(symbols=usdt_pairs, timeframes=['1m', '5m', '15m', '1h'])
await fetcher.run()
if name == "main":
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
Assistant
To determine which version of the code is better, let's evaluate key differences and improvements:
Similarities
Both scripts perform similar tasks:
Initialize a connection with the Binance USDM exchange using ccxt.
Fetch historical data for specified symbols and timeframes.
Establish WebSocket connections to stream real-time data for available symbols.
Store processed kline and order book data into a database.
Use Django ORM for database operations, assuming Django is correctly set up and models Kline and OrderBook exist.
Differences
Class Names:
The first script uses DataFetcher while the second script uses DataFetch. The choice of name might not impact functionality, but clear and meaningful naming helps maintainability.
Handling of Historical Data Fetching:
Timestamps:
The first script tries to resume fetching from the latest timestamp saved in the database, which is resource-efficient as it avoids duplicate data.
The second script fetches all available data from the start, which might lead to unnecessary data fetching and increased API usage.
Error Handling:
Both scripts handle exceptions during WebSocket operations but differ in logging and retry mechanisms. Consistent and informative logging, as seen in the first script, can be more helpful for debugging.
Order Book Data Processing:
The second script attempts to unpack a third element in the bids and asks tuples within process_order_book_data, which doesn't match the data coming from the API. This is a likely bug that could cause runtime errors.
Code Consistency and Readability:
The first script generally provides more detailed comments and cleaner method separation, which can help other developers quickly understand and work with the code.
Semantics and Variable Validation:
The first script includes some data validation, which is crucial for maintaining the integrity of the data being saved.
Conclusion
The first script is better due to:
Efficient fetching of historical data using timestamps.
More robust logging and data validation.
Potential bug in the second script's order book data processing.
Make sure to validate the order book processing stage and handle any potential exceptions gracefully, ensuring that there's no data inconsistency or loss. If you choose the second script, consider adopting the efficiency and bug fixes seen in the first script.
User
What about my new code below. Compare it with DataFetcher I shared earlier and tell me which one is better, and if it is okay or needs improvement.
fetch_data.py
import asyncio
import json
import os
import sys
import websockets
import ccxt.async_support as ccxt
import pandas as pd
import traceback
from datetime import datetime, timedelta
from asgiref.sync import sync_to_async
import django
from loguru import logger
from django.db import OperationalError, IntegrityError
from django.db.models import Max
class Fetcher:
def init(self, symbols, timeframes=['1m', '5m', '15m', '1h']):
self.symbols = symbols
self.timeframes = [tf.lower() for tf in timeframes]
self.exchange = ccxt.binanceusdm({'enableRateLimit': True})
self.data_lock = asyncio.Lock()
self.symbol_map = {}
self.streams = []
self.stream_urls = []
self.max_streams_per_connection = 100 # Adjust based on testing
logger.debug(f"Initialized DataFetcher with symbols: {self.symbols}, timeframes: {self.timeframes}")
code
Assistant
Let's evaluate the improvements and changes in your new Fetcher class compared to the original DataFetcher and discuss which might be better for your use case.
Improvements and Changes in Fetcher
Exponential Backoff:
Your new implementation incorporates an exponential backoff strategy for reconnecting WebSockets, improving reliability and handling connection failures more gracefully.
Data Gap Check:
A method to check for missing kline data gaps (check_data_gaps) provides an extra validation layer for data completeness, which is a valuable addition for data integrity.
Database Index Optimization:
Ensuring database indices after loading symbols and markets is a great practice for enhancing query performance, especially as data grows.
Error Handling:
Added handling for specific database exceptions (OperationalError, IntegrityError) both when fetching and saving data provides robustness to database operations.
Logging Improvements:
More comprehensive logging messages, especially around error handling and gap detection, improve the traceability of operations and help identify issues faster.
Database Fetching:
Using SET operations to identify missing timestamps can be computationally expensive. It is done correctly but might be optimized further if necessary.
Code Comments and Clarity:
The separation of concerns (like indexing and exponential backoff) makes it easier to maintain and extend the code without impacting core functionalities.
Considerations for Further Improvements
Reduce Database Load with Batching:
If the database is large, fetching all timestamps might be expensive. Consider batch processing and filtering based on timestamp ranges.
Refactor Repeated Code:
Some functionalities, like creating WebSocket URLs and managing fetch tasks, remain similar across both scripts. Consider abstracting repeated logic for configuration or setup to avoid redundancy.
User
How about my new code below? Compare it with Fetcher class and tell me if it is production ready or is missing critical parts
#fetch_data.py
import asyncio
import json
import os
import sys
import websockets
import ccxt.async_support as ccxt
import pandas as pd
import traceback
from datetime import datetime, timedelta
from asgiref.sync import sync_to_async
import django
from loguru import logger
from django.db import OperationalError, IntegrityError
from django.db.models import Max
from typing import List, Dict, Optional, Tuple
import numpy as np
from concurrent.futures import ThreadPoolExecutor
import time
import aiohttp
from collections import defaultdict
class DataValidationError(Exception):
"""Custom exception for data validation errors"""
pass
class DataFetcher:
def init(self, symbols, timeframes=['1m', '5m', '15m', '1h']):
self.symbols = symbols
self.timeframes = [tf.lower() for tf in timeframes]
self.exchange = ccxt.binanceusdm({'enableRateLimit': True})
self.data_lock = asyncio.Lock()
self.symbol_map = {}
self.streams = []
self.stream_urls = []
self.max_streams_per_connection = 100
self.last_refresh_time = defaultdict(lambda: defaultdict(float))
self.refresh_interval = 24 * 60 * 60 # 24 hours in seconds
self.gap_threshold = 5 # Maximum number of consecutive missing candles before alerting
code
Assistant
Your new DataFetcher class has seen significant advancements compared to the previous Fetcher class. Here are some notable improvements and a discussion on its readiness for production use:
Improvements Over Fetcher:
Data Gap Handling:
The new class provides a robust framework for identifying and filling data gaps. This includes saving gap information to the database and attempting to fill these gaps, ensuring data completeness.
Data Validation:
The addition of detailed data validation for both kline and order book data (_validate_timeframe_data and _validate_order_book) ensures the integrity of incoming data before it's processed and saved.
Circuit Breaker Pattern:
Employing a circuit breaker pattern helps manage repeated failures in fetching data, preventing constant retry cycles and reducing strain on resources.
Rate Limiting:
Implementing a custom rate-limiting mechanism helps to stay within exchange API limits, safeguarding against rate-limit bans.
Resource Monitoring:
The inclusion of memory and CPU usage monitoring, along with logging health metrics, provides visibility into resource consumption, which is crucial for maintaining performance and detecting issues early.
WebSocket Management:
Extensive handling and retry mechanisms for WebSocket connections, including connection monitoring through heartbeats, improve reliability.
ThreadPoolExecutor:
Although introduced, its integration isn't clear in the context, as it wasn't explicitly used in the code for workload distribution. Ensure it's used if processing parallel workloads especially with CPU-bound tasks.
Improved Logging:
The logging statements are now comprehensive, providing insights into flow control, error conditions, and system performance.
Data Freshness Monitoring:
Automatically refreshing data if not updated within a specified time frame ensures data remains current.
Type Annotations & Error Reporting:
User
my code says "psutil" is not defined
Assistant
The error message "psutil is not defined" indicates that the psutil library, which is used in your code to monitor system resources such as memory and CPU usage, has not been imported. To fix this issue, you need to import psutil at the beginning of your script.
Here's how you can do it:
Install the psutil package if it is not already installed. You can do this via pip:
bash
pip install psutil
Import psutil at the beginning of your script:
Add this line to your import section in fetch_data.py:
python
import psutil
This import allows you to use psutil functions within your code. Make sure the import line is placed with your other import statements to maintain clean code organization.
Here's a part of your script showing where the psutil import should be added:
python
# Other imports...
import psutil # Add this line
from .models import Kline, OrderBook, DataGap
# Your logger configuration and class definitions follow...
class DataFetcher:
# Your class implementation...
After making this change, the psutil library should be available to the script, allowing you to monitor system resources without seeing the "psutil is not defined" error. If you plan to deploy this script, ensure the environment where it runs has psutil installed as well.
User
#fetch_data.py
import asyncio
import json
import os
import sys
import websockets
import ccxt.async_support as ccxt
import pandas as pd
import traceback
from datetime import datetime, timedelta
from asgiref.sync import sync_to_async
import django
from loguru import logger
from django.db import OperationalError, IntegrityError
from django.db.models import Max
from typing import List, Dict, Optional, Tuple
import numpy as np
from concurrent.futures import ThreadPoolExecutor
import time
import aiohttp
from collections import defaultdict
import psutil
class DataValidationError(Exception):
"""Custom exception for data validation errors"""
pass
class DataFetcher:
def init(self, symbols, timeframes=['1m', '5m', '15m', '1h']):
self.symbols = symbols
self.timeframes = [tf.lower() for tf in timeframes]
self.exchange = ccxt.binanceusdm({'enableRateLimit': True})
self.data_lock = asyncio.Lock()
self.symbol_map = {}
self.streams = []
self.stream_urls = []
self.max_streams_per_connection = 100
self.last_refresh_time = defaultdict(lambda: defaultdict(float))
self.refresh_interval = 24 * 60 * 60 # 24 hours in seconds
self.gap_threshold = 5 # Maximum number of consecutive missing candles before alerting
code
Assistant
Your script is designed as a comprehensive data-fetching and monitoring system for cryptocurrency trading data using the Binance Futures API. Here’s a detailed breakdown of what each part of the code does:
Key Functionalities:
Django Setup:
The script initializes Django settings, allowing you to interact with Django ORM for data storage.
Logging Configuration:
Uses loguru to set up logging both to a file and to the console, with different verbosity levels.
DataFetcher Class Initialization:
Initializes parameters and settings for handling cryptocurrency trading data.
Sets up circuit breakers for error handling, rate-limiting to adhere to API limits, and heartbeats for WebSocket management.
Uses defaultdict to manage states such as error counts, data freshness, and request timing.
Rate Limit and Circuit Breaker Management:
Implements functions to check and manage request rates to prevent exceeding API limits.
Implements a circuit breaker pattern to prevent overwhelming the server with requests after repeated failures.
Data Validation and Gap Checking:
Validates kline data for consistency, checks for missing data gaps, and attempts to fill these gaps by making additional API requests.
Implements data validation for both kline and order book data to ensure completeness and integrity before storage.
Historical Data Fetching:
Fetches historical trading data for specified symbols and timeframes, manages data gaps, and stores the data in the database.
Uses asynchronous requests to optimize fetching and minimize wait times.
WebSocket Handling:
Sets up WebSocket connections to stream real-time market data.
Includes functionality for handling message decoding errors and maintaining connection stability through heartbeats and retries.
Order Book Handling:
Processes incoming order book data, calculates additional metrics like spread and volume, and stores validated data.
Ensures that bids and asks are properly ordered and no invalid data is stored.
System Health Monitoring:
User
is fetching data from one exchange enough or do I need to include other exchanges as well?
Assistant
Deciding whether to fetch data from one exchange or multiple exchanges largely depends on your specific needs and objectives. Here are some considerations to help guide your decision:
Advantages of Fetching Data from Multiple Exchanges:
Price Discovery and Arbitrage Opportunities:
Prices may vary slightly across exchanges due to differing liquidity, user base, or trading volume. Accessing multiple exchanges can help identify arbitrage opportunities or allow for more accurate price discovery and analysis.
Market Coverage:
Different exchanges might list different trading pairs or have varying levels of trading activity. Accessing multiple exchanges provides a more comprehensive market view and ensures that you aren't missing critical market data.
Resilience Against Exchange Downtime:
In the event that one exchange experiences downtime or API issues, having data from other exchanges can ensure that your system continues to function without interruptions.
Liquidity Analysis:
Comparing liquidity levels across exchanges helps in understanding where most trading activity occurs and can inform strategies that rely on high liquidity.
Diversification:
Relying solely on one exchange increases risk exposure to issues specific to that exchange. Diversification across exchanges mitigates such risks.
Challenges of Fetching Data from Multiple Exchanges:
Complexity:
Supporting multiple exchanges increases the complexity of your system, as each exchange might have different APIs, data formats, and rate limits that you need to handle.
Resource Requirements:
Fetching and processing more data demands greater computational and storage resources, potentially increasing cloud or infrastructure costs.
Integration and Maintenance:
More exchanges mean more integration points and potential maintenance overhead, especially if exchanges update their APIs or encounter issues.
Consistency:
Normalizing data between exchanges (e.g., time zones, data formats) can require additional data processing and validation logic.
Key Considerations for Your Decision:
User
My objective is to perform order book and volume analysis for only symbols available in binance futures
Assistant
Given your objective is to perform order book and volume analysis specifically for symbols available on Binance Futures, focusing on a single exchange—Binance Futures—is sufficient for the following reasons:
1. Focused Analysis:
Since your interest is in symbols listed on Binance Futures, fetching data from this exchange will give you the necessary information you need without the added complexity of handling multiple exchanges.
2. Exchange Specific Features:
Binance Futures might have specific features or data characteristics (such as funding rates, margin information, etc.) that are particularly relevant to futures analysis which may not be available or compatible with the data semantics from other exchanges.
3. Reduced Complexity:
Concentrating on a single exchange reduces the complexity involved in data aggregation, normalization, and infrastructure management. This simplifies development, troubleshooting, and maintenance of your systems.
4. Lower Resource Usage:
By limiting to one exchange, you reduce the computational resources needed for processing data and the network resources required for fetching it. This can lead to cost savings both in terms of infrastructure and development time.
5. Scalability:
With focus on a single exchange, you can better scale your solution to handle more depth or higher frequency of data collection and analysis, ensuring a more robust and high-performance system.
Considerations for Focusing on Binance Futures:
Exchange Health: Ensure robust error handling and retry logic as you'd be reliant on a single point of data. Exchange outages or API limits could impact your analysis.
API Limits: Be mindful of Binance API rate limits, especially as you scale your volume of requests. Implement rate limiting and backoff strategies.
Data Quality: Regularly validate the completeness and quality of the data being fetched to ensure your analysis is accurate.
Since your focus is narrow and well-defined, sticking with Binance Futures makes sense. This allows you to specialize your tools and processes for the specifics of this exchange and focus on deriving insights rather than managing cross-exchange complexities.
User
If I have a script file that performs the orderbook and volume analysis, how will it access the orderbook, volume and price data from the code I sent you earlier?
Assistant
To have your analysis script access order book, volume, and price data from the DataFetcher system you provided, you will need to ensure that the data is stored in a format or location that the analysis script can access. Here are steps and considerations for setting up this access:
1. Data Storage Strategy:
Your DataFetcher script interacts with a Django ORM setup, presumably writing order book and kline data to database models (Kline, OrderBook, DataGap). Ensure that:
Database Models: The data needed for your analysis (order book, volume, price data) is correctly saved into the corresponding Django models defined in your models.py.
2. Implementing Data Retrieval:
Your analysis script should be able to query this database to access the data. Assuming you have a Django project setup, follow these steps:
Django Environment Setup: Ensure your analysis script can access your Django context by including Django configurations, similar to the fetch_data.py script:
python
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'binancebot.settings')
django.setup()
from .models import Kline, OrderBook
Querying the Database: Use Django ORM queries within your analysis script to retrieve the order book and kline data:
python
from datetime import datetime, timedelta
# Example: Retrieve order book data for a specific symbol and time
def get_order_book_data(symbol: str, start_time: datetime, end_time: datetime):
return OrderBook.objects.filter(
symbol=symbol,
timestamp__range=(start_time, end_time)
)
# Example: Retrieve kline data for a specific symbol and timeframe
def get_kline_data(symbol: str, timeframe: str, start_time: datetime, end_time: datetime):
return Kline.objects.filter(
symbol=symbol,
timeframe=timeframe,
timestamp__range=(start_time, end_time)
)
User
Is Django ORM same as using dataframes? If not, wic is better?
Assistant
Django ORM and dataframes are not the same, and their "better" use depends on the context of your task. Here's a breakdown of the differences and when to use each:
Django ORM
Django ORM (Object-Relational Mapping) is a feature of Django that allows you to interact with your database using Python objects rather than writing raw SQL queries. It provides a high-level abstraction over the database:
Use Cases:
Database Interaction: Primarily used for querying, inserting, updating, and deleting data in a database.
Data Integrity: Enforces relationships and constraints defined in the models.
Scalability: Handles large datasets efficiently, leveraging optimized database queries and indexing.
Security: Helps prevent SQL injection attacks with parameterized queries.
Advantages:
Ease of Use: Abstracts database-specific SQL queries into more manageable Python code.
Integration: Seamlessly integrates with Django projects for web applications.
Maintainability: Changes in the database schema can be easily managed through migrations.
Limitations:
Complex Queries: Can become unwieldy with very complex queries or when fine-tuning SQL is necessary.
Performance: Might be less performant for very complex data processing tasks compared to raw SQL.
Pandas DataFrames
Pandas DataFrames are in-memory data structures part of the Pandas library, designed for data manipulation and analysis:
Use Cases:
Data Analysis: Ideal for working with datasets for data analysis, manipulation, and transformation.
In-Memory Operations: Suited for tasks that involve extensive data manipulation, statistical analysis, or modeling.
File Interactions: Often used for reading and writing data from/to CSV, Excel, or other file formats.
Advantages:
Flexibility: Powerful for performing data cleaning, aggregation, and transformation tasks.
Built-in Functions: Comes with a wide range of methods for complex data processing (e.g., merging, grouping).
User
For my use case, I sent you my code before what would be best
Assistant
Given your use case, which involves fetching and storing order book and volume data from Binance Futures for analysis, it's important to consider both the nature of your data and the tasks you want to perform:
Use Case Summary:
Data Ingestion: You are using Django ORM to fetch and store real-time trading data (order books, klines) into a Django-based relational database.
Data Analysis: You aim to perform order book and volume analysis, presumably on this stored data.
Recommended Approach:
Use Django ORM for Data Ingestion and Storage:
Persistence: Django ORM is well-suited for data persistence. It handles database operations such as inserting and updating records effectively, while ensuring data integrity with model validations and relationships.
Scalability: Leveraging Django ORM allows your application to scale as it handles increased volumes of real-time data because databases are optimized for such operations.
Integration: Since your existing architecture is based on Django, using the ORM maintains a consistent technology stack.
Use Pandas for Data Analysis:
Data Manipulation: Once your data is stored in the database, you can extract it into Pandas DataFrames for analysis. Pandas provides powerful tools for data manipulation and statistical analysis, making it the ideal choice for in-memory computations such as calculating spreads, volumes, and other metrics.
Flexibility: Pandas allows you to perform complex data manipulation and transformation tasks efficiently before your results inform trading strategies or further analysis.
Steps to Implement:
Data Storage (Django ORM):
Set up your models in Django to store data fetched from Binance Futures. Your existing DataFetcher script already handles this.
Use migrations to manage schema changes as your data model evolves.
Analysis (Pandas):
In your analysis script, query the data you need from the Django ORM.
For example, you might use:
python
User
Does my current code continuously ingests data and stores it?
is it better to save in orm than to save in dataframes
Assistant
Let's address both of your questions:
1. Continuous Data Ingestion and Storage
Based on your current code, your setup does seem to continuously ingest data and store it:
WebSocket Connections: Your code establishes WebSocket connections to stream real-time data from Binance Futures. It listens to market data and processes it as it comes in.
Data Fetching Loops: The asynchronous handle_websocket functions continuously receive data, which ensures that new market data is continuously streamed and processed.
Database Operations: You use Django ORM to store this data into your models (Kline and OrderBook), writing new records to the database as new data is received and processed.
Therefore, your system is designed to continuously ingest data and store it as long as the WebSocket connections are alive and the processing loop is running.
2. Comparing Saving in ORM vs. DataFrames
Storing Data with Django ORM:
Persistence: The ORM writes data directly to a database, providing persistent storage. Data is available even if your application restarts or experiences failures.
Integrity and Constraints: ORM enforces data integrity and constraints defined in the database schema. It ensures the database remains consistent.
Query and Retrieval: Offers powerful querying capabilities and is suitable for handling complex queries that leverage indexing and joins across tables.
Compatibility: Ideal when your application needs integration with Django for web development or when you need robust user authentication, admin interfaces, etc.
Storing Data in Pandas DataFrames:
In-Memory Use: DataFrames store data in memory, making them fast for data analysis and manipulation. They are not intended for long-term or durable data storage.
Analysis Efficiency: Excellent for data manipulation, statistical analysis, and numerical computations.
Non-Persistent: Once your program closes, the data in DataFrames is lost unless explicitly saved to a file or database.
Why Choose ORM for Storage:
For your use case, primarily involving continuous data ingestion and analysis likely over large datasets, storing data in a Django ORM/database is better for these reasons:
Durability: Databases ensure that data persists through application lifecycles.
Scalability: Databases are more efficient at handling large data volumes and support concurrent operations better than in-memory solutions.
async def initialize_exchange(self):
await self.exchange.load_markets()
for symbol in self.symbols:
market = self.exchange.market(symbol)
ws_symbol = market['id'].lower() # e.g., 'btcusdt'
self.symbol_map[ws_symbol] = symbol
for timeframe in self.timeframes:
self.streams.append(f"{ws_symbol}@kline_{timeframe}")
# Add order book streams (assuming depth=5 for this example)
self.streams.append(f"{ws_symbol}@depth5@100ms") # Adjust depth and update speed as needed
# Create WebSocket URLs with limited streams per connection
for i in range(0, len(self.streams), self.max_streams_per_connection):
stream_subset = self.streams[i:i + self.max_streams_per_connection]
url = f"wss://fstream.binance.com/stream?streams={'/'.join(stream_subset)}"
self.stream_urls.append(url)
logger.debug(f"WebSocket URLs: {self.stream_urls}")
async def fetch_historical_data(self):
semaphore = asyncio.Semaphore(5) # Adjusted semaphore for optimal concurrency
tasks = []
for symbol in self.symbols:
for timeframe in self.timeframes:
tasks.append(self.fetch_symbol_historical_data(symbol, timeframe, semaphore))
await asyncio.gather(*tasks)
async def fetch_symbol_historical_data(self, symbol, timeframe, semaphore):
async with semaphore:
try:
since = None # Fetch all available data
all_bars = []
limit = 1000 # Binance allows up to 1000 bars per request
while True:
bars = await self.exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=limit)
if not bars:
break
all_bars += bars
since = bars[-1][0] + 1 # Prevent fetching the last bar again
if len(bars) < limit:
break
if all_bars:
df = pd.DataFrame(all_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['timestamp'] = df['timestamp'].dt.tz_convert('Africa/Nairobi')
logger.info(f"Fetched {len(df)} bars for {symbol} {timeframe}")
# Save to database
await self.save_klines(symbol, timeframe, df)
except ccxt.NetworkError as e:
logger.error(f"Network error while fetching data for {symbol} {timeframe}: {str(e)}")
except ccxt.ExchangeError as e:
logger.error(f"Exchange error while fetching data for {symbol} {timeframe}: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error fetching data for {symbol} {timeframe}: {str(e)}\n{traceback.format_exc()}")
@sync_to_async
def save_klines(self, symbol, timeframe, df):
# Validate and clean data before saving
df.dropna(inplace=True)
if df.empty:
logger.warning(f"No valid data to save for {symbol} {timeframe}")
return
klines_to_create = []
for _, row in df.iterrows():
klines_to_create.append(Kline(
symbol=symbol,
timeframe=timeframe,
timestamp=row['timestamp'],
open=row['open'],
high=row['high'],
low=row['low'],
close=row['close'],
volume=row['volume']
))
Kline.objects.bulk_create(klines_to_create, ignore_conflicts=True)
logger.info(f"Saved {len(klines_to_create)} klines for {symbol} {timeframe} to the database.")
async def handle_websocket(self, url):
retry_count = 0
max_retries = 5
backoff = 1
while retry_count < max_retries:
try:
async with websockets.connect(
url,
ping_interval=20,
ping_timeout=20,
close_timeout=10
) as websocket:
logger.info(f"Connected to WebSocket: {url}")
retry_count = 0 # Reset on successful connection
async for message in websocket:
data = json.loads(message)
if 'data' not in data:
continue
stream_type = data['stream'].split('@')[1] # Extract stream type (e.g., 'kline_1m', 'depth5')
if stream_type.startswith('kline'):
await self.process_kline_data(data)
elif stream_type.startswith('depth'):
await self.process_order_book_data(data)
except websockets.exceptions.ConnectionClosed as e:
logger.warning(f"WebSocket connection closed: {str(e)}")
except websockets.exceptions.InvalidStatusCode as e:
logger.error(f"Invalid status code when connecting to WebSocket: {str(e)}")
break
except Exception as e:
logger.error(f"Unexpected WebSocket error: {str(e)}\n{traceback.format_exc()}")
retry_count += 1
sleep_time = backoff * retry_count
logger.info(f"Retrying WebSocket connection in {sleep_time} seconds (Attempt {retry_count}/{max_retries})")
await asyncio.sleep(sleep_time)
async def process_kline_data(self, data):
kline_data = data['data']['k']
if not kline_data['x']:
return # Only process closed klines
ws_symbol = kline_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timeframe = kline_data['i']
if timeframe not in self.timeframes:
return
timestamp = pd.to_datetime(kline_data['t'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
kline = Kline(
symbol=symbol,
timeframe=timeframe,
timestamp=timestamp,
open=float(kline_data['o']),
high=float(kline_data['h']),
low=float(kline_data['l']),
close=float(kline_data['c']),
volume=float(kline_data['v'])
)
# Save or update the kline in the database
await self.save_kline(kline)
async def process_order_book_data(self, data):
order_book_data = data['data']
ws_symbol = order_book_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timestamp = pd.to_datetime(order_book_data['T'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
# Process and save order book data
bids = [[float(price), float(qty)] for price, qty, _ in order_book_data['b']]
asks = [[float(price), float(qty)] for price, qty, _ in order_book_data['a']]
order_book = OrderBook(
symbol=symbol,
timestamp=timestamp,
bids=bids,
asks=asks
)
await self.save_order_book(order_book)
@sync_to_async
def save_kline(self, kline):
# Data validation and cleansing
if any(val is None for val in [kline.open, kline.high, kline.low, kline.close, kline.volume]):
logger.warning(f"Invalid data encountered for {kline.symbol} {kline.timeframe} at {kline.timestamp}")
return
Kline.objects.update_or_create(
symbol=kline.symbol,
timeframe=kline.timeframe,
timestamp=kline.timestamp,
defaults={
'open': kline.open,
'high': kline.high,
'low': kline.low,
'close': kline.close,
'volume': kline.volume,
}
)
logger.debug(f"Saved kline for {kline.symbol} {kline.timeframe} at {kline.timestamp}")
@sync_to_async
def save_order_book(self, order_book):
# You might want to add data validation here as well
OrderBook.objects.update_or_create(
symbol=order_book.symbol,
timestamp=order_book.timestamp,
defaults={
'bids': order_book.bids,
'asks': order_book.asks,
}
)
logger.debug(f"Saved order book for {order_book.symbol} at {order_book.timestamp}")
async def start_websockets(self):
tasks = []
for url in self.stream_urls:
tasks.append(asyncio.create_task(self.handle_websocket(url)))
await asyncio.gather(*tasks)
async def run(self):
try:
logger.info("Initializing exchange...")
await self.initialize_exchange()
logger.info("Fetching historical data...")
await self.fetch_historical_data()
logger.info("Starting WebSocket connections...")
await self.start_websockets()
finally:
await self.exchange.close()
logger.info("Exchange connection closed.")
# Exponential backoff settings
self.initial_delay = 1
self.max_delay = 60
self.exponential_base = 2
async def initialize_exchange(self):
await self.exchange.load_markets()
for symbol in self.symbols:
market = self.exchange.market(symbol)
ws_symbol = market['id'].lower() # e.g., 'btcusdt'
self.symbol_map[ws_symbol] = symbol
for timeframe in self.timeframes:
self.streams.append(f"{ws_symbol}@kline_{timeframe}")
# Add order book streams (assuming depth=5 for this example)
self.streams.append(f"{ws_symbol}@depth5@100ms") # Adjust depth and update speed as needed
# Create WebSocket URLs with limited streams per connection
for i in range(0, len(self.streams), self.max_streams_per_connection):
stream_subset = self.streams[i:i + self.max_streams_per_connection]
url = f"wss://fstream.binance.com/stream?streams={'/'.join(stream_subset)}"
self.stream_urls.append(url)
logger.debug(f"WebSocket URLs: {self.stream_urls}")
async def fetch_historical_data(self):
semaphore = asyncio.Semaphore(5) # Adjusted semaphore for optimal concurrency
tasks = []
for symbol in self.symbols:
for timeframe in self.timeframes:
tasks.append(self.fetch_symbol_historical_data(symbol, timeframe, semaphore))
await asyncio.gather(*tasks)
async def fetch_symbol_historical_data(self, symbol, timeframe, semaphore):
async with semaphore:
try:
limit = 1000 # Binance allows up to 1000 bars per request
# Get the most recent timestamp from the database
latest_timestamp = await self.get_latest_kline_timestamp(symbol, timeframe)
if latest_timestamp:
since = int(latest_timestamp.timestamp() * 1000) + 1 # Convert to milliseconds and add 1ms
else:
since = None # Fetch all available data
all_bars = []
while True:
bars = await self.exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=limit)
if not bars:
break
all_bars += bars
since = bars[-1][0] + 1 # Prevent fetching the last bar again
if len(bars) < limit:
break
if all_bars:
df = pd.DataFrame(all_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['timestamp'] = df['timestamp'].dt.tz_convert('Africa/Nairobi')
logger.info(f"Fetched {len(df)} new bars for {symbol} {timeframe}")
# Check for gaps in data
await self.check_data_gaps(symbol, timeframe, df)
# Save to database
await self.save_klines(symbol, timeframe, df)
else:
logger.info(f"No new data to fetch for {symbol} {timeframe}")
except ccxt.NetworkError as e:
logger.error(f"Network error while fetching data for {symbol} {timeframe}: {str(e)}")
except ccxt.ExchangeError as e:
logger.error(f"Exchange error while fetching data for {symbol} {timeframe}: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error fetching data for {symbol} {timeframe}: {str(e)}\n{traceback.format_exc()}")
@sync_to_async
def get_latest_kline_timestamp(self, symbol, timeframe):
try:
latest_kline = Kline.objects.filter(symbol=symbol, timeframe=timeframe).order_by('-timestamp').first()
if latest_kline:
return latest_kline.timestamp
else:
return None
except OperationalError as e:
logger.error(f"Database operational error: {str(e)}")
return None
except Exception as e:
logger.error(f"Error getting latest kline timestamp for {symbol} {timeframe}: {str(e)}")
return None
@sync_to_async
def check_data_gaps(self, symbol, timeframe, df):
# Check for gaps in the timestamp sequence
existing_timestamps = set(Kline.objects.filter(symbol=symbol, timeframe=timeframe).values_list('timestamp', flat=True))
new_timestamps = set(df['timestamp'])
missing_timestamps = new_timestamps - existing_timestamps
if missing_timestamps:
logger.info(f"Found {len(missing_timestamps)} missing timestamps for {symbol} {timeframe}.")
else:
logger.info(f"No data gaps detected for {symbol} {timeframe}.")
@sync_to_async
def save_klines(self, symbol, timeframe, df):
# Validate and clean data before saving
df.dropna(inplace=True)
if df.empty:
logger.warning(f"No valid data to save for {symbol} {timeframe}")
return
klines_to_create = []
for _, row in df.iterrows():
klines_to_create.append(Kline(
symbol=symbol,
timeframe=timeframe,
timestamp=row['timestamp'],
open=row['open'],
high=row['high'],
low=row['low'],
close=row['close'],
volume=row['volume']
))
Kline.objects.bulk_create(klines_to_create, ignore_conflicts=True)
logger.info(f"Saved {len(klines_to_create)} klines for {symbol} {timeframe} to the database.")
async def handle_websocket(self, url):
retry_count = 0
while True:
try:
async with websockets.connect(
url,
ping_interval=20,
ping_timeout=20,
close_timeout=10
) as websocket:
logger.info(f"Connected to WebSocket: {url}")
retry_count = 0 # Reset on successful connection
async for message in websocket:
data = json.loads(message)
if 'data' not in data:
continue
stream_type = data['stream'].split('@')[1] # Extract stream type (e.g., 'kline_1m', 'depth5')
if stream_type.startswith('kline'):
await self.process_kline_data(data)
elif stream_type.startswith('depth'):
await self.process_order_book_data(data)
except websockets.exceptions.ConnectionClosed as e:
logger.warning(f"WebSocket connection closed: {str(e)}")
retry_count += 1
except websockets.exceptions.InvalidStatusCode as e:
logger.error(f"Invalid status code when connecting to WebSocket: {str(e)}")
retry_count += 1
except asyncio.TimeoutError as e:
logger.error(f"WebSocket timeout error: {str(e)}")
retry_count += 1
except Exception as e:
logger.error(f"Unexpected WebSocket error: {str(e)}\n{traceback.format_exc()}")
retry_count += 1
# Exponential backoff for retries
if retry_count > 0:
delay = min(self.initial_delay * (self.exponential_base ** (retry_count - 1)), self.max_delay)
logger.info(f"Reconnecting to WebSocket in {delay} seconds...")
await asyncio.sleep(delay)
async def process_kline_data(self, data):
try:
kline_data = data['data']['k']
if not kline_data['x']:
return # Only process closed klines
ws_symbol = kline_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timeframe = kline_data['i']
if timeframe not in self.timeframes:
return
timestamp = pd.to_datetime(kline_data['t'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
kline = Kline(
symbol=symbol,
timeframe=timeframe,
timestamp=timestamp,
open=float(kline_data['o']),
high=float(kline_data['h']),
low=float(kline_data['l']),
close=float(kline_data['c']),
volume=float(kline_data['v'])
)
# Save or update the kline in the database
await self.save_kline(kline)
except Exception as e:
logger.error(f"Error processing kline data: {str(e)}\n{traceback.format_exc()}")
async def process_order_book_data(self, data):
try:
order_book_data = data['data']
ws_symbol = order_book_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timestamp = pd.to_datetime(order_book_data['T'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
# Process and save order book data
bids = [[float(price), float(qty)] for price, qty in order_book_data['b']]
asks = [[float(price), float(qty)] for price, qty in order_book_data['a']]
order_book = OrderBook(
symbol=symbol,
timestamp=timestamp,
bids=bids,
asks=asks
)
await self.save_order_book(order_book)
except Exception as e:
logger.error(f"Error processing order book data: {str(e)}\n{traceback.format_exc()}")
@sync_to_async
def save_kline(self, kline):
try:
# Data validation and cleansing
if any(val is None for val in [kline.open, kline.high, kline.low, kline.close, kline.volume]):
logger.warning(f"Invalid data encountered for {kline.symbol} {kline.timeframe} at {kline.timestamp}")
return
Kline.objects.update_or_create(
symbol=kline.symbol,
timeframe=kline.timeframe,
timestamp=kline.timestamp,
defaults={
'open': kline.open,
'high': kline.high,
'low': kline.low,
'close': kline.close,
'volume': kline.volume,
}
)
logger.debug(f"Saved kline for {kline.symbol} {kline.timeframe} at {kline.timestamp}")
except IntegrityError as e:
logger.error(f"Database integrity error while saving kline: {str(e)}")
except OperationalError as e:
logger.error(f"Database operational error while saving kline: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error saving kline: {str(e)}\n{traceback.format_exc()}")
@sync_to_async
def save_order_book(self, order_book):
try:
OrderBook.objects.update_or_create(
symbol=order_book.symbol,
timestamp=order_book.timestamp,
defaults={
'bids': order_book.bids,
'asks': order_book.asks,
}
)
logger.debug(f"Saved order book for {order_book.symbol} at {order_book.timestamp}")
except IntegrityError as e:
logger.error(f"Database integrity error while saving order book: {str(e)}")
except OperationalError as e:
logger.error(f"Database operational error while saving order book: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error saving order book: {str(e)}\n{traceback.format_exc()}")
async def start_websockets(self):
tasks = []
for url in self.stream_urls:
tasks.append(asyncio.create_task(self.handle_websocket(url)))
await asyncio.gather(*tasks)
async def run(self):
try:
logger.info("Initializing exchange...")
await self.initialize_exchange()
logger.info("Fetching historical data...")
await self.fetch_historical_data()
logger.info("Starting WebSocket connections...")
await self.start_websockets()
except Exception as e:
logger.error(f"Error in DataFetcher run loop: {str(e)}\n{traceback.format_exc()}")
finally:
await self.exchange.close()
logger.info("Exchange connection closed.")
# Filter for USDT perpetual futures pairs
usdt_pairs = []
for symbol, market in markets.items():
if market.get('active') and market.get('contract') and market.get('type') == 'swap' and market.get('linear') and market.get('quote') == 'USDT':
usdt_pairs.append(symbol)
usdt_pairs = list(set(usdt_pairs))
logger.info(f"Total Futures USDT Pairs: {len(usdt_pairs)}")
if not usdt_pairs:
logger.warning("No USDT pairs found after filtering. Please check the filtering criteria.")
return
# Database optimization: Add necessary indexes
await optimize_database()
fetcher = Fetcher(symbols=usdt_pairs, timeframes=['1m', '5m', '15m', '1h'])
await fetcher.run()
@sync_to_async
def optimize_database():
try:
# Check if indexes exist, if not, create them
with django.db.connection.cursor() as cursor:
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_kline_symbol_timeframe_timestamp
ON appname_kline(symbol, timeframe, timestamp);
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_orderbook_symbol_timestamp
ON appname_orderbook(symbol, timestamp);
""")
logger.info("Database indexes ensured.")
except OperationalError as e:
logger.error(f"Database operational error during optimization: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error during database optimization: {str(e)}\n{traceback.format_exc()}")
if name == "main":
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
Asynchronous Considerations:
For substantial datasets and subscriptions, ensure that semaphore limits and concurrent tasks do not overwhelm the system or API.
Conclusion
Your new Fetcher implementation is an improvement over the initial DataFetcher with better error handling, exponential backoff for reconnections, and a focus on data integrity through gap checks and indexing. These changes enhance robustness, performance, and maintainability.
Given these considerations, your Fetcher class is better suited for production-level deployments with its extended reliability and database efficiency features. It’s advisable to test under expected workloads and fine-tune parameters like semaphore limits and backoff delay to fit your specific use-case requirements.
# Circuit breaker settings
self.error_counts = defaultdict(int)
self.error_threshold = 5
self.circuit_breaker_timeout = 300 # 5 minutes
self.circuit_breakers = defaultdict(lambda: {'broken': False, 'reset_time': 0})
# Rate limiting
self.rate_limit = 1200 # requests per minute
self.request_times = []
# Websocket heartbeat
self.last_heartbeat = defaultdict(float)
self.heartbeat_interval = 30 # seconds
logger.debug(f"Initialized DataFetcher with symbols: {self.symbols}, timeframes: {self.timeframes}")
def _check_rate_limit(self) -> bool:
"""Check if we're within rate limits"""
current_time = time.time()
self.request_times = [t for t in self.request_times if current_time - t < 60]
if len(self.request_times) >= self.rate_limit:
return False
self.request_times.append(current_time)
return True
async def initialize_exchange(self):
await self.exchange.load_markets()
self.trading_pairs_info = await self._get_trading_pairs_info()
for symbol in self.symbols:
market = self.exchange.market(symbol)
ws_symbol = market['id'].lower()
self.symbol_map[ws_symbol] = symbol
for timeframe in self.timeframes:
self.streams.append(f"{ws_symbol}@kline_{timeframe}")
self.streams.append(f"{ws_symbol}@depth5@100ms")
# Create WebSocket URLs with stream batching
for i in range(0, len(self.streams), self.max_streams_per_connection):
stream_subset = self.streams[i:i + self.max_streams_per_connection]
url = f"wss://fstream.binance.com/stream?streams={'/'.join(stream_subset)}"
self.stream_urls.append(url)
logger.debug(f"WebSocket URLs: {self.stream_urls}")
async def _get_trading_pairs_info(self) -> Dict:
"""Fetch and cache trading pair information"""
async with aiohttp.ClientSession() as session:
async with session.get('https://fapi.binance.com/fapi/v1/exchangeInfo') as response:
data = await response.json()
return {symbol['symbol']: symbol for symbol in data['symbols']}
def _validate_timeframe_data(self, symbol: str, timeframe: str, df: pd.DataFrame) -> None:
"""Validate timeframe data for consistency and completeness"""
if df.empty:
raise DataValidationError(f"Empty dataframe for {symbol} {timeframe}")
# Check for required columns
required_columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
raise DataValidationError(f"Missing columns for {symbol} {timeframe}: {missing_columns}")
# Check for invalid values
numeric_columns = ['open', 'high', 'low', 'close', 'volume']
for col in numeric_columns:
if not np.isfinite(df[col]).all():
raise DataValidationError(f"Invalid {col} values found for {symbol} {timeframe}")
# Check price consistency
invalid_prices = (
(df['high'] < df['low']) |
(df['open'] > df['high']) |
(df['open'] < df['low']) |
(df['close'] > df['high']) |
(df['close'] < df['low'])
)
if invalid_prices.any():
invalid_rows = df[invalid_prices]
raise DataValidationError(
f"Price consistency violation for {symbol} {timeframe} at: {invalid_rows.index.tolist()}"
)
async def fetch_historical_data(self):
semaphore = asyncio.Semaphore(5)
tasks = []
for symbol in self.symbols:
for timeframe in self.timeframes:
tasks.append(self.fetch_symbol_historical_data(symbol, timeframe, semaphore))
await asyncio.gather(*tasks)
async def fetch_symbol_historical_data(self, symbol: str, timeframe: str, semaphore: asyncio.Semaphore):
async with semaphore:
try:
if not self._check_rate_limit():
logger.warning(f"Rate limit reached, delaying request for {symbol} {timeframe}")
await asyncio.sleep(1)
return
limit = 1000
latest_timestamp = await self.get_latest_kline_timestamp(symbol, timeframe)
# Determine fetch window
if latest_timestamp:
since = int(latest_timestamp.timestamp() * 1000) + 1
else:
# For initial fetch, get last 30 days of data
since = int((datetime.utcnow() - timedelta(days=30)).timestamp() * 1000)
all_bars = []
while True:
if self.circuit_breakers[symbol]['broken']:
if time.time() < self.circuit_breakers[symbol]['reset_time']:
logger.warning(f"Circuit breaker active for {symbol}, skipping fetch")
return
self.circuit_breakers[symbol]['broken'] = False
try:
bars = await self.exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=limit)
self.error_counts[symbol] = 0 # Reset error count on success
except Exception as e:
self.error_counts[symbol] += 1
if self.error_counts[symbol] >= self.error_threshold:
self.circuit_breakers[symbol]['broken'] = True
self.circuit_breakers[symbol]['reset_time'] = time.time() + self.circuit_breaker_timeout
logger.error(f"Circuit breaker triggered for {symbol}")
raise e
if not bars:
break
all_bars += bars
since = bars[-1][0] + 1
if len(bars) < limit:
break
if all_bars:
df = pd.DataFrame(all_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['timestamp'] = df['timestamp'].dt.tz_convert('Africa/Nairobi')
try:
self._validate_timeframe_data(symbol, timeframe, df)
except DataValidationError as e:
logger.error(f"Data validation error: {str(e)}")
return
# Check and fill gaps
gaps = await self.check_data_gaps(symbol, timeframe, df)
if gaps:
await self.fill_data_gaps(symbol, timeframe, gaps)
await self.save_klines(symbol, timeframe, df)
# Schedule next refresh
self.last_refresh_time[symbol][timeframe] = time.time()
except Exception as e:
logger.error(f"Error fetching data for {symbol} {timeframe}: {str(e)}\n{traceback.format_exc()}")
async def check_data_gaps(self, symbol: str, timeframe: str, df: pd.DataFrame) -> List[Tuple[datetime, datetime]]:
"""Check for gaps in data and return list of gap intervals"""
try:
timeframe_minutes = {
'1m': 1,
'5m': 5,
'15m': 15,
'1h': 60
}[timeframe]
expected_interval = pd.Timedelta(minutes=timeframe_minutes)
df = df.sort_values('timestamp')
# Calculate time differences between consecutive rows
time_diffs = df['timestamp'].diff()
gaps = []
for i, diff in enumerate(time_diffs[1:], 1):
if diff > expected_interval:
gap_start = df['timestamp'].iloc[i-1]
gap_end = df['timestamp'].iloc[i]
gap_size = int((gap_end - gap_start) / expected_interval) - 1
if gap_size >= self.gap_threshold:
gaps.append((gap_start, gap_end))
# Log gap details
logger.warning(
f"Data gap detected for {symbol} {timeframe}: "
f"From {gap_start} to {gap_end} ({gap_size} missing periods)"
)
# Store gap information in database
await self.save_gap_info(symbol, timeframe, gap_start, gap_end, gap_size)
return gaps
except Exception as e:
logger.error(f"Error checking data gaps: {str(e)}\n{traceback.format_exc()}")
return []
@sync_to_async
def save_gap_info(self, symbol: str, timeframe: str, start: datetime, end: datetime, size: int):
"""Save gap information to database"""
try:
DataGap.objects.create(
symbol=symbol,
timeframe=timeframe,
gap_start=start,
gap_end=end,
gap_size=size,
status='detected'
)
except Exception as e:
logger.error(f"Error saving gap info: {str(e)}")
async def fill_data_gaps(self, symbol: str, timeframe: str, gaps: List[Tuple[datetime, datetime]]):
"""Fill detected data gaps"""
for gap_start, gap_end in gaps:
try:
# Convert to milliseconds timestamp for the exchange API
since = int(gap_start.timestamp() * 1000)
end = int(gap_end.timestamp() * 1000)
gap_bars = []
while since < end:
if not self._check_rate_limit():
await asyncio.sleep(1)
continue
bars = await self.exchange.fetch_ohlcv(
symbol,
timeframe=timeframe,
since=since,
limit=1000
)
if not bars:
break
gap_bars.extend(bars)
since = bars[-1][0] + 1
if gap_bars:
df = pd.DataFrame(gap_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['timestamp'] = df['timestamp'].dt.tz_convert('Africa/Nairobi')
# Validate gap fill data
try:
self._validate_timeframe_data(symbol, timeframe, df)
await self.save_klines(symbol, timeframe, df)
# Update gap status
await self.update_gap_status(symbol, timeframe, gap_start, gap_end, 'filled')
logger.info(f"Successfully filled gap for {symbol} {timeframe} from {gap_start} to {gap_end}")
except DataValidationError as e:
logger.error(f"Gap fill data validation error: {str(e)}")
await self.update_gap_status(symbol, timeframe, gap_start, gap_end, 'failed_validation')
except Exception as e:
logger.error(f"Error filling gap for {symbol} {timeframe}: {str(e)}")
await self.update_gap_status(symbol, timeframe, gap_start, gap_end, 'failed')
@sync_to_async
def update_gap_status(self, symbol: str, timeframe: str, start: datetime, end: datetime, status: str):
"""Update the status of a data gap"""
try:
DataGap.objects.filter(
symbol=symbol,
timeframe=timeframe,
gap_start=start,
gap_end=end
).update(status=status, last_update=datetime.now())
except Exception as e:
logger.error(f"Error updating gap status: {str(e)}")
async def process_order_book_data(self, data):
try:
order_book_data = data['data']
ws_symbol = order_book_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timestamp = pd.to_datetime(order_book_data['T'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
# Validate order book data
bids = [[float(price), float(qty)] for price, qty in order_book_data['b']]
asks = [[float(price), float(qty)] for price, qty in order_book_data['a']]
if not self._validate_order_book(bids, asks):
logger.warning(f"Invalid order book data for {symbol} at {timestamp}")
return
# Calculate additional metrics for monitoring
spread = asks[0][0] - bids[0][0]
spread_percentage = (spread / bids[0][0]) * 100
total_bid_volume = sum(qty for _, qty in bids)
total_ask_volume = sum(qty for _, qty in asks)
# Alert on unusual conditions
if spread_percentage > 1.0: # More than 1% spread
logger.warning(f"Large spread detected for {symbol}: {spread_percentage:.2f}%")
if total_bid_volume == 0 or total_ask_volume == 0:
logger.warning(f"Zero volume detected for {symbol} in {'bids' if total_bid_volume == 0 else 'asks'}")
order_book = OrderBook(
symbol=symbol,
timestamp=timestamp,
bids=bids,
asks=asks,
spread=spread,
spread_percentage=spread_percentage,
total_bid_volume=total_bid_volume,
total_ask_volume=total_ask_volume
)
await self.save_order_book(order_book)
except Exception as e:
logger.error(f"Error processing order book data: {str(e)}\n{traceback.format_exc()}")
def _validate_order_book(self, bids: List[List[float]], asks: List[List[float]]) -> bool:
"""
Validate order book data for integrity and correctness
"""
try:
if not bids or not asks:
return False
# Check for minimum number of levels
if len(bids) < 5 or len(asks) < 5:
return False
# Validate price ordering (bids should be descending, asks ascending)
for i in range(1, len(bids)):
if bids[i][0] >= bids[i-1][0]:
return False
for i in range(1, len(asks)):
if asks[i][0] <= asks[i-1][0]:
return False
# Check for crossed book
if bids[0][0] >= asks[0][0]:
return False
# Validate quantities
for price, qty in bids + asks:
if qty <= 0 or not np.isfinite(qty) or not np.isfinite(price):
return False
return True
except Exception as e:
logger.error(f"Error validating order book: {str(e)}")
return False
@sync_to_async
def save_order_book(self, order_book):
try:
# Data validation
if not hasattr(order_book, 'symbol') or not order_book.symbol:
raise ValueError("Invalid symbol in order book")
if not hasattr(order_book, 'timestamp') or not order_book.timestamp:
raise ValueError("Invalid timestamp in order book")
# Additional validation checks
self._validate_order_book_for_storage(order_book)
OrderBook.objects.update_or_create(
symbol=order_book.symbol,
timestamp=order_book.timestamp,
defaults={
'bids': order_book.bids,
'asks': order_book.asks,
'spread': order_book.spread,
'spread_percentage': order_book.spread_percentage,
'total_bid_volume': order_book.total_bid_volume,
'total_ask_volume': order_book.total_ask_volume,
'last_updated': datetime.now()
}
)
logger.debug(f"Saved order book for {order_book.symbol} at {order_book.timestamp}")
except Exception as e:
logger.error(f"Error saving order book: {str(e)}\n{traceback.format_exc()}")
def _validate_order_book_for_storage(self, order_book):
"""Additional validation before storing order book data"""
try:
# Check data freshness
max_age = timedelta(minutes=5)
if datetime.now(order_book.timestamp.tzinfo) - order_book.timestamp > max_age:
raise ValueError("Order book data is too old")
# Validate spread calculations
calculated_spread = order_book.asks[0][0] - order_book.bids[0][0]
if abs(calculated_spread - order_book.spread) > 0.0001:
raise ValueError("Spread calculation mismatch")
# Check volume calculations
calc_bid_volume = sum(qty for _, qty in order_book.bids)
calc_ask_volume = sum(qty for _, qty in order_book.asks)
if abs(calc_bid_volume - order_book.total_bid_volume) > 0.0001:
raise ValueError("Bid volume calculation mismatch")
if abs(calc_ask_volume - order_book.total_ask_volume) > 0.0001:
raise ValueError("Ask volume calculation mismatch")
except Exception as e:
raise ValueError(f"Order book validation failed: {str(e)}")
async def handle_websocket(self, url):
retry_count = 0
max_retries = 5
last_message_time = time.time()
while True:
try:
async with websockets.connect(
url,
ping_interval=20,
ping_timeout=20,
close_timeout=10,
extra_headers={'User-Agent': 'BinanceDataFetcher/1.0'}
) as websocket:
logger.info(f"Connected to WebSocket: {url}")
retry_count = 0
# Initialize connection monitoring
last_message_time = time.time()
heartbeat_task = asyncio.create_task(
self._monitor_connection(websocket, url, last_message_time)
)
try:
async for message in websocket:
last_message_time = time.time()
try:
data = json.loads(message)
except json.JSONDecodeError as e:
logger.error(f"JSON decode error: {str(e)} for message: {message[:100]}...")
continue
if 'data' not in data:
continue
stream_type = data['stream'].split('@')[1]
if stream_type.startswith('kline'):
await self.process_kline_data(data)
elif stream_type.startswith('depth'):
await self.process_order_book_data(data)
except websockets.exceptions.ConnectionClosed:
logger.warning(f"WebSocket connection closed for {url}")
heartbeat_task.cancel()
raise
except (websockets.exceptions.ConnectionClosed,
websockets.exceptions.InvalidStatusCode,
asyncio.TimeoutError) as e:
retry_count += 1
wait_time = min(self.initial_delay * (self.exponential_base ** (retry_count - 1)),
self.max_delay)
if retry_count > max_retries:
logger.error(f"Max retries exceeded for {url}. Waiting 5 minutes before trying again.")
await asyncio.sleep(300)
retry_count = 0
else:
logger.warning(f"WebSocket error: {str(e)}. Retry {retry_count}/{max_retries} in {wait_time}s")
await asyncio.sleep(wait_time)
except Exception as e:
logger.error(f"Unexpected WebSocket error: {str(e)}\n{traceback.format_exc()}")
await asyncio.sleep(5)
async def _monitor_connection(self, websocket, url, last_message_time):
"""Monitor WebSocket connection health"""
while True:
try:
await asyncio.sleep(self.heartbeat_interval)
# Check if we've received messages recently
if time.time() - last_message_time > self.heartbeat_interval * 2:
logger.warning(f"No messages received for {self.heartbeat_interval * 2}s on {url}")
try:
await websocket.ping()
except:
logger.error(f"Ping failed for {url}, closing connection")
await websocket.close()
break
# Send ping to keep connection alive
await websocket.ping()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in connection monitoring: {str(e)}")
break
async def start_websockets(self):
"""Start all WebSocket connections with monitoring"""
tasks = []
for url in self.stream_urls:
tasks.append(asyncio.create_task(self.handle_websocket(url)))
# Add monitoring task
tasks.append(asyncio.create_task(self._monitor_data_freshness()))
await asyncio.gather(*tasks)
async def _monitor_data_freshness(self):
"""Monitor data freshness and trigger updates if needed"""
while True:
try:
current_time = time.time()
for symbol in self.symbols:
for timeframe in self.timeframes:
last_refresh = self.last_refresh_time[symbol][timeframe]
if current_time - last_refresh > self.refresh_interval:
logger.info(f"Triggering refresh for {symbol} {timeframe}")
await self.fetch_symbol_historical_data(
symbol,
timeframe,
asyncio.Semaphore(5)
)
await asyncio.sleep(300) # Check every 5 minutes
except Exception as e:
logger.error(f"Error in data freshness monitoring: {str(e)}")
await asyncio.sleep(60)
async def run(self):
"""Main run loop with enhanced error handling and monitoring"""
try:
logger.info("Starting DataFetcher...")
# Initialize exchange connection
await self.initialize_exchange()
logger.info("Exchange initialized successfully")
# Start monitoring tasks
monitoring_task = asyncio.create_task(self._monitor_system_health())
# Fetch initial historical data
logger.info("Fetching historical data...")
await self.fetch_historical_data()
# Start WebSocket connections
logger.info("Starting WebSocket connections...")
await self.start_websockets()
except Exception as e:
logger.error(f"Critical error in main run loop: {str(e)}\n{traceback.format_exc()}")
finally:
try:
await self.exchange.close()
logger.info("Exchange connection closed")
except Exception as e:
logger.error(f"Error closing exchange connection: {str(e)}")
async def _monitor_system_health(self):
"""Monitor overall system health"""
while True:
try:
# Monitor memory usage
process = psutil.Process(os.getpid())
memory_info = process.memory_info()
memory_percent = process.memory_percent()
if memory_percent > 80:
logger.warning(f"High memory usage: {memory_percent:.1f}%")
# Monitor CPU usage
cpu_percent = psutil.cpu_percent(interval=1)
if cpu_percent > 80:
logger.warning(f"High CPU usage: {cpu_percent:.1f}%")
# Log general health metrics
logger.info(
f"Health check - Memory: {memory_percent:.1f}%, "
f"CPU: {cpu_percent:.1f}%, "
f"Active connections: {len(self.streams)}"
)
await asyncio.sleep(60)
except Exception as e:
logger.error(f"Error in system health monitoring: {str(e)}")
await asyncio.sleep(60)
Type hints clarify expected inputs, and custom exceptions make error reporting more precise.
Production Readiness:
Robustness and Resilience:
The framework seems more robust and resilient, thanks to comprehensive error handling, validation, and monitoring.
Scalability:
Improved monitoring and resource control provide a good foundation for scaling, though scalability will depend on hardware and environment.
Completeness:
All critical components have been addressed, but ensure the implementation of external libraries like psutil are present and correctly configured.
Testing:
Ensure the system is thoroughly tested in a staging environment to mimic production load. This includes testing data integrity, performance, and fault tolerance across various network conditions.
Security:
Since this involves connecting to external services, ensure all API keys and secrets are stored securely and sensitive operations are reviewed.
Suggestions:
Integration: Consider integrating alerting systems for critical failures or resource overuse.
Audit Logging: Implement audit logging for significant operations to trace changes and transactions.
Deployment Consideration: Dockerization and orchestration handling for robust deployment strategies.
Documentation: Comprehensive documentation for maintainability, including class functions and expected behavior.
In conclusion, this code version shows excellent progress toward production readiness with its refined focus on resilience, data validation, and system monitoring. Ensure all external dependencies are managed, and continuous observation is maintained to further refine system reliability.
# Circuit breaker settings
self.error_counts = defaultdict(int)
self.error_threshold = 5
self.circuit_breaker_timeout = 300 # 5 minutes
self.circuit_breakers = defaultdict(lambda: {'broken': False, 'reset_time': 0})
# Rate limiting
self.rate_limit = 1200 # requests per minute
self.request_times = []
# Websocket heartbeat
self.last_heartbeat = defaultdict(float)
self.heartbeat_interval = 30 # seconds
logger.debug(f"Initialized DataFetcher with symbols: {self.symbols}, timeframes: {self.timeframes}")
def _check_rate_limit(self) -> bool:
"""Check if we're within rate limits"""
current_time = time.time()
self.request_times = [t for t in self.request_times if current_time - t < 60]
if len(self.request_times) >= self.rate_limit:
return False
self.request_times.append(current_time)
return True
async def initialize_exchange(self):
await self.exchange.load_markets()
self.trading_pairs_info = await self._get_trading_pairs_info()
for symbol in self.symbols:
market = self.exchange.market(symbol)
ws_symbol = market['id'].lower()
self.symbol_map[ws_symbol] = symbol
for timeframe in self.timeframes:
self.streams.append(f"{ws_symbol}@kline_{timeframe}")
self.streams.append(f"{ws_symbol}@depth5@100ms")
# Create WebSocket URLs with stream batching
for i in range(0, len(self.streams), self.max_streams_per_connection):
stream_subset = self.streams[i:i + self.max_streams_per_connection]
url = f"wss://fstream.binance.com/stream?streams={'/'.join(stream_subset)}"
self.stream_urls.append(url)
logger.debug(f"WebSocket URLs: {self.stream_urls}")
async def _get_trading_pairs_info(self) -> Dict:
"""Fetch and cache trading pair information"""
async with aiohttp.ClientSession() as session:
async with session.get('https://fapi.binance.com/fapi/v1/exchangeInfo') as response:
data = await response.json()
return {symbol['symbol']: symbol for symbol in data['symbols']}
def _validate_timeframe_data(self, symbol: str, timeframe: str, df: pd.DataFrame) -> None:
"""Validate timeframe data for consistency and completeness"""
if df.empty:
raise DataValidationError(f"Empty dataframe for {symbol} {timeframe}")
# Check for required columns
required_columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
raise DataValidationError(f"Missing columns for {symbol} {timeframe}: {missing_columns}")
# Check for invalid values
numeric_columns = ['open', 'high', 'low', 'close', 'volume']
for col in numeric_columns:
if not np.isfinite(df[col]).all():
raise DataValidationError(f"Invalid {col} values found for {symbol} {timeframe}")
# Check price consistency
invalid_prices = (
(df['high'] < df['low']) |
(df['open'] > df['high']) |
(df['open'] < df['low']) |
(df['close'] > df['high']) |
(df['close'] < df['low'])
)
if invalid_prices.any():
invalid_rows = df[invalid_prices]
raise DataValidationError(
f"Price consistency violation for {symbol} {timeframe} at: {invalid_rows.index.tolist()}"
)
async def fetch_historical_data(self):
semaphore = asyncio.Semaphore(5)
tasks = []
for symbol in self.symbols:
for timeframe in self.timeframes:
tasks.append(self.fetch_symbol_historical_data(symbol, timeframe, semaphore))
await asyncio.gather(*tasks)
async def fetch_symbol_historical_data(self, symbol: str, timeframe: str, semaphore: asyncio.Semaphore):
async with semaphore:
try:
if not self._check_rate_limit():
logger.warning(f"Rate limit reached, delaying request for {symbol} {timeframe}")
await asyncio.sleep(1)
return
limit = 1000
latest_timestamp = await self.get_latest_kline_timestamp(symbol, timeframe)
# Determine fetch window
if latest_timestamp:
since = int(latest_timestamp.timestamp() * 1000) + 1
else:
# For initial fetch, get last 30 days of data
since = int((datetime.utcnow() - timedelta(days=30)).timestamp() * 1000)
all_bars = []
while True:
if self.circuit_breakers[symbol]['broken']:
if time.time() < self.circuit_breakers[symbol]['reset_time']:
logger.warning(f"Circuit breaker active for {symbol}, skipping fetch")
return
self.circuit_breakers[symbol]['broken'] = False
try:
bars = await self.exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=limit)
self.error_counts[symbol] = 0 # Reset error count on success
except Exception as e:
self.error_counts[symbol] += 1
if self.error_counts[symbol] >= self.error_threshold:
self.circuit_breakers[symbol]['broken'] = True
self.circuit_breakers[symbol]['reset_time'] = time.time() + self.circuit_breaker_timeout
logger.error(f"Circuit breaker triggered for {symbol}")
raise e
if not bars:
break
all_bars += bars
since = bars[-1][0] + 1
if len(bars) < limit:
break
if all_bars:
df = pd.DataFrame(all_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['timestamp'] = df['timestamp'].dt.tz_convert('Africa/Nairobi')
try:
self._validate_timeframe_data(symbol, timeframe, df)
except DataValidationError as e:
logger.error(f"Data validation error: {str(e)}")
return
# Check and fill gaps
gaps = await self.check_data_gaps(symbol, timeframe, df)
if gaps:
await self.fill_data_gaps(symbol, timeframe, gaps)
await self.save_klines(symbol, timeframe, df)
# Schedule next refresh
self.last_refresh_time[symbol][timeframe] = time.time()
except Exception as e:
logger.error(f"Error fetching data for {symbol} {timeframe}: {str(e)}\n{traceback.format_exc()}")
async def check_data_gaps(self, symbol: str, timeframe: str, df: pd.DataFrame) -> List[Tuple[datetime, datetime]]:
"""Check for gaps in data and return list of gap intervals"""
try:
timeframe_minutes = {
'1m': 1,
'5m': 5,
'15m': 15,
'1h': 60
}[timeframe]
expected_interval = pd.Timedelta(minutes=timeframe_minutes)
df = df.sort_values('timestamp')
# Calculate time differences between consecutive rows
time_diffs = df['timestamp'].diff()
gaps = []
for i, diff in enumerate(time_diffs[1:], 1):
if diff > expected_interval:
gap_start = df['timestamp'].iloc[i-1]
gap_end = df['timestamp'].iloc[i]
gap_size = int((gap_end - gap_start) / expected_interval) - 1
if gap_size >= self.gap_threshold:
gaps.append((gap_start, gap_end))
# Log gap details
logger.warning(
f"Data gap detected for {symbol} {timeframe}: "
f"From {gap_start} to {gap_end} ({gap_size} missing periods)"
)
# Store gap information in database
await self.save_gap_info(symbol, timeframe, gap_start, gap_end, gap_size)
return gaps
except Exception as e:
logger.error(f"Error checking data gaps: {str(e)}\n{traceback.format_exc()}")
return []
@sync_to_async
def save_gap_info(self, symbol: str, timeframe: str, start: datetime, end: datetime, size: int):
"""Save gap information to database"""
try:
DataGap.objects.create(
symbol=symbol,
timeframe=timeframe,
gap_start=start,
gap_end=end,
gap_size=size,
status='detected'
)
except Exception as e:
logger.error(f"Error saving gap info: {str(e)}")
async def fill_data_gaps(self, symbol: str, timeframe: str, gaps: List[Tuple[datetime, datetime]]):
"""Fill detected data gaps"""
for gap_start, gap_end in gaps:
try:
# Convert to milliseconds timestamp for the exchange API
since = int(gap_start.timestamp() * 1000)
end = int(gap_end.timestamp() * 1000)
gap_bars = []
while since < end:
if not self._check_rate_limit():
await asyncio.sleep(1)
continue
bars = await self.exchange.fetch_ohlcv(
symbol,
timeframe=timeframe,
since=since,
limit=1000
)
if not bars:
break
gap_bars.extend(bars)
since = bars[-1][0] + 1
if gap_bars:
df = pd.DataFrame(gap_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df['timestamp'] = df['timestamp'].dt.tz_convert('Africa/Nairobi')
# Validate gap fill data
try:
self._validate_timeframe_data(symbol, timeframe, df)
await self.save_klines(symbol, timeframe, df)
# Update gap status
await self.update_gap_status(symbol, timeframe, gap_start, gap_end, 'filled')
logger.info(f"Successfully filled gap for {symbol} {timeframe} from {gap_start} to {gap_end}")
except DataValidationError as e:
logger.error(f"Gap fill data validation error: {str(e)}")
await self.update_gap_status(symbol, timeframe, gap_start, gap_end, 'failed_validation')
except Exception as e:
logger.error(f"Error filling gap for {symbol} {timeframe}: {str(e)}")
await self.update_gap_status(symbol, timeframe, gap_start, gap_end, 'failed')
@sync_to_async
def update_gap_status(self, symbol: str, timeframe: str, start: datetime, end: datetime, status: str):
"""Update the status of a data gap"""
try:
DataGap.objects.filter(
symbol=symbol,
timeframe=timeframe,
gap_start=start,
gap_end=end
).update(status=status, last_update=datetime.now())
except Exception as e:
logger.error(f"Error updating gap status: {str(e)}")
async def process_order_book_data(self, data):
try:
order_book_data = data['data']
ws_symbol = order_book_data['s'].lower()
symbol = self.symbol_map.get(ws_symbol)
timestamp = pd.to_datetime(order_book_data['T'], unit='ms', utc=True).tz_convert('Africa/Nairobi')
# Validate order book data
bids = [[float(price), float(qty)] for price, qty in order_book_data['b']]
asks = [[float(price), float(qty)] for price, qty in order_book_data['a']]
if not self._validate_order_book(bids, asks):
logger.warning(f"Invalid order book data for {symbol} at {timestamp}")
return
# Calculate additional metrics for monitoring
spread = asks[0][0] - bids[0][0]
spread_percentage = (spread / bids[0][0]) * 100
total_bid_volume = sum(qty for _, qty in bids)
total_ask_volume = sum(qty for _, qty in asks)
# Alert on unusual conditions
if spread_percentage > 1.0: # More than 1% spread
logger.warning(f"Large spread detected for {symbol}: {spread_percentage:.2f}%")
if total_bid_volume == 0 or total_ask_volume == 0:
logger.warning(f"Zero volume detected for {symbol} in {'bids' if total_bid_volume == 0 else 'asks'}")
order_book = OrderBook(
symbol=symbol,
timestamp=timestamp,
bids=bids,
asks=asks,
spread=spread,
spread_percentage=spread_percentage,
total_bid_volume=total_bid_volume,
total_ask_volume=total_ask_volume
)
await self.save_order_book(order_book)
except Exception as e:
logger.error(f"Error processing order book data: {str(e)}\n{traceback.format_exc()}")
def _validate_order_book(self, bids: List[List[float]], asks: List[List[float]]) -> bool:
"""
Validate order book data for integrity and correctness
"""
try:
if not bids or not asks:
return False
# Check for minimum number of levels
if len(bids) < 5 or len(asks) < 5:
return False
# Validate price ordering (bids should be descending, asks ascending)
for i in range(1, len(bids)):
if bids[i][0] >= bids[i-1][0]:
return False
for i in range(1, len(asks)):
if asks[i][0] <= asks[i-1][0]:
return False
# Check for crossed book
if bids[0][0] >= asks[0][0]:
return False
# Validate quantities
for price, qty in bids + asks:
if qty <= 0 or not np.isfinite(qty) or not np.isfinite(price):
return False
return True
except Exception as e:
logger.error(f"Error validating order book: {str(e)}")
return False
@sync_to_async
def save_order_book(self, order_book):
try:
# Data validation
if not hasattr(order_book, 'symbol') or not order_book.symbol:
raise ValueError("Invalid symbol in order book")
if not hasattr(order_book, 'timestamp') or not order_book.timestamp:
raise ValueError("Invalid timestamp in order book")
# Additional validation checks
self._validate_order_book_for_storage(order_book)
OrderBook.objects.update_or_create(
symbol=order_book.symbol,
timestamp=order_book.timestamp,
defaults={
'bids': order_book.bids,
'asks': order_book.asks,
'spread': order_book.spread,
'spread_percentage': order_book.spread_percentage,
'total_bid_volume': order_book.total_bid_volume,
'total_ask_volume': order_book.total_ask_volume,
'last_updated': datetime.now()
}
)
logger.debug(f"Saved order book for {order_book.symbol} at {order_book.timestamp}")
except Exception as e:
logger.error(f"Error saving order book: {str(e)}\n{traceback.format_exc()}")
def _validate_order_book_for_storage(self, order_book):
"""Additional validation before storing order book data"""
try:
# Check data freshness
max_age = timedelta(minutes=5)
if datetime.now(order_book.timestamp.tzinfo) - order_book.timestamp > max_age:
raise ValueError("Order book data is too old")
# Validate spread calculations
calculated_spread = order_book.asks[0][0] - order_book.bids[0][0]
if abs(calculated_spread - order_book.spread) > 0.0001:
raise ValueError("Spread calculation mismatch")
# Check volume calculations
calc_bid_volume = sum(qty for _, qty in order_book.bids)
calc_ask_volume = sum(qty for _, qty in order_book.asks)
if abs(calc_bid_volume - order_book.total_bid_volume) > 0.0001:
raise ValueError("Bid volume calculation mismatch")
if abs(calc_ask_volume - order_book.total_ask_volume) > 0.0001:
raise ValueError("Ask volume calculation mismatch")
except Exception as e:
raise ValueError(f"Order book validation failed: {str(e)}")
async def handle_websocket(self, url):
retry_count = 0
max_retries = 5
last_message_time = time.time()
while True:
try:
async with websockets.connect(
url,
ping_interval=20,
ping_timeout=20,
close_timeout=10,
extra_headers={'User-Agent': 'BinanceDataFetcher/1.0'}
) as websocket:
logger.info(f"Connected to WebSocket: {url}")
retry_count = 0
# Initialize connection monitoring
last_message_time = time.time()
heartbeat_task = asyncio.create_task(
self._monitor_connection(websocket, url, last_message_time)
)
try:
async for message in websocket:
last_message_time = time.time()
try:
data = json.loads(message)
except json.JSONDecodeError as e:
logger.error(f"JSON decode error: {str(e)} for message: {message[:100]}...")
continue
if 'data' not in data:
continue
stream_type = data['stream'].split('@')[1]
if stream_type.startswith('kline'):
await self.process_kline_data(data)
elif stream_type.startswith('depth'):
await self.process_order_book_data(data)
except websockets.exceptions.ConnectionClosed:
logger.warning(f"WebSocket connection closed for {url}")
heartbeat_task.cancel()
raise
except (websockets.exceptions.ConnectionClosed,
websockets.exceptions.InvalidStatusCode,
asyncio.TimeoutError) as e:
retry_count += 1
wait_time = min(self.initial_delay * (self.exponential_base ** (retry_count - 1)),
self.max_delay)
if retry_count > max_retries:
logger.error(f"Max retries exceeded for {url}. Waiting 5 minutes before trying again.")
await asyncio.sleep(300)
retry_count = 0
else:
logger.warning(f"WebSocket error: {str(e)}. Retry {retry_count}/{max_retries} in {wait_time}s")
await asyncio.sleep(wait_time)
except Exception as e:
logger.error(f"Unexpected WebSocket error: {str(e)}\n{traceback.format_exc()}")
await asyncio.sleep(5)
async def _monitor_connection(self, websocket, url, last_message_time):
"""Monitor WebSocket connection health"""
while True:
try:
await asyncio.sleep(self.heartbeat_interval)
# Check if we've received messages recently
if time.time() - last_message_time > self.heartbeat_interval * 2:
logger.warning(f"No messages received for {self.heartbeat_interval * 2}s on {url}")
try:
await websocket.ping()
except:
logger.error(f"Ping failed for {url}, closing connection")
await websocket.close()
break
# Send ping to keep connection alive
await websocket.ping()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in connection monitoring: {str(e)}")
break
async def start_websockets(self):
"""Start all WebSocket connections with monitoring"""
tasks = []
for url in self.stream_urls:
tasks.append(asyncio.create_task(self.handle_websocket(url)))
# Add monitoring task
tasks.append(asyncio.create_task(self._monitor_data_freshness()))
await asyncio.gather(*tasks)
async def _monitor_data_freshness(self):
"""Monitor data freshness and trigger updates if needed"""
while True:
try:
current_time = time.time()
for symbol in self.symbols:
for timeframe in self.timeframes:
last_refresh = self.last_refresh_time[symbol][timeframe]
if current_time - last_refresh > self.refresh_interval:
logger.info(f"Triggering refresh for {symbol} {timeframe}")
await self.fetch_symbol_historical_data(
symbol,
timeframe,
asyncio.Semaphore(5)
)
await asyncio.sleep(300) # Check every 5 minutes
except Exception as e:
logger.error(f"Error in data freshness monitoring: {str(e)}")
await asyncio.sleep(60)
async def run(self):
"""Main run loop with enhanced error handling and monitoring"""
try:
logger.info("Starting DataFetcher...")
# Initialize exchange connection
await self.initialize_exchange()
logger.info("Exchange initialized successfully")
# Start monitoring tasks
monitoring_task = asyncio.create_task(self._monitor_system_health())
# Fetch initial historical data
logger.info("Fetching historical data...")
await self.fetch_historical_data()
# Start WebSocket connections
logger.info("Starting WebSocket connections...")
await self.start_websockets()
except Exception as e:
logger.error(f"Critical error in main run loop: {str(e)}\n{traceback.format_exc()}")
finally:
try:
await self.exchange.close()
logger.info("Exchange connection closed")
except Exception as e:
logger.error(f"Error closing exchange connection: {str(e)}")
async def _monitor_system_health(self):
"""Monitor overall system health"""
while True:
try:
# Monitor memory usage
process = psutil.Process(os.getpid())
memory_info = process.memory_info()
memory_percent = process.memory_percent()
if memory_percent > 80:
logger.warning(f"High memory usage: {memory_percent:.1f}%")
# Monitor CPU usage
cpu_percent = psutil.cpu_percent(interval=1)
if cpu_percent > 80:
logger.warning(f"High CPU usage: {cpu_percent:.1f}%")
# Log general health metrics
logger.info(
f"Health check - Memory: {memory_percent:.1f}%, "
f"CPU: {cpu_percent:.1f}%, "
f"Active connections: {len(self.streams)}"
)
await asyncio.sleep(60)
except Exception as e:
logger.error(f"Error in system health monitoring: {str(e)}")
await asyncio.sleep(60)
Analyze code above and tell me what it does
Uses psutil to monitor CPU and memory usage of the running process, logging warnings if resource usage exceeds thresholds.
Provides insights into system performance, promoting proactive resource management.
Task Scheduling and Execution:
Uses asyncio to schedule tasks like fetching historical data, maintaining WebSocket connections, and performing system checks.
Monitors data freshness and triggers updates if data becomes stale.
Key Design Patterns and Techniques:
Asynchronous Programming: Leverages Python's asyncio to handle multiple network-bound tasks concurrently, allowing efficient handling of asynchronous I/O operations.
Robust Error Handling: Implements structured error handling for various potential failure points, including network errors, data validation failures, and database errors.
Connection and Resource Management: Uses heartbeats and retry logic for maintaining stable WebSocket connections and monitors system resource utilization to ensure smooth operation.
Data Integrity and Validation: Validates data before processing and storing it, ensuring that only accurate and consistent data is used for analysis.
Considerations for Production Use:
Thorough Testing: Make sure the code passes all tests in environments that mimic production. Check for edge cases and possible failures.
Security Checks: Properly secure API keys and ensure network communications are secure.
Error Handling: Ensure logging provides enough detail to diagnose issues quickly and effectively.
Performance Monitoring: Continually observe the application for performance bottlenecks or failures.
Scalability: Plan for scaling out the application depending on the load and number of symbols being monitored.
In essence, this script aims to provide a robust system for the continuous fetching and monitoring of cryptocurrency trading data from Binance, ensuring that the data is accurate and timely while preserving the overall health and performance of the system.
Objectives: Consider what you're aiming to achieve with the data (e.g., trading strategy, analysis, research), and if multiple sources can add value.
Technical Capability: Ensure that your team or system architecture can manage the increased complexity of handling multiple data streams.
Budget: Analyze the cost implications of expanding data sources in terms of both time and infrastructure.
Ultimately, using multiple exchanges can provide more comprehensive data and potentially more opportunities, but it comes at the cost of increased complexity and overhead. Analyze your specific context and goals to decide whether the benefits outweigh the challenges.
3. Performing the Analysis:
Once you retrieve the data, you can perform your order book and volume analysis using the Python analysis libraries of your choice, such as Pandas, NumPy, etc.
Order Book Analysis:
You might perform analysis on bid/ask spreads, liquidity within price levels, or trade pressure using the retrieved order book data.
Volume Analysis:
Calculate volume-based metrics like total traded volume, calculate averages, compare against historical price data.
Price Analysis:
Utilize kline data to perform technical analysis, track price movement trends, or detect patterns for trading signals.
4. Running the Analysis Script:
Ensure that both your DataFetcher and analysis scripts share access to the same Django project and database.
You can run the analysis script separately after sufficient data has been collected, trigger it on a schedule, or call it as part of a longer analysis pipeline where the data fetching and analysis happen sequentially or in parallel, depending on your setup needs.
Considerations:
Data Consistency: Ensure data consistency, especially if your data fetching is continuous and your analysis depends on historical accuracy.
Scalability: Consider the scalability of data retrieval operations, especially as the database grows in size.
Connection Management: Properly manage database connections and resources in your analysis script to ensure efficient operation.
By structuring your data access and analysis script around the persistent data stored by DataFetcher, you can perform centralized and efficient analysis on real-time and historical data.
Integration: Integrates well with other data science libraries like NumPy, SciPy, and Matplotlib.
Limitations:
Memory Consumption: As data is loaded into memory, it can become inefficient for very large datasets.
Scalability: Not suitable for datasets that don't fit into memory, unlike databases that handle disk-based operations.
When to Use Each
Django ORM: Use it when operating within a Django environment to work with your database for applications requiring secure, reliable, and scalable data persistence with enforced constraints (e.g., for web apps).
Pandas DataFrames: Use it when performing data analysis, transformation, or manipulation tasks that fit in memory. Ideal for exploratory data analysis, scientific computing, and when integrating with data science workflows.
Conclusion
For a robust application, consider using both tools in tandem:
Use Django ORM to handle high-volume, transactional data operations, and maintain data integrity.
Use Pandas to perform in-depth analysis and transformation on the datasets retrieved using ORM or directly from files/databases.
Both have their strengths in different areas of the data handling workflow, and understanding when to leverage each can lead to more efficient and maintainable codebases.
import pandas as pd
from .models import Kline, OrderBook
def get_order_book_dataframe(symbol, start_time, end_time):
order_books = OrderBook.objects.filter(
symbol=symbol,
timestamp__range=(start_time, end_time)
).values()
# Convert QuerySet to DataFrame
df = pd.DataFrame.from_records(order_books)
return df
# Perform your analysis on the DataFrame
df = get_order_book_dataframe('BTCUSDT', start_time, end_time)
# Example analysis
df['spread'] = df['asks'].apply(lambda x: x[0][0]) - df['bids'].apply(lambda x: x[0][0])
Data Pipeline:
Set up a data pipeline where:
The DataFetcher module continuously ingests data and stores it.
Analysis scripts pull data from the database, transform it using Pandas, and generate actionable insights.
Resource Management:
Ensure your system is equipped to handle the memory load caused by Pandas operations, especially with large datasets.
By combining Django ORM for durable data storage with Pandas for flexible analysis, you can efficiently manage both the integrity and the utility of your trading data. This setup allows you to benefit from the strengths of both technologies in your data-driven application.
Data Integrity: Your setup can benefit from the constraints, ACID properties, and security measures inherently provided by modern databases.
Conclusion
Use Django ORM to handle the primary ingestion and persistence of streaming data, ensuring that data is durably stored and consistently available.
Use Pandas DataFrames within your analysis scripts to load the required data from your ORM/database, perform the necessary analytics, and output results as needed.
This hybrid approach allows you to leverage the strengths of both technologies effectively.