GitHub で見る

固定マージン資金管理戦略

この戦略は、StockSharpの高レベルAPIを使用してMetaTraderの「Money Fixed Margin」サンプルを再現します。ポートフォリオの固定割合をリスクにさらしながらポジションサイズを決定し、pipsで表されたストップロス距離を絶対価格オフセットに変換する方法を示しています。この戦略はロングポジションのみを取引し、予測エントリーシグナルではなく資金管理ロジックのデモンストレーションに焦点を当てています。

詳細

  • エントリー条件:
    • ロング: Check Intervalで指定された完成したローソク足カウントごとに成行買いを実行します(デフォルトは980本ごとのバー)。注文はリスク計算の参照として、トリガーとなったローソク足の終値を使用します。
  • ロング/ショート: ロングのみ。
  • エグジット条件:
    • 保護的なストップロスがStop Loss (pips)パラメーターから導出された距離でStartProtectionを通じて自動的に付加されます。
    • 利益目標は使用しません。ポジションはストップロスまたは手動介入によってのみ決済されます。
  • ストップ: ストップロスのみ。
  • デフォルト値:
    • Stop Loss (pips) = 25
    • Risk Percent = 10
    • Check Interval = 980
    • Candle Type = 1分足時間軸
  • フィルター:
    • カテゴリ: リスク管理
    • 方向: ロング
    • インジケーター: なし
    • ストップ: はい(ストップロス)
    • 複雑さ: 基本
    • 時間軸: イントラデイ(Candle Typeで設定可能)
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: いいえ
    • リスクレベル: 中(Risk Percentでスケール)

ポジションサイジングロジック

  1. 戦略はSecurity.PriceStepSecurity.Decimalsを読み取ってpipサイズを推定します。小数点以下3桁または5桁のペアは、MetaTraderのpip定義に合わせるため10倍の乗数を使用します。
  2. Stop Loss (pips)をpipサイズで乗算して、MQL5コードと同一の絶対価格距離(ExtStopLoss)を取得します。
  3. 現在のポートフォリオ価値(Portfolio.CurrentValueを優先し、次にPortfolio.BeginValue)にRisk Percent / 100を乗算して、1トレードあたりのリスクにさらす資本を決定します。
  4. 1ロットのリスクは、ストップロス距離、その距離内の価格ステップ数、および利用可能な場合はSecurity.StepPriceの積で計算されます。StepPriceが不明な場合は、価格距離自体がフォールバックとして使用されます。
  5. リスク額をロットあたりのリスクで割ることで目標ボリュームが得られます。結果はインストゥルメントのVolumeStepに正規化され、最小・最大ボリューム制限にクランプされ、透明性のためにログに記録されます。ストップロス距離がゼロの場合の比較値もログに記録され、保護的なストップがないトレードを資金管理者が拒否する理由を示します。

ワークフロー

  1. 開始時に戦略は設定されたローソク足シリーズをサブスクライブし、pipサイズを計算し、計算された絶対ストップロス距離でStartProtectionを有効にします。
  2. 各完成したローソク足が内部カウンターをインクリメントします。カウンターが選択したCheck Intervalに達すると、戦略はポジションサイズを評価し、診断情報を出力し、カウンターをリセットします。
  3. 計算されたボリュームが正の場合、成行買い注文が出されます。組み込みの保護がClose - ExtStopLossにストップロスを付加します。エラー(例:不十分なデータや価格ゼロのインストゥルメントによる)は注文送信を防ぎます。
  4. カウンターが別のインターバルを完了するまで追加のトレードは行われず、シグナル頻度よりも資金管理に焦点を当てています。

使用上の注意

  • ライブ口座に接続する際はRisk Percentを保守的な値に設定してください。デフォルトの10%リスクはMQLサンプルを反映していますが、実際のトレードには積極的すぎます。
  • インストゥルメントが意味のあるPriceStepStepPriceメタデータを提供することを確認してください。利用できない場合、戦略は引き続き動作しますが、リスクを生価格単位で解釈します。
  • 戦略はオリジナルのデモンストレーションに忠実であるため、意図的にショートトレードを避けています。双方向取引が望まれる場合はBuyMarket/SellMarketの呼び出しを適応させてください。
  • この資金管理モジュールを他のシグナルジェネレーターと組み合わせるには、戦略コードのCalculateFixedMarginVolumeヘルパーを再利用してください。
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;

using StockSharp.Algo;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Recreates the MetaTrader Money Fixed Margin sample using StockSharp.
/// It demonstrates fixed percentage risk sizing for long trades.
/// </summary>
public class MoneyFixedMarginStrategy : Strategy
{
	private readonly StrategyParam<decimal> _stopLossPips;
	private readonly StrategyParam<decimal> _riskPercent;
	private readonly StrategyParam<int> _checkInterval;
	private readonly StrategyParam<DataType> _candleType;

	private int _barCount;
	private decimal _pipSize;

	/// <summary>
	/// Stop-loss distance expressed in pips.
	/// </summary>
	public decimal StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

