Make the trading strategy better. Upgrade the overall function and include ways we can avert risk for small profit.

def simulate_trading_smart_retrain():
    model_path = 'retrain_model.h5'

    # Load the model


    #model = create_model((48,6))
    model = load_model(model_path, compile=False)
    model.compile(optimizer=Adam(learning_rate=0.001), loss='mse', run_eagerly=True)

    window_num = 48
    # Load and normalize the data
    ds = pd.read_csv('price_data2.csv')
    ds = ds.assign(Date=pd.to_datetime(ds['Date']))
    ds.loc[ds['Volume']=="-",'Volume']=0
    ds['Volume'] = ds['Volume'].astype('int64')
    ds=ds[['Date','Close','Open','High','Low','Volume','Market Cap']]
    ds.head()
    scaler = MinMaxScaler()
    ds.drop(['Date'],inplace=True,axis=1)

    ds_normalized = scaler.fit_transform(ds.values[-2232:])
    #ds_normalized = scaler.fit_transform(ds.values[-744:])
    balance = 10  
    holding = False  
    buy_time = None  
    sell_time = None  
    wanted_buy_price = None  
    wanted_sell_price = None  
    prediction_data = []  
    timestamps = []  # Store timestamps for predictions
    balance_over_time = [balance]  # Track balance changes
    actual_prices = [x[0] for x in scaler.inverse_transform(ds_normalized).tolist()]
    print(actual_prices[:10])
    buy_points = []
    sell_points = []
    buy_price = None
    give_up = 0
    # Loop through the data for trading simulation
    for i in range(window_num, len(ds_normalized)):  
        current_window = ds_normalized[i - window_num:i]
        
        pred = model.predict(np.array([current_window]))
        pred = np.concatenate((pred[0], current_window[-1][1:]))
        pred = scaler.inverse_transform([pred])
        pred = pred[0][0]   

        current_price = scaler.inverse_transform([current_window[-1]])
        current_price = current_price[0][0]
        if holding is False and current_price < pred:
            holding = True
            #print('buy', i, current_price)
            buy_points.append((i, current_price))
            sell_time = i+1
            wanted_sell_price = pred
            buy_price = current_price

        if sell_time is not None and sell_time >= i:

            if current_price <= wanted_sell_price and give_up <= 5:  # Max price is greater than the desired sell price
                sell_time += i
                give_up += 1
            else:
                if holding:

                    #print('sell', i, current_price)
                    
                    trade_result = (current_price - buy_price) / buy_price * balance
                    balance += trade_result
                    print(balance, i//24)
                    balance_over_time.append(balance) 
                    holding = False
                    sell_points.append((i, current_price))
                give_up = 0 
     
        timestamps.append(i)
        prediction_data.append(pred)
        if i/24 % 4 == 0:
            # Retrain model on the last 8 days
            data = ds_normalized[i - (4*24):i]
            X, y = process_entries(data)
            history = model.fit(X, y, epochs=5, batch_size=32, verbose=2, shuffle=False)
            model.save('retrain_model.h5')

            balance_over_time.append(balance)  # Record balance periodically
    print(f"Final Balance: {balance}")

    # Plot actual prices and trades
    plt.figure(figsize=(14, 7))
    actual_prices = [x[0] for x in scaler.inverse_transform(ds_normalized).tolist()]
    plt.plot(actual_prices, label="Actual Prices", color='blue')
    plt.plot(timestamps, prediction_data[:len(timestamps)], label="Predicted Prices", color='orange', alpha=0.6)
    for t, price in buy_points:
        plt.scatter(t, price, marker='^', color='green', label='Buy' if t == buy_points[0][0] else "")
    for t, price in sell_points:
        plt.scatter(t, price, marker='v', color='red', label='Sell' if t == sell_points[0][0] else "")

    plt.xlabel("Time")
    plt.ylabel("Price")
    plt.title("AI Trading Simulation")
    plt.legend()
    plt.grid()
    plt.show()

    # Plot balance over time
    plt.figure(figsize=(14, 5))
    plt.plot(balance_over_time, label="Balance Over Time", color='purple')
    plt.xlabel("Time Steps")
    plt.ylabel("Balance")
    plt.title("Balance Changes During Simulation")
    plt.legend()
    plt.grid()
    plt.show()