import asyncio
import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime, timedelta
import json
from typing import List, Dict, Any
import pandas as pd
from decimal import Decimal
import time, os, django
from django.db import transaction
from django.utils import timezone
from zoneinfo import ZoneInfo
from asgiref.sync import sync_to_async
from binance.client import Client
from binance.exceptions import BinanceAPIException
import aiohttp
from concurrent.futures import ThreadPoolExecutor
import backoff
import sys
def setup_logging():
"""
Set up comprehensive logging with both console and file handlers.
"""
# Create logs directory if it doesn't exist
log_dir = 'logs'
os.makedirs(log_dir, exist_ok=True)
After making the modification it says
(myenv) PS D:\binbot\comber> python -m rajj.feda
Traceback (most recent call last):
File "", line 198, in _run_module_as_main
File "", line 88, in run_code
File "D:\binbot\comber\rajj\feda.py", line 1, in
from rajj.models import TradingPair
File "D:\binbot\comber\rajj\models.py", line 4, in
class TradingPair(models.Model):
File "D:\binbot\myenv\Lib\site-packages\django\db\models\base.py", line 129, in new
app_config = apps.get_containing_app_config(module)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\binbot\myenv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config
self.check_apps_ready()
File "D:\binbot\myenv\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready
settings.INSTALLED_APPS
File "D:\binbot\myenv\Lib\site-packages\django\conf_init.py", line 81, in getattr
self.setup(name)
File "D:\binbot\myenv\Lib\site-packages\django\conf_init.py", line 61, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Assistant
User
Something else, that code only fetch historical data but does not connect to websockets
Assistant
User
can it do all those tasks concurrently instead of waiting for each to complete
Assistant
init
code
@staticmethod
def make_nairobi_time(timestamp):
"""Convert timestamp to timezone-aware Nairobi time."""
if timestamp > 1e12: # Check if timestamp is in milliseconds
timestamp /= 1000
return datetime.fromtimestamp(timestamp, tz=NAIROBI_TIMEZONE)
async def initialize(self):
"""Initialize the data fetcher and load all USDT futures pairs."""
self.session = aiohttp.ClientSession()
try:
async with self.session.get(f"{BASE_URL}/fapi/v1/exchangeInfo") as response:
if response.status != 200:
raise Exception(f"HTTP {response.status}: {await response.text()}")
exchange_info = await response.json()
self.all_symbols = [
s['symbol'] for s in exchange_info['symbols']
if s['symbol'].endswith('USDT') and s['status'] == 'TRADING'
]
logger.info(f"Total loaded USDT futures pairs: {len(self.all_symbols)}")
except Exception as e:
logger.error(f"Error initializing Binance connection: {e}")
raise
async def fetch_historical_data(self):
"""Fetch historical data for all symbols concurrently with enhanced logging."""
# Create batches of symbols
symbol_batches = [
self.all_symbols[i:i+SYMBOLS_PER_BATCH]
for i in range(0, len(self.all_symbols), SYMBOLS_PER_BATCH)
]
logger.info(f"Starting historical data fetch for {len(self.all_symbols)} symbols")
logger.info(f"Will process in {len(symbol_batches)} batches of {SYMBOLS_PER_BATCH} symbols each")
# Create tasks for each batch
historical_tasks = []
for batch_num, batch in enumerate(symbol_batches, 1):
logger.info(f"Preparing batch {batch_num}: Symbols {batch}")
historical_tasks.append(self.fetch_batch_historical_klines(batch, batch_num))
# Execute all historical fetch tasks
await asyncio.gather(*historical_tasks)
logger.info("Completed historical data fetching for all symbols")
async def fetch_batch_historical_klines(self, symbols: List[str], batch_num: int):
"""Fetch historical klines for a batch of symbols with enhanced logging."""
from rajj.models import Kline
batch_tasks = []
for symbol in symbols:
for interval in TIMEFRAMES:
task = self.fetch_symbol_interval_klines(symbol, interval, batch_num)
batch_tasks.append(task)
logger.info(f"Batch {batch_num}: Initiating historical kline fetch for {len(symbols)} symbols across {len(TIMEFRAMES)} timeframes")
results = await asyncio.gather(*batch_tasks, return_exceptions=True)
# Log any exceptions
for result in results:
if isinstance(result, Exception):
logger.error(f"Exception in batch processing: {result}")
logger.info(f"Batch {batch_num}: Completed historical kline fetch")
async def fetch_symbol_interval_klines(self, symbol: str, interval: str, batch_num: int):
"""Fetch klines for a specific symbol and interval with advanced logging."""
from rajj.models import Kline
logger.info(f"Batch {batch_num}: Starting kline fetch for {symbol} at {interval} interval")
try:
# Get the last timestamp from the database
last_timestamp = await self.get_last_kline_timestamp(symbol, interval)
# Determine start time for fetching data
if last_timestamp:
start_time = int(last_timestamp.timestamp() * 1000) + 1
logger.info(f"{symbol} {interval}: Fetching data since last recorded timestamp {last_timestamp}")
else:
# If no data exists, fetch data for the last 7 days
end_time = int(time.time() * 1000)
start_time = end_time - (7 * 24 * 60 * 60 * 1000)
logger.info(f"{symbol} {interval}: No previous data found. Fetching last 7 days")
# Track number of klines saved
klines_saved = 0
# Fetch klines
async with self.session.get(f"{BASE_URL}/fapi/v1/klines", params={
'symbol': symbol,
'interval': interval,
'startTime': start_time,
'limit': MAX_HISTORICAL_FETCH_LIMIT
}) as response:
if response.status != 200:
error_text = await response.text()
logger.error(f"{symbol} {interval}: HTTP {response.status} - {error_text}")
raise Exception(f"HTTP {response.status}: {error_text}")
klines = await response.json()
# Process and save klines
for kline in klines:
kline_data = {
'symbol': symbol,
'timeframe': interval,
'timestamp': self.make_nairobi_time(kline[0]),
'open': Decimal(str(kline[1])),
'high': Decimal(str(kline[2])),
'low': Decimal(str(kline[3])),
'close': Decimal(str(kline[4])),
'volume': Decimal(str(kline[5]))
}
# Use get_or_create to avoid duplicates
_, created = await sync_to_async(Kline.objects.get_or_create)(
symbol=symbol,
timeframe=interval,
timestamp=kline_data['timestamp'],
defaults=kline_data
)
if created:
klines_saved += 1
logger.info(f"Batch {batch_num}: {symbol} {interval} - Processed {len(klines)} klines, saved {klines_saved} new entries")
except Exception as e:
logger.error(f"Batch {batch_num}: Error fetching/saving klines for {symbol} {interval}: {e}")
async def fetch_and_save_initial_orderbooks(self):
"""Fetch and save initial orderbooks for all symbols."""
from rajj.models import OrderBook
# Create batches of symbols
symbol_batches = [
self.all_symbols[i:i+SYMBOLS_PER_BATCH]
for i in range(0, len(self.all_symbols), SYMBOLS_PER_BATCH)
]
# Create tasks for each batch
orderbook_tasks = []
for batch in symbol_batches:
orderbook_tasks.append(self.fetch_batch_orderbooks(batch))
# Execute all orderbook fetch tasks
await asyncio.gather(*orderbook_tasks)
async def fetch_batch_orderbooks(self, symbols: List[str]):
"""Fetch orderbooks for a batch of symbols."""
from rajj.models import OrderBook
for symbol in symbols:
try:
# Check if orderbook already exists for this symbol
latest_orderbook = await sync_to_async(OrderBook.objects.filter(
symbol=symbol
).order_by('-timestamp').first)()
# Fetch current orderbook
async with self.session.get(f"{BASE_URL}/fapi/v1/depth", params={
'symbol': symbol,
'limit': 20 # Adjust limit as needed
}) as response:
if response.status != 200:
logger.error(f"Failed to fetch orderbook for {symbol}")
continue
data = await response.json()
bids = data.get('bids', [])
asks = data.get('asks', [])
# Calculate spread
if bids and asks:
first_bid_price = Decimal(str(bids[0][0]))
first_ask_price = Decimal(str(asks[0][0]))
spread = first_ask_price - first_bid_price
spread_percentage = (spread / first_ask_price) * 100
# Use Nairobi time
current_time = timezone.now().astimezone(NAIROBI_TIMEZONE)
orderbook_data = {
'symbol': symbol,
'timestamp': current_time,
'last_updated': current_time,
'bids': json.dumps(bids),
'asks': json.dumps(asks),
'spread': spread,
'spread_percentage': spread_percentage,
'total_bid_volume': sum(Decimal(str(bid[1])) for bid in bids),
'total_ask_volume': sum(Decimal(str(ask[1])) for ask in asks)
}
# Create orderbook entry if it doesn't exist or is significantly different
await sync_to_async(OrderBook.objects.create)(**orderbook_data)
except Exception as e:
logger.error(f"Error processing orderbook for {symbol}: {e}")
async def connect_websockets(self):
"""
Establish WebSocket connections in batches for all symbols.
"""
# Create batches of symbols
symbol_batches = [
self.all_symbols[i:i+SYMBOLS_PER_BATCH]
for i in range(0, len(self.all_symbols), SYMBOLS_PER_BATCH)
]
# Create WebSocket connection tasks for each batch
websocket_tasks = []
for batch in symbol_batches:
websocket_tasks.append(self.create_websocket_connection(batch))
# Run WebSocket connections concurrently
await asyncio.gather(*websocket_tasks)
async def create_websocket_connection(self, symbols: List[str]):
"""Create a WebSocket connection for a batch of symbols."""
# Prepare streams for the batch of symbols
streams = []
for symbol in symbols:
# Add kline streams for each timeframe
streams.extend([
f"{symbol.lower()}@kline_{interval}" for interval in TIMEFRAMES
])
# Add depth stream
streams.append(f"{symbol.lower()}@depth")
# Combine streams into a single WebSocket connection
ws_url = f"{WS_URL}/stream?streams={'/'.join(streams)}"
try:
async with aiohttp.ClientSession().ws_connect(ws_url) as ws:
logger.info(f"WebSocket connected for {len(symbols)} symbols")
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await self.handle_websocket_message(json.loads(msg.data))
elif msg.type == aiohttp.WSMsgType.CLOSED:
logger.warning(f"WebSocket closed for batch {symbols}")
break
elif msg.type == aiohttp.WSMsgType.ERROR:
logger.error(f"WebSocket error for batch {symbols}")
break
except Exception as e:
logger.error(f"WebSocket connection error for batch {symbols}: {e}")
async def handle_websocket_message(self, msg):
"""Handle incoming websocket messages."""
try:
# Extract the actual data from the WebSocket message
data = msg.get('data', {})
# Determine message type
event_type = data.get('e')
if event_type == 'kline':
await self.process_kline_message(data)
elif event_type == 'depthUpdate':
await self.process_depth_message(data)
except Exception as e:
logger.error(f"Error processing websocket message: {e}")
async def process_kline_message(self, msg):
"""Process kline websocket message."""
from rajj.models import Kline
try:
kline = msg.get('k', {})
symbol = msg.get('s')
if not kline or not symbol:
return
kline_data = {
'symbol': symbol,
'timeframe': kline.get('i'),
'timestamp': self.make_nairobi_time(kline.get('t')),
'open': Decimal(str(kline.get('o', 0))),
'high': Decimal(str(kline.get('h', 0))),
'low': Decimal(str(kline.get('l', 0))),
'close': Decimal(str(kline.get('c', 0))),
'volume': Decimal(str(kline.get('v', 0)))
}
# Ensure all required data is present
if all(kline_data.values()):
await sync_to_async(Kline.objects.get_or_create)(
symbol=kline_data['symbol'],
timeframe=kline_data['timeframe'],
timestamp=kline_data['timestamp'],
defaults=kline_data
)
except Exception as e:
logger.error(f"Error processing kline message: {e}")
async def process_depth_message(self, msg):
"""Process depth (orderbook) websocket message."""
from rajj.models import OrderBook
try:
symbol = msg.get('s')
bids = msg.get('b', [])
asks = msg.get('a', [])
if not bids or not asks:
return
# Convert bid and ask prices to decimals
first_bid_price = Decimal(str(bids[0][0]))
first_ask_price = Decimal(str(asks[0][0]))
spread = first_ask_price - first_bid_price
spread_percentage = (spread / first_ask_price) * 100
# Use Nairobi time
current_time = timezone.now().astimezone(NAIROBI_TIMEZONE)
orderbook_data = {
'symbol': symbol,
'timestamp': current_time,
'last_updated': current_time,
'bids': json.dumps(bids),
'asks': json.dumps(asks),
'spread': spread,
'spread_percentage': spread_percentage,
'total_bid_volume': sum(Decimal(str(bid[1])) for bid in bids),
'total_ask_volume': sum(Decimal(str(ask[1])) for ask in asks)
}
await sync_to_async(OrderBook.objects.create)(**orderbook_data)
except Exception as e:
logger.error(f"Error processing depth message: {e}")
async def get_last_kline_timestamp(self, symbol: str, interval: str):
"""
Retrieve the last kline timestamp for a specific symbol and interval.
Returns None if no klines exist.
"""
from rajj.models import Kline
last_kline = await sync_to_async(Kline.objects.filter(
symbol=symbol,
timeframe=interval
).order_by('-timestamp').first)()
return last_kline.timestamp if last_kline else None
async def run(self):
"""Main execution method."""
try:
# Initialize and load all symbols
await self.initialize()
# Fetch historical klines concurrently
logger.info("Fetching historical klines...")
await self.fetch_historical_data()
# Fetch and save initial orderbooks
logger.info("Fetching initial orderbooks...")
await self.fetch_and_save_initial_orderbooks()
# Connect to WebSockets
logger.info("Connecting to WebSockets...")
await self.connect_websockets()
except Exception as e:
logger.error(f"Error in main execution: {e}")
async def cleanup(self):
"""Cleanup resources."""
if self.session:
await self.session.close()
if name == "main":
fetcher = BinanceDataFetcher()
try:
asyncio.run(fetcher.run())
except KeyboardInterrupt:
logger.info("Shutting down...")
asyncio.run(fetcher.cleanup())
except Exception as e:
logger.error(f"Fatal error: {e}")
asyncio.run(fetcher.cleanup())
The code above is supposed to fetch and store data as well as connecting to websockets. When I run it it runs successfully and fetch over 300 symbols. The code below is supposed to use the symbols fetched and use realtime data to perform technical analysis and generate signals. however, when I run the code it says 0 symbols fetched. It only show
(myenv) PS D:\binbot\comber> python -m rajj.tean
2024-12-03 14:49:18 [INFO] CryptoBot initialized with timeframes: ['1m', '5m', '15m', '1h'] and num_candles: 500
2024-12-03 14:49:18 [INFO] Starting bot cycle...
2024-12-03 14:49:18 [INFO] Fetched 0 symbols.
2024-12-03 14:49:18 [INFO] Bot cycle complete. Sleeping for 59.90007185935974 seconds.
Please analyze the above code for fetching data and analyze the code below for performing technical analysis, and tell me why it is not working and assist in debugging.
technical_analysis.py
import asyncio
import logging
import time
from typing import Dict, List, Tuple
from datetime import timedelta
from asgiref.sync import sync_to_async
import pandas as pd
import numpy as np
from ta.momentum import (
RSIIndicator,
StochasticOscillator,
)
from ta.trend import (
ADXIndicator,
MACD,
SMAIndicator,
)
from ta.volatility import BollingerBands, AverageTrueRange
from functools import wraps
Django setup
import os
import django
from django.utils import timezone
Global settings for retry mechanism and circuit breaker
MAX_RETRIES = 5
CIRCUIT_BREAKER_THRESHOLD = 3 # Number of consecutive failures before opening the circuit
CIRCUIT_BREAKER_TIMEOUT = 60 # Time in seconds to keep the circuit open
def retry_with_exponential_backoff(coroutine):
"""
Decorator for retrying a coroutine with exponential backoff.
"""
@wraps(coroutine)
async def wrapper(*args, **kwargs):
retries = 0
delay = 1
while retries < MAX_RETRIES:
try:
result = await coroutine(*args, **kwargs)
return result
except Exception as e:
retries += 1
logger.warning(f"Retry {retries}/{MAX_RETRIES} for {coroutine.name}: {e}")
await asyncio.sleep(delay)
delay *= 2 # Exponential backoff
logger.error(f"Max retries exceeded for {coroutine.name}")
raise Exception(f"Max retries exceeded for {coroutine.name}")
return wrapper
class CircuitBreaker:
"""
A simple circuit breaker implementation.
"""
failure_count = 0
circuit_open = False
last_failure_time = None
code
@staticmethod
def call(func):
@wraps(func)
async def wrapper(*args, **kwargs):
if CircuitBreaker.circuit_open:
elapsed_time = time.time() - CircuitBreaker.last_failure_time
if elapsed_time > CIRCUIT_BREAKER_TIMEOUT:
CircuitBreaker.circuit_open = False
CircuitBreaker.failure_count = 0
logger.info("Circuit breaker closed, resuming operation.")
else:
logger.error("Circuit breaker is open. Call rejected.")
raise Exception("Circuit breaker is open.")
try:
result = await func(*args, **kwargs)
CircuitBreaker.failure_count = 0 # Reset on success
return result
except Exception as e:
CircuitBreaker.failure_count += 1
CircuitBreaker.last_failure_time = time.time()
if CircuitBreaker.failure_count >= CIRCUIT_BREAKER_THRESHOLD:
CircuitBreaker.circuit_open = True
logger.error("Circuit breaker opened due to repeated failures.")
raise e
return wrapper
class CryptoBot:
def init(
self,
timeframes: List[str] = ["1m", "5m", "15m", "1h"],
num_candles: int = 500,
):
self.timeframes = timeframes
self.num_candles = num_candles
logger.info(
"CryptoBot initialized with timeframes: %s and num_candles: %d",
timeframes,
num_candles,
)
code
@retry_with_exponential_backoff
async def get_symbols(self) -> List[str]:
"""
Asynchronously fetch trading pair symbols.
"""
symbols = await sync_to_async(list)(
TradingPair.objects.values_list("symbol", flat=True)
)
return [symbol for symbol in symbols if symbol] # Filter out empty strings
@retry_with_exponential_backoff
async def get_candles_df(self, symbol: str, timeframe: str) -> pd.DataFrame:
"""
Fetches the most recent `num_candles` records for the specified trading pair and timeframe.
Includes data preprocessing to handle missing values and outliers.
"""
try:
# Use sync_to_async to perform synchronous database query in an async context
klines = await sync_to_async(list)(
Kline.objects.filter(symbol=symbol, timeframe=timeframe)
.order_by("-timestamp")[: self.num_candles]
.values()
)
if not klines:
logger.warning(f"No candles found for {symbol} ({timeframe})")
return pd.DataFrame()
df = pd.DataFrame.from_records(klines)
df["timestamp"] = pd.to_datetime(df["timestamp"])
df.set_index("timestamp", inplace=True)
df.sort_index(inplace=True) # Ensure chronological order for analysis
# Data preprocessing
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df.fillna(method="ffill", inplace=True) # Forward-fill missing values
df.dropna(inplace=True) # Drop any remaining NaNs
# Outlier detection and handling using Z-score
z_scores = ((df - df.mean()) / df.std()).abs()
df = df[(z_scores < 3).all(axis=1)]
return df
except Exception as e:
logger.error(f"Error fetching candles for {symbol} ({timeframe}): {e}")
raise
async def calculate_technical_indicators_set1(self, df: pd.DataFrame) -> pd.DataFrame:
"""
Calculates the first set of technical indicators and adds them to the DataFrame.
"""
try:
# First set of indicators
df["rsi"] = RSIIndicator(close=df["close"], window=14).rsi()
macd = MACD(
close=df["close"], window_slow=26, window_fast=12, window_sign=9
)
df["macd"] = macd.macd()
df["macd_signal"] = macd.macd_signal()
df["sma_fast"] = SMAIndicator(close=df["close"], window=14).sma_indicator()
df["sma_slow"] = SMAIndicator(close=df["close"], window=28).sma_indicator()
bollinger = BollingerBands(
close=df["close"], window=20, window_dev=2
)
df["bollinger_mavg"] = bollinger.bollinger_mavg()
df["bollinger_hband"] = bollinger.bollinger_hband()
df["bollinger_lband"] = bollinger.bollinger_lband()
# Additional preprocessing
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df.fillna(method="ffill", inplace=True)
df.dropna(inplace=True)
return df
except Exception as e:
logger.error(f"Error calculating indicators set 1: {e}")
raise
async def calculate_technical_indicators_set2(self, df: pd.DataFrame) -> pd.DataFrame:
"""
Calculates the second set of technical indicators with advanced volatility and trend indicators.
"""
try:
# Stochastic Oscillator
stoch = StochasticOscillator(
high=df["high"], low=df["low"], close=df["close"], window=14, smooth_window=3
)
df["stoch_k"] = stoch.stoch()
df["stoch_d"] = stoch.stoch_signal()
# RVI
df["rvi"] = self.calculate_rvi(df)
# Advanced Trend and Volatility Indicators
# ADX for trend strength
adx_indicator = ADXIndicator(
high=df["high"], low=df["low"], close=df["close"], window=14
)
df["adx"] = adx_indicator.adx()
df["adx_pos"] = adx_indicator.adx_pos()
df["adx_neg"] = adx_indicator.adx_neg()
# ATR for volatility
atr = AverageTrueRange(
high=df["high"], low=df["low"], close=df["close"], window=14
)
df["atr"] = atr.average_true_range()
# Volatility Bands (more advanced than Keltner Channels)
df["upper_volatility_band"] = df["close"] + (df["atr"] * 2)
df["lower_volatility_band"] = df["close"] - (df["atr"] * 2)
# Directional Movement Index (DMI)
df["plus_di"] = adx_indicator.adx_pos()
df["minus_di"] = adx_indicator.adx_neg()
# Additional preprocessing
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df.fillna(method="ffill", inplace=True)
df.dropna(inplace=True)
return df
except Exception as e:
logger.error(f"Error calculating indicators set 2: {e}")
raise
def calculate_rvi(self, df: pd.DataFrame) -> pd.Series:
"""
Calculates the Relative Vigor Index (RVI).
"""
close_open = df["close"] - df["open"]
high_low = df["high"] - df["low"]
numerator = close_open.rolling(window=10).mean()
denominator = high_low.rolling(window=10).mean()
rvi = numerator / denominator
return rvi
@CircuitBreaker.call
async def generate_signal_set(
self,
symbol: str,
timeframe: str,
higher_timeframe: str = "1h",
lower_timeframe: str = "15m",
set_number: int = 1
) -> Tuple[str, Dict[str, float]]:
"""
Generates signal for a given set of indicators.
"""
try:
df = await self.get_candles_df(symbol, timeframe)
if df.empty:
return "No Signal", {}
if set_number == 1:
df_set = await self.calculate_technical_indicators_set1(df.copy())
else:
df_set = await self.calculate_technical_indicators_set2(df.copy())
# Get higher timeframe data for trend confirmation
higher_df = await self.get_candles_df(symbol, higher_timeframe)
if higher_df.empty:
return "No Signal", {}
if set_number == 1:
higher_df = await self.calculate_technical_indicators_set1(higher_df)
else:
higher_df = await self.calculate_technical_indicators_set2(higher_df)
# Get lower timeframe data for additional confirmation
lower_df = await self.get_candles_df(symbol, lower_timeframe)
if lower_df.empty:
return "No Signal", {}
if set_number == 1:
lower_df = await self.calculate_technical_indicators_set1(lower_df)
else:
lower_df = await self.calculate_technical_indicators_set2(lower_df)
current_price = df["close"].iloc[-1]
current_time = pd.Timestamp.now()
# Calculate 24h change
change_24h = self.calculate_24h_change(df)
# Generate signals
if set_number == 1:
signal, reasons = self.generate_signal_from_set1(df_set, higher_df, lower_df)
# Determine market regime
market_regime = self.determine_market_regime(higher_df)
else:
signal, reasons = self.generate_signal_from_set2(df_set, higher_df, lower_df)
# Determine market regime
market_regime = self.determine_market_regime(higher_df)
# Calculate support and resistance
support_level, resistance_level = self.calculate_support_and_resistance(df)
# Calculate stop-loss and take-profit
stop_loss, take_profit = self.calculate_stop_loss_take_profit(
signal, current_price, df
)
# Determine risk-reward ratio
risk_reward_ratio = self.calculate_risk_reward_ratio(
signal, current_price, stop_loss, take_profit
)
# Determine the result (Won, Lost, Pending)
result = "Pending" # Since real-time price movement is needed
# Initial success rate and win probability
success_rate = 50 # Base success rate
win_probability = success_rate # For now, set equal to success rate
# Prepare additional info
additional_info = {
"reasons": reasons,
"support_level": support_level,
"resistance_level": resistance_level,
}
metrics = {
"timestamp": df.index[-1],
"symbol": symbol,
"price": current_price,
"price_change_24h": change_24h,
"signal": signal,
"stop_loss": stop_loss,
"take_profit": take_profit,
"success_rate": success_rate,
"win_probability": win_probability,
"risk_reward_ratio": risk_reward_ratio,
"market_regime": market_regime,
"result": result,
"additional_info": additional_info,
}
logger.info(
f"Generated signal for {symbol} ({timeframe}) Set {set_number}: {signal}"
)
return signal, metrics
except Exception as e:
logger.error(f"Error generating signal for {symbol} ({timeframe}): {str(e)}")
raise
def calculate_24h_change(self, df: pd.DataFrame) -> float:
"""
Calculates the percentage change over the last 24 hours.
"""
try:
current_time = df.index[-1]
past_time = current_time - timedelta(hours=24)
past_price = df[df.index >= past_time]["close"].iloc[0]
current_price = df["close"].iloc[-1]
change = ((current_price - past_price) / past_price) * 100
return round(change, 2)
except Exception as e:
logger.error(f"Error calculating 24h change: {e}")
return 0.0
def generate_signal_from_set1(
self, df: pd.DataFrame, higher_df: pd.DataFrame, lower_df: pd.DataFrame
) -> Tuple[str, List[str]]:
"""
Generates signal based on the first set of indicators.
"""
signal_strength = 0
reasons = []
# RSI
rsi = df["rsi"].iloc[-1]
if rsi < 30:
signal_strength += 1
reasons.append("RSI indicates oversold conditions.")
elif rsi > 70:
signal_strength -= 1
reasons.append("RSI indicates overbought conditions.")
# RSI Divergence
if self.detect_rsi_divergence(df):
signal_strength += 1
reasons.append("Bullish RSI divergence detected.")
# MACD crossover
if df["macd"].iloc[-1] > df["macd_signal"].iloc[-1]:
signal_strength += 1
reasons.append("MACD bullish crossover.")
elif df["macd"].iloc[-1] < df["macd_signal"].iloc[-1]:
signal_strength -= 1
reasons.append("MACD bearish crossover.")
# SMA crossover
if df["sma_fast"].iloc[-1] > df["sma_slow"].iloc[-1]:
signal_strength += 1
reasons.append("SMA bullish crossover.")
elif df["sma_fast"].iloc[-1] < df["sma_slow"].iloc[-1]:
signal_strength -= 1
reasons.append("SMA bearish crossover.")
# Bollinger Bands
if df["close"].iloc[-1] < df["bollinger_lband"].iloc[-1]:
signal_strength += 1
reasons.append("Price below Bollinger lower band.")
elif df["close"].iloc[-1] > df["bollinger_hband"].iloc[-1]:
signal_strength -= 1
reasons.append("Price above Bollinger upper band.")
# Higher timeframe trend confirmation
if higher_df["sma_fast"].iloc[-1] > higher_df["sma_slow"].iloc[-1]:
signal_strength += 1
reasons.append("Higher timeframe trend is bullish.")
else:
signal_strength -= 1
reasons.append("Higher timeframe trend is bearish.")
# Lower timeframe momentum
if lower_df["rsi"].iloc[-1] > 50:
signal_strength += 1
reasons.append("Lower timeframe momentum is bullish.")
else:
signal_strength -= 1
reasons.append("Lower timeframe momentum is bearish.")
signal = self.determine_signal(signal_strength)
return signal, reasons
def generate_signal_from_set2(
self, df: pd.DataFrame, higher_df: pd.DataFrame, lower_df: pd.DataFrame
) -> Tuple[str, List[str]]:
"""
Generates signal based on the advanced second set of indicators.
"""
signal_strength = 0
reasons = []
# Stochastic Oscillator
stoch_k = df["stoch_k"].iloc[-1]
stoch_d = df["stoch_d"].iloc[-1]
# Advanced trend strength analysis
adx = df["adx"].iloc[-1]
plus_di = df["plus_di"].iloc[-1]
minus_di = df["minus_di"].iloc[-1]
atr = df["atr"].iloc[-1]
# Stochastic analysis with more nuanced conditions
if stoch_k < 20 and stoch_k > stoch_d:
signal_strength += 2
reasons.append("Strong bullish Stochastic Oscillator signal in oversold territory.")
elif stoch_k > 80 and stoch_k < stoch_d:
signal_strength -= 2
reasons.append("Strong bearish Stochastic Oscillator signal in overbought territory.")
# Advanced trend strength evaluation
if adx > 25: # Strong trend
if plus_di > minus_di:
signal_strength += 2
reasons.append("Strong bullish trend confirmed by ADX and Directional Indicators.")
else:
signal_strength -= 2
reasons.append("Strong bearish trend confirmed by ADX and Directional Indicators.")
else:
reasons.append("Weak trend strength, market might be ranging.")
# Volatility-based analysis
if df["close"].iloc[-1] < df["lower_volatility_band"].iloc[-1]:
signal_strength += 1
reasons.append("Price near lower volatility band, potential bounce.")
elif df["close"].iloc[-1] > df["upper_volatility_band"].iloc[-1]:
signal_strength -= 1
reasons.append("Price near upper volatility band, potential reversal.")
# RVI momentum
if df["rvi"].iloc[-1] > 0:
signal_strength += 1
reasons.append("RVI indicates positive momentum.")
else:
signal_strength -= 1
reasons.append("RVI indicates negative momentum.")
# Volatility expansion/contraction
prev_atr = df["atr"].iloc[-2]
if atr > prev_atr * 1.5:
signal_strength += 1
reasons.append("Volatility expansion detected, potential significant move.")
elif atr < prev_atr * 0.5:
signal_strength -= 1
reasons.append("Volatility contraction detected, potential range-bound market.")
# Higher and lower timeframe confirmations
higher_adx = higher_df["adx"].iloc[-1]
higher_plus_di = higher_df["plus_di"].iloc[-1]
higher_minus_di = higher_df["minus_di"].iloc[-1]
if higher_adx > 25 and higher_plus_di > higher_minus_di:
signal_strength += 1
reasons.append("Higher timeframe trend is strongly bullish.")
elif higher_adx > 25 and higher_plus_di < higher_minus_di:
signal_strength -= 1
reasons.append("Higher timeframe trend is strongly bearish.")
signal = self.determine_signal(signal_strength)
return signal, reasons
def detect_rsi_divergence(self, df: pd.DataFrame) -> bool:
"""
Detects bullish RSI divergence.
"""
try:
# Price makes lower lows
price_diff = df["close"].iloc[-2] - df["close"].iloc[-1]
# RSI makes higher lows
rsi_diff = df["rsi"].iloc[-1] - df["rsi"].iloc[-2]
if price_diff > 0 and rsi_diff > 0:
return True
else:
return False
except Exception as e:
logger.error(f"Error detecting RSI divergence: {e}")
return False
def determine_signal(self, signal_strength: int) -> str:
"""
Determines the signal based on signal strength.
"""
if signal_strength >= 4:
signal = "STRONG BUY"
elif signal_strength == 3:
signal = "BUY"
elif signal_strength == 2:
signal = "WEAK BUY"
elif signal_strength <= -4:
signal = "STRONG SELL"
elif signal_strength == -3:
signal = "SELL"
elif signal_strength == -2:
signal = "WEAK SELL"
else:
signal = "NO_SIGNAL"
return signal
def determine_market_regime(self, higher_df: pd.DataFrame) -> str:
"""
Determines the market regime based on higher timeframe trends.
"""
if higher_df["sma_fast"].iloc[-1] > higher_df["sma_slow"].iloc[-1]:
return "Bullish"
elif higher_df["sma_fast"].iloc[-1] < higher_df["sma_slow"].iloc[-1]:
return "Bearish"
else:
return "Neutral"
def calculate_support_and_resistance(self, df: pd.DataFrame) -> Tuple[float, float]:
"""
Calculates support and resistance levels as the recent lows and highs.
"""
try:
recent_lows = df["low"].rolling(window=20, min_periods=1).min()
recent_highs = df["high"].rolling(window=20, min_periods=1).max()
support_level = recent_lows.iloc[-1]
resistance_level = recent_highs.iloc[-1]
return support_level, resistance_level
except Exception as e:
logger.error(f"Error calculating support and resistance: {str(e)}")
return (
df["low"].iloc[-1],
df["high"].iloc[-1],
) # Fallback to last row values in case of error.
def calculate_stop_loss_take_profit(
self, signal: str, current_price: float, df: pd.DataFrame
) -> Tuple[float, float]:
"""
Uses ATR to calculate dynamic stop-loss and take-profit levels based on volatility.
"""
try:
atr = AverageTrueRange(
high=df["high"], low=df["low"], close=df["close"], window=14
).average_true_range().iloc[-1]
risk_to_reward_ratio = 1.5 # Desired risk-to-reward ratio
if signal in ["BUY", "STRONG BUY", "WEAK BUY"]:
stop_loss = current_price - (atr * 1.5)
take_profit = current_price + (atr * 1.5 * risk_to_reward_ratio)
elif signal in ["SELL", "STRONG SELL", "WEAK SELL"]:
stop_loss = current_price + (atr * 1.5)
take_profit = current_price - (atr * 1.5 * risk_to_reward_ratio)
else:
stop_loss = current_price - (atr * 2)
take_profit = current_price + (atr * 2)
return round(stop_loss, 8), round(take_profit, 8)
except Exception as e:
logger.error(f"Error calculating stop-loss and take-profit: {e}")
return current_price, current_price
def calculate_risk_reward_ratio(
self, signal: str, price: float, stop_loss: float, take_profit: float
) -> float:
"""
Calculates the risk-reward ratio.
"""
try:
if signal in ["BUY", "STRONG BUY", "WEAK BUY"]:
risk = price - stop_loss
reward = take_profit - price
elif signal in ["SELL", "STRONG SELL", "WEAK SELL"]:
risk = stop_loss - price
reward = price - take_profit
else:
return None
if risk == 0:
return None
ratio = reward / risk
return round(ratio, 2)
except Exception as e:
logger.error(f"Error calculating risk-reward ratio: {e}")
return None
@retry_with_exponential_backoff
async def save_signal(
self, symbol: str, timeframe: str, signal: str, metrics: Dict[str, float], set_number: int
):
"""
Saves the generated signal to the database asynchronously.
"""
try:
# Use sync_to_async to create the Signal object
await sync_to_async(Signal.objects.create)(
symbol=symbol,
timestamp=metrics.get("timestamp"),
timeframe=timeframe,
signal_type=signal,
price=metrics.get("price"),
stop_loss=metrics.get("stop_loss"),
take_profit=metrics.get("take_profit"),
result=metrics.get("result"),
win_probability=metrics.get("win_probability"),
success_rate=metrics.get("success_rate"),
price_change_24h=metrics.get("price_change_24h"),
risk_reward_ratio=metrics.get("risk_reward_ratio"),
market_regime=metrics.get("market_regime"),
additional_info=metrics.get("additional_info"),
)
logger.info(f"Signal for {symbol} {timeframe} (Set {set_number}) saved to the database.")
except Exception as e:
logger.error(f"Error saving signal for {symbol} {timeframe}: {e}")
raise
async def run_bot(self):
"""
Main loop of the bot. It runs continuously, processing symbols asynchronously.
"""
while True:
logger.info("Starting bot cycle...")
start_time = time.time()
try:
# Fetch symbols asynchronously
symbols = await self.get_symbols()
logger.info(f"Fetched {len(symbols)} symbols.")
except Exception as e:
logger.error(f"Error fetching symbols: {e}")
await asyncio.sleep(60) # Wait before retrying
continue
tasks = []
for symbol in symbols:
for timeframe in self.timeframes:
task = self.process_symbol(symbol, timeframe)
tasks.append(task)
await asyncio.gather(*tasks)
end_time = time.time()
execution_time = end_time - start_time
sleep_time = max(60 - execution_time, 0)
logger.info(f"Bot cycle complete. Sleeping for {sleep_time} seconds.")
await asyncio.sleep(sleep_time)
async def process_symbol(self, symbol: str, timeframe: str):
"""
Processes a single symbol and timeframe, generating and saving signals from both sets.
"""
try:
# Generate signals for both sets
signal1, metrics1 = await self.generate_signal_set(
symbol, timeframe, set_number=1
)
signal2, metrics2 = await self.generate_signal_set(
symbol, timeframe, set_number=2
)
tasks = []
# Save signals from each set independently
if signal1 != "NO_SIGNAL":
tasks.append(
self.save_signal(symbol, timeframe, signal1, metrics1, set_number=1)
)
if signal2 != "NO_SIGNAL":
tasks.append(
self.save_signal(symbol, timeframe, signal2, metrics2, set_number=2)
)
# If both sets have the same signal (excluding "NO_SIGNAL"), mark it as Strong and increase success rate
if signal1 == signal2 and signal1 != "NO_SIGNAL":
combined_signal = f"STRONG {signal1}" if "STRONG" not in signal1 else signal1
# Merge metrics for combined signal
combined_metrics = metrics1.copy()
combined_metrics["signal"] = combined_signal
combined_metrics["success_rate"] = 80 # Increase success rate
combined_metrics["win_probability"] = 80 # Increase win probability
# Combine reasons from both sets
combined_metrics["additional_info"]["reasons"] += metrics2["additional_info"]["reasons"]
tasks.append(
self.save_signal(symbol, timeframe, combined_signal, combined_metrics, set_number=0)
)
logger.info(
f"Confirmed signal for {symbol} ({timeframe}): {combined_signal}"
)
else:
logger.info(
f"No confirmed signal for {symbol} ({timeframe}). Signals: Set1={signal1}, Set2={signal2}"
)
if tasks:
await asyncio.gather(*tasks)
else:
logger.info(
f"No significant signals to save for {symbol} ({timeframe})."
)
except Exception as e:
logger.error(f"Error processing symbol {symbol} ({timeframe}): {e}")
if name == "main":
bot = CryptoBot()
try:
asyncio.run(bot.run_bot())
except KeyboardInterrupt:
logger.info("Stopping bot...")
The issue you're facing stems from this section in technical_analysis.py within the CryptoBot.get_symbols method:
The reason why 0 symbols are being fetched could be due to:
Empty TradingPair Table:
In the BinanceDataFetcher code, when you fetched symbols from Binance API, it appears that the symbols are stored in a list (self.all_symbols). However, it seems these symbols were not properly saved to the TradingPair database table.
CryptoBot.get_symbols is attempting to fetch symbols that are expected to exist in the TradingPair database model, but it's likely that the TradingPair table is empty or hasn't been populated.
Debugging Steps:
Verify the TradingPair Table Content:
Open the Django shell and check the content of the TradingPair table:
bash
python manage.py shell
Then, execute:
python
from rajj.models import TradingPair
print(TradingPair.objects.all()) # Should print all trading pairs saved
If this returns an empty query set, then the issue lies in how TradingPair was populated during the BinanceDataFetcher run.
Fixing the TradingPair Population Issue:
You need to ensure that after fetching symbols in the BinanceDataFetcher code, they are saved to the TradingPair model. Add the following logic to the BinanceDataFetcher.initialize method:
Modify BinanceDataFetcher.initialize to Save Symbols to TradingPair:
Import the TradingPair model at the top of BinanceDataFetcher:
python
from rajj.models import TradingPair
Add a loop that saves the fetched symbols:
Modify the initialize method:
python
async def initialize(self):
"""Initialize the data fetcher and load all USDT futures pairs."""
self.session = aiohttp.ClientSession()
try:
async with self.session.get(f"{BASE_URL}/fapi/v1/exchangeInfo") as response:
if response.status != 200:
raise Exception(f"HTTP {response.status}: {await response.text()}")
exchange_info = await response.json()
self.all_symbols = [
s['symbol'] for s in exchange_info['symbols']
if s['symbol'].endswith('USDT') and s['status'] == 'TRADING'
]
logger.info(f"Total loaded USDT futures pairs: {len(self.all_symbols)}")
# Save symbols to the database
for symbol in self.all_symbols:
await sync_to_async(TradingPair.objects.get_or_create)(symbol=symbol)
logger.info(f"Saved {len(self.all_symbols)} symbols to the database.")
except Exception as e:
logger.error(f"Error initializing Binance connection: {e}")
raise
Ensure TradingPair has an appropriately defined symbol field if it's not yet defined. For example:
python
class TradingPair(models.Model):
symbol = models.CharField(max_length=20, unique=True)
Run the fetcher again after applying the modification:
bash
python your_fetcher_script.py
Explanation of the Core Issue:
The CryptoBot relies on the TradingPair table for symbols, but unless the BinanceDataFetcher correctly saves fetched symbols to this table, no symbols will be available for the bot to process, resulting in the message Fetched 0 symbols.
How to Confirm the Fix?
Once the patch is applied and you run the fetcher again, do the following:
Check the TradingPair table content using the Django shell.
bash
python manage.py shell
from rajj.models import TradingPair
print(TradingPair.objects.all()) # Ensure it lists the symbols
Run the CryptoBot. It should now fetch symbols and proceed with processing:
bash
python technical_analysis.py
You should see logs with:
plaintext
2024-12-03 14:49:18 [INFO] Fetched 300 symbols.
Additional Diagnostic Points:
If the database isn't connected correctly or migrations aren't applied, ensure migrations are run:
If TradingPair.objects.all() still shows no entries, ensure there are no database-related errors (e.g., check database configs in settings.py).
With the proposed fixes, the technical_analysis.py script will be able to successfully fetch the symbols saved by the BinanceDataFetcher and generate signals.
The error you are encountering (django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured) occurs because Django settings are not properly initialized when the script rajj.feda is run.
ROOT CAUSE:
Django requires the environment variable DJANGO_SETTINGS_MODULE to be set before any models, settings, or Django components are accessed. However, in your code, the models (TradingPair) are being imported but the Django environment is not properly initialized.
RESOLUTION:
You need to properly initialize the Django environment at the beginning of the script, before importing any models or using any Django functionalities. Follow the steps below to fix the issue:
1. Initialize Django in feda.py
Add the following code to the top of your feda.py script before importing TradingPair or any other Django component:
python
# feda.py
import os
import django
# Set the default Django settings module (replace "comber.settings" with your actual settings module path if different)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "comber.settings")
django.setup() # Initialize Django
The corrected feda.py script should look like this:
python
# feda.py
import os
import django
# Set the default Django settings module (replace "comber.settings" with your actual settings module path if different)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "comber.settings")
django.setup() # Initialize Django
from rajj.models import TradingPair
# Remaining code for the fetcher or any other logic
2. Verify Your Django Setup
Ensure the following points are correct in your project:
DJANGO_SETTINGS_MODULE Path:
The string "comber.settings" passed to os.environ.setdefault should match the location of your Django settings module.
If your settings are located elsewhere, such as myproject.settings, update the value accordingly.
Django Installed Apps:
The rajj app (or the app where TradingPair is defined) should be included in the INSTALLED_APPS list in your project’s settings.py.
Example:
python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rajj', # Ensure the 'rajj' app is listed here
]
Migrations Applied:
Once TradingPair is defined, ensure migrations are created and applied:
Database Configuration:
Verify that your settings.py file contains the correct database configuration for where you want to save data:
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Use appropriate database backend (e.g., PostgreSQL, MySQL)
'NAME': BASE_DIR / "db.sqlite3", # Update with your database name
}
}
3. Test the Script
After making the above changes, run feda.py again. The script should now correctly initialize the Django environment and be able to import TradingPair without errors.
bash
python -m rajj.feda
Why This Fix Works
The django.setup() call initializes the Django environment, ensuring Django settings, apps, and models are properly loaded before use.
The os.environ.setdefault ensures the DJANGO_SETTINGS_MODULE environment variable is pointing to your Django settings file.
FOLLOW-UP CHECKS:
If the script still doesn't behave as expected, verify the following:
The TradingPair table has data after you've successfully fetched and saved trading pair symbols.
Use the Django shell to confirm:
bash
python manage.py shell
from rajj.models import TradingPair
print(TradingPair.objects.all())
The primary issue here is that, although the BinanceDataFetcher class has methods like connect_websockets, they are not being invoked during the execution of the run() method. As a result, the historical data fetching runs successfully, but the WebSocket connection part does not happen.
Let’s analyze this and make adjustments to ensure the WebSocket connection functionality works as intended.
Core Issue
The BinanceDataFetcher.run() method only:
Initializes the client (via self.initialize())
Fetches historical data (via self.fetch_historical_data())
Fetches and saves the initial orderbooks (via self.fetch_and_save_initial_orderbooks())
However, it does not invoke the connect_websockets() call, which is the function responsible for creating the WebSocket connections.
Solution
To ensure that the connect_websockets method is executed, you need to explicitly invoke it in your run() method. This will establish the WebSocket connections after fetching historical and initial data.
Modify the BinanceDataFetcher.run() method as follows:
Updated run()
python
async def run(self):
"""Main execution method."""
try:
# Step 1: Initialize and load all symbols
await self.initialize()
# Step 2: Fetch historical klines
logger.info("Fetching historical klines...")
await self.fetch_historical_data()
# Step 3: Fetch and save initial orderbooks
logger.info("Fetching initial orderbooks...")
await self.fetch_and_save_initial_orderbooks()
# Step 4: Connect to WebSockets
logger.info("Connecting to WebSockets...")
await self.connect_websockets()
except Exception as e:
logger.error(f"Error in main execution: {e}")
WebSocket Connection Implementation in connect_websockets
From your original code, the connect_websockets() method contains the logic to create WebSocket connections for all symbols.
Below is a breakdown of what the current code already does, and a few improvements that can be made:
Current Implementation (connect_websockets)
python
async def connect_websockets(self):
"""
Establish WebSocket connections in batches for all symbols.
"""
# Create batches of symbols
symbol_batches = [
self.all_symbols[i:i+SYMBOLS_PER_BATCH]
for i in range(0, len(self.all_symbols), SYMBOLS_PER_BATCH)
]
# Create WebSocket connection tasks for each batch
websocket_tasks = []
for batch in symbol_batches:
websocket_tasks.append(self.create_websocket_connection(batch))
# Run WebSocket connections concurrently
await asyncio.gather(*websocket_tasks)
The function starts WebSocket connections for all symbols in batches. This is a good approach since Binance WebSocket streams can handle multiple symbols in a single connection, and batching helps manage the number of concurrent connections.
Step-by-Step Debugging and Improvement
Ensure self.all_symbols Is Populated:
If self.all_symbols is empty, no WebSocket connections will be attempted.
To verify, add debug log messages or assertions before splittings symbols into batches:
python
logger.info(f"Total symbols for WebSocket connections: {len(self.all_symbols)}")
assert len(self.all_symbols) > 0, "No symbols found. Ensure `initialize()` was called successfully."
Handle WebSocket Lifetime and Disconnects:
If Binance disconnects a WebSocket connection after a certain time (e.g., due to rate limits or server issues), you might need to reconnect those streams automatically. Add error handling within the WebSocket loop:
python
try:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await self.handle_websocket_message(json.loads(msg.data))
elif msg.type == aiohttp.WSMsgType.CLOSED:
logger.warning(f"WebSocket closed. Retrying connection for {symbols} batch...")
break
elif msg.type == aiohttp.WSMsgType.ERROR:
logger.error(f"WebSocket error: {msg.data}")
break
except Exception as e:
logger.error(f"WebSocket connection error for batch {symbols}: {e}")
Ensure Continuous Running:
Add a while True loop around WebSocket reconnection logic to ensure it keeps running indefinitely. Modify connect_websockets() or create_websocket_connection() to reconnect after a disconnection:
python
async def create_websocket_connection(self, symbols: List[str]):
while True: # Keep reconnecting
try:
await self._connect_websocket_once(symbols)
except Exception as e:
logger.error(f"WebSocket batch connection failed. Retrying: {e}")
await asyncio.sleep(5) # Add a delay before reconnecting
Testing the WebSocket Connection
To ensure WebSocket connections work as expected, test the program:
Enable logging outputs to monitor the establishment of WebSocket connections:
python
logger.info(f"WebSocket connected for {len(symbols)} symbols")
Test the WebSocket handler methods, especially handle_websocket_message (already defined):
Ensure that messages from Binance (e.g., kline or depthUpdate) are processed correctly.
Add a manual temporary timeout or stopping mechanism if necessary during development testing.
Example Output from the Logs (Expected Behavior)
If everything works correctly, you should see output similar to:
code
2024-12-03 14:49:18 [INFO] Initializing Binance Client and loading symbols...
2024-12-03 14:49:18 [INFO] Total loaded USDT futures pairs: 300
2024-12-03 14:49:18 [INFO] Fetching historical klines...
2024-12-03 14:50:50 [INFO] Completed historical data fetching for all symbols.
2024-12-03 14:50:50 [INFO] Fetching initial orderbooks...
2024-12-03 14:50:55 [INFO] Fetching initial orderbooks complete.
2024-12-03 14:50:55 [INFO] Connecting to WebSockets...
2024-12-03 14:51:00 [INFO] WebSocket connected for 10 symbols
2024-12-03 14:51:00 [INFO] WebSocket connected for 10 symbols
2024-12-03 14:51:00 [INFO] ...
Conclusion
With these adjustments:
The WebSocket connections will properly initiate using connect_websockets() inside run().
The connections will process real-time market data (kline, depthUpdate) and process messages accordingly.
If Binance disconnects the WebSocket, the reconnect loop ensures persistence.
Logging helps debug issues during connection, disconnection, and message handling.
Yes, it is possible to execute all tasks in the BinanceDataFetcher.run() method concurrently to improve execution efficiency. Instead of waiting for each step (initialization, fetching historical data, saving order books, and connecting to WebSockets) to complete sequentially, you can leverage asynchronous operations like asyncio.gather to perform them concurrently.
Here’s how you can modify the code to perform those tasks concurrently while maintaining correct execution order:
Revised BinanceDataFetcher.run() for Concurrent Execution
python
async def run(self):
"""Main execution method with concurrent task execution."""
try:
# Step 1: Initialize and load all symbols
await self.initialize() # Initialization must be done first to load symbols
logger.info("Starting concurrent tasks for data fetching and real-time processing...")
# Step 2, 3, and 4: Launch tasks concurrently
tasks = [
self.fetch_historical_data(), # Fetch historical klines
self.fetch_and_save_initial_orderbooks(), # Fetch initial orderbooks
self.connect_websockets() # Connect to WebSockets
]
# Run all tasks concurrently
await asyncio.gather(*tasks)
logger.info("All tasks completed successfully.")
except Exception as e:
logger.error(f"Error in main execution: {e}")
Explanation of Changes
Initialization First (initialize() is Sequential):
initialize() must run before anything else because it populates self.all_symbols, which is required by the other methods (fetch_historical_data, fetch_and_save_initial_orderbooks, connect_websockets).
Without proper initialization, the subsequent tasks would fail.
Concurrency Using asyncio.gather:
Other tasks are independent of each other, so they can be run concurrently:
self.fetch_historical_data(): Fetches historical klines for all symbols.
self.fetch_and_save_initial_orderbooks(): Fetches and saves order books.
self.connect_websockets(): Establishes WebSocket connections for real-time data processing.
By running these tasks concurrently using asyncio.gather, they do not block each other.
Efficient Waiting:
asyncio.gather(*tasks) ensures that all tasks run concurrently but waits until all tasks complete before proceeding. This is more efficient than completing tasks one by one.
Error Handling:
Since all tasks run concurrently, an unhandled exception in any single task would normally cancel the others. To prevent this and allow partial success if one task fails, you can wrap each task with error handling. This will ensure that failures in one task do not stop others (see further improvements in "Advanced Error Handling").
Concurrent Behavior
The modified run() method will execute tasks like this:
Each symbol's historical data fetching occurs concurrently within fetch_historical_data().
Each WebSocket batch connection occurs concurrently within connect_websockets().
All top-level tasks (fetch_historical_data, fetch_and_save_initial_orderbooks, connect_websockets) also run concurrently.
For example:
While historical data is being fetched for all 300 symbols, the task to fetch orderbook data begins execution.
Meanwhile, WebSocket connections for live data streaming are also being established.
Ensuring WebSocket Task Keeps Running
Since WebSockets need to run indefinitely to listen for real-time updates, ensure that the WebSocket task (connect_websockets()) continues running after other tasks (like fetching historical data) are complete.
Here’s how you can modify your connect_websockets() to handle this requirement:
Updated connect_websockets()
python
async def connect_websockets(self):
"""
Establish WebSocket connections in batches for all symbols and keep them running.
"""
symbol_batches = [
self.all_symbols[i:i + SYMBOLS_PER_BATCH]
for i in range(0, len(self.all_symbols), SYMBOLS_PER_BATCH)
]
# Launch WebSocket connections for each batch concurrently
tasks = [self.create_websocket_connection(batch) for batch in symbol_batches]
logger.info(f"Establishing WebSocket connections for {len(self.all_symbols)} symbols in {len(symbol_batches)} batches.")
while True: # Keep WebSocket tasks running indefinitely
try:
await asyncio.gather(*tasks)
except Exception as e:
logger.error(f"Error in WebSocket connections: {e}. Restarting...")
await asyncio.sleep(5) # Brief delay before restarting WebSocket connections
Updated create_websocket_connection()
python
async def create_websocket_connection(self, symbols: List[str]):
"""
Create a WebSocket connection for a given batch of symbols.
"""
streams = [
f"{symbol.lower()}@kline_{interval}" for symbol in symbols for interval in TIMEFRAMES
]
streams.append(f"{symbol.lower()}@depth" for symbol in symbols) # Depth stream for orderbooks
ws_url = f"{WS_URL}/stream?streams={'/'.join(streams)}"
while True: # Reconnect WebSocket if it closes or fails
try:
async with aiohttp.ClientSession() as session:
async with session.ws_connect(ws_url) as ws:
logger.info(f"WebSocket connected for batch: {symbols}")
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await self.handle_websocket_message(json.loads(msg.data))
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):
logger.warning(f"WebSocket closed. Reconnecting batch for symbols: {symbols}")
break
except Exception as e:
logger.error(f"Error with WebSocket batch {symbols}: {e}")
await asyncio.sleep(5) # Retry after delay
Advanced Error Handling
When running tasks concurrently using asyncio.gather, any exception in one task can cancel all others. To avoid this, use a wrapper for each task to catch and log errors without stopping other tasks.
For example, wrap each task with a helper function that logs and suppresses exceptions:
This ensures that one failing task (e.g., fetching historical data) doesn’t prevent other tasks (e.g., WebSocket connections) from continuing.
Final Full run() with Concurrency and Error Handling
python
async def run(self):
"""Main execution method with concurrent task execution and error handling."""
try:
# Step 1: Initialize and load all symbols
await self.initialize() # Must run first
logger.info("Starting concurrent tasks for data fetching and WebSocket connections...")
# Step 2, 3, and 4: Launch main tasks concurrently
tasks = [
safe_task(self.fetch_historical_data()), # Historical data
safe_task(self.fetch_and_save_initial_orderbooks()), # Orderbooks
safe_task(self.connect_websockets()) # WebSockets
]
await asyncio.gather(*tasks)
logger.info("All tasks completed successfully.")
except Exception as e:
logger.error(f"Error in main execution: {e}")
Expected Behavior:
Initialization First: Symbols are loaded via initialize() sequentially.
Concurrent Execution: Historical data fetching, orderbook saving, and WebSocket connection tasks run concurrently.
In Case of WebSocket Disconnect: The WebSocket tasks automatically reconnect.
Resilience to Failures: If one task fails, other tasks continue running.
Example Log Output:
plaintext
2024-12-03 14:49:18 [INFO] Total loaded USDT futures pairs: 300
2024-12-03 14:49:18 [INFO] Starting concurrent tasks for data fetching and WebSocket connections...
2024-12-03 14:50:50 [INFO] Completed historical data fetching for all symbols.
2024-12-03 14:50:55 [INFO] Fetching initial orderbooks complete.
2024-12-03 14:51:00 [INFO] WebSocket connected for 10 symbols
2024-12-03 14:51:05 [INFO] WebSocket message received: {...}
2024-12-03 14:55:00 [INFO] WebSocket batch retrying due to disconnection...
With these changes, you now have concurrent task execution for historical data fetching, order book saving, and real-time WebSocket connections. Keep an eye on logs during testing to validate performance and robustness.