在 GitHub 上查看

Vlado 策略

基于 Larry Williams %R 指标的动量反转策略。系统等待指标进入深度超卖或超买区,然后在下一根收盘蜡烛上完成持仓翻转。此 StockSharp 版本完整保留 MetaTrader 脚本的核心思路,并把关键参数全部开放给使用者调整。

概览

  • 类型:振荡器驱动的逆势策略。
  • 适用市场:提供稳定蜡烛数据的高流动性品种,例如外汇主流货币对、指数期货、加密货币现货。
  • 时间框架:通过 CandleType 参数配置,默认使用 1 小时蜡烛,与原脚本一致。
  • 持仓方向:支持多头与空头,只会在任意时刻保持一个仓位,出现反向信号时自动翻仓。
  • 核心指标:Williams %R,可自定义计算周期及阈值。

工作原理

  1. 订阅指定的蜡烛序列,并在每根收盘蜡烛上计算 Williams %R。
  2. 默认超卖阈值为 -75,超买阈值为 -25(该指标数值区间位于 -100 到 0 之间)。
  3. %R <= OversoldLevel 时,策略在下一根收盘后建立或翻转为多头仓位。
  4. %R >= OverboughtLevel 时,策略建立或翻转为空头仓位。
  5. 下单数量为 Volume + Math.Abs(Position),意味着翻仓时会用单笔市价单完成平旧仓与开新仓。
  6. 策略未内置止损止盈,风险控制依赖阈值、时间框架及外部资金管理。
  7. 所有信号均通过 LogInfo 输出,方便在 StockSharp 前端或日志文件中复盘。

参数说明

  • WilliamsPeriod:指标计算周期,数值越大越平滑,越小越敏感。
  • OverboughtLevel:判定超买的阈值(默认 -25),支持优化。
  • OversoldLevel:判定超卖的阈值(默认 -75),支持优化。
  • CandleType:用于计算的蜡烛类型与时间框架,可选择时间、成交量或区间蜡烛。
  • Volume(继承自 Strategy):基础下单手数,需根据账户规模与风险承受力自行设定。

交易规则

  • 做多条件%R <= OversoldLevel 且当前仓位为空或做空。
  • 做空条件%R >= OverboughtLevel 且当前仓位为空或做多。
  • 离场方式:出现反向信号时直接翻仓,相当于同时完成出场与进场。
  • 仓位管理:策略不做加仓或分批出场,始终保持单一仓位。

额外提示

  • 更适合区间或震荡市况,若市场快速单边运行需要配合其他过滤器使用。
  • 建议在实盘中额外叠加资金止损、交易时段限制等风险管理模块。
  • 实现包含图表输出:主图绘制蜡烛与成交,副图展示 Williams %R 曲线。
  • 所有关键参数均已允许在 StockSharp 优化器中进行批量测试。
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>
/// Vlado momentum strategy using EMA crossover.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class VladoStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	/// <summary>
	/// Fast EMA period.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow EMA period.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <summary>
	/// Stop-loss distance in price steps.
	/// </summary>
	public int StopLossPoints
	{
		get => _stopLossPoints.Value;
		set => _stopLossPoints.Value = value;
	}

	/// <summary>
	/// Take-profit distance in price steps.
	/// </summary>
	public int TakeProfitPoints
	{
		get => _takeProfitPoints.Value;
		set => _takeProfitPoints.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="VladoStrategy"/> class.
	/// </summary>
	public VladoStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast EMA period", "Indicator");

		_slowPeriod = Param(nameof(SlowPeriod), 50)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Slow EMA period", "Indicator");

		_stopLossPoints = Param(nameof(StopLossPoints), 200)
			.SetNotNegative()
			.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400)
			.SetNotNegative()
			.SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_fast = null;
		_slow = null;
		_prevFast = 0;
		_prevSlow = 0;
		_entryPrice = 0;
		_cooldown = 0;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };

		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (!_fast.IsFormed || !_slow.IsFormed)
		{
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		if (_cooldown > 0)
		{
			_cooldown--;
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		// Check SL/TP
		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}

		// EMA crossover
		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();

			BuyMarket();
			_entryPrice = close;
			_cooldown = 80;
		}
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{
			if (Position > 0)
				SellMarket();

			SellMarket();
			_entryPrice = close;
			_cooldown = 80;
		}

		_prevFast = fastValue;
		_prevSlow = slowValue;
	}
}