improve script berikut ini agar lebih smart dalam managament posisi jika arah market jauh berlawanan arah, gunakan cara atau logika yang sangat pintar dan mind blowing yang dapat di implementasikan untuk mengurangi loss dan mencegah margin call, karena script ini digunakan untuk capital yang minim, buatkan dengan tanpa menghapus fitur yang ada, lakukan saja improvisasi dengan benar dan lengkap : import asyncio
import sys
import os
import logging
import time
import MetaTrader5 as mt5
from utilities import Utils
from indicator import Indicator, Candle
from metatrader import Order

## Telegram Configuration
TOKEN = '<TRUFFLEHOG_REDACTED_TELEGRAMBOTTOKEN>'
CHAT_ID = '882283026'

## MetaTrader Configuration
path = "C:\\Program Files\\MetaTrader 5\\terminal64.exe"
login = 103880989
server = "Exness-MT5Real15"
password = "748798lokaldeN#"  

## Order Configuration
symbols = ["XAUUSD"]
vol = 0.01
max_lots = 3 * vol
pnl_add = -1000 * vol
vol_add = 2 * vol

## Configure logging
logging.basicConfig(
    format="%(asctime)s - %(message)s", level=logging.INFO
)
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)

## Library
indicator = Indicator()
bot_utils = Utils(token=TOKEN, chat_id=CHAT_ID, server=server)
candles = Candle(bot_utils)
order = Order(bot_utils)
script_dir = os.path.dirname(os.path.abspath(__file__))
script = os.path.splitext(os.path.basename(__file__))[0]

