Auf GitHub ansehen

Alligator Simple Strategy

Overview

The Alligator Simple strategy recreates the MetaTrader "Alligator Simple v1.0" expert advisor using StockSharp's high-level API. It reads the Bill Williams Alligator indicator on finished candles and opens a position when the Lips, Teeth, and Jaw lines expand in the same direction on the previous completed bar. Every trade can optionally include pip-based stop-loss, take-profit, and trailing stop management that mirrors the original MQL implementation.

Indicators and Data

  • Alligator lines: three Smoothed Moving Averages (SMMA) calculated on the candle median price (high + low) / 2 with configurable lengths and forward shifts for the Jaw, Teeth, and Lips.
  • Candles: the strategy subscribes to a single configurable CandleType (one-hour candles by default) and only processes finished candles to avoid look-ahead bias.

Trade Logic

  1. Signal evaluation
    • Retrieve the shifted Alligator values for the previous completed candle.
    • Long signal: Lips[t-1] > Teeth[t-1] > Jaw[t-1].
    • Short signal: Lips[t-1] < Teeth[t-1] < Jaw[t-1].
  2. Execution
    • Enter the market with OrderVolume when no position is open.
    • Only one position is held at a time; opposite signals are ignored until the current position is closed.

Exit and Risk Management

  • Initial stop-loss: if StopLossPips > 0, the strategy offsets the fill price by the pip distance converted with the instrument's price step (including the 3/5-digit pip multiplier used by MetaTrader symbols).
  • Take-profit: when TakeProfitPips > 0, a profit target is placed symmetrically around the entry price. A zero value disables the target.
  • Trailing stop: when both TrailingStopPips and TrailingStepPips are positive, the stop is advanced to close − TrailingStop (longs) or close + TrailingStop (shorts) once price has moved at least TrailingStop + TrailingStep in favor of the trade. Trailing updates rely on the candle high/low to simulate intrabar touches.
  • Exit handling: stop-loss, take-profit, and trailing conditions issue market orders to flatten the position and are evaluated on every finished candle.

Parameters

  • OrderVolume (default 1): trade size in lots or contracts.
  • StopLossPips (default 100): initial stop-loss distance in pips. Set to zero to disable.
  • TakeProfitPips (default 100): take-profit distance in pips. Set to zero to disable.
  • TrailingStopPips (default 5): trailing stop distance in pips. Zero disables trailing.
  • TrailingStepPips (default 5): extra pip distance that price must travel before the trailing stop advances. Must be positive when trailing is enabled.
  • JawPeriod, TeethPeriod, LipsPeriod: SMMA lengths for the jaw, teeth, and lips (defaults 13/8/5).
  • JawShift, TeethShift, LipsShift: forward shifts applied when reading Alligator values (defaults 8/5/3).
  • CandleType: candle data type/time frame for calculations (default one-hour candles).

Implementation Notes

  • Pip distances automatically adapt to the security's tick size. Instruments with three or five decimals multiply the price step by ten to replicate the MetaTrader pip definition.
  • Indicator history buffers store enough values to respect the configured forward shifts, eliminating manual array manipulation.
  • The strategy uses BuyMarket and SellMarket helpers to submit orders, keeping the code focused on signal generation and risk handling.
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>
/// Simplified Bill Williams Alligator breakout strategy.
/// Buys when Lips > Teeth > Jaw (upward expansion).
/// Sells when Lips less than Teeth less than Jaw (downward expansion).
/// Uses stop-loss and take-profit for risk management.
/// </summary>
public class AlligatorSimpleStrategy : Strategy
{
	private readonly StrategyParam<int> _jawPeriod;
	private readonly StrategyParam<int> _teethPeriod;
	private readonly StrategyParam<int> _lipsPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private SmoothedMovingAverage _jaw;
	private SmoothedMovingAverage _teeth;
	private SmoothedMovingAverage _lips;

	private decimal _entryPrice;
	private int _cooldown;

	/// <summary>
	/// Period for the Alligator jaw (blue) smoothed moving average.
	/// </summary>
	public int JawPeriod
	{
		get => _jawPeriod.Value;
		set => _jawPeriod.Value = value;
	}

	/// <summary>
	/// Period for the Alligator teeth (red) smoothed moving average.
	/// </summary>
	public int TeethPeriod
	{
		get => _teethPeriod.Value;
		set => _teethPeriod.Value = value;
	}

	/// <summary>
	/// Period for the Alligator lips (green) smoothed moving average.
	/// </summary>
	public int LipsPeriod
	{
		get => _lipsPeriod.Value;
		set => _lipsPeriod.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>
	/// Initialize <see cref="AlligatorSimpleStrategy"/>.
	/// </summary>
	public AlligatorSimpleStrategy()
	{
		_jawPeriod = Param(nameof(JawPeriod), 13)
			.SetGreaterThanZero()
			.SetDisplay("Jaw Period", "Alligator jaw period", "Alligator");

		_teethPeriod = Param(nameof(TeethPeriod), 8)
			.SetGreaterThanZero()
			.SetDisplay("Teeth Period", "Alligator teeth period", "Alligator");

		_lipsPeriod = Param(nameof(LipsPeriod), 5)
			.SetGreaterThanZero()
			.SetDisplay("Lips Period", "Alligator lips period", "Alligator");

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

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400)
			.SetNotNegative()
			.SetDisplay("Take Profit", "Take-profit distance 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();

		_jaw = null;
		_teeth = null;
		_lips = null;
		_entryPrice = 0;
		_cooldown = 0;
	}

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

		_jaw = new SmoothedMovingAverage { Length = JawPeriod };
		_teeth = new SmoothedMovingAverage { Length = TeethPeriod };
		_lips = new SmoothedMovingAverage { Length = LipsPeriod };

		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_jaw, _teeth, _lips, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal jawValue, decimal teethValue, decimal lipsValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (!_jaw.IsFormed || !_teeth.IsFormed || !_lips.IsFormed)
			return;

		if (_cooldown > 0)
		{
			_cooldown--;
			return;
		}

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

		// Check SL/TP for existing positions
		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 110;
				return;
			}

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

			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 110;
				return;
			}
		}

		// Buy when lips > teeth > jaw (Alligator opening upward)
		if (lipsValue > teethValue && teethValue > jawValue && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();

			BuyMarket();
			_entryPrice = close;
			_cooldown = 110;
		}
		// Sell when lips < teeth < jaw (Alligator opening downward)
		else if (lipsValue < teethValue && teethValue < jawValue && Position >= 0)
		{
			if (Position > 0)
				SellMarket();

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