Trailing stop loss not functioning properly in C# - am I using lists wrong?












0















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.










share|improve this question




















  • 4





    nothing obvious on first sight. "it doesn't seem to be working" is not a useful error description. are the values just off, or do you get a runtime exception? it would be great if you could substitute values for dependencies like Portfolio so we get a minimal, complete example to debug.

    – dlatikay
    Nov 20 '18 at 1:20











  • I'm not sure if the values are off, but it never exists in profit, even when it goes past the profit threshold and then back down. The stop loss seems to work fine, however. I'm not sure what values I can substitute for Portfolio, unfortunately. What I can say for sure though is that the Console.WriteLine in the else if statement outputs values like -40.149284802348.

    – Phil
    Nov 20 '18 at 1:58













  • Seemingly profitPercentage is returning the expected values, but isn't exiting properly when it goes above profitThreshold. So I'm assuming something must be going wrong with the list or the logic related to it. When I simplify the example and make it simply exit once profitPercentage > profitThreshold then it exits properly. For example: if (profitPercentage > profitThreshold) { SetHoldings(_symbol, 0); } This works fine.

    – Phil
    Nov 20 '18 at 2:04













  • you probably want trailingpercent to have a value of 0.1 then

    – dlatikay
    Nov 20 '18 at 2:13






  • 1





    Watch a 10 minute YouTube video on Debugging in Visual Studio, you need to step through the code, line by line and work out whats wrong with the logic.

    – Jeremy Thompson
    Nov 20 '18 at 3:28
















0















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.










share|improve this question




















  • 4





    nothing obvious on first sight. "it doesn't seem to be working" is not a useful error description. are the values just off, or do you get a runtime exception? it would be great if you could substitute values for dependencies like Portfolio so we get a minimal, complete example to debug.

    – dlatikay
    Nov 20 '18 at 1:20











  • I'm not sure if the values are off, but it never exists in profit, even when it goes past the profit threshold and then back down. The stop loss seems to work fine, however. I'm not sure what values I can substitute for Portfolio, unfortunately. What I can say for sure though is that the Console.WriteLine in the else if statement outputs values like -40.149284802348.

    – Phil
    Nov 20 '18 at 1:58













  • Seemingly profitPercentage is returning the expected values, but isn't exiting properly when it goes above profitThreshold. So I'm assuming something must be going wrong with the list or the logic related to it. When I simplify the example and make it simply exit once profitPercentage > profitThreshold then it exits properly. For example: if (profitPercentage > profitThreshold) { SetHoldings(_symbol, 0); } This works fine.

    – Phil
    Nov 20 '18 at 2:04













  • you probably want trailingpercent to have a value of 0.1 then

    – dlatikay
    Nov 20 '18 at 2:13






  • 1





    Watch a 10 minute YouTube video on Debugging in Visual Studio, you need to step through the code, line by line and work out whats wrong with the logic.

    – Jeremy Thompson
    Nov 20 '18 at 3:28














0












0








0








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.










share|improve this question
















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.







c# quantitative-finance algorithmic-trading






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 2:09







Phil

















asked Nov 20 '18 at 1:05









PhilPhil

32




