Estrategia de Fuerza Promedio
La estrategia de Fuerza Promedio utiliza un oscilador que mide dónde se ubica el cierre dentro del máximo más alto y el mínimo más bajo de un período de referencia, y suaviza el resultado con una media móvil. Los valores positivos señalan presión alcista mientras que los valores negativos muestran fuerza bajista.
La estrategia abre una posición larga cuando el valor suavizado de la Fuerza Promedio está por encima de cero y abre una posición corta cuando está por debajo de cero.
Detalles
- Criterios de entrada:
- Average Force > 0 → Comprar.
- Average Force < 0 → Vender.
- Largo/Corto: Ambas posiciones largas y cortas.
- Criterios de salida:
- La posición se invierte cuando la Fuerza Promedio cruza cero en dirección opuesta.
- Stops: Ninguno.
- Valores predeterminados:
Period= 18Smooth= 6
- Filtros:
- Categoría: Momentum
- Dirección: Ambos
- Indicadores: Highest, Lowest, SMA
- Stops: No
- Complejidad: Bajo
- Marco temporal: Cualquiera
- Estacionalidad: No
- Redes neuronales: No
- Divergencia: No
- Nivel de riesgo: Bajo
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>
/// Average Force strategy.
/// The raw force is the position of the close inside the highest high and lowest low of the last Period candles, centred on zero
/// ((close - lowest) / (highest - lowest) - 0.5), and the Average Force is its SMA over Smooth candles. A positive Average
/// Force holds a long and a negative one holds a short, so the position reverses whenever it crosses zero.
/// </summary>
public class AverageForceStrategy : Strategy
{
private readonly StrategyParam<int> _period;
private readonly StrategyParam<int> _smooth;
private readonly StrategyParam<DataType> _candleType;
private SimpleMovingAverage _forceAverage;
/// <summary>
/// Lookback of the highest high and lowest low.
/// </summary>
public int Period
{
get => _period.Value;
set => _period.Value = value;
}
/// <summary>
/// SMA period of the force.
/// </summary>
public int Smooth
{
get => _smooth.Value;
set => _smooth.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public AverageForceStrategy()
{
_period = Param(nameof(Period), 18)
.SetGreaterThanZero()
.SetDisplay("Period", "Lookback of the highest high and lowest low", "Indicator");
_smooth = Param(nameof(Smooth), 6)
.SetGreaterThanZero()
.SetDisplay("Smooth", "SMA period of the force", "Indicator");
_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)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_forceAverage = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var highest = new Highest { Length = Period };
var lowest = new Lowest { Length = Period };
_forceAverage = new SimpleMovingAverage { Length = Smooth };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(highest, lowest, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal highest, decimal lowest)
{
if (candle.State != CandleStates.Finished)
return;
var range = highest - lowest;
var force = range > 0m ? (candle.ClosePrice - lowest) / range - 0.5m : 0m;
var averageForce = _forceAverage.Process(force, candle.ServerTime, true).ToDecimal();
if (!_forceAverage.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (averageForce > 0m && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (averageForce < 0m && 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
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import Highest, Lowest, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class average_force_strategy(Strategy):
"""
Average Force strategy.
The raw force is the position of the close inside the highest high and lowest low of the last Period candles, centred on zero
((close - lowest) / (highest - lowest) - 0.5), and the Average Force is its SMA over Smooth candles. A positive Average
Force holds a long and a negative one holds a short, so the position reverses whenever it crosses zero.
"""
def __init__(self):
super(average_force_strategy, self).__init__()
self._period = self.Param("Period", 18) \
.SetGreaterThanZero() \
.SetDisplay("Period", "Lookback of the highest high and lowest low", "Indicator")
self._smooth = self.Param("Smooth", 6) \
.SetGreaterThanZero() \
.SetDisplay("Smooth", "SMA period of the force", "Indicator")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._force_average = None
@property
def CandleType(self):
return self._candle_type.Value
def GetWorkingSecurities(self):
return [(self.Security, self.CandleType)]
def OnReseted(self):
super(average_force_strategy, self).OnReseted()
self._force_average = None
def OnStarted2(self, time):
super(average_force_strategy, self).OnStarted2(time)
highest = Highest()
highest.Length = self._period.Value
lowest = Lowest()
lowest.Length = self._period.Value
self._force_average = SimpleMovingAverage()
self._force_average.Length = self._smooth.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(highest, lowest, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def _process_candle(self, candle, highest_value, lowest_value):
if candle.State != CandleStates.Finished:
return
highest = float(highest_value)
lowest = float(lowest_value)
value_range = highest - lowest
force = (float(candle.ClosePrice) - lowest) / value_range - 0.5 if value_range > 0 else 0.0
average_force = float(to_decimal(process_float(self._force_average, force, candle.ServerTime, True)))
if not self._force_average.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
if average_force > 0 and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif average_force < 0 and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return average_force_strategy()