Início
/
Exemplos de estratégias
Ver no GitHub
Exp ColorX2MA X2 Strategy
The strategy recreates the dual timeframe "Exp_ColorX2MA_X2" expert for StockSharp. It layers two ColorX2MA filters: a higher timeframe trend map and a lower timeframe entry trigger. Both ColorX2MA values are built by cascading two configurable moving averages and then coloring the result according to the current slope. Trading decisions are performed when the lower timeframe color changes in the direction of the higher timeframe trend.
The implementation supports the original applied price options and the most common smoothing modes (SMA, EMA, SMMA, LWMA, Jurik). When the Jurik indicator exposes a Phase property it is updated with the configured phase value.
Trading Rules
Long entry
Higher timeframe ColorX2MA color is bullish (trend direction > 0).
Lower timeframe ColorX2MA changed from bullish color on the previous bar to a neutral or bearish color on the latest completed bar (Clr[1] == 1 and Clr[0] != 1).
Long trading is enabled.
Short entry
Higher timeframe ColorX2MA color is bearish (trend direction < 0).
Lower timeframe ColorX2MA changed from bearish color on the previous bar to a neutral or bullish color on the latest completed bar (Clr[1] == 2 and Clr[0] != 2).
Short trading is enabled.
Long exit
When a bearish lower timeframe color appears (Clr[1] == 2) and secondary long closing permission is enabled, or the higher timeframe trend flips bearish while primary long closing permission is enabled.
Short exit
When a bullish lower timeframe color appears (Clr[1] == 1) and secondary short closing permission is enabled, or the higher timeframe trend flips bullish while primary short closing permission is enabled.
Stops
Optional stop loss and take profit distances are specified in points (multiplied by the instrument price step). They are evaluated on every finished signal candle by comparing the candle extremes with the average position price.
Default Parameters
Trend timeframe : 6-hour candles.
Signal timeframe : 30-minute candles.
Trend smoothing : SMA(12) feeding Jurik(5, phase 15).
Signal smoothing : SMA(12) feeding Jurik(5, phase 15).
Applied price : Close.
Signal shift : 1 bar on both timeframes.
Permissions : long/short entries and exits are enabled.
Stop loss : 1000 points (converted using the price step).
Take profit : 2000 points (converted using the price step).
Filters & Notes
Direction: trades both long and short, controlled via permission flags.
Timeframe: dual timeframe (trend on HTF, entries on LTF).
Indicators: two-level ColorX2MA with configurable smoothing methods.
Smoothing support: Sma, Ema, Smma, Lwma, Jurik. Other modes from the original library are not implemented.
Applied prices: all 12 original formulas including TrendFollow and Demark prices.
Stops: optional fixed-distance stop loss and take profit.
Complexity: intermediate because it synchronizes two timeframes and color buffers.
Suitable for: trend-following setups on FX, indices or crypto where the ColorX2MA indicator is preferred.
Usage Tips
Keep the higher timeframe significantly larger than the signal timeframe to avoid frequent whipsaws.
Tighten the signal shift parameter (SignalSignalBar) to react faster or increase it to smooth more.
If the instrument does not provide PriceStep, the stop/take distances are interpreted directly in price units.
Jurik smoothing requires a licensed StockSharp indicator package; when unavailable the strategy still runs with the other smoothing options.
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;
/// <summary>
/// ColorX2MA X2 strategy (simplified). Uses dual EMA smoothing to detect trend color transitions.
/// Buys when the smoothed MA turns up, sells when it turns down.
/// </summary>
public class ExpColorX2MaX2Strategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int FastLength
{
get => _fastLength.Value;
set => _fastLength.Value = value;
}
public int SlowLength
{
get => _slowLength.Value;
set => _slowLength.Value = value;
}
public ExpColorX2MaX2Strategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
_fastLength = Param(nameof(FastLength), 12)
.SetGreaterThanZero()
.SetDisplay("Fast Length", "Fast EMA period", "Indicators");
_slowLength = Param(nameof(SlowLength), 26)
.SetGreaterThanZero()
.SetDisplay("Slow Length", "Slow EMA period", "Indicators");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastEma = new ExponentialMovingAverage { Length = FastLength };
var slowEma = new ExponentialMovingAverage { Length = SlowLength };
decimal prevFast = 0, prevSlow = 0;
var hasPrev = false;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastEma, slowEma, (ICandleMessage candle, decimal fastValue, decimal slowValue) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!hasPrev)
{
prevFast = fastValue;
prevSlow = slowValue;
hasPrev = true;
return;
}
if (!IsFormedAndOnlineAndAllowTrading())
{
prevFast = fastValue;
prevSlow = slowValue;
return;
}
// Fast crosses above slow
if (prevFast <= prevSlow && fastValue > slowValue && Position <= 0)
BuyMarket();
// Fast crosses below slow
else if (prevFast >= prevSlow && fastValue < slowValue && Position >= 0)
SellMarket();
prevFast = fastValue;
prevSlow = slowValue;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastEma);
DrawIndicator(area, slowEma);
DrawOwnTrades(area);
}
}
}
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 exp_color_x2_ma_x2_strategy(Strategy):
def __init__(self):
super(exp_color_x2_ma_x2_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candles", "General")
self._fast_length = self.Param("FastLength", 12) \
.SetDisplay("Fast Length", "Fast EMA period", "Indicators")
self._slow_length = self.Param("SlowLength", 26) \
.SetDisplay("Slow Length", "Slow EMA period", "Indicators")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._has_prev = False
@property
def CandleType(self):
return self._candle_type.Value
@property
def FastLength(self):
return self._fast_length.Value
@property
def SlowLength(self):
return self._slow_length.Value
def OnReseted(self):
super(exp_color_x2_ma_x2_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(exp_color_x2_ma_x2_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._has_prev = False
fast_ema = ExponentialMovingAverage()
fast_ema.Length = self.FastLength
slow_ema = ExponentialMovingAverage()
slow_ema.Length = self.SlowLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast_ema, slow_ema, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_ema)
self.DrawIndicator(area, slow_ema)
self.DrawOwnTrades(area)
def _on_process(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fv = float(fast_value)
sv = float(slow_value)
if not self._has_prev:
self._prev_fast = fv
self._prev_slow = sv
self._has_prev = True
return
if self._prev_fast <= self._prev_slow and fv > sv and self.Position <= 0:
self.BuyMarket()
elif self._prev_fast >= self._prev_slow and fv < sv and self.Position >= 0:
self.SellMarket()
self._prev_fast = fv
self._prev_slow = sv
def CreateClone(self):
return exp_color_x2_ma_x2_strategy()