In def historical_data_worker(symbol):
signal_generator = SignalGenerator(symbol=symbol)
signal_generator.df = signal_generator.fetch_historical_data()
if not signal_generator.df.empty:
logging.info(f"Processed historical data for {symbol}")
signal_generator.run()
It says aise self._exception
TypeError: historical_data_worker() takes 1 positional argument but 2 were given
Assistant
The error message you're seeing indicates that historical_data_worker was called with two arguments, but it's defined to accept only one. Let's break down the issue and how you might resolve it.
Problem Analysis
Definition: historical_data_worker(symbol) is defined to accept only one parameter, symbol.
Error Message: historical_data_worker() takes 1 positional argument but 2 were given suggests that somewhere in your code, historical_data_worker is being called with an additional, unintended argument.
Possible Causes
Incorrect Function Call: There might be a place in your code where you accidentally call historical_data_worker with two arguments. For instance:
python
historical_data_worker('AAPL', 'extra_argument')
Threading or Pooling Issue: If historical_data_worker is used in conjunction with thread pools or process pools (like those from concurrent.futures or multiprocessing), a self or context argument might be silently passed, especially if the function is nested or indirectly referenced.
Decorator Misuse: If you're using decorators, they might be inadvertently passing additional arguments.
Solution Steps
Search for All Function Calls:
Search your codebase for all instances where historical_data_worker is called and ensure that it's only called with one argument.
Examine Context:
If used with threading or pooling, make sure the execution context is properly set up so that only the intended symbol is passed.
Check for Decorators:
If a decorator is applied to historical_data_worker, review its implementation to ensure no additional arguments are being introduced.
Review Function Signatures:
If historical_data_worker is referenced in a class or part of a larger module setup, ensure its definition is consistent with how it’s invoked (self should not be an issue unless it’s improperly used within a method context).
Debugging Log:
Add logging to check how and where the function is called, which might help identify inappropriate usages:
python
def historical_data_worker(symbol):
logging.debug(f"Calling historical_data_worker with symbol: {symbol}")
# rest of the function...
Once you have identified the specific instance where two arguments are being passed, correct the call to pass only the symbol parameter.
User
Where is the problem? Below is my code
import asyncio
import json
import os
import threading
import time
import django
import websockets
Set the environment variable to point to your project’s settings
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor, as_completed
import ccxt
import pandas as pd
import numpy as np
import talib as ta
from django.utils import timezone
from .models import Signal
import logging
from multiprocessing import Process, Event
from loguru import logger
Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("debug.log"), # Output logs to a file
logging.StreamHandler() # Also continue logging to the console
]
)
#logger.add("trading_bot.log", rotation="1 MB", compression="zip", retention="10 days")
class SignalGenerator:
def init(self, symbol='BTC/USDT', timeframe='1m', ):
self.symbol = symbol
self.timeframe = timeframe
self.url = f"wss://stream.binance.com:9443/ws/{self.symbol}@kline_{self.timeframe}"
self.exchange = ccxt.binance({
'options': {'defaultType': 'future'} # Configure for futures markets
})
self.df = pd.DataFrame()
logging.debug(f"Initialized SignalGenerator with symbol: {symbol}, timeframe: {timeframe}")
code
Assistant
The problem in your code arises from the way you're using the ProcessPoolExecutor in the main() function. Specifically, the executor.map() function is likely passing more arguments to historical_data_worker than it can handle. Let's break it down:
Identified Problem
In the main() function, you're using the ProcessPoolExecutor like this:
python
with ProcessPoolExecutor(max_workers=6) as executor:
signal_generators = list(executor.map(
historical_data_worker,
usdt_pairs,
['1m'] * len(usdt_pairs) # Assuming a 1-minute timeframe
))
The problem here is that executor.map() tries to pass each element of usdt_pairs and ['1m'] * len(usdt_pairs) as arguments to historical_data_worker. This ends up passing two arguments (a symbol and a timeframe) to historical_data_worker, but historical_data_worker is only defined to take one argument:
python
def historical_data_worker(symbol):
# ...
Solution
To align the function calls correctly, you need to update either the function definition or the way you map it. If your intention was for historical_data_worker to handle the timeframe argument as well, you’d need to redefine the function to accept two parameters, like this:
Modify historical_data_worker:
python
def historical_data_worker(symbol, timeframe='1m'): # Added timeframe parameter
signal_generator = SignalGenerator(symbol=symbol, timeframe=timeframe)
signal_generator.df = signal_generator.fetch_historical_data()
if not signal_generator.df.empty:
logging.info(f"Processed historical data for {symbol}")
signal_generator.run()
(Optional) Direct Mapping:
If you only wish to pass the symbol, use just the list of symbols in :
User
import asyncio
import json
import os
import threading
import time
import django
import websockets
Set the environment variable to point to your project’s settings
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor, as_completed
import ccxt
import pandas as pd
import numpy as np
import talib as ta
from django.utils import timezone
from .models import Signal
import logging
from multiprocessing import Process, Event
from loguru import logger
Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("debug.log"), # Output logs to a file
logging.StreamHandler() # Also continue logging to the console
]
)
#logger.add("trading_bot.log", rotation="1 MB", compression="zip", retention="10 days")
class SignalGenerator:
def init(self, symbol='BTC/USDT', timeframe='1m', ):
self.symbol = symbol
self.timeframe = timeframe
self.url = f"wss://stream.binance.com:9443/ws/{self.symbol}@kline_{self.timeframe}"
self.exchange = ccxt.binance({
'options': {'defaultType': 'future'} # Configure for futures markets
})
self.df = pd.DataFrame()
logging.debug(f"Initialized SignalGenerator with symbol: {symbol}, timeframe: {timeframe}")
code
Assistant
To generate real-time signals based on current price data while still utilizing historical data for technical analysis, you need to properly integrate real-time data fetching with the historical data. The key is to continuously update your DataFrame with the latest data from the websocket and then generate signals based on the updated data. Here’s how you can achieve that:
Steps to Implement Real-Time Signal Generation
Initialize Your DataFrame with Historical Data: Start by fetching historical data to initialize your DataFrame for technical indicators computation. This is what you're already doing.
Update the DataFrame with Real-Time Data: As new data comes in from the websocket, append it to your DataFrame and recalculate the signals.
Check for Signals Continuously: After appending the new data, immediately generate signals. This setup allows you to always have the most up-to-date market view for decision making.
Here's how you refine your existing code to achieve these steps:
Revised Approach
Enhance your collect_data function:
To update your DataFrame with real-time data and generate signals immediately.
python
async def collect_data(self, kline_data):
logging.debug(f"{self.symbol} - Latest: {kline_data}")
# Append the latest kline to the DataFrame
self.df = self.df.append(kline_data, ignore_index=True)
self.df.drop_duplicates(subset='timestamp', keep='last', inplace=True)
# Ensure the DataFrame is sorted by timestamp before generating signals
self.df.sort_values(by='timestamp', inplace=True)
# Recalculate and update signals based on new data
df_with_signals = self.generate_signals(self.df)
# Optionally: Log or save signals based on the latest data
if df_with_signals is not None:
latest_signal = df_with_signals.iloc[-1]['Signal']
logging.info(f"Real-time signal for {self.symbol}: {latest_signal}")
self.save_signals(df_with_signals)
User
If I run the code as it is with ProcessPoolExecutor, KeyboardInterrupt doesn't stop the process. So what ways can I use to stop it?
Assistant
When using ProcessPoolExecutor, stopping the processes with KeyboardInterrupt (Ctrl+C) can be a bit tricky because the subprocesses can ignore the signal. This behavior is due to how multiprocessing works in Python, where signals like KeyboardInterrupt are sent to the parent process, but child processes in a pool do not automatically forward or handle these signals.
Here are some strategies to handle KeyboardInterrupt to gracefully shut down your application:
1. Use shutdown with wait=True
You can use the shutdown method of the ProcessPoolExecutor, which will attempt to gracefully stop the executor:
python
with ProcessPoolExecutor(max_workers=6) as executor:
try:
signal_generators = list(executor.map(
historical_data_worker,
usdt_pairs
))
except KeyboardInterrupt:
logging.info("KeyboardInterrupt received. Shutting down executor...")
executor.shutdown(wait=True, cancel_futures=True)
logging.info("Executor has been shut down successfully.")
2. Custom Signal Handling
You can manually handle signals in your main script and propagate a shutdown event to subprocesses:
python
User
In wic folder in PostgreSQL are signals saved?
Assistant
In PostgreSQL, when you save data (such as your signals) using a Django model or other methods, the data is stored in a database, not directly as files in a directory. PostgreSQL databases consist of multiple components, including tables, indexes, and logs, but these are part of the database engine's structure rather than file-based storage you would navigate like a typical filesystem.
Here is an overview of how PostgreSQL data is managed:
Database Structure in PostgreSQL
Database Files:
PostgreSQL stores its data files in a data directory configured during the installation or managed by your database administrator.
These files are not intended to be accessed or modified directly. They include system catalogs, user data files, WAL (Write Ahead Logs), and configuration files.
Tablespace:
PostgreSQL uses tablespaces to manage storage of the database objects (tables, indexes, etc.) in files.
By default, all data is stored in the base directory inside the data directory, but custom tablespaces can be created to store data on different file systems.
Accessing Data:
You access and manipulate this data through SQL queries, typically using a database client or through a web application using Django ORM (Object-Relational Mapping).
Using Django ORM
In Django, when you save a Signal object using your models, you would typically do something like this:
Location: The PostgreSQL data directory location depends on your system setup and configuration. It might be under a path like /var/lib/pgsql/data on Linux, but this varies.
Contents: Contains subdirectories and files that store metadata, configurations, and actual data blobs.
Best Practices
Access Through SQL: Always access and manage database content through SQL interfaces or ORM tools like Django ORM, and never manipulate files directly.
User
Does that mean I can't see the signals even using pgAdmin?
Assistant
You can definitely see and manage your signals using pgAdmin or any other PostgreSQL client that you prefer. pgAdmin provides a graphical interface to view and interact with your PostgreSQL databases, which includes the ability to view tables, execute queries, and inspect data directly.
Here's how you can view your signals using pgAdmin:
Steps to View Signals in pgAdmin
Connect to Your Database:
Open pgAdmin and connect to your PostgreSQL server using the necessary credentials (host, port, username, password).
Navigate to Your Database:
In the server tree on the left, expand the list to find and expand your database (e.g., "binancebot" if that’s the name of your Django project database).
Locate the Table:
Inside your database, navigate to Schemas -> Public -> Tables.
Find the table corresponding to your Signal model. By default, if your Signal model is in a Django app named app_name, the table name might be app_name_signal unless explicitly defined otherwise in the model’s Meta class.
View Data:
Right-click on the table(s) and select View/Edit Data -> All Rows to see the stored signals.
This option will display all rows of data currently stored in the table, reflecting your real-time signals if they are actively being updated.
Query for Specific Data:
Use the Query Tool within pgAdmin to execute SQL queries for more specific views of your data, such as filtering by symbol or date range:
sql
SELECT * FROM app_name_signal WHERE symbol = 'BTC/USDT' ORDER BY timestamp DESC;
Considerations
Model-Table Mapping: Ensure you understand the mapping between your Django models and the PostgreSQL tables. Django’s ORM handles table creation and updates based on models, but the naming is generally predictable.
Database Migrations: Make sure your database migrations (manage.py makemigrations and manage.py migrate) have been successfully applied to reflect any recent changes in your Django models.
Permissions: Ensure that your user account used for accessing the database in pgAdmin has the appropriate permissions to view and query the tables.
By using pgAdmin, you can effectively manage and inspect the data in your PostgreSQL database, including the signals your application generates.
User
My debug log reached over 1gb of data. How do I delete it
Assistant
If your debug log has grown significantly and you need to reduce its size, you can either clear its content or delete it entirely, and then restart your logging process. Here are a few methods to manage large log files:
Method 1: Truncate the Log File
Truncating the file will remove its contents without deleting the file itself, allowing it to continue being used by your application.
bash
# This will empty the file without deleting it
> debug.log
Method 2: Delete the Log File
Deleting the file is straightforward and will remove the log file. Your application should typically recreate it as needed, though you might want to verify your logging setup to ensure this.
bash
# Delete the log file
rm debug.log
# Ensure your application or service is restarted to create a fresh log file
Method 3: Use Log Rotation
To prevent large log files in the future, set up log rotation. This automatically manages log file sizes by rotating them periodically or when they reach a certain size. You can use tools like logrotate on Linux or integrate log rotation within your Python application using modules such as logging.handlers.RotatingFileHandler.
maxBytes: Maximum size of the log file in bytes before it gets rotated. Adjust this according to how much log data you expect to generate.
backupCount: Number of backup files to keep. Old logs will be replaced as new logs are generated.
Using RotatingFileHandler ensures that once the debug.log file reaches the specified size, it will be renamed and a new log file will start. The old log will have a number appended, such as debug.log.1, debug.log.2, etc.
By implementing log rotation, you can effectively manage log file sizes and prevent them from consuming too much disk space unexpectedly.
User
(venv) PS D:\Binance\binancebot> > debug.log
: The term '>' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At line:1 char:1
The error message indicates you're using the PowerShell terminal, where the > redirection operator doesn't work the same way as in traditional Unix-based shells. In PowerShell, you need to use the Out-File cmdlet to clear a file or truncate its contents. Here's how you can empty or delete your log file in PowerShell:
Truncate the Log File Using Out-File
To truncate (clear) the contents of debug.log:
powershell
# Truncate the log file
"" | Out-File -FilePath "debug.log"
This command effectively writes an empty string to debug.log, clearing its contents without deleting the file.
Delete the Log File Using Remove-Item
To completely remove the log file:
powershell
# Delete the log file
Remove-Item -Path "debug.log"
This will delete the debug.log file entirely. If your application is actively writing to it, ensure the application can either recreate the log file or you restart the application to initiate the log file creation process.
Setting Up Log Rotation with Python
To prevent the log from growing too large again, consider setting up log rotation in your Python application using RotatingFileHandler as described earlier. This will help manage the log size automatically by creating new logs when the file reaches a specified size.
Implementing these steps should help you manage and control your log file's size effectively in a Windows environment using PowerShell.
User
After I Truncate the log file, it is now writing in Chinese
Assistant
If your log file starts to appear with unexpected characters or in a language like Chinese after truncating it, it's typically due to an encoding mismatch. This can happen if the log file was initially written with a particular encoding (like UTF-8) but is being read or appended using a different encoding.
Here’s how you can resolve this issue:
Steps to Ensure Proper Encoding
Check Your Logging Configuration:
Ensure that your logging handler explicitly specifies the correct encoding when opening the log file. For most cases, UTF-8 is a safe choice:
If you've encountered an encoding mismatch, delete the altered log file and let your logging configuration recreate it with the correct settings:
powershell
# Use PowerShell to remove the existing log file
Remove-Item -Path "debug.log"
Restart Your Application:
After adjusting encoding settings in your logging configuration and removing the old log file, restart your application to ensure it's writing logs using the correct encoding.
Verify File Encoding in Text Editors:
If you continue to encounter issues, some text editors allow you to specify or detect the file’s encoding. Use a text editor that can display the file encoding and ensure it's set to UTF-8 or your desired encoding when viewing the log file.
Explanation
Encoding Mismatch: When files are opened in an unspecified or incompatible encoding, the content may appear garbled or in a different language. This issue often arises when opening an existing file with a different encoding than the one used previously.
Handling Encoding Explicitly: Always specify the encoding in your logging handlers to avoid unexpected character representation, especially in environments with mixed encoding standards or settings.
These steps should ensure that your logs are consistently written in the correct encoding, preventing misinterpretation of log entries.
##def fetch_market_data(self):
def fetch_historical_data(self):
try:
since = self.exchange.parse8601('2024-07-01T00:00:00Z')
historical_bars = self.exchange.fetch_ohlcv(self.symbol, self.timeframe, since=since)
df = pd.DataFrame(historical_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
logging.info("Fetched historical data for {self.symbol} successfully.")
return df
except Exception as e:
logging.error(f"Error fetching historical data for {self.symbol}: {e}")
return pd.DataFrame()
async def fetch_realtime_data(self):
try:
async with websockets.connect(self.url) as websocket:
logging.info(f"Connected to websocket for {self.symbol}")
while True:
message = await websocket.recv()
data = json.loads(message)
# Extract kline data
kline = data['k']
kline_data = {
'timestamp': pd.to_datetime(kline['t'], unit='ms'),
'open': float(kline['o']),
'high': float(kline['h']),
'low': float(kline['l']),
'close': float(kline['c']),
'volume': float(kline['v']),
}
await self.collect_data(kline_data)
except Exception as e:
logging.error(f"Websocket connection error for {self.symbol}: {e}")
#return pd.DataFrame()
async def collect_data(self, kline_data):
logging.debug(f"{self.symbol} - Latest: {kline_data}")
self.df = self.df.append(kline_data, ignore_index=True)
self.df.drop_duplicates(subset='timestamp', keep='last', inplace=True)
self.generate_signals()
# Implement your data collection logic here, e.g., append to a DataFrame
def generate_signals(self, df):
if self.df.empty:
logging.error("No data present for signal generation.")
return
try:
df = self.df.copy()
# Ensure there is enough data to calculate indicators
if len(df) < 50:
logging.warning("Not enough data to perform full technical analysis.")
return
# Calculate EMAs
df['EMA20'] = ta.EMA(df['close'], timeperiod=20)
df['EMA50'] = ta.EMA(df['close'], timeperiod=50)
# Calculate Ichimoku Cloud components
nine_period_high = df['high'].rolling(window=9).max()
nine_period_low = df['low'].rolling(window=9).min()
df['tenkan_sen'] = (nine_period_high + nine_period_low) / 2
period26_high = df['high'].rolling(window=26).max()
period26_low = df['low'].rolling(window=26).min()
df['kijun_sen'] = (period26_high + period26_low) / 2
df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)
df['senkou_span_b'] = ((df['high'].rolling(window=52).max() + df['low'].rolling(window=52).min()) / 2).shift(26)
df['chikou_span'] = df['close'].shift(-26)
# Calculate ATR
df['ATR'] = ta.ATR(df['high'], df['low'], df['close'], timeperiod=14)
# Calculate RSI
df['RSI'] = ta.RSI(df['close'], timeperiod=14)
# Generate signals
bullish_cross = (df['EMA20'] > df['EMA50']) & (df['EMA20'].shift() <= df['EMA50'].shift())
bearish_cross = (df['EMA20'] < df['EMA50']) & (df['EMA20'].shift() >= df['EMA50'].shift())
price_above_cloud = df['close'] > df[['senkou_span_a', 'senkou_span_b']].max(axis=1)
price_below_cloud = df['close'] < df[['senkou_span_a', 'senkou_span_b']].min(axis=1)
rsi_overbought = df['RSI'] > 70
rsi_oversold = df['RSI'] < 30
# Define buy and sell conditions
conditions_for_buy = (bullish_cross & price_above_cloud & ~rsi_overbought)
conditions_for_sell = (bearish_cross & price_below_cloud & ~rsi_oversold)
df['Signal'] = np.where(conditions_for_buy, 'BUY', np.where(conditions_for_sell, 'SELL', 'HOLD'))
return df
#df['Signal'] = 'HOLD'
#df.loc[bullish_cross & price_above_cloud & ~rsi_overbought, 'Signal'] = 'BUY'
#df.loc[bearish_cross & price_below_cloud & ~rsi_oversold, 'Signal'] = 'SELL'
#last_signal = df.iloc[-1]['Signal']
# logging.debug(f"Generated signal for {self.symbol}: {last_signal}")
#self.save_signals(df)
except Exception as e:
logging.error(f"Error generating signals for {self.symbol}: {e}")
return df
def save_signals(self, df):
try:
last_signal = df.iloc[-1]
# Save all generated signals to the database
Signal.objects.update_or_create(
timestamp=timezone.make_aware(last_signal['timestamp']),
symbol=self.symbol,
defaults={
'price': last_signal['close'],
'signal_type': last_signal['Signal'],
}
)
logging.info(f"Signal saved for {self.symbol}: {last_signal['Signal']}")
except Exception as e:
logging.error(f"Error saving signals for {self.symbol} to database: {e}")
def run(self):
#while not stop_event.is_set():
df = self.fetch_historical_data()
#logging.debug(df.tail(5)) # Check the last few rows
if not df.empty:
df = self.generate_signals(df)
df = self.save_signals(df)
else:
logging.error("No data fetched, cannot proceed with signal generation.")
#stop_event.wait(1) # Check the event every second
def historical_data_worker(symbol):
signal_generator = SignalGenerator(symbol=symbol)
signal_generator.df = signal_generator.fetch_historical_data()
if not signal_generator.df.empty:
logging.info(f"Processed historical data for {symbol}")
signal_generator.run()
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
#usdt_pairs = [symbol for symbol in markets if symbol.endswith('/USDT')]
# Setup process pool for historical data
with ProcessPoolExecutor(max_workers=6) as executor:
signal_generators = list(executor.map(
historical_data_worker,
usdt_pairs,
#[exchange] * len(usdt_pairs), # Pass the same exchange instance
['1m'] * len(usdt_pairs) # Assuming a 1-minute timeframe
))
# Setup tasks for real-time data retrieval
tasks = []
#fetch_realtime_data(symbol, f'wss://your.websocket.url/{symbol}', collect_data)
#for symbol in usdt_pairs
#]
for signal_generator in signal_generators:
tasks.append(signal_generator.fetch_realtime_data())
# Use asyncio to run the real-time tasks concurrently
await asyncio.gather(*tasks)
if name == "main":
asyncio.run(main())
executor.map
python
with ProcessPoolExecutor(max_workers=6) as executor:
signal_generators = list(executor.map(
historical_data_worker,
usdt_pairs
))
If you don't actually need the timeframe as an argument to be varied in historical_data_worker, you should remove that second list argument to map.
By implementing the first approach, you ensure that historical_data_worker can accommodate the two arguments it's being passed without raising a TypeError. This change aligns with the original intent of the way you're using the ProcessPoolExecutor. If you're only interested in accommodating the current signature, ensure each mapped invocation aligns with the symbol parameter only.
##def fetch_market_data(self):
def fetch_historical_data(self):
try:
since = self.exchange.parse8601('2024-07-01T00:00:00Z')
historical_bars = self.exchange.fetch_ohlcv(self.symbol, self.timeframe, since=since)
df = pd.DataFrame(historical_bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
logging.info("Fetched historical data for {self.symbol} successfully.")
return df
except Exception as e:
logging.error(f"Error fetching historical data for {self.symbol}: {e}")
return pd.DataFrame()
async def fetch_realtime_data(self):
try:
async with websockets.connect(self.url) as websocket:
logging.info(f"Connected to websocket for {self.symbol}")
while True:
message = await websocket.recv()
data = json.loads(message)
# Extract kline data
kline = data['k']
kline_data = {
'timestamp': pd.to_datetime(kline['t'], unit='ms'),
'open': float(kline['o']),
'high': float(kline['h']),
'low': float(kline['l']),
'close': float(kline['c']),
'volume': float(kline['v']),
}
await self.collect_data(kline_data)
except Exception as e:
logging.error(f"Websocket connection error for {self.symbol}: {e}")
#return pd.DataFrame()
async def collect_data(self, kline_data):
logging.debug(f"{self.symbol} - Latest: {kline_data}")
self.df = self.df.append(kline_data, ignore_index=True)
self.df.drop_duplicates(subset='timestamp', keep='last', inplace=True)
self.generate_signals()
# Implement your data collection logic here, e.g., append to a DataFrame
def generate_signals(self, df):
if self.df.empty:
logging.error("No data present for signal generation.")
return
try:
df = self.df.copy()
# Ensure there is enough data to calculate indicators
if len(df) < 50:
logging.warning("Not enough data to perform full technical analysis.")
return
# Calculate EMAs
df['EMA20'] = ta.EMA(df['close'], timeperiod=20)
df['EMA50'] = ta.EMA(df['close'], timeperiod=50)
# Calculate Ichimoku Cloud components
nine_period_high = df['high'].rolling(window=9).max()
nine_period_low = df['low'].rolling(window=9).min()
df['tenkan_sen'] = (nine_period_high + nine_period_low) / 2
period26_high = df['high'].rolling(window=26).max()
period26_low = df['low'].rolling(window=26).min()
df['kijun_sen'] = (period26_high + period26_low) / 2
df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)
df['senkou_span_b'] = ((df['high'].rolling(window=52).max() + df['low'].rolling(window=52).min()) / 2).shift(26)
df['chikou_span'] = df['close'].shift(-26)
# Calculate ATR
df['ATR'] = ta.ATR(df['high'], df['low'], df['close'], timeperiod=14)
# Calculate RSI
df['RSI'] = ta.RSI(df['close'], timeperiod=14)
# Generate signals
bullish_cross = (df['EMA20'] > df['EMA50']) & (df['EMA20'].shift() <= df['EMA50'].shift())
bearish_cross = (df['EMA20'] < df['EMA50']) & (df['EMA20'].shift() >= df['EMA50'].shift())
price_above_cloud = df['close'] > df[['senkou_span_a', 'senkou_span_b']].max(axis=1)
price_below_cloud = df['close'] < df[['senkou_span_a', 'senkou_span_b']].min(axis=1)
rsi_overbought = df['RSI'] > 70
rsi_oversold = df['RSI'] < 30
# Define buy and sell conditions
conditions_for_buy = (bullish_cross & price_above_cloud & ~rsi_overbought)
conditions_for_sell = (bearish_cross & price_below_cloud & ~rsi_oversold)
df['Signal'] = np.where(conditions_for_buy, 'BUY', np.where(conditions_for_sell, 'SELL', 'HOLD'))
return df
#df['Signal'] = 'HOLD'
#df.loc[bullish_cross & price_above_cloud & ~rsi_overbought, 'Signal'] = 'BUY'
#df.loc[bearish_cross & price_below_cloud & ~rsi_oversold, 'Signal'] = 'SELL'
#last_signal = df.iloc[-1]['Signal']
# logging.debug(f"Generated signal for {self.symbol}: {last_signal}")
#self.save_signals(df)
except Exception as e:
logging.error(f"Error generating signals for {self.symbol}: {e}")
return df
def save_signals(self, df):
try:
last_signal = df.iloc[-1]
# Save all generated signals to the database
Signal.objects.update_or_create(
timestamp=timezone.make_aware(last_signal['timestamp']),
symbol=self.symbol,
defaults={
'price': last_signal['close'],
'signal_type': last_signal['Signal'],
}
)
logging.info(f"Signal saved for {self.symbol}: {last_signal['Signal']}")
except Exception as e:
logging.error(f"Error saving signals for {self.symbol} to database: {e}")
def run(self):
#while not stop_event.is_set():
df = self.fetch_historical_data()
#logging.debug(df.tail(5)) # Check the last few rows
if not df.empty:
df = self.generate_signals(df)
df = self.save_signals(df)
else:
logging.error("No data fetched, cannot proceed with signal generation.")
#stop_event.wait(1) # Check the event every second
def historical_data_worker(symbol):
signal_generator = SignalGenerator(symbol=symbol)
signal_generator.df = signal_generator.fetch_historical_data()
if not signal_generator.df.empty:
logging.info(f"Processed historical data for {symbol}")
signal_generator.run()
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
#usdt_pairs = [symbol for symbol in markets if symbol.endswith('/USDT')]
# Setup process pool for historical data
with ProcessPoolExecutor(max_workers=6) as executor:
signal_generators = list(executor.map(
historical_data_worker,
usdt_pairs,
#[exchange] * len(usdt_pairs), # Pass the same exchange instance
#['1m'] * len(usdt_pairs) # Assuming a 1-minute timeframe
))
# Setup tasks for real-time data retrieval
tasks = []
#fetch_realtime_data(symbol, f'wss://your.websocket.url/{symbol}', collect_data)
#for symbol in usdt_pairs
#]
for signal_generator in signal_generators:
tasks.append(signal_generator.fetch_realtime_data())
# Use asyncio to run the real-time tasks concurrently
await asyncio.gather(*tasks)
if name == "main":
asyncio.run(main())
When I run the above code, it only generates signals for previous periods like July 1. How do I make it generate signals that I can use today, and now. The historical data was to just help in technical analysis but there are also current price data from websockets, which should be used to produce realtime signals
Ensure asynchronous real-time data fetching continues unhindered:
The fetch_realtime_data method should run without blocking due to errors:
python
async def fetch_realtime_data(self):
retry_count = 0
while True:
try:
async with websockets.connect(self.url) as websocket:
logging.info(f"Connected to websocket for {self.symbol}")
while True:
message = await websocket.recv()
data = json.loads(message)
# Extract kline data
kline = data['k']
kline_data = {
'timestamp': pd.to_datetime(kline['t'], unit='ms'),
'open': float(kline['o']),
'high': float(kline['h']),
'low': float(kline['l']),
'close': float(kline['c']),
'volume': float(kline['v']),
}
await self.collect_data(kline_data)
except Exception as e:
logging.error(f"Websocket connection error for {self.symbol}: {e}")
retry_count += 1
if retry_count < 5: # Optional: Limit retries to avoid endless loop
logging.info("Retrying websocket connection...")
else:
logging.error(f"Exceeded maximum retries for websocket of {self.symbol}.")
break
Key Considerations
Real-time Processing: Each time new data comes in, you both update the DataFrame and generate new indicators/signals. Ensure you have enough data (at least 50 rows in your case) for meaningful calculations.
Asynchronous Task Handling: Websocket connections are handled asynchronously to allow multiple symbols to be processed simultaneously without blocking.
Error and Retry Handling: Implement retry logic for websocket connections to handle intermittent network issues gracefully.
By implementing these steps, your system should continuously fetch real-time data and update signals, providing up-to-date trading recommendations.
import signal
import sys
shut_down = False
def signal_handler(sig, frame):
global shut_down
print("Shutdown initiated...")
shut_down = True
# Register the signal handler
signal.signal(signal.SIGINT, signal_handler)
def historical_data_worker(symbol):
while not shut_down:
# Your task logic
time.sleep(1) # Simulate ongoing task
logging.info(f"Worker for {symbol} is shutting down.")
async def main():
exchange = ccxt.binance({'options': {'defaultType': 'future'}})
markets = exchange.fetch_markets()
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
with ProcessPoolExecutor(max_workers=6) as executor:
try:
futures = [executor.submit(historical_data_worker, symbol) for symbol in usdt_pairs]
# Optionally gather their results if needed
done, pending = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_COMPLETED)
except KeyboardInterrupt:
logging.info("KeyboardInterrupt received. Shutting down executor...")
executor.shutdown(wait=True, cancel_futures=True)
logging.info("Executor has been shut down successfully.")
3. Use asyncio and cleanup tasks
When using asyncio, it’s important to handle cleanup gracefully. Here’s how you can tie asyncio with signal handling:
python
def main():
asyncio.run(start_async_operations())
async def start_async_operations():
try:
await run_your_tasks() # Replace with the actual function that starts tasks
except KeyboardInterrupt:
logging.info("Stopping asynchronous operations due to KeyboardInterrupt.")
finally:
await cleanup_tasks() # Ensure cleanup tasks are awaited if necessary
def run_your_tasks():
# Your task logic
pass
async def cleanup_tasks():
# Do cleanup tasks like closing websockets or connections
pass
Key Considerations
Signal Propagation: When using ProcessPoolExecutor, signals are not propagated to subprocesses. You need to handle cleanup explicitly.
Graceful Shutdown: Ensure all open connections or resources are properly closed in your shutdown logic.
Consistent Logging: Track shutdown and cleanup processes in your logs for easier debugging.
Implementing these changes should allow you to handle KeyboardInterrupt and shut down your application gracefully.
Backups and Snapshots: For accessing the data externally, consider making SQL dumps or using snapshot utilities provided by PostgreSQL.
Database Management Tools: Use tools like pgAdmin, psql (command-line tool), or any other SQL client to interact with databases at a higher level intended for users and administrators.
This abstracted layer over the actual file storage ensures data integrity, consistency, and ease of access without having to deal with the complexities of how the data is physically stored on disk.