Close posititon based on equity

Created at 23 May 2017, 00:06
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

Close posititon based on equity
23 May 2017, 00:06


I hope that someone can help me with, and or provide me a code example for closing the postion with the biggest negative gross loss when reaching a certain equity percentage.

So when my equity drawdown is 10% I want to close the postion with the biggest loss

 

I hope someone can help me


@tinker.this
Replies

Mikro
09 Jun 2017, 18:12

Try something like this:
protected override void OnStart()
{
    _myEquity = Account.Equity;
}
 
protected override void OnTick()
{
    if ((_myEquity / Account.Equity)<0.95)
    {
        Position _myWorstPosition=Positions[0];
        foreach (Position pos in Positions)
        {
            if (_myWorstPosition.NetProfit>pos.NetProfit)
            {
                _myWorstPosition = pos;
            }
        }
        ClosePosition(_myWorstPosition);
    }
}

cheers Mirko


@Mikro

Mikro
09 Jun 2017, 18:39

RE:

an of course _myEquity need to be initialized as class member

 

yourRobot : Robot
{
double _myEquity;

OnStart()
OnTick()
OnStop()
}

 


@Mikro

ClickAlgo
10 Jun 2017, 07:53

this block of code

  Position _myWorstPosition=Positions[0];
        foreach (Position pos in Positions)
        {
            if (_myWorstPosition.NetProfit>pos.NetProfit)
            {
                _myWorstPosition = pos;
            }
        }

can be replaced using LINQ to a single line

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

read more here


@ClickAlgo

Mikro
10 Jun 2017, 17:42

RE:

Hi Paul,

nice, thanks. Seems like I should take the time to look into Linq in a bit more Detail ;)


@Mikro

ClickAlgo
10 Jun 2017, 21:41

:-)


@ClickAlgo