在 GitHub 上查看

Artificial Intelligence Accelerator 策略

该策略使用比尔·威廉姆斯的**加速/减速振荡器(AC)**构建一个简单的感知器模型。策略提取0、7、14、21根K线的AC值,与可调权重相乘并求和作为信号。信号大于零表示看涨动能,信号小于零表示看跌动能。当信号变号时策略会反向持仓,并在入场价格设置固定止损。

AC源自超强振荡器(AO),即AO减去5周期移动平均,使得策略对市场加速度变化更敏感。

详情

  • 入场条件
    • 多头:感知器信号 > 0。
    • 空头:感知器信号 < 0。
  • 多空方向:双向,信号翻转时反向。
  • 出场条件
    • 达到固定止损。
    • 信号穿越零点时反向。
  • 止损:是,按价格单位固定止损。
  • 默认值
    • X1 = 76
    • X2 = 47
    • X3 = 153
    • X4 = 135
    • StopLoss = 8355
    • CandleType = 1分钟K线
  • 过滤器
    • 类型:趋势跟随
    • 方向:双向
    • 指标:AC(源自AO)
    • 止损:有
    • 复杂度:中等
    • 时间框架:短期
    • 神经网络:感知器
    • 风险等级:高
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>
/// Perceptron-based strategy using Acceleration/Deceleration values.
/// </summary>
public class ArtificialIntelligenceAcceleratorStrategy : Strategy
{
	private readonly StrategyParam<int> _x1;
	private readonly StrategyParam<int> _x2;
	private readonly StrategyParam<int> _x3;
	private readonly StrategyParam<int> _x4;
	private readonly StrategyParam<decimal> _stopLoss;
	private readonly StrategyParam<DataType> _candleType;

	private SimpleMovingAverage _aoFast;
	private SimpleMovingAverage _aoSlow;
	private SimpleMovingAverage _acMa;

	private readonly decimal[] _acBuffer = new decimal[22];
	private int _bufferCount;
	private decimal _entryPrice;
	private decimal? _prevSignal;
	private int _barsSinceTrade;

	/// <summary>
	/// First weight of perceptron.
	/// </summary>
	public int X1 { get => _x1.Value; set => _x1.Value = value; }

	/// <summary>
	/// Second weight of perceptron.
	/// </summary>
	public int X2 { get => _x2.Value; set => _x2.Value = value; }

	/// <summary>
	/// Third weight of perceptron.
	/// </summary>
	public int X3 { get => _x3.Value; set => _x3.Value = value; }

	/// <summary>
	/// Fourth weight of perceptron.
	/// </summary>
	public int X4 { get => _x4.Value; set => _x4.Value = value; }

	/// <summary>
	/// Stop loss in price units.
	/// </summary>
	public decimal StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }

	/// <summary>
	/// Candle series type.
	/// </summary>
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	/// <summary>
	/// Initializes a new instance of <see cref="ArtificialIntelligenceAcceleratorStrategy"/>.
	/// </summary>
	public ArtificialIntelligenceAcceleratorStrategy()
	{
		_x1 = Param(nameof(X1), 76)
			.SetDisplay("X1", "Perceptron weight 1", "Parameters");
		_x2 = Param(nameof(X2), 47)
			.SetDisplay("X2", "Perceptron weight 2", "Parameters");
		_x3 = Param(nameof(X3), 153)
			.SetDisplay("X3", "Perceptron weight 3", "Parameters");
		_x4 = Param(nameof(X4), 135)
			.SetDisplay("X4", "Perceptron weight 4", "Parameters");

		_stopLoss = Param(nameof(StopLoss), 8355m)
			.SetDisplay("Stop Loss", "Stop loss in price units", "Risk");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

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

		Array.Clear(_acBuffer);
		_bufferCount = 0;
		_entryPrice = 0m;
		_prevSignal = null;
		_barsSinceTrade = 10;
		_aoFast = null;
		_aoSlow = null;
		_acMa = null;
	}

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

		Array.Clear(_acBuffer);
		_bufferCount = 0;
		_entryPrice = 0m;
		_prevSignal = null;
		_barsSinceTrade = 10;
		_aoFast = new SimpleMovingAverage { Length = 5 };
		_aoSlow = new SimpleMovingAverage { Length = 34 };
		_acMa = new SimpleMovingAverage { Length = 5 };

		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(ProcessCandle).Start();
	}

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

		_barsSinceTrade++;

		// Calculate Accelerator Oscillator value.
		var hl2 = (candle.HighPrice + candle.LowPrice) / 2m;
		var t = candle.ServerTime;

		var aoFastResult = _aoFast.Process(hl2, t, true);
		var aoSlowResult = _aoSlow.Process(hl2, t, true);
		if (!_aoFast.IsFormed || !_aoSlow.IsFormed)
			return;

		var ao = aoFastResult.ToDecimal() - aoSlowResult.ToDecimal();

		var acMaResult = _acMa.Process(ao, t, true);
		if (!_acMa.IsFormed)
			return;

		var ac = ao - acMaResult.ToDecimal();

		for (var i = 21; i > 0; i--)
			_acBuffer[i] = _acBuffer[i - 1];
		_acBuffer[0] = ac;
		if (_bufferCount < 22)
		{
			_bufferCount++;
			return;
		}

		var signal = Perceptron();
		var previousSignal = _prevSignal;
		_prevSignal = signal;

		if (previousSignal is null)
			return;

		if (_barsSinceTrade >= 5 && previousSignal <= 0m && signal > 0m && Position <= 0)
		{
			BuyMarket();
			_entryPrice = candle.ClosePrice;
			_barsSinceTrade = 0;
		}
		else if (_barsSinceTrade >= 5 && previousSignal >= 0m && signal < 0m && Position >= 0)
		{
			SellMarket();
			_entryPrice = candle.ClosePrice;
			_barsSinceTrade = 0;
		}
		else if (Position > 0 && candle.ClosePrice <= _entryPrice - StopLoss)
		{
			SellMarket();
			_barsSinceTrade = 0;
		}
		else if (Position < 0 && candle.ClosePrice >= _entryPrice + StopLoss)
		{
			BuyMarket();
			_barsSinceTrade = 0;
		}
	}

	private decimal Perceptron()
	{
		var w1 = X1 - 100m;
		var w2 = X2 - 100m;
		var w3 = X3 - 100m;
		var w4 = X4 - 100m;

		return w1 * _acBuffer[0] + w2 * _acBuffer[7] + w3 * _acBuffer[14] + w4 * _acBuffer[21];
	}
}