	/// <summary>
	/// Portfolio percentage risked on each trade.
	/// </summary>
	public decimal RiskPercent
	{
		get => _riskPercent.Value;
		set => _riskPercent.Value = value;
	}

	/// <summary>
	/// Number of finished candles between trade attempts.
	/// </summary>
	public int CheckInterval
	{
		get => _checkInterval.Value;
		set => _checkInterval.Value = value;
	}

	/// <summary>
	/// Candle series used to time entries.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of <see cref="MoneyFixedMarginStrategy"/>.
	/// </summary>
	public MoneyFixedMarginStrategy()
	{
		_stopLossPips = Param(nameof(StopLossPips), 25m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss (pips)", "Stop loss distance in pips", "Risk");

		_riskPercent = Param(nameof(RiskPercent), 10m)
			.SetGreaterThanZero()
			.SetDisplay("Risk Percent", "Percent of equity risked per trade", "Risk");

		_checkInterval = Param(nameof(CheckInterval), 150)
			.SetGreaterThanZero()
			.SetDisplay("Check Interval", "Completed candles between trades", "Execution");

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
			.SetDisplay("Candle Type", "Candle timeframe", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_barCount = 0;
		_pipSize = 0m;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var priceStep = Security?.PriceStep ?? 1m;
		var decimals = Security?.Decimals ?? 0;
		var adjust = decimals == 3 || decimals == 5 ? 10m : 1m;

		_pipSize = priceStep * adjust;
		if (_pipSize <= 0m)
			_pipSize = priceStep > 0m ? priceStep : 1m;

		// Attach a protective stop using the pip-based distance converted to price units.
		StartProtection(
			new Unit(StopLossPips * _pipSize, UnitTypes.Absolute),
			new Unit(StopLossPips * _pipSize * 2, UnitTypes.Absolute));

		// Subscribe to the candle stream that emulates the tick counter from the MQL example.
		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(ProcessCandle).Start();
	}

	private void ProcessCandle(ICandleMessage candle)
	{
		if (candle.State != CandleStates.Finished)
			return;

		// Count finished candles to mirror the tick counter from the original script.
		_barCount++;

		if (_barCount < CheckInterval)
			return;

		var entryPrice = candle.ClosePrice;

		if (entryPrice <= 0m)
		{
			LogWarning("Skip trade because entry price is not positive. Close={0}", entryPrice);
			return;
		}

		var riskAmount = CalculateRiskAmount();
		if (riskAmount <= 0m)
		{
			LogWarning("Skip trade because risk amount is not positive. Portfolio value={0}", riskAmount);
			return;
		}

		var stopDistance = StopLossPips * _pipSize;
		var stopPrice = entryPrice - stopDistance;

		var volumeWithoutStop = CalculateFixedMarginVolume(entryPrice, 0m, riskAmount);
		var volumeWithStop = CalculateFixedMarginVolume(entryPrice, stopPrice, riskAmount);

		this.LogInfo(
			"StopLoss=0 -> volume {0:0.####}; StopLoss={1:0.#####} -> volume {2:0.####}; Portfolio={3:0.##}",
			volumeWithoutStop,
			stopPrice,
			volumeWithStop,
			GetPortfolioValue());

		BuyMarket();

		// Reset the counter only after successfully sending an order.
		_barCount = 0;
	}

	private decimal CalculateRiskAmount()
	{
		var portfolioValue = GetPortfolioValue();
		return portfolioValue > 0m ? portfolioValue * RiskPercent / 100m : 0m;
	}

	private decimal GetPortfolioValue()
	{
		var current = Portfolio?.CurrentValue ?? 0m;
		if (current > 0m)
			return current;

		var begin = Portfolio?.BeginValue ?? 0m;
		return begin > 0m ? begin : current;
	}

	private decimal CalculateFixedMarginVolume(decimal entryPrice, decimal stopPrice, decimal riskAmount)
	{
		if (riskAmount <= 0m || entryPrice <= 0m || stopPrice <= 0m)
			return 0m;

		var stopDistance = entryPrice - stopPrice;
		if (stopDistance <= 0m)
			return 0m;

		var priceStep = Security?.PriceStep ?? 0m;
		if (priceStep <= 0m)
			priceStep = 1m;

		var stepPrice = 0m;
		if (stepPrice <= 0m)
			stepPrice = priceStep;

		var stepsCount = stopDistance / priceStep;
		if (stepsCount <= 0m)
			return 0m;

		var riskPerVolume = stepsCount * stepPrice;
		if (riskPerVolume <= 0m)
			return 0m;

		var rawVolume = riskAmount / riskPerVolume;
		return NormalizeVolume(rawVolume);
	}

	private decimal NormalizeVolume(decimal volume)
	{
		if (volume <= 0m)
			return 0m;

		if (Security?.VolumeStep is decimal step && step > 0m)
		{
			volume = Math.Ceiling(volume / step) * step;
		}

		return volume;
	}
}