Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;

using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Balance of Power Histogram strategy that reacts on direction changes
/// of the Balance of Power indicator.
/// </summary>
public class BalanceOfPowerHistogramStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;

private decimal? _prev;
private decimal? _prevPrev;

/// <summary>
/// Candle type for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}

/// <summary>
/// Initializes a new instance of the <see cref="BalanceOfPowerHistogramStrategy"/>.
/// </summary>
public BalanceOfPowerHistogramStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}

/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}

/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();

_prev = _prevPrev = null;
}

/// <inheritdoc />
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;
}
}
22 changes: 22 additions & 0 deletions API/2332_Balance_Of_Power_Histogram/README.md
Original file line number Diff line number Diff line change
@@ -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.

22 changes: 22 additions & 0 deletions API/2332_Balance_Of_Power_Histogram/README_cn.md
Original file line number Diff line number Diff line change
@@ -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 版本中的资金管理设置。

22 changes: 22 additions & 0 deletions API/2332_Balance_Of_Power_Histogram/README_ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Стратегия "Гистограмма Баланса Сил"

Стратегия представляет собой адаптацию оригинального эксперта из `MQL/16214`. Она использует индикатор **Balance of Power** (BOP) для определения изменений рыночного импульса.

## Логика

1. Для каждой завершённой свечи рассчитывается показатель баланса сил:

$$BOP = \frac{Close - Open}{High - Low}$$
2. Сравниваются три последовательных значения BOP.
- Если предыдущее значение ниже ещё более раннего, а текущее выше предыдущего, происходит разворот вверх и стратегия открывает длинную позицию.
- Если предыдущее значение выше ещё более раннего, а текущее ниже предыдущего, происходит разворот вниз и стратегия открывает короткую позицию.
3. Изменение позиции выполняется только после закрытия свечи во избежание ложных сигналов.

## Параметры

- **CandleType** – таймфрейм свечей для расчёта. По умолчанию используется четырёхчасовой таймфрейм.

## Примечание

Данный порт уделяет внимание основной логике оригинальной стратегии и не реализует расширенные функции управления капиталом из версии MQL.