From c5c146d1ac36f17fa3c7be078675f0cd5b290041 Mon Sep 17 00:00:00 2001 From: Mikhail Date: Mon, 15 Sep 2025 08:51:16 +0300 Subject: [PATCH] Add Balance of Power Histogram strategy --- .../CS/BalanceOfPowerHistogramStrategy.cs | 95 +++++++++++++++++++ API/2332_Balance_Of_Power_Histogram/README.md | 22 +++++ .../README_cn.md | 22 +++++ .../README_ru.md | 22 +++++ 4 files changed, 161 insertions(+) create mode 100644 API/2332_Balance_Of_Power_Histogram/CS/BalanceOfPowerHistogramStrategy.cs create mode 100644 API/2332_Balance_Of_Power_Histogram/README.md create mode 100644 API/2332_Balance_Of_Power_Histogram/README_cn.md create mode 100644 API/2332_Balance_Of_Power_Histogram/README_ru.md diff --git a/API/2332_Balance_Of_Power_Histogram/CS/BalanceOfPowerHistogramStrategy.cs b/API/2332_Balance_Of_Power_Histogram/CS/BalanceOfPowerHistogramStrategy.cs new file mode 100644 index 000000000..614f7f13b --- /dev/null +++ b/API/2332_Balance_Of_Power_Histogram/CS/BalanceOfPowerHistogramStrategy.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; + +using StockSharp.Algo.Strategies; +using StockSharp.BusinessEntities; +using StockSharp.Messages; + +namespace StockSharp.Samples.Strategies; + +/// +/// Balance of Power Histogram strategy that reacts on direction changes +/// of the Balance of Power indicator. +/// +public class BalanceOfPowerHistogramStrategy : Strategy +{ + private readonly StrategyParam _candleType; + + private decimal? _prev; + private decimal? _prevPrev; + + /// + /// Candle type for strategy calculation. + /// + public DataType CandleType + { + get => _candleType.Value; + set => _candleType.Value = value; + } + + /// + /// Initializes a new instance of the . + /// + public BalanceOfPowerHistogramStrategy() + { + _candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame()) + .SetDisplay("Candle Type", "Type of candles to use", "General"); + } + + /// + public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() + { + return [(Security, CandleType)]; + } + + /// + protected override void OnReseted() + { + base.OnReseted(); + + _prev = _prevPrev = null; + } + + /// + protected override void OnStarted(DateTimeOffset time) + { + base.OnStarted(time); + + var subscription = SubscribeCandles(CandleType); + subscription + .Bind(ProcessCandle) + .Start(); + + var area = CreateChartArea(); + if (area != null) + { + DrawCandles(area, subscription); + DrawOwnTrades(area); + } + } + + private void ProcessCandle(ICandleMessage candle) + { + if (candle.State != CandleStates.Finished) + return; + + if (candle.HighPrice == candle.LowPrice) + return; + + var bop = (candle.ClosePrice - candle.OpenPrice) / (candle.HighPrice - candle.LowPrice); + + if (_prev is decimal prev && _prevPrev is decimal prevPrev) + { + var turnedUp = prev < prevPrev && bop > prev; + var turnedDown = prev > prevPrev && bop < prev; + + if (turnedUp && Position <= 0) + BuyMarket(); + else if (turnedDown && Position >= 0) + SellMarket(); + } + + _prevPrev = _prev; + _prev = bop; + } +} diff --git a/API/2332_Balance_Of_Power_Histogram/README.md b/API/2332_Balance_Of_Power_Histogram/README.md new file mode 100644 index 000000000..e94aa5069 --- /dev/null +++ b/API/2332_Balance_Of_Power_Histogram/README.md @@ -0,0 +1,22 @@ +# Balance Of Power Histogram Strategy + +This strategy is an adaptation of the original MetaTrader expert from `MQL/16214`. It uses the **Balance of Power** (BOP) indicator to detect momentum changes in the market. + +## Logic + +1. The strategy calculates the Balance of Power for each finished candle: + + $$BOP = \frac{Close - Open}{High - Low}$$ +2. Three consecutive BOP values are compared. + - When the previous value is lower than the value before it and the current value is higher than the previous one, the BOP turns upward and the strategy enters a long position. + - When the previous value is higher than the value before it and the current value is lower than the previous one, the BOP turns downward and the strategy enters a short position. +3. Position is changed only after a completed candle to avoid false signals. + +## Parameters + +- **CandleType** – timeframe of candles used for calculations. The default is four-hour candles. + +## Notes + +This port focuses on the core behaviour of the original strategy and does not implement the advanced money-management options from the MQL version. + diff --git a/API/2332_Balance_Of_Power_Histogram/README_cn.md b/API/2332_Balance_Of_Power_Histogram/README_cn.md new file mode 100644 index 000000000..c34c7d25f --- /dev/null +++ b/API/2332_Balance_Of_Power_Histogram/README_cn.md @@ -0,0 +1,22 @@ +# 平衡力量直方图策略 + +该策略改编自 `MQL/16214` 中的 MetaTrader 专家顾问,利用 **平衡力量**(BOP)指标来识别市场动能的变化。 + +## 逻辑 + +1. 对每个完成的K线计算平衡力量: + + $$BOP = \frac{Close - Open}{High - Low}$$ +2. 比较连续的三个 BOP 值。 + - 如果前一个值低于更早的值,且当前值高于前一个值,说明 BOP 向上转折,策略做多。 + - 如果前一个值高于更早的值,且当前值低于前一个值,说明 BOP 向下转折,策略做空。 +3. 仅在K线收盘后才改变仓位,以避免假信号。 + +## 参数 + +- **CandleType** – 用于计算的K线周期,默认使用4小时K线。 + +## 说明 + +该移植版本聚焦于原策略的核心行为,并未实现 MQL 版本中的资金管理设置。 + diff --git a/API/2332_Balance_Of_Power_Histogram/README_ru.md b/API/2332_Balance_Of_Power_Histogram/README_ru.md new file mode 100644 index 000000000..352989f01 --- /dev/null +++ b/API/2332_Balance_Of_Power_Histogram/README_ru.md @@ -0,0 +1,22 @@ +# Стратегия "Гистограмма Баланса Сил" + +Стратегия представляет собой адаптацию оригинального эксперта из `MQL/16214`. Она использует индикатор **Balance of Power** (BOP) для определения изменений рыночного импульса. + +## Логика + +1. Для каждой завершённой свечи рассчитывается показатель баланса сил: + + $$BOP = \frac{Close - Open}{High - Low}$$ +2. Сравниваются три последовательных значения BOP. + - Если предыдущее значение ниже ещё более раннего, а текущее выше предыдущего, происходит разворот вверх и стратегия открывает длинную позицию. + - Если предыдущее значение выше ещё более раннего, а текущее ниже предыдущего, происходит разворот вниз и стратегия открывает короткую позицию. +3. Изменение позиции выполняется только после закрытия свечи во избежание ложных сигналов. + +## Параметры + +- **CandleType** – таймфрейм свечей для расчёта. По умолчанию используется четырёхчасовой таймфрейм. + +## Примечание + +Данный порт уделяет внимание основной логике оригинальной стратегии и не реализует расширенные функции управления капиталом из версии MQL. +