Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Close a position one year after opened

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Close a position one year after opened

    Hello,

    I am developing a strategy that will open a position. it will wait one year minus one day and verify if the position is winning or losing. If the position is losing, it will close the position. if the position is winning it will wait until one year plus one day to close the position.
    Can you please help me with the piece of code that will help me identify that it has been one year since the position was opened? Any suggestion on where to find the information will be greatly appreciated

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;

    // Entry Signal
    if (ADX1[0] < ADXinput)
    {
    EnterLongLimit(Convert.ToInt32(DefaultQuantity), ZonasdeOperacionCompra1[0], @"Compra");
    }

    // Exit signal 1 = if position is losing
    if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) < 0 && days since position open < one year) //piece of code I don't know how to write
    {
    ExitLong(Convert.ToInt32(DefaultQuantity), @"Exitloss", @"Compra");
    }

    // Exit signal 2 = if the position is winning
    if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) > 0 && days since position open > one year) //piece of code i dont know how to write
    {
    ExitLong(Convert.ToInt32(DefaultQuantity), "Exitwinning", @"compra");
    }

    }

    #2
    Hello Jorge.andres.o,

    Thanks for your post.

    You can consider using OnExecutionUpdate to see when the entry order executes (fills,) and then save the time parameter from OnExecutuionUpdate to a private DateTime variable. Inside OnExecutuonUpdate, you can check execution.Name to see if it matches your entry signal name to identify the execution of the entry order.

    OnExecutionUpdate - https://ninjatrader.com/support/help...tionupdate.htm

    Then in OnBarUpdate, you can use this DateTime variable which reflects the time you entered, and you can use the AddDays() DateTime method to add 364 days, or 366 days to the DateTime variable to go 1 year ahead +/- a day.

    We look forward to assisting.

    Comment


      #3
      Jim,

      Than you very much

      Comment


        #4
        Jim,

        I think I am a little bit confused with the code. Would you please help me figure out the mistake?


        protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
        {

        //Entry order 01

        if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
        {
        myFecha = DateTime.Today; Print(string.Format("{0} | Fecha de entrada: {1}", Time[0], myFecha));
        }

        }

        protected override void OnBarUpdate()
        {
        if (BarsInProgress != 0)
        return;

        if (CurrentBars[0] < 1)
        return;

        // Entry Signal
        if (ADX1[0] < ADXinput)
        {
        EnterLongLimit(Convert.ToInt32(DefaultQuantity), ZonasdeOperacionCompra1[0], @"Compra");
        }

        // Exit signal 1 = if position is losing
        if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) < 0 && DateTime.Today == myFecha.AddDays(364))
        {
        ExitLong(Convert.ToInt32(DefaultQuantity), @"Exitloss", @"Compra");
        }

        // Exit signal 2 = if the position is winning
        if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) > 0 && DateTime.Today == MyFecha.AddDays(366))
        {
        ExitLong(Convert.ToInt32(DefaultQuantity), "Exitwinning", @"compra");
        }

        }

        Comment


          #5
          Hi Jorge, thanks for your reply.

          What specificaly is going wrong with this piece of code? I did notice you are not checking for the order.Name property. This is important to identify the entry order so that you only save the entry order and nothing else.

          if ( execution.Order.Name = "Compra" && execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))

          Comment


            #6
            Chris L.

            It seems like the strategy analyzer records the date of the computer instead of getting the date which the position was historically opened.

            Comment


              #7
              Hello Jorge.andres.o,

              DateTime.Today is from the PC clock. Please see the parameters of the OnExecutionUpdate method. The time parameter would be the time of that execution.

              I.E. within OnExecutionUpdate: Print(time.Today);

              Comment


                #8
                Jim,

                Thank you so much. The strategy is getting the right dates. However, it is not closing the position at the right time. I think the problem is the strategy analyzer does not get the date one year after the position was opened. I currently have it this way:

                if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) < 0 && DateTime.Today == myFecha.AddDays(364))
                {
                ExitLong(Convert.ToInt32(DefaultQuantity), @"Exitloss", @"Compra");
                }

                I think the problem could be Date.Time.Today but I am not able to find the documentation for other options. Would you please help me?

                Comment


                  #9
                  Hello Jorge.andres.o,

                  Remember that DateTime.Today is from the PC clock. If you are backtesting, you do not want to use the PC clock time and you would want to use the timestamp of the current bar (Time[0]) or in the case of getting the time of an execution from OnExecutuionUpdate, the time parameter.

                  Comment


                    #10
                    Jim,

                    Thanks for your help. I fixed the dates and got the appropriate dates (with prints). However, the position is not closing on the appropriate dates. It is closing the following day. This is the logic for exiting. I cannot find the error.

                    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                    {
                    //Entry order 01
                    if ( execution.Order.Name == "Compra")

                    if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                    {
                    myDate = time; Print(string.Format("{0} | Date Execution: {1}", Time[0], myDate));
                    }
                    }

                    if (Position.MarketPosition != MarketPosition.Flat)
                    {
                    // Exit signal 1 = if position is losing
                    if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) < 0 && Time[0] == myDate.AddDays(364)) ; Print(string.Format("{0} | Exit Losing Date: {1}", Time[0], myDate.AddDays(364)));
                    {
                    ExitLong(Convert.ToInt32(DefaultQuantity), @"Exitloss", @"Compra");
                    }

                    // Exit signal 1 = if position is losing
                    if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) > 0 && Time[0] == myDate.AddDays(366)); Print(string.Format("{0} | Exit Winning date: {1}", Time[0], myDate.AddDays(364)));
                    {
                    ExitLong(Convert.ToInt32(DefaultQuantity), @"ExitWin", @"Compra");
                    }
                    }
                    Click image for larger version

