(venv) PS D:\Binance\binancebot> python manage.py makemigrations
D:\Binance\venv\Lib\site-packages\django\core\management\commands\makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (::1),
port 5432 failed: FATAL: database "D:\Binance\binancebot\binancebot" does not exist
warnings.warn(
No changes detected
Assistant
The warning message and the "No changes detected" message you're seeing are indicative of a couple of different things. Let's break them down and troubleshoot:
Database Connection Error:
The warning message is telling you that Django attempted to connect to your PostgreSQL database and failed because the database "D:\Binance\binancebot\binancebot" does not exist.
Ensure your DATABASES settings in your Django settings.py file are correctly pointing to an existing PostgreSQL database.
Here’s a basic outline of what to check or do:
Database Name: Make sure the database specified in your settings.py actually exists in your PostgreSQL server.
Database Creation: If the database doesn’t exist, create it using:
code
createdb your_db_name
PostgreSQL Service: Ensure that your PostgreSQL service is running and accessible on the specified host and port.
No Changes Detected:
This message indicates that Django did not detect any changes to your models that would necessitate a new migration file.
If you were expecting changes, double-check your models.py files to ensure changes were made and saved correctly.
Steps to Resolve:
Verify that the PostgreSQL server is running and that you can connect to it using the credentials and database specified in your settings.py.
Check if other terminal windows or applications (like pgAdmin) can connect to the database.
Confirm your model changes, if any, were saved and check your app is set up correctly in INSTALLED_APPS.
Following these steps should help resolve the issues you're encountering or provide further insights into what's going wrong.
User
(venv) PS D:\Binance\binancebot> createdb binancebot
createdb : The term 'createdb' 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 you're encountering (createdb : The term 'createdb' is not recognized as the name of a cmdlet...) indicates that the createdb command, which is used to create a new PostgreSQL database, isn't recognized in your command prompt. This typically happens if PostgreSQL is not properly installed or its bin directory is not included in your system's PATH.
Here are a few steps to resolve this:
Ensure PostgreSQL is Installed:
If you haven't installed PostgreSQL yet, download and install it from the official website.
Make sure to install PostgreSQL and select the components necessary, including the command-line tools.
Add PostgreSQL to PATH:
Open the Start menu and search for "Environment Variables."
Click on "Edit the system environment variables."
In the System Properties window, click on "Environment Variables."
Under "System variables," find and select the "Path" variable, then click "Edit."
Click "New" and add the path to the PostgreSQL bin directory (e.g., C:\Program Files\PostgreSQL\<version>\bin).
Click OK to close all dialogs.
Verify the Installation:
Open a new command prompt or PowerShell window and type psql --version to ensure PostgreSQL is accessible from the command line.
If installed correctly, you'll see the version of PostgreSQL printed out.
Create the Database:
Once PostgreSQL is in your PATH, you should be able to use the createdb command.
Alternatively, you can use the psql command-line tool to connect to your PostgreSQL server:
code
psql -U your_db_user -h localhost
After logging in, you can create the database manually:
code
CREATE DATABASE binancebot;
If PostgreSQL is not the database system you're using, or if there's another underlying issue, please provide more information, and I'll be glad to assist you further.
User
I already created a database in pgadmin and want to connect the same to my django project. I also want it to show up in the Django directory so I can easily view it
Assistant
Great! If you’ve already created a PostgreSQL database using pgAdmin and want it connected to your Django project, you need to ensure that your Django settings are correctly configured to connect to this database. Here's a step-by-step guide to achieve that:
Step 1: Update settings.py in Your Django Project
Locate settings.py: This file is usually found in your Django project’s main directory.
Configure the DATABASES Setting:
Ensure your settings.py file is set to connect to the PostgreSQL database you’ve created. Update it with the credentials and database name.
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'your_db_name', # Replace with your database name
'USER': 'your_db_user', # Replace with your PostgreSQL user
'PASSWORD': 'your_db_password', # Replace with your PostgreSQL password
'HOST': 'localhost', # Generally localhost unless you've set it differently
'PORT': '5432', # Default PostgreSQL port
}
}
Save the Changes to your settings.py file.
Step 2: Verify the Connection
Test Database Connection:
Run the following command to apply the migrations to your database and test if the connection is working properly:
bash
python manage.py migrate
If the command runs without errors, your connection is working.
Step 3: Use Django's Admin Interface for Database Inspection
Django's built-in admin interface allows you to view and manage your database content directly.
Create a Superuser (if you haven't already):
bash
python manage.py createsuperuser
Follow the on-screen instructions to create an admin user.
Run the Development Server:
bash
User
must I install psycopg2
Assistant
Yes, if you're using PostgreSQL as your database with a Django project, you need to install psycopg2. It is the most popular PostgreSQL adapter for Python and provides a database interface for connecting Django to your PostgreSQL database.
Here’s how you can install it and ensure it's properly integrated with your Django project:
1. Install psycopg2
You can install psycopg2 using pip. There are two variants:
psycopg2: This is the traditional version.
psycopg2-binary: This version is a stand-alone package that doesn’t require compilation. It's usually suitable for development.
For most cases, especially during development, you can use psycopg2-binary:
bash
pip install psycopg2-binary
However, for production environments, it's often recommended to use psycopg2 due to potential issues with the binary package. Install it with:
(Note: The 'ENGINE' setting above should already be using django.db.backends.postgresql as the backend since Django 1.9, so you can use 'ENGINE': 'django.db.backends.postgresql' as well.)
3. Verify Installation and Connection
Run python manage.py migrate to apply migrations and test connection.
If everything is configured properly, this command should run without errors.
Potential Issues
Binary Compatibility: If using psycopg2-binary, be aware that while it’s convenient, some specific environment or deployment configurations might require compiling from source using psycopg2.
SSL Requirements: If your PostgreSQL instance requires an SSL connection, you may need to adjust your settings accordingly to include SSL certificates.
By installing psycopg2 and configuring your settings correctly, you’ll be able to connect Django to your PostgreSQL database effectively.
User
Traceback (most recent call last):
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\logging_init_.py", line 1163, in emit
stream.write(msg + self.terminator)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeEncodeError: 'charmap' codec can't encode character '\u01c2' in position 42: character maps to
Call stack:
File "", line 1, in
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 314, in _bootstrap
self.run()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py", line 263, in _process_worker
r = call_item.fn(*call_item.args, **call_item.kwargs)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py", line 212, in _process_chunk
return [fn(*args) for args in chunk]
File "D:\Binance\binancebot\signals\tradlog.py", line 173, in worker
signal_generator.run()
File "D:\Binance\binancebot\signals\tradlog.py", line 159, in run
asyncio.run(self.fetch_realtime_data())
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 674, in run_until_complete
self.run_forever()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\windows_events.py", line 322, in run_forever
super().run_forever()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 641, in run_forever
self._run_once()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 1987, in _run_once
handle._run()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\events.py", line 88, in _run
self._context.run(self._callback, *self.args)
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 1247, in keepalive_ping
pong_waiter = await self.ping()
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 858, in ping
await self.write_frame(True, OP_PING, data)
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 1200, in write_frame
self.write_frame_sync(fin, opcode, data)
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 1170, in write_frame_sync
self.logger.debug("> %s", frame)
Message: '> %s'
Arguments: (Frame(fin=True, opcode=<Opcode.PING: 9>, data=b'\xc7\x82\x11O', rsv1=False, rsv2=False, rsv3=False),)
2024-09-16 09:46:08,337 - DEBUG - > PING 'ǂ\x11O' [text, 4 bytes]
--- Logging error ---
Traceback (most recent call last):
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\logging_.py", line 1163, in emit
stream.write(msg + self.terminator)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeEncodeError: 'charmap' codec can't encode character '\u01c2' in position 42: character maps to
Call stack:
File "", line 1, in
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 314, in _bootstrap
self.run()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py", line 263, in _process_worker
r = call_item.fn(*call_item.args, **call_item.kwargs)
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\concurrent\futures\process.py", line 212, in _process_chunk
return [fn(*args) for args in chunk]
File "D:\Binance\binancebot\signals\tradlog.py", line 173, in worker
signal_generator.run()
File "D:\Binance\binancebot\signals\tradlog.py", line 159, in run
asyncio.run(self.fetch_realtime_data())
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 674, in run_until_complete
self.run_forever()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\windows_events.py", line 322, in run_forever
super().run_forever()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 641, in run_forever
self._run_once()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 1987, in _run_once
handle._run()
File "C:\Users\benrajj\AppData\Local\Programs\Python\Python312\Lib\asyncio\events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 955, in transfer_data
message = await self.read_message()
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 1025, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 1100, in read_data_frame
frame = await self.read_frame(max_size)
File "D:\Binance\venv\Lib\site-packages\websockets\legacy\protocol.py", line 1164, in read_frame
self.logger.debug("< %s", frame)
Message: '< %s'
Assistant
The error you're encountering is a UnicodeEncodeError due to the logging module trying to write characters that aren't supported by the default system codec (in this case, cp1252). This commonly happens on Windows systems where some Unicode characters in your log may not map to your terminal's encoding.
Here's how you can address it:
1. Change Console Encoding
You can change the encoding of your console to UTF-8, which is more capable of handling Unicode characters:
Open your command prompt and run:
bash
chcp 65001
This changes the code page to UTF-8. However, it's worth noting that this doesn't guarantee all issues will be fixed as the actual font used in the console also needs to support the characters.
2. Set Console Logger to Use UTF-8
If you're logging to the console, configure the logger to handle Unicode properly:
python
import sys
import logging
# Set up your logger with a StreamHandler using UTF-8 encoding
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
# Create a formatter that will output in UTF-8
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Add handler to the root logger
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.DEBUG)
3. Use a File Logger
If changing the console's encoding doesn't work, consider logging to a file that can effectively handle Unicode characters:
python
import logging
logging.basicConfig(
filename='app.log', # Log to a file instead of console
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
encoding='utf-8' # Ensure the log file is in UTF-8
)
By logging to a file, you ensure that Unicode characters are captured correctly regardless of console limitations.
4. Verify Data Content
Review the data you are logging to see if it contains unexpected Unicode characters. If possible, sanitize or normalize these characters before logging.
Incorporate this updated logging configuration into your Python script to handle encoding issues properly and prevent UnicodeEncodeError from arising during operation.
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']),
}
latest_row = pd.DataFrame([kline_data])
self.df = pd.concat([self.df, latest_row]).drop_duplicates(subset='timestamp', keep='last')
logging.debug(f"Updated real-time data for {self.symbol}")
if len(self.df) > 2: # Ensure sufficient data for calculation
self.generate_signals(self.df)
except Exception as e:
logging.error(f"Websocket connection error: {e}")
return pd.DataFrame()
Wat does the above code do
Assistant
The provided Python code defines a class with two methods used for fetching financial data for a particular trading symbol: fetch_historical_data (a synchronous method) and fetch_realtime_data (an asynchronous method). Here's a breakdown of what each method does:
fetch_historical_data(self)
Purpose: Fetch historical market data for a given symbol and timeframe from a cryptocurrency exchange using the ccxt library (implied by the use of self.exchange).
Main Steps:
Convert a Start Date: It parses an ISO 8601 date string ('2024-07-01T00:00:00Z') into a timestamp (likely in milliseconds) using self.exchange.parse8601(), marking the start point for data retrieval.
Fetch Data: It uses self.exchange.fetch_ohlcv() to fetch historical OHLCV (Open, High, Low, Close, Volume) data starting from the date above for self.symbol, and at the interval specified by self.timeframe.
DataFrame Construction: The data fetched is stored in a pandas DataFrame with explicitly named columns: 'timestamp', 'open', 'high', 'low', 'close', 'volume'.
Timestamp Conversion: Timestamps in the DataFrame are converted to a human-readable datetime format using milliseconds as the unit.
Store Data: The resulting DataFrame is stored in self.df.
Logging: It logs a success message or an error message if exceptions are raised.
fetch_realtime_data(self)
Purpose: Fetch real-time market data using a WebSocket connection (suggested by the use of websockets.connect(self.url)). This method updates a DataFrame continuously with incoming data.
Main Steps:
Connect to WebSocket: Establishes a WebSocket connection to self.url.
Receive and Process Messages: In an infinite loop, it receives messages from the WebSocket and processes each one.
Parse Kline Data: Assumes the incoming data are structured JSON with a key 'k' representing kline (candlestick) data.
Extract and Convert Data: Extracts and converts the kline data fields ('t', 'o', 'h', 'l', 'c', 'v') into a dictionary of floats and timestamps.
User
ow can I fetch all USDT pairs in binance futures concurrently? I want like 6 workers to work simultaneously in retrieving historical data and 6 workers to work simultaneously in retrieving real time data. Can you use ProcessPoolExecutor for tat
Assistant
To fetch all USDT pairs from Binance Futures concurrently and have workers retrieve both historical and real-time data, you can indeed use concurrent.futures.ProcessPoolExecutor. Here's a comprehensive guide on how you might structure your code to achieve this:
Step 1: Setup and Imports
First, ensure you have the necessary libraries. You likely need ccxt for API requests, websockets for real-time data, and other standard libraries for concurrency and data handling.
Define functions to fetch historical and real-time data. These will be executed by the workers.
Fetching Historical Data:
python
def fetch_historical_data(symbol, exchange, timeframe):
try:
since = exchange.parse8601('2024-07-01T00:00:00Z')
historical_bars = exchange.fetch_ohlcv(symbol, 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 {symbol} successfully.")
return df
except Exception as e:
logging.error(f"Error fetching historical data for {symbol}: {e}")
return None
Fetching Real-Time Data:
For real-time data, use asynchronous functions:
python
User
wic other option can we use to fetch data without using Binance API that can be banned
Assistant
Fetching financial data without directly using the Binance API involves relying on third-party data providers or aggregators that collect cryptocurrency market data and offer access through their own APIs or platforms. Here are several options you might consider:
1. Alternative Data Providers
There are various third-party providers offering cryptocurrency market data. Some popular ones include:
CoinMarketCap API: Offers data on cryptocurrencies, including historical pricing, market cap, and more. Remember that some of these services also have rate limits and subscription tiers.
These platforms collect data from multiple exchanges and provide it to users:
TradingView: Provides a platform for market analysis and trading with comprehensive historical data and various financial indicators.
Cryptowatch: A subsidiary of Kraken, Cryptowatch offers a real-time crypto market data visualization and trading platform.
3. Blockchain Explorers
Some blockchain explorers offer APIs with data on transactions and market metrics that may be of interest, though they may not match the granularity of exchange data.
4. Public Datasets
Kaggle: Occasionally hosts datasets with historical crypto trading data which can be explored offline once downloaded.
User
In with concurrent.futures.ProcessPoolExecutor(max_workers=6) as executor: it says "concurrent" is not defined
In fetch_realtime_data(symbol, f'wss://your.websocket.url/{symbol}', collect_data)
for symbol in usdt_pairs, it says "fetch_historical_data" is not defined, "collect_data" is not defined
Assistant
The issues you're facing are related to scope and missing definitions in your code. Let’s address each one:
Issue 1: concurrent is not defined
The error indicates that Python cannot find the concurrent module, which typically means it hasn't been imported. Make sure you have imported it at the top of your script:
python
import concurrent.futures
This will import the concurrent.futures module, allowing you to use the ProcessPoolExecutor.
Issue 2: Functions are not defined
fetch_historical_data is not defined:
Ensure that the function fetch_historical_data is correctly defined before you attempt to use it. If you are copying code snippets from different places, make sure you include the full function definition in your script. Based on the earlier code idea, it might look something like this:
python
def fetch_historical_data(symbol, exchange, timeframe):
try:
since = exchange.parse8601('2024-07-01T00:00:00Z')
historical_bars = exchange.fetch_ohlcv(symbol, 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 {symbol} successfully.")
return df
except Exception as e:
logging.error(f"Error fetching historical data for {symbol}: {e}")
return None
collect_data is not defined:
The collect_data function is supposed to act as a consumer or handler for real-time data. From the context, it seems to be a part of the real-time data processing using WebSockets. Here’s an example of how you might implement it:
python
User
This is the whole code, Please tell me why I get errors that
Assistant
Certainly! Let's take a deeper look at potential issues in your code based on the error messages you've received. If you could provide the entire code or detail exactly where the error messages are occurring, it would be easier to identify the issues. However, I can guide you on common pitfalls that might cause the errors you're encountering, especially for the given error messages.
Common Issues and Solutions
Import Statements:
Ensure all necessary modules are imported at the start of your script:
For concurrent futures: import concurrent.futures
For asynchronous operations: import asyncio
For WebSockets: import websockets
For data handling: import pandas as pd
For JSON parsing: import json
For logging: import logging
If using ccxt for exchange data: import ccxt
Without these imports, Python will not recognize the functions and libraries you're trying to use.
Function Definitions:
Ensure all functions (fetch_historical_data, fetch_realtime_data, collect_data) are defined before they are used.
Example function fetch_realtime_data should look something like this:
python
async def fetch_realtime_data(symbol, url, collect_data):
try:
async with websockets.connect(url) as websocket:
logging.info(f"Connected to websocket for {symbol}")
while True:
message = await websocket.recv()
data = json.loads(message)
kline = data.get('k', {})
kline_data = {
'timestamp': pd.to_datetime(kline.get('t'), unit='ms'),
'open': float(kline.get('o', 0)),
'high': float(kline.get('h', 0)),
'low': float(kline.get('l', 0)),
'close': float(kline.get('c', 0)),
'volume': float(kline.get('v', 0)),
}
await collect_data(symbol, kline_data)
except Exception as e:
logging.error(f"Websocket connection error for {symbol}: {e}")
User
I didn't send the code, see it below
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
Based on the code you've provided, let's address potential issues and errors:
Error: concurrent is not defined
This particular error should not occur as long as you have correctly imported concurrent.futures:
python
import concurrent.futures
This import statement should be at the top of your file, and it seems you have it, so if you’re still encountering the error, ensure the script is being executed without modification.
Error: fetch_historical_data and collect_data not defined
This can occur if the code is structured such that these functions are defined within a class (i.e., SignalGenerator) and you're trying to call them outside of a class context.
Fix: Properly call the class methods and handle instances.
fetch_historical_data is a class method. When used outside of SignalGenerator, you'll need to access it via an instance or adjust how you're using it with ProcessPoolExecutor.
To fix how fetch_historical_data is used within ProcessPoolExecutor, use a lambda or wrapper function to ensure it's called with an instance context:
python
# Define a worker function outside of the SignalGenerator class
def historical_data_worker(symbol, timeframe):
generator = SignalGenerator(symbol=symbol, timeframe=timeframe)
return generator.fetch_historical_data()
# Modify how you pass fetch_historical_data to the executor
with concurrent.futures.ProcessPoolExecutor(max_workers=6) as executor:
historical_results = list(executor.map(
historical_data_worker,
usdt_pairs,
['1m'] * len(usdt_pairs) # Assuming a 1-minute timeframe
))
collect_data is an asynchronous method and should be invoked within the context of the SignalGenerator class. When calling it in main, refactor collect_data to the following context:
User
Make the changes and send me the whole code
Assistant
Let's refactor the code to address the issues identified. I'll make sure the methods are properly utilized, ensure imports are correctly placed, and provide a structured approach. Here's the revised code:
python
User
It says "historical_results" is not accessed in with concurrent.futures.ProcessPoolExecutor(max_workers=6) as executor:
historical_results = list(executor.map(
historical_data_worker,
Assistant
The warning "historical_results" is not accessed typically indicates that the variable historical_results is assigned a value but not used anywhere afterward. This doesn't lead to a runtime error, but it's a sign that you might be doing unnecessary work or missing some intended functionality.
How to Handle historical_results
If you don't need to use the historical data results immediately within the script (e.g., for further processing, analysis, or saving to a database), you might simply be collecting the data as a side effect within the historical_data_worker function. However, here's how you can access and potentially use historical_results:
Ensure the Data is Used:
If you want to process or save the results, do something like this:
python
import logging
from concurrent.futures import ProcessPoolExecutor
import asyncio
# Assuming historical_data_worker returns a DataFrame or similar data structure
def historical_data_worker(symbol, timeframe):
generator = SignalGenerator(symbol=symbol, timeframe=timeframe)
df = generator.fetch_historical_data()
# You might process or save each DataFrame here
if df is not None:
logging.info(f"Processed historical data for {symbol}")
return df
async def main():
exchange = ccxt.binance({'options': {'defaultType': 'future'}})
markets = exchange.fetch_markets()
# Filter for USDT pairs
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
# Setup process pool for historical data
with ProcessPoolExecutor(max_workers=6) as executor:
historical_results = list(executor.map(
historical_data_worker,
usdt_pairs,
['1m'] * len(usdt_pairs)
))
# Access the results here if necessary
for result, symbol in zip(historical_results, usdt_pairs):
if result is not None:
# Process the result, e.g., store it in a database or further process it
logging.info(f"Successfully retrieved historical data for {symbol}")
# Setup tasks for real-time data retrieval
tasks = []
for symbol in usdt_pairs:
generator = SignalGenerator(symbol=symbol)
tasks.append(generator.fetch_realtime_data())
# Use asyncio to run the real-time tasks concurrently
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
User
The historical data is supposed to be used in technical analysis. Some indicators such as MA need more data to perform analysis. So we don't have to store it but pass it on to signal generation function to use it
Assistant
To use the historical data directly for technical analysis, especially for indicators like moving averages that require a series of data points, you'll want to ensure that the historical data is passed directly to the signal generation process.
Here's how you can refactor your code to pass the historical data to the generate_signals method of your SignalGenerator class and perform the analysis accordingly:
Updated Class and Main Function
python
User
I had set for the signals to be saved in PostgreSQL database, how do I check if
Assistant
To verify that signals are being saved correctly in your PostgreSQL database, you need to follow a few steps to check both the application and database aspects.
Step 1: Ensure Django Configuration
First, ensure that your Django project's settings.py is properly configured to connect to your PostgreSQL database. Confirm the following:
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_db_name', # The name of your database
'USER': 'your_db_user', # Your database username
'PASSWORD': 'your_db_password', # Your database user's password
'HOST': 'localhost', # Consider changing if your database isn't on localhost
'PORT': '5432', # Default PostgreSQL port
}
}
Step 2: Confirm Django Model
Make sure that your Signal model is correctly defined in models.py and it matches the columns you are trying to save. It should look something like this:
python
from django.db import models
class Signal(models.Model):
timestamp = models.DateTimeField()
symbol = models.CharField(max_length=10)
price = models.FloatField()
signal_type = models.CharField(max_length=5)
def __str__(self):
return f"{self.symbol}: {self.signal_type} at {self.price}"
Step 3: Inspect Logs
Your logging setup should capture any errors that occur when attempting to save the signals. Check debug.log (or wherever you are logging) for any error messages related to database operations, particularly during the execution of save_signals.
Step 4: Use Django Shell
You can use the Django shell to query the database directly and check if the records are there:
Start the Django shell:
bash
python manage.py shell
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
If it seems that the execution isn't progressing past the initial logging statements, it could be due to several reasons, including issues with how processes are managed, blocking operations, or incorrect handling of async operations. Here's a breakdown of potential issues and solutions:
Potential Issues and Solutions
Process Initialization and Execution Order:
Ensure that ProcessPoolExecutor is initialized correctly and that each worker reaches the subsequent parts of processing.
Mix of Sync and Async Code:
Ensure that the mix of synchronous processes and asynchronous tasks is managed correctly. You might be running into issues where the workers aren't able to fully complete their tasks because of improper synchronization between asynchronous and synchronous code parts.
WebSocket Connections Not Established Correctly:
Ensure that WebSocket connections are being established and handled correctly.
Error Handling:
Make sure to have adequate logging around WebSocket and async operations. This can help diagnose silent failures.
Revised Structure & Debugging
Let’s enhance logging and adjust the async parts of your code to improve debugging and clarity.
python
Dataset releases
Not yet included in a published release.
python manage.py runserver
Access the Admin Interface:
Navigate to http://localhost:8000/admin in your web browser.
Log in using the superuser credentials you created earlier.
You will see an interface to view and manage your models' data.
Notes:
Django Directory Visibility: If by “show up in the Django directory” you mean listing the database structure directly in Django's directory, Django itself doesn’t directly visualize the database schema in file directories. You can interact with the data using Django’s ORM and view structure via pgAdmin or through the Django Admin interface as described.
Database Browser Tools: For more direct database browsing, rely on tools like pgAdmin or other third-party applications that allow database management and inspection alongside Django's admin tools.
By following these steps, you’ve integrated your Django project with your PostgreSQL database and have configured Django's admin site to allow you to view and manage the database effectively.
init
Update DataFrame: Appends the new kline data to self.df, ensuring there are no duplicate timestamps with drop_duplicates.
Logging and Signal Generation: Logs debug information about the updates and, if there are enough data points (more than 2), calls self.generate_signals(self.df) to potentially perform technical analysis or generate trading signals.
Exception Handling: Logs any exceptions during WebSocket operations as errors and returns an empty DataFrame if an error occurs.
Contextual Assumptions
Dependencies and Libraries: The code seems to use pandas, ccxt, and websockets.
Other Methods: generate_signals(self.df) suggests additional logic not shown here, likely performing analysis or making trading decisions based on the data.
Overall, the code is designed for a trading bot that keeps a continuous watch on market data, selectively updating calculations or signals as new data becomes available.
async def fetch_realtime_data(symbol, url, collect_data):
try:
async with websockets.connect(url) as websocket:
logging.info(f"Connected to websocket for {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']),
}
# Send data to the collector method (could be a queue, or a callback)
await collect_data(symbol, kline_data)
except Exception as e:
logging.error(f"Websocket connection error for {symbol}: {e}")
async def collect_data(symbol, kline_data):
logging.debug(f"{symbol} - Latest: {kline_data}")
# Implement your data collection logic here, e.g., append to a DataFrame
Step 3: Setup Concurrency
Use ProcessPoolExecutor for parallel processing of historical data. You can run asynchronous tasks for real-time data concurrently using asyncio.
python
async def main():
exchange = ccxt.binance({
'options': {'defaultType': 'future'}
})
# Fetch all USDT pairs
markets = exchange.fetch_markets()
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
# Setup process pool for historical data
with concurrent.futures.ProcessPoolExecutor(max_workers=6) as executor:
historical_results = list(executor.map(
fetch_historical_data,
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
]
# Use asyncio to run the real-time tasks concurrently
await asyncio.gather(*tasks)
# Run the main function
if __name__ == '__main__':
asyncio.run(main())
Considerations
API Limits: Be mindful of Binance API rate limits to avoid getting rate-limited or banned. Consider implementing a retry mechanism or exponential backoff in case of too many requests.
Fault Tolerance: Implement additional exception handling and logging to ensure long-running jobs can self-recover or at least notify you of issues.
WebSocket URL: Replace 'wss://your.websocket.url/{symbol}' with the correct WebSocket endpoint provided by Binance for futures.
Concurrency: Adjust the number of workers (max_workers) based on your system's capability and network environment, possibly balancing between I/O and CPU-bound tasks.
By structuring your code with concurrency and async tasks, you effectively fetch real-time data and batch-process historical data, enabling a scalable data ingestion framework for trading or analysis purposes.
Considerations
Data Accuracy and Latency: Third-party services might introduce slight inaccuracies or latencies compared to direct exchange data. Evaluate these factors based on your use case (e.g., high-frequency trading could require more immediate data access).
Cost and Rate Limits: Services can have different pricing models and API usage limits, so choose based on your budget and needed data volume.
Reliability and Support: Ensure the provider you choose is reliable, with good documentation and support. Check user reviews and community feedback where possible.
By using these services, you can access cryptocurrency data rooms without directly engaging with the Binance API, thereby reducing the chance of hitting rate limits or bans associated with direct API usage. Always ensure that any use aligns with the terms of service of the data provider.
async def collect_data(symbol, kline_data):
# Implement your data collection logic here
logging.debug(f"{symbol} - Latest data: {kline_data}")
# This could involve appending data to a DataFrame, storing it in a queue, etc.
Use Correct URLs and Setup:
When using WebSockets, ensure the URL is valid for the endpoint you want to connect to. For the Binance Futures WebSocket API, make sure your URL matches their API documentation format.
Putting it All Together
Ensure your script contextually includes all definitions and necessary imports:
python
import concurrent.futures
import ccxt
import pandas as pd
import logging
import asyncio
import websockets
import json
def fetch_historical_data(symbol, exchange, timeframe):
try:
since = exchange.parse8601('2024-07-01T00:00:00Z')
historical_bars = exchange.fetch_ohlcv(symbol, 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 {symbol} successfully.")
return df
except Exception as e:
logging.error(f"Error fetching historical data for {symbol}: {e}")
return None
async def fetch_realtime_data(symbol, url, collect_data):
try:
async with websockets.connect(url) as websocket:
logging.info(f"Connected to websocket for {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']),
}
await collect_data(symbol, kline_data)
except Exception as e:
logging.error(f"Websocket connection error for {symbol}: {e}")
async def collect_data(symbol, kline_data):
logging.debug(f"{symbol} - Latest: {kline_data}")
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 concurrent.futures.ProcessPoolExecutor(max_workers=6) as executor:
historical_results = list(executor.map(
fetch_historical_data,
usdt_pairs,
[exchange] * len(usdt_pairs), # Pass the exchange instance to each worker
['1m'] * len(usdt_pairs) # Assuming a 1-minute timeframe for each worker
))
tasks = [
fetch_realtime_data(symbol, f'wss://your.websocket.url/{symbol}', collect_data)
for symbol in usdt_pairs
]
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
Make sure that the WebSocket URL and any configuration matches your actual needs and environment. And remember to handle any specific rate limits or API constraints of the services you use.
WebSocket URL:
Make sure the WebSocket URL you're using is correct and set up correctly based on the provider’s documentation (e.g., Binance API documentation).
Concurrency Setup:
When setting up the ProcessPoolExecutor, ensure the data you pass in parallel (like exchange instances) are properly constructed and usable in a parallel context.
python
with concurrent.futures.ProcessPoolExecutor(max_workers=6) as executor:
futures = [executor.submit(fetch_historical_data, symbol, exchange, '1m') for symbol in usdt_pairs]
concurrent.futures.wait(futures)
Handling Futures Results:
Check the results after computation:
python
for future in futures:
try:
result = future.result()
if result:
print(f"Successfully fetched data for a symbol")
except Exception as ex:
logging.error(f"Error occurred: {ex}")
Exception Handling:
Be precise about the exception handling block to catch exceptions, especially in asynchronous contexts.
Debugging and Logging:
Ensure you have appropriate logging to capture the flow of data and where it possibly fails.
python
logging.basicConfig(level=logging.INFO)
Final Advice
Without seeing the complete code, these are a few guesses based on your initial description. For specific diagnostics, ensure you are capturing the full error messages—exactly where in the code they occur, and under what circumstances (which function, line number, or data). Debugging tools, or simply adding more logging or print statements, will help pinpoint which part of the code is failing and why.
##def fetch_market_data(self):
def fetch_historical_data(symbol, exchange, timeframe):
try:
since = exchange.parse8601('2024-07-01T00:00:00Z')
historical_bars = exchange.fetch_ohlcv(symbol, 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 {symbol} successfully.")
return df
except Exception as e:
logging.error(f"Error fetching historical data for {symbol}: {e}")
return None
async def fetch_realtime_data(symbol, url, collect_data):
try:
async with websockets.connect(url) as websocket:
logging.info(f"Connected to websocket for {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 collect_data(symbol, kline_data)
except Exception as e:
logging.error(f"Websocket connection error for {symbol}: {e}")
#return pd.DataFrame()
async def collect_data(symbol, kline_data):
logging.debug(f"{symbol} - Latest: {kline_data}")
# Implement your data collection logic here, e.g., append to a DataFrame
def generate_signals(self, df):
try:
# 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
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: {last_signal}")
return 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():
self.fetch_historical_data()
asyncio.run(self.fetch_realtime_data())
#####df = self.fetch_market_data()
#logging.debug(df.tail(5)) # Check the last few rows
if not df.empty:
df = self.generate_signals(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 worker(symbol):
signal_generator = SignalGenerator(symbol=symbol)
while True:
try:
signal_generator.run()
#time.sleep(60) # Avoid hammering the API, adjust to your timeframe
except Exception as e:
logging.error(f"An error occurred in worker for {symbol}: {e}")
#time.sleep(60) # Backoff time to handle API limitations
async def main():
exchange = ccxt.binance({'options': {'defaultType': 'future'}})
markets = exchange.fetch_markets()
Filter for USDT pairs
code
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 concurrent.futures.ProcessPoolExecutor(max_workers=6) as executor:
historical_results = list(executor.map(
fetch_historical_data,
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
]
# Use asyncio to run the real-time tasks concurrently
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
python
async def main():
exchange = ccxt.binance({'options': {'defaultType': 'future'}})
markets = exchange.fetch_markets()
# Filter for USDT pairs
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
tasks = []
for symbol in usdt_pairs:
generator = SignalGenerator(symbol=symbol)
task = fetch_realtime_data(symbol, generator.url, generator.collect_data)
tasks.append(task)
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Additional Considerations
Class Method Access: When using methods like fetch_historical_data and fetch_realtime_data, ensure they are either static methods or being accessed correctly via an instance of SignalGenerator.
WebSocket URL: Be sure to replace 'wss://your.websocket.url/{symbol}' with the correct endpoint based on Binance’s WebSocket documentation.
Django Setup: Since you're integrating with Django, ensure that the Django project’s path is correctly set if the script is executed outside the typical Django context:
Logging: Ensure logging levels and formats meet your debugging needs and consider rotating logs for production use.
These steps should help you resolve the issues. The most significant error is likely calling instance-required methods like fetch_historical_data as if they are standalone functions. Proper instantiation and access using class methods should mitigate such issues.
import asyncio
import json
import os
import logging
import ccxt
import pandas as pd
import websockets
from concurrent.futures import ProcessPoolExecutor
from django.utils import timezone
from .models import Signal
# Set the environment variable to point to your project’s settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'binancebot.settings')
# Initialize Django
import django
django.setup()
# 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() # Continue logging to the console
]
)
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.lower()}@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}")
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 None
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}")
async def collect_data(self, kline_data):
logging.debug(f"{self.symbol} - Latest: {kline_data}")
# Implement your data collection logic here
def generate_signals(self, df):
try:
# Calculate EMAs, Ichimoku Cloud components, ATR, RSI, and signals
df['EMA20'] = ta.EMA(df['close'], timeperiod=20)
df['EMA50'] = ta.EMA(df['close'], timeperiod=50)
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)
df['ATR'] = ta.ATR(df['high'], df['low'], df['close'], timeperiod=14)
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
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: {last_signal}")
return 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]
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):
df = self.fetch_historical_data()
if df is not None and not df.empty:
df = self.generate_signals(df)
self.save_signals(df)
else:
logging.error("No data fetched, cannot proceed with signal generation.")
def historical_data_worker(symbol, timeframe):
generator = SignalGenerator(symbol=symbol, timeframe=timeframe)
return generator.fetch_historical_data()
async def main():
exchange = ccxt.binance({'options': {'defaultType': 'future'}})
markets = exchange.fetch_markets()
# Filter for USDT pairs
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
# Setup process pool for historical data
with ProcessPoolExecutor(max_workers=6) as executor:
historical_results = list(executor.map(
historical_data_worker,
usdt_pairs,
['1m'] * len(usdt_pairs)
))
# Setup tasks for real-time data retrieval
tasks = []
for symbol in usdt_pairs:
generator = SignalGenerator(symbol=symbol)
tasks.append(generator.fetch_realtime_data())
# Use asyncio to run the real-time tasks concurrently
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Modifications Made:
Function Definitions: The methods are now within the SignalGenerator class and are accessed correctly via instances.
Concurrency Setup: Used the ProcessPoolExecutor to run historical_data_worker for historical data retrieval. Each worker now creates its own SignalGenerator instance.
WebSocket URL Correction: Ensure the trading pair symbol is in lowercase for the WebSocket URL.
Async/Await Setup: Adjusted fetch_realtime_data to run asynchronously and be collected using gather.
Please replace the placeholder WebSocket URL (wss://your.websocket.url/{symbol}) with the correct endpoint for Binance or any service you're using. Also, ensure Django is set up correctly to handle environmental settings and database interactions.
Potential Actions:
Log Results: Log each result briefly, as shown with logging.info(...).
Process/Store Data: If the data needs to be stored or processed, include this logic right after retrieving it.
Debug Output: Utilize print() or logging.debug() to output content for debug purposes if needed.
Conclusion
The key takeaway is to leverage historical_results meaningfully by logging, saving, or processing the data to ensure that the work done by the executor has a productive outcome. If you truly don't need the data from historical_results, you might consider simplifying your script to avoid unnecessary computation.
import asyncio
import json
import os
import logging
import ccxt
import pandas as pd
import websockets
from concurrent.futures import ProcessPoolExecutor
from django.utils import timezone
from .models import Signal
import talib as ta
# Set the environment variable to point to your project’s settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'binancebot.settings')
# Initialize Django
import django
django.setup()
# 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() # Continue logging to the console
]
)
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.lower()}@kline_{self.timeframe}"
self.exchange = ccxt.binance({
'options': {'defaultType': 'future'}
})
self.df = pd.DataFrame()
logging.debug(f"Initialized SignalGenerator with symbol: {symbol}, timeframe: {timeframe}")
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)
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}")
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)
def generate_signals(self):
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 technical indicators
df['EMA20'] = ta.EMA(df['close'], timeperiod=20)
df['EMA50'] = ta.EMA(df['close'], timeperiod=50)
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)
df['ATR'] = ta.ATR(df['high'], df['low'], df['close'], timeperiod=14)
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
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: {last_signal}")
self.df = df # Update self.df with new calculations
except Exception as e:
logging.error(f"Error generating signals for {self.symbol}: {e}")
def run(self):
# Initialize with historical data
self.df = self.fetch_historical_data()
# Check if there's sufficient data to start
if not self.df.empty:
self.generate_signals()
else:
logging.error("No historical data, cannot proceed with signal generation.")
def historical_data_worker(symbol, timeframe):
# Initialize and fetch historical data then return the generator
generator = SignalGenerator(symbol=symbol, timeframe=timeframe)
generator.df = generator.fetch_historical_data()
return generator
async def main():
exchange = ccxt.binance({'options': {'defaultType': 'future'}})
markets = exchange.fetch_markets()
# Filter for USDT pairs
usdt_pairs = [market['symbol'] for market in markets if '/USDT' in market['symbol']]
# Setup process pool for historical data
with ProcessPoolExecutor(max_workers=6) as executor:
generators = list(executor.map(
historical_data_worker,
usdt_pairs,
['1m'] * len(usdt_pairs)
))
# Now each SignalGenerator has historical data
tasks = []
for generator in generators:
# Start fetching real-time data for each generator
tasks.append(generator.fetch_realtime_data())
# Use asyncio to run the real-time tasks concurrently
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Key Changes:
Fetching and Appending Historical Data:
df is fetched using the fetch_historical_data and immediately used in generate_signals.
DataFrame Checks:
Perform checks to ensure there's enough data for technical analysis before attempting calculations.
Using ProcessPoolExecutor:
Ensure historical_data_worker populates the df attribute for each SignalGenerator instance, which can then be used for subsequent technical analysis.
Asynchronous Real-Time Fetching:
Asynchronous tasks for each symbol to fetch real-time data, allowing updates on existing DataFrames.
By organizing your historical data in this way, you'll ensure that it is ready to be used whenever you need to apply technical indicators for signal generation. Remember to adjust any configurations and URLs according to your actual data sources.
Query the Signal model:
python
from your_app.models import Signal
signals = Signal.objects.all()
for signal in signals:
print(signal)
This will print out all the signals stored in the database. Check that the data matches what you expect.
Step 5: Use Database Management Tools
You can also use a database management tool like pgAdmin to directly inspect the contents of your PostgreSQL database tables:
Open pgAdmin and connect to your database server.
Navigate through the tree to your database and find the Signal table.
Right-click on the table and choose "View/Edit Data" to see the contents.
Step 6: Confirm Migrations
Ensure that your database schema is up to date:
Run Django migrations to make sure all models are reflected in the database schema:
In the save_signals method, ensure robust exception handling to capture any errors:
python
def save_signals(self, df):
try:
last_signal = df.iloc[-1]
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}")
These steps should allow you to verify whether signals are being properly saved to your PostgreSQL database and help identify any issues if they are not being saved correctly.
##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)
# 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
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: {last_signal}")
self.df = 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():
self.df = self.fetch_historical_data()
#logging.debug(df.tail(5)) # Check the last few rows
if not self.df.empty:
self.generate_signals()
self.save_signals()
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, timeframe):
signal_generator = SignalGenerator(symbol=symbol, timeframe=timeframe)
signal_generator.df = signal_generator.fetch_historical_data()
if signal_generator.df is not None:
logging.info(f"Processed historical data for {symbol}")
return signal_generator
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())
In the code above, I only see Initialized SignalGenerator with symbol: {symbol}, Fetched historical data for {symbol} successfully and Processed historical data for BSV/USDT, seems like the other functions after that are not working
import asyncio
import json
import os
import logging
import ccxt
import pandas as pd
import websockets
from concurrent.futures import ProcessPoolExecutor
from django.utils import timezone
from .models import Signal
import talib as ta
# Set up Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'binancebot.settings')
django.setup()
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
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.lower()}@kline_{self.timeframe}"
self.exchange = ccxt.binance({
'options': {'defaultType': 'future'}
})
self.df = pd.DataFrame()
logging.debug(f"Initialized SignalGenerator with symbol: {self.symbol}, timeframe: {self.timeframe}")
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)
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}")
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()
def generate_signals(self):
if self.df.empty:
logging.error("No data present for signal generation.")
return
try:
df = self.df.copy()
if len(df) < 50:
logging.warning(f"Not enough data to perform full technical analysis for {self.symbol}.")
return
df['EMA20'] = ta.EMA(df['close'], timeperiod=20)
df['EMA50'] = ta.EMA(df['close'], timeperiod=50)
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)
df['ATR'] = ta.ATR(df['high'], df['low'], df['close'], timeperiod=14)
df['RSI'] = ta.RSI(df['close'], timeperiod=14)
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
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}")
def save_signals(self, df):
try:
last_signal = df.iloc[-1]
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 historical_data_worker(symbol, timeframe):
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}")
return signal_generator
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:
signal_generators = list(executor.map(
historical_data_worker,
usdt_pairs,
['1m'] * len(usdt_pairs)
))
tasks = []
for signal_generator in signal_generators:
if signal_generator.df is not None and not signal_generator.df.empty:
tasks.append(signal_generator.fetch_realtime_data())
else:
logging.error(f"Skipping real-time data fetching for {signal_generator.symbol} due to lack of historical data.")
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Key Adjustments:
More Detailed Logging: I've added more detailed logging to track precisely where each step in your code is executing. This should help determine where things might be stalling.
Signal Generation and Saving within Real-Time Data Loop: I moved generate_signals and save_signals calls inside collect_data to ensure every new set of real-time data updates the signals.
Verification on Data Before Real-Time Tasks: Each SignalGenerator checks if it has historical data before setting up real-time WebSocket connections.
Asynchronous Management: Ensure all async operations are fully compatible with Python's asynchronous runtime. Use logging immediately before async calls to help diagnose connectivity issues.
With these adjustments, you should be able to get more insight into where any failures or stalls might be happening. Make sure your WebSocket endpoints and any API keys are correctly configured in production.