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

Track/Store Max Bid Value Since Entry

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

    Track/Store Max Bid Value Since Entry

    Hi,

    I'm trying to do the following:

    Track/store the Bid values since my buy order got filled. Then get the max value from the Bid values stored/tracked.

    I found about the Max.Math function and got this far:

    double maxValue = Math.Max( );

    How do I state the range from Entry Price Bid to the Real Time Bid?

    I mean some pseudo code like that Range:

    PositionAccount.AveragePrice.Bid TO getCurrentBid()


    Example to illustrate:

    PositionAccount.AveragePrice.Bid = 1.01 (Entry price, entered at 12 :00 pm)

    1.02, 1.03, 0.99 (Bids fluctuations, from 12:00 pm to 12:09 pm)

    1.07 (current real time Bid, at 12:10 pm)

    1.07 = double maxValue = Math.Max(PositionAccount.AveragePrice.Bid TO getCurrentBid() );

    #2
    Hi PaulMohn, thanks for posting.

    Set up a boolean variable at the class level, then switch the boolean to true/false in the OnPositionUpdate method. When the Position changes to long/short, set the boolean to true and while it is true in OnBarUpdate, assign the bid/ask values to a custom Series<T> object that can hold the values (a Series object is an array with a size always equal to the number of bars on the chart).

    Best regards,
    -ChrisL
    Chris L.NinjaTrader Customer Service

    Comment


      #3
      Hi Chris,
      Thanks for the process detail. That seems complex but I think i get the principle of it. I'll do some modeling and be back.

      Comment


        #4
        Here's the model I've come to so far. Supposing it's correct, I still don't understand how to assign the Bid values to the custom Series<t> variable (I'm stuck at bidValsfrmEntry = Math.Max( ... ); ).

        Also for some reason I miss my script works with AddDataSeries(BarsPeriodType.Tick, 1); and (BarsInProgress != 0) return;
        but it stops working with AddDataSeries("", BarsPeriodType.Tick, 1, MarketDataType.Bid); and distinct/separated blocks of BarsInProgress statements ( like in the structure oshown in this sample https://ninjatrader.com/support/foru...893#post472893)

        What is the correct way to assign the Bid values to the custom Series<t> variable you'd recommend?
        I'll go to sleep now and will be back tomorrow. Thanks so much.

        1. Set up a boolean variable (private bool maxBid; ) at the class level
        (+ Custom Series <T> (private Series<double> bidValsfrmEntry; ))
        Code:
        namespace NinjaTrader.NinjaScript.Strategies
        {
             public class AutoExitTwo : Strategy
             {
                   private bool maxBid;
        
                   private Series<double> bidValsfrmEntry;
        Do I have to set/initialize the maxBid bool in the State.SetDefaults scope as well? For example:
        Code:
        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
             {
                  ...
                  maxBid = false;
        2. ...then switch the boolean to true/false in the OnPositionUpdate method.
        Code:
        protected override void OnPositionUpdate(Cbi.Position position, double averagePrice, int quantity, Cbi.MarketPosition marketPosition)
        {
             if (position.MarketPosition == MarketPosition.Flat)
             {
                  maxBid = false;
             }
        }
        3. When the Position changes to long/short, set the boolean to true
        Code:
        protected override void OnBarUpdate()
        {
             if (CurrentBar < BarsRequiredToTrade)
                  return;
        
             // ??? BarsInProgress Sample 1
             // https://ninjatrader.com/support/forum/forum/ninjatrader-7/general-development/80886-uptick-or-downtick?p=701325#post701325
        
             // ???  BarsInProgress Sample 2
             // https://ninjatrader.com/support/forum/forum/ninjatrader-7/indicator-development-aa/47241-how-do-i-retrieve-bid-ask-and-last?p=472893#post472893
             if (BarsInProgress != 0)
                  return;
        
        if (PositionAccount.MarketPosition == MarketPosition.Long)
        {
             {
                  maxBid = true;
             }
        ...and while it is true in OnBarUpdate, assign the bid/ask values to a custom Series<T> object that can hold the values (a Series object is an array with a size always equal to the number of bars on the chart).
        Series<T> sample SampleCustomSeries_NT8.zip (taken as model)

        Code:
        // bidValsfrmEntry declaration
        namespace NinjaTrader.NinjaScript.Strategies
        {
             public class AutoExitTwo : Strategy
             {
                  private bool maxBid;
        
                  private Series<double> bidValsfrmEntry;
        
              ...
        
        // ??? assign the Bid values to the custom [U][URL="https://ninjatrader.com/support/helpGuides/nt8/NT%20HelpGuide%20English.html?seriest.htm"]Series<T>[/URL][/U]
        else if (State == State.Configure)
        {
             // ??? The script works with that Simple .Tick statement, but it does not work with the following MarketDataType.Bid statemeent
             //AddDataSeries(BarsPeriodType.Tick, 1);
        
             // Using Historical Bid/Ask Series
             // [URL="https://ninjatrader.com/support/helpGuides/nt8/NT%20HelpGuide%20English.html?using_historical_bid_ask_serie.htm"]https://ninjatrader.com/support/help..._ask_serie.htm[/URL]
        
             AddDataSeries("", BarsPeriodType.Tick, 1, MarketDataType.Bid);
        
        ...
        
        // ??? the [URL="https://ninjatrader.com/support/helpGuides/nt8/samples/SampleCustomSeries_NT8.zip"]SampleCustomSeries_NT8.zip[/URL] uses the following, I'm not sure how it's relevant for my script
        else if (State == State.DataLoaded)
        {
             bidValsfrmEntry = new Series<double>(this, MaximumBarsLookBack.Infinite);
        }
        
        ...
        
        // I still don't know how to assign the Bid values to the custom series<t> variable bidValsfrmEntry
        protected override void OnBarUpdate()
        {
             if (CurrentBar < BarsRequiredToTrade)
                  return;
        
             if (BarsInProgress != 0)
                  return;
        
             if (PositionAccount.MarketPosition == MarketPosition.Long)
             {
                  {
                       maxBid = true;
                       bidValsfrmEntry = Math.Max(Close[0]);
                  }
        
        // DataSeries object method is set the same way as a plotted value as mentioned in the the [URL="https://ninjatrader.com/support/helpGuides/nt8/samples/SampleCustomSeries_NT8.zip"]SampleCustomSeries_NT8.zip[/URL]
        //I'm not if this property needs updating nor sure how to update it
        #region Properties
        
        [Range(1, int.MaxValue), NinjaScriptProperty]
        [Display(ResourceType = typeof(Custom.Resource), Name = "Period", GroupName = "NinjaScriptParameters", Order = 0)]
        public int Period
        { get; set; }
        
        #endregion
        
        }
        Last edited by PaulMohn; 12-24-2021, 04:31 PM. Reason: added MaximumBarsLookBack.Infinite

        Comment


          #5
          Hello PaulMohn,

          To assign a series value you would use the BarsAgo syntax:

          Code:
          bidValsfrmEntry[0] = somevalue;
          That would set the current value of the plot to some value of your choice.

          The second AddDataSeries syntax you have shown needs the instrument, that would be the only observation I could make as to why it may not be working.

          JesseNinjaTrader Customer Service

          Comment


            #6
            Hello Jesse and thank you for the reply and tips! I'll get back on your first point tomorrow.
            For your second point how can I make it not instrument specific (I'd like to use the same code on multiple instruments)?

            Comment


              #7
              Hello PaulMohn,

              You can use one of the overrides that does not require an instrument or pass null as the instrument for the others.

              AddDataSeries(BarsPeriod barsPeriod)
              AddDataSeries(BarsPeriodType periodType, int period)
              JesseNinjaTrader Customer Service

              Comment


                #8
                Ok thanks. I'm not sure what you mean by overrides. What overrides do not require an instrument? What would be the use of this method (why choosing overrides)? I'd prefer the simpler way if possible.


                How do we pass null for instrument?
                Code:
                AddDataSeries("null", BarsPeriodType.Tick, 1, MarketDataType.Bid);
                Code:
                AddDataSeries(null, BarsPeriodType.Tick, 1, MarketDataType.Bid);
                I've found this post about it and I'm confused:
                https://ninjatrader.com/support/foru...932#post783932

                Oh I've reread and I think I got what you meant by passing null for instrument, just leave it blank? like the second syntax example:

                Code:
                AddDataSeries(BarsPeriodType.Tick, 1, MarketDataType.Bid);
                Is that correct?
                Last edited by PaulMohn; 01-05-2022, 03:37 PM. Reason: pass null = leave blank?

                Comment


                  #9
                  Hello PaulMohn,

                  The code i provided in the last post are the overrides i was referring to that do not require an instrument. There is just not an instrument needed with those two.

                  "null" is not an instrument that would be an instrument named null because you have used quotes. To make a null object you would specify null without quotes, (null, ...

                  It looks like you have understood correctly.

                  .

                  JesseNinjaTrader Customer Service

                  Comment


                    #10
                    Ok great thanks again. I'll proceed with the code tomorrow.

                    Comment


                      #11
                      Hello Jesse,
                      I've restarted my strategy code from scratch again to proceed by steps, trying to eliminate errors one by one.

                      My 1st current issue is with the Stop Loss order placement when PositionAccount.MarketPosition == MarketPosition.Long is true:

                      The strategy works with (BarsInProgress !=0) return; but it doesn't with (BarsInProgress == 1).

                      I need it to work with the (BarsInProgress == 1) because the bid calculation I'm after will depend on it.
                      How can I get it to work with the (BarsInProgress == 1)?

                      I attach the code and a video link to show both case:
                      https://drive.google.com/file/d/1d8B...ew?usp=sharing

                      Also, I checked the

                      AddDataSeries(null, BarsPeriodType.Tick, 1, MarketDataType.Bid);

                      at the end of the video and it's working. Thanks.

                      I'll proceed with the next problems one by one once the (BarsInProgress == 1) one is solved.
                      Attached Files

                      Comment


                        #12
                        Hello PaulMohn,

                        It looks like you are trying to do a few conflicting actions here:

                        Code:
                        if (BarsInProgress !=0) return;
                        {
                        This is not valid to begin with but this is also not how you would form a condition for a specific BarsInProgress. If you wanted to isolate two series you would remove the return and for it like this:

                        Code:
                        if (BarsInProgress ==0)
                        {
                        //do something for the first series
                        }
                        if (BarsInProgress ==1)
                        {
                        // do something for the second series
                        }


                        JesseNinjaTrader Customer Service

                        Comment


                          #13
                          Hello Jesse and thank you for the reply.
                          I'm trying to go step by step using one condition at a time because I tried before the multi BarsInProgress structure (in post #4 above) to no avail.

                          I've just tried with

                          if (BarsInProgress ==0)
                          {
                          //do something for the first series
                          }
                          and that works.

                          But it's not working with
                          if (BarsInProgress ==1)
                          {
                          //do something for the second series
                          }

                          How to get it to work with
                          if (BarsInProgress ==1)
                          {
                          //do something for the second series
                          }

                          ?

                          Here's a new video link:
                          https://drive.google.com/file/d/1vmQ...ew?usp=sharing


                          I've just tested the prints but it only shows that the order is not submitted:



                          Last edited by PaulMohn; 01-06-2022, 02:15 PM. Reason: prints test

                          Comment


                            #14
                            Hello PaulMohn,

                            I am not certain I understand what the problem is based on your description. To work with multiple series you would need to first use AddDataSeries which adds the second series. if you then wanted to access values from that series you can use a condition like post #4. Your video does not contain the code for BarsInProgress 1 so you would still have to add that part if you wanted to use the second series.

                            You can see the following link for a sample of using BarsInProgress: https://ninjatrader.com/support/help...arupdateMethod


                            JesseNinjaTrader Customer Service

                            Comment


                              #15
                              Ok thanks for the note on the AddDataSeries. I've added it below. I'm not sure I understand what you mean by BarsInprogress 1 is not in the code. Please explain. Thanks.
                              I've just tested the code below (with the series variable added) but it's not working.
                              What else am I missing?

                              New video:
                              https://drive.google.com/file/d/1OVZ...ew?usp=sharing


                              Here's the code:

                              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
                              {
                              public class BidAskIncDecr : Strategy
                              {
                              
                              
                              private Series<double> bidValsfrmEntry;
                              
                              private Order initialExitOrderLong = null;
                              
                              private double chase1ExitOrderLong0;
                              
                              
                              protected override void OnStateChange()
                              {
                              if (State == State.SetDefaults)
                              {
                              Description = @"Enter the description for your new custom Strategy here.";
                              Name = "BidAskIncDecr";
                              Calculate = Calculate.OnEachTick;
                              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;
                              
                              IsUnmanaged = true;
                              }
                              else if (State == State.Configure)
                              {
                              // Add a secondary data series to sync our Secondary Series<double>
                              AddDataSeries(null, BarsPeriodType.Tick, 1, MarketDataType.Bid);
                              }
                              else if (State == State.DataLoaded)
                              {
                              bidValsfrmEntry = new Series<double>(this, MaximumBarsLookBack.Infinite);
                              }
                              else if (State == State.Realtime)
                              {
                              if (initialExitOrderLong != null)
                              initialExitOrderLong = GetRealtimeOrder(initialExitOrderLong);
                              }
                              }
                              
                              protected override void OnBarUpdate()
                              {
                              
                              if(CurrentBar<2) return;
                              
                              if (BarsInProgress ==1)
                              {
                              // Set 2
                              if ( PositionAccount.MarketPosition == MarketPosition.Long )
                              {
                              if (initialExitOrderLong == null)
                              {
                              initialExitOrderLong = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket, PositionAccount.Quantity, 0, PositionAccount.AveragePrice -25*TickSize, "", @"Exit Long FULL STOP" );
                              }
                              }
                              
                              Print("1" + " " + Time[0] + " " + initialExitOrderLong);
                              
                              }
                              
                              
                              }
                              
                              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
                              {
                              if (order.Name == "Exit Long FULL STOP")
                              {
                              {
                              initialExitOrderLong = order;
                              }
                              if (initialExitOrderLong != null && initialExitOrderLong == order)
                              {
                              if (initialExitOrderLong.OrderState == OrderState.Cancelled || initialExitOrderLong.OrderState == OrderState.Filled)
                              {
                              initialExitOrderLong = null;
                              }
                              }
                              }
                              }
                              
                              
                              }
                              }
                              Attached Files

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by cre8able, Today, 01:16 PM
                              2 responses
                              9 views
                              0 likes
                              Last Post cre8able  
                              Started by chbruno, 04-24-2024, 04:10 PM
                              3 responses
                              48 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by samish18, Today, 01:01 PM
                              1 response
                              7 views
                              0 likes
                              Last Post NinjaTrader_LuisH  
                              Started by WHICKED, Today, 12:56 PM
                              1 response
                              9 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by WHICKED, Today, 12:45 PM
                              1 response
                              11 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Working...
                              X