Pairs Strategy 策略
该配对交易策略在参考资产收盘价高于开盘价且当前标的形成下跌蜡烛时买入。当收盘价突破前一根蜡烛的最高点时平仓。
细节
- 入场条件:参考资产上涨且当前蜡烛为下跌。
- 多/空:仅多头。
- 退出条件:收盘价高于前一根蜡烛的最高点。
- 止损:无。
- 默认值:
CandleType= 1 分钟
- 过滤条件:
- 类别: 配对交易
- 方向: 仅多头
- 指标: 价格行为
- 止损: 无
- 复杂度: 初级
- 时间框架: 日内
- 季节性: 无
- 神经网络: 无
- 背离: 无
- 风险级别: 中等
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()