Cant get Trailing StopLoss Working
Cant get Trailing StopLoss Working
04 Feb 2024, 18:31
Hi first and foremost I would like to apologise if this is in the wrong section of the website :)
For the life of me i cannot get the trailing stop loss to work when i run a backtest the only variables that change the outcome of the cbot is take profit and stop loss this is really confusing me now im very new to coding ive spent a full day on this now before coming here lol i tried, could someone please explain what ive done wrong and how to correct it please?
any help would be very much appreciated thankyou in advance
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ADXCrossingBot : Robot
{
private bool isTradeOpen = false;
[Parameter("Instance Name", DefaultValue = "ADX TS")]
public string InstanceName { get; set; }
[Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
public double Quantity { get; set; }
[Parameter("ADX Periods", Group = "ADX", DefaultValue = 20, MinValue = 6, Step = 1, MaxValue = 1000)]
public int AdxPeriods { get; set; }
[Parameter("MA", Group = "ADX", DefaultValue = 21, MinValue = 6, Step = 1, MaxValue = 1000)]
public int TrendMME { get; set; }
[Parameter("Take Profit", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int TakeProfit { get; set; }
[Parameter("Stop Loss", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int StopLoss { get; set; }
//[Parameter("Trade Label", DefaultValue = "ADX Crossing")]
//public string TradeLabel { get; set; }
[Parameter("Include Trailing Stop", Group = "Risk",DefaultValue = true)]
public bool IncludeTrailingStop { get; set; }
[Parameter("Trailing Stop Trigger (pips)", Group = "Risk", DefaultValue = 20)]
public double TrailingStopTrigger { get; set; }
[Parameter("Trailing Stop Step (pips)", Group = "Risk", DefaultValue = 10)]
public double TrailingStopStep { get; set; }
private DirectionalMovementSystem adx;
private double volumeInUnits;
private ExponentialMovingAverage mme;
private RelativeStrengthIndex rsi;
protected override void OnStart()
{
volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity);
adx = Indicators.DirectionalMovementSystem(AdxPeriods);
mme = Indicators.ExponentialMovingAverage(Bars.ClosePrices, TrendMME);
rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, 14);
Positions.Closed += OnPositionClosed;
}
protected override void OnTick()
{
// Check if a trade is already open
if (isTradeOpen)
return;
if (IncludeTrailingStop)
{
// Trailing stop logic
SetTrailingStop();
}
if (adx.DIMinus.Last(3) < adx.DIPlus.Last(3) && adx.DIMinus.Last(1) > adx.DIPlus.Last(1) && adx.DIMinus.LastValue > adx.DIPlus.LastValue)
{
if (Symbol.Bid < mme.Result.Last(2))
if (rsi.Result.LastValue <= 70)
{
ExecuteMarketOrder(TradeType.Sell, SymbolName, volumeInUnits, InstanceName, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
else if (adx.DIPlus.Last(3) < adx.DIMinus.Last(3) && adx.DIPlus.Last(1) > adx.DIMinus.Last(1) && adx.DIPlus.LastValue > adx.DIMinus.LastValue)
{
if (Symbol.Bid > mme.Result.Last(2))
if (rsi.Result.LastValue >= 30)
{
ExecuteMarketOrder(TradeType.Buy, SymbolName, volumeInUnits, InstanceName, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
}
private void SetTrailingStop()
{
var sellPositions = Positions.FindAll(InstanceName, SymbolName, TradeType.Sell);
foreach (var position in sellPositions)
{
double distance = position.EntryPrice - Symbol.Ask;
if (distance < TrailingStopTrigger * Symbol.PipSize)
continue;
double newStopLossPrice = Symbol.Ask + TrailingStopStep * Symbol.PipSize;
double newTakeProfit = position.TakeProfit ?? 0;
if (position.StopLoss == null || newStopLossPrice < position.StopLoss)
{
ModifyPosition(position, newStopLossPrice, newTakeProfit);
Print("Trailing Stop Loss triggered...");
}
}
var buyPositions = Positions.FindAll(InstanceName, SymbolName, TradeType.Buy);
foreach (var position in buyPositions)
{
double distance = Symbol.Bid - position.EntryPrice;
if (distance < TrailingStopTrigger * Symbol.PipSize)
continue;
double newStopLossPrice = Symbol.Bid - TrailingStopStep * Symbol.PipSize;
double newTakeProfit = position.TakeProfit ?? 0;
if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
{
ModifyPosition(position, newStopLossPrice, newTakeProfit);
Print("Trailing Stop Loss triggered...");
}
}
}
private void OnPositionClosed(PositionClosedEventArgs args)
{
// Reset the flag when a position is closed
isTradeOpen = false;
if (args.Position.Label != InstanceName) //Comment changed to InstanceName
return;
if (args.Reason == PositionCloseReason.StopLoss || args.Reason == PositionCloseReason.TakeProfit)
{
Print($"Position closed by {args.Reason}. Profit: {args.Position.GrossProfit}");
}
}
}
}
Replies
jmenotts
06 Feb 2024, 04:50
RE: Cant get Trailing StopLoss Working
PanagiotisCharalampous said:
Hi there,
I am really lazy figuring out why your code does not work therefore I am quoting some code that has been tested and runs well
[Parameter("Use Trailing Stop", DefaultValue = false, Group = "Trailing Stop Loss")] public bool UseTSL { get; set; } [Parameter("Trigger (pips)", DefaultValue = 20, Group = "Trailing Stop Loss")] public int TSLTrigger { get; set; } [Parameter("Distance (pips)", DefaultValue = 10, Group = "Trailing Stop Loss")] public int TSLDistance { get; set; }
protected override void OnTick() { // If Trailing Stop Loss is set to true, then we execute the following code block if (UseTSL) { // we iterate through all the instance's positions foreach (var position in Positions.Where(x => x.Label == Instance)) { // If position's pips is above the trailing stop loss pips and the position has not trailing stop loss set if (position.Pips > TSLTrigger && !position.HasTrailingStop) { // We check the position's trade type and excute the relevant code block if (position.TradeType == TradeType.Buy) { // We calculate the stop loss based on the TSL Distance To Add parameter var stopLoss = Symbol.Bid - (TSLDistance * Symbol.PipSize); // We modify the stop loss price position.ModifyStopLossPrice(stopLoss); // We set the trailing stop loss to true position.ModifyTrailingStop(true); Print("Trailing Stop Loss Triggered"); } else { // We calculate the stop loss based on the TSL Distance To Add parameter var sl = Symbol.Ask + (TSLDistance * Symbol.PipSize); // We modify the stop loss price position.ModifyStopLossPrice(sl); position.ModifyTrailingStop(true); Print("Trailing Stop Loss Triggered"); } } } } }
Thankyou I really appreciate the help will try it when I get back from working away and update here the results.
@jmenotts
jmenotts
06 Feb 2024, 13:55
RE: RE: Cant get Trailing StopLoss Working
Hjmenotts said:
PanagiotisCharalampous said:
Hi there,
I am really lazy figuring out why your code does not work therefore I am quoting some code that has been tested and runs well
[Parameter("Use Trailing Stop", DefaultValue = false, Group = "Trailing Stop Loss")] public bool UseTSL { get; set; } [Parameter("Trigger (pips)", DefaultValue = 20, Group = "Trailing Stop Loss")] public int TSLTrigger { get; set; } [Parameter("Distance (pips)", DefaultValue = 10, Group = "Trailing Stop Loss")] public int TSLDistance { get; set; }
protected override void OnTick() { // If Trailing Stop Loss is set to true, then we execute the following code block if (UseTSL) { // we iterate through all the instance's positions foreach (var position in Positions.Where(x => x.Label == Instance)) { // If position's pips is above the trailing stop loss pips and the position has not trailing stop loss set if (position.Pips > TSLTrigger && !position.HasTrailingStop) { // We check the position's trade type and excute the relevant code block if (position.TradeType == TradeType.Buy) { // We calculate the stop loss based on the TSL Distance To Add parameter var stopLoss = Symbol.Bid - (TSLDistance * Symbol.PipSize); // We modify the stop loss price position.ModifyStopLossPrice(stopLoss); // We set the trailing stop loss to true position.ModifyTrailingStop(true); Print("Trailing Stop Loss Triggered"); } else { // We calculate the stop loss based on the TSL Distance To Add parameter var sl = Symbol.Ask + (TSLDistance * Symbol.PipSize); // We modify the stop loss price position.ModifyStopLossPrice(sl); position.ModifyTrailingStop(true); Print("Trailing Stop Loss Triggered"); } } } } }
Thankyou I really appreciate the help will try it when I get back from working away and update here the results.
@jmenotts
jmenotts
06 Feb 2024, 13:57
Hi im still unable to get it working even with the tried and tested code am i being silly? lol i pasted the exact code im using, im altering parameters and he results are no different when running back test im lost now any further help will be much appreciated thank you once again.
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ADXCrossingBot : Robot
{
private bool isTradeOpen = false;
[Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
public double Quantity { get; set; }
[Parameter("ADX Periods", Group = "ADX", DefaultValue = 20, MinValue = 6, Step = 1, MaxValue = 1000)]
public int AdxPeriods { get; set; }
[Parameter("MA", Group = "ADX", DefaultValue = 21, MinValue = 6, Step = 1, MaxValue = 1000)]
public int TrendMME { get; set; }
[Parameter("Take Profit", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int TakeProfit { get; set; }
[Parameter("Stop Loss", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int StopLoss { get; set; }
[Parameter("Trade Label", DefaultValue = "ADX Crossing")]
public string TradeLabel { get; set; }
[Parameter("Use Trailing Stop", DefaultValue = false, Group = "Trailing Stop Loss")]
public bool UseTSL { get; set; }
[Parameter("Trigger (pips)", DefaultValue = 20, Group = "Trailing Stop Loss")]
public int TSLTrigger { get; set; }
[Parameter("Distance (pips)", DefaultValue = 10, Group = "Trailing Stop Loss")]
public int TSLDistance { get; set; }
private DirectionalMovementSystem adx;
private double volumeInUnits;
private ExponentialMovingAverage mme;
private RelativeStrengthIndex rsi;
protected override void OnStart()
{
volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity);
adx = Indicators.DirectionalMovementSystem(AdxPeriods);
mme = Indicators.ExponentialMovingAverage(Bars.ClosePrices, TrendMME);
rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, 14);
Positions.Closed += OnPositionClosed;
}
protected override void OnTick()
{
// Check if a trade is already open
if (isTradeOpen)
return;
if (adx.DIMinus.Last(3) < adx.DIPlus.Last(3) && adx.DIMinus.Last(1) > adx.DIPlus.Last(1) && adx.DIMinus.LastValue > adx.DIPlus.LastValue)
{
if (Symbol.Bid < mme.Result.Last(2))
if (rsi.Result.LastValue <= 70)
{
ExecuteMarketOrder(TradeType.Sell, Symbol.Name, volumeInUnits, "ADX Sell", StopLoss, TakeProfit);
isTradeOpen = true;
}
}
else if (adx.DIPlus.Last(3) < adx.DIMinus.Last(3) && adx.DIPlus.Last(1) > adx.DIMinus.Last(1) && adx.DIPlus.LastValue > adx.DIMinus.LastValue)
{
if (Symbol.Bid > mme.Result.Last(2))
if (rsi.Result.LastValue >= 30)
{
ExecuteMarketOrder(TradeType.Buy, Symbol.Name, volumeInUnits, "ADX Buy", StopLoss, TakeProfit);
isTradeOpen = true;
}
}
{
// If Trailing Stop Loss is set to true, then we execute the following code block
if (UseTSL)
{
// we iterate through all the instance's positions
foreach (var position in Positions.Where(x => x.Label == TradeLabel))
{
// If position's pips is above the trailing stop loss pips and the position has not trailing stop loss set
if (position.Pips > TSLTrigger && !position.HasTrailingStop)
{
// We check the position's trade type and excute the relevant code block
if (position.TradeType == TradeType.Buy)
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var stopLoss = Symbol.Bid - (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(stopLoss);
// We set the trailing stop loss to true
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
else
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var sl = Symbol.Ask + (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(sl);
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
}
}
}
}}
private void OnPositionClosed(PositionClosedEventArgs args)
{
// Reset the flag when a position is closed
isTradeOpen = false;
}
}
}
@jmenotts
PanagiotisCharalampous
06 Feb 2024, 14:21
RE: Cant get Trailing StopLoss Working
jmenotts said:
Hi im still unable to get it working even with the tried and tested code am i being silly? lol i pasted the exact code im using, im altering parameters and he results are no different when running back test im lost now any further help will be much appreciated thank you once again.
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ADXCrossingBot : Robot
{
private bool isTradeOpen = false;
[Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
public double Quantity { get; set; }
[Parameter("ADX Periods", Group = "ADX", DefaultValue = 20, MinValue = 6, Step = 1, MaxValue = 1000)]
public int AdxPeriods { get; set; }
[Parameter("MA", Group = "ADX", DefaultValue = 21, MinValue = 6, Step = 1, MaxValue = 1000)]
public int TrendMME { get; set; }
[Parameter("Take Profit", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int TakeProfit { get; set; }
[Parameter("Stop Loss", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int StopLoss { get; set; }
[Parameter("Trade Label", DefaultValue = "ADX Crossing")]
public string TradeLabel { get; set; }
[Parameter("Use Trailing Stop", DefaultValue = false, Group = "Trailing Stop Loss")]
public bool UseTSL { get; set; }
[Parameter("Trigger (pips)", DefaultValue = 20, Group = "Trailing Stop Loss")]
public int TSLTrigger { get; set; }
[Parameter("Distance (pips)", DefaultValue = 10, Group = "Trailing Stop Loss")]
public int TSLDistance { get; set; }
private DirectionalMovementSystem adx;
private double volumeInUnits;
private ExponentialMovingAverage mme;
private RelativeStrengthIndex rsi;
protected override void OnStart()
{
volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity);
adx = Indicators.DirectionalMovementSystem(AdxPeriods);
mme = Indicators.ExponentialMovingAverage(Bars.ClosePrices, TrendMME);
rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, 14);
Positions.Closed += OnPositionClosed;
}
protected override void OnTick()
{
// Check if a trade is already open
if (isTradeOpen)
return;
if (adx.DIMinus.Last(3) < adx.DIPlus.Last(3) && adx.DIMinus.Last(1) > adx.DIPlus.Last(1) && adx.DIMinus.LastValue > adx.DIPlus.LastValue)
{
if (Symbol.Bid < mme.Result.Last(2))
if (rsi.Result.LastValue <= 70)
{
ExecuteMarketOrder(TradeType.Sell, Symbol.Name, volumeInUnits, "ADX Sell", StopLoss, TakeProfit);
isTradeOpen = true;
}
}
else if (adx.DIPlus.Last(3) < adx.DIMinus.Last(3) && adx.DIPlus.Last(1) > adx.DIMinus.Last(1) && adx.DIPlus.LastValue > adx.DIMinus.LastValue)
{
if (Symbol.Bid > mme.Result.Last(2))
if (rsi.Result.LastValue >= 30)
{
ExecuteMarketOrder(TradeType.Buy, Symbol.Name, volumeInUnits, "ADX Buy", StopLoss, TakeProfit);
isTradeOpen = true;
}
}
{
// If Trailing Stop Loss is set to true, then we execute the following code block
if (UseTSL)
{
// we iterate through all the instance's positions
foreach (var position in Positions.Where(x => x.Label == TradeLabel))
{
// If position's pips is above the trailing stop loss pips and the position has not trailing stop loss set
if (position.Pips > TSLTrigger && !position.HasTrailingStop)
{
// We check the position's trade type and excute the relevant code block
if (position.TradeType == TradeType.Buy)
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var stopLoss = Symbol.Bid - (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(stopLoss);
// We set the trailing stop loss to true
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
else
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var sl = Symbol.Ask + (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(sl);
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
}
}
}
}}
private void OnPositionClosed(PositionClosedEventArgs args)
{
// Reset the flag when a position is closed
isTradeOpen = false;
}
}
}
Try passing TradeLabel to your orders as well :)
@PanagiotisCharalampous
jmenotts
06 Feb 2024, 14:51
RE: RE: Cant get Trailing StopLoss Working
Thankyou for your prompt response i have done this and still not getting anywhere this is driving me crazy im an absolute newby when it comes to this i have pasted the code again to show what i have done, Thankyou in advance…..
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ADXCrossingBot : Robot
{
private bool isTradeOpen = false;
[Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
public double Quantity { get; set; }
[Parameter("ADX Periods", Group = "ADX", DefaultValue = 20, MinValue = 6, Step = 1, MaxValue = 1000)]
public int AdxPeriods { get; set; }
[Parameter("MA", Group = "ADX", DefaultValue = 21, MinValue = 6, Step = 1, MaxValue = 1000)]
public int TrendMME { get; set; }
[Parameter("Take Profit", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int TakeProfit { get; set; }
[Parameter("Stop Loss", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int StopLoss { get; set; }
[Parameter("Trade Label", DefaultValue = "ADX Crossing")]
public string TradeLabel { get; set; }
[Parameter("Use Trailing Stop", DefaultValue = false, Group = "Trailing Stop Loss")]
public bool UseTSL { get; set; }
[Parameter("Trigger (pips)", DefaultValue = 20, Group = "Trailing Stop Loss")]
public int TSLTrigger { get; set; }
[Parameter("Distance (pips)", DefaultValue = 10, Group = "Trailing Stop Loss")]
public int TSLDistance { get; set; }
private DirectionalMovementSystem adx;
private double volumeInUnits;
private ExponentialMovingAverage mme;
private RelativeStrengthIndex rsi;
protected override void OnStart()
{
volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity);
adx = Indicators.DirectionalMovementSystem(AdxPeriods);
mme = Indicators.ExponentialMovingAverage(Bars.ClosePrices, TrendMME);
rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, 14);
Positions.Closed += OnPositionClosed;
}
protected override void OnTick()
{
// Check if a trade is already open
if (isTradeOpen)
return;
if (adx.DIMinus.Last(3) < adx.DIPlus.Last(3) && adx.DIMinus.Last(1) > adx.DIPlus.Last(1) && adx.DIMinus.LastValue > adx.DIPlus.LastValue)
{
if (Symbol.Bid < mme.Result.Last(2))
if (rsi.Result.LastValue <= 70)
{
ExecuteMarketOrder(TradeType.Sell, Symbol.Name, volumeInUnits, TradeLabel, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
else if (adx.DIPlus.Last(3) < adx.DIMinus.Last(3) && adx.DIPlus.Last(1) > adx.DIMinus.Last(1) && adx.DIPlus.LastValue > adx.DIMinus.LastValue)
{
if (Symbol.Bid > mme.Result.Last(2))
if (rsi.Result.LastValue >= 30)
{
ExecuteMarketOrder(TradeType.Buy, Symbol.Name, volumeInUnits, TradeLabel, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
{
// If Trailing Stop Loss is set to true, then we execute the following code block
if (UseTSL)
{
// we iterate through all the instance's positions
foreach (var position in Positions.Where(x => x.Label == TradeLabel))
{
// If position's pips is above the trailing stop loss pips and the position has not trailing stop loss set
if (position.Pips > TSLTrigger && !position.HasTrailingStop)
{
// We check the position's trade type and excute the relevant code block
if (position.TradeType == TradeType.Buy)
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var stopLoss = Symbol.Bid - (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(stopLoss);
// We set the trailing stop loss to true
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
else
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var sl = Symbol.Ask + (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(sl);
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
}
}
}
}}
private void OnPositionClosed(PositionClosedEventArgs args)
{
// Reset the flag when a position is closed
isTradeOpen = false;
}
}
}
@jmenotts
jmenotts
06 Feb 2024, 14:53
RE: RE: Cant get Trailing StopLoss Working
Thankyou for your reply buddy but ….. im still unable to get it running heres my code it must be something so simple im sure lol.
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ADXCrossingBot : Robot
{
private bool isTradeOpen = false;
[Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
public double Quantity { get; set; }
[Parameter("ADX Periods", Group = "ADX", DefaultValue = 20, MinValue = 6, Step = 1, MaxValue = 1000)]
public int AdxPeriods { get; set; }
[Parameter("MA", Group = "ADX", DefaultValue = 21, MinValue = 6, Step = 1, MaxValue = 1000)]
public int TrendMME { get; set; }
[Parameter("Take Profit", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int TakeProfit { get; set; }
[Parameter("Stop Loss", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int StopLoss { get; set; }
[Parameter("Trade Label", DefaultValue = "ADX Crossing")]
public string TradeLabel { get; set; }
[Parameter("Use Trailing Stop", DefaultValue = false, Group = "Trailing Stop Loss")]
public bool UseTSL { get; set; }
[Parameter("Trigger (pips)", DefaultValue = 20, Group = "Trailing Stop Loss")]
public int TSLTrigger { get; set; }
[Parameter("Distance (pips)", DefaultValue = 10, Group = "Trailing Stop Loss")]
public int TSLDistance { get; set; }
private DirectionalMovementSystem adx;
private double volumeInUnits;
private ExponentialMovingAverage mme;
private RelativeStrengthIndex rsi;
protected override void OnStart()
{
volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity);
adx = Indicators.DirectionalMovementSystem(AdxPeriods);
mme = Indicators.ExponentialMovingAverage(Bars.ClosePrices, TrendMME);
rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, 14);
Positions.Closed += OnPositionClosed;
}
protected override void OnTick()
{
// Check if a trade is already open
if (isTradeOpen)
return;
if (adx.DIMinus.Last(3) < adx.DIPlus.Last(3) && adx.DIMinus.Last(1) > adx.DIPlus.Last(1) && adx.DIMinus.LastValue > adx.DIPlus.LastValue)
{
if (Symbol.Bid < mme.Result.Last(2))
if (rsi.Result.LastValue <= 70)
{
ExecuteMarketOrder(TradeType.Sell, Symbol.Name, volumeInUnits, TradeLabel, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
else if (adx.DIPlus.Last(3) < adx.DIMinus.Last(3) && adx.DIPlus.Last(1) > adx.DIMinus.Last(1) && adx.DIPlus.LastValue > adx.DIMinus.LastValue)
{
if (Symbol.Bid > mme.Result.Last(2))
if (rsi.Result.LastValue >= 30)
{
ExecuteMarketOrder(TradeType.Buy, Symbol.Name, volumeInUnits, TradeLabel, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
{
// If Trailing Stop Loss is set to true, then we execute the following code block
if (UseTSL)
{
// we iterate through all the instance's positions
foreach (var position in Positions.Where(x => x.Label == TradeLabel))
{
// If position's pips is above the trailing stop loss pips and the position has not trailing stop loss set
if (position.Pips > TSLTrigger && !position.HasTrailingStop)
{
// We check the position's trade type and excute the relevant code block
if (position.TradeType == TradeType.Buy)
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var stopLoss = Symbol.Bid - (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(stopLoss);
// We set the trailing stop loss to true
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
else
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var sl = Symbol.Ask + (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(sl);
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
}
}
}
}}
private void OnPositionClosed(PositionClosedEventArgs args)
{
// Reset the flag when a position is closed
isTradeOpen = false;
}
}
}
@jmenotts
PanagiotisCharalampous
07 Feb 2024, 07:09
RE: RE: RE: Cant get Trailing StopLoss Working
jmenotts said:
Thankyou for your reply buddy but ….. im still unable to get it running heres my code it must be something so simple im sure lol.
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ADXCrossingBot : Robot
{
private bool isTradeOpen = false;
[Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
public double Quantity { get; set; }
[Parameter("ADX Periods", Group = "ADX", DefaultValue = 20, MinValue = 6, Step = 1, MaxValue = 1000)]
public int AdxPeriods { get; set; }
[Parameter("MA", Group = "ADX", DefaultValue = 21, MinValue = 6, Step = 1, MaxValue = 1000)]
public int TrendMME { get; set; }
[Parameter("Take Profit", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int TakeProfit { get; set; }
[Parameter("Stop Loss", Group = "Risk", DefaultValue = 150, MinValue = 0, Step = 1, MaxValue = 1000)]
public int StopLoss { get; set; }
[Parameter("Trade Label", DefaultValue = "ADX Crossing")]
public string TradeLabel { get; set; }
[Parameter("Use Trailing Stop", DefaultValue = false, Group = "Trailing Stop Loss")]
public bool UseTSL { get; set; }
[Parameter("Trigger (pips)", DefaultValue = 20, Group = "Trailing Stop Loss")]
public int TSLTrigger { get; set; }
[Parameter("Distance (pips)", DefaultValue = 10, Group = "Trailing Stop Loss")]
public int TSLDistance { get; set; }
private DirectionalMovementSystem adx;
private double volumeInUnits;
private ExponentialMovingAverage mme;
private RelativeStrengthIndex rsi;
protected override void OnStart()
{
volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity);
adx = Indicators.DirectionalMovementSystem(AdxPeriods);
mme = Indicators.ExponentialMovingAverage(Bars.ClosePrices, TrendMME);
rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, 14);
Positions.Closed += OnPositionClosed;
}
protected override void OnTick()
{
// Check if a trade is already open
if (isTradeOpen)
return;
if (adx.DIMinus.Last(3) < adx.DIPlus.Last(3) && adx.DIMinus.Last(1) > adx.DIPlus.Last(1) && adx.DIMinus.LastValue > adx.DIPlus.LastValue)
{
if (Symbol.Bid < mme.Result.Last(2))
if (rsi.Result.LastValue <= 70)
{
ExecuteMarketOrder(TradeType.Sell, Symbol.Name, volumeInUnits, TradeLabel, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
else if (adx.DIPlus.Last(3) < adx.DIMinus.Last(3) && adx.DIPlus.Last(1) > adx.DIMinus.Last(1) && adx.DIPlus.LastValue > adx.DIMinus.LastValue)
{
if (Symbol.Bid > mme.Result.Last(2))
if (rsi.Result.LastValue >= 30)
{
ExecuteMarketOrder(TradeType.Buy, Symbol.Name, volumeInUnits, TradeLabel, StopLoss, TakeProfit);
isTradeOpen = true;
}
}
{
// If Trailing Stop Loss is set to true, then we execute the following code block
if (UseTSL)
{
// we iterate through all the instance's positions
foreach (var position in Positions.Where(x => x.Label == TradeLabel))
{
// If position's pips is above the trailing stop loss pips and the position has not trailing stop loss set
if (position.Pips > TSLTrigger && !position.HasTrailingStop)
{
// We check the position's trade type and excute the relevant code block
if (position.TradeType == TradeType.Buy)
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var stopLoss = Symbol.Bid - (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(stopLoss);
// We set the trailing stop loss to true
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
else
{
// We calculate the stop loss based on the TSL Distance To Add parameter
var sl = Symbol.Ask + (TSLDistance * Symbol.PipSize);
// We modify the stop loss price
position.ModifyStopLossPrice(sl);
position.ModifyTrailingStop(true);
Print("Trailing Stop Loss Triggered");
}
}
}
}
}}
private void OnPositionClosed(PositionClosedEventArgs args)
{
// Reset the flag when a position is closed
isTradeOpen = false;
}
}
}
This condition does not allow the TSL code to be executed. Place the TSL code above it
// Check if a trade is already open
if (isTradeOpen)
return;
@PanagiotisCharalampous
jmenotts
08 Feb 2024, 12:58
RE: RE: RE: RE: Cant get Trailing StopLoss Working
Hi bud i tried to add that below tsl but im getting problems with it not sure if im being stupid here lol could you insert it into the code for me and paste it here as im getting no where sorry to be a pain and thank you for your help buddy
@jmenotts
PanagiotisCharalampous
08 Feb 2024, 13:13
RE: RE: RE: RE: RE: Cant get Trailing StopLoss Working
jmenotts said:
Hi bud i tried to add that below tsl but im getting problems with it not sure if im being stupid here lol could you insert it into the code for me and paste it here as im getting no where sorry to be a pain and thank you for your help buddy
Hi,
Personally I would not use that code :) Instead I would check if there are no open positions before proceeding. Something like below
if(Positions.Count == 0)
{
...
}
I will not give you a ready made solution, I will help you fix stuff yourself instead. That's the only way to learn :)
@PanagiotisCharalampous
jmenotts
11 Feb 2024, 15:48
Auto Lot Sizing Based on Account Balance/Equity
Would just like to thank you for all your help I have a cBot that works well tbh, On another note though how would I go about increasing lot size per 1k account balance/equity from lets say a percentage or every 1k? I'm unsure I've looked all over the net.
Thanks In Advance.
@jmenotts
PanagiotisCharalampous
12 Feb 2024, 06:53
RE: Auto Lot Sizing Based on Account Balance/Equity
jmenotts said:
Would just like to thank you for all your help I have a cBot that works well tbh, On another note though how would I go about increasing lot size per 1k account balance/equity from lets say a percentage or every 1k? I'm unsure I've looked all over the net.
Thanks In Advance.
I did not understand your question. Can you explain with examples?
@PanagiotisCharalampous
PanagiotisCharalampous
13 Feb 2024, 06:58
RE: RE: RE: Auto Lot Sizing Based on Account Balance/Equity
jmenotts said:
Hi and thankyou for the reply, How would i make the robot trade higher lots automatically per 1k account balance and add a spread filter please?
Hi there,
If you want to adjust the volume automatically then write a formula that will calculate the volume as per your needs. It will look something like this
public double GetVolume()
{
...
return myCustomVolume;
}
Regarding the spread, you can get the current symbol spread using the Spread property. Your condition will look something like the below
if(Symbol.Spread < mySpreadThreshold)
{
...
}
@PanagiotisCharalampous
PanagiotisCharalampous
05 Feb 2024, 07:08
Hi there,
I am really lazy figuring out why your code does not work therefore I am quoting some code that has been tested and runs well
@PanagiotisCharalampous