GitHub で見る
条件付きポジションオープナー戦略
概要
条件付きポジション オープナー戦略は、元の MetaTrader スクリプト 「オープン ポジションがない場合は買いポジションをオープンする」 の動作を再現します。ロジックは意図的に単純になっています。手動スイッチでロングサイドまたはショートサイドが有効になっている場合、その方向にオープンエクスポージャーがない場合にのみ、ストラテジーは成行注文を送信します。これにより、重複したエントリが防止され、位置が選択した側に揃えられます。
StockSharp ポートは、フレームワークの高レベルのキャンドル サブスクリプションと組み込みの保護ヘルパーに依存することで、実装をブローカー中立に保ちます。ストップロスとテイクプロフィットの距離はピップ単位(価格ステップ)で提供されるため、あらゆる商品に適応できます。
戦略ロジック
- タイミング ハートビートとして機能するように、構成されたキャンドル シリーズをサブスクライブします。
- 完成したローソクごとに、現在のネットポジションを確認します。
- ロングスイッチが有効で、ポジションがフラットまたはショートの場合は、買い成行注文を送信します。
- ショートスイッチが有効で、ポジションがフラットまたはロングの場合は、売り成行注文を送信します。
- プロテクション注文は、ピップ距離を実際の価格オフセットに変換する
StartProtection を通じて自動的に管理されます。
StockSharp はネット ポジションを使用するため、両方を同時に有効にすると、まずロング トレードが開始され、約定後もまだ横ばいの場合はショート トレードが開始されます。これは、方向ごとに複数の注文を回避する MQL コードの意図を反映しています。
パラメーター
| 名前 |
デフォルト |
説明 |
Volume |
1 |
各市場エントリーの注文サイズ。 |
StopLossPips |
100 |
価格ステップで表されるストップロス距離。無効にするには、ゼロに設定します。 |
TakeProfitPips |
200 |
価格ステップで表される利食い距離。無効にするには、ゼロに設定します。 |
EnableBuy |
false |
true の場合、長時間露光が存在しない場合、戦略はロングポジションをオープンする可能性があります。 |
EnableSell |
false |
true の場合、ショートエクスポージャーが存在しない場合、戦略はショートポジションをオープンする可能性があります。 |
CandleType |
1 minute timeframe |
定期評価を推進するキャンドルシリーズ。 |
注意事項
- 距離は、商品の
PriceStep を使用して実際の価格増分に変換されます。取引所がそれを報告しない場合、生の pip 値が絶対オフセットとして使用されます。
StartProtection は、約定のたびにストップロス注文と利食い注文を自動的に付加するため、手動で注文を管理する必要はありません。
- この戦略は手動スタイルのトリガーに焦点を当てており、パラメーターによる任意実行のテンプレートとして意図されています。
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Simplified from "Conditional Position Opener" MetaTrader expert.
/// Uses Momentum indicator to conditionally open long or short positions.
/// Opens long when momentum is positive, short when negative.
/// </summary>
public class ConditionalPositionOpenerStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _momentumPeriod;
private Momentum _momentum;
private decimal? _prevMomentum;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int MomentumPeriod
{
get => _momentumPeriod.Value;
set => _momentumPeriod.Value = value;
}
public ConditionalPositionOpenerStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(60).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for signal generation", "General");
_momentumPeriod = Param(nameof(MomentumPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Momentum Period", "Momentum indicator period", "Indicators");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevMomentum = null;
_momentum = new Momentum { Length = MomentumPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_momentum, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal momentumValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_momentum.IsFormed)
{
_prevMomentum = momentumValue;
return;
}
if (_prevMomentum is null)
{
_prevMomentum = momentumValue;
return;
}
var volume = Volume;
if (volume <= 0)
volume = 1;
// Cross above 101 (positive momentum)
var crossUp = _prevMomentum.Value <= 101m && momentumValue > 101m;
// Cross below 99 (negative momentum)
var crossDown = _prevMomentum.Value >= 99m && momentumValue < 99m;
if (crossUp)
{
if (Position <= 0)
BuyMarket(Position < 0 ? Math.Abs(Position) + volume : volume);
}
else if (crossDown)
{
if (Position >= 0)
SellMarket(Position > 0 ? Math.Abs(Position) + volume : volume);
}
_prevMomentum = momentumValue;
}
/// <inheritdoc />
protected override void OnReseted()
{
_momentum = null;
_prevMomentum = null;
base.OnReseted();
}
}
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 Momentum
from StockSharp.Algo.Strategies import Strategy
class conditional_position_opener_strategy(Strategy):
def __init__(self):
super(conditional_position_opener_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(60)))
self._momentum_period = self.Param("MomentumPeriod", 20)
self._prev_momentum = None
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def MomentumPeriod(self):
return self._momentum_period.Value
@MomentumPeriod.setter
def MomentumPeriod(self, value):
self._momentum_period.Value = value
def OnReseted(self):
super(conditional_position_opener_strategy, self).OnReseted()
self._prev_momentum = None
def OnStarted2(self, time):
super(conditional_position_opener_strategy, self).OnStarted2(time)
self._prev_momentum = None
momentum = Momentum()
momentum.Length = self.MomentumPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(momentum, self._process_candle).Start()
def _process_candle(self, candle, momentum_value):
if candle.State != CandleStates.Finished:
return
mom_val = float(momentum_value)
if self._prev_momentum is None:
self._prev_momentum = mom_val
return
# Cross above 101 (positive momentum)
cross_up = self._prev_momentum <= 101.0 and mom_val > 101.0
# Cross below 99 (negative momentum)
cross_down = self._prev_momentum >= 99.0 and mom_val < 99.0
if cross_up:
if self.Position <= 0:
self.BuyMarket()
elif cross_down:
if self.Position >= 0:
self.SellMarket()
self._prev_momentum = mom_val
def CreateClone(self):
return conditional_position_opener_strategy()