I am attempting to implement a trailing stop loss functionality in C# similar to what is described here:
https://www.multicharts.com/trading-software/index.php/SetPercentTrailing
Basically, if the profit rises over a certain amount and then drops by a certain percentage of that amount, it closes the order.
Unfortunately, for whatever reason, it doesn't seem to be working. It never exits when there's a profit, but the stop-loss works. I am inexperienced with C# and after spending quite a while on this I'm stumped as to what could be going wrong - my thought is that I may be using lists incorrectly. This is being written with QuantConnect/LEAN. Here is what I've written:
// 0.00025m is the conversion factor for profitPercentage into recognizable integers
var profitPercentage = Portfolio[_symbol].UnrealizedProfitPercent / 0.00025m;
var percentages = new List<decimal>();
var profitThreshold = 10;
decimal maxProfit;
decimal trailingPercent = 10;
decimal stopLoss = -10;
if (profitPercentage > profitThreshold)
{
percentages.Add(profitPercentage);
percentages.Sort();
maxProfit = percentages[percentages.Count - 1];
if (profitPercentage < (maxProfit - (maxProfit * trailingPercent)))
{
SetHoldings(_symbol, 0);
percentages.Clear();
position = "none";
}
}
else if (profitPercentage < stopLoss)
{
Console.WriteLine("Profit:" + profitPercentage);
SetHoldings(_symbol, 0);
percentages.Clear();
position = "none";
}
The stop loss seems to work fine, so profitPercentage
appears to be outputting the right values. The issue seems to lie in the logic related to the list. Similarly, if I simplify the first if statement thus:
if (profitPercentage > profitThreshold)
{
SetHoldings(_symbol, 0);
}
This also works fine.