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

Need help with Stochastic Strategy

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

    Need help with Stochastic Strategy

    Hello,

    I'm trying to implement a StochasticsFast Strategy where I buy when the D value crosses above 20 the second time, without crossing above 80.

    For example, D value crosses above 20 but stays below 80....then crosses below 20 and I go long once it crosses over 20.

    I have the code below but it's stuck on "Calculating...". Any help is appreciated.


    #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 StochasticFLAGLONG : Strategy
    {

    private int flag = 0;
    private StochasticsFast StochasticsFast1;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "StochasticFLAGLONG";
    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;
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {

    //SetStopLoss("", CalculationMode.Currency, 200, false);
    StochasticsFast1 = StochasticsFast(Close, 3, 5);
    AddChartIndicator(StochasticsFast1);
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;


    // Set 1
    if (CrossAbove(StochasticsFast1.D, 20, 1))
    {

    double value = StochasticsFast(3, 5).D[0];

    while ((value < 80) && (value > 20))
    {

    flag=1;

    }


    }


    if ((CrossBelow(StochasticsFast1.D, 20, 1) && flag!=1))
    {


    EnterLong(Convert.ToInt32(10000), "");
    }


    // Set 2
    if (CrossBelow(StochasticsFast1.D, 80, 1))
    {
    ExitLong(Convert.ToInt32(10000), "", "");
    }



    }
    }
    }

    #2
    Hello omermirza,

    I recommend you check your while loop.

    That appears to be logic that would be infinitely true.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      I tried changing that a few times but still can't get it work. What do you suggest?

      Comment


        #4
        Hello omermirza,

        I would suggest you have a while loop that ends.

        If value is less than 80 and greater than 20 the while loop will start setting Flag to 1 forever. The value variable is never going to change in that loop. It will forever be less than 80 and greater than 20 and the while loop will forever be setting Flag to 1. The code will never get past that point because the CPU will be forever setting Flag to 1, over and over and over again.

        Possibly you don't want a while loop at all. What are you trying to loop over?

        You also have not provided the code you have changed. Possibly the new code is still causing an endless loop? Do you have questions about the new code you have written? Would you like to provide this?
        Last edited by NinjaTrader_ChelseaB; 04-08-2021, 09:21 AM.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          OK my updated code is below, it's not working but at least it's not stuck anymore.

          I don't know if the while loop is the best way, but what I'm trying to do is enter the trade the second time the D value of stochastics crosses above 20, as long as the first time when it crossed it doesn't make it above 80. I've attached a picture to illustrate, the trade should execute at point 2.

          Here's my updated 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 StochasticFLAGLONG : Strategy
          {

          private int flag = 0;
          private StochasticsFast StochasticsFast1;

          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"Enter the description for your new custom Strategy here.";
          Name = "StochasticFLAGLONG";
          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;
          }
          else if (State == State.Configure)
          {
          }
          else if (State == State.DataLoaded)
          {

          //SetStopLoss("", CalculationMode.Currency, 200, false);
          StochasticsFast1 = StochasticsFast(Close, 3, 5);
          AddChartIndicator(StochasticsFast1);
          }
          }

          protected override void OnBarUpdate()
          {
          if (BarsInProgress != 0)
          return;

          if (CurrentBars[0] < 1)
          return;

          double value = StochasticsFast(3, 5).D[0];

          // Set 1
          if (CrossAbove(StochasticsFast1.D, 20, 1))
          {



          while ((value > 21) && (value < 80))
          {
          flag=1;
          return;

          }


          }



          if (CrossBelow(StochasticsFast1.D, 20, 1))
          {
          flag=0;

          }




          if ((CrossAbove(StochasticsFast1.D, 20, 1)) && (flag==0))
          {

          EnterLong(Convert.ToInt32(10000), "");
          }


          // Set 2
          if (CrossBelow(StochasticsFast1.D, 80, 1))
          {
          ExitLong(Convert.ToInt32(10000), "", "");
          }



          }
          }
          }




          Attached Files

          Comment


            #6
            Hello omermirza,

            I'm not seeing this while loop serves any function.

            Perhaps the while loop is not necessary at?

            if ((value > 21) && (value < 80))
            {
            Flag = 1;
            }


            You can save a value, and then on a later bar refer to that value.

            OnBarUpdate is going to run for every bar update.

            Below is a link to an example.
            Hi, To improve a strategy, I would like the condition to enter a trade to be triggered only after a second crossing happens. Meaning, for instance we have a sthocastics crossing, but the strategy would only trigger when a crossing between 2 emas happen. Would the looking back N bars work? Can it be done within the builder
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Is there anyway to specify if the D value has not crossed over 80?

              Comment


                #8
                Hello omermirza,

                You can use a NOT operator with the CrossAbove.

                if (!CrossAbove(StochasticsFast1.D, 0, 1))

                You may also just wish to check that the D plot is less than 80.

                if (StochasticsFast1.D < 80)

                We look forward to assisting.
                JimNinjaTrader Customer Service

                Comment


                  #9
                  I still can't seem to get it too work. Can you take a crack at it ?

                  Comment


                    #10
                    Hello omermirza,

                    I've added the suggested code to a test strategy to demonstrate.
                    Attached Files
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hi Chelsea,

                      Thanks - but I'm going to need a bit more than that. If you can try and write the entire strategy it would be greatly appreciated. Everything I've tried so far hasn't worked.

                      Comment


                        #12
                        Hello omermirza,

                        I have tested and this absolutely will print when there is no cross above and when the value is below 80.

                        Unfortunately, in the support department at NinjaTrader it is against our policy to create, debug, or modify, code or logic for our clients. Further, we do not provide C# programming education services or one on one educational support over the phone in our NinjaScript Support department. This is so that we can maintain a high level of service for all of our clients as well as our associates.

                        That said, through email we are happy to answer any questions you may have about NinjaScript if you decide to code this yourself. We are also happy to assist with finding resources in our help guide as well as simple examples, and we are happy to assist with guiding you through the debugging process to assist you with understanding unexpected behavior.

                        We do have a large ecosystem available to help you with programming logic questions. You can post on our forum and ask the other 40,000+ forum members.

                        https://ninjatrader.com/support/foru.../ninjatrader-8

                        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 contacts who provide educational as well as consulting services. Please let me know if you would like our NinjaTrader Ecosystem team follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.


                        What specifically have you tried that has not worked?

                        Have you tested this condition from the test script and found it is evaluating as true even when there is no cross above occurring?
                        If so, please include the output from the prints.

                        Are you certain that is the logic you want?
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          I was finally able to get this to work but incrementing the flag instead of updating it manually. Also I had to remember to reset the flag once it crosses above 80 and once a position is closed.

                          Thank you for the support.

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by Pattontje, Yesterday, 02:10 PM
                          2 responses
                          15 views
                          0 likes
                          Last Post Pattontje  
                          Started by flybuzz, 04-21-2024, 04:07 PM
                          17 responses
                          229 views
                          0 likes
                          Last Post TradingLoss  
                          Started by agclub, 04-21-2024, 08:57 PM
                          3 responses
                          17 views
                          0 likes
                          Last Post TradingLoss  
                          Started by TradingLoss, 04-21-2024, 04:32 PM
                          4 responses
                          44 views
                          2 likes
                          Last Post TradingLoss  
                          Started by cre8able, 04-17-2024, 04:16 PM
                          6 responses
                          57 views
                          0 likes
                          Last Post cre8able  
                          Working...
                          X