Estrategia de Robot Autónomo de 5 Minutos
La estrategia de Robot Autónomo de 5 Minutos opera en un marco temporal de 5 minutos. Abre una posición larga cuando el precio está en tendencia alcista y la presión compradora supera a la vendedora, y abre una posición corta en condiciones opuestas.
Detalles
- Criterios de entrada: Tendencia alcista (cierre por encima de la SMA de 50 períodos y por encima del cierre de 6 barras atrás) con volumen comprador mayor que el vendedor.
- Criterios de salida: Reversión de posición ante señal opuesta.
- Stops: Stop-loss del 3% y take profit del 29% desde el precio de entrada.
- Valores predeterminados:
MaLength= 50VolumeLength= 10StopLossPercent= 3TakeProfitPercent= 29CandleType= 5m
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>
/// Autonomous 5-minute robot strategy.
/// Buy volume is the volume of up candles and sell volume the volume of down candles over the last VolumeLength candles. A close
/// above the SMA and above the close 6 candles ago with buy volume above sell volume goes long; a close below the SMA and below
/// the close 6 candles ago with sell volume above buy volume goes short, reversing an opposite position. Percent stop-loss and
/// take-profit protect every position.
/// </summary>
public class Autonomous5MinuteRobotStrategy : Strategy
{
private const int _momentumBars = 6;
private readonly StrategyParam<int> _maLength;
private readonly StrategyParam<int> _volumeLength;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<decimal> _takeProfitPercent;
private readonly StrategyParam<DataType> _candleType;
private readonly List<decimal> _closes = [];
private readonly List<(decimal buy, decimal sell)> _volumes = [];
/// <summary>
/// SMA period.
/// </summary>
public int MaLength
{
get => _maLength.Value;
set => _maLength.Value = value;
}
/// <summary>
/// Candles over which buy and sell volume are summed.
/// </summary>
public int VolumeLength
{
get => _volumeLength.Value;
set => _volumeLength.Value = value;
}
/// <summary>
/// Stop-loss percentage.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Take-profit percentage.
/// </summary>
public decimal TakeProfitPercent
{
get => _takeProfitPercent.Value;
set => _takeProfitPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public Autonomous5MinuteRobotStrategy()
{
_maLength = Param(nameof(MaLength), 50)
.SetGreaterThanZero()
.SetDisplay("MA Length", "SMA period", "Trend");
_volumeLength = Param(nameof(VolumeLength), 10)
.SetGreaterThanZero()
.SetDisplay("Volume Length", "Candles over which buy and sell volume are summed", "Volume");
_stopLossPercent = Param(nameof(StopLossPercent), 3m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop-loss percentage", "Risk");
_takeProfitPercent = Param(nameof(TakeProfitPercent), 29m)
.SetNotNegative()
.SetDisplay("Take Profit %", "Take-profit percentage", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_closes.Clear();
_volumes.Clear();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_closes.Clear();
_volumes.Clear();
var sma = new SimpleMovingAverage { Length = MaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, ProcessCandle)
.Start();
StartProtection(
TakeProfitPercent > 0m ? new Unit(TakeProfitPercent, UnitTypes.Percent) : new Unit(),
StopLossPercent > 0m ? new Unit(StopLossPercent, UnitTypes.Percent) : new Unit(),
useMarketOrders: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal sma)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
var volume = candle.TotalVolume;
_closes.Add(close);
if (_closes.Count > _momentumBars + 1)
_closes.RemoveAt(0);
_volumes.Add((close > candle.OpenPrice ? volume : 0m, close < candle.OpenPrice ? volume : 0m));
if (_volumes.Count > VolumeLength)
_volumes.RemoveAt(0);
if (_closes.Count <= _momentumBars || _volumes.Count < VolumeLength)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var buyVolume = 0m;
var sellVolume = 0m;
foreach (var (buy, sell) in _volumes)
{
buyVolume += buy;
sellVolume += sell;
}
var pastClose = _closes[0];
if (close > sma && close > pastClose && buyVolume > sellVolume && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (close < sma && close < pastClose && sellVolume > buyVolume && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
MOMENTUM_BARS = 6
class autonomous_5_minute_robot_strategy(Strategy):
"""
Autonomous 5-minute robot strategy.
Buy volume is the volume of up candles and sell volume the volume of down candles over the last VolumeLength candles. A close
above the SMA and above the close 6 candles ago with buy volume above sell volume goes long; a close below the SMA and below
the close 6 candles ago with sell volume above buy volume goes short, reversing an opposite position. Percent stop-loss and
take-profit protect every position.
"""
def __init__(self):
super(autonomous_5_minute_robot_strategy, self).__init__()
self._ma_length = self.Param("MaLength", 50) \
.SetGreaterThanZero() \
.SetDisplay("MA Length", "SMA period", "Trend")
self._volume_length = self.Param("VolumeLength", 10) \
.SetGreaterThanZero() \
.SetDisplay("Volume Length", "Candles over which buy and sell volume are summed", "Volume")
self._stop_loss_percent = self.Param("StopLossPercent", 3.0) \
.SetNotNegative() \
.SetDisplay("Stop Loss %", "Stop-loss percentage", "Risk")
self._take_profit_percent = self.Param("TakeProfitPercent", 29.0) \
.SetNotNegative() \
.SetDisplay("Take Profit %", "Take-profit percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._closes = []
self._volumes = []
@property
def CandleType(self):
return self._candle_type.Value
def GetWorkingSecurities(self):
return [(self.Security, self.CandleType)]
def OnReseted(self):
super(autonomous_5_minute_robot_strategy, self).OnReseted()
self._closes = []
self._volumes = []
def OnStarted2(self, time):
super(autonomous_5_minute_robot_strategy, self).OnStarted2(time)
self._closes = []
self._volumes = []
sma = SimpleMovingAverage()
sma.Length = self._ma_length.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(sma, self._process_candle).Start()
take = float(self._take_profit_percent.Value)
stop = float(self._stop_loss_percent.Value)
self.StartProtection(
Unit(Decimal(take), UnitTypes.Percent) if take > 0 else Unit(),
Unit(Decimal(stop), UnitTypes.Percent) if stop > 0 else Unit(),
useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawOwnTrades(area)
def _process_candle(self, candle, sma_value):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
open_price = float(candle.OpenPrice)
volume = float(candle.TotalVolume)
self._closes.append(close)
if len(self._closes) > MOMENTUM_BARS + 1:
self._closes.pop(0)
self._volumes.append((volume if close > open_price else 0.0, volume if close < open_price else 0.0))
volume_length = self._volume_length.Value
if len(self._volumes) > volume_length:
self._volumes.pop(0)
if len(self._closes) <= MOMENTUM_BARS or len(self._volumes) < volume_length:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
buy_volume = sum(v[0] for v in self._volumes)
sell_volume = sum(v[1] for v in self._volumes)
past_close = self._closes[0]
sma = float(sma_value)
if close > sma and close > past_close and buy_volume > sell_volume and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif close < sma and close < past_close and sell_volume > buy_volume and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return autonomous_5_minute_robot_strategy()