Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

¿how can i liquidate all positions before the close on friday?

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

    ¿how can i liquidate all positions before the close on friday?




    regards to everyone,



    nt is an excellent platform and support is also consistently excellent, i don't have any doubts that it should be easy to create the necessary code so that my strategies liquidate all positions before the close on friday and are always flat over the weekend.


    i have been working on this same logic on another inferior platform i have used for a long time (ts) and it required two conditions, one to close all positions shortly before the end of the session and another so that strategies would not open any positions at the close of the last bar of the session.


    - i first created a condition that would be true if dayofweek = 5 and time was between 16:58 and 17:01 exchange time. this condition would be false in any other case. my strategies would not generate entries if this condition was true.

    - i then created commands to close all positions at 16:59.


    i imagine this same structure should work beautifully in nt, but i'm having trouble with the code. this is what i have so far:

    Code:
    if ((Times[0][0].DayOfWeek == DayOfWeek.Friday)
    && (Times[0][0].TimeOfDay >= new TimeSpan(16, 58, 0))
    && (Times[0][0].TimeOfDay <= new TimeSpan(17, 1, 0)))
    {
    Notrco = true;
    }
    
    
    
    if ((Times[0][0].DayOfWeek == DayOfWeek.Friday)
    && (Times[0][0].TimeOfDay == new TimeSpan(16, 59, 0))
    && (Position.MarketPosition == MarketPosition.Long))
    {
    ExitLong(Convert.ToInt32(Position.Quantity), @"clallopo", "");
    }
    
    
    
    if ((Times[0][0].DayOfWeek == DayOfWeek.Friday)
    && (Times[0][0].TimeOfDay == new TimeSpan(16, 59, 0))
    && (Position.MarketPosition == MarketPosition.Short))
    {
    ExitShort(Convert.ToInt32(Position.Quantity), @"clalshpo", "");
    }
    there are two aspects i could use a lot of help with. first of all, ¿will this code work for my objectives? and also, ¿is there a way to keep the day of the week and the different time values as user defined parameters that can be easily adjusted as necessary and not hard-coded into my strategies?


    well, thanks, regards.
    Last edited by rtwave; 10-03-2019, 12:04 AM.

    #2
    Hello rtwave,

    Thank you for your post.

    You're pretty close here; I'd suggest instead of making this an exact time:

    && (Times[0][0].TimeOfDay == new TimeSpan(16, 59, 0))

    That you instead make a comparison and have it fire if you're between 16:58 and 16:59 - this way if you're running it OnBarUpdate the order executes on the last bar before the market closes, and it'd still fire if you're running OnBarUpdate and for some reason it's not exactly 16:59:00 when it processes that command.

    I've created a quick example using a modified version of your code and the SampleMACrossOver strategy that comes with NinjaTrader. This example also shows how you could have the time and day of the week of the exit adjustable according to user input.

    Please let us know if we may be of further assistance to you.
    Attached Files
    Kate W.NinjaTrader Customer Service

    Comment


      #3




      regards again.


      i'm going to need more help with this particular development.


      i have applied the sample strategy provided to a chart (daily bars) and it does generate trades but it fails to perform as intended as it does hold positions over all weekends. i then saved the strategy with a new name to be able to make some modifications to the code and then it does compile but it doesn't generate any trades anymore:


      Code:
      if ( ( Close[0] > smaFast[0] ) &&
                      ( Notrco = false ) )
                      {
                          EnterLong();
                      }
                  if ( ( Close[0] < smaFast[0] ) &&
                      ( Notrco = false ) )
                      {
                          EnterShort();
                      }
      
                  if ((Times[0][0].DayOfWeek == myDayOfWeek)
                  && (Times[0][0].TimeOfDay >= StartExit.TimeOfDay)
                  && (Times[0][0].TimeOfDay <= StartExit.AddMinutes(3).TimeOfDay))
                  {
                  Notrco = true;
                  }
                  else
                  {
                  Notrco = false;
                  }
      
      
      
                  if ((Times[0][0].DayOfWeek == myDayOfWeek)
                  && (Times[0][0].TimeOfDay >= StartExit.TimeOfDay)
                  && (Times[0][0].TimeOfDay < StartExit.AddMinutes(1).TimeOfDay)
                  && (Position.MarketPosition == MarketPosition.Long))
                  {
                  ExitLong();
                  }
      
      
      
                  if ((Times[0][0].DayOfWeek == myDayOfWeek)
                  && (Times[0][0].TimeOfDay >= StartExit.TimeOfDay)
                  && (Times[0][0].TimeOfDay < StartExit.AddMinutes(1).TimeOfDay)
                  && (Position.MarketPosition == MarketPosition.Short))
                  {
                  ExitShort();
                  }

      it seems to me like the no trades condition (Notrco) is the cause of most issues. i want to set Notrco to true only for the final minutes of the session on friday so that the strategy will not generate any entries inside that window. i want Notrco to be false in any other case but i don't think this code is working as desired as i have structured it. it is also important to use Notrco as a filter every time a new entry would be generated.


      i also made some style changes that could be causing the strategy to fail to generate any trades. ¿would this code below be ok?


      Code:
                      switch(DayToExit)
                      {
                          case "mo":
                              myDayOfWeek = DayOfWeek.Monday;
                              break;
                          case "tu":
                              myDayOfWeek = DayOfWeek.Tuesday;
                              break;
                          case "we":
                              myDayOfWeek = DayOfWeek.Wednesday;
                              break;
                          case "th":
                              myDayOfWeek = DayOfWeek.Thursday;
                              break;
                          case "fr":
                              myDayOfWeek = DayOfWeek.Friday;
                              break;
                          case "sa":
                              myDayOfWeek = DayOfWeek.Saturday;
                              break;
                          case "su":
                              myDayOfWeek = DayOfWeek.Sunday;
                              break;
                      }


      i'm also using non minute bars (range) in some charts, i'm not sure whether the sample code would work on non minute bars or if it would be necessary to add a second 1 minute data series so that the exit orders will be generated timely and correctly.


      very well, thanks, regards.

      Comment


        #4
        Hello rtwave,

        Thank you for your reply.

        The original example code is really meant to be run on a 1 minute data series. If you're wanting to use this on a daily data series, you would need to add a 1 minute data series so you can get the times and exit on that time frame.

        I've adjusted the original example code to incorporate your changes, and also to be usable on Daily and non-time based charts.

        Please let us know if we may be of further assistance to you.
        Attached Files
        Kate W.NinjaTrader Customer Service

        Comment


          #5




          regards to everyone.




          over the past days i tried to activate this strategy that the people with nt support kindly made available on a couple of charts but i had not been able to get it to work as intended so that it would liquidate all positions before the weekend (the strategy would hold positions over every weekend). in consequence, i tried to create a very simple indicator that would draw an arrow below every every bar only if the day was the day of the week that had been set as an input (similar to the day one would define to have all positions liquidated before the close in the strategy). this indicator would be helpful as it could make it far easier to tell visually if all positions had been correctly liquidated before every weekend.


          Code:
          else if (State == State.DataLoaded)
                      {
                      switch(Dawe)
                          {
                              case "mo":
                                  dw = DayOfWeek.Monday;
                                  break;
                              case "tu":
                                  dw = DayOfWeek.Tuesday;
                                  break;
                              case "we":
                                  dw = DayOfWeek.Wednesday;
                                  break;
                              case "th":
                                  dw = DayOfWeek.Thursday;
                                  break;
                              case "fr":
                                  dw = DayOfWeek.Friday;
                                  break;
                              case "sa":
                                  dw = DayOfWeek.Saturday;
                                  break;
                              case "su":
                                  dw = DayOfWeek.Sunday;
                                  break;
                          }
                      }
                  }
          
                  protected override void OnBarUpdate()
                  {
                      if ((Times[0][0].DayOfWeek == dw))
                      {
                          Draw.ArrowUp(this, "iup"+CurrentBar, true, 0, Low[0] - (Dtau * TickSize), Brushes.Gray);
                      }
                  }

          when i inserted this indicator to a range chart i was working with, neither the second sample strategy that Kate created nor the indicator would work (the strategy would hold positions over weekends and the indicator would not draw any arrows at all). i then changed the chart type to 1 minute bars and both the strategy and the indicator worked correctly. i changed the chart type again to daily and both scripts were performing as they would be supposed to, i then decided to switch once more to range bars and the scripts would work fine. this was intriguing, so i repeated this same routine in another different chart and the results were the same, the strategy and the indicator only work after one has changed the type of chart at least once and then there are no problems with them. this is some strange behavior that should not happen so i decided to take the time to report it to nt here.


          i will now incorporate the relevant elements from the sampleflattenonfridaynt8v2 strategy to my own strategies but i will definitely remain very cautious with the performance of the strategy and specially the results when optimizing parameters in a strategy analyzer window. the idea of liquidating all positions before every weekend is about keeping risk under control and avoiding all gaps that happen when markets are closed. by adding the scripts necessary to exit all positions before the close on friday to my strategies i expect that the biggest losing trades will not occur anymore but i will be very cautious and check the trades list if necessary to make sure that this script works as intended because it took me several days, trials and changes to get the code to work.


          thanks, regards.

          Comment


            #6
            Hello rtwave,

            Thank you for your reply.

            That is odd, in my testing with the exact same strategy as I sent it It's working as expected for me. Did you make any changes to the strategy prior to this testing? Did you test by opening a fresh chart with no indicators or other strategies applied?

            Thanks in advance; I look forward to assisting you further.
            Kate W.NinjaTrader Customer Service

            Comment


              #7
              Hello rtwave,

              Thank you for your patience.

              Just following up to see if you'd had a chance to review my questions in my previous post.

              Please let us know if we may be of further assistance or if you have resolved your inquiry.
              Kate W.NinjaTrader Customer Service

              Comment


                #8

                Originally posted by NinjaTrader_Kate View Post
                Hello rtwave,

                Thank you for your reply.

                That is odd, in my testing with the exact same strategy as I sent it It's working as expected for me. Did you make any changes to the strategy prior to this testing? Did you test by opening a fresh chart with no indicators or other strategies applied?

                Thanks in advance; I look forward to assisting you further.


                regards to everyone,



                i had not had time to reply to these questions as i have been busy with a lot of minor refinements my strategies still needed (i'm now certain that strategies as finished by the strategy builder are nowhere near ready, there are always issues with the number of bars needed to begin making calculations and other subjects like concurrent exit and entry orders). also, i have been running tens of optimization processes and this is a time consuming and quite impractical chore that must be initiated one at a time and only after the previous one has been finished.


                from the optimization processes that i have ran, i can say that the elements that i took from the second version of the flattenonfriday strategy seem to be working. from the limited number of trade lists that i have inspected visually i can say that positions are indeed being liquidated on friday before the close.


                now, when i first tried to activate this strategy and couldn't get it to work for days it was in a couple of range charts in a workspace that i had been working on for weeks. i had activated and deleted several other strategies and indicators in those charts. i'm not a programmer, but to me it seems that placing all the day and time calculations - evaluations in the on data loaded void means that the nt platform always needs data to be reloaded before it can perform these tasks in any chart. and that's exactly what i have been doing, i either change the instrument to any other contract and back or change the bar size and back in any chart where i have activated the strategies i have developed that contain this code to liquidate all positions on friday before the close. and it has been the same story with the indicator i created, it only works after data in a chart has been reloaded.

                Comment


                  #9
                  Hello rtwave,

                  Thank you for your reply.

                  From what you said, it sounds like you're making changes to the strategies in the NinjaScript editor, then not seeing those changes show up in the indicators until you switch the chart to a different instrument and back again, is that right? Generally to see any changes made to a strategy, you'd need to reload your NinjaScript. It's a good rule of thumb to remove and re-add strategies you've edited to a chart after you recompile to make sure any changes are accounted for. Are you removing and re-adding the strategies when you make changes?

                  Thanks in advance; I look forward to resolving this for you.
                  Kate W.NinjaTrader Customer Service

                  Comment


                    #10


                    Kate, people with nt,



                    thanks.



                    from now i will do as you recommend and remove and reinsert pieces of code from a chart if i have made any changes to them.


                    in this case, however, that was not the situation at all. from the dates between posts i see that it took me 10 days to get the second sample strategy that nt made available to work correctly, even when i never made any changes to it after i received it. i created an exact copy of this strategy with a different name so that i could make changes and try different things that i would think of and it didn't work either. even the simple indicator i put together wouldn't work, and the only part of the code that seemingly was not working was the one that made the date and time calculations.


                    in the days since i shared these strange results i have been running tens of optimization processes and i can report that the fragments of code i took from the second version of this sample perform correctly so that my strategies do not hold any positions over any weekends. however, that is the case when evaluating this code in a strategy analyzer window, it is still a different story when one inserts this code into a chart window as it is necessary to reload all data so that it will work correctly. anyone can replicate these results, just insert the sample strategy or the indicator i created into an old chart that already contains other pieces of code and they won't work correctly until all data has been reloaded. this is the only piece of code with which i have had this kind of atypical results and that is why i decided to inform the people with nt.


                    that is the situation, very well, thanks.

                    Comment


                      #11
                      Hello rtwave,

                      Thank you for your reply.

                      Here's a video of a test I ran where I started with a new daily ES chart, added some indicators, ran a different sample strategy, then removed that and added the SampleFlattenOnFridayNT8V2 strategy:



                      As you can see, this is closing out when expected on Fridays without needing to reload data. Have you ensured you've adjusted the exit time to be a time within the instrument you're using's trading hours?

                      Thanks in advance; I look forward to assisting you further.
                      Kate W.NinjaTrader Customer Service

                      Comment


                        #12




                        Kate, people with nt,



                        thanks.


                        i have taken a look at the video that was linked. it does seem like the strategy you kindly provided is working flawlessly for you. in my case its performance has been inconsistent and i wouldn't have any reasons to make up the incidents i have mentioned. it could well be that i'm pushing the nt platform too hard, for weeks i have had 5 or more charts open at all times plus 5 or more strategy analyzers and other windows that right now add up to 16 of them. it is in one of those charts, that i have had around for a long time and has been saved, opened and closed with the platform innumerable times that i tried to make this logic to liquidate positions work and it took me weeks before i was able to do so. over the past four weeks, the nt platform has frozen and crashed a number of times on me when i was trying to run optimizations and i do think that i could have too many charts and too strategy analyzers open and active at the same time for the platform to be able to perform correctly.


                        in general i would say that the logic has performed well in the numerous optimization processes i have run on strategy analyzer windows over the past few weeks. but when i have activated it to charts things haven't been so smooth.


                        actually, this past friday there was an incident that called my attention. i have been using this logic to liquidate all positions before the close on friday extensively in a number of strategies of mine and starting on the 20th of october i have been automating strategies on simulator on 3 different symbols. on friday the 25th, the strategies were running automated and i was quite busy getting other work done but approximately one hour after the close of the futures session i took a look at nt and this logic had liquidated all positions beautifully:


                        Click image for larger version

Name:	nt liquidate positions friday 001.JPG
Views:	437
Size:	189.4 KB
ID:	1076644


                        this was so beautiful that i wanted to post to this thread to congratulate Kate and the nt support people for their work and also to curse my luck as i have wasted years of my time since november 2012 trying to make a useless platform (ts) work when i would have been profitable in a matter of weeks if i had started out using nt since i first began to trade.


                        however, i had the very same strategies running automated on simulator this past friday, the 1st of november, and a large position with 80 m2k contracts was never liquidated as it should have. and even more, i copied and modified this logic so that the strategies would restore all positions liquidated on fridays if the conditions to hold those positions were still present on sunday at 18:01 and those orders were never sent on the 27 as the strategies should have done.

                        Code:
                                        if ( (Times[1][0].DayOfWeek == Dawechre)
                                        && (Times[1][0].TimeOfDay == Tirepo.TimeOfDay)
                                        && ( Dtc == true )
                                        && (Position.MarketPosition != MarketPosition.Short) )
                                        {
                                        EnterShort(Convert.ToInt32(Posi), @"sp01");
                                        }
                        
                                        if ( (Times[1][0].DayOfWeek == Dawechre)
                                        && (Times[1][0].TimeOfDay == Tirepo.TimeOfDay)
                                        && ( Utc == true )
                                        && (Position.MarketPosition != MarketPosition.Long) )
                                        {
                                        EnterLong(Convert.ToInt32(Posi), @"lp01");
                                        }

                        this has been my experience with this particular piece of code, which has performed quite erratically for me in the weeks since i have been testing it. i would be glad to provide nt support with further nonsensitive information like nt logs if that could help to improve the performance of this piece of code.


                        very well, thanks, regards to everyone.

                        Comment


                          #13
                          Hello rtwave,

                          Thank you for your reply.

                          I suspect you may be correct, you may be running into some performance issues that could be affecting the strategy. I would like to take a look at your log and trace files to see if you're hitting any errors or data disconnects that could also be affecting the strategy.

                          Since log and trace files can contain identifiable personal information, we'd want you to email those to us directly rather than post them on the forums. You can do so by going to Help > Email to Support. Please ensure that include Log and Trace is checked (it should be by default). In the subject line, please include 2291618 ATTN Kate W., and also include a link to this thread in the body of the email.

                          Thanks in advance; I look forward to assisting you further.
                          Kate W.NinjaTrader Customer Service

                          Comment


                            #14
                            Hello rtwave,

                            Thanks for your patience.

                            I haven't seen your log and trace files come through the queue so I wanted to check in with you to see if you'd had the chance to send them or if you'd resolved the issue.

                            Thanks in advance; I look forward to resolving this for you.
                            Kate W.NinjaTrader Customer Service

                            Comment


                              #15



                              Kate, people with nt,



                              thanks.



                              i'm getting ready to send the log - trace files, i just want to know ¿how can i configure those files so that only information from the 20th of october and later is sent? before that weekend i was using strategy names that would give away too much information.



                              very well, thanks, regards.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by AttiM, 02-14-2024, 05:20 PM
                              12 responses
                              212 views
                              0 likes
                              Last Post DrakeiJosh  
                              Started by cre8able, 02-11-2023, 05:43 PM
                              3 responses
                              236 views
                              0 likes
                              Last Post rhubear
                              by rhubear
                               
                              Started by frslvr, 04-11-2024, 07:26 AM
                              8 responses
                              115 views
                              1 like
                              Last Post NinjaTrader_BrandonH  
                              Started by stafe, 04-15-2024, 08:34 PM
                              10 responses
                              47 views
                              0 likes
                              Last Post stafe
                              by stafe
                               
                              Started by rocketman7, Today, 09:41 AM
                              3 responses
                              11 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Working...
                              X