Ver en GitHub

Estrategia TCPivotLimit

Esta estrategia opera alrededor de los niveles clásicos de puntos de pivote diarios. Los puntos de pivote se calculan a partir del máximo, mínimo y precios de cierre del día anterior. Se colocan órdenes limitadas en los niveles de soporte o resistencia seleccionados y las posiciones se gestionan con niveles predefinidos de stop-loss y take-profit.

Parámetros

  • Volume – volumen de la orden.
  • Target Variant – selecciona qué niveles de soporte/resistencia se utilizan para la entrada, el stop y el objetivo:
    1. Entrada en S1/R1, stop en S2/R2, objetivo en R1/S1.
    2. Entrada en S1/R1, stop en S2/R2, objetivo en R2/S2.
    3. Entrada en S2/R2, stop en S3/R3, objetivo en R1/S1.
    4. Entrada en S2/R2, stop en S3/R3, objetivo en R2/S2.
    5. Entrada en S2/R2, stop en S3/R3, objetivo en R3/S3.
  • Intraday Close – cerrar cualquier posición abierta a las 23:00.
  • Modify Stop Loss – mover el stop loss al primer nivel objetivo una vez alcanzado.

Lógica de operación

  1. Al inicio de cada día, la estrategia calcula el pivote y tres niveles de resistencia y tres de soporte usando los datos del día anterior.
  2. Cuando el precio toca el nivel de soporte o resistencia elegido, se envía una orden limitada en la dirección opuesta.
  3. La posición se cierra cuando se alcanza el nivel de stop-loss o take-profit. La modificación opcional del stop-loss puede reducir el riesgo tras alcanzar el primer objetivo.
  4. Si Intraday Close está activado, cualquier posición abierta se cierra al final de la sesión de trading.
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>
/// Pivot point trading strategy based on previous period support/resistance levels.
/// Buys at support, sells at resistance, exits at opposite pivot level.
/// </summary>
public class TcpPivotLimitStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;

	private DateTime _currentDay;
	private decimal _dayHigh;
	private decimal _dayLow;
	private decimal _dayClose;

	private decimal _pivot;
	private decimal _r1, _s1;
	private decimal _entryPrice;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public TcpPivotLimitStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_currentDay = default;
		_dayHigh = 0;
		_dayLow = 0;
		_dayClose = 0;
		_pivot = _r1 = _s1 = 0;
		_entryPrice = 0;
	}

	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;

		var day = candle.OpenTime.Date;

		if (_currentDay != day)
		{
			if (_currentDay != default)
			{
				_pivot = (_dayHigh + _dayLow + _dayClose) / 3m;
				_r1 = 2m * _pivot - _dayLow;
				_s1 = 2m * _pivot - _dayHigh;
			}

			_currentDay = day;
			_dayHigh = candle.HighPrice;
			_dayLow = candle.LowPrice;
			_dayClose = candle.ClosePrice;
			return;
		}

		_dayHigh = Math.Max(_dayHigh, candle.HighPrice);
		_dayLow = Math.Min(_dayLow, candle.LowPrice);
		_dayClose = candle.ClosePrice;

		if (_pivot == 0) return;

		var close = candle.ClosePrice;

		if (Position == 0)
		{
			// Buy at support
			if (close <= _s1)
			{
				BuyMarket();
				_entryPrice = close;
			}
			// Sell at resistance
			else if (close >= _r1)
			{
				SellMarket();
				_entryPrice = close;
			}
		}
		else if (Position > 0)
		{
			// Exit long at resistance or stop at entry - (r1 - s1)
			if (close >= _r1 || close <= _entryPrice - (_r1 - _s1))
			{
				SellMarket();
				_entryPrice = 0;
			}
		}
		else if (Position < 0)
		{
			// Exit short at support or stop
			if (close <= _s1 || close >= _entryPrice + (_r1 - _s1))
			{
				BuyMarket();
				_entryPrice = 0;
			}
		}
	}
}