ホーム
/
戦略のサンプル
GitHub で見る
Above Below MA 戦略
Above Below MA 戦略は、MetaTraderのエキスパートアドバイザー Above Below MA (barabashkakvn's edition) を再現したものです。現在の価格が設定可能な移動平均線からどれだけ離れているかを監視し、価格が平均線の「逆側」に少なくとも定義された距離だけ位置し、かつ平均線自体が予想される方向にトレンドしている場合にのみ取引を許可します。ロジックはStockSharpの高レベルAPIに移植され、完成したローソク足のみで実行されます。
概要
市場レジーム : 移動平均線を頻繁に再テストしてからトレンドを再開する銘柄で最も効果を発揮します。
銘柄 : StockSharp接続でサポートされる任意の銘柄。元のスクリプトが距離をpipsで測定していたため、Forex通貨ペアが最も恩恵を受けます。
時間軸 : Candle Type パラメーターで調整可能(デフォルト: 1分足)。
ポジション方向 : ロングとショートの両方の取引をサポートしますが、任意の時点でネットポジションは1つのみ保持できます。
戦略ロジック
選択したローソク足シリーズで移動平均線を計算します。平均化手法(SMA、EMA、SMMA、WMA)、適用価格(close、open、high、low、median、typical、weighted)および前方シフトはMetaTraderの入力を再現します。
pipsで表された最小距離を、銘柄の PriceStep を使用して実際の価格オフセットに変換します。ブローカーが価格ステップを提供しない場合、距離フィルターは自動的にスキップされます。
完成した各ローソク足で:
ロング設定 :
ローソク足の始値と終値は、シフトされた移動平均線より少なくとも設定距離だけ下に位置しなければなりません。
移動平均線は前のローソク足と比較して上昇していなければなりません。
ショート設定 :
ローソク足の始値と終値は、シフトされた移動平均線より少なくとも設定距離だけ上に位置しなければなりません。
移動平均線は前のローソク足と比較して下降していなければなりません。
戦略はシグナル方向に新しい成行注文を送る前に、反対ポジションをクローズします。同時ロング/ショートのエクスポージャーは許可されません。
全ての取引決定は、形成中のバー内での繰り返しエントリーを避けるため、完成したローソク足で行われます。注文は設定されたボリュームで BuyMarket または SellMarket を通じて実行されます。
パラメーター
パラメーター
説明
MaPeriod
移動平均線の長さ。デフォルト 6。
MaShift
移動平均線を前方にシフトするローソク足の数。0は現在のバーを使用し、n は n バー前の値を使用します。デフォルト 0。
MaMethod
移動平均線の種類: Simple、Exponential、Smoothed、または Weighted。デフォルト Exponential。
AppliedPrice
価格ソース: close、open、high、low、median、typical、またはweighted。デフォルト Typical。
MinimumDistancePips
ローソク足の価格と移動平均線の間の必要距離(pips)。PriceStep を使用して変換されます。デフォルト 5。
CandleType
インジケーターの更新を駆動するローソク足の種類。デフォルト: 1分足。
TradeVolume
新規エントリーの注文ボリューム。デフォルト 1。
補足事項
ストップロスまたはテイクプロフィットのロジックは含まれていません。リスク管理はポートフォリオ設定または外部モジュールで実装する必要があります。
移動平均線のシフトバッファーは最小限に保たれ、指定されたシフトに必要な値のみを格納することで「コレクション不使用」のガイドラインに従います。
PriceStep が利用できない場合、最小距離フィルターを評価できないため、エントリーは移動平均線の条件のみに依存します。
チャートコンテナーが利用可能な場合、戦略はデフォルトのチャートエリアにローソク足シリーズ、移動平均線インジケーター、および取引を描画します。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Above/Below MA strategy. Trades when price crosses above or below a moving average.
/// </summary>
public class AboveBelowMaStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _maPeriod;
private decimal? _prevClose;
private decimal? _prevMa;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
public AboveBelowMaStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Timeframe", "General");
_maPeriod = Param(nameof(MaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Moving average period", "Indicators");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevClose = null;
_prevMa = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevClose = null;
_prevMa = null;
var sma = new SimpleMovingAverage { Length = MaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal maVal)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
if (!IsFormedAndOnlineAndAllowTrading())
{
_prevClose = close;
_prevMa = maVal;
return;
}
if (_prevClose == null || _prevMa == null)
{
_prevClose = close;
_prevMa = maVal;
return;
}
// Price crosses above MA → buy
if (_prevClose.Value <= _prevMa.Value && close > maVal && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Price crosses below MA → sell
else if (_prevClose.Value >= _prevMa.Value && close < maVal && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_prevClose = close;
_prevMa = maVal;
}
}
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 CandleStates
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
from datatype_extensions import *
class above_below_ma_strategy(Strategy):
"""
Above/Below MA strategy. Trades when price crosses above or below a moving average.
"""
def __init__(self):
super(above_below_ma_strategy, self).__init__()
self._candle_type = self.Param("CandleType", tf(5)) \
.SetDisplay("Candle Type", "Timeframe", "General")
self._ma_period = self.Param("MaPeriod", 20) \
.SetGreaterThanZero() \
.SetDisplay("MA Period", "Moving average period", "Indicators")
self._prev_close = None
self._prev_ma = None
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def MaPeriod(self):
return self._ma_period.Value
@MaPeriod.setter
def MaPeriod(self, value):
self._ma_period.Value = value
def OnReseted(self):
super(above_below_ma_strategy, self).OnReseted()
self._prev_close = None
self._prev_ma = None
def OnStarted2(self, time):
super(above_below_ma_strategy, self).OnStarted2(time)
self._prev_close = None
self._prev_ma = None
sma = SimpleMovingAverage()
sma.Length = self.MaPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(sma, self.ProcessCandle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawOwnTrades(area)
def ProcessCandle(self, candle, ma_val):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
if self._prev_close is None or self._prev_ma is None:
self._prev_close = close
self._prev_ma = ma_val
return
# Price crosses above MA -> buy
if self._prev_close <= self._prev_ma and close > ma_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Price crosses below MA -> sell
elif self._prev_close >= self._prev_ma and close < ma_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_close = close
self._prev_ma = ma_val
def CreateClone(self):
"""!! REQUIRED!! Creates a new instance of the strategy."""
return above_below_ma_strategy()