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

RhyStrat

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

    RhyStrat

    Well I came up with a strategy in my head after observing market conditions. Trying to convert it over to code. Wondering if I am obeying all the syntax rules. More questions to follow. I am certainly do not know code. Trying to copy + paste examples of code I find fitting. To this strategy I would like to add a few other pieces of logic regarding the cross over. As well as a stopless/trailing stop exit strategy. Any help is appreciated.

    Basically I copy + pasted the SMA crossover strategy. To which I added the part inside the [red] tags.


    Code:
        /// </summary>
        [Description("Simple moving average cross over strategy.")]
        public class SampleMACrossOver : Strategy
        {
            #region Variables
            private int        fast    = 10;
            private int        slow    = 25;
            #endregion
    
            /// <summary>
            /// This method is used to configure the strategy and is called once before any strategy method is called.
            /// </summary>
            protected override void Initialize()
            {
                IncludeCommission = true; 
                
                SMA(Fast).Plots[0].Pen.Color = Color.Orange;
                SMA(Slow).Plots[0].Pen.Color = Color.Green;
    
                Add(SMA(Fast));
                Add(SMA(Slow));
    
                CalculateOnBarClose = true;
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick).
            /// </summary>
    [red]        protected override void OnBarUpdate()
            {
                double Account =  ;//account size reset manually at the beginning of each trade session
                double PnL = GetAtmStrategyRealizedProfitLoss;
                double CurrentAccount = Account + PnL;
                double UsableAccount = CurrentAccount * .66; //leaving a small buffer
                int    ContractMargin = //commodity being traded;
                int    MaxContracts = UsableAccount / ContractMargin;
                if      MaxContracts > 40;
                         MaxContracts = 40;
                if (CrossAbove(SMA(Fast), SMA(Slow), 1))
                    EnterLong(MaxContracts);
                else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
                    EnterShort(MaxContracts);
            }
    [/red]
            #region Properties
            /// <summary>
            /// </summary>
            [Description("Period for fast MA")]
            [Category("Parameters")]
            public int Fast
            {
                get { return fast; }
                set { fast = Math.Max(1, value); }
            }
    
            /// <summary>
            /// </summary>
            [Description("Period for slow MA")]
            [Category("Parameters")]
            public int Slow
            {
                get { return slow; }
                set { slow = Math.Max(1, value); }
            }
            #endregion
        }
    }
    Last edited by Rhyshaelkan; 11-05-2009, 07:12 PM.

    #2
    Thanks for sharing Rhyshaelkan, for working stop logic in you could take a look at this sample here - http://www.ninjatrader-support2.com/...ead.php?t=3222
    BertrandNinjaTrader Customer Service

    Comment


      #3
      Will the code in blue be able to use the code in red? Or will I have to save the sum of the code in red in some sort of storage to be used by the code in blue? Specifically, the value found for MaxContracts.

      In addition. Will OnPositionUpdate() be called once when the script starts? If not then the main logic part of the script will not know how many contracts MaxContracts is worth. Is there another method I can call once at startup to run the same block of code. Then OnPositionUpdate() for when I am getting out or into the market?

      Thanks again.


      #region Using declarations
      using System;
      using System.ComponentModel;
      using System.Diagnostics;
      using System.Drawing;
      using System.Drawing.Drawing2D;
      using System.Xml.Serialization;
      using NinjaTrader.Cbi;
      using NinjaTrader.Data;
      using NinjaTrader.Indicator;
      using NinjaTrader.Strategy;
      #endregion

      // This namespace holds all strategies and is required. Do not change it.
      namespace NinjaTrader.Strategy
      {
      /// <summary>
      /// Simple moving average cross over strategy.
      /// </summary>
      [Description("Simple moving average cross over strategy.")]
      public class SampleMACrossOver : Strategy
      {
      #region Variables
      private int fast = 10;
      private int slow = 25;
      #endregion

      /// <summary>
      /// This method is used to configure the strategy and is called once before any strategy method is called.
      /// </summary>
      protected override void Initialize()
      {
      IncludeCommission = true;

      SMA(Fast).Plots[0].Pen.Color = Color.Orange;
      SMA(Slow).Plots[0].Pen.Color = Color.Green;

      Add(SMA(Fast));
      Add(SMA(Slow));

      CalculateOnBarClose = true;
      }

      /// <summary>
      /// This method is used to reset contracts traded levels on position update.
      /// </summary>
      protected override void OnPositionUpdate()
      {
      double Account = ;//account size reset manually at the beginning of each trade session
      double PnL = GetAtmStrategyRealizedProfitLoss;
      double CurrentAccount = Account + PnL;
      double UsableAccount = CurrentAccount * .66; //leaving a small buffer
      int ContractMargin = //commodity being traded;
      int MaxContracts = UsableAccount / ContractMargin;
      if MaxContracts > 40;
      MaxContracts = 40;

      }

      /// <summary>
      /// Called on each bar update event (incoming tick).
      /// </summary>
      protected override void OnBarUpdate()
      {
      if (CrossAbove(SMA(Fast), SMA(Slow), 1))
      EnterLong(
      MaxContracts);
      else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
      EnterShort(
      MaxContracts);
      }

      #region Properties
      /// <summary>
      /// </summary>
      [Description("Period for fast MA")]
      [Category("Parameters")]
      public int Fast
      {
      get { return fast; }
      set { fast = Math.Max(1, value); }
      }

      /// <summary>
      /// </summary>
      [Description("Period for slow MA")]
      [Category("Parameters")]
      public int Slow
      {
      get { return slow; }
      set { slow = Math.Max(1, value); }
      }
      #endregion
      }
      }
      Last edited by Rhyshaelkan; 11-09-2009, 12:01 AM.

      Comment


        #4
        Rhyshaelkan, unfortunately not as you use keywords specific to working with ATM strategies for exit management, which would not return the needed value if taken and called out of context.

        OnPositionUpdate() is called for every state change of a position, if you want to place some logic at the start of the script, try putting it in

        if (CurrentBar == 0)
        {
        do your calcs on first OnBarUpdate() call
        }

        Accessing live account info in NinjaScript strategies is unfortunately not supported for 6.5, but we have added this to NinjaTrader 7 -



        New Account Access
        We added methods to get access to live brokerage account values such as cash balance. This is dependant on the broker and the level of information they provide if any.
        BertrandNinjaTrader Customer Service

        Comment


          #5
          Thank you for your help.

          Then my code should look like this?
          Code:
          protected override void OnPositionUpdate()
                  {
                      double myAccount =  ;//account size reset manually at the beginning of each trade session
                      double PnL = GetAtmStrategyRealizedProfitLoss;
                      double CurrentAccount = myAccount + PnL;
                      double UsableAccount = CurrentAccount * .66; //leaving a small buffer
                      int    ContractMargin = //margin of commodity being traded here;
                      int    MaxContracts = UsableAccount / ContractMargin;
                      if     MaxContracts > 40
                          MaxContracts = 40;
                  }
          
                  /// <summary>
                  /// Called on each bar update event (incoming tick).
                  /// </summary>
                  protected override void OnBarUpdate()
                  {
                      if (CurrentBar == 0)
                      {
                      double myAccount =  ;//account size reset manually at the beginning of each trade session
                      double PnL = GetAtmStrategyRealizedProfitLoss;
                      double CurrentAccount = myAccount + PnL;
                      double UsableAccount = CurrentAccount * .66; //leaving a small buffer
                      int    ContractMargin = //margin of commodity being traded here;
                      int    MaxContracts = UsableAccount / ContractMargin;
                      if     MaxContracts > 40
                          MaxContracts = 40;
                      }  
                      if (CrossAbove(SMA(Fast), SMA(Slow), 1))
                          EnterLong(MaxContracts);
                      else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
                          EnterShort(MaxContracts);
                  }
          Is this syntax correct? After the initial setting of MaxContracts when CurrentBar == 0. It will then use OnPositionUpdate's calculations of MaxContracts after a trade?

          I was not certain whether EnterLong(MaxContracts) or EnterShort(MaxContracts) would be able to pull the value of MaxContracts from the OnPositionUpdate's calculations.

          I would rather catch the bug in my programming before compiling into NinjaScript. Being clueless as I am about script writing.
          Last edited by Rhyshaelkan; 11-15-2009, 10:34 PM.

          Comment


            #6
            You would need to give a test run to see whether it's working as you would expect or not, but given since you do not call any AtmStrategyCreate for exit management I doubt this will hit home.

            BertrandNinjaTrader Customer Service

            Comment


              #7
              In continuation, I sorted out the problem of how many contracts to trade with the simple DefaultQuanity variable. So axed that portion of the code. However, I do have new issues.


              Code:
              //Nuts and bolts entry area    
                          if (CrossAbove(SMA(Fast), SMA(Slow), 1))
                              {    
                                  double Target = (Close[0] + 0.015);                
                                  
                                  if (Close[0]> Target)
                                  {
                                           EnterLong(DefaultQuantity);
                                  }    
                              }
                          else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
                              {
                                  double Target = (Close[0] - 0.015);
                                  
                                  if (Close[0]<= Target)
                                      {
                                           EnterShort(DefaultQuantity);
                                      }
                              }
              This code is ran with "CalculateOnBarClose = false". If you work your way through the logic you will, or might, see that Cross(Above, or Below) is more like a tested condition instead of an event. So the logic will continuously reset the target further and further away from the current price. Thus never entering the market. Or so has been my testing of the code so far.

              Unless I am missing something else which prevents the logic from entering the market.

              If someone has a better process take a snapshot of the price which caused the Cross(Above, or Below). So that I can add a variable to said price to be used as a target entry price. I am all ears.

              Comment


                #8
                Rhyshaelkan,

                If you would not like it to continually check the CrossAbove/Below you should add additional checks into your if-statements. You can add a bool statement and set it to false once you are inside the if-statement and that would make it not reenter and adjust your price values.
                Josh P.NinjaTrader Customer Service

                Comment


                  #9
                  To the NT guys or any other helpful peoples out there. How might I accomplish this. How might I code, for instance, after running the CrossAbove code it will not run again until it runs the CrossBelow.

                  Comment


                    #10
                    Hello,

                    You can use a flag system.

                    if(...condition1... && wasCondition2)
                    {
                    //do stuff
                    wasCondition1 = true;
                    wasCondition2 = false;
                    }

                    Then just the oppposite for condition2.
                    DenNinjaTrader Customer Service

                    Comment


                      #11
                      RhyStratWithFlags

                      Moving on now. I have other issues. Up in Initialize I have.

                      Code:
                              protected override void Initialize()
                              {
                                  IncludeCommission = true; 
                                  
                                  SMA(Fast).Plots[0].Pen.Color = Color.Red;
                                  SMA(Slow).Plots[0].Pen.Color = Color.Green;
                      
                                  Add(SMA(Fast));
                                  Add(SMA(Slow));
                                  
                                  TraceOrders        = true; 
                                  CalculateOnBarClose = false;
                                  
                                  ExitOnClose        = true;
                                  SetTrailStop(CalculationMode.Ticks, 10);
                                      ExitOnCloseSeconds = 20;
                                  bool CrossAboveFlag = true;
                                  bool CrossBelowFlag = true;            
                              }
                      Then in my logic OnBarUpdate section I have.

                      Code:
                      //Nuts and bolts entry area    
                                  if (CrossAbove(SMA(Fast), SMA(Slow), 1) && CrossAboveFlag = true)
                                      {                    
                                          bool CrossAboveFlag = false;
                                          bool CrossBelowFlag = true;
                                          double Target = (Close[0] + 0.375);                
                                          if (Close[0] >= Target)
                                              {
                                                   EnterLong(DefaultQuantity);
                                              }
                                      }
                                  else if (CrossAbove(SMA(Fast), SMA(Slow), 1) && CrossAboveFlag = false)
                                      {
                                          return;
                                      }
                      However I am getting a compile error "the name 'CrossAboveFlag' does not exist in the current context" CS0103. I thought I had completely explained CrossAboveFlag and CrossBelowFlag within the Initialize method(or is that a class).

                      I added bool to both the initialize statement and in the if statements. But I still get the error.

                      Thanks always,
                      Rhy.

                      P.S. I omitted the CrossBelow section. But just imagine the CrossAbove section in reverse.

                      Comment


                        #12
                        You need to declare your variables in the variable section of your indicator. Initialize() is a method of the indicator class, everything declared in this method is only valid inside this method.

                        Regards
                        Ralph

                        Comment


                          #13
                          Originally posted by Ralph View Post
                          You need to declare your variables in the variable section of your indicator. Initialize() is a method of the indicator class, everything declared in this method is only valid inside this method.

                          Regards
                          Ralph

                          Thanks man. Surely I am no programmer. I need to read the instruction manual.
                          Last edited by Rhyshaelkan; 04-14-2010, 05:44 AM.

                          Comment


                            #14
                            Am I not allowed to add decimals to Close[0]? I am having the issue still, of the script not wanting to enter the market. Is my logic faulty?

                            In essence, I would like the script to take a snapshot of the price when the crossover happens. Then add a value to the price and define it as our Target entry price. If and when the price achieves the Target, then the order is placed.

                            If the Target is not reached and actually heads the opposite direction. I would like the opposite crossover to reset Target.

                            Comment


                              #15
                              Rhyshaelkan, you can add to the close price but it would be easier if you add in terms of multiples in TickSize...Close[0] + 3 * TickSize for example...

                              You should also add visual checks like Arrows on your conditions so you can ensure they trigger as you would expect.
                              BertrandNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Max238, Today, 01:28 AM
                              2 responses
                              26 views
                              0 likes
                              Last Post NinjaTrader_ChristopherJ  
                              Started by Shansen, 08-30-2019, 10:18 PM
                              25 responses
                              949 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by JonesJoker, 04-22-2024, 12:23 PM
                              8 responses
                              41 views
                              0 likes
                              Last Post JonesJoker  
                              Started by timko, Today, 06:45 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post timko
                              by timko
                               
                              Started by Waxavi, 04-19-2024, 02:10 AM
                              2 responses
                              39 views
                              0 likes
                              Last Post poeds
                              by poeds
                               
                              Working...
                              X