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

Stochastic over indicator

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

    Stochastic over indicator

    Hi,

    I'm trying to adapt Stochastics indicator in order to use it over another indicator (not price, not High and Low, just a value), so I've modified the original Stochastics code (just the three lines marked), but the indicator in real time fails; the top value, which should be 100, goes higher, to 140 for example, when I have the indicator running for some hours. EDIT: Just add that when top value goes to 140, bottom value is 40. It looks like values slide 40 to the top for some reason.

    I'm pretty sure the code should be really simple, but I don't know exactly how to modify it to get just that, a stochastics over a series of values which have no High and Low but just a simple value.

    Thanks in advance for any help.

    MyStochastics 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.DrawingTools;
    #endregion
    
    // This namespace holds indicators in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Indicators
    {
        /// <summary>
        /// The Stochastic Oscillator is made up of two lines that oscillate between 
        /// a vertical scale of 0 to 100. The %K is the main line and it is drawn as 
        /// a solid line. The second is the %D line and is a moving average of %K. 
        /// The %D line is drawn as a dotted line. Use as a buy/sell signal generator, 
        /// buying when fast moves above slow and selling when fast moves below slow.
        /// </summary>
        public class MyStochastics : Indicator
        {
            private Series<double>        den;
            private Series<double>        fastK;
            private MIN                    min;
            private MAX                    max;
            private Series<double>        nom;
            private SMA                    smaFastK;
            private SMA                    smaK;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                    = NinjaTrader.Custom.Resource.NinjaScriptIndicatorDescriptionStochastics;
                    Name                        = "MyStochastics";
                    IsSuspendedWhileInactive    = true;
                    PeriodD                        = 7;
                    PeriodK                        = 14;
                    Smooth                        = 3;
    
                    AddPlot(Brushes.DodgerBlue,                NinjaTrader.Custom.Resource.StochasticsD);
                    AddPlot(Brushes.Goldenrod,                NinjaTrader.Custom.Resource.StochasticsK);
    
                    AddLine(Brushes.DarkCyan,        20,    NinjaTrader.Custom.Resource.NinjaScriptIndicatorLower);
                    AddLine(Brushes.DarkCyan,    80,    NinjaTrader.Custom.Resource.NinjaScriptIndicatorUpper);
                }
                else if (State == State.Configure)
                {
                    den            = new Series<double>(this);
                    nom            = new Series<double>(this);
                    fastK        = new Series<double>(this);
                    min            = MIN(Input, PeriodK); // [B]<<<<<<<<<<<<<< MODIFIED LINE (Low => Input)[/B]
                    max            = MAX(Input, PeriodK); [B]// <<<<<<<<<<<<<< MODIFIED LINE (Max => Input)[/B]
                    smaFastK    = SMA(fastK, Smooth);
                    smaK        = SMA(K, PeriodD);
                }
            }
    
            protected override void OnBarUpdate()
            {
                double min0 = min[0];
                
                nom[0]        = Input[0] - min0; [B]// <<<<<<<<<<<<<<<<<<<<<<<<<<< MODIFIED LINE (Close[0] => Input[0])[/B]
                den[0]        = max[0] - min0;
    
                if (den[0].ApproxCompare(0) == 0)
                    fastK[0] = CurrentBar == 0 ? 50 : fastK[1];
                else
                    fastK[0] = Math.Min(100, Math.Max(0, 100 * nom[0] / den[0]));
    
                // Slow %K == Fast %D
                K[0] = smaFastK[0];
                D[0] = smaK[0];
            }
    
            #region Properties
            [Browsable(false)]
            [XmlIgnore()]
            public Series<double> D
            {
                get { return Values[0]; }
            }
    
            [Browsable(false)]
            [XmlIgnore()]
            public Series<double> K
            {
                get { return Values[1]; }
            }
            
            [Range(1, int.MaxValue), NinjaScriptProperty]
            [Display(ResourceType = typeof(Custom.Resource), Name = "PeriodD", GroupName = "NinjaScriptParameters", Order = 0)]
            public int PeriodD
            { get; set; }
    
            [Range(1, int.MaxValue), NinjaScriptProperty]
            [Display(ResourceType = typeof(Custom.Resource), Name = "PeriodK", GroupName = "NinjaScriptParameters", Order = 1)]
            public int PeriodK
            { get; set; }
    
            [Range(1, int.MaxValue), NinjaScriptProperty]
            [Display(ResourceType = typeof(Custom.Resource), Name = "Smooth", GroupName = "NinjaScriptParameters", Order = 2)]
            public int Smooth
            { get; set; }
            #endregion
        }
    }
    
    #region NinjaScript generated code. Neither change nor remove.
    
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
        {
            private MyStochastics[] cacheMyStochastics;
            public MyStochastics MyStochastics(int periodD, int periodK, int smooth)
            {
                return MyStochastics(Input, periodD, periodK, smooth);
            }
    
            public MyStochastics MyStochastics(ISeries<double> input, int periodD, int periodK, int smooth)
            {
                if (cacheMyStochastics != null)
                    for (int idx = 0; idx < cacheMyStochastics.Length; idx++)
                        if (cacheMyStochastics[idx] != null && cacheMyStochastics[idx].PeriodD == periodD && cacheMyStochastics[idx].PeriodK == periodK && cacheMyStochastics[idx].Smooth == smooth && cacheMyStochastics[idx].EqualsInput(input))
                            return cacheMyStochastics[idx];
                return CacheIndicator<MyStochastics>(new MyStochastics(){ PeriodD = periodD, PeriodK = periodK, Smooth = smooth }, input, ref cacheMyStochastics);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
        public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
        {
            public Indicators.MyStochastics MyStochastics(int periodD, int periodK, int smooth)
            {
                return indicator.MyStochastics(Input, periodD, periodK, smooth);
            }
    
            public Indicators.MyStochastics MyStochastics(ISeries<double> input , int periodD, int periodK, int smooth)
            {
                return indicator.MyStochastics(input, periodD, periodK, smooth);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
        {
            public Indicators.MyStochastics MyStochastics(int periodD, int periodK, int smooth)
            {
                return indicator.MyStochastics(Input, periodD, periodK, smooth);
            }
    
            public Indicators.MyStochastics MyStochastics(ISeries<double> input , int periodD, int periodK, int smooth)
            {
                return indicator.MyStochastics(input, periodD, periodK, smooth);
            }
        }
    }
    
    #endregion
    Last edited by manugarc; 01-09-2017, 10:24 AM. Reason: clarification

    #2
    Hello manugarc,

    In the NinjaScript Support would not be able to assist with custom logic, calculations, equations, etc.
    This thread will remain open for any community members that would like to assist.

    In the support department at NinjaTrader we do not create, debug, or modify code for our clients. This is so that we can maintain a high level of service for all of our clients as well as our partners.

    You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate partners who provide educational as well as consulting services. Please let me know if you would like our business development follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request.

    That said, I do want to mention the Stochatics indicator will have a change to it in 8.0.4.0. (ID #NTEIGHT-10958)
    The min and max are added in State.Configure. This causes an incorrect calculation when used with a secondary data series because the secondary series is not yet prepared. In the next iteration the following lines will be moved to State.DataLoaded after all data has been loaded.

    8.0.3.0:
    Code:
    else if (State == State.Configure)
    {
    	den			= new Series<double>(this);
    	nom			= new Series<double>(this);
    	fastK		= new Series<double>(this);
    	min			= MIN(Low, PeriodK);
    	max			= MAX(High, PeriodK);
    	smaFastK		= SMA(fastK, Smooth);
    	smaK		= SMA(K, PeriodD);
    }
    8.0.4.0:
    Code:
    else if (State == State.DataLoaded)
    {
    	den			= new Series<double>(this);
    	nom			= new Series<double>(this);
    	fastK		= new Series<double>(this);
    	min			= MIN(Low, PeriodK);
    	max			= MAX(High, PeriodK);
    	smaFastK		= SMA(fastK, Smooth);
    	smaK		= SMA(K, PeriodD);
    }
    In your script that is a modified copy, I would recommend making these changes.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hello ChelseaB,

      Absolutely; if it was a logic-related issue I would have perfectly accepted an answer like "It's in your code; just check it", but the code was so simple that I was almost sure it has to be something else.

      Great! So that was the problem. Thanks a lot!

      Comment


        #4
        The secondary (or more) series bug exists with the DoubleStochastics indicator as well. While waiting for a fix, is there a workaround for that also? (e.g. change "State.Configure" to "State.DataLoaded")

        else if (State == State.Configure)
        {
        p1 = new Series<double>(this);
        p2 = new Series<double>(this);
        p3 = new Series<double>(this);
        emaP1 = EMA(p1, 3);
        emaP3 = EMA(p3, 3);
        maxHigh = MAX(High, Period);
        maxP2 = MAX(p2, Period);
        minLow = MIN(Low, Period);
        minP2 = MIN(p2, Period);
        }

        Comment


          #5
          Hello Lancer,

          (edited)
          Yes, moving any code that relies on data to State.DataLoaded should correct the error.

          Have you tried this and found this did not correct the error?
          Last edited by NinjaTrader_ChelseaB; 01-10-2017, 01:59 PM.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            Originally posted by NinjaTrader_ChelseaB View Post
            Hello Lancer,

            Yes, moving any code that relies on data to State.SetDefaults should correct the error.

            Have you tried this and found this did not correct the error?
            Surely, you mean State.DataLoaded, right? Not State.SetDefaults.

            Comment


              #7
              koganam,

              Nice catch. Yes, I did mean State.DataLoaded.

              My mistake here.
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                ChelseaB, After changing State.Configure to State.DataLoaded, three of the four script conditions are now working. One condition is not working, and I'm looking into it.

                Thanks very much for mentioning that fix.

                Comment


                  #9
                  Still not working

                  Hi,

                  I've been using the indicator, modified in the way I was indicated (State.Configure => State.DataLoaded) but it keeps on failing. After hours of being active in real-time it goes beyond values 100 and 0 (one direction or the other, depending on the product it's applied to).

                  Still the same behaviour; I have to deactivate and activate the strategy to get things back to normal, since it works fine over historical values but fails on real-time ones, and the error gets bigger as time goes by.

                  The problem is that I can't keep on checking when it begins to fail because sooner or later I won't realize on time, so it's becoming a mayor problem for me.

                  I'm not asking for help on a custom indicator but on a predefined one; Could it be related to 0s and 1s indexes?
                  Last edited by manugarc; 01-31-2017, 05:12 PM.

                  Comment


                    #10
                    Hello manugarc,

                    These indicators have been corrected in the latest release of NinjaTrader (8.0.4.0). Please update to the latest version and test for the behavior once more.

                    NinjaTrader is a futures trading platform that delivers integrated multi-device trading. Discover our best platform to trade futures for active futures traders.


                    Let me know if this is a continuing issue with 8.0.4.0.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      You are right; I'm still using 8.0.3.1 (I thought it was the last one); I'll update it right now and of course I'll let you know in a week whether it keeps on going well (Since you've answered so sure about it, I'm also quite sure it will ).

                      Thank you Chelsea!

                      Comment


                        #12
                        Originally posted by NinjaTrader_ChelseaB View Post
                        Hello manugarc,

                        These indicators have been corrected in the latest release of NinjaTrader (8.0.4.0). Please update to the latest version and test for the behavior once more.

                        NinjaTrader is a futures trading platform that delivers integrated multi-device trading. Discover our best platform to trade futures for active futures traders.


                        Let me know if this is a continuing issue with 8.0.4.0.
                        Hi Chelsea,

                        I'm afraid the problem persists. I'm getting negative values in a number of stochastics I launched yesterday and values over 100 in another one.

                        I cannot send/show the code of my strategy, but please tell me what information or steps do you want me to take to make it easier for you to solve it if possible.

                        Thanks in advance.

                        Comment


                          #13
                          Just to provide an image of it:

                          Attached Files

                          Comment


                            #14
                            Hello manugarc, and thank you for your question.

                            I have added a simple unit test to the stock Stochastics indicator, and have attached this indicator to this file. To avoid using your code, let's build on this script until it helps us both see and understand what is happening.

                            If you would like help testing NinjaTrader against your custom code, please feel free to modify the attached code so that it reproduces any scenario in your code. Otherwise I will be using the code attached to this reply alone, updated with any modifications, to ensure :
                            • Stochastics values below 0 and above 100 never occur
                            • Using BarsArray[0] as the MIN and MAX input instead of Low and High, respectively, does not cause values outside range, or if it does, the reason is well understood
                            • Using BarsArray[0][0] as a replacement for Close[0] in a calculation for nom[0] does not cause values outside range, or if it does, the reason is well understood
                            • This indicator behaves the same way in NT7 and NT8

                            I'll keep this post updated with the test scenarios I will run, please feel free to suggest more :
                            • Run under a strategy through the Strategy Analyzer
                              • Minute, tick, and day data
                              • Based on Ask, Bid, Last
                              • ES 03-17, S&P 500 (all)
                              • 1 year period

                            • Run through market replay
                              • As per Strategy Analyzer
                              • Fast forward, then let alone for 3 hours on tick data


                            I will report back with my findings.
                            Attached Files
                            Last edited by NinjaTrader_JessicaP; 02-03-2017, 02:47 PM.
                            Jessica P.NinjaTrader Customer Service

                            Comment


                              #15
                              Hello Jessica,

                              Thank you for your time. Actually I would suggest to test it over a moving average for example, since that would be quite similar to my scenario, where I use the stochastics on another indicator, not the price itself.

                              I'll check whether it happens on the scenarios you have pointed and I'll tell you as well.

                              Kind regards.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by bortz, 11-06-2023, 08:04 AM
                              47 responses
                              1,602 views
                              0 likes
                              Last Post aligator  
                              Started by jaybedreamin, Today, 05:56 PM
                              0 responses
                              8 views
                              0 likes
                              Last Post jaybedreamin  
                              Started by DJ888, 04-16-2024, 06:09 PM
                              6 responses
                              18 views
                              0 likes
                              Last Post DJ888
                              by DJ888
                               
                              Started by Jon17, Today, 04:33 PM
                              0 responses
                              4 views
                              0 likes
                              Last Post Jon17
                              by Jon17
                               
                              Started by Javierw.ok, Today, 04:12 PM
                              0 responses
                              12 views
                              0 likes
                              Last Post Javierw.ok  
                              Working...
                              X