Adding a trailing average true range stop loss to my SMA strategy
Adding a trailing average true range stop loss to my SMA strategy
18 Nov 2020, 21:18
Hello lovely people of Ctrader,
I am having issues with adding an ATR stop loss to my algorithm. it is sending me nutty. I am still a newbie to ctrader and i do not have an awful lot of coding experience. I have been able to add a regular stop loss to my code but i wish to add a ATR to my code, so that my trade will automatically cash out once it hits a certain atr value in terms of the stop loss. Any help will be greatly appreciated!
// -------------------------------------------------------------------------------------------------
//
SMA Crossover wuith ATR stop loss
//
// -------------------------------------------------------------------------------------------------
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class SampleTrendcBot : Robot
{
[Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
public double Quantity { get; set; }
[Parameter("MA Type", Group = "Moving Average")]
public MovingAverageType MAType { get; set; }
[Parameter("Source", Group = "Moving Average")]
public DataSeries SourceSeries { get; set; }
[Parameter("Slow Periods", Group = "Moving Average", DefaultValue = 10)]
public int SlowPeriods { get; set; }
[Parameter("Fast Periods", Group = "Moving Average", DefaultValue = 5)]
public int FastPeriods { get; set; }
[Parameter("Stop Loss (pips)", Group = "Protection", DefaultValue = 20, MinValue = 1)]
public int StopLossInPips { get; set; }
private MovingAverage slowMa;
private MovingAverage fastMa;
private const string label = "Sample Trend cBot";
protected override void OnStart()
{
fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType);
slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType);
}
protected override void OnTick()
{
var longPosition = Positions.Find(label, SymbolName, TradeType.Buy);
var shortPosition = Positions.Find(label, SymbolName, TradeType.Sell);
var currentSlowMa = slowMa.Result.Last(0);
var currentFastMa = fastMa.Result.Last(0);
var previousSlowMa = slowMa.Result.Last(1);
var previousFastMa = fastMa.Result.Last(1);
if (previousSlowMa > previousFastMa && currentSlowMa <= currentFastMa && longPosition == null)
{
if (shortPosition != null)
ClosePosition(shortPosition);
ExecuteMarketOrder(TradeType.Buy, SymbolName, VolumeInUnits, label, StopLossInPips, null);
}
else if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa && shortPosition == null)
{
if (longPosition != null)
ClosePosition(longPosition);
ExecuteMarketOrder(TradeType.Sell, SymbolName, VolumeInUnits, label, StopLossInPips, null);
}
}
private double VolumeInUnits
{
get { return Symbol.QuantityToVolumeInUnits(Quantity); }
}
}
}