Close maximum profitable position

Created at 05 Dec 2021, 17:41
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!
AN

anikaurmi420

Joined 18.10.2020

Close maximum profitable position
05 Dec 2021, 17:41


I have multiple open positions. How can I close a position which has maximum net profit?


@anikaurmi420
Replies

amusleh
06 Dec 2021, 09:08

Hi,

This code example might help you:

using cAlgo.API;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class Test : Robot
    {
        protected override void OnStart()
        {
            var maxNetProfitPosition = GetMaxNetProfitPosition();

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

        private Position GetMaxNetProfitPosition()
        {
            Position result = null;

            foreach (var position in Positions)
            {
                if (result == null)
                {
                    result = position;

                    continue;
                }

                if (position.NetProfit > result.NetProfit)
                {
                    result = position;
                }
            }

            return result;
        }
    }
}

 


@amusleh