using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class HmaClusterBot : Robot
    {
        #region Parameters

        [Parameter("Symbols (CSV)", DefaultValue = "", Group = "Multi Symbol")]
        public string SymbolsCsv { get; set; }

        [Parameter("Risk % of Balance", DefaultValue = 1.0, MinValue = 0.1, MaxValue = 10.0, Group = "Risk")]
        public double RiskPercent { get; set; }

        [Parameter("Entry Significance %", DefaultValue = 20.0, MinValue = 1.0, Group = "Thresholds")]
        public double EntrySigThreshold { get; set; }

        [Parameter("Stop Loss Significance %", DefaultValue = 10.0, MinValue = 1.0, Group = "Thresholds")]
        public double SlSigThreshold { get; set; }

        [Parameter("SMA Bias Period", DefaultValue = 200, Group = "Bias")]
        public int SmaBiasPeriod { get; set; }

        [Parameter("HMA Bias Period", DefaultValue = 250, Group = "Bias")]
        public int HmaBiasPeriod { get; set; }

        [Parameter("Use Bias Deviation Filter", DefaultValue = true, Group = "Bias Filter")]
        public bool UseBiasDeviationFilter { get; set; }

        [Parameter("Bias Deviation Avg Period", DefaultValue = 500, Group = "Bias Filter")]
        public int BiasDeviationAvgPeriod { get; set; }

        [Parameter("Use Dynamic Position Management", DefaultValue = true, Group = "Management")]
        public bool UseDynamicPositionManagement { get; set; }

        [Parameter("Close Profit on Bias Flip", DefaultValue = false, Group = "Management")]
        public bool CloseProfitOnBiasFlip { get; set; }

        [Parameter("HMA Cluster Period", DefaultValue = 25, Group = "Clusters")]
        public int HmaClusterPeriod { get; set; }

        [Parameter("Cluster Max Points", DefaultValue = 2000, Group = "Clusters")]
        public int MaxPoints { get; set; }

        [Parameter("Cluster Decay (Bars)", DefaultValue = 1000, Group = "Clusters")]
        public int DecayPeriod { get; set; }

        // --- Telegram Parameters ---
        [Parameter("Send Telegram Only", DefaultValue = false, Group = "Telegram")]
        public bool SendTelegramOnly { get; set; }

        [Parameter("Telegram Bot Token", DefaultValue = "8569913524:AAE9RGsvkBPa0yhTFCKBjVeST0fuzdOx5w0", Group = "Telegram")]
        public string TelegramBotToken { get; set; }

        [Parameter("Telegram Chat ID", DefaultValue = "5171721381", Group = "Telegram")]
        public string TelegramChatId { get; set; }

        #endregion

        private readonly List<ClusterStrategy> _strategies = new List<ClusterStrategy>();
        private static readonly HttpClient _httpClient = new HttpClient();

        protected override void OnStart()
        {
            try 
            {
                if (string.IsNullOrWhiteSpace(SymbolsCsv))
                {
                    Print("CSV is empty. Running in Single-Symbol Mode on Chart Symbol.");
                    
                    var config = new StrategyConfig
                    {
                        SymbolName = SymbolName,
                        EntrySigThreshold = EntrySigThreshold,
                        SlSigThreshold = SlSigThreshold,
                        SmaBiasPeriod = SmaBiasPeriod,
                        HmaBiasPeriod = HmaBiasPeriod,
                        HmaClusterPeriod = HmaClusterPeriod,
                        UseBiasDeviationFilter = UseBiasDeviationFilter,
                        BiasDeviationAvgPeriod = BiasDeviationAvgPeriod,
                        UseDynamicPositionManagement = UseDynamicPositionManagement,
                        CloseProfitOnBiasFlip = CloseProfitOnBiasFlip,
                        SendTelegramOnly = SendTelegramOnly,
                        RiskPercent = RiskPercent,
                        MaxPoints = MaxPoints,
                        DecayPeriod = DecayPeriod
                    };

                    var strategy = new ClusterStrategy(this, Symbol, Bars, config, _httpClient, TelegramBotToken, TelegramChatId, BroadcastError);
                    _strategies.Add(strategy);
                    strategy.Start();
                }
                else
                {
                    Print("CSV detected. Running in Multi-Symbol Mode.");
                    ParseCsvAndCreateStrategies();
                }
            }
            catch (Exception ex)
            {
                BroadcastError($"CRITICAL STARTUP ERROR: {ex.Message}");
                Stop();
            }
        }

        protected override void OnStop()
        {
            foreach (var strategy in _strategies)
            {
                strategy.Stop();
            }
        }

        protected override void OnError(Error error)
        {
            BroadcastError($"TRADING ERROR [{error.Code}]: {error.ToString}");
        }

        public void BroadcastError(string message)
        {
            Print(message);

            if (!string.IsNullOrWhiteSpace(TelegramBotToken) && !string.IsNullOrWhiteSpace(TelegramChatId))
            {
                string formattedMsg = $"⚠️ <b>ERROR @ {DateTime.UtcNow:HH:mm:ss} UTC</b>\n\n{message}";
                _ = SendTelegramRawAsync(TelegramBotToken, TelegramChatId, formattedMsg);
            }
        }

        private async Task SendTelegramRawAsync(string token, string chatId, string message)
        {
            try
            {
                string url = $"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatId}&text={Uri.EscapeDataString(message)}&parse_mode=HTML";
                await _httpClient.GetAsync(url);
            }
            catch (Exception ex)
            {
                Print("FAILED TO SEND TELEGRAM ERROR: " + ex.Message);
            }
        }

        private void ParseCsvAndCreateStrategies()
        {
            var normalizedCsv = SymbolsCsv.Replace("\n", ",").Replace("\r", ",");
            
            var tokens = normalizedCsv.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                      .Select(t => t.Trim())
                                      .Where(t => !string.IsNullOrEmpty(t))
                                      .ToArray();

            int paramsPerSymbol = 10;

            if (tokens.Length % paramsPerSymbol != 0)
            {
                string err = $"CSV Token count ({tokens.Length}) is not a multiple of {paramsPerSymbol}. Check format.";
                BroadcastError(err);
            }

            for (int i = 0; i < tokens.Length; i += paramsPerSymbol)
            {
                if (i + paramsPerSymbol > tokens.Length) break;

                string symName = tokens[i];

                try
                {
                    Symbol symbol = Symbols.GetSymbol(symName);
                    if (symbol == null)
                    {
                        BroadcastError($"Symbol '{symName}' not found in cTrader.");
                        continue;
                    }

                    Bars bars = MarketData.GetBars(TimeFrame, symName);

                    var config = new StrategyConfig
                    {
                        SymbolName = symName,
                        EntrySigThreshold = double.Parse(tokens[i + 1], CultureInfo.InvariantCulture),
                        SlSigThreshold = double.Parse(tokens[i + 2], CultureInfo.InvariantCulture),
                        SmaBiasPeriod = int.Parse(tokens[i + 3], CultureInfo.InvariantCulture),
                        HmaBiasPeriod = int.Parse(tokens[i + 4], CultureInfo.InvariantCulture),
                        HmaClusterPeriod = int.Parse(tokens[i + 5], CultureInfo.InvariantCulture),
                        UseBiasDeviationFilter = bool.Parse(tokens[i + 6]),
                        BiasDeviationAvgPeriod = int.Parse(tokens[i + 7], CultureInfo.InvariantCulture),
                        UseDynamicPositionManagement = bool.Parse(tokens[i + 8]),
                        SendTelegramOnly = bool.Parse(tokens[i + 9]),
                        
                        // Default values for parameters not in CSV yet
                        CloseProfitOnBiasFlip = CloseProfitOnBiasFlip, 
                        RiskPercent = RiskPercent,
                        MaxPoints = MaxPoints,
                        DecayPeriod = DecayPeriod
                    };

                    var strategy = new ClusterStrategy(this, symbol, bars, config, _httpClient, TelegramBotToken, TelegramChatId, BroadcastError);
                    _strategies.Add(strategy);
                    strategy.Start();

                    Print("Initialized Strategy for {0}", symName);
                }
                catch (Exception ex)
                {
                    BroadcastError($"Config Error for '{symName}': {ex.Message}");
                }
            }
        }
    }

    public class StrategyConfig
    {
        public string SymbolName { get; set; }
        public double EntrySigThreshold { get; set; }
        public double SlSigThreshold { get; set; }
        public int SmaBiasPeriod { get; set; }
        public int HmaBiasPeriod { get; set; }
        public int HmaClusterPeriod { get; set; }
        public bool UseBiasDeviationFilter { get; set; }
        public int BiasDeviationAvgPeriod { get; set; }
        public bool UseDynamicPositionManagement { get; set; }
        public bool CloseProfitOnBiasFlip { get; set; } 
        public bool SendTelegramOnly { get; set; }
        public double RiskPercent { get; set; }
        public int MaxPoints { get; set; }
        public int DecayPeriod { get; set; }
    }

    public class ClusterStrategy
    {
        #region Types & Fields

        private enum PointType { Peak, Trough }
        private enum Bias { Long, Short, Neutral }

        private struct ExtremumPoint
        {
            public double Price;
            public int Index;
            public PointType Type;
        }

        public struct ClusterLevel
        {
            public double Price;
            public double Significance;
        }

        private readonly Robot _robot;
        private readonly Symbol _symbol;
        private readonly Bars _bars;
        private readonly StrategyConfig _config;
        private readonly HttpClient _httpClient;
        private readonly string _botToken;
        private readonly string _chatId;
        private readonly Action<string> _errorCallback;

        private SimpleMovingAverage _smaBias;
        private HullMovingAverage _hmaBias;
        private HullMovingAverage _hmaCluster;

        private readonly Queue<double> _deviationQueue = new Queue<double>();
        private double _runningDeviationSum;
        
        private bool _deviationConditionMetInCurrentCycle;
        private bool _isTradingAllowedBasedOnPrevCycle;

        private readonly List<ExtremumPoint> _extremaPoints = new();
        private readonly List<double> _amplitudes = new();
        
        private double _trendExtremum;
        private int _trendExtremumIndex;
        private double _lastExtremumPrice;
        private bool? _isUpTrend;
        private double _currentDynamicRange;

        private const string Label = "HmaClusterBot";

        #endregion

        public ClusterStrategy(
            Robot robot, 
            Symbol symbol, 
            Bars bars, 
            StrategyConfig config, 
            HttpClient httpClient, 
            string token, 
            string chatId,
            Action<string> errorCallback)
        {
            _robot = robot;
            _symbol = symbol;
            _bars = bars;
            _config = config;
            _httpClient = httpClient;
            _botToken = token;
            _chatId = chatId;
            _errorCallback = errorCallback;
        }

        public void Start()
        {
            int requiredBars = Math.Max(_config.SmaBiasPeriod, _config.HmaBiasPeriod);
            requiredBars = Math.Max(requiredBars, _config.BiasDeviationAvgPeriod) + 10; 

            while (_bars.Count < requiredBars)
            {
                int loaded = _bars.LoadMoreHistory();
                if (loaded == 0) 
                {
                    _errorCallback?.Invoke($"Not enough history for {_config.SymbolName}. Loaded: {_bars.Count}, Req: {requiredBars}");
                    return;
                }
            }

            _smaBias = _robot.Indicators.SimpleMovingAverage(_bars.ClosePrices, _config.SmaBiasPeriod);
            _hmaBias = _robot.Indicators.HullMovingAverage(_bars.ClosePrices, _config.HmaBiasPeriod);
            _hmaCluster = _robot.Indicators.HullMovingAverage(_bars.ClosePrices, _config.HmaClusterPeriod);

            _currentDynamicRange = 5.0 * _symbol.PipSize;
            _deviationConditionMetInCurrentCycle = false;
            _isTradingAllowedBasedOnPrevCycle = false;

            int startIndex = Math.Max(_config.SmaBiasPeriod, _config.HmaBiasPeriod);
            startIndex = Math.Max(startIndex, _config.BiasDeviationAvgPeriod);
            
            for (int i = startIndex; i < _bars.Count; i++)
            {
                UpdateFilterState(i);
                UpdateClusterData(i); 
            }

            _bars.BarOpened += OnBarOpened;
        }

        public void Stop()
        {
            _bars.BarOpened -= OnBarOpened;
        }

        private void OnBarOpened(BarOpenedEventArgs obj)
        {
            try
            {
                int index = _bars.Count - 2;
                if (index < _config.BiasDeviationAvgPeriod) return;

                UpdateFilterState(index);
                UpdateClusterData(index);
                
                var clusters = CalculateClusters(index);

                // 1. Dynamic SL/TP Management
                if (!_config.SendTelegramOnly && _config.UseDynamicPositionManagement && clusters.Count >= 2)
                {
                    ManagePositions(clusters);
                }
                
                var currentBias = GetCurrentBias(index);

                // 2. Check for Profit Close on Bias Flip
                if (!_config.SendTelegramOnly && _config.CloseProfitOnBiasFlip)
                {
                    CloseReversedPositions(currentBias);
                }

                // 3. New Entry Logic
                ManageOrders(currentBias, index, clusters);
            }
            catch (Exception ex)
            {
                _errorCallback?.Invoke($"Runtime Error ({_config.SymbolName}): {ex.Message}\n{ex.StackTrace}");
            }
        }

        private void CloseReversedPositions(Bias currentBias)
        {
            if (currentBias == Bias.Neutral) return;

            foreach (var pos in _robot.Positions)
            {
                if (pos.SymbolName != _config.SymbolName || pos.Label != Label) continue;
                if (pos.NetProfit <= 0) continue; 

                bool close = false;

                if (currentBias == Bias.Short && pos.TradeType == TradeType.Buy)
                    close = true;
                else if (currentBias == Bias.Long && pos.TradeType == TradeType.Sell)
                    close = true;

                if (close)
                {
                    var result = _robot.ClosePosition(pos);
                    if (result.IsSuccessful)
                    {
                        string msg = $"🔒 <b>CLOSE PROFIT</b> (Bias Flip) @ <b>{_config.SymbolName}</b>\n" +
                                     $"Profit: {pos.NetProfit:F2}";
                         _ = SendTelegramMessageAsync(msg);
                    }
                }
            }
        }

        private void UpdateFilterState(int index)
        {
            double currHma = _hmaBias.Result[index];
            double currSma = _smaBias.Result[index];
            double prevHma = _hmaBias.Result[index - 1];
            double prevSma = _smaBias.Result[index - 1];

            double currentBiasDeviation = Math.Abs(currHma - currSma);
            
            _deviationQueue.Enqueue(currentBiasDeviation);
            _runningDeviationSum += currentBiasDeviation;

            if (_deviationQueue.Count > _config.BiasDeviationAvgPeriod)
            {
                double removed = _deviationQueue.Dequeue();
                _runningDeviationSum -= removed;
            }

            double averageDeviation = (_deviationQueue.Count > 0) 
                ? _runningDeviationSum / _deviationQueue.Count 
                : 0.0;

            bool currHmaAbove = currHma > currSma;
            bool prevHmaAbove = prevHma > prevSma;

            if (currHmaAbove != prevHmaAbove)
            {
                _isTradingAllowedBasedOnPrevCycle = _deviationConditionMetInCurrentCycle;
                _deviationConditionMetInCurrentCycle = false;
            }

            if (currentBiasDeviation > averageDeviation)
            {
                _deviationConditionMetInCurrentCycle = true;
            }
        }

        private Bias GetCurrentBias(int index)
        {
            double hma = _hmaBias.Result[index];
            double sma = _smaBias.Result[index];
            double prevSma = _smaBias.Result[index - 1];

            if ((hma > sma) && (sma > prevSma)) return Bias.Long;
            if ((hma < sma) && (sma < prevSma)) return Bias.Short;

            return Bias.Neutral;
        }

        private void ManagePositions(List<ClusterLevel> clusters)
        {
            double pNow = _symbol.Bid; 

            foreach (var pos in _robot.Positions)
            {
                if (pos.Label != Label || pos.SymbolName != _config.SymbolName) continue;

                ClusterLevel? newSl = null;
                ClusterLevel? newTp = null;

                if (pos.TradeType == TradeType.Buy)
                {
                    double highestSlPrice = double.MinValue;
                    double highestTpPrice = double.MinValue;

                    foreach (var c in clusters)
                    {
                        if (c.Price < pNow && c.Significance < _config.SlSigThreshold && c.Price > highestSlPrice)
                        {
                            newSl = c;
                            highestSlPrice = c.Price;
                        }
                        if (c.Price > pNow && c.Significance >= _config.EntrySigThreshold && c.Price > highestTpPrice)
                        {
                            newTp = c;
                            highestTpPrice = c.Price;
                        }
                    }

                    double proposedSl = (newSl.HasValue) ? newSl.Value.Price : (pos.StopLoss ?? 0);
                    double proposedTp = (newTp.HasValue) ? newTp.Value.Price : (pos.TakeProfit ?? 0);

                    bool modifySl = pos.StopLoss.HasValue && (proposedSl > pos.StopLoss.Value + _symbol.TickSize);
                    if (!pos.StopLoss.HasValue && newSl.HasValue) modifySl = true;

                    bool modifyTp = newTp.HasValue && Math.Abs(proposedTp - (pos.TakeProfit ?? 0)) > _symbol.TickSize;

                    if (modifySl || modifyTp)
                    {
                        double finalSl = modifySl ? proposedSl : pos.StopLoss ?? 0;
                        double finalTp = modifyTp ? proposedTp : pos.TakeProfit ?? 0;

                        if (finalSl < _symbol.Bid && (finalTp == 0 || finalTp > _symbol.Bid))
                        {
                            _robot.ModifyPosition(pos, finalSl, finalTp, ProtectionType.Absolute);
                        }
                    }
                }
                else // Sell
                {
                    double lowestSlPrice = double.MaxValue;
                    double lowestTpPrice = double.MaxValue;

                    foreach (var c in clusters)
                    {
                        if (c.Price > pNow && c.Significance < _config.SlSigThreshold && c.Price < lowestSlPrice)
                        {
                            newSl = c;
                            lowestSlPrice = c.Price;
                        }
                        if (c.Price < pNow && c.Significance >= _config.EntrySigThreshold && c.Price < lowestTpPrice)
                        {
                            newTp = c;
                            lowestTpPrice = c.Price;
                        }
                    }

                    double proposedSl = (newSl.HasValue) ? newSl.Value.Price : (pos.StopLoss ?? 0);
                    double proposedTp = (newTp.HasValue) ? newTp.Value.Price : (pos.TakeProfit ?? 0);

                    bool modifySl = pos.StopLoss.HasValue && (proposedSl < pos.StopLoss.Value - _symbol.TickSize);
                    if (!pos.StopLoss.HasValue && newSl.HasValue) modifySl = true;

                    bool modifyTp = newTp.HasValue && Math.Abs(proposedTp - (pos.TakeProfit ?? 0)) > _symbol.TickSize;

                    if (modifySl || modifyTp)
                    {
                        double finalSl = modifySl ? proposedSl : pos.StopLoss ?? 0;
                        double finalTp = modifyTp ? proposedTp : pos.TakeProfit ?? 0;

                        if (finalSl > _symbol.Ask && (finalTp == 0 || finalTp < _symbol.Ask))
                        {
                            _robot.ModifyPosition(pos, finalSl, finalTp, ProtectionType.Absolute);
                        }
                    }
                }
            }
        }

        private void ManageOrders(Bias bias, int index, List<ClusterLevel> clusters)
        {
            CleanupOrders(bias);

            if (_config.UseBiasDeviationFilter && !_isTradingAllowedBasedOnPrevCycle) 
                return;

            if (bias == Bias.Neutral) return;

            if (!_config.SendTelegramOnly)
            {
                bool hasLong = _robot.Positions.Any(p => p.SymbolName == _config.SymbolName && p.Label == Label && p.TradeType == TradeType.Buy);
                bool hasShort = _robot.Positions.Any(p => p.SymbolName == _config.SymbolName && p.Label == Label && p.TradeType == TradeType.Sell);

                if ((bias == Bias.Long && hasLong) || (bias == Bias.Short && hasShort))
                    return;
            }

            if (clusters.Count < 2) return;

            double pNow = _bars.ClosePrices[index];

            if (bias == Bias.Short)
                ProcessShortSetup(clusters, pNow);
            else if (bias == Bias.Long)
                ProcessLongSetup(clusters, pNow);
        }

        private void CleanupOrders(Bias currentBias)
        {
            if (_config.SendTelegramOnly) return;

            foreach (var order in _robot.PendingOrders)
            {
                if (order.Label != Label || order.SymbolName != _config.SymbolName) continue;

                if (currentBias == Bias.Long && order.TradeType == TradeType.Sell)
                    _robot.CancelPendingOrder(order);
                else if (currentBias == Bias.Short && order.TradeType == TradeType.Buy)
                    _robot.CancelPendingOrder(order);
                else if (currentBias == Bias.Neutral)
                    _robot.CancelPendingOrder(order);
            }
        }

        private void ProcessShortSetup(List<ClusterLevel> clusters, double pNow)
        {
            ClusterLevel? entry = null;
            ClusterLevel? sl = null;
            ClusterLevel? tp = null;

            double highestEntryPrice = double.MinValue;
            double lowestSlPrice = double.MaxValue;
            double lowestTpPrice = double.MaxValue;

            foreach (var c in clusters)
            {
                if (c.Price > pNow)
                {
                    if ((c.Significance >= _config.EntrySigThreshold) && (c.Price > highestEntryPrice))
                    {
                        entry = c;
                        highestEntryPrice = c.Price;
                    }
                    if ((c.Significance < _config.SlSigThreshold) && (c.Price < lowestSlPrice))
                    {
                        sl = c;
                        lowestSlPrice = c.Price;
                    }
                }
            }

            if (entry == null || sl == null) return;

            foreach (var c in clusters)
            {
                if ((c.Price < entry.Value.Price) && (c.Significance >= _config.EntrySigThreshold))
                {
                    if (c.Price < lowestTpPrice)
                    {
                        tp = c;
                        lowestTpPrice = c.Price;
                    }
                }
            }

            if (tp != null && (sl.Value.Price > entry.Value.Price))
            {
                double risk = sl.Value.Price - entry.Value.Price;
                double reward = entry.Value.Price - tp.Value.Price;

                if (risk <= reward)
                    UpdateOrPlaceLimitOrder(TradeType.Sell, entry.Value.Price, sl.Value.Price, tp.Value.Price);
            }
        }

        private void ProcessLongSetup(List<ClusterLevel> clusters, double pNow)
        {
            ClusterLevel? entry = null;
            ClusterLevel? sl = null;
            ClusterLevel? tp = null;

            double lowestEntryPrice = double.MaxValue;
            double highestSlPrice = double.MinValue;
            double highestTpPrice = double.MinValue;

            foreach (var c in clusters)
            {
                if (c.Price < pNow)
                {
                    if ((c.Significance >= _config.EntrySigThreshold) && (c.Price < lowestEntryPrice))
                    {
                        entry = c;
                        lowestEntryPrice = c.Price;
                    }
                    if ((c.Significance < _config.SlSigThreshold) && (c.Price > highestSlPrice))
                    {
                        sl = c;
                        highestSlPrice = c.Price;
                    }
                }
            }

            if (entry == null || sl == null) return;

            foreach (var c in clusters)
            {
                if ((c.Price > entry.Value.Price) && (c.Significance >= _config.EntrySigThreshold))
                {
                    if (c.Price > highestTpPrice)
                    {
                        tp = c;
                        highestTpPrice = c.Price;
                    }
                }
            }

            if (tp != null && (sl.Value.Price < entry.Value.Price))
            {
                double risk = entry.Value.Price - sl.Value.Price;
                double reward = tp.Value.Price - entry.Value.Price;

                if (risk <= reward)
                    UpdateOrPlaceLimitOrder(TradeType.Buy, entry.Value.Price, sl.Value.Price, tp.Value.Price);
            }
        }

        private void UpdateOrPlaceLimitOrder(TradeType type, double entry, double sl, double tp)
        {
            double slDistPips = Math.Abs(entry - sl) / _symbol.PipSize;
            if (slDistPips <= 0) return;

            double riskAmount = _robot.Account.Balance * (_config.RiskPercent / 100.0);
            double volume = _symbol.VolumeForFixedRisk(riskAmount, slDistPips);
            
            volume = _symbol.NormalizeVolumeInUnits(volume, RoundingMode.Down);
            if (volume < _symbol.VolumeInUnitsMin) return;

            double lots = _symbol.VolumeInUnitsToQuantity(volume);

            if (_config.SendTelegramOnly)
            {
                string directionStr = type == TradeType.Buy ? "BUY" : "SELL";
                string directionIcon = type == TradeType.Buy ? "📈" : "📉";
                string msg = $"{directionIcon} <b>{directionStr}</b> Signal @ <b>{_config.SymbolName}</b>\n\n" +
                                $"<b>Entry:</b> {entry}\n" +
                                $"<b>SL:</b> {sl}\n" +
                                $"<b>TP:</b> {tp}\n" +
                                $"<b>Vol:</b> {lots:F2} Lots";
                
                _ = SendTelegramMessageAsync(msg);
                return;
            }

            var existingOrder = _robot.PendingOrders.FirstOrDefault(o => o.SymbolName == _config.SymbolName && o.Label == Label && o.TradeType == type);

            if (existingOrder != null)
            {
                bool volumeChanged = Math.Abs(existingOrder.VolumeInUnits - volume) > _symbol.VolumeInUnitsStep;
                bool entryChanged = Math.Abs(existingOrder.TargetPrice - entry) > _symbol.TickSize;
                bool slChanged = Math.Abs((existingOrder.StopLoss ?? 0) - sl) > _symbol.TickSize;
                bool tpChanged = Math.Abs((existingOrder.TakeProfit ?? 0) - tp) > _symbol.TickSize;

                if (volumeChanged || entryChanged || slChanged || tpChanged)
                {
                    _robot.ModifyPendingOrder(existingOrder, entry, sl, tp, ProtectionType.Absolute, null, volume);
                }
            }
            else
            {
                _robot.Print("[SIGNAL] {0} {1} | Entry: {2} | SL: {3} | TP: {4} | Vol: {5:F2} Lots",
                    (type == TradeType.Buy ? "BUY" : "SELL"), _config.SymbolName, entry, sl, tp, lots);

                _robot.PlaceLimitOrder(type, _config.SymbolName, volume, entry, Label, sl, tp, ProtectionType.Absolute);
            }
        }

        private async Task SendTelegramMessageAsync(string message)
        {
            if (_robot.IsBacktesting) return;
            if (string.IsNullOrWhiteSpace(_botToken) || string.IsNullOrWhiteSpace(_chatId)) return;

            try
            {
                string url = $"https://api.telegram.org/bot{_botToken}/sendMessage?chat_id={_chatId}&text={Uri.EscapeDataString(message)}&parse_mode=HTML";
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                
                if (!response.IsSuccessStatusCode)
                {
                    _errorCallback?.Invoke($"Telegram Error: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                _errorCallback?.Invoke($"Telegram Exception: {ex.Message}");
            }
        }

        private void UpdateClusterData(int index)
        {
            double currentHma = _hmaCluster.Result[index];
            double prevHma = _hmaCluster.Result[index - 1];
            bool currentDirectionUp = (currentHma > prevHma);

            if (_isUpTrend == null)
            {
                _isUpTrend = currentDirectionUp;
                SetExtremum(index);
                _lastExtremumPrice = _trendExtremum;
                return;
            }

            if (currentDirectionUp != _isUpTrend)
            {
                double amp = Math.Abs(_trendExtremum - _lastExtremumPrice);
                if (amp > 0)
                {
                    _amplitudes.Add(amp);
                    if (_amplitudes.Count > 50) _amplitudes.RemoveAt(0);
                    
                    double sum = 0;
                    for (int i = 0; i < _amplitudes.Count; i++) sum += _amplitudes[i];
                    _currentDynamicRange = (sum / _amplitudes.Count) * 0.5;
                }
                _extremaPoints.Add(new ExtremumPoint { Price = _trendExtremum, Index = _trendExtremumIndex, Type = _isUpTrend.Value ? PointType.Peak : PointType.Trough });
                if (_extremaPoints.Count > _config.MaxPoints) _extremaPoints.RemoveAt(0);

                _lastExtremumPrice = _trendExtremum;
                _isUpTrend = currentDirectionUp;
                SetExtremum(index);
            }
            else
            {
                UpdateExtremum(index);
            }
        }

        private void SetExtremum(int index)
        {
            _trendExtremum = _isUpTrend.Value ? _bars.HighPrices[index] : _bars.LowPrices[index];
            _trendExtremumIndex = index;
        }

        private void UpdateExtremum(int index)
        {
            if (_isUpTrend.Value && (_bars.HighPrices[index] > _trendExtremum))
            {
                _trendExtremum = _bars.HighPrices[index];
                _trendExtremumIndex = index;
            }
            else if (!_isUpTrend.Value && (_bars.LowPrices[index] < _trendExtremum))
            {
                _trendExtremum = _bars.LowPrices[index];
                _trendExtremumIndex = index;
            }
        }

        private List<ClusterLevel> CalculateClusters(int currentIndex)
        {
            int count = _extremaPoints.Count;
            if (count < 2) return new List<ClusterLevel>();

            double currentPrice = _bars.ClosePrices[currentIndex];
            double range = _currentDynamicRange;

            // Score-First / Global Density Approach (Matches Indicator)
            var candidates = _extremaPoints
                .Select(p => {
                    double weightedScore = _extremaPoints
                        .Where(other => Math.Abs(other.Price - p.Price) <= range)
                        .Sum(other => GetWeight(other, currentIndex, currentPrice));

                    return new { Price = p.Price, Score = weightedScore };
                })
                .OrderByDescending(z => z.Score)
                .ToList();

            var topZones = new List<ClusterLevel>();
            foreach (var zone in candidates)
            {
                // Filter Overlap
                if (!topZones.Any(z => Math.Abs(z.Price - zone.Price) < range))
                {
                    // Normalize Score relative to total Weight of all points (Matches Indicator Normalization)
                    double totalWeightSum = _extremaPoints.Sum(p => GetWeight(p, currentIndex, currentPrice));
                    double sigPercent = (totalWeightSum > 0) ? (zone.Score / totalWeightSum) * 100.0 : 0;
                    
                    topZones.Add(new ClusterLevel { Price = zone.Price, Significance = sigPercent });
                }
            }

            return topZones;
        }

        private double GetWeight(ExtremumPoint point, int currentIndex, double currentPrice)
        {
            double weight = Math.Max(0.0, 1.0 - ((double)(currentIndex - point.Index) / _config.DecayPeriod));
            if ((point.Type == PointType.Peak) && (point.Price < currentPrice)) weight *= 2.0;
            else if ((point.Type == PointType.Trough) && (point.Price > currentPrice)) weight *= 2.0;
            return weight;
        }
    }
}