N Candles 戦略
N Candles 戦略は、設定可能な数の連続したローソク足が同じ方向を共有する場合に取引に入るMQLエキスパートアドバイザーを再現します。最新のN本の完成したローソク足がすべて強気の場合、戦略は成行の買い注文を送信します。すべて弱気の場合、成行の売り注文を送信します。出口ロジックは含まれていません。ポジションは外部から、または追加の戦略によって管理する必要があります。
概要
- 市場レジーム: 短いモメンタムの急騰を示す市場で最もよく機能します。
- インストゥルメント: 継続的な取引をサポートする任意のインストゥルメント(FX、先物、暗号資産)。
- 時間軸: 設定可能。デフォルトは1時間ローソク足。
- 注文タイプ: 保護ストップや目標なしの成行注文。
仕組み
- 完成したローソク足ごとに戦略は最後の
N本のローソク足を評価します。 - そのウィンドウ内のすべてのローソク足が強気の場合、設定されたボリュームで買い成行注文を出します。
- すべてのローソク足が弱気の場合、売り成行注文を出します。
- ドージローソク足(始値と終値が等しい)はカウントをリセットし、新しい連続が形成されるまで取引を抑制します。
- 戦略はオープンポジションを管理しません。繰り返しシグナルはネッティング口座で既存の方向に追加されます。
パラメーター
- Consecutive Candles: 注文を出す前に必要な同一ローソク足の数。
- Volume: 各シグナルで送信される成行注文のサイズ。
- Candle Type: 連続検出に使用するローソク足シリーズ(タイムフレームまたはカスタムローソク足タイプ)。
使用上の注意
- 戦略にはストップや出口がないため、手動管理、保護戦略、またはポートフォリオリスクコントロールと組み合わせてください。
- 高ボラティリティの市場では、より速い連続を捉えるためにローソク足数またはタイムフレームを減らすことを検討してください。
- 過度な連続シグナルは大きなポジションを蓄積する可能性があります。レバレッジと口座の制限を監視してください。
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>
/// Trades in the direction of consecutive candles of the same color.
/// </summary>
public class NCandlesStrategy : Strategy
{
private readonly StrategyParam<int> _consecutiveCandles;
private readonly StrategyParam<DataType> _candleType;
private int _currentDirection;
private int _streakLength;
/// <summary>
/// Number of identical candles that must appear in a row to trigger an order.
/// </summary>
public int ConsecutiveCandles
{
get => _consecutiveCandles.Value;
set => _consecutiveCandles.Value = value;
}
/// <summary>
/// The type of candles used for analysis.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of the strategy.
/// </summary>
public NCandlesStrategy()
{
_consecutiveCandles = Param(nameof(ConsecutiveCandles), 4)
.SetGreaterThanZero()
.SetDisplay("Consecutive Candles", "Number of identical candles required", "General")
.SetOptimize(2, 6, 1);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Candles to analyze", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_currentDirection = 0;
_streakLength = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(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;
var direction = 0;
if (candle.ClosePrice > candle.OpenPrice)
{
direction = 1;
}
else if (candle.ClosePrice < candle.OpenPrice)
{
direction = -1;
}
else
{
// Doji candle breaks the streak just like in the original expert.
_currentDirection = 0;
_streakLength = 0;
return;
}
if (direction == _currentDirection)
{
_streakLength = Math.Min(_streakLength + 1, ConsecutiveCandles);
}
else
{
_currentDirection = direction;
_streakLength = 1;
}
if (_streakLength < ConsecutiveCandles)
return;
if (direction > 0 && Position <= 0)
{
BuyMarket();
}
else if (direction < 0 && Position >= 0)
{
SellMarket();
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Strategies import Strategy
class n_candles_strategy(Strategy):
def __init__(self):
super(n_candles_strategy, self).__init__()
self._consecutive_candles = self.Param("ConsecutiveCandles", 4)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1)))
self._current_direction = 0
self._streak_length = 0
@property
def ConsecutiveCandles(self):
return self._consecutive_candles.Value
@ConsecutiveCandles.setter
def ConsecutiveCandles(self, value):
self._consecutive_candles.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(n_candles_strategy, self).OnStarted2(time)
self._current_direction = 0
self._streak_length = 0
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self.ProcessCandle).Start()
def ProcessCandle(self, candle):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
open_price = float(candle.OpenPrice)
direction = 0
if close > open_price:
direction = 1
elif close < open_price:
direction = -1
else:
self._current_direction = 0
self._streak_length = 0
return
consecutive = int(self.ConsecutiveCandles)
if direction == self._current_direction:
self._streak_length = min(self._streak_length + 1, consecutive)
else:
self._current_direction = direction
self._streak_length = 1
if self._streak_length < consecutive:
return
if direction > 0 and self.Position <= 0:
self.BuyMarket()
elif direction < 0 and self.Position >= 0:
self.SellMarket()
def OnReseted(self):
super(n_candles_strategy, self).OnReseted()
self._current_direction = 0
self._streak_length = 0
def CreateClone(self):
return n_candles_strategy()