在 GitHub 上查看

Renko 线图策略

该策略模拟经典的 Renko 砖图,并在砖块方向变化时进行交易。代码源自 MetaTrader 脚本 RenkoLiveChart_v600

逻辑

策略使用已经完成的时间 K 线构建 Renko 砖块。当价格相对上一个砖块价格移动不少于设置的砖块大小时,就形成一个新砖块。向上的砖块开多单,向下的砖块开空单。

参数

  • Candle Type – 用于构建砖块的输入 K 线周期。
  • Brick Size – 定义 Renko 砖块高度的价格步长。
  • Brick Offset – 应用于第一个砖块的初始偏移量(以砖块数表示)。
  • Show Wicks – 在图表上绘制蜡烛时是否显示影线。

说明

  • 仅在 K 线收盘后执行交易。
  • 策略启动时自动开启仓位保护。
  • 本实现仅关注 Renko 的核心行为,未包含原脚本中的文件操作等高级特性。
using System;
using System.Collections.Generic;

using Ecng.Common;

using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Renko live chart emulation strategy.
/// </summary>
public class RenkoLiveChartStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _brickSize;

	private decimal _renkoPrice;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public decimal BrickSize { get => _brickSize.Value; set => _brickSize.Value = value; }

	public RenkoLiveChartStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Working candle timeframe", "General");

		_brickSize = Param(nameof(BrickSize), 500m)
			.SetGreaterThanZero()
			.SetDisplay("Brick Size", "Renko brick size", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_renkoPrice = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		SubscribeCandles(CandleType).Bind(ProcessCandle).Start();
	}

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

		var close = candle.ClosePrice;
		var size = BrickSize;

		if (_renkoPrice == 0m)
		{
			_renkoPrice = close;
			return;
		}

		var diff = close - _renkoPrice;
		if (Math.Abs(diff) < size)
			return;

		var direction = Math.Sign(diff);
		_renkoPrice += direction * size;

		if (direction > 0 && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (direction < 0 && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}
	}
}