## Initial ---------------------------------------------------------------------------------
async def main():
    logger.info(f"Script Starting for {server}")

    if not mt5.initialize(path=path, login=login, server=server, password=password):
        logger.error(f"initialize() failed, error code: {mt5.last_error()}")
        return
    
    message_time = time.time()

    while True:  
        try:
            for symbol in symbols:
                logger.info(f"{script}_Running for {login}_{symbol}...")

                ## INDICATOR
                ma = await indicator.moving_average(symbol=symbol)
                supmacd = await indicator.macd(symbol=symbol)
                trf = await indicator.twin_range_filter(symbol=symbol)
                candle = await indicator.candle_check(symbol=symbol)
                psar = await indicator.parabolic_sar(symbol=symbol)
                bband, upper_band, lower_band = await indicator.bollinger_bands(symbol=symbol)
                
                ## GET INFO
                orders = mt5.orders_get(symbol=symbol)
                position_added = False
                if orders:
                    for _order in orders:
                        if (_order.type == mt5.ORDER_TYPE_BUY_LIMIT or _order.type == mt5.ORDER_TYPE_SELL_LIMIT) and _order.volume_current == vol_add:
                            position_added = True
                            break
                positions = mt5.positions_get(symbol=symbol)
                if positions:
                    lot_buy = sum(p.volume for p in positions if p.type == mt5.POSITION_TYPE_BUY)
                    lot_sell = sum(p.volume for p in positions if p.type == mt5.POSITION_TYPE_SELL)
                    buy_pnl = sum(p.profit for p in positions if p.type == mt5.POSITION_TYPE_BUY)
                    sell_pnl = sum(p.profit for p in positions if p.type == mt5.POSITION_TYPE_SELL)
                    total_pl = sum(p.profit for p in positions)
                    avg_open_price_buy = sum(p.price_open * p.volume for p in positions if p.type == mt5.POSITION_TYPE_BUY) / lot_buy if lot_buy > 0 else 0
                    avg_open_price_sell = sum(p.price_open * p.volume for p in positions if p.type == mt5.POSITION_TYPE_SELL) / lot_sell if lot_sell > 0 else 0
                    for position in positions:
                        if position.volume == vol_add:
                            position_added = True
                            break
                else:
                    avg_open_price_buy = avg_open_price_sell =  lot_buy = lot_sell = total_pl = buy_pnl = sell_pnl = 0

                account_info = mt5.account_info()
                if account_info:
                    equity = account_info.equity
                    balance = account_info.balance
                    drawdown = (balance - equity) / balance * 100

                ## PYRAMIDING FLOATING POSITION
                if positions and (lot_buy + lot_sell) < max_lots * 2:
                    if total_pl < pnl_add:
                        if not position_added:
                            current_price = mt5.symbol_info_tick(symbol).bid if positions[0].type == mt5.POSITION_TYPE_BUY else mt5.symbol_info_tick(symbol).ask
                            distance = 3
                            for i, position in enumerate(positions):
                                order_type = "buy_limit" if position.type == mt5.POSITION_TYPE_BUY else "sell_limit"
                                price_offset = (i + 1) * distance
                                if position.type == mt5.POSITION_TYPE_BUY:
                                    limit_price = current_price - price_offset
                                else:
                                    limit_price = current_price + price_offset
                                await order.send_order(
                                    symbol=symbol,
                                    volume=vol_add,
                                    order_type=order_type,
                                    price=limit_price
                                )
                                position_added = True

                ## CLOSE POSITION         
                if positions:
                    for position in positions:
                        if ((bband == 1 and position.type == mt5.POSITION_TYPE_BUY) or
                            (bband == 2 and position.type == mt5.POSITION_TYPE_SELL)):
                            candle_close = await candles.candle_cp(symbol=symbol, bband=bband)
                            if candle_close == 1 or candle_close == 2:
                                await order.close_order(symbol=symbol, current_bband=bband, candle_close=candle_close)
                                for order_ in orders:
                                    if order_.type == mt5.ORDER_TYPE_BUY_LIMIT or order_.type == mt5.ORDER_TYPE_SELL_LIMIT:
                                        close_order={
                                            "order": order_.ticket,
                                            "action": mt5.TRADE_ACTION_REMOVE,   
                                            }
                                        mt5.order_send(close_order)
                                position_added = False

                ## MESSAGE
                messages = [
                    f"{signal_name} {'🚀<i>Bullish</i>🚀' if signal_value == 1 else '🔻<i>Bearish</i>🔻' if signal_value == 2 else '⚪️<i>Neutral</i>⚪️'}"
                    for signal_name, signal_value in [
                        ("<b>MA:</b>", ma),
                        ("<b>MACD:</b>", supmacd),
                        ("<b>TRF:</b>", trf),
                        ("<b>Candle:</b>", candle),
                        ("<b>SAR:</b>", psar),
                        ("<b>BBand:</b>", bband)
                    ]
                ]
                drawdown_display = '-' if drawdown < 0 else f"{drawdown:.2f}%" 
                if lot_buy > 0:
                    messages.append(
                        f"--------------------------------------------------------------------\n"
                        f"<i>Buy:</i> <b>{lot_buy:.2f} lot(s)</b> at <b>${avg_open_price_buy:.2f}</b> | <b>${buy_pnl:.2f} 💵</b> |\n"
                        f"<i>Target Price:</i> <b>${upper_band:.2f}</b> |\n"
                        f"<i>Drawdown:</i> <b>{drawdown_display}</b>\n"
                        )
                if lot_sell > 0:
                    messages.append(
                        f"--------------------------------------------------------------------\n"
                        f"<i>Sell:</i> <b>{lot_sell:.2f} lot(s)</b> at <b>${avg_open_price_sell:.2f}</b> | <b>${sell_pnl:.2f} 💵</b> |\n"
                        f"<i>Target Price:</i> <b>${lower_band:.2f}</b> |\n"
                        f"<i>Drawdown:</i> <b>{drawdown_display}</b>\n"
                        ) 
                current_time = time.time()
                if current_time - message_time >= 11:
                    await bot_utils.send_message_async("\n".join(messages), symbol)
                    message_time = current_time

                ## OPEN POSITION
                if supmacd==1 and trf==1 and candle==1 and psar==1 and ma==1:
                    if lot_buy < max_lots:
                        candle_signal = await candles.candle_op(symbol=symbol, order_type="buy")
                        if candle_signal == 1:
                            if lot_sell > 0 and drawdown > 80:
                                for position in positions:
                                    if position.type == mt5.POSITION_TYPE_SELL:
                                        mt5.Close(symbol, ticket=position.ticket)
                                for order_ in orders:
                                    if order_.type == mt5.ORDER_TYPE_SELL_LIMIT:
                                        close_order={
                                            "order": order_.ticket,
                                            "action": mt5.TRADE_ACTION_REMOVE,   
                                            }
                                        mt5.order_send(close_order)
                            await order.send_order(symbol=symbol, volume=vol, order_type="buy")
                            await asyncio.sleep(120)
                        else:
                            await bot_utils.send_message_async(f"No suitable candle condition for Buy\n", symbol)
                    else:
                        await bot_utils.send_message_async(f"Maximum number of Buy positions ({max_lots}) reached for {symbol}. Skipping trade execution.\n", symbol)
                        await asyncio.sleep(120)

                elif supmacd==2 and trf==2 and candle==2 and psar==2 and ma==2:
                    if lot_sell < max_lots:
                        candle_signal = await candles.candle_op(symbol=symbol, order_type="sell")
                        if candle_signal == 2:
                            if lot_buy > 0 and drawdown > 80:
                                for position in positions:
                                    if position.type == mt5.POSITION_TYPE_BUY:
                                        mt5.Close(symbol, ticket=position.ticket)
                                for order_ in orders:
                                    if order_.type == mt5.ORDER_TYPE_BUY_LIMIT:
                                        close_order={
                                            "order": order_.ticket,
                                            "action": mt5.TRADE_ACTION_REMOVE,   
                                            }
                                        mt5.order_send(close_order)
                            await order.send_order(symbol=symbol, volume=vol, order_type="sell")
                            await asyncio.sleep(120)
                        else:
                            await bot_utils.send_message_async(f"No suitable candle condition for Sell\n", symbol)
                    else:
                        await bot_utils.send_message_async(f"Maximum number of Sell positions ({max_lots}) reached for {symbol}. Skipping trade execution.\n", symbol)
                        await asyncio.sleep(120)
                else:
                    await asyncio.sleep(1)
                    continue
                
        except Exception as e:
            await bot_utils.send_message_async("An error occurred: \n" + str(e), symbol)
            await asyncio.sleep(10)
            continue
                
try:
    asyncio.run(main())
except KeyboardInterrupt:
    logger.info(".....Script stopped by user. Exiting gracefully.....")
    sys.exit(0)