Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Need some help for c sharp scripting

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

    Need some help for c sharp scripting

    Hi all:
    I am new to c# and ninjatrader.. and i tried to make some simple strategy work. Now i just to long SPY when sma(10)>sma(20) and sell the other way.
    1. About Add(some indicators), could i also specify the color?
    2. In my code , I first want to Add(sma10), it looks like i can't do this. So how could i initialize a indicator object?
    3. In my code, I tried to call BackColorAll = Color.Green; Yet the backtest result does not show any green color on the chart though the trading log did execute some selling orders.
    4. In general , my logic is to first check if my position is empty, if so, check the long condition. if my position is not empty, check the short condition.

    Could someone help check where i goes wrong?
    Code:
     public class Crossover01 : Strategy
        {
            #region Variables
            // Wizard generated variables
            private int myInput0 = 1; // Default setting for MyInput0
            // User defined variables (add any user defined variables below)
            #endregion
    
            /// <summary>
            /// This method is used to configure the strategy and is called once before any strategy method is called.
            /// </summary>
    		private IOrder entryOrder = null;
            protected override void Initialize()
            {
                CalculateOnBarClose = true;
    			//global stop loss
    			SetStopLoss(CalculationMode.Percent, 0.07);
    			SetProfitTarget(CalculationMode.Percent,0.1);
    			//Add(sma10);
    			//Add(sma20);
    			Add(SMA(10));
    			Add(SMA(20));
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
    			var sma10 = SMA(10);
    			var sma20 = SMA(20);
    			var sma50 = SMA(50);
    			if(entryOrder == null)
    			{
    				if(CrossAbove(sma10,sma20,1)&& Rising(sma50) == true)
    				{
    					EnterLong();
    					BackColorAll = Color.Red;
    				}
    			}
    			else if (entryOrder != null)
    			{
    				if (CrossBelow(sma10,sma20,1)|| Falling(sma50) == true)
    				{
    					EnterShort();
    					BackColorAll = Color.Green;
    				}
    				entryOrder = null;
    			}
            }
    
            #region Properties
            [Description("")]
            [GridCategory("Parameters")]
            public int MyInput0
            {
                get { return myInput0; }
                set { myInput0 = Math.Max(1, value); }
            }
            #endregion
        }

    #2
    hugebaozi, welcome to our forums here. Generally tips for working with the Add() including colors could be reviewed here - http://www.ninjatrader.com/support/f...ead.php?t=3228

    The backcolor call should work as you expect, however due to your cross condition it would only plot for one bar then when then condition triggered, may it just be hard to see visually in your SA chart?

    Comment


      #3
      the trading log actually has some selling trade. Yet no green back color.

      Comment


        #4
        Can you please give my attached example a try on your data? I see it indicating the crossovers visually via BackColorAll with no issues in my SA chart.
        Attached Files

        Comment


          #5
          Hi Bertrand:
          Thx for reply. Your code works. But How could i do something to check my position first before doing any trade. (In my code i did if(entryOrder == null)...)
          Because First I don't want to short stocks.(just long and sell). If i use your code then i may short stocks then buy to cover.
          Second Your code somehow gave wrong result. See the link below.
          Discover the magic of the internet at Imgur, a community powered entertainment destination. Lift your spirits with funny jokes, trending memes, entertaining gifs, inspiring stories, viral videos, and so much more from users.

          It first sell short , then instead of buy to cover, it buy ...(which does not make sense)

          Comment


            #6
            hugebaozi, for the position check just use the Position object then please -



            You can then enter long only if this reports flat for example, and just call ExitLong to get out of the long position (that would be a market order).

            The Enter() methods would reverse automatically for you, so first you would see an the exit from the currnet held position (Close Position) and then the actual Buy or SellShort entries taking you into the new desired position direction.

            Comment


              #7
              Could u give a complete example or edit based on mine? I just edit based on your code. yet the if else seems wrong. The position part i believe is wrong.
              Attached Files

              Comment


                #8
                You don't want to EnterShort, but just ExitLong - that way you just get a long exit if the cross below occurs.

                i.e. consider this changed OnBarUpdate()

                Code:
                protected override void OnBarUpdate()
                {
                		if (CrossAbove(SMA(Fast), SMA(Slow), 1) && Position.MarketPosition == MarketPosition.Flat)
                		{
                			EnterLong();
                			BackColorAll = Color.Green;
                		}
                			
                		if (CrossBelow(SMA(Fast), SMA(Slow), 1) && Position.MarketPosition == MarketPosition.Long)
                		{
                			ExitLong();
                			BackColorAll = Color.Red;
                                }
                }

                Comment


                  #9
                  Hi Bertrand: It works fine finally.. One more question: After checking the plot,It looks like the logic is when condition == true, the Onbarupdate will actually send orders based on next bar's data(close)..I thought it works fine for minute data. But it does not make sense for daily data. What do u think? Is it possible to buy and sell on the current bar?
                  Discover the magic of the internet at Imgur, a community powered entertainment destination. Lift your spirits with funny jokes, trending memes, entertaining gifs, inspiring stories, viral videos, and so much more from users.

                  Comment


                    #10
                    Hello hugebaozi,

                    You will need to add an intergranular data series to your script so you can submit the orders to that finer timeframe.

                    See the sample below -
                    http://www.ninjatrader.com/support/f...ead.php?t=5787
                    Cal H.NinjaTrader Customer Service

                    Comment


                      #11
                      Hi Bertrand: The codes is not what i am looking for. (the codes just set additional bar frequency...) my questions is about sending orders based on the current bar (close value) instead of the next bar.

                      Comment


                        #12
                        hugebaozi,

                        You can use CalculateOnBarClose set to false for when running real time data.

                        However, for a backtest this property will always be true and thus why you see the executions on the next bar.

                        You will need to use the intrabar granularity that I provided if you want to submit orders intrabar on a daily time frame
                        Cal H.NinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                        0 responses
                        582 views
                        0 likes
                        Last Post Geovanny Suaza  
                        Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                        0 responses
                        338 views
                        1 like
                        Last Post Geovanny Suaza  
                        Started by Mindset, 02-09-2026, 11:44 AM
                        0 responses
                        103 views
                        0 likes
                        Last Post Mindset
                        by Mindset
                         
                        Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                        0 responses
                        554 views
                        1 like
                        Last Post Geovanny Suaza  
                        Started by RFrosty, 01-28-2026, 06:49 PM
                        0 responses
                        552 views
                        1 like
                        Last Post RFrosty
                        by RFrosty
                         
                        Working...
                        X