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

Closing trades specially when using Data Series "Custom Range" in Time Frames

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

    Closing trades specially when using Data Series "Custom Range" in Time Frames

    As I continue to do my testing specially around dates in which there is a partial holiday or a full holiday, I am using the Custom Range in the Data Series Time Frames section to set the date range for which I wan to run the strategy.

    Whenever I set a range an by the time it runs through the historical time range, the strategy might leave a position open as the trigger has not been reached. Usually my triggers are either a stopLoss order or a target profit. By the time the strategy evaluates the last candle of the range, I have an Open order and two "Working" orders. The two "working orders are OCO since they where associated with the same entry order string.

    I am am using the Managed approach for order management using the techniques outline in Advance Order handling (using order objects and OnOrderUpdate() and OnExecutionUpdate() methods.

    I would like to close and destroyed the "Working" orders (stopLoss and targetProfit).

    Where should I do this?

    I am trying to do it in the else if (State == State.Transition) state.

    When I do this I get an error that I am trying to cancel a Live order. I am never reaching out the state of RealTime since the Date range end in another date which is not the current day.

    I am also aware of a strategy parameter which allows you to close all open position x number of seconds before the EOD. I was thinking of locating an event, check to see that (Position.MarketPosition != MarketPosition.Flat) and then submit a ExitLong or ExitShort order pase of the Position.MarketPosition.

    Please advice.


    #2
    Hello GARZONJ,

    Thank you for your post.

    Is this testing that you're doing in the Strategy Analyzer?

    I'd try this, which should trigger any open position to exit with an exit market order on the last historical bar:

    if (State == State.Historical && CurrentBar == Count — 2)
    {
    // submit your exit orders here
    }

    Below is a link to the help guide on the 'State' NinjaScript property.


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

    Comment


      #3
      Kate,

      I am using running the Strategy through the Chart; right click | Strategies ....

      From your sample code, I was able to gather the following:
      • By the time it reaches the Historical State, the event gets executed only one time when CurrentBar is -1 (the first bar has not been processed)
      • By the time it reaches the Historical State, the strategy already knows how many bar it will Dra under State = Historical. This is stored in Count. I was not expecting this one!
      • Although I am not using a Today's date within the Custom Range (in my example I am using ES 12-19 on a 15-min from 11/12/19 to 11/14/19) , once the strategy is done processing all the Historical bars, the RealTime state is reached. I was not expecting this one!
      In my test sample, so that I have an open position towards the end of the historical bars, I am using 10 for Fast and 45 for Slow.

      I am including my quick test script.

      Please let me know if I am closing any open trade coming from historical at the right place. Should I close it once it reaches the Transition state? Definitely not in the RealTime static as I would have to deal with Live orders. I also know that I cannot do anything in the Historical state.

      Please advice.


      Attached Files

      Comment


        #4
        Hello GARZONJ,

        Thank you for your reply.

        You were definitely on the right track, the only real issue was that you were trying to use Time[0] in OnStateChange() - since OnStateChange() isn't synced to bars, to print the time you can use DateTime.Now there.

        Here's my revised version that should illustrate nicely exactly what happens if you take a look in a NinjaScript Output window when you run it. I've turned on the Trace Orders function here, as well as added a name to the exit so it's easier to tell that it is indeed the exit we intended and checking that we're still in State.Historical before exiting, but really all I've done here is clean things up and rearrange a bit:

        Code:
            public class TestingDateRange : Strategy
            {
                private SMA smaFast;
                private SMA smaSlow;
        
                protected override void OnStateChange()
                {
                    if (State == State.SetDefaults)
                    {
                        Description                                    = @"Enter the description for your new custom Strategy here.";
                        Name                                        = "TestingDateRange";
                        // Turn on trace orders so you can tell when the exit order is fired
                        TraceOrders                                    = true;
                        IsInstantiatedOnEachOptimizationIteration    = true;
        
                        Fast        = 10;
                        Slow        = 25;
                    }
                    else if (State == State.DataLoaded)
                    {
                        smaFast = SMA(Fast);
                        smaSlow = SMA(Slow);
        
                        smaFast.Plots[0].Brush = Brushes.Goldenrod;
                        smaSlow.Plots[0].Brush = Brushes.SeaGreen;
        
                        AddChartIndicator(smaFast);
                        AddChartIndicator(smaSlow);
                    }
                    else if (State == State.Historical)
                    {
                        // it's better practice to do these all as "else if" rather than just ifs
                        Print(State + " in " + Name + "    " + DateTime.Now);
        
                        Print("I know the CurrentBar " + CurrentBar + " and the total number of bars which will be drawn " + Count);
                    }
                    else if (State == State.Realtime)
                    {
                        Print(State + " in " + Name + "    " + DateTime.Now + "  RealTime occurs at CurrentBar " + CurrentBar);//);// + " TraceOrders " + TraceOrders);
                    }
                    else if (State == State.Transition)
                    {
                        Print(State + " in " + Name + "    " + DateTime.Now + "  Transition occurs at CurrentBar " + CurrentBar + "    " + Position.MarketPosition);
                    }
        
                }
        
                protected override void OnBarUpdate()
                {            
                    if (CurrentBar < BarsRequiredToTrade)
                        return;
        
                    if (CrossAbove(smaFast, smaSlow, 1))
                    {
                        EnterLong();
                    }
                    else if (CrossBelow(smaFast, smaSlow, 1))
                    {
                        EnterShort();
                    }
                    // we need to do the exiting in OnBarUpdate because that's where we are processing the bars.
                    // if we're on the last historical bar, our market position is not flat, and we're still in State.Historical, exit.
                    if (CurrentBar == Count - 2 && Position.MarketPosition != MarketPosition.Flat && State == State.Historical)
                    {
                        if (Position.MarketPosition == MarketPosition.Short)
                        {
                            Print("I am SHORT " + CurrentBar);
        
                            ExitShort("ExitShortBeforeRealTime","");
                        }
                        else 
                        {
                            Print("I am LONG " + CurrentBar);
        
                            ExitLong("ExitLongBeforeRealTime","");
                        }
        
                    }
        
                }
        Please let us know if we may be of further assistance to you.
        Kate W.NinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by yertle, Yesterday, 08:38 AM
        7 responses
        28 views
        0 likes
        Last Post yertle
        by yertle
         
        Started by bmartz, 03-12-2024, 06:12 AM
        2 responses
        21 views
        0 likes
        Last Post bmartz
        by bmartz
         
        Started by funk10101, Today, 12:02 AM
        0 responses
        6 views
        0 likes
        Last Post funk10101  
        Started by gravdigaz6, Yesterday, 11:40 PM
        1 response
        9 views
        0 likes
        Last Post NinjaTrader_Manfred  
        Started by MarianApalaghiei, Yesterday, 10:49 PM
        3 responses
        11 views
        0 likes
        Last Post NinjaTrader_Manfred  
        Working...
        X