this is my script "from flask import Flask, request
from binance.client import Client
from telegram import Bot
import sys
import os
from binance.enums import *
from dotenv import load_dotenv
import math
import asyncio
import aiohttp
from werkzeug.exceptions import HTTPException
from threading import Thread, Event
import threading
import time
import multiprocessing
from multiprocessing import Value

load_dotenv()  # take environment variables from .env.

binance_api_key = os.getenv("BINANCE_API_KEY")
binance_api_secret = os.getenv("BINANCE_API_SECRET")
bot_token = os.getenv("TELEGRAM_BOT_TOKEN")
channel_id = os.getenv("TELEGRAM_CHANNEL_ID")

app = Flask(__name__)

client = Client(binance_api_key, binance_api_secret)
bot = Bot(token=bot_token)

# Event for stopping the server
stop_event = Event()

# Initialize total_pnl as a shared variable
total_pnl = Value('d', 0.0)  # 'd' is the typecode for double

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

def run_asyncio_coroutine(coroutine):
    return loop.run_until_complete(coroutine)

async def send_message(text):
    async with aiohttp.ClientSession() as session:
        url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
        payload = {"chat_id": channel_id, "text": text}
        async with session.post(url, data=payload) as resp:
            return await resp.text()

total_pnl.value = 0

def get_balance(asset="USDT"):
    balances = client.futures_account_balance()
    for balance in balances:
        if balance["asset"] == asset:
            return float(balance["withdrawAvailable"])
    return 0

def get_precision(symbol):
    info = client.futures_exchange_info()
    for s in info['symbols']:
        if s['symbol'] == symbol:
            return next((filter['stepSize'] for filter in s['filters'] if filter['filterType'] == 'LOT_SIZE'), None)
    return None

def calculate_pnl(entry_price, exit_price, leverage, action):
    percentage_change = ((exit_price - entry_price) / entry_price) * 100
    if action == "SHORT":
        percentage_change = -percentage_change
    pnl = percentage_change * leverage
    print(f"Calculated PnL: {pnl}%")  # New line
    return pnl

def close_all_positions(symbol):
    positions = client.futures_position_information(symbol=symbol)
    for position in positions:
        if float(position['positionAmt']) > 0:
            exit_price = float(client.futures_ticker(symbol=symbol)["lastPrice"])
            entry_price = float(position['entryPrice'])
            pnl = calculate_pnl(entry_price, exit_price, float(position['leverage']), "LONG")
            total_pnl.value += pnl
            print(f"Total PnL: {total_pnl.value}%")  # New line
            message = f"Closed LONG position on {symbol} at price {exit_price}. PnL: {pnl}%"
            print(message)
            run_asyncio_coroutine(send_message(message))
            client.futures_create_order(
                symbol=symbol,
                side=SIDE_SELL,
                positionSide="LONG",
                quantity=float(position['positionAmt']),
                type=ORDER_TYPE_MARKET
            )
        elif float(position['positionAmt']) < 0:
            exit_price = float(client.futures_ticker(symbol=symbol)["lastPrice"])
            entry_price = float(position['entryPrice'])
            pnl = calculate_pnl(entry_price, exit_price, float(position['leverage']), "SHORT")
            total_pnl.value += pnl
            print(f"Total PnL: {total_pnl.value}%")  # New line
            message = f"Closed SHORT position on {symbol} at price {exit_price}. PnL: {pnl}%"
            print(message)
            run_asyncio_coroutine(send_message(message))
            client.futures_create_order(
                symbol=symbol,
                side=SIDE_BUY,
                positionSide="SHORT",
                quantity=abs(float(position['positionAmt'])),
                type=ORDER_TYPE_MARKET
            )

def handle_entry(symbol, action, quantity, leverage):
    client.futures_change_leverage(symbol=symbol, leverage=leverage)
    if action == "LONG":
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_BUY,
            positionSide="LONG",
            type=ORDER_TYPE_MARKET,
            quantity=quantity
        )
    else:  # SHORT
        client.futures_create_order(
            symbol=symbol,
            side=SIDE_SELL,
            positionSide="SHORT",
            type=ORDER_TYPE_MARKET,
            quantity=quantity
        )

