GitHub で見る
Cycle Market Order戦略
MetaTrader 4のエキスパートアドバイザー「CycleMarketOrder_V181」から変換されました。この戦略は価格ラダー内に固定数のスロットを整理し、ライブのbid/askが個別のスロットを通過するときに成行注文を開きます。各スロットは独自のボリューム、ブレイクイーブン閾値、トレーリングストップ値を持ち、グリッドはすでに必要な距離に達した利益を保護しながら段階的にポジションにスケールインできます。
トレードロジック
- pipサイズはインストゥルメントの価格ステップと小数精度から導出されます(5/3桁のシンボルは1 pip = 10ポイントにマッピングされます)。
MaxPrice、SpanPips、MaxCount パラメーターは各スロットが処理する価格範囲を事前計算するために使用されます。
- 元のエキスパートアドバイザーのティックベースの動作を模倣するためにレベル1マーケットデータが消費されます。各更新はキャッシュされた最良のbid/ask価格をリフレッシュします。
UseWeekendMode が有効な場合、戦略は設定された週末ウィンドウ外(WeekendHour からの土曜日、日曜日全体、WeekstartHour 前の月曜日)での取引を拒否します。
- ロングサイクル(
EntryDirection = 1)の場合、アルゴリズムは最低から最高の識別子でスロットをスキャンします。現在のask価格がスロットの startPrice と endPrice の間に入るたびに、OrderVolume ボリュームで成行買い注文が送信されます。ショートサイクル(EntryDirection = -1)はこのロジックを反映し、bid価格を使用します。
- スロット状態はペンディングのエントリー/エグジット注文、約定済みボリューム、平均エントリー価格を追跡します。ログはMT4の「マジック」識別子に合わせるために
MagicNumberBase + index を使用します。
- トレーリング管理は新しいエントリーを評価する前に各レベル1更新で実行されます。ロングスロットの利益が
BreakEvenPips + TrailingStopPips を超えると、ストップは Bid - TrailingStopPips にプッシュされます。ショートスロットは Ask + TrailingStopPips と反転したブレイクイーブン条件を使用します。市場価格が保存されたストップを交差すると、スロットは成行注文で決済されます。
- 成行注文のみが使用されるため、キャンセルするペンディング注文はありません。部分約定はスロットの残ボリュームを調整し、スロットがフラットになったときに戦略がトレーリングを継続するかスロットを再起動できるようにします。
パラメーター
| パラメーター |
説明 |
EntryDirection |
トレード方向:1 はラダーを買い、-1 は売り、0 はトレーリングをアクティブに保ちながら新規エントリーを無効にします。 |
MaxPrice |
スロット範囲を計算するために使用される上部アンカー価格。 |
MaxCount |
グリッド内のアクティブスロットの合計数。 |
SpanPips |
連続するスロット境界間のpips距離。 |
OrderVolume |
スロットが発動したときに送信されるボリューム。 |
BreakEvenPips |
トレーリングストップが起動される前に超える必要がある利益距離。 |
TrailingStopPips |
ブレイクイーブン達成後に適用されるトレーリング距離。 |
UseWeekendMode |
週末取引ブラックアウトウィンドウを有効化。 |
WeekendHour |
取引が停止される土曜日の時間(ターミナル時間)。 |
WeekstartHour |
取引が再開される月曜日の時間。 |
MagicNumberBase |
元のマジックナンバーに合わせるためのログメッセージで使用される識別子オフセット。 |
実装上の注意
- スロット管理はペンディングのエントリーおよびエグジット注文を追跡し、繰り返しの約定が重複ボリュームを登録しないようにします。
- 戦略は新しい約定がスロットのエクスポージャーを増加させるたびにトレーリングストップをリセットし、ストップが最新の平均エントリー価格を反映することを確保します。
- 週末保護はトレーリングとエントリーロジックの両方を単純にスキップします;ブラックアウトがアクティブな間、既存のポジションは変更されません。
- ロジックはローソク足クローズではなく生のbid/ask価格を比較するため、レベル1データが必要であり、MT4バージョンのティックごとの動作を正確に再現します。
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;
public class CycleMarketOrderStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private int _cooldown;
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }
public CycleMarketOrderStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
}
protected override void OnReseted()
{
base.OnReseted();
_fast = null; _slow = null;
_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fast = new ExponentialMovingAverage { Length = FastPeriod };
_slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.Bind(_fast, _slow, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished) return;
if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }
_prevFast = fastValue; _prevSlow = slowValue;
}
}
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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class cycle_market_order_strategy(Strategy):
def __init__(self):
super(cycle_market_order_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 14) \
.SetDisplay("Fast Period", "Fast MA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow MA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
def OnReseted(self):
super(cycle_market_order_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(cycle_market_order_strategy, self).OnStarted2(time)
self._fast = ExponentialMovingAverage()
self._fast.Length = self.fast_period
self._slow = ExponentialMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 100
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return cycle_market_order_strategy()