hi. first of all, Im not seeing a 200 code so im  not sure if this code is properly connecting to the tradier api. and secondly, i cant seem to get the code to run properly. I will give you the code and then the error.. please try and fix it so i can get real time market data from tradier. Also, please debug the code, look it over real good, check for duplicate imports and lines of code, and if you see something that needs changed or deleted or something that would make it better, please feel free to make the changes and then send me the full complete updated code please. thank you.. HERE IS CODE: import pandas as pd
import numpy as np
import torch
from datetime import datetime, timedelta
import requests
import json
import time
from playsound import playsound
import threading
from tradier_api import Tradier
import telegram_send
import plotly.graph_objects as go
from dash import Dash, dcc, html
from dash.dependencies import Input, Output
import os

from train_transformer_model_enhanced import TransformerXLModel


import logging

# Setup logging with timestamp and file output
logging.basicConfig(
    filename='trading_assistant.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)


def create_tradier_session():
    response = requests.post('https://api.tradier.com/v1/markets/events/session',
                           data={},
                           headers={'Authorization': 'Bearer qIADpgSzG2oGEi9KYaog3tcJtZSr',
                                  'Accept': 'application/json'},
                           timeout=5
                           )
    
    if response.status_code == 200:
        json_response = response.json()
        new_session_id = json_response.get('stream', {}).get('sessionid')
        os.environ['SESSION_ID'] = new_session_id
        logging.info(f"New Tradier session created: {new_session_id}")
        return new_session_id
    else:
        logging.error(f"Failed to create Tradier session: {response.text}")
        return None

class TradingAssistant:
    def __init__(self, model_path, tradier_token, risk_percentage=2.0, account_size=25000):
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.model = self.load_model(model_path)
        self.session_id = create_tradier_session()
        self.tradier = Tradier(tradier_token, session_id=self.session_id)
        self.risk_percentage = risk_percentage
        self.account_size = account_size
        self.current_position = None
        self.sequence_length = 60
        self.features = ['Open', 'High', 'Low', 'Close', 'Volume']
        
        # Initialize dashboard
        self.app = Dash(__name__)
        self.setup_dashboard()        
    def load_model(self, path):
        model = TransformerXLModel(
            input_size=5,
            d_model=512,     # Matches trained model
            nhead=8,         # Matches trained model
            num_layers=3,    # Matches trained model
            dropout=0.1,
            mem_len=60
        )
        model.load_state_dict(torch.load(path, weights_only=True))
        model.eval()
        return model.to(self.device)
    
    def get_real_time_data(self):
        data = self.tradier.get_timesales('SPY', interval='1min')
        df = pd.DataFrame(data)
        return df[self.features].values
    
    def predict_next_move(self, sequence):
        with torch.no_grad():
            sequence = torch.FloatTensor(sequence).unsqueeze(0).to(self.device)
            prediction = self.model(sequence)
            return prediction.cpu().numpy()[0]
    
    def calculate_position_size(self, current_price, stop_loss):
        risk_amount = self.account_size * (self.risk_percentage / 100)
        position_size = risk_amount / abs(current_price - stop_loss)
        return int(position_size)
    
    def generate_trading_signals(self):
        while True:
            try:
                # Get latest data
                current_data = self.get_real_time_data()
                if len(current_data) < self.sequence_length:
                    continue
                
                # Make prediction
                sequence = current_data[-self.sequence_length:]
                predicted_price = self.predict_next_move(sequence)
                current_price = current_data[-1][3]  # Close price
                
                # Calculate metrics
                price_change = (predicted_price - current_price) / current_price * 100
                volatility = np.std(current_data[-20:, 3]) / current_price * 100
                
                # Generate signals
                if price_change > 0.5 and volatility < 1.0 and not self.current_position:
                    stop_loss = current_price - (2 * volatility)
                    position_size = self.calculate_position_size(current_price, stop_loss)
                    
                    self.send_alert(
                        "ENTRY SIGNAL",
                        f"Buy {position_size} shares at {current_price:.2f}\n"
                        f"Stop Loss: {stop_loss:.2f}\n"
                        f"Predicted Move: {price_change:.2f}%"
                    )
                    
                elif price_change < -0.3 and self.current_position:
                    self.send_alert(
                        "EXIT SIGNAL",
                        f"Close position at {current_price:.2f}\n"
                        f"Predicted Move: {price_change:.2f}%"
                    )
                
                # Update dashboard
                self.update_dashboard_data(current_price, predicted_price, price_change, volatility)
                
                time.sleep(60)  # Check every minute
                
            except Exception as e:
                print(f"Error in signal generation: {e}")
                time.sleep(60)
    
    def setup_dashboard(self):
        self.app.layout = html.Div([
            html.H1('Trading Assistant Dashboard'),
            dcc.Graph(id='price-chart'),
            dcc.Interval(id='interval-component', interval=60*1000),
            html.Div([
                html.H3('Current Position'),
                html.Div(id='position-info')
            ])
        ])
        
        @self.app.callback(
            [Output('price-chart', 'figure'),
             Output('position-info', 'children')],
            Input('interval-component', 'n_intervals')
        )
        def update_dashboard(n):
            return self.generate_dashboard_figures()
    
    def send_alert(self, title, message):
        logging.info(f"{title}: {message}")
        print(f"\n{'*'*50}\n{title}\n{message}\n{'*'*50}\n")
    
    def run(self):
        # Start signal generation in a separate thread
        signal_thread = threading.Thread(target=self.generate_trading_signals)
        signal_thread.start()
        
        # Run dashboard
        self.app.run_server(debug=False)

if __name__ == "__main__":
    assistant = TradingAssistant(
        model_path='transmodels/best_transformer_xl_model.pth',
        tradier_token='YOUR_TRADIER_TOKEN'
    )
    assistant.run()
AND HERE IS ERROR:2024-11-13 05:52:44,559 INFO:New Tradier session created: a86cee7b-bac4-452a-b4c7-e604541423f6
Dash is running on http://127.0.0.1:8050/

2024-11-13 05:52:44,571 INFO:Dash is running on http://127.0.0.1:8050/

 * Serving Flask app 'trading_assistant'
 * Debug mode: off
2024-11-13 05:52:44,591 INFO:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:8050
2024-11-13 05:52:44,592 INFO:Press CTRL+C to quit
Error in signal generation: Expecting value: line 1 column 1 (char 0)
Error in signal generation: Expecting value: line 1 column 1 (char 0)
Error in signal generation: Expecting value: line 1 column 1 (char 0)
Error in signal generation: Expecting value: line 1 column 1 (char 0)
Error in signal generation: Expecting value: line 1 column 1 (char 0)