Стратегия торгует фиксированным набором основных валютных пар без использования технических индикаторов.
Для каждой пары алгоритм хранит направление и объем. После прибыльного движения объем увеличивается, после убытка направление переворачивается. Торговля прекращается и все позиции закрываются, когда общий профит или убыток превышает заданные пороговые значения.
Подробности
Условия входа:
При отсутствии позиции и достаточном балансе (Margin) открывается сделка в заранее выбранном направлении с объемом MinVolume.
Лонг/Шорт: Оба, в зависимости от внутреннего направления для пары.
Условия выхода:
Позиция закрывается при прибыли выше KClose * MinVolume.
При убытке больше KChange * текущий объем позиция закрывается и направление меняется.
Стопы: Явно не используются; риск контролируется порогами прибыли/убытка.
Значения по умолчанию:
Loss = 1900
Profit = 4000
Margin = 5000
MinVolume = 0.01
KChange = 2100
KClose = 4600
Фильтры:
Категория: Управление капиталом
Направление: Оба
Индикаторы: Нет
Стопы: Нет
Сложность: Средняя
Таймфрейм: Тиковый
Сезонность: Нет
Нейросети: Нет
Дивергенция: Нет
Уровень риска: Высокий
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>
/// Momentum flip strategy: trades in current momentum direction,
/// flips direction when loss threshold hit, adds on profit.
/// Adapted from multi-currency EA to single-security candle-based approach.
/// </summary>
public class ExpMulticStrategy : Strategy
{
private readonly StrategyParam<int> _period;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevMomentum;
public int Period { get => _period.Value; set => _period.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ExpMulticStrategy()
{
_period = Param(nameof(Period), 14)
.SetGreaterThanZero()
.SetDisplay("Period", "Momentum lookback period", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevMomentum = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var momentum = new Momentum { Length = Period };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(momentum, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
var area2 = CreateChartArea();
if (area2 != null)
DrawIndicator(area2, momentum);
}
}
private void ProcessCandle(ICandleMessage candle, decimal momentumValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
{
_prevMomentum = momentumValue;
return;
}
if (_prevMomentum is decimal prev)
{
// Momentum crosses above zero - buy
if (prev <= 0 && momentumValue > 0 && Position <= 0)
BuyMarket();
// Momentum crosses below zero - sell
else if (prev >= 0 && momentumValue < 0 && Position >= 0)
SellMarket();
}
_prevMomentum = momentumValue;
}
}
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 Momentum
from StockSharp.Algo.Strategies import Strategy
class exp_multic_strategy(Strategy):
def __init__(self):
super(exp_multic_strategy, self).__init__()
self._period = self.Param("Period", 14).SetDisplay("Period", "Momentum lookback period", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Timeframe", "General")
self._prev_momentum = None
@property
def period(self): return self._period.Value
@property
def candle_type(self): return self._candle_type.Value
def OnReseted(self):
super(exp_multic_strategy, self).OnReseted()
self._prev_momentum = None
def OnStarted2(self, time):
super(exp_multic_strategy, self).OnStarted2(time)
momentum = Momentum()
momentum.Length = self.period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(momentum, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
area2 = self.CreateChartArea()
if area2 is not None:
self.DrawIndicator(area2, momentum)
def process_candle(self, candle, momentum_value):
if candle.State != CandleStates.Finished: return
mv = float(momentum_value)
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_momentum = mv
return
if self._prev_momentum is not None:
if self._prev_momentum <= 0.0 and mv > 0.0 and self.Position <= 0:
self.BuyMarket()
elif self._prev_momentum >= 0.0 and mv < 0.0 and self.Position >= 0:
self.SellMarket()
self._prev_momentum = mv
def CreateClone(self): return exp_multic_strategy()