Estratégia de Pares
Esta estratégia de trading de pares compra quando o ativo de referência fecha acima de sua abertura enquanto o símbolo atual forma uma vela de baixa. A posição é fechada quando o preço rompe acima da máxima da vela anterior.
Detalhes
- Critérios de entrada: Ativo de referência em alta e vela de baixa no símbolo atual.
- Comprado/Vendido: Somente comprado.
- Critérios de saída: Fechamento acima da máxima anterior.
- Stops: Não.
- Valores padrão:
CandleType= 1 minuto
- Filtros:
- Categoria: Trading de pares
- Direção: Somente comprado
- Indicadores: Price action
- Stops: Não
- Complexidade: Iniciante
- Período: Intradiário
- Sazonalidade: Não
- Redes neurais: Não
- Divergência: Não
- Nível de risco: Médio
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>
/// Buys when the reference asset closes above its open and the current symbol forms a down bar.
/// Closes the position when price closes above the previous candle's high.
/// </summary>
public class PairsStrategy : Strategy
{
private readonly StrategyParam<Security> _referenceSecurity;
private readonly StrategyParam<DataType> _candleType;
private bool _referenceUp;
private decimal _previousHigh;
/// <summary>
/// Reference security used for comparison.
/// </summary>
public Security ReferenceSecurity
{
get => _referenceSecurity.Value;
set => _referenceSecurity.Value = value;
}
/// <summary>
/// Candle type used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="PairsStrategy"/>.
/// </summary>
public PairsStrategy()
{
_referenceSecurity = Param<Security>(nameof(ReferenceSecurity))
.SetDisplay("Reference Security", "Security used for pair comparison", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType), (ReferenceSecurity, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_referenceUp = false;
_previousHigh = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
if (ReferenceSecurity == null)
throw new InvalidOperationException("ReferenceSecurity must be specified.");
base.OnStarted2(time);
SubscribeCandles(CandleType, true, ReferenceSecurity)
.Bind(ProcessReference)
.Start();
SubscribeCandles(CandleType)
.Bind(ProcessMain)
.Start();
StartProtection(null, null);
}
private void ProcessReference(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
_referenceUp = candle.ClosePrice > candle.OpenPrice;
}
private void ProcessMain(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
if (Position <= 0 && _referenceUp && candle.ClosePrice < candle.OpenPrice && IsFormedAndOnlineAndAllowTrading())
BuyMarket();
if (Position > 0 && candle.ClosePrice > _previousHigh && IsFormedAndOnlineAndAllowTrading())
SellMarket();
_previousHigh = candle.HighPrice;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, InvalidOperationException
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
class pairs_strategy(Strategy):
def __init__(self):
super(pairs_strategy, self).__init__()
self._reference_security = self.Param("ReferenceSecurity", None) \
.SetDisplay("Reference Security", "Security used for pair comparison", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._reference_up = False
self._previous_high = 0.0
@property
def reference_security(self):
return self._reference_security.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(pairs_strategy, self).OnReseted()
self._reference_up = False
self._previous_high = 0.0
def OnStarted2(self, time):
super(pairs_strategy, self).OnStarted2(time)
if self.reference_security is None:
raise InvalidOperationException("ReferenceSecurity must be specified.")
self.StartProtection(None, None)
self.SubscribeCandles(self.candle_type, True, self.reference_security) \
.Bind(self._process_reference).Start()
self.SubscribeCandles(self.candle_type) \
.Bind(self._process_main).Start()
def _process_reference(self, candle):
if candle.State != CandleStates.Finished:
return
self._reference_up = float(candle.ClosePrice) > float(candle.OpenPrice)
def _process_main(self, candle):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
opn = float(candle.OpenPrice)
if self.Position <= 0 and self._reference_up and close < opn and self.IsFormedAndOnlineAndAllowTrading():
self.BuyMarket()
if self.Position > 0 and close > self._previous_high and self.IsFormedAndOnlineAndAllowTrading():
self.SellMarket()
self._previous_high = float(candle.HighPrice)
def CreateClone(self):
return pairs_strategy()