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

Output during OnBarUpdate only once

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

    Output during OnBarUpdate only once

    Hi,
    is there a way to set up Ninjascript to only print to the output window once and not on every 5min Bar? I played with OnOrderUpdate and OnExecutionUpdate but cant figure it out.
    Example I want the Entry Price and Stop and Target levels print on the output window. But only when the entry happens. Currently I get the same output on every bar until the order is exited. I understand that happens because it is OnBarUpdate but how can I limit it?

    #2
    Hello JBU1314,

    To limit the prints only to when Entry happens you would need to add the print into the same condition as the entry.

    For example :

    Code:
    if(Close[0] > Open[0])
    {
        EnterLong();
        Print("Entered: " + Close[0]);
    }
    This should work unless the condition you have becomes true over and over and the repeated calls to Enter are ignored, in that case the print would continue to happen. If that is your problem, you could add a bool to control the print more closely.

    Code:
    private bool doOneTime = true;
    protected override void OnBarUpdate
    {
        if(Close[0] > Open[0])
        {
            EnterLong();
            if(doOneTime)
            {
                Print("Entered: " + Close[0]);
                doOneTime = false;
            }
        }
    }
    When doOneTime is set to true, the print would happen and reset to false so it cant print again. The reset of doOneTime would need to be added when you are Flat as one example, or after a fill, really any time you feel nessasary to reset the print again.

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

    Comment


      #3
      Thank you Jesse, this was very helpful. Can I also use this approach to enter a Stop Loss Level which is depended on the point of entry? E.g. I want to set my stop loss as a multiple of ATR at the point of entry but dont want the stop loss adjust on every BarUpdate...

      Comment


        #4
        Hello JBU1314,

        Yes this would also likely work in that situation, really a bool can be used to create any number of little conditions like these to aid in refining the logic as needed.

        For a Set method, you would want to ensure to Set the price before calling the entry though, here is a example useing the previous example:

        Code:
        private bool doOneTime = true;
        protected override void OnBarUpdate
        {
            if(Close[0] > Open[0])
            {
                if(doOneTime)
                {
                    SetStopLoss(...);
                    // notice we do not reset doOneTime here, do it in the last usage below
                }
                EnterLong();
                if(doOneTime)
                {
                    Print("Entered: " + Close[0]);
                    doOneTime = false;
                }
            }
        }

        I specifically divided this example into two if statements to show how you could use this if you wanted to add more of them, otherwise this could be combined into a single if statement as well:

        Code:
        private bool doOneTime = true;
        protected override void OnBarUpdate
        {
            if(Close[0] > Open[0])
            {
                if(doOneTime)
                {
                    SetStopLoss(...);
                    Print("Entered: " + Close[0]);
                    doOneTime = false;
                }
                EnterLong();
            }
        }

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

        Comment


          #5
          Thank you very much Jesse. If I wanted to do OnTickUpdate... Print("Entered: " + Close[0]); would not give me the accurate Entry Price correct? To accomplish this would I have to implement on ExecutionUpdate?

          Comment


            #6
            Hello JBU1314,

            Well the price in these examples have just been the Close price at the time of the entry, on a Tick by Tick basis this would give the last price at the time Enter was called. If you want the true entry price you were filled at, you could look for the Order object in OnExecutionUpdate. http://ninjatrader.com/support/helpG...ub=onexecution

            You could use the help guide examples to locate the entry order, once located you could get the average fill price to know specifically what price was filled. You could also add a Print in to OnExecutionUpdate, this would not need the bool from the previous examples because this is only called for Executions and not every bar. This could be used in place of the prior examples where we store the price during the time of the entry.

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

            Comment


              #7
              Hi Jesse,
              I was playing arround with your feedback but it just does not work. What did I miss? Any idea?

              protected override void OnBarUpdate()
              {
              if(base.CurrentBar < BarsRequiredToTrade)
              return;

              double SL = (_atr[0] * this.ATRM1);
              double PT = (_atr[0] * this.ATRM2);


              if(Close[0] > Open[0])
              {

              if(DoOnce)
              {
              SetStopLoss(CalculationMode.Price, SL);
              SetProfitTarget(CalculationMode.Price, PT);
              }
              EnterLong("B"+CurrentBar);
              if(DoOnce)
              {
              P("CASSIOPEIA - Entered Long @:" + Close[0]);
              P(String.Format("CASSIOPEIA - ATR at Entry is: {0:0.00}", _atr[0]));
              P(String.Format("CASSIOPEIA - Set StopLoss @: {0:0.00}", SL));
              P(String.Format("CASSIOPEIA - Set ProfitTarget @: {0:0.00}", PT));
              DoOnce = false;
              }

              }

              if (IsFlat)
              {
              DoOnce = true;

              }

              Comment


                #8
                I also did declare
                public class CATRTEST : Strategy
                {
                bool DoOnce = true;

                Comment


                  #9
                  Hello JBU1314,

                  Could you provide the whole script? I am not seeing where you are setting the variable "IsFlat". If you are not setting IsFlat to true somewhere, this is likely the problem as the condition you want needs IsFlat to be true before resetting the DoOnce variable.

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

                  Comment


                    #10
                    Hi Jesse, hope you had a nice weekend. Here the complete code.

                    #region Using declarations
                    using System;
                    using System.Collections.Generic;
                    using System.ComponentModel;
                    using System.ComponentModel.DataAnnotations;
                    using System.Linq;
                    using System.Text;
                    using System.Threading.Tasks;
                    using System.Windows;
                    using System.Windows.Input;
                    using System.Windows.Media;
                    using System.Xml.Serialization;
                    using NinjaTrader.Cbi;
                    using NinjaTrader.Gui;
                    using NinjaTrader.Gui.Chart;
                    using NinjaTrader.Gui.SuperDom;
                    using NinjaTrader.Gui.Tools;
                    using NinjaTrader.Data;
                    using NinjaTrader.NinjaScript;
                    using NinjaTrader.Core.FloatingPoint;
                    using NinjaTrader.NinjaScript.Indicators;
                    using NinjaTrader.NinjaScript.DrawingTools;
                    #endregion

                    //This namespace holds Strategies in this folder and is required. Do not change it.
                    namespace NinjaTrader.NinjaScript.Strategies.FINAL
                    {
                    public class NTSUPPORT : Strategy
                    {
                    bool DoOnce = true;
                    ATR _atr;

                    protected override void OnStateChange()
                    {
                    if (State == State.SetDefaults)
                    {
                    Description = @"THIS HAS TO WORK!";
                    Name = "NTSUPPORT";
                    Calculate = Calculate.OnBarClose;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    IsFillLimitOnTouch = false;
                    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution = OrderFillResolution.Standard;
                    Slippage = 0;
                    StartBehavior = StartBehavior.WaitUntilFlat;
                    TimeInForce = TimeInForce.Gtc;
                    TraceOrders = false;
                    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade = 20;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration = true;

                    ATRM1 = 3.0;
                    ATRM2 = 6.0;
                    BEA = 4;

                    }
                    else if (State == State.Configure)
                    {

                    _atr = ATR(14);
                    base.AddChartIndicator(_atr);

                    base.ClearOutputWindow();

                    }
                    }

                    protected override void OnBarUpdate()
                    {
                    if(base.CurrentBar < BarsRequiredToTrade)
                    return;

                    double _betrigger = Position.AveragePrice + BEA;
                    double _betriggershort = Position.AveragePrice - BEA;

                    double breakeven = Position.AveragePrice;

                    double SL = (_atr[0] * this.ATRM1);
                    double PT = (_atr[0] * this.ATRM2);

                    //TRADE ENTRY
                    // LONG SIDE

                    if (Close[0] > Open[0])
                    {

                    if(DoOnce)
                    {
                    SetStopLoss(CalculationMode.Price, SL);
                    SetProfitTarget(CalculationMode.Price, PT);
                    }
                    EnterLong("B"+CurrentBar);
                    if(DoOnce)
                    {
                    P("CASSIOPEIA - Entered Long @:" + Close[0]);
                    P(String.Format("CASSIOPEIA - ATR at Entry is: {0:0.00}", _atr[0]));
                    P(String.Format("CASSIOPEIA - Set StopLoss @: {0:0.00}", SL));
                    P(String.Format("CASSIOPEIA - Set ProfitTarget @: {0:0.00}", PT));
                    DoOnce = false;
                    }

                    }

                    if (IsFlat)
                    {
                    DoOnce = true;
                    }


                    }


                    #region Helpers
                    bool IsFlat { get { return base.Position.MarketPosition == MarketPosition.Flat; }}
                    bool IsLong { get { return base.Position.MarketPosition == MarketPosition.Long; }}
                    bool IsShort { get { return base.Position.MarketPosition == MarketPosition.Short; }}
                    private void P(string msg)
                    {
                    Print(Time[0].ToShortDateString() + " " + Time[0].ToShortTimeString() + ":" + msg);
                    }
                    #endregion


                    #region Properties

                    [NinjaScriptProperty]
                    [Range(1, double.MaxValue)]
                    [Display(ResourceType = typeof(Custom.Resource), Name="ATRM1", Order=1, GroupName="NinjaScriptStrategyParameters")]
                    public double ATRM1
                    { get; set; }

                    [NinjaScriptProperty]
                    [Range(1, double.MaxValue)]
                    [Display(ResourceType = typeof(Custom.Resource), Name="ATRM2", Order=2, GroupName="NinjaScriptStrategyParameters")]
                    public double ATRM2
                    { get; set; }

                    [NinjaScriptProperty]
                    [Range(1, int.MaxValue)]
                    [Display(ResourceType = typeof(Custom.Resource), Name="BEA", Order=3, GroupName="NinjaScriptStrategyParameters")]
                    public double BEA
                    { get; set; }


                    #endregion

                    }
                    }

                    Comment


                      #11
                      Hello JBU1314,

                      Thank you for providing the full code, seeing the helper properties you have added clears up the question on the IsFlat. It appears this is likely caused by the placement of the if condition for IsFlat. Because the position will not be updated in the same bar that you call EnterLong, the if(IsFlat) will be true resetting the variable. You would likely need to move this check to the top of OnBarUpdate to wait for the next call to OnBarUpdate:
                      Code:
                      protected override void OnBarUpdate()
                      {
                      if(base.CurrentBar < BarsRequiredToTrade)
                      return;
                      
                      if (IsFlat)
                      {
                      DoOnce = true;	
                      }
                      Could you try this change and see if this corrects the result?

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

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Rapine Heihei, Today, 07:51 PM
                      0 responses
                      3 views
                      0 likes
                      Last Post Rapine Heihei  
                      Started by frslvr, 04-11-2024, 07:26 AM
                      5 responses
                      96 views
                      1 like
                      Last Post caryc123  
                      Started by algospoke, 04-17-2024, 06:40 PM
                      6 responses
                      49 views
                      0 likes
                      Last Post algospoke  
                      Started by arvidvanstaey, Today, 02:19 PM
                      4 responses
                      11 views
                      0 likes
                      Last Post arvidvanstaey  
                      Started by samish18, 04-17-2024, 08:57 AM
                      16 responses
                      61 views
                      0 likes
                      Last Post samish18  
                      Working...
                      X