Reset input parameters when position closes/opens

Created at 03 Aug 2017, 10:20
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!
DA

davidp13

Joined 06.05.2014

Reset input parameters when position closes/opens
03 Aug 2017, 10:20


Hi. I would like to reset my defaul parameters when a position opens or closes. Everytime a position opens/closes i need the Boolean to change from Buy to ExitLong.

Here is the code (taken some unnecessary parts out):

         [Parameter("Buy", DefaultValue = false)]
        public bool Buy { get; set; }

        [Parameter("Exit Long", DefaultValue = false)]
        public bool ExitLong { get; set; }
 //=============================================================================================

        protected override void OnBar()
        {
            var label_orig = label_a + " " + Symbol.Code;
            var longPosition = Positions.Find(label_orig, Symbol, TradeType.Buy);
            var shortPosition = Positions.Find(label_orig, Symbol, TradeType.Sell);

            if (Buy)
            {
                    ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, label_orig, nullnullnull, name);
             }

            //CLOSE OUT OPEN TRADES
            if (ExitLong)
            {
                    ClosePosition(longPosition);
                }
            }


@davidp13
Replies

Spotware
03 Aug 2017, 11:03

Dear davidp13,

You can use the Positions.Opened and Positions.Closed events to reset your boolean parameters. See a small example below

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class NewcBot : Robot
    {
        [Parameter(DefaultValue = 0.0)]
        public double Parameter { get; set; }
        
        [Parameter("Buy", DefaultValue = false)]
        public bool Buy { get; set; }

        [Parameter("Exit Long", DefaultValue = false)]
        public bool ExitLong { get; set; }
        protected override void OnStart()
        {
           Positions.Opened += OnPositionsOpened;
           Positions.Closed += OnPositionsClosed;
        }
        
        void OnPositionsClosed(PositionClosedEventArgs obj)
        {
            Buy = false;
            ExitLong = true;
        }
        
        void OnPositionsOpened(PositionOpenedEventArgs obj)
        {
            Buy = false;
            ExitLong = true;
        }

        protected override void OnBar()
        {
            // Put your core logic here
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
}

Best Regards,

cTrader Team


@Spotware