MA MACD ポジションアベレージング戦略
この戦略は、MetaTraderエキスパートアドバイザー**「MA MACD Position averaging」**の忠実な変換です。加重移動平均フィルターと MACD比率チェックを組み合わせ、設定可能な数のpips分だけ価格が不利な方向に動くたびにポジションサイズを増やすマーチンゲール式 アベレージングモジュールを追加します。すべてのリスクパラメーターはpips単位で設定され、StockSharpが提供する銘柄メタデータを 使用して内部的に価格オフセットに変換されます。
取引ロジック
- インジケーター準備
- 設定可能な移動平均(
MaPeriod、MaMethod、MaAppliedPrice)が完成した足でサンプリングされます。SignalBarとMaShiftパラメーターは、MetaTraderが指定した数の足だけ遡り、水平オフセットで移動平均をプロットする機能をエミュレートします。 - MACDインジケーター(
MacdFastPeriod、MacdSlowPeriod、MacdSignalPeriod、MacdAppliedPrice)が同じ足で処理されます。 戦略は、インジケーターAPIを直接呼び出すことなく履歴値にアクセスできるよう、MACDのメインラインとシグナルラインを小さな ローリングバッファに保存します。
- 設定可能な移動平均(
- エントリー条件
- ロング:両MACD線がゼロ以下で、比率
MACDmain / MACDsignalがMacdRatio以上で、足のクローズがサンプリングされた 移動平均より上にあり、価格と平均の距離が少なくともIndentPipspipsある。 - ショート:両MACD線がゼロ以上で、比率が
MacdRatioより上で、足のクローズが移動平均より下にあり、それらの距離が 少なくともIndentPipspipsある。 - 新規エントリーは戦略にポジションがないときのみ許可されます。アベレージングサイクルがすでに進行中の場合、シグナルロジックは スキップされ、アベレージングルールのみが適用されます。
- ロング:両MACD線がゼロ以下で、比率
- アベレージングモジュール
- ロングポジションが存在し、価格が最良(最低)のロングエントリーから少なくとも
StepLossingPips下落した場合、戦略は 追加のロング取引を開き、そのボリュームは最後のレッグボリュームにLotCoefficientを掛けた値(銘柄ボリュームステップで 丸め)に等しい。 - ショートポジションが存在し、価格が最良(最高)のショートエントリーから少なくとも
StepLossingPips上昇した場合、同じLotCoefficient乗数を使用して新しいショートレッグが追加されます。 - 両方向でエクスポージャーが検出された場合(通常の条件下では起こらないはず)、戦略は一貫性を回復するためにすべてのレッグを 即座に閉じます。
- ロングポジションが存在し、価格が最良(最低)のロングエントリーから少なくとも
- 保護決済
- 各レッグは価格単位(
StopLossPips、TakeProfitPips)で表現された個別のストップロスとテイクプロフィットレベルを保存します。 完成した各足で、戦略は足の値幅が保存されたレベルのいずれかをクロスしたかどうかを確認し、そうであればレッグを成行注文で 閉じます。 - トレーリングストップ(
TrailingStopPips、TrailingStepPips)はオプションです。価格がレッグに有利な方向にTrailingStopPips + TrailingStepPips動いたら、ストップは現在のクローズからTrailingStopPipspips後ろに移動します。 ストップは価格が少なくともTrailingStepPipspipsの追加進歩をした場合にのみ締め付けられます。
- 各レッグは価格単位(
- 保守管理
- ボリューム命令は銘柄のボリュームステップに合わせられ、許容最小値/最大値にクリップされます。戦略は二重処理を避けるために
完全に形成された足(
CandleStates.Finished)でのみ実行されます。
- ボリューム命令は銘柄のボリュームステップに合わせられ、許容最小値/最大値にクリップされます。戦略は二重処理を避けるために
完全に形成された足(
パラメーター
| パラメーター | 型 | デフォルト | 説明 |
|---|---|---|---|
CandleType |
DataType |
TimeSpan.FromHours(1).TimeFrame() |
インジケーター計算に使用する時間軸。 |
OrderVolume |
decimal |
0.1 |
最初のエントリーのベースロットサイズ。 |
StopLossPips |
int |
50 |
pips単位のストップロス距離(0でストップ無効)。 |
TakeProfitPips |
int |
50 |
pips単位のテイクプロフィット距離(0でターゲット無効)。 |
TrailingStopPips |
int |
5 |
pips単位のトレーリングストップオフセット。トレーリングを有効にするには正の値が必要。 |
TrailingStepPips |
int |
5 |
トレーリングストップが再び動く前に必要な追加pip距離。 |
StepLossingPips |
int |
30 |
新しいアベレージングレッグをトリガーするpips単位の価格後退。 |
LotCoefficient |
decimal |
2.0 |
アベレージング時に前回レッグボリュームに適用される乗数。 |
SignalBar |
int |
0 |
インジケーターサンプリング時に遡る完成足数。 |
MaPeriod |
int |
15 |
足単位の移動平均の長さ。 |
MaShift |
int |
0 |
移動平均値に適用される水平シフト(足単位)。 |
MaMethod |
MovingAverageMethod |
Weighted |
移動平均の平滑化アルゴリズム(単純、指数、平滑、加重)。 |
MaAppliedPrice |
AppliedPriceType |
Weighted |
移動平均の入力として使用される足の価格。 |
IndentPips |
int |
4 |
エントリー前に価格と移動平均の間に必要な最小pip差。 |
MacdFastPeriod |
int |
12 |
MACDフィルターの高速EMAの長さ。 |
MacdSlowPeriod |
int |
26 |
MACDフィルターの低速EMAの長さ。 |
MacdSignalPeriod |
int |
9 |
MACDフィルターのシグナルラインの長さ。 |
MacdAppliedPrice |
AppliedPriceType |
Weighted |
MACD計算に使用される適用価格。 |
MacdRatio |
decimal |
0.9 |
取引を許可するために必要な最小MACDメイン/シグナル比率。 |
pip変換
すべてのpipベースの設定(StopLossPips、TakeProfitPips、TrailingStopPips、TrailingStepPips、StepLossingPips、
IndentPips)は銘柄のPriceStepで乗算されます。銘柄が小数点以下3または5桁の場合、小数点以下の分数建値のMetaTraderの
「pip」定義を再現するために値がさらに10倍されます。価格ステップが利用できない場合は、フォールバック値0.0001が使用されます。
実装上の注意
- StockSharpはネッティングモードで動作するため、戦略はポジションレッグの内部リストを維持します。各レッグは独自のエントリー 価格、ストップ、テイクレベルを追跡し、アベレージングが元のMetaTrader EAのように動作するようにします。
- 保護注文はソフトウェアでシミュレートされます:足がストップロスまたはテイクプロフィットレベルに触れると、そのバーでポジション が成行注文で閉じられます。
StepLossingPipsがゼロの場合、アベレージングは自動的に無効になります。そうでない場合、各追加レッグは前のレッグボリューム にLotCoefficientを掛け、最も近いボリュームステップに切り捨てた値を使用します。- トレーリングストップの更新は現在の価格プロキシとして足のクローズを使用します。ストップは不利な方向には動かず、価格の進歩が
TrailingStopPips + TrailingStepPipsを超えるまで非アクティブのままです。 - インジケーターバッファは
SignalBarとMaShiftオフセットを遵守するため、決定ロジックはMetaTraderエキスパートがそのインジ ケーターバッファから得るのとまったく同じ値を見ます。
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
public enum MaMacdMovingAverageMethod
{
Simple,
Exponential,
Smoothed,
Weighted,
}
public enum MaMacdAppliedPrice
{
Close,
Open,
High,
Low,
Median,
Typical,
Weighted,
}
/// <summary>
/// MA + MACD position averaging strategy.
/// </summary>
public class MaMacdPositionAveragingStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _orderVolume;
private readonly StrategyParam<int> _stopLossPips;
private readonly StrategyParam<int> _takeProfitPips;
private readonly StrategyParam<int> _trailingStopPips;
private readonly StrategyParam<int> _trailingStepPips;
private readonly StrategyParam<int> _stepLossingPips;
private readonly StrategyParam<decimal> _lotCoefficient;
private readonly StrategyParam<int> _signalBar;
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<int> _maShift;
private readonly StrategyParam<MaMacdMovingAverageMethod> _maMethod;
private readonly StrategyParam<MaMacdAppliedPrice> _maAppliedPrice;
private readonly StrategyParam<int> _indentPips;
private readonly StrategyParam<int> _macdFastPeriod;
private readonly StrategyParam<int> _macdSlowPeriod;
private readonly StrategyParam<int> _macdSignalPeriod;
private readonly StrategyParam<MaMacdAppliedPrice> _macdAppliedPrice;
private readonly StrategyParam<decimal> _macdRatio;
private readonly List<decimal> _maInputs = [];
private readonly List<decimal> _maValues = [];
private readonly List<(decimal Main, decimal Signal)> _macdValues = [];
private readonly List<Leg> _legs = [];
private decimal? _macdFast;
private decimal? _macdSlow;
private decimal? _macdSignal;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public decimal OrderVolume { get => _orderVolume.Value; set => _orderVolume.Value = value; }
public int StopLossPips { get => _stopLossPips.Value; set => _stopLossPips.Value = value; }
public int TakeProfitPips { get => _takeProfitPips.Value; set => _takeProfitPips.Value = value; }
public int TrailingStopPips { get => _trailingStopPips.Value; set => _trailingStopPips.Value = value; }
public int TrailingStepPips { get => _trailingStepPips.Value; set => _trailingStepPips.Value = value; }
public int StepLossingPips { get => _stepLossingPips.Value; set => _stepLossingPips.Value = value; }
public decimal LotCoefficient { get => _lotCoefficient.Value; set => _lotCoefficient.Value = value; }
public int SignalBar { get => _signalBar.Value; set => _signalBar.Value = value; }
public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
public int MaShift { get => _maShift.Value; set => _maShift.Value = value; }
public MaMacdMovingAverageMethod MaMethod { get => _maMethod.Value; set => _maMethod.Value = value; }
public MaMacdAppliedPrice MaAppliedPrice { get => _maAppliedPrice.Value; set => _maAppliedPrice.Value = value; }
public int IndentPips { get => _indentPips.Value; set => _indentPips.Value = value; }
public int MacdFastPeriod { get => _macdFastPeriod.Value; set => _macdFastPeriod.Value = value; }
public int MacdSlowPeriod { get => _macdSlowPeriod.Value; set => _macdSlowPeriod.Value = value; }
public int MacdSignalPeriod { get => _macdSignalPeriod.Value; set => _macdSignalPeriod.Value = value; }
public MaMacdAppliedPrice MacdAppliedPrice { get => _macdAppliedPrice.Value; set => _macdAppliedPrice.Value = value; }
public decimal MacdRatio { get => _macdRatio.Value; set => _macdRatio.Value = value; }
public MaMacdPositionAveragingStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame());
_orderVolume = Param(nameof(OrderVolume), 0.1m).SetGreaterThanZero();
_stopLossPips = Param(nameof(StopLossPips), 50).SetNotNegative();
_takeProfitPips = Param(nameof(TakeProfitPips), 50).SetNotNegative();
_trailingStopPips = Param(nameof(TrailingStopPips), 5).SetNotNegative();
_trailingStepPips = Param(nameof(TrailingStepPips), 5).SetNotNegative();
_stepLossingPips = Param(nameof(StepLossingPips), 30).SetNotNegative();
_lotCoefficient = Param(nameof(LotCoefficient), 2m).SetGreaterThanZero();
_signalBar = Param(nameof(SignalBar), 0).SetNotNegative();
_maPeriod = Param(nameof(MaPeriod), 15).SetGreaterThanZero();
_maShift = Param(nameof(MaShift), 0).SetNotNegative();
_maMethod = Param(nameof(MaMethod), MaMacdMovingAverageMethod.Weighted);
_maAppliedPrice = Param(nameof(MaAppliedPrice), MaMacdAppliedPrice.Weighted);
_indentPips = Param(nameof(IndentPips), 4).SetNotNegative();
_macdFastPeriod = Param(nameof(MacdFastPeriod), 12).SetGreaterThanZero();
_macdSlowPeriod = Param(nameof(MacdSlowPeriod), 26).SetGreaterThanZero();
_macdSignalPeriod = Param(nameof(MacdSignalPeriod), 9).SetGreaterThanZero();
_macdAppliedPrice = Param(nameof(MacdAppliedPrice), MaMacdAppliedPrice.Weighted);
_macdRatio = Param(nameof(MacdRatio), 0.9m).SetNotNegative();
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_maInputs.Clear();
_maValues.Clear();
_macdValues.Clear();
_legs.Clear();
_macdFast = null;
_macdSlow = null;
_macdSignal = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
SubscribeCandles(CandleType).Bind(ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
UpdateIndicators(candle);
if (_legs.Select(l => l.Side).Distinct().Count() > 1)
{
FlattenAll();
return;
}
ApplyProtection(candle);
if (_legs.Count > 0)
{
TryAverage(candle.ClosePrice, candle.OpenTime);
return;
}
if (Position != 0)
return;
var maIndex = _maValues.Count - 1 - SignalBar - MaShift;
var macdIndex = _macdValues.Count - 1 - SignalBar;
if (maIndex < 0 || macdIndex < 0)
return;
var ma = _maValues[maIndex];
var (main, signal) = _macdValues[macdIndex];
if (signal == 0m)
return;
var ratio = main / signal;
var pip = GetPipSize();
var indent = IndentPips * pip;
var close = candle.ClosePrice;
if (main < 0m && signal < 0m && ratio >= MacdRatio && close > ma && close - ma >= indent)
AddLeg(Sides.Buy, NormalizeVolume(OrderVolume), close, candle.OpenTime);
else if (main > 0m && signal > 0m && ratio >= MacdRatio && close < ma && ma - close >= indent)
AddLeg(Sides.Sell, NormalizeVolume(OrderVolume), close, candle.OpenTime);
}
private void UpdateIndicators(ICandleMessage candle)
{
var maPrice = GetAppliedPrice(candle, MaAppliedPrice);
_maInputs.Add(maPrice);
_maValues.Add(CalculateMa(_maInputs, MaPeriod, MaMethod));
var macdPrice = GetAppliedPrice(candle, MacdAppliedPrice);
_macdFast = Ema(_macdFast, macdPrice, MacdFastPeriod, 2m);
_macdSlow = Ema(_macdSlow, macdPrice, MacdSlowPeriod, 2m);
var main = _macdFast.Value - _macdSlow.Value;
_macdSignal = Ema(_macdSignal, main, MacdSignalPeriod, 2m);
_macdValues.Add((main, _macdSignal.Value));
var keep = Math.Max(MaPeriod + MaShift + SignalBar + 10, MacdSlowPeriod + MacdSignalPeriod + SignalBar + 10);
if (_maInputs.Count > keep)
{
var remove = _maInputs.Count - keep;
_maInputs.RemoveRange(0, remove);
_maValues.RemoveRange(0, remove);
_macdValues.RemoveRange(0, remove);
}
}
private void TryAverage(decimal close, DateTimeOffset candleTime)
{
if (StepLossingPips <= 0 || _legs.Count == 0)
return;
var side = _legs[0].Side;
if (_legs.Any(l => l.Side != side))
return;
var pip = GetPipSize();
var distance = StepLossingPips * pip;
var lastVolume = _legs[^1].Volume;
var volume = NormalizeVolume(lastVolume * LotCoefficient);
if (side == Sides.Buy)
{
var bestEntry = _legs.Min(l => l.EntryPrice);
if (close <= bestEntry - distance)
AddLeg(Sides.Buy, volume, close, candleTime);
}
else
{
var bestEntry = _legs.Max(l => l.EntryPrice);
if (close >= bestEntry + distance)
AddLeg(Sides.Sell, volume, close, candleTime);
}
}
private void ApplyProtection(ICandleMessage candle)
{
if (_legs.Count == 0)
return;
var pip = GetPipSize();
var exitBuy = 0m;
var exitSell = 0m;
for (var i = _legs.Count - 1; i >= 0; i--)
{
var leg = _legs[i];
if (candle.OpenTime <= leg.EntryTime)
continue;
var stopPrice = leg.StopPrice;
var takePrice = leg.TakePrice;
var hit = leg.Side == Sides.Buy
? (stopPrice is decimal stop && candle.LowPrice <= stop) || (takePrice is decimal take && candle.HighPrice >= take)
: (stopPrice is decimal shortStop && candle.HighPrice >= shortStop) || (takePrice is decimal shortTake && candle.LowPrice <= shortTake);
if (!hit)
{
// A stop moved on this close only guards the candles that follow.
UpdateTrailing(leg, candle.ClosePrice, pip);
continue;
}
if (leg.Side == Sides.Buy)
exitSell += leg.Volume;
else
exitBuy += leg.Volume;
_legs.RemoveAt(i);
}
if (exitSell > 0m)
SellMarket(exitSell);
if (exitBuy > 0m)
BuyMarket(exitBuy);
}
private void UpdateTrailing(Leg leg, decimal close, decimal pip)
{
if (TrailingStopPips <= 0 || TrailingStepPips < 0)
return;
var trail = TrailingStopPips * pip;
var step = TrailingStepPips * pip;
if (leg.Side == Sides.Buy)
{
if (close - leg.EntryPrice < trail + step)
return;
var candidate = close - trail;
if (leg.StopPrice is null || candidate >= leg.StopPrice.Value + step)
leg.StopPrice = candidate;
}
else
{
if (leg.EntryPrice - close < trail + step)
return;
var candidate = close + trail;
if (leg.StopPrice is null || candidate <= leg.StopPrice.Value - step)
leg.StopPrice = candidate;
}
}
private void AddLeg(Sides side, decimal volume, decimal price, DateTimeOffset entryTime)
{
if (volume <= 0m)
return;
if (side == Sides.Buy)
BuyMarket(volume);
else
SellMarket(volume);
var pip = GetPipSize();
var stopDistance = StopLossPips * pip;
var takeDistance = TakeProfitPips * pip;
_legs.Add(new Leg
{
Side = side,
Volume = volume,
EntryPrice = price,
EntryTime = entryTime,
StopPrice = StopLossPips > 0 ? side == Sides.Buy ? price - stopDistance : price + stopDistance : null,
TakePrice = TakeProfitPips > 0 ? side == Sides.Buy ? price + takeDistance : price - takeDistance : null,
});
}
private void FlattenAll()
{
if (Position > 0)
SellMarket(Math.Abs(Position));
else if (Position < 0)
BuyMarket(Math.Abs(Position));
_legs.Clear();
}
private decimal NormalizeVolume(decimal volume)
{
if (Security?.MaxVolume is decimal max && max > 0m)
volume = Math.Min(volume, max);
if (Security?.MinVolume is decimal min && min > 0m)
volume = Math.Max(volume, min);
if (Security?.VolumeStep is decimal step && step > 0m)
volume = Math.Floor(volume / step) * step;
return volume;
}
private decimal GetPipSize()
{
var step = Security?.PriceStep ?? 0m;
if (step <= 0m)
return 0.0001m;
return step is 0.00001m or 0.001m ? step * 10m : step;
}
private static decimal GetAppliedPrice(ICandleMessage candle, MaMacdAppliedPrice type)
=> type switch
{
MaMacdAppliedPrice.Open => candle.OpenPrice,
MaMacdAppliedPrice.High => candle.HighPrice,
MaMacdAppliedPrice.Low => candle.LowPrice,
MaMacdAppliedPrice.Median => (candle.HighPrice + candle.LowPrice) / 2m,
MaMacdAppliedPrice.Typical => (candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 3m,
MaMacdAppliedPrice.Weighted => (candle.HighPrice + candle.LowPrice + 2m * candle.ClosePrice) / 4m,
_ => candle.ClosePrice,
};
private static decimal CalculateMa(List<decimal> values, int period, MaMacdMovingAverageMethod method)
{
var count = Math.Min(period, values.Count);
var start = values.Count - count;
if (method == MaMacdMovingAverageMethod.Weighted)
{
var weighted = 0m;
var weights = 0m;
for (var i = 0; i < count; i++)
{
var weight = i + 1m;
weighted += values[start + i] * weight;
weights += weight;
}
return weighted / weights;
}
if (method == MaMacdMovingAverageMethod.Simple)
return values.Skip(start).Average();
var alpha = method == MaMacdMovingAverageMethod.Smoothed ? 1m / period : 2m / (period + 1m);
var result = values[start];
for (var i = start + 1; i < values.Count; i++)
result += alpha * (values[i] - result);
return result;
}
private static decimal Ema(decimal? previous, decimal value, int period, decimal numerator)
{
if (previous is null)
return value;
var alpha = numerator / (period + 1m);
return previous.Value + alpha * (value - previous.Value);
}
private sealed class Leg
{
public Sides Side { get; init; }
public decimal Volume { get; init; }
public decimal EntryPrice { get; init; }
public DateTimeOffset EntryTime { get; init; }
public decimal? StopPrice { get; set; }
public decimal? TakePrice { get; init; }
}
}
import clr
import math
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates, Sides
from StockSharp.Algo.Strategies import Strategy
class ma_macd_position_averaging_strategy(Strategy):
MA_SIMPLE = 0
MA_EXPONENTIAL = 1
MA_SMOOTHED = 2
MA_WEIGHTED = 3
PRICE_CLOSE = 0
PRICE_OPEN = 1
PRICE_HIGH = 2
PRICE_LOW = 3
PRICE_MEDIAN = 4
PRICE_TYPICAL = 5
PRICE_WEIGHTED = 6
def __init__(self):
super(ma_macd_position_averaging_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1)))
self._order_volume = self.Param("OrderVolume", 0.1).SetGreaterThanZero()
self._stop_loss = self.Param("StopLossPips", 50).SetNotNegative()
self._take_profit = self.Param("TakeProfitPips", 50).SetNotNegative()
self._trailing_stop = self.Param("TrailingStopPips", 5).SetNotNegative()
self._trailing_step = self.Param("TrailingStepPips", 5).SetNotNegative()
self._step_lossing = self.Param("StepLossingPips", 30).SetNotNegative()
self._lot_coefficient = self.Param("LotCoefficient", 2.0).SetGreaterThanZero()
self._signal_bar = self.Param("SignalBar", 0).SetNotNegative()
self._ma_period = self.Param("MaPeriod", 15).SetGreaterThanZero()
self._ma_shift = self.Param("MaShift", 0).SetNotNegative()
self._ma_method = self.Param("MaMethod", self.MA_WEIGHTED)
self._ma_applied = self.Param("MaAppliedPrice", self.PRICE_WEIGHTED)
self._indent = self.Param("IndentPips", 4).SetNotNegative()
self._macd_fast_period = self.Param("MacdFastPeriod", 12).SetGreaterThanZero()
self._macd_slow_period = self.Param("MacdSlowPeriod", 26).SetGreaterThanZero()
self._macd_signal_period = self.Param("MacdSignalPeriod", 9).SetGreaterThanZero()
self._macd_applied = self.Param("MacdAppliedPrice", self.PRICE_WEIGHTED)
self._macd_ratio = self.Param("MacdRatio", 0.9).SetNotNegative()
self._ma_inputs = []
self._ma_values = []
self._macd_values = []
self._legs = []
self._macd_fast = None
self._macd_slow = None
self._macd_signal = None
def GetWorkingSecurities(self):
return [(self.Security, self._candle_type.Value)]
def OnReseted(self):
super(ma_macd_position_averaging_strategy, self).OnReseted()
self._ma_inputs = []
self._ma_values = []
self._macd_values = []
self._legs = []
self._macd_fast = None
self._macd_slow = None
self._macd_signal = None
def OnStarted2(self, time):
super(ma_macd_position_averaging_strategy, self).OnStarted2(time)
self.SubscribeCandles(self._candle_type.Value).Bind(self._process_candle).Start()
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
self._update_indicators(candle)
if len(set(leg["side"] for leg in self._legs)) > 1:
self._flatten_all()
return
self._apply_protection(candle)
if self._legs:
self._try_average(float(candle.ClosePrice), candle.OpenTime)
return
if self.Position != 0:
return
ma_index = len(self._ma_values) - 1 - int(self._signal_bar.Value) - int(self._ma_shift.Value)
macd_index = len(self._macd_values) - 1 - int(self._signal_bar.Value)
if ma_index < 0 or macd_index < 0:
return
ma = self._ma_values[ma_index]
main, signal = self._macd_values[macd_index]
if signal == 0:
return
ratio = main / signal
pip = self._pip_size()
indent = int(self._indent.Value) * pip
close = float(candle.ClosePrice)
if main < 0 and signal < 0 and ratio >= float(self._macd_ratio.Value) and close > ma and close - ma >= indent:
self._add_leg(Sides.Buy, self._normalize_volume(float(self._order_volume.Value)), close, candle.OpenTime)
elif main > 0 and signal > 0 and ratio >= float(self._macd_ratio.Value) and close < ma and ma - close >= indent:
self._add_leg(Sides.Sell, self._normalize_volume(float(self._order_volume.Value)), close, candle.OpenTime)
def _update_indicators(self, candle):
ma_price = self._applied_price(candle, int(self._ma_applied.Value))
self._ma_inputs.append(ma_price)
self._ma_values.append(self._calculate_ma(self._ma_inputs, int(self._ma_period.Value), int(self._ma_method.Value)))
macd_price = self._applied_price(candle, int(self._macd_applied.Value))
self._macd_fast = self._ema(self._macd_fast, macd_price, int(self._macd_fast_period.Value), 2.0)
self._macd_slow = self._ema(self._macd_slow, macd_price, int(self._macd_slow_period.Value), 2.0)
main = self._macd_fast - self._macd_slow
self._macd_signal = self._ema(self._macd_signal, main, int(self._macd_signal_period.Value), 2.0)
self._macd_values.append((main, self._macd_signal))
keep = max(
int(self._ma_period.Value) + int(self._ma_shift.Value) + int(self._signal_bar.Value) + 10,
int(self._macd_slow_period.Value) + int(self._macd_signal_period.Value) + int(self._signal_bar.Value) + 10)
if len(self._ma_inputs) > keep:
remove = len(self._ma_inputs) - keep
del self._ma_inputs[:remove]
del self._ma_values[:remove]
del self._macd_values[:remove]
def _try_average(self, close, candle_time):
step_pips = int(self._step_lossing.Value)
if step_pips <= 0 or not self._legs:
return
side = self._legs[0]["side"]
if any(leg["side"] != side for leg in self._legs):
return
distance = step_pips * self._pip_size()
volume = self._normalize_volume(self._legs[-1]["volume"] * float(self._lot_coefficient.Value))
if side == Sides.Buy:
best = min(leg["entry"] for leg in self._legs)
if close <= best - distance:
self._add_leg(Sides.Buy, volume, close, candle_time)
else:
best = max(leg["entry"] for leg in self._legs)
if close >= best + distance:
self._add_leg(Sides.Sell, volume, close, candle_time)
def _apply_protection(self, candle):
if not self._legs:
return
pip = self._pip_size()
exit_buy = 0.0
exit_sell = 0.0
for i in range(len(self._legs) - 1, -1, -1):
leg = self._legs[i]
if candle.OpenTime <= leg["entry_time"]:
continue
if leg["side"] == Sides.Buy:
hit = ((leg["stop"] is not None and float(candle.LowPrice) <= leg["stop"]) or
(leg["take"] is not None and float(candle.HighPrice) >= leg["take"]))
else:
hit = ((leg["stop"] is not None and float(candle.HighPrice) >= leg["stop"]) or
(leg["take"] is not None and float(candle.LowPrice) <= leg["take"]))
if not hit:
# A stop moved on this close only guards the candles that follow.
self._update_trailing(leg, float(candle.ClosePrice), pip)
continue
if leg["side"] == Sides.Buy:
exit_sell += leg["volume"]
else:
exit_buy += leg["volume"]
del self._legs[i]
if exit_sell > 0:
self.SellMarket(exit_sell)
if exit_buy > 0:
self.BuyMarket(exit_buy)
def _update_trailing(self, leg, close, pip):
trail_pips = int(self._trailing_stop.Value)
step_pips = int(self._trailing_step.Value)
if trail_pips <= 0 or step_pips < 0:
return
trail = trail_pips * pip
step = step_pips * pip
if leg["side"] == Sides.Buy:
if close - leg["entry"] < trail + step:
return
candidate = close - trail
if leg["stop"] is None or candidate >= leg["stop"] + step:
leg["stop"] = candidate
else:
if leg["entry"] - close < trail + step:
return
candidate = close + trail
if leg["stop"] is None or candidate <= leg["stop"] - step:
leg["stop"] = candidate
def _add_leg(self, side, volume, price, entry_time):
if volume <= 0:
return
if side == Sides.Buy:
self.BuyMarket(volume)
else:
self.SellMarket(volume)
pip = self._pip_size()
sl = int(self._stop_loss.Value) * pip
tp = int(self._take_profit.Value) * pip
self._legs.append({
"side": side,
"volume": volume,
"entry": price,
"entry_time": entry_time,
"stop": (price - sl if side == Sides.Buy else price + sl) if int(self._stop_loss.Value) > 0 else None,
"take": (price + tp if side == Sides.Buy else price - tp) if int(self._take_profit.Value) > 0 else None,
})
def _flatten_all(self):
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
elif self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self._legs = []
def _normalize_volume(self, volume):
if self.Security is not None:
if self.Security.MaxVolume is not None and float(self.Security.MaxVolume) > 0:
volume = min(volume, float(self.Security.MaxVolume))
if self.Security.MinVolume is not None and float(self.Security.MinVolume) > 0:
volume = max(volume, float(self.Security.MinVolume))
if self.Security.VolumeStep is not None and float(self.Security.VolumeStep) > 0:
step = float(self.Security.VolumeStep)
volume = math.floor(volume / step) * step
return volume
def _pip_size(self):
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 0.0
if step <= 0:
return 0.0001
return step * 10.0 if abs(step - 0.00001) < 1e-12 or abs(step - 0.001) < 1e-12 else step
@classmethod
def _applied_price(cls, candle, kind):
o = float(candle.OpenPrice)
h = float(candle.HighPrice)
l = float(candle.LowPrice)
c = float(candle.ClosePrice)
if kind == cls.PRICE_OPEN:
return o
if kind == cls.PRICE_HIGH:
return h
if kind == cls.PRICE_LOW:
return l
if kind == cls.PRICE_MEDIAN:
return (h + l) / 2.0
if kind == cls.PRICE_TYPICAL:
return (h + l + c) / 3.0
if kind == cls.PRICE_WEIGHTED:
return (h + l + 2.0 * c) / 4.0
return c
@classmethod
def _calculate_ma(cls, values, period, method):
count = min(period, len(values))
sample = values[-count:]
if method == cls.MA_WEIGHTED:
weights = list(range(1, count + 1))
return sum(v * w for v, w in zip(sample, weights)) / float(sum(weights))
if method == cls.MA_SIMPLE:
return sum(sample) / float(count)
alpha = 1.0 / period if method == cls.MA_SMOOTHED else 2.0 / (period + 1.0)
result = sample[0]
for value in sample[1:]:
result += alpha * (value - result)
return result
@staticmethod
def _ema(previous, value, period, numerator):
if previous is None:
return value
alpha = numerator / (period + 1.0)
return previous + alpha * (value - previous)
def CreateClone(self):
return ma_macd_position_averaging_strategy()