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()
code
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}")
The two functions above, one is to retrieve historical and the other fetches realtime price data. Can you combine the two functions above, say in another function to combine the two prices so as to have one continous price of an asset to make it easy to perform analysis
Assistant
To combine historical and real-time data into a continuous dataset for analysis, you can create a new function that first retrieves and processes the historical data, and then continuously updates this data in real time with data from the websocket. Below is an example implementation:
python
import pandas as pd
import asyncio
import logging
import json
import websockets
class DataFetcher:
def __init__(self, exchange, symbol, timeframe, url):
self.exchange = exchange
self.symbol = symbol
self.timeframe = timeframe
self.url = url
self.data = pd.DataFrame()
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(f"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):
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)
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']),
}
self.data = self.data.append(kline_data, ignore_index=True)
logging.info(f"Added new real-time data for {self.symbol}")
async def combine_data(self):
# Fetch historical data
self.data = self.fetch_historical_data()
# Start real-time data gathering
await self.fetch_realtime_data()
async def run(self):
await self.combine_data()
# Usage example with an exchange client, symbol, timeframe, and websocket URL
# exchange_client = ... # Initialize your exchange client here
# symbol = 'BTC/USD'
# timeframe = '1m' # 1 minute timeframe for example
# websocket_url = 'wss://api.example.com/ws'
# data_fetcher = DataFetcher(exchange_client, symbol, timeframe, websocket_url)
# asyncio.run(data_fetcher.run())
User
async def run(self):
#while not stop_event.is_set():
await self.combine_data()
#df = self.collect_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)
Is the above correct? What is missing?
Assistant
The code snippet you provided attempts to run a continuous data-fetching and processing loop for market data, but it has some issues that need to be addressed for correct functionality. Here are some considerations and modifications:
Correctly Define and Use stop_event: If you are attempting to control the execution flow with a stop_event, you need to define it properly. You typically use asyncio.Event or similar synchronization primitives.
Data Management: The variable df (dataframe) needs to be correctly defined and manipulated. It seems you are trying to fetch data and process signals, but df seems undefined in some parts of the script.
Flow Logic: Ensure that each step in your execution flow is clearly defined and processed.
Here is a revised version of your run method, implemented within a class context:
python
import asyncio
import logging
class DataFetcher:
# Initialization and other methods...
async def run(self, stop_event):
while not stop_event.is_set():
# Fetch and combine historical and real-time data
self.data = self.fetch_historical_data()
await self.fetch_realtime_data()
# Assuming collect_data is meant to process the combined dataframe
if not self.data.empty:
processed_df = self.collect_data(self.data)
# Check recent rows (for debug purposes)
logging.debug(processed_df.tail(5))
# Process signals
if not processed_df.empty:
signals_df = self.generate_signals(processed_df)
self.save_signals(signals_df)
# Dummy implementations for illustration
def collect_data(self, data):
# Example processing and return new dataframe
return data
def generate_signals(self, data):
# Example signal generation logic
return data
def save_signals(self, data):
# Example save logic
return data
# Example usage
async def main():
stop_event = asyncio.Event() # Initialize the stop event
data_fetcher = DataFetcher(...) # Initialize with appropriate params
try:
await data_fetcher.run(stop_event)
except Exception as e:
logging.error(f"Error during data fetching/processing: {e}")
finally:
stop_event.set()
# Run the main function
# asyncio.run(main()) # Uncomment to run
# If you are running this code directly, make sure to uncomment asyncio.run(main())
User
async def run(self):
await self.combine_data()
if not df.empty:
df = self.generate_signals(df)
df = self.save_signals(df)
Is the above correct? What is missing?
Assistant
The provided run method has several issues that need to be addressed for it to function correctly. Here's a breakdown of what's missing or incorrect:
Indentation and Formatting: In Python, indentation is crucial since it defines the block of code. Make sure to keep consistent indentation so that the code executes as expected.
DataFrame Management: You reference df, but it's unclear where df is initialized or defined. This needs to be managed properly.
Asynchronous Context: Ensure that all asynchronous operations are correctly awaited.
Here is a revised version, focusing on fixing these key issues:
python
import pandas as pd
class DataFetcher:
# Define other methods and initialization...
async def run(self):
# Combined data is stored in self.data
await self.combine_data()
# Check if `self.data` (or alternatively `df`) is not empty
if not self.data.empty:
# Generate and save signals if `self.data` is defined and contains data
self.data = self.generate_signals(self.data)
self.data = self.save_signals(self.data)
def combine_data(self):
# This method should async fetch both historical and real-time data
# Here you can call a method that will fetch and combine both
historical_data = self.fetch_historical_data()
# In this example, we'll assume real-time data appends to `self.data`
asyncio.create_task(self.fetch_realtime_data())
# Start with historical data
self.data = historical_data
def generate_signals(self, df):
# Logic to generate signals from data
return df # Return the processed dataframe
def save_signals(self, df):
# Logic to save signals for further use or analysis
return df # Return the saved dataframe
# Example execution context
async def main():
data_fetcher = DataFetcher(...) # Initialize with appropriate parameters
await data_fetcher.run()
# Coroutine entry point
# asyncio.run(main()) # Uncomment this to run the main function
User
async def run(self):
await self.combine_data()
df = self.combine_data()
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.")
Is the above correct? What is missing?
Assistant
The code you provided has some issues that need to be addressed. Here's what you need to fix:
Duplicate Data Fetch: You're calling await self.combine_data() followed by df = self.combine_data(). This results in two calls, where the first uses await and the second doesn't. Also, you seem to expect a return value, but await is usually used with functions that don't return result synchronously.
Data Handling: Ensure proper handling of the data and avoid overwriting.
Indentation and Syntax: Ensure consistent and correct indentation. There's an indentation issue with if not df.empty:. Moreover, Python's syntax requires a space after the if statement.
Here's a corrected version of your method, assuming combine_data updates a class attribute:
python
import logging
class DataFetcher:
# Initialization, other methods, and attributes...
async def combine_data(self):
# Fetch historical data
historical_data = self.fetch_historical_data()
# Assign historical data to a class attribute (or handle it appropriately)
self.data = historical_data
# Start fetching real-time data which should update self.data
await self.fetch_realtime_data()
async def run(self):
await self.combine_data()
# Access the combined data stored in a class attribute (e.g., self.data)
if not self.data.empty:
# Generate and save signals using the current self.data
self.data = self.generate_signals(self.data)
self.data = self.save_signals(self.data)
else:
logging.error("No data fetched, cannot proceed with signal generation.")
def generate_signals(self, df):
# Generate trading signals logic
return df
def save_signals(self, df):
# Save signals logic
return df
# Example usage with the main function
async def main():
data_fetcher = DataFetcher(...) # Initialize with appropriate parameters
await data_fetcher.run()
# Entry point to execute run within an asyncio context
# asyncio.run(main()) # Uncomment to run
User
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)
except Exception as e:
logging.error(f"Websocket connection error for {self.symbol}: {e}")
The two functions above, one is to retrieve historical and the other fetches realtime price data. Can you combine the two functions above, say in another function called combined_data to combine the two prices so as to have one continous price of an asset to make it easy to perform analysis. Integrate it into the below function that uses the combined data to perform analysis and generate signals
def run(self):
df = self.combined_data()
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.")
Assistant
To integrate your historical and real-time data fetching into a single continuous dataset and use this for analysis and signal generation, you'll need to carry out the following steps in a structured manner. Here's how you can implement the combined_data method and integrate it into your run function:
Key Tasks:
Fetching Historical Data: Load historical data first to initialize your dataset.
Appending Real-time Data: Continuously update your dataset with real-time data.
Processing and Generating Signals: Use your up-to-date dataset to generate and save trading signals.
Below is the full implementation:
python
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", encoding='utf-8'), # Output logs to a file
logging.StreamHandler() # Also continue logging to the console
]
)
logger.add("trading_bot.log", rotation="5 MB", retention="2 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 replace the built-in logging module with loguru and configure it to output logs both to a file and the console, you need to set up loguru at the start of your script. Below is how you can achieve this with loguru, focusing solely on logging aspects:
python
from loguru import logger
# Configure loguru to write logs to a file and also output to console
logger.add("trading_bot.log", rotation="5 MB", retention="2 days", level="DEBUG") # File logging
logger.add(sys.stdout, level="DEBUG") # Console logging
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()
logger.debug(f"Initialized SignalGenerator with symbol: {symbol}, timeframe: {timeframe}")
# Replace all instances of logging with logger from loguru
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')
logger.info(f"Fetched historical data for {self.symbol} successfully.")
return df
except Exception as e:
logger.error(f"Error fetching historical data for {self.symbol}: {e}")
return pd.DataFrame()
# Other methods...
# Usage in the code would be the same, replacing logging calls with logger
User
(venv) PS D:\Binance\binancebot> python -m signals.tradlog
2024-09-17 15:44:18.160 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: BTC/USDT, timeframe: 1m
2024-09-17 15:44:18.160 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: BTC/USDT, timeframe: 1m
2024-09-17 15:44:18.526 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: ETH/USDT, timeframe: 1m
2024-09-17 15:44:18.526 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: ETH/USDT, timeframe: 1m
2024-09-17 15:44:18.590 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: BNB/USDT, timeframe: 1m
2024-09-17 15:44:18.590 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: BNB/USDT, timeframe: 1m
2024-09-17 15:44:18.707 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: BCC/USDT, timeframe: 1m
2024-09-17 15:44:18.707 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: BCC/USDT, timeframe: 1m
2024-09-17 15:44:18.938 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: NEO/USDT, timeframe: 1m
2024-09-17 15:44:18.938 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: NEO/USDT, timeframe: 1m
2024-09-17 15:44:19.001 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: LTC/USDT, timeframe: 1m
2024-09-17 15:44:19.001 | DEBUG | mp_main:init:49 - Initialized SignalGenerator with symbol: LTC/USDT, timeframe: 1m
2024-09-17 15:44:33.973 | ERROR | mp_main:fetch_historical_data:61 - Error fetching historical data for BCC/USDT: binance does not have market symbol BCC/USDT
2024-09-17 15:44:33.973 | ERROR | mp_main:fetch_historical_data:61 - Error fetching historical data for BCC/USDT: binance does not have market symbol BCC/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:34.185 | INFO | mp_main:fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:34.185 | INFO | mp_main:fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:34.219 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:34.219 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:34.344 | INFO | :historical_data_worker:204 - Processed historical data for BTC/USDT
2024-09-17 15:44:34.344 | INFO | :historical_data_worker:204 - Processed historical data for BTC/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:34.455 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:34.455 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:34.903 | INFO | :historical_data_worker:204 - Processed historical data for BNB/USDT
2024-09-17 15:44:34.903 | INFO | :historical_data_worker:204 - Processed historical data for BNB/USDT
2024-09-17 15:44:34.670 | DEBUG | ::49 - Initialized SignalGenerator with symbol: QTUM/USDT, timeframe: 1m
2024-09-17 15:44:34.670 | DEBUG | ::49 - Initialized SignalGenerator with symbol: QTUM/USDT, timeframe: 1m
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:34.222 | INFO | :historical_data_worker:204 - Processed historical data for ETH/USDT
2024-09-17 15:44:34.222 | INFO | :historical_data_worker:204 - Processed historical data for ETH/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:35.313 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ADA/USDT, timeframe: 1m
2024-09-17 15:44:35.313 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ADA/USDT, timeframe: 1m
2024-09-17 15:44:35.418 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:35.418 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:35.427 | INFO | :historical_data_worker:204 - Processed historical data for LTC/USDT
2024-09-17 15:44:35.427 | INFO | :historical_data_worker:204 - Processed historical data for LTC/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:35.593 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:35.593 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:35.601 | INFO | :historical_data_worker:204 - Processed historical data for NEO/USDT
2024-09-17 15:44:35.609 | DEBUG | ::49 - Initialized SignalGenerator with symbol: XRP/USDT, timeframe: 1m
2024-09-17 15:44:35.609 | DEBUG | ::49 - Initialized SignalGenerator with symbol: XRP/USDT, timeframe: 1m
2024-09-17 15:44:35.601 | INFO | :historical_data_worker:204 - Processed historical data for NEO/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:35.677 | DEBUG | ::49 - Initialized SignalGenerator with symbol: EOS/USDT, timeframe: 1m
2024-09-17 15:44:35.677 | DEBUG | ::49 - Initialized SignalGenerator with symbol: EOS/USDT, timeframe: 1m
2024-09-17 15:44:35.800 | DEBUG | ::49 - Initialized SignalGenerator with symbol: TUSD/USDT, timeframe: 1m
2024-09-17 15:44:35.800 | DEBUG | ::49 - Initialized SignalGenerator with symbol: TUSD/USDT, timeframe: 1m
2024-09-17 15:44:36.031 | DEBUG | ::49 - Initialized SignalGenerator with symbol: IOTA/USDT, timeframe: 1m
2024-09-17 15:44:36.031 | DEBUG | ::49 - Initialized SignalGenerator with symbol: IOTA/USDT, timeframe: 1m
2024-09-17 15:44:49.664 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:49.664 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:49.678 | INFO | :historical_data_worker:204 - Processed historical data for ADA/USDT
2024-09-17 15:44:49.678 | INFO | :historical_data_worker:204 - Processed historical data for ADA/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:49.723 | ERROR | :fetch_historical_data:61 - Error fetching historical data for TUSD/USDT: binance
does not have market symbol TUSD/USDT
2024-09-17 15:44:49.723 | ERROR | :fetch_historical_data:61 - Error fetching historical data for TUSD/USDT: binance
does not have market symbol TUSD/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:49.857 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:49.857 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:49.865 | INFO | :historical_data_worker:204 - Processed historical data for QTUM/USDT
2024-09-17 15:44:49.893 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:49.893 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:49.927 | INFO | :historical_data_worker:204 - Processed historical data for EOS/USDT
2024-09-17 15:44:49.927 | INFO | :historical_data_worker:204 - Processed historical data for EOS/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:49.865 | INFO | :historical_data_worker:204 - Processed historical data for QTUM/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:50.062 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:50.062 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:50.079 | INFO | :historical_data_worker:204 - Processed historical data for IOTA/USDT
2024-09-17 15:44:50.079 | INFO | :historical_data_worker:204 - Processed historical data for IOTA/USDT
2024-09-17 15:44:50.132 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:50.132 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:44:50.210 | INFO | :historical_data_worker:204 - Processed historical data for XRP/USDT
2024-09-17 15:44:50.210 | INFO | :historical_data_worker:204 - Processed historical data for XRP/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:44:50.222 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ONT/USDT, timeframe: 1m
2024-09-17 15:44:50.222 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ONT/USDT, timeframe: 1m
2024-09-17 15:44:50.170 | DEBUG | ::49 - Initialized SignalGenerator with symbol: XLM/USDT, timeframe: 1m
2024-09-17 15:44:50.170 | DEBUG | ::49 - Initialized SignalGenerator with symbol: XLM/USDT, timeframe: 1m
2024-09-17 15:44:50.383 | DEBUG | ::49 - Initialized SignalGenerator with symbol: TRX/USDT, timeframe: 1m
2024-09-17 15:44:50.380 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ETC/USDT, timeframe: 1m
2024-09-17 15:44:50.380 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ETC/USDT, timeframe: 1m
2024-09-17 15:44:50.383 | DEBUG | ::49 - Initialized SignalGenerator with symbol: TRX/USDT, timeframe: 1m
2024-09-17 15:44:50.549 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ICX/USDT, timeframe: 1m
2024-09-17 15:44:50.549 | DEBUG | ::49 - Initialized SignalGenerator with symbol: ICX/USDT, timeframe: 1m
2024-09-17 15:44:50.566 | DEBUG | ::49 - Initialized SignalGenerator with symbol: VEN/USDT, timeframe: 1m
2024-09-17 15:44:50.566 | DEBUG | ::49 - Initialized SignalGenerator with symbol: VEN/USDT, timeframe: 1m
2024-09-17 15:45:06.215 | ERROR | :fetch_historical_data:61 - Error fetching historical data for VEN/USDT: binance does not have market symbol VEN/USDT
2024-09-17 15:45:06.215 | ERROR | :fetch_historical_data:61 - Error fetching historical data for VEN/USDT: binance does not have market symbol VEN/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:45:06.441 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.441 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.448 | INFO | :historical_data_worker:204 - Processed historical data for ONT/USDT
2024-09-17 15:45:06.448 | INFO | :historical_data_worker:204 - Processed historical data for ONT/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:45:06.628 | DEBUG | ::49 - Initialized SignalGenerator with symbol: NULS/USDT, timeframe: 1m
2024-09-17 15:45:06.628 | DEBUG | ::49 - Initialized SignalGenerator with symbol: NULS/USDT, timeframe: 1m
2024-09-17 15:45:06.738 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.738 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.746 | DEBUG | ::49 - Initialized SignalGenerator with symbol: VET/USDT, timeframe: 1m
2024-09-17 15:45:06.746 | INFO | :historical_data_worker:204 - Processed historical data for XLM/USDT
2024-09-17 15:45:06.746 | DEBUG | ::49 - Initialized SignalGenerator with symbol: VET/USDT, timeframe: 1m
2024-09-17 15:45:06.746 | INFO | :historical_data_worker:204 - Processed historical data for XLM/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:45:06.843 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.843 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.852 | INFO | :historical_data_worker:204 - Processed historical data for ETC/USDT
2024-09-17 15:45:06.858 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.858 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.882 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.891 | INFO | :historical_data_worker:204 - Processed historical data for TRX/USDT
2024-09-17 15:45:06.882 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:06.852 | INFO | :historical_data_worker:204 - Processed historical data for ETC/USDT
2024-09-17 15:45:06.891 | INFO | :historical_data_worker:204 - Processed historical data for TRX/USDT
2024-09-17 15:45:06.897 | INFO | :historical_data_worker:204 - Processed historical data for ICX/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:45:06.897 | INFO | :historical_data_worker:204 - Processed historical data for ICX/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
signal_generator.run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-09-17 15:45:07.111 | DEBUG | ::49 - Initialized SignalGenerator with symbol: PAX/USDT, timeframe: 1m
2024-09-17 15:45:07.111 | DEBUG | ::49 - Initialized SignalGenerator with symbol: PAX/USDT, timeframe: 1m
2024-09-17 15:45:07.211 | DEBUG | ::49 - Initialized SignalGenerator with symbol: BCHABC/USDT, timeframe: 1m2024-09-17 15:45:07.211 | DEBUG | ::49 - Initialized SignalGenerator with symbol: BCHABC/USDT, timeframe: 1m2024-09-17 15:45:07.260 | DEBUG | ::49 - Initialized SignalGenerator with symbol: BSV/USDT, timeframe: 1m
2024-09-17 15:45:07.260 | DEBUG | ::49 - Initialized SignalGenerator with symbol: BSV/USDT, timeframe: 1m
2024-09-17 15:45:07.293 | DEBUG | ::49 - Initialized SignalGenerator with symbol: USDC/USDT, timeframe: 1m
2024-09-17 15:45:07.293 | DEBUG | ::49 - Initialized SignalGenerator with symbol: USDC/USDT, timeframe: 1m
2024-09-17 15:45:21.771 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:21.771 | INFO | :fetch_historical_data:58 - Fetched historical data for {self.symbol} successfully.
2024-09-17 15:45:21.780 | INFO | :historical_data_worker:204 - Processed historical data for NULS/USDT
2024-09-17 15:45:21.780 | INFO | :historical_data_worker:204 - Processed historical data for NULS/USDT
D:\Binance\binancebot\signals\tradlog.py:205: RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited
Assistant
You've encountered two main issues in your script:
Logging Duplication: You're seeing duplicate log entries. This might be due to multiple handlers or sources of logging messages being configured. Given the setup with both the basicConfig for the standard logging (which is commented out) and loguru, this might appear if parts of your script using standard logging were not fully switched over to loguru.
Coroutines Not Awaited: The error RuntimeWarning: coroutine 'SignalGenerator.run' was never awaited occurs because you're calling an asynchronous function (run) without await. In Python, async functions must be awaited to execute properly.
Fixing the Code
Ensure Proper Awaiting:
The run method in SignalGenerator is asynchronous (async def run(self):). It should be awaited wherever it is called, particularly within the historical_data_worker function.
Loguru Logging Setup:
Since you've transitioned to using loguru, make sure that all instances of logging in your code are using loguru's logger. Ensure that all log entries are generated by logger.info, logger.debug, etc., for consistency.
Revised Code Strategy
Here's how you can address the issues:
python
User
Also in the above code, in the logging it shows that signals were saved but are not in the database
Assistant
If your logs indicate that signals should have been saved but they do not appear in your database, several issues could be causing this discrepancy. Here are some possible causes and steps to troubleshoot and resolve the issue:
Possible Causes and Solutions
Database Configuration:
Ensure the database settings in your Django project are correct and match the database you expect to be using (e.g., correct database name, user, password, host, and port).
Django Models and Migrations:
Make sure the Signal model is correctly defined and that all migrations have been applied. Run python manage.py makemigrations and python manage.py migrate to ensure your database schema is up to date.
Transaction Management:
If you're making multiple changes to the database in a single transaction, ensure transactions are being committed. Django’s ORM usually handles this, but if you explicitly manage transactions, check that they are committed.
Signal Saving Logic:
Verify the logic in the save_signals method. Ensure that:
The update_or_create method is called with correct and sufficient conditions.
The attributes being saved match those expected in your model.
Check for any exceptions that might be silently catching issues without logging errors. If your error handling around the signal save is logger.error, ensure no try-except inadvertently silences errors.
Data Validation:
Ensure the data being saved matches the model’s field types and constraints. For instance, date fields should match Django’s timezone-aware datetime.
Logging Verification:
Ensure that logs accurately capture the flow. You can add additional debugging logs within the save_signals function to log the data and the result returned by update_or_create.
Updated save_signals Implementation with Debugging
Here's how you might adjust your save_signals method for additional debugging:
python
User
After the modifications you said it now says (venv) PS D:\Binance\binancebot> python -m signals.tradlog
C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py:271: RuntimeWarning: coroutine 'historical_data_worker' was never awaited
del r
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py:271: RuntimeWarning: coroutine 'historical_data_worker' was never awaited
del r
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py:271: RuntimeWarning: coroutine 'historical_data_worker' was never awaited
del r
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py:271: RuntimeWarning: coroutine 'historical_data_worker' was never awaited
del r
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
concurrent.futures.process._RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py", line 219, in _sendback_result
result_queue.put(_ResultItem(work_id, result=result,
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\queues.py", line 393, in put
obj = _ForkingPickler.dumps(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: cannot pickle 'coroutine' object
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "", line 198, in _run_module_as_main
File "", line 88, in _run_code
File "D:\Binance\binancebot\signals\tradlog.py", line 238, in
asyncio.run(main())
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "D:\Binance\binancebot\signals\tradlog.py", line 218, in main
await asyncio.gather(*tasks)
TypeError: cannot pickle 'coroutine' object
Assistant
The error you're seeing is due to an attempt to use an asyncio coroutine (historical_data_worker) in a ProcessPoolExecutor, which operates in a separate process context and does not support asynchronous coroutines directly. The error message indicates that a coroutine object could not be pickled, which is required when passing objects between processes.
Solutions
Use a Synchronous Function with ProcessPoolExecutor:
Ensure that tasks scheduled with ProcessPoolExecutor are synchronous. You can call coroutines within these functions using asyncio.run() if needed for a blocking call.
Use ThreadPoolExecutor for Concurrent I/O:
If your objective is to concurrently manage I/O-bound tasks, consider using ThreadPoolExecutor or native async support.
Modifying Your Code
Here's how to adjust the function to be synchronous for ProcessPoolExecutor:
python
import asyncio
from concurrent.futures import ProcessPoolExecutor
import logging
logger = logging.getLogger(__name__)
def historical_data_worker(symbol):
# This function should operate synchronously in a separate process
signal_generator = SignalGenerator(symbol=symbol)
df = signal_generator.fetch_historical_data() # Synchronous call
if not df.empty:
logger.info(f"Processed historical data for {symbol}")
# Run any coroutine using 'asyncio.run' if blocking behavior is acceptable.
try:
asyncio.run(signal_generator.run())
except Exception as e:
logger.error(f"Error running signal processing for {symbol}: {e}")
async def main():
# Fetch USDT pairs and set up the executor
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:
# Map 'historical_data_worker' synchronously over the pairs
executor.map(historical_data_worker, usdt_pairs)
except KeyboardInterrupt:
logger.info("KeyboardInterrupt received. Shutting down executor...")
executor.shutdown(wait=True, cancel_futures=True)
logger.info("Executor has been shut down successfully.")
# Run the main coroutine
if __name__ == "__main__":
asyncio.run(main())
Initialization: The DataFetcher class handles the fetching and combination of historical and real-time data.
Historical Data: The fetch_historical_data method retrieves historical data up to a specified start date.
Real-time Data: The fetch_realtime_data method continuously receives real-time data using a websocket and appends it to the existing dataframe.
Combine Data: The combine_data method sequentially calls methods to fetch historical and real-time data, and updates a shared dataframe.
Execution: Use the run method to start the combined data fetching and updating process.
This setup allows you to maintain a continuously updated dataframe of price data for analysis. Adjust the logging and error handling as necessary for your specific use case.
Key Adjustments and Considerations:
Stop Event: Make sure to pass and correctly handle a stop_event to control the loop. This can be useful for clean shutdowns.
Data Handling: Ensure that self.data (or df) is consistently operated upon and updated.
Collect, Generate, and Save: Your subsidiary methods (collect_data, generate_signals, and save_signals) should return and operate correctly on dataframes. Modify these as per their intended logic.
Asynchronous Context: Since you're executing this in an async context, ensure that any blocking operations are appropriately handled.
This setup assumes you have the necessary exchange and market data methods already defined in your class. Adjust parameters and logic according to your specific application requirements.
Explanation:
Indentation: The issues with indentation are resolved to ensure the code structure is clear.
DataFrame (df) Management: Use self.data (or a similar class-level variable) to manage the combined dataset, ensuring that it is consistently available for operations like signal generation and saving.
Asynchronous Combination: The combine_data method needs to initiate both the historical data fetch and the continuous real-time data fetching.
Sequential Processing: Ensure generate_signals and save_signals are operating on the correctly updated version of the DataFrame.
Async Tasks: Use asynchronous patterns (asyncio.create_task) correctly for real-time data fetching.
Calling from Main: Ensure to correctly initialize and run the entire class in an async context, handling exceptions and clean-ups as necessary.
Key Points:
Remove Duplicate Calls: Make a single call to await self.combine_data() to handle data combination.
Class Attribute for Data: Use an instance attribute (self.data) to store and manage combined data, avoiding local variable confusion.
Await and Async: Ensure combine_data includes await for tasks that require asynchronous execution (like real-time fetching).
Error Logging: Retain the error logging mechanism to handle cases where no data is available for processing.
This structure will help maintain clarity and data integrity across the execution of your data fetching and processing pipeline. Adjust other details to fit within your actual class and application context.
import asyncio
import json
import logging
import pandas as pd
import websockets
class DataFetcher:
def __init__(self, exchange, symbol, timeframe, url):
self.exchange = exchange
self.symbol = symbol
self.timeframe = timeframe
self.url = url
self.data = pd.DataFrame()
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(f"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']),
}
self.data = self.data.append(kline_data, ignore_index=True)
self.data.drop_duplicates(subset='timestamp', keep='last', inplace=True)
except Exception as e:
logging.error(f"Websocket connection error for {self.symbol}: {e}")
async def combined_data(self):
# Fetch the historical data first
self.data = self.fetch_historical_data()
# Start the real-time data gathering and combining
await self.fetch_realtime_data()
def generate_signals(self, df):
# Implement your signal generation logic here
# This is just a placeholder
return df
def save_signals(self, df):
# Implement your signal saving logic here
# This is just a placeholder
return df
async def run(self):
await self.combined_data()
if not self.data.empty:
self.data = self.generate_signals(self.data)
self.data = self.save_signals(self.data)
else:
logging.error("No data fetched, cannot proceed with signal generation.")
# Usage example
async def main():
# Initialize exchange client and other parameters here
data_fetcher = DataFetcher(exchange=None, symbol='BTC/USD', timeframe='1m', url='wss://api.example.com/ws')
await data_fetcher.run()
# Run the main coroutine when you need it, for example during script execution
# asyncio.run(main()) # Uncomment this to run the asyncio-based function
Important Points:
DataFrame Initialization and Management: The class attribute self.data is used to hold the combined dataset for both historical and real-time data.
Real-time Update: The method fetch_realtime_data continuously appends new real-time data to self.data. To keep the data consistent, duplicates are removed based on the 'timestamp' column.
Signals Generation: Once the data is up-to-date, generate_signals and save_signals can be called to generate trading signals and potentially save them for further analysis or action.
Asynchronous Execution: fetch_realtime_data is designed for asynchronous execution to keep the connection open and listen for new data.
This structure allows the code to begin processing a pre-existing dataset and continuously make it more robust with real-time updates, thereby facilitating ongoing analysis. Adjust the placeholders and integration details based on your specific requirements, such as signal generation logic and real-time endpoint URL.
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.df.sort_values(by='timestamp', inplace=True)
async def combine_data(self):
# Fetch historical data
self.df = self.fetch_historical_data()
# Start real-time data gathering
await self.fetch_realtime_data()
#self.generate_signals()
#df_with_signals = self.generate_signals(self.df)
#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)
# 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']}")
return df
except Exception as e:
logging.error(f"Error saving signals for {self.symbol} to database: {e}")
return df
async def run(self):
await self.combine_data()
if not self.df.empty:
self.df = self.generate_signals(self.df)
self.df = self.save_signals(self.df)
#df = self.combined_data()
#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:
try:
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
))
except KeyboardInterrupt:
logging.info("KeyboardInterrupt received. Shutting down executor…")
executor.shutdown(wait=True, cancel_futures=True)
logging.info("Executor has been shut down successfully.")
# 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())
In the above code, I want to use logurus logger instead of the basic inbuilt logging. I want it to output the logs in a file as well as in the console. Ignore the other parts of code and send me only about logger
Key Points:
Loguru Configuration:
logger.add("trading_bot.log", rotation="5 MB", retention="2 days", level="DEBUG") ensures that logs are written to trading_bot.log, with a maximum file size of 5 MB and logs retained for 2 days.
logger.add(sys.stdout, level="DEBUG") makes sure logs are also printed to the console.
Log Level: You can set the logging level directly in the add method. Here it's set to "DEBUG" to capture detailed logs.
Convenience: loguru provides a more convenient interface compared to Python’s built-in logging, especially for quickly setting up outputs and formats.
Modifying Logging Calls: Replace your code's use of logging.debug, logging.info, logging.warning, logging.error, etc., with logger.debug, logger.info, and so on.
Incorporate these changes into your code where necessary, ensuring that any logging statements use the logurulogger. This setup will give you enhanced logging capabilities with rotation and retention strategies.
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
init
mp_main
init
mp_main
mp_main
mp_main
init
mp_main
init
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
init
mp_main
init
mp_main
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
init
mp_main
init
mp_main
mp_main
mp_main
init
mp_main
mp_main
init
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
init
mp_main
mp_main
mp_main
mp_main
I see above errors wen I run the code below
import asyncio
import json
import os
import sys
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", encoding='utf-8'), # Output logs to a file
#logging.StreamHandler() # Also continue logging to the console
#]
#)
logger.add("trading_bot.log", rotation="20 MB", retention="2 days", level="DEBUG") # File logging
logger.add(sys.stdout, level="DEBUG") # Console logging
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()
logger.debug(f"Initialized SignalGenerator with symbol: {symbol}, timeframe: {timeframe}")
code
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')
logger.info("Fetched historical data for {self.symbol} successfully.")
return df
except Exception as e:
logger.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:
logger.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:
logger.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.df.sort_values(by='timestamp', inplace=True)
async def combine_data(self):
# Fetch historical data
self.df = self.fetch_historical_data()
# Start real-time data gathering
await self.fetch_realtime_data()
#self.generate_signals()
#df_with_signals = self.generate_signals(self.df)
#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)
# Implement your data collection logic here, e.g., append to a DataFrame
def generate_signals(self, df):
if self.df.empty:
logger.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:
logger.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:
logger.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'],
}
)
logger.info(f"Signal saved for {self.symbol}: {last_signal['Signal']}")
return df
except Exception as e:
logger.error(f"Error saving signals for {self.symbol} to database: {e}")
return df
async def run(self):
await self.combine_data()
if not self.df.empty:
self.df = self.generate_signals(self.df)
self.df = self.save_signals(self.df)
#df = self.combined_data()
#if not df.empty:
#df = self.generate_signals(df)
#df = self.save_signals(df)
else:
logger.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:
logger.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:
try:
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
))
except KeyboardInterrupt:
logger.info("KeyboardInterrupt received. Shutting down executor…")
executor.shutdown(wait=True, cancel_futures=True)
logger.info("Executor has been shut down successfully.")
# 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())
from loguru import logger
import sys
import asyncio
# Configure logging
# Set up Loguru to log both to a file and the console
logger.add("trading_bot.log", rotation="20 MB", retention="2 days", level="DEBUG") # File logging
logger.add(sys.stdout, level="DEBUG") # Console logging
class SignalGenerator:
# ... [Your class code here, as provided] ...
async def run(self):
await self.combine_data()
if not self.df.empty:
self.df = self.generate_signals(self.df)
self.df = self.save_signals(self.df)
else:
logger.error("No data fetched, cannot proceed with signal generation.")
async def historical_data_worker(symbol):
signal_generator = SignalGenerator(symbol=symbol)
signal_generator.df = signal_generator.fetch_historical_data()
if not signal_generator.df.empty:
logger.info(f"Processed historical data for {symbol}")
await signal_generator.run() # Ensure the `run` method is awaited
async def main():
# ... [Setup and market fetching code here] ...
with ProcessPoolExecutor(max_workers=6) as executor:
try:
# Use `asyncio.get_running_loop().run_in_executor` for async execution with ProcessPoolExecutor
loop = asyncio.get_running_loop()
tasks = [
loop.run_in_executor(executor, historical_data_worker, symbol)
for symbol in usdt_pairs
]
await asyncio.gather(*tasks)
except KeyboardInterrupt:
logger.info("KeyboardInterrupt received. Shutting down executor...")
executor.shutdown(wait=True, cancel_futures=True)
logger.info("Executor has been shut down successfully.")
# Run the main coroutine
if __name__ == "__main__":
asyncio.run(main())
Key Changes
Await the run Method: Within historical_data_worker, ensure that the run method is awaited using await signal_generator.run().
Async Task Execution: When submitting tasks to the ProcessPoolExecutor, ensure to adapt the logic for cooperation with the asyncio loop if necessary. This can be more intricate, especially because mixing asyncio with ProcessPoolExecutor can require specific handling of blocking calls.
Consistent Logging: Ensure loguru is consistently used for all logging activities across your script to handle output effectively without duplicates.
With these adjustments, you should expect more streamlined execution without the mentioned warnings and cleaner logging output.
def save_signals(self, df):
if df.empty:
logger.error("DataFrame is empty, cannot save signals.")
return df
try:
last_signal = df.iloc[-1]
# Log what data is about to be saved
logger.debug(f"Attempting to save signal: {last_signal.to_dict()}")
signal, created = 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'],
}
)
if created:
logger.info(f"New signal saved for {self.symbol}: {signal.signal_type}")
else:
logger.info(f"Signal updated for {self.symbol}: {signal.signal_type}")
return df
except Exception as e:
logger.error(f"Error saving signals for {self.symbol} to database: {e}")
return df
Further Debugging Steps
Inspect Model Methods: Ensure all custom model methods and Signal model attributes behave as expected.
Database Logs: If possible, check the database logs to see if queries are reaching the database.
Query Debugging: Utilize Django’s query debugging tools. For example:
python
from django.db import connection
print(connection.queries)
This can provide insights into the actual queries being executed.
By systematically checking these areas, you should identify where the gap lies between your expected signal saves and what's actually happening in your database.
Key Points:
Synchronous Worker: historical_data_worker is made to operate synchronously. Any asynchronous functionality is wrapped using asyncio.run() to execute inside a synchronous function context.
Executor Tasks: Be sure that any task assigned to ProcessPoolExecutor is a normal, synchronous Python function. This allows ProcessPoolExecutor to serially schedule tasks without requiring coroutines to be pickled.
Coroutines Inside Blocking Contexts: If you need to call asynchronous code within a blocking context, wrap it in asyncio.run(), as done above.
This setup should resolve the pickling problem by ensuring only sync-compatible operations get passed to ProcessPoolExecutor, while still preserving the asynchronous logic where necessary.