symbol_action_map = {
    "btc": ["LONG", "SHORT", "EXIT_LONG", "EXIT_SHORT", "STOPLOSS"],
    "eth": ["LONG1", "SHORT1", "EXIT_LONG1", "EXIT_SHORT1", "STOPLOSS1"],
    "xrp": ["LONG2", "SHORT2", "EXIT_LONG2", "EXIT_SHORT2", "STOPLOSS2"],
    "matic": ["LONG3", "SHORT3", "EXIT_LONG3", "EXIT_SHORT3", "STOPLOSS3"],
    "bnb": ["LONG4", "SHORT4", "EXIT_LONG4", "EXIT_SHORT4", "STOPLOSS4"],
    "dot": ["LONG5", "SHORT5", "EXIT_LONG5", "EXIT_SHORT5", "STOPLOSS5"],
    "sol": ["LONG6", "SHORT6", "EXIT_LONG6", "EXIT_SHORT6", "STOPLOSS6"],
    "agix": ["LONG7", "SHORT7", "EXIT_LONG7", "EXIT_SHORT7", "STOPLOSS7"],
    "xvs": ["LONG8", "SHORT8", "EXIT_LONG8", "EXIT_SHORT8", "STOPLOSS8"],
    "fxs": ["LONG9", "SHORT9", "EXIT_LONG9", "EXIT_SHORT9", "STOPLOSS9"],
}

symbol_leverage_map = {
    "btc": 50,
    "eth": 50,
    "xrp": 25,
    "matic": 25,
    "bnb": 45,
    "dot": 25,
    "sol": 25,
    "agix": 25,
    "xvs": 25,
    "fxs": 25,
}

def webhook():
    data = request.data.decode('utf-8')  # get the text data directly
    print(f"Received webhook data: {data}")
    try:
        message = data.upper()  # assuming that the entire message is the action
        symbol = "btc"  # default to BTC if no symbol is specified in the message
        for potential_symbol, actions in symbol_action_map.items():
            if any(action in message for action in actions):
                symbol = potential_symbol
                break
        leverage = symbol_leverage_map[symbol.upper()]
        symbol += "USDT"
        precision = float(get_precision(symbol))
        quantity = math.floor((get_balance() * 0.03) / float(client.futures_ticker(symbol=symbol)["lastPrice"]) / precision) * precision
        if "LONG" in message:
            handle_entry(symbol, "LONG", quantity, leverage)
        elif "SHORT" in message:
            handle_entry(symbol, "SHORT", quantity, leverage)
        elif "EXIT" in message or "STOPLOSS" in message:
            close_all_positions(symbol)
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        run_asyncio_coroutine(send_message(f"An error occurred: {str(e)}"))
    return {
        "code": "success",
    }, 200

@app.errorhandler(Exception)
def handle_exception(e):
    # pass through HTTP errors
    if isinstance(e, HTTPException):
        return e

    # now you're handling non-HTTP exceptions only
    print(f"Unhandled Exception: {str(e)}")
    return "Internal server error", 500

def run_app():
    app.run(host='0.0.0.0', port=5000, debug=False)

# Flag to indicate if the application should exit
should_exit = False

def check_for_exit():
    global should_exit
    while True:
        if should_exit:
            print(f"Bye")
            os._exit(0)
        time.sleep(1)  # Check every second

if __name__ == "__main__":
    # Start the server in a separate process
    server_process = multiprocessing.Process(target=run_app)
    server_process.start()

    try:
        while True:
            time.sleep(0.1)
    except KeyboardInterrupt:
        print(f"Total PnL on termination: {total_pnl.value}%")
        run_asyncio_coroutine(send_message(f"Total PnL on termination: {total_pnl.value}%"))
        server_process.terminate()
        server_process.join()
"