import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt

date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)

url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)

# API keys and other configuration
API_KEY = ''
API_SECRET = ''

client = Client(API_KEY, API_SECRET)

STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 0.27
order_type = 'MARKET'
leverage = 125

client = Client(API_KEY, API_SECRET)

def getminutedata(symbol, interval, lookback):
    frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC'))
    frame = frame.iloc[:60,:6]
    frame.columns = ['Time','Open','High','Low','Close','Volume']
    frame = frame.set_index('Time')
    today = dt.date.today()
    frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S")
    frame = frame.astype(float)
    return frame

df = getminutedata('BTCUSDT', '1m', '44640')

def signal_generator(df):
    open = df.Open.iloc[-1]
    close = df.Close.iloc[-1]
    previous_open = df.Open.iloc[-2]
    previous_close = df.Close.iloc[-2]

        #Bearish pattern
    if (open>close and 
    previous_open<previous_close and
    close<previous_open and 
    open>=previous_close):
        return 'sell'

        #Bullish pattern
    elif (open<close and
    previous_open>previous_close and
    close>previous_open and
    open<=previous_close):
        return 'buy'
        
        #No clear pattern
    else:
        return ''
df = getminutedata('BTCUSDT', '1m', '44640')
signal = ["" for i in range(len(df))] # initialize signal as a list of empty strings
for i in range(1, len(df)):
    df_temp = df[i-1:i+1]
    signal[i] = signal_generator(df_temp)
df["signal"] = signal

def order_execution(symbol, interval, lookback, max_trade_quantity_percentage):
    MAX_TRADE_QUANTITY_PERCENTAGE = max_trade_quantity_percentage
    
    account_balance = client.futures_account_balance()
    usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
    max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100

    STOP_LOSS_PERCENTAGE = -50
    TAKE_PROFIT_PERCENTAGE = 100
    POSITION_SIDE_SHORT = SIDE_SELL
    POSITION_SIDE_LONG = SIDE_BUY
    long_position = POSITION_SIDE_LONG
    short_position = POSITION_SIDE_SHORT

    positions = client.futures_position_information(symbol=symbol)

    long_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'LONG'), None)
    if long_position:
        # Close long position if signal is opposite
        if signal[i] == "sell":
            order = client.futures_create_order(
                symbol=symbol,
                side=SIDE_SELL,
                type=ORDER_TYPE_MARKET,
                quantity=long_position['positionAmt'],
                reduceOnly=True
            )
            print(f"Closed long position with order ID {order['orderId']}")
            time.sleep(1)
    # Place short order if signal is the same
    else:
        order_quantity = min(max_trade_quantity, float(long_position['maxNotionalValue']) / leverage)
        order = client.futures_create_order(
            symbol=symbol,
            side=SIDE_SELL,
            type=ORDER_TYPE_MARKET,
            quantity=order_quantity,
            reduceOnly=False,
            timeInForce=TIME_IN_FORCE_GTC,
            positionSide=POSITION_SIDE_SHORT,
            leverage=leverage
        )
        print(f"Placed short order with order ID {order['orderId']} and quantity {order_quantity})")
        time.sleep(1)
        # Set stop loss and take profit orders
        stop_loss_price = order['avgPrice'] * (1 + STOP_LOSS_PERCENTAGE / 100)
        take_profit_price = order['avgPrice'] * (1 + TAKE_PROFIT_PERCENTAGE / 100)
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_BUY,
            type=ORDER_TYPE_STOP_LOSS,
            quantity=order_quantity,
            stopPrice=stop_loss_price,
            reduceOnly=True,
            timeInForce=TIME_IN_FORCE_GTC,
            positionSide=POSITION_SIDE_SHORT
        )
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_BUY,
            type=ORDER_TYPE_LIMIT,
            quantity=order_quantity,
            price=take_profit_price,
            reduceOnly=True,
            timeInForce=TIME_IN_FORCE_GTC,
            positionSide=POSITION_SIDE_SHORT
        )
        print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}")
        time.sleep(1)

    short_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'SHORT'), None)
    if short_position:
        # Close short position if signal is opposite
        if signal[i] == "buy":
            order = client.futures_create_order(
                symbol=symbol,
                side=SIDE_BUY,
                type=ORDER_TYPE_MARKET,
                quantity=short_position['positionAmt'],
                reduceOnly=True
            )
            print(f"Closed short position with order ID {order['orderId']}")
            time.sleep(1)
    # Place long order if signal is the same
    else:
        order_quantity = min(max_trade_quantity, float(short_position['maxNotionalValue']) / leverage)
        order = client.futures_create_order(
            symbol=symbol,
            side=SIDE_BUY,
            type=ORDER_TYPE_MARKET,
            quantity=order_quantity,
            reduceOnly=False,
            timeInForce=TIME_IN_FORCE_GTC,
            positionSide=POSITION_SIDE_LONG,
            leverage=leverage
        )
        print(f"Placed long order with order ID {order['orderId']} and quantity {order_quantity}")
        time.sleep(1)
        # Set stop loss and take profit orders
        stop_loss_price = order['avgPrice'] * (1 - STOP_LOSS_PERCENTAGE / 100)
        take_profit_price = order['avgPrice'] * (1 - TAKE_PROFIT_PERCENTAGE / 100)
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_SELL,
            type=ORDER_TYPE_STOP_LOSS,
            quantity=order_quantity,
            stopPrice=stop_loss_price,
            reduceOnly=True,
            timeInForce=TIME_IN_FORCE_GTC,
            positionSide=POSITION_SIDE_LONG
        )
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_SELL,
            type=ORDER_TYPE_LIMIT,
            quantity=order_quantity,
            price=take_profit_price,
            reduceOnly=True,
            timeInForce=TIME_IN_FORCE_GTC,
            positionSide=POSITION_SIDE_LONG
        )
        print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}")
        time.sleep(1)

    current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    current_signal = signal_generator(df.signal.iloc[-1])

    while True:
        print(f"The signal time is: {current_time} :{current_signal}")
        time.sleep(1) # Add a delay of 1 second
        positions = client.futures_position_information(symbol='BTCUSDT')
        current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") How I can print live signals with time.sleep(1) ?