Find position with biggest loss and close it

Created at 23 May 2017, 12:31
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
TI

tinker.this

Joined 22.10.2015

Find position with biggest loss and close it
23 May 2017, 12:31


Can someone help me with a code snippet that will:

Find position with biggest loss and close it

 

Thanks


@tinker.this
Replies

ClickAlgo
23 May 2017, 13:45 ( Updated at: 21 Dec 2023, 09:20 )

With EF or LINQ use this:

 var position = Positions.OrderByDescending(i => i.NetProfit).FirstOrDefault();

 if(position != null)
 {
      ClosePosition(position);
 }

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var position = Positions.MaxBy(i => i.NetProfit);

I have not tested this, but it should work.

 

https://clickalgo.com


@ClickAlgo

tinker.this
23 May 2017, 13:53

Thanks I'm going to try it.

Following your course btw ;)


@tinker.this

tinker.this
23 May 2017, 14:02

So how do I apply Filtering for postions labels in this example


@tinker.this

tinker.this
23 May 2017, 14:06

I did this

 var position = Positions.Find("Label");
                if (position != null)
                {
                    var positionBL = Positions.OrderByDescending(x => x.NetProfit).FirstOrDefault();
                    if (positionBL != null)
                    {
                        ClosePosition(position);
                    }
                }

Im sure there is a better way


@tinker.this

ClickAlgo
23 May 2017, 14:42

One possible way is to chain the LINQ statement, there are many ways to write LINQ, this uses a method syntax with LAMBDA expressions

var position = r.Positions.OrderByDescending(i => (i.NetProfit)).Where(i => i.Label == "Label").FirstOrDefault();

I would suggest you learn LINQ, it is invaluable for dealing with data and very suitable for algorithmic software development to reduce complexity, the days are over where you have 100 lines of repetitive code when you can use just 5

https://www.codeproject.com/Articles/18116/LINQ-Introduction-Part-Of

I am offering training and coaching courses later in the summer, also much more education content will be published on the website.

https://clickalgo.com/cTrader-algorithmic-trading-school-for-beginners


@ClickAlgo

ClickAlgo
23 May 2017, 14:44

Ignore the "r" use the code below

var position = Positions.OrderByDescending(i => (i.NetProfit)).Where(i => i.Label == "Label").FirstOrDefault();

Also this has not been tested.


@ClickAlgo

PhoenixCapital
01 May 2020, 21:21

RE:

tinker.this said:

Can someone help me with a code snippet that will:

Find position with biggest loss and close it

 

Thanks

Its:

var position = Positions.OrderByDescending(i => (i.NetProfit)).Where(i => i.Label == "Label").LastOrDefault();

 


@PhoenixCapital