Name:	Output.PNG
Views:	191
Size:	24.2 KB
ID:	1171805


                    Click image for larger version

Name:	order resolution.PNG
Views:	139
Size:	25.6 KB
ID:	1171806



                    Comment


                      #11
                      Hello Jorge.andres.o,

                      When you are debugging your logic to see why a condition has become true when you do not expect it to be true, you will need to print out what is used in the condition, above/outside of the condition to see why it has evaluated the way it did.

                      Also, when writing C# logic, a semicolon immediately after a condition will mean that the condition will do nothing. Your code that should be triggered by a condition should be within curly braces after that condition.

                      I.E.

                      This condition will do nothing and we will always trigger an entry, because the semicolon separates the condition from the code block in curly braces:
                      Code:
                      if (Close[0] > Open[0])[B]; // Note the semicolon here[/B]
                      {
                          EnterLong();
                      }
                      But this condition will be control the entry method:
                      Code:
                      if (Close[0] > Open[0])[B] // Note there is no semicolon between the condition and the curly braces[/B]
                      {
                      EnterLong();
                      }
                      Last edited by NinjaTrader_Jim; 09-24-2021, 12:25 PM.

                      Comment


                        #12
                        Thank you very much Jim

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by NullPointStrategies, Yesterday, 05:17 AM
                        0 responses
                        65 views
                        0 likes
                        Last Post NullPointStrategies  
                        Started by argusthome, 03-08-2026, 10:06 AM
                        0 responses
                        139 views
                        0 likes
                        Last Post argusthome  
                        Started by NabilKhattabi, 03-06-2026, 11:18 AM
                        0 responses
                        75 views
                        0 likes
                        Last Post NabilKhattabi  
                        Started by Deep42, 03-06-2026, 12:28 AM
                        0 responses
                        45 views
                        0 likes
                        Last Post Deep42
                        by Deep42
                         
                        Started by TheRealMorford, 03-05-2026, 06:15 PM
                        0 responses
                        50 views
                        0 likes
                        Last Post TheRealMorford  
                        Working...
                        X