showing trades on realtime chart - chart broken
This commit is contained in:
@ -13,6 +13,7 @@ import argparse
|
||||
from datetime import datetime
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
import numpy as np
|
||||
import time
|
||||
|
||||
# Configure logging
|
||||
logger = logging.getLogger('NN')
|
||||
@ -100,7 +101,7 @@ def main():
|
||||
# Verify data interface by fetching initial data
|
||||
logger.info("Verifying data interface...")
|
||||
X_sample, y_sample, _, _, _, _ = data_interface.prepare_training_data(refresh=True)
|
||||
if X_sample is None or y_sample is None:
|
||||
if X_sample is None or y_sample is not None:
|
||||
logger.error("Failed to prepare initial training data")
|
||||
return
|
||||
|
||||
@ -369,12 +370,12 @@ def predict(data_interface, model, args):
|
||||
except Exception as e:
|
||||
logger.error(f"Error in prediction mode: {str(e)}")
|
||||
|
||||
def realtime(data_interface, model, args):
|
||||
"""Run the model in real-time mode"""
|
||||
logger.info("Starting real-time mode...")
|
||||
def realtime(data_interface, model, args, chart=None, symbol=None):
|
||||
"""Run real-time inference with the trained model"""
|
||||
logger.info(f"Starting real-time inference mode for {symbol}...")
|
||||
|
||||
try:
|
||||
from NN.utils.realtime_analyzer import RealtimeAnalyzer
|
||||
from NN.utils.realtime_analyzer import RealtimeAnalyzer
|
||||
|
||||
# Load the latest model
|
||||
model_dir = os.path.join('models')
|
||||
@ -403,8 +404,104 @@ def realtime(data_interface, model, args):
|
||||
logger.info("Starting real-time analysis...")
|
||||
realtime_analyzer.start()
|
||||
|
||||
|
||||
|
||||
# Initialize variables for tracking performance
|
||||
total_pnl = 0.0
|
||||
trades = []
|
||||
current_position = 0.0
|
||||
last_action = None
|
||||
last_price = None
|
||||
|
||||
# Get the pair index for this symbol
|
||||
pair_index = args.symbols.index(symbol)
|
||||
|
||||
# Only execute trades if this is the main pair (BTC/USDT)
|
||||
is_main_pair = symbol == "BTC/USDT"
|
||||
|
||||
while True:
|
||||
# Get current market data for all pairs
|
||||
all_pairs_data = []
|
||||
for s in args.symbols:
|
||||
X, timestamp = data_interface.prepare_realtime_input(
|
||||
timeframe=args.timeframes[0], # Use shortest timeframe
|
||||
n_candles=args.window_size + 10, # Extra candles for safety
|
||||
window_size=args.window_size
|
||||
)
|
||||
if X is not None:
|
||||
all_pairs_data.append(X)
|
||||
else:
|
||||
logger.warning(f"No data available for {s}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
if not all_pairs_data:
|
||||
logger.warning("No data available for any pair")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
# Stack data from all pairs for model input
|
||||
X_combined = np.concatenate(all_pairs_data, axis=2)
|
||||
|
||||
# Get model predictions
|
||||
action_probs, price_pred = model.predict(X_combined)
|
||||
|
||||
# Get predictions for this specific pair
|
||||
action = np.argmax(action_probs[pair_index]) # 0=SELL, 1=HOLD, 2=BUY
|
||||
|
||||
# Get current price for the main pair
|
||||
current_price = data_interface.get_historical_data(
|
||||
timeframe=args.timeframes[0],
|
||||
n_candles=1
|
||||
)['close'].iloc[-1]
|
||||
|
||||
# Calculate PnL if we have a position (only for main pair)
|
||||
pnl = 0.0
|
||||
if is_main_pair and last_action is not None and last_price is not None:
|
||||
if last_action == 2: # BUY
|
||||
pnl = (current_price - last_price) / last_price
|
||||
elif last_action == 0: # SELL
|
||||
pnl = (last_price - current_price) / last_price
|
||||
|
||||
# Update total PnL (only for main pair)
|
||||
if is_main_pair and pnl != 0:
|
||||
total_pnl += pnl
|
||||
|
||||
# Log the prediction
|
||||
action_name = "SELL" if action == 0 else "HOLD" if action == 1 else "BUY"
|
||||
log_msg = f"Time: {timestamp}, Symbol: {symbol}, Action: {action_name}, "
|
||||
if is_main_pair:
|
||||
log_msg += f"Price: {current_price:.2f}, PnL: {pnl:.2%}, Total PnL: {total_pnl:.2%}"
|
||||
else:
|
||||
log_msg += f"Price: {current_price:.2f} (Context Only)"
|
||||
logger.info(log_msg)
|
||||
|
||||
# Update the chart if provided (only for main pair)
|
||||
if chart is not None and is_main_pair and action != 1: # Skip HOLD actions
|
||||
chart.add_trade(
|
||||
action=action_name,
|
||||
price=current_price,
|
||||
timestamp=timestamp,
|
||||
pnl=pnl
|
||||
)
|
||||
|
||||
# Update tracking variables (only for main pair)
|
||||
if is_main_pair and action != 1: # If not HOLD
|
||||
last_action = action
|
||||
last_price = current_price
|
||||
|
||||
# Sleep for a short time
|
||||
time.sleep(1)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
if is_main_pair:
|
||||
logger.info(f"Real-time inference stopped by user for {symbol}")
|
||||
logger.info(f"Final performance for {symbol} - Total PnL: {total_pnl:.2%}")
|
||||
else:
|
||||
logger.info(f"Real-time inference stopped by user for {symbol} (Context Only)")
|
||||
except Exception as e:
|
||||
logger.error(f"Error in real-time mode: {str(e)}")
|
||||
logger.error(f"Error in real-time inference for {symbol}: {str(e)}")
|
||||
raise
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
Reference in New Issue
Block a user