Стратегия Inside Candle
Стратегия ищет внутренние свечи и открывает позицию при пробое диапазона материнской свечи. Выход осуществляется по соотношению риск/прибыль.
Параметры
- Candle Type — таймфрейм используемых свечей.
- RR Ratio — соотношение риск/прибыль для расчета цели.
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Inside candle breakout strategy with risk/reward based exits.
/// Waits for an inside candle and trades breakouts of its range.
/// </summary>
public class InsideCandleStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _riskReward;
private ICandleMessage _previousCandle;
private decimal _insideHigh;
private decimal _insideLow;
private bool _waitingForBreakout;
private decimal _stopPrice;
private decimal _takeProfitPrice;
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Risk/reward ratio.
/// </summary>
public decimal RiskReward
{
get => _riskReward.Value;
set => _riskReward.Value = value;
}
/// <summary>
/// Initializes a new instance of the strategy.
/// </summary>
public InsideCandleStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_riskReward = Param(nameof(RiskReward), 2m)
.SetDisplay("RR Ratio", "Risk/reward ratio for exits", "Risk Management")
.SetOptimize(0.5m, 5m, 0.5m);
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, CandleType);
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_previousCandle = null;
_waitingForBreakout = false;
_insideHigh = 0m;
_insideLow = 0m;
_stopPrice = 0m;
_takeProfitPrice = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
StartProtection(null, null);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
if (Position > 0 && _stopPrice != 0m && _takeProfitPrice != 0m)
{
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _takeProfitPrice)
{
SellMarket();
_stopPrice = 0m;
_takeProfitPrice = 0m;
}
}
else if (Position < 0 && _stopPrice != 0m && _takeProfitPrice != 0m)
{
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _takeProfitPrice)
{
BuyMarket();
_stopPrice = 0m;
_takeProfitPrice = 0m;
}
}
if (_previousCandle != null)
{
if (_waitingForBreakout)
{
if (candle.ClosePrice > _insideHigh)
{
BuyMarket();
var entry = candle.ClosePrice;
_stopPrice = _insideLow;
_takeProfitPrice = entry + (entry - _insideLow) * RiskReward;
_waitingForBreakout = false;
}
else if (candle.ClosePrice < _insideLow)
{
SellMarket();
var entry = candle.ClosePrice;
_stopPrice = _insideHigh;
_takeProfitPrice = entry - (_insideHigh - entry) * RiskReward;
_waitingForBreakout = false;
}
else
{
_waitingForBreakout = false;
}
}
else if (candle.HighPrice < _previousCandle.HighPrice && candle.LowPrice > _previousCandle.LowPrice)
{
_insideHigh = _previousCandle.HighPrice;
_insideLow = _previousCandle.LowPrice;
_waitingForBreakout = true;
}
}
_previousCandle = candle;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
class inside_candle_strategy(Strategy):
def __init__(self):
super(inside_candle_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(60))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._risk_reward = self.Param("RiskReward", 2.0) \
.SetDisplay("RR Ratio", "Risk/reward ratio for exits", "Risk Management")
self._prev_candle_high = 0.0
self._prev_candle_low = 0.0
self._prev_candle_set = False
self._inside_high = 0.0
self._inside_low = 0.0
self._waiting_for_breakout = False
self._stop_price = 0.0
self._take_profit_price = 0.0
@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(inside_candle_strategy, self).OnReseted()
self._prev_candle_high = 0.0
self._prev_candle_low = 0.0
self._prev_candle_set = False
self._waiting_for_breakout = False
self._inside_high = 0.0
self._inside_low = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
def OnStarted2(self, time):
super(inside_candle_strategy, self).OnStarted2(time)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def OnProcess(self, candle):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
rr = float(self._risk_reward.Value)
if self.Position > 0 and self._stop_price != 0 and self._take_profit_price != 0:
if low <= self._stop_price or high >= self._take_profit_price:
self.SellMarket()
self._stop_price = 0.0
self._take_profit_price = 0.0
elif self.Position < 0 and self._stop_price != 0 and self._take_profit_price != 0:
if high >= self._stop_price or low <= self._take_profit_price:
self.BuyMarket()
self._stop_price = 0.0
self._take_profit_price = 0.0
if self._prev_candle_set:
if self._waiting_for_breakout:
if close > self._inside_high:
self.BuyMarket()
entry = close
self._stop_price = self._inside_low
self._take_profit_price = entry + (entry - self._inside_low) * rr
self._waiting_for_breakout = False
elif close < self._inside_low:
self.SellMarket()
entry = close
self._stop_price = self._inside_high
self._take_profit_price = entry - (self._inside_high - entry) * rr
self._waiting_for_breakout = False
else:
self._waiting_for_breakout = False
elif high < self._prev_candle_high and low > self._prev_candle_low:
self._inside_high = self._prev_candle_high
self._inside_low = self._prev_candle_low
self._waiting_for_breakout = True
self._prev_candle_high = high
self._prev_candle_low = low
self._prev_candle_set = True
def CreateClone(self):
return inside_candle_strategy()