IS 策略
该策略在所选数据源等于多头触发值且前一个值不同时时做多;若允许做空,则在相反信号上做空。止盈和止损以入场价的百分比表示。
细节
- 入场:数据源等于多头/空头值且前一个值不同。
- 出场:反向信号或保护性止损。
- 止损:有,以百分比设置。
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>
/// Simple strategy based on source values equal to 1 or 2.
/// Uses short-term SMA crossover to classify candle close as signal 1 (bullish) or 2 (bearish).
/// </summary>
public class IsStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<bool> _reverse;
private readonly StrategyParam<bool> _enableShort;
private readonly StrategyParam<decimal> _profitPercent;
private readonly StrategyParam<decimal> _lossPercent;
private decimal _previousValue;
private SimpleMovingAverage _smaFast;
private SimpleMovingAverage _smaSlow;
/// <summary>
/// Candle type for processing.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Reverse trading direction.
/// </summary>
public bool Reverse
{
get => _reverse.Value;
set => _reverse.Value = value;
}
/// <summary>
/// Enable short selling.
/// </summary>
public bool EnableShort
{
get => _enableShort.Value;
set => _enableShort.Value = value;
}
/// <summary>
/// Take profit percent.
/// </summary>
public decimal ProfitPercent
{
get => _profitPercent.Value;
set => _profitPercent.Value = value;
}
/// <summary>
/// Stop loss percent.
/// </summary>
public decimal LossPercent
{
get => _lossPercent.Value;
set => _lossPercent.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public IsStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles used by the strategy", "General");
_reverse = Param(nameof(Reverse), false)
.SetDisplay("Reverse", "Reverse trading direction", "General");
_enableShort = Param(nameof(EnableShort), true)
.SetDisplay("Sell On", "Enable short selling", "General");
_profitPercent = Param(nameof(ProfitPercent), 1.5m)
.SetRange(0m, 30m)
.SetDisplay("Profit %", "Take profit percent", "Risk");
_lossPercent = Param(nameof(LossPercent), 1.5m)
.SetRange(0m, 30m)
.SetDisplay("Loss %", "Stop loss percent", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, CandleType);
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_previousValue = 0m;
_smaFast = null;
_smaSlow = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_smaFast = new SimpleMovingAverage { Length = 80 };
_smaSlow = new SimpleMovingAverage { Length = 200 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_smaFast, _smaSlow, ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(ProfitPercent, UnitTypes.Percent),
stopLoss: new Unit(LossPercent, UnitTypes.Percent),
isStopTrailing: false);
}
private void ProcessCandle(ICandleMessage candle, decimal fastVal, decimal slowVal)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
// Map price action to signal: 1 = bullish (fast > slow), 2 = bearish (fast < slow)
var hb5 = fastVal > slowVal ? 1m : 2m;
var ii = Reverse ? 2m : 1m;
var i2 = Reverse ? 1m : 2m;
var prev = _previousValue;
if (hb5 == ii && prev != ii)
{
if (Position < 0 && EnableShort)
BuyMarket(Position.Abs());
BuyMarket();
}
else if (hb5 == i2 && prev != i2)
{
if (Position > 0)
SellMarket(Position);
if (EnableShort)
SellMarket();
}
_previousValue = hb5;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class is_strategy(Strategy):
def __init__(self):
super(is_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles used by the strategy", "General")
self._reverse = self.Param("Reverse", False) \
.SetDisplay("Reverse", "Reverse trading direction", "General")
self._enable_short = self.Param("EnableShort", True) \
.SetDisplay("Sell On", "Enable short selling", "General")
self._profit_percent = self.Param("ProfitPercent", 1.5) \
.SetDisplay("Profit %", "Take profit percent", "Risk")
self._loss_percent = self.Param("LossPercent", 1.5) \
.SetDisplay("Loss %", "Stop loss percent", "Risk")
self._previous_value = 0.0
self._sma_fast = None
self._sma_slow = None
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(is_strategy, self).OnReseted()
self._previous_value = 0.0
self._sma_fast = None
self._sma_slow = None
def OnStarted2(self, time):
super(is_strategy, self).OnStarted2(time)
self._sma_fast = SimpleMovingAverage()
self._sma_fast.Length = 80
self._sma_slow = SimpleMovingAverage()
self._sma_slow.Length = 200
subscription = self.SubscribeCandles(self.candle_type)
subscription \
.Bind(self._sma_fast, self._sma_slow, self.ProcessCandle) \
.Start()
self.StartProtection(
takeProfit=Unit(self._profit_percent.Value, UnitTypes.Percent),
stopLoss=Unit(self._loss_percent.Value, UnitTypes.Percent),
isStopTrailing=False)
def ProcessCandle(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
# Map price action to signal: 1 = bullish (fast > slow), 2 = bearish (fast < slow)
hb5 = 1.0 if fast_val > slow_val else 2.0
ii = 2.0 if self._reverse.Value else 1.0
i2 = 1.0 if self._reverse.Value else 2.0
prev = self._previous_value
if hb5 == ii and prev != ii:
if self.Position < 0 and self._enable_short.Value:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket()
elif hb5 == i2 and prev != i2:
if self.Position > 0:
self.SellMarket(self.Position)
if self._enable_short.Value:
self.SellMarket()
self._previous_value = hb5
def CreateClone(self):
return is_strategy()