32








  • 4





    nothing obvious on first sight. "it doesn't seem to be working" is not a useful error description. are the values just off, or do you get a runtime exception? it would be great if you could substitute values for dependencies like Portfolio so we get a minimal, complete example to debug.

    – dlatikay
    Nov 20 '18 at 1:20











  • I'm not sure if the values are off, but it never exists in profit, even when it goes past the profit threshold and then back down. The stop loss seems to work fine, however. I'm not sure what values I can substitute for Portfolio, unfortunately. What I can say for sure though is that the Console.WriteLine in the else if statement outputs values like -40.149284802348.

    – Phil
    Nov 20 '18 at 1:58













  • Seemingly profitPercentage is returning the expected values, but isn't exiting properly when it goes above profitThreshold. So I'm assuming something must be going wrong with the list or the logic related to it. When I simplify the example and make it simply exit once profitPercentage > profitThreshold then it exits properly. For example: if (profitPercentage > profitThreshold) { SetHoldings(_symbol, 0); } This works fine.

    – Phil
    Nov 20 '18 at 2:04













  • you probably want trailingpercent to have a value of 0.1 then

    – dlatikay
    Nov 20 '18 at 2:13






  • 1





    Watch a 10 minute YouTube video on Debugging in Visual Studio, you need to step through the code, line by line and work out whats wrong with the logic.

    – Jeremy Thompson
    Nov 20 '18 at 3:28














  • 4





    nothing obvious on first sight. "it doesn't seem to be working" is not a useful error description. are the values just off, or do you get a runtime exception? it would be great if you could substitute values for dependencies like Portfolio so we get a minimal, complete example to debug.

    – dlatikay
    Nov 20 '18 at 1:20











  • I'm not sure if the values are off, but it never exists in profit, even when it goes past the profit threshold and then back down. The stop loss seems to work fine, however. I'm not sure what values I can substitute for Portfolio, unfortunately. What I can say for sure though is that the Console.WriteLine in the else if statement outputs values like -40.149284802348.

    – Phil
    Nov 20 '18 at 1:58













  • Seemingly profitPercentage is returning the expected values, but isn't exiting properly when it goes above profitThreshold. So I'm assuming something must be going wrong with the list or the logic related to it. When I simplify the example and make it simply exit once profitPercentage > profitThreshold then it exits properly. For example: if (profitPercentage > profitThreshold) { SetHoldings(_symbol, 0); } This works fine.

    – Phil
    Nov 20 '18 at 2:04













  • you probably want trailingpercent to have a value of 0.1 then

    – dlatikay
    Nov 20 '18 at 2:13






  • 1





    Watch a 10 minute YouTube video on Debugging in Visual Studio, you need to step through the code, line by line and work out whats wrong with the logic.

    – Jeremy Thompson
    Nov 20 '18 at 3:28








4




4





nothing obvious on first sight. "it doesn't seem to be working" is not a useful error description. are the values just off, or do you get a runtime exception? it would be great if you could substitute values for dependencies like Portfolio so we get a minimal, complete example to debug.

– dlatikay
Nov 20 '18 at 1:20





nothing obvious on first sight. "it doesn't seem to be working" is not a useful error description. are the values just off, or do you get a runtime exception? it would be great if you could substitute values for dependencies like Portfolio so we get a minimal, complete example to debug.

– dlatikay
Nov 20 '18 at 1:20













I'm not sure if the values are off, but it never exists in profit, even when it goes past the profit threshold and then back down. The stop loss seems to work fine, however. I'm not sure what values I can substitute for Portfolio, unfortunately. What I can say for sure though is that the Console.WriteLine in the else if statement outputs values like -40.149284802348.

– Phil
Nov 20 '18 at 1:58







I'm not sure if the values are off, but it never exists in profit, even when it goes past the profit threshold and then back down. The stop loss seems to work fine, however. I'm not sure what values I can substitute for Portfolio, unfortunately. What I can say for sure though is that the Console.WriteLine in the else if statement outputs values like -40.149284802348.

– Phil
Nov 20 '18 at 1:58















Seemingly profitPercentage is returning the expected values, but isn't exiting properly when it goes above profitThreshold. So I'm assuming something must be going wrong with the list or the logic related to it. When I simplify the example and make it simply exit once profitPercentage > profitThreshold then it exits properly. For example: if (profitPercentage > profitThreshold) { SetHoldings(_symbol, 0); } This works fine.

– Phil
Nov 20 '18 at 2:04







Seemingly profitPercentage is returning the expected values, but isn't exiting properly when it goes above profitThreshold. So I'm assuming something must be going wrong with the list or the logic related to it. When I simplify the example and make it simply exit once profitPercentage > profitThreshold then it exits properly. For example: if (profitPercentage > profitThreshold) { SetHoldings(_symbol, 0); } This works fine.

– Phil
Nov 20 '18 at 2:04















you probably want trailingpercent to have a value of 0.1 then

– dlatikay
Nov 20 '18 at 2:13





you probably want trailingpercent to have a value of 0.1 then

– dlatikay
Nov 20 '18 at 2:13




1




1





Watch a 10 minute YouTube video on Debugging in Visual Studio, you need to step through the code, line by line and work out whats wrong with the logic.

– Jeremy Thompson
Nov 20 '18 at 3:28





Watch a 10 minute YouTube video on Debugging in Visual Studio, you need to step through the code, line by line and work out whats wrong with the logic.

– Jeremy Thompson
Nov 20 '18 at 3:28












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384800%2ftrailing-stop-loss-not-functioning-properly-in-c-sharp-am-i-using-lists-wrong%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384800%2ftrailing-stop-loss-not-functioning-properly-in-c-sharp-am-i-using-lists-wrong%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

ComboBox Display Member on multiple fields

Is it possible to collect Nectar points via Trainline?