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

Strategy Dev. Enter and Exit trade only during specified hours

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

    Strategy Dev. Enter and Exit trade only during specified hours

    I am trying to learn NinjaScript / Strategy development. As a first step, I have used the sample NinjaScript and tried to modify so that the script can enter and exit trades based on the hours indicated in the script. However, when I execute the script, I see that the script is executing trades at all hours.

    Any help is much appreciated in pointing out the error in logic.

    Thank you,
    Walker

    //
    // Copyright (C) 2015, NinjaTrader LLC <www.ninjatrader.com>.
    // NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
    //
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.Cbi;
    #endregion

    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class Mytimes2 : Strategy
    {
    private int fast;
    private int slow;

    protected override void OnStateChange()
    {
    if(State == State.SetDefaults)
    {
    Fast = 10;
    Slow = 27;
    Calculate = Calculate.OnBarClose;
    Name = "MyTimes2";
    }

    else if(State == State.Configure)
    {
    /* Add a secondary bar series.
    Very Important: This secondary bar series needs to be smaller than the primary bar series.

    Note: The primary bar series is whatever you choose for the strategy at startup. In this example I will
    reference the primary as a 5min bars series. */
    AddDataSeries(Data.BarsPeriodType.Tick, 1);

    // Add two EMA indicators to be plotted on the primary bar series
    AddChartIndicator(EMA(Fast));
    AddChartIndicator(EMA(Slow));

    /* Adjust the color of the EMA plots.
    For more information on this please see this tip: http://www.ninjatrader-support.com/v...ead.php?t=3228 */
    EMA(Fast).Plots[0].Brush = Brushes.Blue;
    EMA(Slow).Plots[0].Brush = Brushes.Green;
    }
    }

    protected override void OnBarUpdate()
    {
    /* When working with multiple bar series objects it is important to understand the sequential order in which the
    OnBarUpdate() method is triggered. The bars will always run with the primary first followed by the secondary and
    so on.

    Important: Primary bars will always execute before the secondary bar series.
    If a bar is timestamped as 12:00PM on the 5min bar series, the call order between the equally timestamped 12:00PM
    bar on the 1min bar series is like this:
    12:00PM 5min
    12:00PM 1min
    12:01PM 1min
    12:02PM 1min
    12:03PM 1min
    12:04PM 1min
    12:05PM 5min
    12:05PM 1min

    When the OnBarUpdate() is called from the primary bar series (5min series in this example), do the following */

    if (BarsInProgress == 0)
    {

    // If not flat print our open PnL
    if (Position.MarketPosition != MarketPosition.Flat)

    ExitLong();
    ExitShort();
    Print("Open PnL: " + Position.GetUnrealizedProfitLoss(PerformanceUnit.P oints, Close[0]) +" Start of Script PL 0 ");


    {
    // When the fast EMA crosses above the slow EMA, enter long on the secondary (1min) bar series
    if (CrossAbove(EMA(Fast), EMA(Slow), 1))
    {
    {
    if ((ToTime(Time[0]) >= 015000 && ToTime(Time[0]) <= 230000)
    /* || (ToTime(Time[0]) >= 645000 && ToTime(Time[0]) <= 925000)
    || (ToTime(Time[0]) >= 100000 && ToTime(Time[0]) <= 121500)*/
    || (ToTime(Time[0]) >= 141500 && ToTime(Time[0]) <= 173000)
    /* || (ToTime(Time[0]) >= 200000 && ToTime(Time[0]) <= 230000) */
    );

    /* The entry condition is triggered on the primary bar series, but the order is sent and filled on the
    secondary bar series. The way the bar series is determined is by the first parameter: 0 = primary bars,
    1 = secondary bars, 2 = tertiary bars, etc. */

    EnterLong(1, 1, "Long: 1min");

    }

    Print("Open PnL: " + Position.GetUnrealizedProfitLoss(PerformanceUnit.P oints, Close[0]) +" After Long Entry ");

    }
    // When the fast EMA crosses below the slow EMA, enter short on the secondary (1min) bar series
    else if (CrossBelow(EMA(Fast), EMA(Slow), 1))
    {
    {
    if ((ToTime(Time[0]) >= 015000 && ToTime(Time[0]) <= 230000)
    /* || (ToTime(Time[0]) >= 645000 && ToTime(Time[0]) <= 925000)
    || (ToTime(Time[0]) >= 100000 && ToTime(Time[0]) <= 121500) */
    || (ToTime(Time[0]) >= 141500 && ToTime(Time[0]) <= 173000)
    /* || (ToTime(Time[0]) >= 200000 && ToTime(Time[0]) <= 230000) */
    );



    /* The entry condition is triggered on the primary bar series, but the order is sent and filled on the
    secondary bar series. The way the bar series is determined is by the first parameter: 0 = primary bars,
    1 = secondary bars, 2 = tertiary bars, etc. */
    EnterShort(1, 1, "Short: 1min");

    }
    Print("Open PnL: " + Position.GetUnrealizedProfitLoss(PerformanceUnit.P oints, Close[0]) +" After Short Entry ");
    }



    // When the OnBarUpdate() is called from the secondary bar series, do nothing.
    else
    {
    /* if ( (ToTime(Time[0]) >= 235000 && ToTime(Time[0]) <= 636000)
    || (ToTime(Time[0]) >= 924000 && ToTime(Time[0]) <= 945000)
    || (ToTime(Time[0]) >= 121500 && ToTime(Time[0]) <= 141000)
    || (ToTime(Time[0]) >= 150700 && ToTime(Time[0]) <= 160200)
    || (ToTime(Time[0]) >= 182900 && ToTime(Time[0]) <= 235900) && PositionAccount.MarketPosition != MarketPosition.Flat)

    ExitLong();
    ExitShort();
    Print("Open PnL: " + Position.GetUnrealizedProfitLoss(PerformanceUnit.P oints, Close[0]) +"End of Script");

    {
    if (Position.MarketPosition == MarketPosition.Flat)
    Print("Open PnL: " + Position.GetUnrealizedProfitLoss(PerformanceUnit.P oints, Close[0])+"Confirm All Pos Closed");
    } */

    return;
    }
    }

    }

    }
    #region Properties

    [Range(1, int.MaxValue), NinjaScriptProperty]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Fast", GroupName = "NinjaScriptParameters", Order = 0)]
    public int Fast
    { get; set; }

    [Range(1, int.MaxValue), NinjaScriptProperty]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Slow", GroupName = "NinjaScriptParameters", Order = 0)]
    public int Slow
    { get; set; }

    #endregion
    }
    }

    Last edited by NinjaTrader_Jesse; 02-21-2020, 04:22 PM. Reason: removed protected/compiled file

    #2
    Hello Walker DM,

    Thank you for the post.

    A quick note, I had to remove the attachment as it was a compiled version of your script. If you want to re upload the Source code please feel free to do that.

    Before I can go further into this I would like to see the actual file, if your conditions are formed like you have them here this may just be a formatting error. You have a semi colon at the end of your condition as far as I can tell:

    Code:
    if ((ToTime(Time[0]) >= 015000 && ToTime(Time[0]) <= 230000)
    /* || (ToTime(Time[0]) >= 645000 && ToTime(Time[0]) <= 925000)
    || (ToTime(Time[0]) >= 100000 && ToTime(Time[0]) <= 121500)*/
    || (ToTime(Time[0]) >= 141500 && ToTime(Time[0]) <= 173000)
    /* || (ToTime(Time[0]) >= 200000 && ToTime(Time[0]) <= 230000) */
    [B]);[/B]
    If that is correct and you have a ); at the end of the if statement the condition will be bypassed because you ended it with the semicolon. Try to make sure your conditions are specifically in this format:

    if(condition || condition2)
    {

    }

    There should be no semicolons in your if condition or following it before the curly braces.

    If you can otherwise upload the file directly I can take a look at that to see if anything else sticks out.



    I look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Hello Jesse,
      Going through your notes.. in the mean while I have uploaded the source file. Looking forward to your help.

      Thank you,
      Walker
      Attached Files

      Comment


        #4
        Hello Walker DM,

        Thank you for providing the file, seeing the actual formatting in the script helps.

        It looks like you have some semi colons which are in the wrong location, when you place a semi colon at the end of an if statement that is valid and will terminate the condition.

        Here is a quick example of what I mean:

        Code:
        if(condition);
        {
            //always true
        }
        Code:
        if(condition)
        {
           // conditionally true
        }
        The { } just wrap the code in a body and the semi colon on the if statement effectivly lets the code run any time.



        To fix this you just need to remove the ; at the end of each if statement.


        Code:
        if         ((ToTime(Time[0])   >= 015000   && ToTime(Time[0]) <= 230000) 
                                /*    || (ToTime(Time[0]) >= 645000   && ToTime(Time[0]) <= 925000) 
                                    || (ToTime(Time[0]) >= 100000   && ToTime(Time[0]) <= 121500) */
                                    || (ToTime(Time[0]) >= 141500   && ToTime(Time[0]) <= 173000)
                                /*    || (ToTime(Time[0]) >= 200000   && ToTime(Time[0]) <= 230000) */
                                )[B];  <----- remove this[/B]


        Also looking in the script you have some braces around your condition rather than after it:
        Code:
        // When the fast EMA crosses below the slow EMA, enter short on the secondary (1min) bar series
        else if (CrossBelow(EMA(Fast), EMA(Slow), 1)) 
        {    
        [COLOR=#FFA500]   {    <-- problematic[/COLOR]
                if         ((ToTime(Time[0])   >= 015000   && ToTime(Time[0]) <= 230000) 
                /*    || (ToTime(Time[0]) >= 645000   && ToTime(Time[0]) <= 925000) 
                    || (ToTime(Time[0]) >= 100000   && ToTime(Time[0]) <= 121500) */
                    || (ToTime(Time[0]) >= 141500   && ToTime(Time[0]) <= 173000)
                /*    || (ToTime(Time[0]) >= 200000   && ToTime(Time[0]) <= 230000) */
                )[COLOR=#FFA500]; <-- problematic[/COLOR]
        
        
        
            /* The entry condition is triggered on the primary bar series, but the order is sent and filled on the
            secondary bar series. The way the bar series is determined is by the first parameter: 0 = primary bars,
            1 = secondary bars, 2 = tertiary bars, etc. */
            EnterShort(1, 1, "Short: 1min");
        
            }
            Print("Open PnL: " + Position.GetUnrealizedProfitLoss(PerformanceUnit.Points, Close[0]) +" After Short Entry ");        
        }

        An if statement should always be in the format of if(condition) { }

        In what you have provided the curly brace is before the if statement and there is a semi colon, so you would need to make the following changes. I also removed the comments here to simplify the condition:


        Code:
        // When the fast EMA crosses below the slow EMA, enter short on the secondary (1min) bar series
        else if (CrossBelow(EMA(Fast), EMA(Slow), 1)) 
        {    
            if((ToTime(Time[0])   >= 015000   && ToTime(Time[0]) <= 230000) || (ToTime(Time[0]) >= 141500   && ToTime(Time[0]) <= 173000))
            {
                EnterShort(1, 1, "Short: 1min");                    
            }
            Print("Open PnL: " + Position.GetUnrealizedProfitLoss(PerformanceUnit.Points, Close[0]) +" After Short Entry ");        
        }

        I look forward to being of further assistance.
        JesseNinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by love2code2trade, 04-17-2024, 01:45 PM
        4 responses
        31 views
        0 likes
        Last Post love2code2trade  
        Started by cls71, Today, 04:45 AM
        2 responses
        10 views
        0 likes
        Last Post eDanny
        by eDanny
         
        Started by proptrade13, Today, 11:06 AM
        0 responses
        5 views
        0 likes
        Last Post proptrade13  
        Started by kulwinder73, Today, 10:31 AM
        1 response
        10 views
        0 likes
        Last Post NinjaTrader_Erick  
        Started by RookieTrader, Today, 09:37 AM
        3 responses
        15 views
        0 likes
        Last Post NinjaTrader_ChelseaB  
        Working...
        X