Karpenkoチャネル戦略
Karpenkoチャネル戦略は2つの移動平均を使用して動的な価格チャネルを構築します。基準線は終値の平均であり、上限と下限は高値-安値の平均レンジを黄金比1.618でスケールしたものから導出されます。チャネルは現在のバーを包むまで拡張します。
ロングへのシグナルは、以前は基準線より上にあった上限が下を抜けたときに現れます。ショートシグナルは、上限が下に留まった後に基準線を上抜けしたときに発生します。レジームが変わると、反対方向の既存ポジションがクローズされます。
完了したローソク足のみが処理されます。固定のストップロスとテイクプロフィットレベルが各トレードを保護します。
詳細
- エントリー条件:
- ロング: 前の上限が基準線より上にあり、現在の値がそれ以下または等しい場合。
- ショート: 前の上限が基準線より下にあり、現在の値がそれ以上または等しい場合。
- エグジット条件:
- 前の上限が基準線より下にあった場合、ロングをクローズ。
- 前の上限が基準線より上にあった場合、ショートをクローズ。
- ストップ: 価格単位での固定ストップロスとテイクプロフィット距離。
- デフォルト値:
Base MA= 144History= 500Stop Loss= 1000Take Profit= 2000Candle Type= 4 hour
- フィルター:
- カテゴリ: トレンドフォロー
- 方向: 両方
- インジケーター: Custom
- ストップ: はい
- 複雑さ: 中級
- 時間軸: 中期
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Karpenko Channel strategy.
/// Generates signals based on dynamic channel and SMA baseline crossover.
/// Long when price is below channel baseline, short when above.
/// </summary>
public class KarpenkoChannelStrategy : Strategy
{
private readonly StrategyParam<int> _basicMa;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevClose;
private decimal _prevMa;
private bool _initialized;
private int _cooldownRemaining;
/// <summary>
/// Period for base moving average.
/// </summary>
public int BasicMa { get => _basicMa.Value; set => _basicMa.Value = value; }
/// <summary>
/// Number of completed candles to wait after a position change.
/// </summary>
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
/// <summary>
/// Candle type used by the strategy.
/// </summary>
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public KarpenkoChannelStrategy()
{
_basicMa = Param(nameof(BasicMa), 20)
.SetGreaterThanZero()
.SetDisplay("Base MA", "Length of base moving average", "Parameters");
_cooldownBars = Param(nameof(CooldownBars), 8)
.SetDisplay("Cooldown Bars", "Completed candles to wait after a signal", "Signal");
_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 OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = BasicMa };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevClose = 0m;
_prevMa = 0m;
_initialized = false;
_cooldownRemaining = 0;
}
private void ProcessCandle(ICandleMessage candle, decimal maValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_initialized)
{
_prevClose = candle.ClosePrice;
_prevMa = maValue;
_initialized = true;
return;
}
// Cross above MA -> buy signal
var crossUp = _prevClose <= _prevMa && candle.ClosePrice > maValue;
// Cross below MA -> sell signal
var crossDown = _prevClose >= _prevMa && candle.ClosePrice < maValue;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
if (crossUp && _cooldownRemaining == 0 && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_cooldownRemaining = CooldownBars;
}
else if (crossDown && _cooldownRemaining == 0 && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
_cooldownRemaining = CooldownBars;
}
_prevClose = candle.ClosePrice;
_prevMa = maValue;
}
}
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
class karpenko_channel_strategy(Strategy):
def __init__(self):
super(karpenko_channel_strategy, self).__init__()
self._basic_ma = self.Param("BasicMa", 20) \
.SetDisplay("Base MA", "Length of base moving average", "Parameters")
self._cooldown_bars = self.Param("CooldownBars", 8) \
.SetDisplay("Cooldown Bars", "Completed candles to wait after a signal", "Signal")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_close = 0.0
self._prev_ma = 0.0
self._initialized = False
self._cooldown_remaining = 0
@property
def basic_ma(self):
return self._basic_ma.Value
@property
def cooldown_bars(self):
return self._cooldown_bars.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(karpenko_channel_strategy, self).OnReseted()
self._prev_close = 0.0
self._prev_ma = 0.0
self._initialized = False
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(karpenko_channel_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = self.basic_ma
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawOwnTrades(area)
def process_candle(self, candle, ma_value):
if candle.State != CandleStates.Finished:
return
ma_value = float(ma_value)
close = float(candle.ClosePrice)
if not self._initialized:
self._prev_close = close
self._prev_ma = ma_value
self._initialized = True
return
cross_up = self._prev_close <= self._prev_ma and close > ma_value
cross_down = self._prev_close >= self._prev_ma and close < ma_value
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
if cross_up and self._cooldown_remaining == 0 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._cooldown_remaining = self.cooldown_bars
elif cross_down and self._cooldown_remaining == 0 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._cooldown_remaining = self.cooldown_bars
self._prev_close = close
self._prev_ma = ma_value
def CreateClone(self):
return karpenko_channel_strategy()