Ver en GitHub

Estrategia de Ruptura TMA

Esta estrategia aprovecha las rupturas relativas a una Media Móvil Triangular (TMA). Observa una serie de velas configurable y compara el cierre de la vela anterior con el valor TMA más o menos los offsets definidos por el usuario. Se abre una posición larga cuando el cierre anterior está por encima de TMA + UpLevel, y se abre una posición corta cuando está por debajo de TMA - DownLevel. Las señales opuestas revierten la posición.

Parámetros

  • TMA Length – período utilizado para calcular la Media Móvil Triangular.
  • Upper Level – offset de precio añadido al TMA para detectar señales largas.
  • Lower Level – offset de precio sustraído del TMA para detectar señales cortas.
  • Candle Type – marco temporal de las velas utilizadas por la estrategia.

Cómo Funciona

  1. Se suscribe a la serie de velas seleccionada.
  2. Vincula un indicador de Media Móvil Triangular a las velas.
  3. En cada vela finalizada:
    • Almacena los valores anteriores de TMA y precio de cierre.
    • Verifica si el cierre anterior superó el nivel superior o inferior.
    • Envía órdenes de mercado para abrir o revertir posiciones según corresponda.
  4. Grafica velas, línea del indicador y operaciones propias para análisis visual.

Notas

La estrategia utiliza órdenes de mercado sin gestión de stop-loss ni take-profit. Está pensada con fines educativos y debe ampliarse con controles de riesgo adecuados antes de operar en real.

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;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy that enters when price breaks the Triangular Moving Average by configurable offsets.
/// </summary>
public class TmaBreakoutStrategy : Strategy
{
	private readonly StrategyParam<int> _length;
	private readonly StrategyParam<decimal> _upLevel;
	private readonly StrategyParam<decimal> _downLevel;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevTma;
	private decimal? _prevClose;

	/// <summary>
	/// Period for the Triangular Moving Average.
	/// </summary>
	public int Length
	{
		get => _length.Value;
		set => _length.Value = value;
	}

	/// <summary>
	/// Offset above the TMA to trigger a long entry.
	/// </summary>
	public decimal UpLevel
	{
		get => _upLevel.Value;
		set => _upLevel.Value = value;
	}

	/// <summary>
	/// Offset below the TMA to trigger a short entry.
	/// </summary>
	public decimal DownLevel
	{
		get => _downLevel.Value;
		set => _downLevel.Value = value;
	}

	/// <summary>
	/// Candle type.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initialize the TMA breakout strategy.
	/// </summary>
	public TmaBreakoutStrategy()
	{
		_length = Param(nameof(Length), 30)
			.SetDisplay("TMA Length", "Period for the Triangular Moving Average", "Parameters")
			
			.SetOptimize(10, 60, 10);

		_upLevel = Param(nameof(UpLevel), 300m)
			.SetDisplay("Upper Level", "Offset above TMA in price units", "Parameters")
			
			.SetOptimize(100m, 500m, 100m);

		_downLevel = Param(nameof(DownLevel), 300m)
			.SetDisplay("Lower Level", "Offset below TMA in price units", "Parameters")
			
			.SetOptimize(100m, 500m, 100m);

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevTma = _prevClose = null;
	}

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

		var tma = new ExponentialMovingAverage { Length = Length };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(tma, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, tma);
			DrawOwnTrades(area);
		}
	}

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var prevTma = _prevTma;
		var prevClose = _prevClose;

		if (prevTma is null || prevClose is null)
		{
			_prevTma = tmaValue;
			_prevClose = candle.ClosePrice;
			return;
		}

		var signalUp = prevClose > prevTma + UpLevel;
		var signalDn = prevClose < prevTma - DownLevel;

		if (signalUp && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();
			BuyMarket();
		}
		else if (signalDn && Position >= 0)
		{
			if (Position > 0)
				SellMarket();
			SellMarket();
		}

		_prevTma = tmaValue;
		_prevClose = candle.ClosePrice;
	}
}