Ver no GitHub

Estratégia BTCUSD com SLTP Ajustável

A estratégia opera BTCUSD usando um cruzamento entre SMA(10) e SMA(25) com um filtro EMA(150). As entradas compradas aguardam um recuo: após o cruzamento, um percentual de retração é rastreado e uma posição comprada é aberta quando o preço cruza de volta acima desse nível. As entradas vendidas são acionadas imediatamente em um cruzamento de baixa enquanto o preço está abaixo da EMA.

As saídas usam distâncias ajustáveis de take-profit, stop-loss e break-even. Uma posição comprada também é encerrada se SMA(10) cruzar abaixo de SMA(25) enquanto o preço estiver abaixo de EMA(150).

Detalhes

  • Critérios de entrada:
    • Comprado: SMA(10) cruza acima de SMA(25), então o preço retrai um percentual definido e cruza acima do nível de retração.
    • Vendido: SMA(10) cruza abaixo de SMA(25) enquanto o preço está abaixo de EMA(150).
  • Comprado/Vendido: Comprado e vendido.
  • Critérios de saída:
    • Distâncias configuráveis de take-profit, stop-loss e break-even.
    • Saída comprada quando SMA(10) cruza abaixo de SMA(25) abaixo de EMA(150).
  • Stops: Sim, ajustáveis em pontos.
  • Valores padrão:
    • FastSmaLength = 10
    • SlowSmaLength = 25
    • EmaFilterLength = 150
    • TakeProfitDistance = 1000
    • StopLossDistance = 250
    • BreakEvenTrigger = 500
    • RetracementPercentage = 0.01
  • Filtros:
    • Categoria: Seguidor de tendência
    • Direção: Comprado e Vendido
    • Indicadores: SMA, EMA
    • Stops: Sim
    • Complexidade: Moderado
    • Período: Qualquer
    • Sazonalidade: Não
    • Redes neurais: Não
    • Divergência: Não
    • Nível de risco: Médio
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>
/// BTCUSD strategy with adjustable SL/TP using SMA crossover.
/// Enters long on golden cross above EMA filter, short on death cross below EMA filter.
/// </summary>
public class BtcusdAdjustableSltpStrategy : Strategy
{
	private readonly StrategyParam<int> _fastSmaLength;
	private readonly StrategyParam<int> _slowSmaLength;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevFast;
	private decimal _prevSlow;

	public int FastSmaLength { get => _fastSmaLength.Value; set => _fastSmaLength.Value = value; }
	public int SlowSmaLength { get => _slowSmaLength.Value; set => _slowSmaLength.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public BtcusdAdjustableSltpStrategy()
	{
		_fastSmaLength = Param(nameof(FastSmaLength), 120)
			.SetGreaterThanZero()
			.SetDisplay("Fast SMA", "Length of fast SMA", "Indicators");

		_slowSmaLength = Param(nameof(SlowSmaLength), 450)
			.SetGreaterThanZero()
			.SetDisplay("Slow SMA", "Length of slow SMA", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

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

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

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

		var fastSma = new SimpleMovingAverage { Length = FastSmaLength };
		var slowSma = new SimpleMovingAverage { Length = SlowSmaLength };

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

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

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

		if (_prevFast == 0m || _prevSlow == 0m)
		{
			_prevFast = fast;
			_prevSlow = slow;
			return;
		}

		if (_prevFast <= _prevSlow && fast > slow && Position <= 0)
		{
			BuyMarket();
		}
		else if (_prevFast >= _prevSlow && fast < slow && Position >= 0)
		{
			SellMarket();
		}

		_prevFast = fast;
		_prevSlow = slow;
	}
}