跳到正文

个人记录

基于价格行为分析的XAUUSD量化策略

li_xufeng约 71 分钟
原文
文章信息与版本

文章信息

发布
2025年5月17日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 71 分钟

版本

  1. v1当前
c#
using System;
using System.Collections.Generic; // For List
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class NakedKVolumeStrategy : Robot
    {
        [Parameter("Instance Name", DefaultValue = "NKV_001")]
        public string InstanceName { get; set; }

        [Parameter("Volume MA Period", DefaultValue = 20, MinValue = 5)]
        public int VolumeMaPeriod { get; set; }

        [Parameter("Volume Multiplier (Confirmation)", DefaultValue = 1.5, MinValue = 1.0)]
        public double VolumeMultiplier { get; set; }

        [Parameter("ATR Period", DefaultValue = 14, MinValue = 5)]
        public int AtrPeriod { get; set; }

        // ZigZag Parameters (Embedded)
        [Parameter("ZigZag Depth", DefaultValue = 12, MinValue = 2)]
        public int ZigZagDepth { get; set; }

        [Parameter("ZigZag Deviation (Pips)", DefaultValue = 50, MinValue = 1)]
        public int ZigZagDeviationPips { get; set; }

        [Parameter("ZigZag Backstep", DefaultValue = 3, MinValue = 0)]
        public int ZigZagBackstep { get; set; }


        [Parameter("PinBar Shadow/Body Ratio Min", DefaultValue = 2.0, MinValue = 1.5)]
        public double PinBarShadowBodyRatio { get; set; }

        [Parameter("PinBar Opposite Shadow/Body Max Ratio", DefaultValue = 0.75, MinValue = 0.1)]
        public double PinBarOppositeShadowMaxRatio { get; set; }

        [Parameter("Fractal Quality Shadow/Body Min Ratio (for middle bar)", DefaultValue = 1.0, MinValue = 0.5)]
        public double FractalQualityShadowRatio { get; set; }

        [Parameter("Risk Per Trade (%)", DefaultValue = 1.0, MinValue = 0.1, MaxValue = 5.0)]
        public double RiskPerTradePercent { get; set; }

        [Parameter("Use Fixed Lot Size", DefaultValue = true)]
        public bool UseFixedLotSize { get; set; }

        [Parameter("Fixed Lot Size", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
        public double FixedLotAmount { get; set; }


        [Parameter("Risk Reward Ratio (TP)", DefaultValue = 2.0, MinValue = 0.5)]
        public double RiskRewardRatio { get; set; }

        [Parameter("Stop Loss Buffer (ATR Multiplier)", DefaultValue = 0.2, MinValue = 0.0)]
        public double StopLossBufferAtrMultiplier { get; set; }


        private MovingAverage _volumeMa;
        private AverageTrueRange _atr;
        private string _botLabel;

        // --- Embedded ZigZag State and Data ---
        private double _zigZagDeviationInPrice;
        private List<ZigZagPoint> _zigZagPivots = new List<ZigZagPoint>();

        private double _currentLegPotentialExtremePrice;
        private int _currentLegPotentialExtremeBarIndex;
        private PivotType _currentLegPotentialExtremeType; // To know if current extreme is high or low
        private int _currentZigZagTrend = 0; // 0: Undefined; 1: Up leg, looking for High; -1: Down leg, looking for Low


        protected override void OnStart()
        {
            _botLabel = $"{InstanceName}_{SymbolName}_{TimeFrame}";
            _volumeMa = Indicators.MovingAverage(Bars.TickVolumes, VolumeMaPeriod, MovingAverageType.Simple);
            _atr = Indicators.AverageTrueRange(AtrPeriod, MovingAverageType.Simple);

            _zigZagDeviationInPrice = ZigZagDeviationPips * Symbol.PipSize;
            InitializeZigZagState();

            if (Bars.Count > ZigZagDepth + ZigZagBackstep + 1) // Ensure enough bars for at least one full ZigZag cycle
            {
                LogInfo($"Starting historical ZigZag calculation for {Bars.Count - 1} bars.");
                for (int i = 0; i < Bars.Count - 1; i++)
                {
                    CalculateEmbeddedZigZag(i);
                }
                LogInfo($"Finished historical ZigZag. Found {_zigZagPivots.Count} pivots.");
            } else {
                LogInfo("Not enough historical bars for full initial ZigZag calculation.");
            }
        }

        private void InitializeZigZagState()
        {
            _zigZagPivots.Clear();
            _currentZigZagTrend = 0;
            _currentLegPotentialExtremePrice = 0;
            _currentLegPotentialExtremeBarIndex = -1;
        }


        protected override void OnBar()
        {
            if (Bars.Count < Math.Max(VolumeMaPeriod, AtrPeriod) + ZigZagDepth + 5 || Bars.Count < ZigZagDepth + ZigZagBackstep + 10)
            {
                return;
            }

            int lastClosedBarIdx = Bars.Count - 2;
            if (lastClosedBarIdx < 0) return;

            CalculateEmbeddedZigZag(lastClosedBarIdx);

            if (_zigZagPivots.Count < 1)
            {
                return;
            }

            if (IsTradeOpenForThisBot() || PendingOrders.Any(o => o.Label == _botLabel))
            {
                return;
            }

            ZigZagPoint lastPivot = _zigZagPivots.LastOrDefault();
            ZigZagPoint secondLastPivot = _zigZagPivots.Count >= 2 ? _zigZagPivots[_zigZagPivots.Count - 2] : null;

            double prevHighPivot = 0;
            double prevLowPivot = 0;

            if (lastPivot != null)
            {
                if (lastPivot.Type == PivotType.High)
                {
                    prevHighPivot = lastPivot.Price;
                    prevLowPivot = (secondLastPivot != null && secondLastPivot.Type == PivotType.Low) ? secondLastPivot.Price : GetFallbackLow(lastClosedBarIdx, lastPivot.BarIndex);
                }
                else
                {
                    prevLowPivot = lastPivot.Price;
                    prevHighPivot = (secondLastPivot != null && secondLastPivot.Type == PivotType.High) ? secondLastPivot.Price : GetFallbackHigh(lastClosedBarIdx, lastPivot.BarIndex);
                }
            }
            else
            {
                return;
            }

            SignalInfo signal = GetSignal(lastClosedBarIdx, Bars.Count - 3, prevHighPivot, prevLowPivot);

            if (!signal.TradeDirection.HasValue)
                return;

            double entryPrice = signal.TradeDirection.Value == TradeType.Buy ? Symbol.Ask : Symbol.Bid;
            double stopLossPrice = signal.StopLoss;

            if ((signal.TradeDirection.Value == TradeType.Buy && stopLossPrice >= entryPrice) ||
                (signal.TradeDirection.Value == TradeType.Sell && stopLossPrice <= entryPrice))
            {
                LogWarning($"Invalid SL price. Entry: {entryPrice}, SL: {stopLossPrice} for {signal.TradeDirection.Value}. SL must be below entry for BUY, above for SELL.");
                return;
            }

            double stopLossDistance = Math.Abs(entryPrice - stopLossPrice);
             if (stopLossDistance < Symbol.PipSize * 0.1)
            {
                 LogWarning($"Stop loss distance too small: {stopLossDistance}");
                 return;
            }

            double takeProfitPrice = 0;
            if (signal.TradeDirection.Value == TradeType.Buy)
                takeProfitPrice = entryPrice + stopLossDistance * RiskRewardRatio;
            else
                takeProfitPrice = entryPrice - stopLossDistance * RiskRewardRatio;

            double positionSize = CalculatePositionSize(stopLossDistance);
            if (positionSize <= 0)
            {
                return;
            }

            LogInfo($"Signal: {signal.SignalName} | Direction: {signal.TradeDirection.Value} | Entry ~ {entryPrice} | SL: {stopLossPrice} | TP: {takeProfitPrice} | Size: {positionSize}");
            TradeResult result = ExecuteMarketOrder(signal.TradeDirection.Value, SymbolName, positionSize, _botLabel, stopLossPrice, takeProfitPrice, signal.SignalName);

            if (result.IsSuccessful)
            {
                LogInfo($"Order placed successfully for {signal.SignalName}. Position ID: {result.Position?.Id}");
            }
            else
            {
                LogError($"Failed to place order for {signal.SignalName}: {result.Error}");
            }
        }

        private double GetFallbackLow(int currentIndex, int lastPivotBarIndex)
        {
            double low = double.MaxValue;
            int startSearchIndex = Math.Max(0, lastPivotBarIndex > 0 ? lastPivotBarIndex : currentIndex - (ZigZagDepth * 2));
            for(int i = startSearchIndex; i <= currentIndex; i++)
            {
                if (i < 0 || i >= Bars.LowPrices.Count) continue;
                if (Bars.LowPrices[i] < low) low = Bars.LowPrices[i];
            }
            return low == double.MaxValue ? (Bars.LowPrices.Count > currentIndex && currentIndex >=0 ? Bars.LowPrices[currentIndex] : 0) : low;
        }
        private double GetFallbackHigh(int currentIndex, int lastPivotBarIndex)
        {
            double high = double.MinValue;
            int startSearchIndex = Math.Max(0, lastPivotBarIndex > 0 ? lastPivotBarIndex : currentIndex - (ZigZagDepth * 2));
            for(int i = startSearchIndex; i <= currentIndex; i++)
            {
                 if (i < 0 || i >= Bars.HighPrices.Count) continue;
                if (Bars.HighPrices[i] > high) high = Bars.HighPrices[i];
            }
            return high == double.MinValue ? (Bars.HighPrices.Count > currentIndex && currentIndex >=0 ? Bars.HighPrices[currentIndex] : 0) : high;
        }

        // --- Embedded ZigZag Calculation Logic ---
        private void CalculateEmbeddedZigZag(int index)
        {
            if (index < 0) return;

            if (_zigZagPivots.Count == 0) // Initializing ZigZag
            {
                if (index < ZigZagDepth - 1) return;

                double initialHigh = double.MinValue;
                int initialHighIdx = -1;
                double initialLow = double.MaxValue;
                int initialLowIdx = -1;
                int startIndexForInitialScan = Math.Max(0, index - ZigZagDepth + 1);

                for (int i = startIndexForInitialScan; i <= index; i++)
                {
                    if (Bars.HighPrices[i] > initialHigh) { initialHigh = Bars.HighPrices[i]; initialHighIdx = i; }
                    if (Bars.LowPrices[i] < initialLow) { initialLow = Bars.LowPrices[i]; initialLowIdx = i; }
                }

                if (initialHighIdx == -1 || initialLowIdx == -1) return;

                double firstBarOpenForTrend = Bars.OpenPrices[Math.Max(0, initialLowIdx - ZigZagDepth)];
                if (Math.Abs(initialHigh - firstBarOpenForTrend) > Math.Abs(firstBarOpenForTrend - initialLow) && initialHighIdx >= initialLowIdx)
                {
                    AddZigZagPivot(initialLowIdx, initialLow, PivotType.Low, index);
                    _currentZigZagTrend = 1;
                    _currentLegPotentialExtremePrice = initialLow;
                    _currentLegPotentialExtremeBarIndex = initialLowIdx;
                    _currentLegPotentialExtremeType = PivotType.Low;
                }
                else
                {
                    AddZigZagPivot(initialHighIdx, initialHigh, PivotType.High, index);
                    _currentZigZagTrend = -1;
                    _currentLegPotentialExtremePrice = initialHigh;
                    _currentLegPotentialExtremeBarIndex = initialHighIdx;
                    _currentLegPotentialExtremeType = PivotType.High;
                }
                return;
            }

            ZigZagPoint lastConfirmedPivot = _zigZagPivots.Last();

            if (_currentZigZagTrend == 1) // Looking for High
            {
                if (Bars.HighPrices[index] > _currentLegPotentialExtremePrice)
                {
                    _currentLegPotentialExtremePrice = Bars.HighPrices[index];
                    _currentLegPotentialExtremeBarIndex = index;
                    _currentLegPotentialExtremeType = PivotType.High; // Current extreme is a high
                }
                // Check for reversal from the current leg's highest point
                if (_currentLegPotentialExtremeBarIndex != -1 && _currentLegPotentialExtremeType == PivotType.High &&
                    _currentLegPotentialExtremePrice - Bars.LowPrices[index] >= _zigZagDeviationInPrice &&
                    index - _currentLegPotentialExtremeBarIndex >= ZigZagDepth -1 ) // Depth from potential high to current bar
                {
                    bool backstepConfirmed = true;
                    if (index >= _currentLegPotentialExtremeBarIndex + ZigZagBackstep)
                    {
                        for (int k = 1; k <= ZigZagBackstep; k++)
                        {
                            int checkIdx = _currentLegPotentialExtremeBarIndex + k;
                            if (checkIdx >= Bars.Count) { backstepConfirmed = false; break; }
                            if (Bars.HighPrices[checkIdx] > _currentLegPotentialExtremePrice)
                            {
                                backstepConfirmed = false;
                                // New higher high during backstep, update potential extreme
                                _currentLegPotentialExtremePrice = Bars.HighPrices[checkIdx];
                                _currentLegPotentialExtremeBarIndex = checkIdx;
                                // _currentLegPotentialExtremeType remains PivotType.High
                                break;
                            }
                        }
                        if (backstepConfirmed)
                        {
                            if (_currentLegPotentialExtremePrice > lastConfirmedPivot.Price) // New high must be > last low
                            {
                                AddZigZagPivot(_currentLegPotentialExtremeBarIndex, _currentLegPotentialExtremePrice, PivotType.High, index);
                                _currentZigZagTrend = -1; // Switch to looking for Low
                                if (_zigZagPivots.Any()) {
                                    _currentLegPotentialExtremePrice = _zigZagPivots.Last().Price;
                                    _currentLegPotentialExtremeBarIndex = _zigZagPivots.Last().BarIndex;
                                    _currentLegPotentialExtremeType = PivotType.High;
                                } else InitializeZigZagState();
                            }
                        }
                    }
                }
            }
            else if (_currentZigZagTrend == -1) // Looking for Low
            {
                if (Bars.LowPrices[index] < _currentLegPotentialExtremePrice)
                {
                    _currentLegPotentialExtremePrice = Bars.LowPrices[index];
                    _currentLegPotentialExtremeBarIndex = index;
                    _currentLegPotentialExtremeType = PivotType.Low; // Current extreme is a low
                }

                if (_currentLegPotentialExtremeBarIndex != -1 && _currentLegPotentialExtremeType == PivotType.Low &&
                    Bars.HighPrices[index] - _currentLegPotentialExtremePrice >= _zigZagDeviationInPrice &&
                    index - _currentLegPotentialExtremeBarIndex >= ZigZagDepth -1)
                {
                    bool backstepConfirmed = true;
                    if (index >= _currentLegPotentialExtremeBarIndex + ZigZagBackstep)
                    {
                        for (int k = 1; k <= ZigZagBackstep; k++)
                        {
                            int checkIdx = _currentLegPotentialExtremeBarIndex + k;
                            if (checkIdx >= Bars.Count) { backstepConfirmed = false; break; }
                            if (Bars.LowPrices[checkIdx] < _currentLegPotentialExtremePrice)
                            {
                                backstepConfirmed = false;
                                _currentLegPotentialExtremePrice = Bars.LowPrices[checkIdx];
                                _currentLegPotentialExtremeBarIndex = checkIdx;
                                // _currentLegPotentialExtremeType remains PivotType.Low
                                break;
                            }
                        }
                        if (backstepConfirmed)
                        {
                            if (_currentLegPotentialExtremePrice < lastConfirmedPivot.Price) // New low must be < last high
                            {
                                AddZigZagPivot(_currentLegPotentialExtremeBarIndex, _currentLegPotentialExtremePrice, PivotType.Low, index);
                                _currentZigZagTrend = 1; // Switch to looking for High
                                 if (_zigZagPivots.Any()) {
                                    _currentLegPotentialExtremePrice = _zigZagPivots.Last().Price;
                                    _currentLegPotentialExtremeBarIndex = _zigZagPivots.Last().BarIndex;
                                    _currentLegPotentialExtremeType = PivotType.Low;
                                 } else InitializeZigZagState();
                            }
                        }
                    }
                }
            }
        }


        private void AddZigZagPivot(int barIndex, double price, PivotType type, int confirmationBarIndex)
        {
            if (barIndex < 0) return; // Invalid bar index

            ZigZagPoint lastPivot = _zigZagPivots.LastOrDefault();

            if (lastPivot != null)
            {
                if (lastPivot.Type == type) // Trying to add same type as last
                {
                    // If new pivot is "better" (higher high, lower low), or same price at earlier bar, replace last one
                    bool replace = false;
                    if ((type == PivotType.High && price > lastPivot.Price) || (type == PivotType.Low && price < lastPivot.Price))
                        replace = true;
                    else if (price == lastPivot.Price && barIndex < lastPivot.BarIndex)
                        replace = true;

                    if (replace)
                    {
                        // LogInfo($"ZigZag: Replacing last {lastPivot.Type} pivot ({lastPivot.Price} @{lastPivot.BarIndex}) with better/earlier one ({price} @{barIndex})");
                        _zigZagPivots.RemoveAt(_zigZagPivots.Count - 1);
                    } else {
                        // LogInfo($"ZigZag: Ignoring new {type} pivot ({price} @{barIndex}) as it's not better than or same as last ({lastPivot.Price} @{lastPivot.BarIndex})");
                        return;
                    }
                } else { // Adding opposite type, check deviation
                    if ((type == PivotType.High && price - lastPivot.Price < _zigZagDeviationInPrice) ||
                        (type == PivotType.Low && lastPivot.Price - price < _zigZagDeviationInPrice))
                    {
                        // LogInfo($"ZigZag: Ignoring new {type} pivot ({price} @{barIndex}) due to insufficient deviation from last opposite pivot ({lastPivot.Price} @{lastPivot.BarIndex})");
                        return;
                    }
                }
            }

            // Remove any pivots that occurred at or after this new pivot's bar index
            // This helps correct if a later bar confirms an earlier, more significant pivot
            _zigZagPivots.RemoveAll(p => p.BarIndex >= barIndex);


            var newPivot = new ZigZagPoint { BarIndex = barIndex, Price = price, Type = type, ConfirmedAtIndex = confirmationBarIndex };
            _zigZagPivots.Add(newPivot);
            // LogInfo($"ZigZag: Added {type} Pivot at Bar {barIndex}, Price {price} (Confirmed at {confirmationBarIndex}) | Total Pivots: {_zigZagPivots.Count}");
        }


        // --- GetSignal Method ---
        private SignalInfo GetSignal(int barIdx, int prevBarIdx, double recentHighPivot, double recentLowPivot)
        {
            var signalInfo = new SignalInfo { TradeDirection = null, StopLoss = 0, SignalName = "NoSignal" };

            if (barIdx < 1 || prevBarIdx < 0 || _atr.Result.Count == 0) return signalInfo;

            double atrValue = _atr.Result.Last(1);
            if (double.IsNaN(atrValue) || atrValue <= Symbol.PipSize * 0.01) return signalInfo; // Miniscule ATR

            double slBuffer = atrValue * StopLossBufferAtrMultiplier;

            bool nearSupport = (recentLowPivot > 0) && (Math.Abs(Bars.LowPrices[barIdx] - recentLowPivot) < atrValue * 0.75 || Math.Abs(Bars.ClosePrices[barIdx] - recentLowPivot) < atrValue * 0.75);
            bool nearResistance = (recentHighPivot > 0) && (Math.Abs(Bars.HighPrices[barIdx] - recentHighPivot) < atrValue * 0.75 || Math.Abs(Bars.ClosePrices[barIdx] - recentHighPivot) < atrValue * 0.75);

            // 1. Engulfing
            if (IsBullishEngulfing(barIdx, prevBarIdx) && IsVolumeConfirmed(barIdx) && nearSupport)
            {
                signalInfo.TradeDirection = TradeType.Buy;
                signalInfo.StopLoss = Bars.LowPrices[barIdx] - slBuffer;
                signalInfo.SignalName = "BullishEngulfing";
                return signalInfo;
            }
            if (IsBearishEngulfing(barIdx, prevBarIdx) && IsVolumeConfirmed(barIdx) && nearResistance)
            {
                signalInfo.TradeDirection = TradeType.Sell;
                signalInfo.StopLoss = Bars.HighPrices[barIdx] + slBuffer;
                signalInfo.SignalName = "BearishEngulfing";
                return signalInfo;
            }

            // 2. Pin Bar
            if (IsBullishPinBar(barIdx) && IsVolumeConfirmed(barIdx) && nearSupport)
            {
                signalInfo.TradeDirection = TradeType.Buy;
                signalInfo.StopLoss = Bars.LowPrices[barIdx] - slBuffer;
                signalInfo.SignalName = "BullishPinBar";
                return signalInfo;
            }
            if (IsBearishPinBar(barIdx) && IsVolumeConfirmed(barIdx) && nearResistance)
            {
                signalInfo.TradeDirection = TradeType.Sell;
                signalInfo.StopLoss = Bars.HighPrices[barIdx] + slBuffer;
                signalInfo.SignalName = "BearishPinBar";
                return signalInfo;
            }

            // 3. Inside Bar Breakout
            int motherBarIdx = prevBarIdx - 1;
            if (motherBarIdx >= 0)
            {
                if (IsInsideBar(prevBarIdx, motherBarIdx))
                {
                    if (Bars.ClosePrices[barIdx] > Bars.HighPrices[motherBarIdx] && IsVolumeConfirmed(barIdx, true) && nearSupport)
                    {
                        signalInfo.TradeDirection = TradeType.Buy;
                        signalInfo.StopLoss = Bars.LowPrices[motherBarIdx] - slBuffer;
                        signalInfo.SignalName = "BullishInsideBarBreakout";
                        return signalInfo;
                    }
                    if (Bars.ClosePrices[barIdx] < Bars.LowPrices[motherBarIdx] && IsVolumeConfirmed(barIdx, true) && nearResistance)
                    {
                        signalInfo.TradeDirection = TradeType.Sell;
                        signalInfo.StopLoss = Bars.HighPrices[motherBarIdx] + slBuffer;
                        signalInfo.SignalName = "BearishInsideBarBreakout";
                        return signalInfo;
                    }
                }
            }

            // 4. Quality Fractal Breakout
            int fractalMiddleIdx = barIdx - 2;
            int fractalLeftShoulderIdx = barIdx - 3;
            int fractalRightShoulderIdx = barIdx - 1;

            if (fractalLeftShoulderIdx >= 0 && fractalRightShoulderIdx < barIdx && fractalMiddleIdx >=0)
            {
                if (IsQualityBottomFractalStructure(fractalMiddleIdx, fractalLeftShoulderIdx, fractalRightShoulderIdx) &&
                    Bars.ClosePrices[barIdx] > Bars.HighPrices[fractalMiddleIdx] &&
                    IsVolumeConfirmed(barIdx, true) && nearSupport)
                {
                    signalInfo.TradeDirection = TradeType.Buy;
                    signalInfo.StopLoss = Bars.LowPrices[fractalMiddleIdx] - slBuffer;
                    signalInfo.SignalName = "BottomFractalBreakout";
                    return signalInfo;
                }
                if (IsQualityTopFractalStructure(fractalMiddleIdx, fractalLeftShoulderIdx, fractalRightShoulderIdx) &&
                    Bars.ClosePrices[barIdx] < Bars.LowPrices[fractalMiddleIdx] &&
                    IsVolumeConfirmed(barIdx, true) && nearResistance)
                {
                    signalInfo.TradeDirection = TradeType.Sell;
                    signalInfo.StopLoss = Bars.HighPrices[fractalMiddleIdx] + slBuffer;
                    signalInfo.SignalName = "TopFractalBreakout";
                    return signalInfo;
                }
            }
            return signalInfo;
        }


        // --- K-Line Pattern Helper Functions ---
        private bool IsBullishEngulfing(int currentIdx, int prevIdx)
        {
            if (prevIdx < 0 || currentIdx <= prevIdx || currentIdx >= Bars.Count || prevIdx >= Bars.Count) return false;
            bool prevBearish = Bars.ClosePrices[prevIdx] < Bars.OpenPrices[prevIdx];
            bool currentBullish = Bars.ClosePrices[currentIdx] > Bars.OpenPrices[currentIdx];
            if (!prevBearish || !currentBullish) return false;
            return Bars.OpenPrices[currentIdx] < Bars.ClosePrices[prevIdx] && Bars.ClosePrices[currentIdx] > Bars.OpenPrices[prevIdx];
        }

        private bool IsBearishEngulfing(int currentIdx, int prevIdx)
        {
            if (prevIdx < 0 || currentIdx <= prevIdx || currentIdx >= Bars.Count || prevIdx >= Bars.Count) return false;
            bool prevBullish = Bars.ClosePrices[prevIdx] > Bars.OpenPrices[prevIdx];
            bool currentBearish = Bars.ClosePrices[currentIdx] < Bars.OpenPrices[currentIdx];
            if (!prevBullish || !currentBearish) return false;
            return Bars.OpenPrices[currentIdx] > Bars.ClosePrices[prevIdx] && Bars.ClosePrices[currentIdx] < Bars.OpenPrices[prevIdx];
        }

         private bool IsBullishPinBar(int idx)
        {
            if (idx < 0 || idx >= Bars.Count) return false;
            double body = Math.Abs(Bars.OpenPrices[idx] - Bars.ClosePrices[idx]);
            if (body < Symbol.PipSize * 0.01) body = Symbol.PipSize * 0.01; // Ensure minimal body for ratio
            double lowerShadow = Math.Min(Bars.OpenPrices[idx], Bars.ClosePrices[idx]) - Bars.LowPrices[idx];
            double upperShadow = Bars.HighPrices[idx] - Math.Max(Bars.OpenPrices[idx], Bars.ClosePrices[idx]);
            bool isPin = lowerShadow >= body * PinBarShadowBodyRatio && upperShadow <= body * PinBarOppositeShadowMaxRatio;
            bool closesInUpperPortion = Bars.ClosePrices[idx] >= Bars.LowPrices[idx] + (Bars.HighPrices[idx] - Bars.LowPrices[idx]) * 0.66; // Closes in upper third
            return isPin && closesInUpperPortion;
        }

        private bool IsBearishPinBar(int idx)
        {
            if (idx < 0 || idx >= Bars.Count) return false;
            double body = Math.Abs(Bars.OpenPrices[idx] - Bars.ClosePrices[idx]);
            if (body < Symbol.PipSize * 0.01) body = Symbol.PipSize * 0.01;
            double upperShadow = Bars.HighPrices[idx] - Math.Max(Bars.OpenPrices[idx], Bars.ClosePrices[idx]);
            double lowerShadow = Math.Min(Bars.OpenPrices[idx], Bars.ClosePrices[idx]) - Bars.LowPrices[idx];
            bool isPin = upperShadow >= body * PinBarShadowBodyRatio && lowerShadow <= body * PinBarOppositeShadowMaxRatio;
            bool closesInLowerPortion = Bars.ClosePrices[idx] <= Bars.HighPrices[idx] - (Bars.HighPrices[idx] - Bars.LowPrices[idx]) * 0.66; // Closes in lower third
            return isPin && closesInLowerPortion;
        }

        private bool IsInsideBar(int insideBarIdx, int motherBarIdx)
        {
            if (motherBarIdx < 0 || insideBarIdx <= motherBarIdx || insideBarIdx >= Bars.Count || motherBarIdx >= Bars.Count) return false;
            return Bars.HighPrices[insideBarIdx] < Bars.HighPrices[motherBarIdx] &&
                   Bars.LowPrices[insideBarIdx] > Bars.LowPrices[motherBarIdx];
        }

        private bool IsQualityBottomFractalStructure(int middleIdx, int leftIdx, int rightIdx)
        {
            if (leftIdx < 0 || middleIdx <= leftIdx || rightIdx <= middleIdx ||
                rightIdx >= Bars.Count || middleIdx >= Bars.Count || leftIdx >= Bars.Count) return false;

            bool isBottomFractal = Bars.LowPrices[middleIdx] < Bars.LowPrices[leftIdx] &&
                                   Bars.LowPrices[middleIdx] < Bars.LowPrices[rightIdx];
            if (!isBottomFractal) return false;

            double body = Math.Abs(Bars.OpenPrices[middleIdx] - Bars.ClosePrices[middleIdx]);
            if (body < Symbol.PipSize * 0.01) body = Symbol.PipSize * 0.01;
            double lowerShadow = Math.Min(Bars.OpenPrices[middleIdx], Bars.ClosePrices[middleIdx]) - Bars.LowPrices[middleIdx];
            return lowerShadow >= body * FractalQualityShadowRatio;
        }

        private bool IsQualityTopFractalStructure(int middleIdx, int leftIdx, int rightIdx)
        {
            if (leftIdx < 0 || middleIdx <= leftIdx || rightIdx <= middleIdx ||
                rightIdx >= Bars.Count || middleIdx >= Bars.Count || leftIdx >= Bars.Count) return false;

            bool isTopFractal = Bars.HighPrices[middleIdx] > Bars.HighPrices[leftIdx] &&
                                Bars.HighPrices[middleIdx] > Bars.HighPrices[rightIdx];
            if (!isTopFractal) return false;

            double body = Math.Abs(Bars.OpenPrices[middleIdx] - Bars.ClosePrices[middleIdx]);
            if (body < Symbol.PipSize * 0.01) body = Symbol.PipSize * 0.01;
            double upperShadow = Bars.HighPrices[middleIdx] - Math.Max(Bars.OpenPrices[middleIdx], Bars.ClosePrices[middleIdx]);
            return upperShadow >= body * FractalQualityShadowRatio;
        }

        // --- Volume Confirmation ---
        private bool IsVolumeConfirmed(int idx, bool isBreakout = false)
        {
            if (idx < 0 || idx >= Bars.TickVolumes.Count || _volumeMa.Result.Count == 0) return false;

            double volMultiplier = isBreakout ? VolumeMultiplier * 1.5 : VolumeMultiplier;

            int offset = (Bars.Count - 1) - idx;
            if (offset < 0 || offset >= _volumeMa.Result.Count) return false;

            double maValue = _volumeMa.Result.Last(offset);
            if(double.IsNaN(maValue) || maValue <= 0) return false; // MA value must be positive

            return Bars.TickVolumes[idx] > maValue * volMultiplier;
        }


        // --- Risk Management ---
        private double CalculatePositionSize(double stopLossDistanceInPrice)
        {
            if (UseFixedLotSize)
            {
                double volumeInUnits = Symbol.QuantityToVolumeInUnits(FixedLotAmount);
                volumeInUnits = Symbol.NormalizeVolumeInUnits(volumeInUnits, RoundingMode.ToNearest);

                if (volumeInUnits < Symbol.VolumeInUnitsMin)
                {
                    LogWarning($"Fixed volume {FixedLotAmount} lots -> {volumeInUnits} units is less than min {Symbol.VolumeInUnitsMin}. Attempting to use min volume.");
                    volumeInUnits = Symbol.VolumeInUnitsMin;
                    if (volumeInUnits < Symbol.VolumeInUnitsMin && Symbol.VolumeInUnitsMin > 0) {
                        LogError($"Min volume {Symbol.VolumeInUnitsMin} is invalid or zero after attempting to set. Cannot trade.");
                        return 0;
                    } else if (Symbol.VolumeInUnitsMin == 0 && volumeInUnits == 0 && FixedLotAmount > 0) {
                        LogError($"Min volume is zero and calculated volume is zero for FixedLot {FixedLotAmount}. Cannot trade.");
                        return 0;
                    }
                }
                if (volumeInUnits > Symbol.VolumeInUnitsMax)
                {
                    LogWarning($"Fixed volume {FixedLotAmount} lots -> {volumeInUnits} units exceeds max {Symbol.VolumeInUnitsMax}. Using max volume.");
                    volumeInUnits = Symbol.VolumeInUnitsMax;
                }
                return volumeInUnits;
            }
            else // Dynamic risk-based sizing
            {
                if (stopLossDistanceInPrice <= Symbol.PipSize * 0.1)
                {
                    LogWarning("Stop loss distance is too small for dynamic sizing: " + stopLossDistanceInPrice);
                    return 0;
                }
                double riskAmount = Account.Balance * (RiskPerTradePercent / 100.0);
                double stopLossInPips = stopLossDistanceInPrice / Symbol.PipSize;

                if (stopLossInPips <= 0)
                {
                    LogWarning("Stop loss in pips is zero or negative for dynamic sizing.");
                    return 0;
                }
                double moneyRiskedPerLot = stopLossInPips * Symbol.PipValue;
                if (moneyRiskedPerLot <= 0)
                {
                    LogWarning("Money risked per lot is zero or negative for dynamic sizing: " + moneyRiskedPerLot);
                    return 0;
                }
                double lotsToTrade = riskAmount / moneyRiskedPerLot;
                double volumeInUnits = Symbol.QuantityToVolumeInUnits(lotsToTrade);
                volumeInUnits = Symbol.NormalizeVolumeInUnits(volumeInUnits, RoundingMode.Down);

                if (volumeInUnits < Symbol.VolumeInUnitsMin)
                {
                    LogWarning($"Calculated dynamic volume {volumeInUnits} units is less than min {Symbol.VolumeInUnitsMin}. Not trading.");
                    return 0;
                }
                if (volumeInUnits > Symbol.VolumeInUnitsMax)
                {
                    LogWarning($"Calculated dynamic volume {volumeInUnits} units exceeds max {Symbol.VolumeInUnitsMax}. Using max volume.");
                    volumeInUnits = Symbol.VolumeInUnitsMax;
                }
                return volumeInUnits;
            }
        }

        private bool IsTradeOpenForThisBot()
        {
            return Positions.Any(p => p.SymbolName == SymbolName && p.Label == _botLabel);
        }

        // --- Logging Helpers ---
        private void LogInfo(string message)
        {
            Print($"INFO | {_botLabel} | {Server.Time.ToShortTimeString()} | {message}");
        }
        private void LogWarning(string message)
        {
            Print($"WARN | {_botLabel} | {Server.Time.ToShortTimeString()} | {message}");
        }
        private void LogError(string message)
        {
            Print($"ERROR | {_botLabel} | {Server.Time.ToShortTimeString()} | {message}");
        }


        protected override void OnStop()
        {
            LogInfo("cBot stopped.");
        }

        private struct SignalInfo
        {
            public TradeType? TradeDirection;
            public double StopLoss;
            public string SignalName;
        }

        private enum PivotType { High, Low }
        private class ZigZagPoint
        {
            public int BarIndex { get; set; }
            public double Price { get; set; }
            public PivotType Type { get; set; }
            public int ConfirmedAtIndex { get; set; }
        }
    }
}

基于价格行为分析,通过zigzag来实现绘制形态,通过检测k线状态来进行入场出场。

原文