# 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
# Optionally, sort symbols by volatility or other criteria here
# For simplicity, we'll proceed with the filtered list
fetcher = DataFetcher(symbols=usdt_pairs, timeframes=['5m', '15m', '1h'])
await fetcher.run()
if name == "main":
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
What does this code do
Assistant
The provided Python script is a data-fetching utility designed to interact with the Binance cryptocurrency exchange, specifically for Binance USDT perpetual futures. Here's an overview of what the script does:
Setup and Initialization:
Uses ccxt library for exchange interaction, specifically with Binance USDM.
Utilizes Django models to save data to a database (indicating a Django project context).
Uses asynchronous programming with Python's asyncio for efficient handling of network operations.
Logging:
Configures logging with loguru, outputting to both console and a rotating file.
Fetching Data:
Historical Data: Fetches historical candlestick (kline) data for specified symbols and timeframes. It retrieves 1000 data points per request, due to Binance's limits, and continues fetching until all available data is collected.
WebSocket Streams: Connects to Binance WebSocket streams to get real-time kline updates. It handles multiple connections if the number of requested streams exceeds the allowed limit per connection.
Data Handling:
Converts timestamps from Unix time to a readable format with timezone conversion.
Upon receiving data (both historical and real-time), the script saves it to a database using Django ORM with the models defined in the Django project, specifically with a Kline model.
Uses sync_to_async to allow Django ORM usage in async functions.
Concurrency and Error Handling:
Utilizes semaphores to control the number of concurrent operations in fetching historical data.
Implements retry logic with exponential backoff for WebSocket connections to handle disconnections and errors gracefully.
Main Workflow:
Initializes exchange and market data.
Filters for active USDT perpetual futures contracts.
Initiates a DataFetcher instance to execute the data fetching and real-time streaming.
Script Execution:
Ensures compatibility with Windows event loop policy for asyncio.
Runs the main event loop, which performs the full data acquisition and streaming process.
This script is aimed at efficiently collecting market data for analytical, trading, or monitoring purposes within a broader Django application setup.
User
What can I do to improve it
Assistant
Improving the script could involve optimizations, additional features, and handling edge cases more robustly. Here are several suggestions:
Exception Management:
Refine exception handling to target specific expected errors (e.g., connection issues, rate limit errors) rather than using general exceptions.
Concurrency and Efficiency:
Review the semaphore value for optimal concurrency based on empirical testing of network and server capabilities.
Implement more granular concurrency (per symbol or per timeframe) to maximize parallel data fetching.
Configuration Management:
Move configuration details (e.g., symbol lists, timeframes, logging levels) to a configuration file or environment variables for easier modifications and deployments.
Logging Enhancements:
Include more granular logging (e.g., warning logs when a specific fetch attempt fails due to rate limits).
Add a logging level argument to easily toggle verbose logging for debugging versus concise logging for production.
Code Organization:
Consider separating code into modules for cleaner organization (e.g., WebSocket handling, database operations, data fetching).
Define constants for magic numbers (e.g., timeframes, max retries) to increase readability and maintainability.
Testing and Monitoring:
Implement unit tests for the different components (e.g., data fetching, WebSocket handling).
Add monitoring for ongoing WebSocket connections and data flow to quickly identify and resolve live issues.
Data Handling:
Enhance error handling during database operations to catch and log specific database errors.
Consider data validation and cleansing steps before saving to ensure integrity.
Feature Expansion:
Add capabilities to dynamically alter tracked symbols and timeframes without restarting the script.
Integrate additional data sources or features such as alerts on certain conditions, or aggregation of fetched data for analytics.
Resource Usage:
Investigate and optimize the script's RAM and CPU usage, especially during high-frequency trading hours or with many symbols.
User
Those are minor changes in that I can ignore. I want you to make sure it fetch price data for 1 minute, 5 minute, 15 minute, and 1 hour. After fetching historical data, I want it to keep adding price data from websockets so that if right now is 3.30, the market data it fetches right now should be added to historical data at 3.31, 3.32, 3.33 onwards for 1 minute timeframe, 3.35, 3.40, 3.45 onwards for 5 minute timeframe, 3.45, 4.00, 4.15 onwards for 15 minute timeframe and so on. Let data from websockets be added to historical data and saved automatically upon being streamed.
Refine exception handling to target specific expected errors (e.g., connection issues, rate limit errors) rather than using general exceptions. Review the semaphore value for optimal concurrency based on empirical testing of network and server capabilities. Implement more granular concurrency (per symbol or per timeframe) to maximize parallel data fetching. Consider data validation and cleansing steps before saving to ensure integrity. Write the whole code with modifications and send it to me.
Assistant
Sure! Below is a refined version of your script that incorporates the specified improvements while ensuring it fetches the 1-minute, 5-minute, 15-minute, and 1-hour kline data. It also keeps updating the data with WebSocket streaming and improves exception handling, concurrency control, and data validation.
python
User
#priceaction.py
import pandas as pd
import numpy as np
from binance.client import Client
from binance.exceptions import BinanceAPIException
import time
import logging
import traceback
from concurrent.futures import ThreadPoolExecutor
To enable priceaction.py to utilize the price data fetched by fetch_data.py instead of refetching it, you'll need to modify the bot to interact with the Django database where the historical klines are being stored. Here's how you could restructure it to use the Kline model from Django:
python
User
What can we do to improve priceaction.py accuracy
Assistant
Enhancing the accuracy of priceaction.py involves both refining the technical analysis techniques and ensuring robust data and analysis practices. Here are some suggestions to improve the accuracy of the trading bot:
Enhance Data Quality:
Data Cleansing: Ensure no missing values in your DataFrame and handle any anomalies or outliers in historical data.
Granularity: Use a finer resolution for your time intervals if needed, like merging data from different intervals for richer insights.
Advanced Technical Indicators:
Divergence Indicators: Implement indicators like RSI (Relative Strength Index) or MACD (Moving Average Convergence Divergence) to detect divergences.
Volume Indicators: Introduce indicators like the On-Balance Volume (OBV) or Chaikin Money Flow (CMF) to assess the strength of trends.
Pattern Recognition: Implement more comprehensive pattern recognition using libraries like TA-Lib or pandas-ta.
Machine Learning Models:
Incorporate machine learning algorithms to predict price movements based on historical data and technical indicators. Libraries like scikit-learn or tensorflow could be used.
Use models like Random Forests or Gradient Boosting to capture complex patterns in market behavior.
Optimize Parameters:
Use historical data to backtest and optimize the parameters of your trading strategy (e.g., lookback periods for trend analysis, support/resistance thresholds).
Implement parameter optimization techniques like Genetic Algorithms for finding the best settings.
Risk Management:
Implement more sophisticated risk management strategies, like dynamic position sizing based on volatility or drawdown limits to minimize potential losses.
Sentiment Analysis:
Supplement technical analysis with sentiment analysis using data from social media, news, or other platforms to gauge market sentiment.
Performance Metrics:
Regularly evaluate the performance of your trading strategy using key metrics like Sharpe Ratio, Sortino Ratio, or Maximum Drawdown to ensure it meets performance objectives.
If scaling the number of symbols being tracked, consider sharding the WebSocket connections or running the script in a distributed fashion.
Documentation:
Add docstrings and comments to the code, making it more user-friendly for collaborative environments or handovers.
Write a README file explaining usage, configuration, and dependencies.
These improvements would depend on the specific requirements of your project, such as the importance of real-time data accuracy, system resource limitations, and feature expansion priorities.
# 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
# Initialize Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'binancebot.settings')
django.setup()
from signals.models import Kline
# Remove default Loguru handlers and configure new ones
logger.remove()
logger.add("fetch_data.log", rotation="20 MB", retention="7 days", level="DEBUG",
format="{time} | {level} | {message}") # File logging
logger.add(sys.stdout, level="INFO") # Console logging
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}")
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}")
# 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
kline_data = data['data']['k']
if not kline_data['x']:
continue # 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:
continue
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 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)
@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}")
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.")
async def main():
exchange = ccxt.binanceusdm({'enableRateLimit': True})
await exchange.load_markets()
markets = exchange.markets
# 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())
Key Modifications:
Timeframes: Now includes '1m', '5m', '15m', '1h'.
Concurrency Control: Increased semaphore to control the number of concurrent network operations more effectively.
WebSocket Connection: Improved with specific exception handling for connection issues.
Data Validation: Cleanses and validates data before database operations.
Error Handling: Improved with targeted handling of common connection and request errors specific to network and exchanges.
This structure will ensure efficient data retrieval and update, error mitigation, and maximized reliability when interacting with the exchange.
def get_historical_data(self):
try:
bars = self.client.get_historical_klines(self.symbol, self.interval, self.lookback + " ago UTC")
self.df = pd.DataFrame(bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])
self.df['timestamp'] = pd.to_datetime(self.df['timestamp'], unit='ms')
for col in ['open', 'high', 'low', 'close', 'volume']:
self.df[col] = self.df[col].astype(float)
self.df.set_index('timestamp', inplace=True)
except BinanceAPIException as e:
logger.error(f"Error fetching historical data: {e}")
def price_action_analysis(self, df):
try:
recent_df = df.iloc[-100:] # Increased lookback for more robust analysis
recent_df.dropna(inplace=True)
if len(recent_df) < 20:
return None
highs = recent_df['high'].values
lows = recent_df['low'].values
closes = recent_df['close'].values
# Trend Analysis
short_term_trend = np.polyfit(range(20), closes[-20:], 1)[0]
medium_term_trend = np.polyfit(range(50), closes[-50:], 1)[0]
long_term_trend = np.polyfit(range(100), closes[-100:], 1)[0]
# Support and Resistance
support = np.min(lows[-20:])
resistance = np.max(highs[-20:])
# Volatility
volatility = np.std(closes[-20:])
# Price Action Patterns
bullish_engulfing = (closes[-1] > opens[-1]) and (closes[-2] < opens[-2]) and (closes[-1] > opens[-2]) and (closes[-1] - opens[-1] > opens[-2] - closes[-2])
bearish_engulfing = (closes[-1] < opens[-1]) and (closes[-2] > opens[-2]) and (closes[-1] < opens[-2]) and (opens[-1] - closes[-1] > closes[-2] - opens[-2])
pin_bar_bullish = (highs[-1] - max(opens[-1], closes[-1])) > 2 * abs(opens[-1] - closes[-1]) and (min(opens[-1], closes[-1]) - lows[-1]) < abs(opens[-1] - closes[-1])
pin_bar_bearish = (max(opens[-1], closes[-1]) - lows[-1]) > 2 * abs(opens[-1] - closes[-1]) and (highs[-1] - min(opens[-1], closes[-1])) < abs(opens[-1] - closes[-1])
# Inside bar
inside_bar = highs[-1] < highs[-2] and lows[-1] > lows[-2]
# Decision making
if short_term_trend > 0 and medium_term_trend > 0 and long_term_trend > 0:
if closes[-1] > resistance or bullish_engulfing or pin_bar_bullish:
signal = 'STRONG_BUY'
elif inside_bar:
signal = 'POTENTIAL_BREAKOUT'
else:
signal = 'WEAK_BUY'
elif short_term_trend < 0 and medium_term_trend < 0 and long_term_trend < 0:
if closes[-1] < support or bearish_engulfing or pin_bar_bearish:
signal = 'STRONG_SELL'
elif inside_bar:
signal = 'POTENTIAL_BREAKDOWN'
else:
signal = 'WEAK_SELL'
else:
signal = 'NO_SIGNAL'
last_row = recent_df.iloc[-1].copy()
last_row['Signal'] = signal
last_row['Volatility'] = volatility
last_row['Support'] = support
last_row['Resistance'] = resistance
return last_row.to_frame().T
except Exception as e:
logger.error(f"Error in price action analysis: {e}\n{traceback.format_exc()}")
return None
def advanced_price_action_analysis(self, df):
try:
recent_df = df.iloc[-200:] # Extended lookback for more comprehensive analysis
recent_df.dropna(inplace=True)
if len(recent_df) < 50:
return None
highs = recent_df['high'].values
lows = recent_df['low'].values
closes = recent_df['close'].values
opens = recent_df['open'].values
# Swing High and Swing Low detection
swing_high = np.where((highs[1:-1] > highs[:-2]) & (highs[1:-1] > highs[2:]))[0] + 1
swing_low = np.where((lows[1:-1] < lows[:-2]) & (lows[1:-1] < lows[2:]))[0] + 1
# Higher Highs and Lower Lows
higher_highs = len(swing_high) >= 2 and highs[swing_high[-1]] > highs[swing_high[-2]]
lower_lows = len(swing_low) >= 2 and lows[swing_low[-1]] < lows[swing_low[-2]]
# Fibonacci Retracement
if len(swing_high) > 0 and len(swing_low) > 0:
fib_high = highs[swing_high[-1]]
fib_low = lows[swing_low[-1]]
fib_diff = fib_high - fib_low
fib_levels = [fib_low + l * fib_diff for l in [0.236, 0.382, 0.5, 0.618, 0.786]]
current_price = closes[-1]
fib_support = max([l for l in fib_levels if l < current_price], default=None)
fib_resistance = min([l for l in fib_levels if l > current_price], default=None)
else:
fib_support = fib_resistance = None
# Volume Analysis
volume = recent_df['volume'].values
avg_volume = np.mean(volume[-20:])
volume_trend = 'UP' if volume[-1] > avg_volume else 'DOWN'
# Momentum
momentum = closes[-1] - closes[-20]
# Decision making
if higher_highs and momentum > 0:
if closes[-1] > fib_resistance and volume_trend == 'UP':
signal = 'STRONG_BUY'
elif closes[-1] > fib_resistance:
signal = 'BUY'
else:
signal = 'WEAK_BUY'
elif lower_lows and momentum < 0:
if closes[-1] < fib_support and volume_trend == 'UP':
signal = 'STRONG_SELL'
elif closes[-1] < fib_support:
signal = 'SELL'
else:
signal = 'WEAK_SELL'
else:
signal = 'NO_SIGNAL'
last_row = recent_df.iloc[-1].copy()
last_row['Signal'] = signal
last_row['Volume_Trend'] = volume_trend
last_row['Momentum'] = momentum
last_row['Fib_Support'] = fib_support
last_row['Fib_Resistance'] = fib_resistance
return last_row.to_frame().T
except Exception as e:
logger.error(f"Error in advanced price action analysis: {e}\n{traceback.format_exc()}")
return None
def execute_trade(self, side, quantity):
try:
if side == 'BUY':
order = self.client.create_order(symbol=self.symbol, side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=quantity)
else:
order = self.client.create_order(symbol=self.symbol, side=Client.SIDE_SELL, type=Client.ORDER_TYPE_MARKET, quantity=quantity)
logger.info(f"Order executed: {order}")
except Exception as e:
logger.error(f"An error occurred while executing trade: {e}")
def run_bot(self):
while True:
try:
self.get_historical_data()
with ThreadPoolExecutor(max_workers=2) as executor:
future_pa = executor.submit(self.price_action_analysis, self.df)
future_apa = executor.submit(self.advanced_price_action_analysis, self.df)
pa_result = future_pa.result()
apa_result = future_apa.result()
if pa_result is not None and apa_result is not None:
pa_signal = pa_result.iloc[-1]['Signal']
apa_signal = apa_result.iloc[-1]['Signal']
if pa_signal in ['STRONG_BUY', 'BUY'] and apa_signal in ['STRONG_BUY', 'BUY']:
self.execute_trade('BUY', self.quantity)
elif pa_signal in ['STRONG_SELL', 'SELL'] and apa_signal in ['STRONG_SELL', 'SELL']:
self.execute_trade('SELL', self.quantity)
time.sleep(60) # Wait for 1 minute before next iteration
except Exception as e:
logger.error(f"Error in main loop: {e}\n{traceback.format_exc()}")
time.sleep(60) # Wait for 1 minute before retrying
if name == "main":
bot = PriceActionTradingBot('your_api_key', 'your_api_secret', 'BTCUSDT', Client.KLINE_INTERVAL_1HOUR, "1 week", 0.001)
bot.run_bot()
For the priceaction.py code above, I want you to modify it so that instead of it fetching data again, it uses the same price data fetched by fetch_data.py
# priceaction.py
import pandas as pd
import numpy as np
from binance.client import Client
from binance.exceptions import BinanceAPIException
import time
import logging
import traceback
from concurrent.futures import ThreadPoolExecutor
import django
import os
# Set up Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'binancebot.settings')
django.setup()
from signals.models import Kline
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class PriceActionTradingBot:
def __init__(self, api_key, api_secret, symbol, interval, lookback, quantity):
self.client = Client(api_key, api_secret)
self.symbol = symbol
self.interval = interval
self.lookback = lookback
self.quantity = quantity
self.df = None
self.position = None
def get_historical_data(self):
try:
# Fetch historical data from the database
klines = Kline.objects.filter(symbol=self.symbol, timeframe=self.interval).order_by('timestamp')
df = pd.DataFrame(list(klines.values()))
df['timestamp'] = pd.to_datetime(df['timestamp'])
df.set_index('timestamp', inplace=True)
for col in ['open', 'high', 'low', 'close', 'volume']:
df[col] = df[col].astype(float)
self.df = df
except Exception as e:
logger.error(f"Error fetching historical data from the database: {e}\n{traceback.format_exc()}")
def price_action_analysis(self, df):
try:
recent_df = df.iloc[-100:] # Increased lookback for more robust analysis
recent_df.dropna(inplace=True)
if len(recent_df) < 20:
return None
highs = recent_df['high'].values
lows = recent_df['low'].values
closes = recent_df['close'].values
opens = recent_df['open'].values
# Trend Analysis
short_term_trend = np.polyfit(range(20), closes[-20:], 1)[0]
medium_term_trend = np.polyfit(range(50), closes[-50:], 1)[0]
long_term_trend = np.polyfit(range(100), closes[-100:], 1)[0]
# Support and Resistance
support = np.min(lows[-20:])
resistance = np.max(highs[-20:])
# Volatility
volatility = np.std(closes[-20:])
# Price Action Patterns
bullish_engulfing = (closes[-1] > opens[-1]) and (closes[-2] < opens[-2]) and (closes[-1] > opens[-2]) and (closes[-1] - opens[-1] > opens[-2] - closes[-2])
bearish_engulfing = (closes[-1] < opens[-1]) and (closes[-2] > opens[-2]) and (closes[-1] < opens[-2]) and (opens[-1] - closes[-1] > closes[-2] - opens[-2])
pin_bar_bullish = (highs[-1] - max(opens[-1], closes[-1])) > 2 * abs(opens[-1] - closes[-1]) and (min(opens[-1], closes[-1]) - lows[-1]) < abs(opens[-1] - closes[-1])
pin_bar_bearish = (max(opens[-1], closes[-1]) - lows[-1]) > 2 * abs(opens[-1] - closes[-1]) and (highs[-1] - min(opens[-1], closes[-1])) < abs(opens[-1] - closes[-1])
# Inside bar
inside_bar = highs[-1] < highs[-2] and lows[-1] > lows[-2]
# Decision making
if short_term_trend > 0 and medium_term_trend > 0 and long_term_trend > 0:
if closes[-1] > resistance or bullish_engulfing or pin_bar_bullish:
signal = 'STRONG_BUY'
elif inside_bar:
signal = 'POTENTIAL_BREAKOUT'
else:
signal = 'WEAK_BUY'
elif short_term_trend < 0 and medium_term_trend < 0 and long_term_trend < 0:
if closes[-1] < support or bearish_engulfing or pin_bar_bearish:
signal = 'STRONG_SELL'
elif inside_bar:
signal = 'POTENTIAL_BREAKDOWN'
else:
signal = 'WEAK_SELL'
else:
signal = 'NO_SIGNAL'
last_row = recent_df.iloc[-1].copy()
last_row['Signal'] = signal
last_row['Volatility'] = volatility
last_row['Support'] = support
last_row['Resistance'] = resistance
return last_row.to_frame().T
except Exception as e:
logger.error(f"Error in price action analysis: {e}\n{traceback.format_exc()}")
return None
def advanced_price_action_analysis(self, df):
try:
recent_df = df.iloc[-200:] # Extended lookback for more comprehensive analysis
recent_df.dropna(inplace=True)
if len(recent_df) < 50:
return None
highs = recent_df['high'].values
lows = recent_df['low'].values
closes = recent_df['close'].values
opens = recent_df['open'].values
# Swing High and Swing Low detection
swing_high = np.where((highs[1:-1] > highs[:-2]) & (highs[1:-1] > highs[2:]))[0] + 1
swing_low = np.where((lows[1:-1] < lows[:-2]) & (lows[1:-1] < lows[2:]))[0] + 1
# Higher Highs and Lower Lows
higher_highs = len(swing_high) >= 2 and highs[swing_high[-1]] > highs[swing_high[-2]]
lower_lows = len(swing_low) >= 2 and lows[swing_low[-1]] < lows[swing_low[-2]]
# Fibonacci Retracement
if len(swing_high) > 0 and len(swing_low) > 0:
fib_high = highs[swing_high[-1]]
fib_low = lows[swing_low[-1]]
fib_diff = fib_high - fib_low
fib_levels = [fib_low + l * fib_diff for l in [0.236, 0.382, 0.5, 0.618, 0.786]]
current_price = closes[-1]
fib_support = max([l for l in fib_levels if l < current_price], default=None)
fib_resistance = min([l for l in fib_levels if l > current_price], default=None)
else:
fib_support = fib_resistance = None
# Volume Analysis
volume = recent_df['volume'].values
avg_volume = np.mean(volume[-20:])
volume_trend = 'UP' if volume[-1] > avg_volume else 'DOWN'
# Momentum
momentum = closes[-1] - closes[-20]
# Decision making
if higher_highs and momentum > 0:
if closes[-1] > fib_resistance and volume_trend == 'UP':
signal = 'STRONG_BUY'
elif closes[-1] > fib_resistance:
signal = 'BUY'
else:
signal = 'WEAK_BUY'
elif lower_lows and momentum < 0:
if closes[-1] < fib_support and volume_trend == 'UP':
signal = 'STRONG_SELL'
elif closes[-1] < fib_support:
signal = 'SELL'
else:
signal = 'WEAK_SELL'
else:
signal = 'NO_SIGNAL'
last_row = recent_df.iloc[-1].copy()
last_row['Signal'] = signal
last_row['Volume_Trend'] = volume_trend
last_row['Momentum'] = momentum
last_row['Fib_Support'] = fib_support
last_row['Fib_Resistance'] = fib_resistance
return last_row.to_frame().T
except Exception as e:
logger.error(f"Error in advanced price action analysis: {e}\n{traceback.format_exc()}")
return None
def execute_trade(self, side, quantity):
try:
if side == 'BUY':
order = self.client.create_order(symbol=self.symbol, side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=quantity)
else:
order = self.client.create_order(symbol=self.symbol, side=Client.SIDE_SELL, type=Client.ORDER_TYPE_MARKET, quantity=quantity)
logger.info(f"Order executed: {order}")
except Exception as e:
logger.error(f"An error occurred while executing trade: {e}")
def run_bot(self):
while True:
try:
self.get_historical_data()
with ThreadPoolExecutor(max_workers=2) as executor:
future_pa = executor.submit(self.price_action_analysis, self.df)
future_apa = executor.submit(self.advanced_price_action_analysis, self.df)
pa_result = future_pa.result()
apa_result = future_apa.result()
if pa_result is not None and apa_result is not None:
pa_signal = pa_result.iloc[-1]['Signal']
apa_signal = apa_result.iloc[-1]['Signal']
if pa_signal in ['STRONG_BUY', 'BUY'] and apa_signal in ['STRONG_BUY', 'BUY']:
self.execute_trade('BUY', self.quantity)
elif pa_signal in ['STRONG_SELL', 'SELL'] and apa_signal in ['STRONG_SELL', 'SELL']:
self.execute_trade('SELL', self.quantity)
time.sleep(60) # Wait for 1 minute before next iteration
except Exception as e:
logger.error(f"Error in main loop: {e}\n{traceback.format_exc()}")
time.sleep(60) # Wait for 1 minute before retrying
if __name__ == "__main__":
bot = PriceActionTradingBot('your_api_key', 'your_api_secret', 'BTCUSDT', '1h', "1 week", 0.001)
bot.run_bot()
Key Changes:
Django Integration:
Used Django ORM to fetch historical Kline data directly from the database instead of refetching it through the Binance API.
DataFrame Construction:
Retrieved klines from the Kline model in the database.
Constructed the DataFrame from the query.
Error Handling:
Added exception handling for the database operations to catch potential issues with data retrieval.
This setup assumes that fetch_data.py is continuously populating the Kline table in the database with up-to-date pricing information, providing the necessary data for priceaction.py to operate without duplicating effort or API calls. Make sure your Django’s database is accessible and correctly configured for this to work seamlessly.
Robust Testing:
Conduct extensive backtesting and validation using unseen historical data to assess the efficacy of your strategy.
Use walk-forward analysis to minimize overfitting and ensure robustness across various market conditions.
Integration with Real-world Events:
Incorporate a calendar of economic events and news that can impact price movements to adjust trading decisions based on impending reports or news releases.
Continuous Learning:
Regularly update your strategy based on new data and learnings to adapt to changing market conditions. Use feedback loops to refine the model continuously.
These enhancements can make your trading bot more reliable and reflective of real-world market dynamics, thereby improving its decision-making accuracy. Combining different methodologies and continuously testing and tuning the strategy is crucial to achieving better outcomes.