熊牛力量策略
该策略是 MetaTrader 5 专家顾问 "Exp_Bear_Bulls_Power" 的转换版本,使用平滑后的熊牛力量指标来识别趋势反转。
工作原理
- 计算每根K线的中值价格:
(最高价 + 最低价) / 2。 - 使用长度为
FirstLength的移动平均线平滑中值价格。 - 计算中值价格与其移动平均值之间的差值。
- 使用长度为
SecondLength的移动平均线再次平滑该差值。 - 通过比较当前平滑值与先前值来确定趋势方向。
- 当方向发生变化时生成信号:
- 指标向上并高于零时开多。
- 指标向下并低于零时开空。
参数
- Candle Type – 处理的K线时间周期。
- First Length – 价格平滑的周期长度。
- Second Length – 信号平滑的周期长度。
该策略仅在完成的K线上运行,并使用市价单执行交易。
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Bear Bulls Power strategy.
/// Uses smoothed difference between median price and moving average.
/// Opens long when indicator turns upward above zero, short when turns downward below zero.
/// </summary>
public class BearBullsPowerStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _firstLength;
private readonly StrategyParam<int> _secondLength;
private SimpleMovingAverage _priceMa;
private SimpleMovingAverage _signalMa;
private decimal? _prevValue;
private int? _prevColor;
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Period for price smoothing.
/// </summary>
public int FirstLength
{
get => _firstLength.Value;
set => _firstLength.Value = value;
}
/// <summary>
/// Period for signal smoothing.
/// </summary>
public int SecondLength
{
get => _secondLength.Value;
set => _secondLength.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public BearBullsPowerStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Timeframe of processed candles", "General");
_firstLength = Param(nameof(FirstLength), 3)
.SetGreaterThanZero()
.SetDisplay("Price MA Length", "Length of the first smoothing", "Indicator")
.SetOptimize(5, 30, 1);
_secondLength = Param(nameof(SecondLength), 2)
.SetGreaterThanZero()
.SetDisplay("Signal MA Length", "Length of the second smoothing", "Indicator")
.SetOptimize(3, 20, 1);
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_priceMa = null;
_signalMa = null;
_prevValue = null;
_prevColor = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_priceMa = new SimpleMovingAverage { Length = FirstLength };
_signalMa = new SimpleMovingAverage { Length = SecondLength };
_prevValue = null;
_prevColor = null;
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;
var price = (candle.HighPrice + candle.LowPrice) / 2m;
var priceMa = _priceMa.Process(new DecimalIndicatorValue(_priceMa, price, candle.OpenTime) { IsFinal = true }).ToDecimal();
var diff = (candle.HighPrice + candle.LowPrice - 2m * priceMa) / 2m;
var signal = _signalMa.Process(new DecimalIndicatorValue(_signalMa, diff, candle.OpenTime) { IsFinal = true }).ToDecimal();
if (!_priceMa.IsFormed || !_signalMa.IsFormed || !IsFormedAndOnlineAndAllowTrading())
{
_prevColor = _prevValue is null ? null : _prevValue < signal ? 0 : _prevValue > signal ? 2 : 1;
_prevValue = signal;
return;
}
var color = signal > 0 ? 0 : signal < 0 ? 2 : 1;
var threshold = (Security?.PriceStep ?? 1m) * 10m;
if (_prevValue is decimal prevSignal)
{
if (prevSignal <= -threshold && signal > threshold && Position <= 0)
BuyMarket();
else if (prevSignal >= threshold && signal < -threshold && Position >= 0)
SellMarket();
}
_prevColor = color;
_prevValue = signal;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class bear_bulls_power_strategy(Strategy):
def __init__(self):
super(bear_bulls_power_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Timeframe of processed candles", "General")
self._first_length = self.Param("FirstLength", 3) \
.SetDisplay("Price MA Length", "Length of the first smoothing", "Indicator")
self._second_length = self.Param("SecondLength", 2) \
.SetDisplay("Signal MA Length", "Length of the second smoothing", "Indicator")
self._price_ma = None
self._signal_ma = None
self._prev_value = None
@property
def candle_type(self):
return self._candle_type.Value
@property
def first_length(self):
return self._first_length.Value
@property
def second_length(self):
return self._second_length.Value
def OnReseted(self):
super(bear_bulls_power_strategy, self).OnReseted()
self._price_ma = None
self._signal_ma = None
self._prev_value = None
def OnStarted2(self, time):
super(bear_bulls_power_strategy, self).OnStarted2(time)
self._price_ma = SimpleMovingAverage()
self._price_ma.Length = self.first_length
self._signal_ma = SimpleMovingAverage()
self._signal_ma.Length = self.second_length
self._prev_value = None
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def OnProcess(self, candle):
if candle.State != CandleStates.Finished:
return
price = (float(candle.HighPrice) + float(candle.LowPrice)) / 2.0
price_ma_val = float(process_float(self._price_ma, price, candle.OpenTime, True))
diff = (float(candle.HighPrice) + float(candle.LowPrice) - 2.0 * price_ma_val) / 2.0
signal = float(process_float(self._signal_ma, diff, candle.OpenTime, True))
if not self._price_ma.IsFormed or not self._signal_ma.IsFormed or not self.IsFormedAndOnlineAndAllowTrading():
self._prev_value = signal
return
sec = self.Security
threshold = (float(sec.PriceStep) if sec is not None and sec.PriceStep is not None else 1.0) * 10.0
if self._prev_value is not None:
if self._prev_value <= -threshold and signal > threshold and self.Position <= 0:
self.BuyMarket()
elif self._prev_value >= threshold and signal < -threshold and self.Position >= 0:
self.SellMarket()
self._prev_value = signal
def CreateClone(self):
return bear_bulls_power_strategy()