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

Multiple time frame strategy sharing a variable

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

    Multiple time frame strategy sharing a variable

    Please take a look at the code below. I'm working on a multitime frame strategy that tests for some conditions on three different time frames 2/10/60 and then updates a "Score" variable based on the findings.
    Rather than update the score and print just one updated number, the output is showing three different scores one for each time frame. When added together they are correct but why are they printing to the output window separately?

    I want one updated score that updates at each tick on all time frames at once.

    code below
    -------------------------------------------------------------------------------------------------------------------
    Code:
    namespace NinjaTrader.Strategy
    {
        /// <summary>
        /// for testing strategy componants
        /// </summary>
        [Description("for testing strategy componants")]
        public class TESTSTRATEGY2 : Strategy
        {
            #region Variables
    		
    		//These are the amounts to add or subtract to score
    		int HourlyScore = 1; int TenMinScore = 2; int TwoMinScore = 6;
    		
            #endregion
    
    
            protected override void Initialize()
            {
                CalculateOnBarClose = false;
    			
    			Add(PeriodType.Minute, 10);		//adding 10 minute data
    			Add(PeriodType.Minute, 60);		//adding 60 minute data
            }
    
    
            protected override void OnBarUpdate()
            {
    			ClearOutputWindow();
    			
    			if (CurrentBars[0] <= BarsRequired || 
    				CurrentBars[1] <= BarsRequired || 
    				CurrentBars[2] <= BarsRequired)
    				return;
    			
    			//reset score on each bar update
    			int Score = 0;	
    			
    //------------------------------------------------------------------------------------	
    			//for each BarsInProgress
    			for(int x = 0; x <= 2; x++)
    			{
    				if(BarsInProgress == x)
    				{
    					bool MaUp;			//define moving average up variable
    					string LongOrShort;	//define Long or short string
    					
    					// determines if 8ema is above the 15sma
    					if (EMA(8)[0] > SMA(25)[0])
    					{
    						MaUp = true;
    					}
    					else 
    						MaUp = false;
    					
    					
    					if(MaUp)
    					{
    						LongOrShort = "SHORT";	//set short bias
    					
    						switch(x)	//score for each time frame
    						{
    							case 2:
    								Score = Score + HourlyScore;
    								break;
    							case 1:
    								Score = Score + TenMinScore;
    								break;
    							case 0:
    								Score = Score + TwoMinScore;
    								break;
    						}
    					
    					}
    					else					
    					if(MaUp == false)
    					{
    						LongOrShort = "LONG";	//set long bias
    						
    						switch(x)	//score for each time frame
    						{
    							case 2:
    								Score = Score - HourlyScore;
    								break;
    							case 1:
    								Score = Score - TenMinScore;
    								break;
    							case 0:
    								Score = Score - TwoMinScore;
    								break;
    						}
    					}				
    					else 
    						
    						LongOrShort = "NOTRADE";  //set no trade bias
    				}
    			}	
    				Print(ToTime(Time[0]));		//print time of score
    				Print("Score is " + Score);	//print score
           }
    
            #region Properties
            #endregion
        }
    }
    Attached Files
    Last edited by ShruggedAtlas; 02-07-2012, 09:01 AM.

    #2
    ShruggedAtlas, I would expect that to be the case - you're printing the score for each BarsInProgress, so in total for each tick you see 3 calls to OnBarUpdate() then. You could print simply from the primary series to see one update, you can refer to other series data in BarsInProgress == 0 as well to calculate anything you need for the score.
    BertrandNinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_Bertrand View Post
      ShruggedAtlas, I would expect that to be the case - you're printing the score for each BarsInProgress, so in total for each tick you see 3 calls to OnBarUpdate() then. You could print simply from the primary series to see one update, you can refer to other series data in BarsInProgress == 0 as well to calculate anything you need for the score.
      how would I print from the primary series since all the series are in scope of a for statement?
      I can't print the score outside of BarsUpdate because the Score variable is reset on each update. I've tried putting the print statement in the switch cases but they won't print to the output window for some reason. Is my mistake that i'm using a for loop to loop through the BarsInProgress?

      Also, you said that I was printing the score for each BarsInProgress, but i'm not sure thats right. I have my time and print statements after the BarsInProgress for loop block. Therefore isn't it printing after all three BarsInProgress, not during?
      Last edited by ShruggedAtlas; 02-07-2012, 07:57 AM.

      Comment


        #4
        Yes, just process your logic in BarsInProgress == 0, the primary series - you can still check all other bars object data for your conditions inside this call by pointing to the needed BarsArray for your MA calcs - http://www.ninjatrader.com/support/h.../barsarray.htm

        That should simplify matters and you update your code score from one timeframe only but on each tick if realtime.
        BertrandNinjaTrader Customer Service

        Comment


          #5
          Ok I see what you mean. So I'll need a different approach to cycling through the BarsInProgress. Instead of using a for loop, I'll just access the other BarArrays from within BarsInProgress == 0 (the primary series)

          let me know if you think I have it wrong. thx!

          Comment


            #6
            Bertrand,

            Yes, I agree, use BarsArray in BarsInProgress=0 to access all timeframes while CalculateOnBarClose=False.

            Most indicators include calculations with the variable 'Close', and 'Close' value changes intrabar, so with this approach, how often are the additional timeframe dataset in BarArrays updated for intrabar calculations? Does NT wait until the user script completes for BarsInProgress ==0, or is the dataset updated concurrently?

            Comment


              #7
              Hello,
              An example will be like:

              Code:
              protected override void OnBarUpdate()
                      {
                          
              	if (BarsInProgress == 0)	//called upon when BarsArray[0] is updated
              	{
              		double primaryClose = Close[0]; //we can also write Closes[0][0];
              		double secondary1Close = Closes[1][0]; //1st secodnary series
              		double secondary2Close = Closes[2][0]; //2nd secondary series
              	}
              	else if (BarsInProgress == 1)	//called upon when BarsArray[1] is updated
              	{
              		double primaryClose = Closes[0][0]; //close for primary series
              		double secondary1Close = Close[0];	//we can also write Closes[1][0];
              		double secondary2Close = Closes[2][0]; //2nd secondary series
              	}
              	else if (BarsInProgress == 2)	//called upon when BarsArray[2] is updated
              	{
              		double primaryClose = Closes[0][0];	//close for primary series
              		double secondary1Close = Closes[1][0];	//1st secondary series
              		double secondary2Close = Close[0];	//we can also write Closes[2][0];
              	}
              }
              NinjaTrader is an event driven application and OnBarUpdate event is updated as and when it receives the quotes.

              NinjaTrader will process the entire code before processing any other quotes.

              To get a further understanding please refer here http://www.ninjatrader.com/support/h...nstruments.htm

              Please let me know if I can assist you any further.
              JoydeepNinjaTrader Customer Service

              Comment


                #8
                Sorry, I don't understand your reply Joydeep. What you've said seems to conflict.

                In your sample code, you have commented that BarsArray[0] is updated only when BarInProgress ==0:

                if (BarsInProgress == 0) //called upon when BarsArray[0] is updated
                I understand that, but if user's code (script) is called (becasue of the current state of BarsInProgress) and is executing, and a streaming quote comes in (event driven interupt), is the execution of the user's code (script) suspended? Or is the update of the BarsArray[] dataset delayed until the user code completes? Note: I don't see an explaination of this in the NT documentation.

                Is the user's code or script considered an event, and the updating of the BarsArray[] dataset another event? Which takes precedence? Or is there a queue?

                Comment


                  #9
                  I believe the stream is delayed until user code is processed. I can't remember where i saw a posting but I know NT support clarified that in another thread somewhere. It's a good reason to optimize your code and to keep it as simple and streamlined as possible.

                  Comment


                    #10
                    Originally posted by ShruggedAtlas View Post
                    I believe the stream is delayed until user code is processed. I can't remember where i saw a posting but I know NT support clarified that in another thread somewhere. It's a good reason to optimize your code and to keep it as simple and streamlined as possible.
                    I would HOPE that it is delayed for only that chart/instrument/indicator/strategy,as the other charts/instruments/strats/indicators should be processing still.

                    That would something worth testing.

                    Create an indicator/strat, wait 10 seconds every tick, and see what happens.. (if other charts are fine, etc).

                    But I think when I did an infinite loop - everything was locked up.. so this might not work.

                    Comment


                      #11
                      Hello,
                      When a quote comes in, the OnBarUpdate event is triggered. Any code in OnBarUpdate is executed first before the next quote could be processed. If you put resource hungry code, NinjaTrader will become sluggish or lag, an infinite loop will lock up NinjaTrader.

                      Please let me know if I can assist you any further.
                      JoydeepNinjaTrader Customer Service

                      Comment


                        #12
                        Joydeep,

                        Thank you for the reply.

                        So in summary, when the quote comes in, and no user code is currently executing, the BarsArray[] dataset is updated and the OnBarUpdate event is then triggered so that user code can execute on the newly updated dataset.

                        However if the quote comes in and user code is currently executing, then the updating of the BarsArray[] dataset is delayed until user code is complete. The dataset would subsequently be updated and an OnBarUpdate event would then be set so that user code could execute on the updated dataset.

                        Comment


                          #13
                          Hello Borland,
                          Yes, you are correct.

                          Please let me know if I can assist you any further.
                          JoydeepNinjaTrader Customer Service

                          Comment


                            #14
                            Originally posted by NinjaTrader_Joydeep View Post
                            Hello,
                            When a quote comes in, the OnBarUpdate event is triggered. Any code in OnBarUpdate is executed first before the next quote could be processed. If you put resource hungry code, NinjaTrader will become sluggish or lag, an infinite loop will lock up NinjaTrader.

                            Please let me know if I can assist you any further.
                            Yes, you can. Here's a good question -

                            When I EnterLong(), and SetProfitTarget and SetStopLoss, is the female voice for Playing "Order Filled" "Order Pending", separately threaded or dumped off to windows, or is it also in synch such that NT doesn't respond until it is finished?



                            I know in MarketReplay the audio gets cut off at 500x.. but what is really happening behind the scenes in live?

                            I guess I could record a Sound of 30 seconds and play that live and see what happens if I get hung up.

                            thanks

                            Comment


                              #15
                              Hello sledge,
                              The sounds files are played asynchronously.

                              Please let me know if I can assist you any further.
                              JoydeepNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by andrewtrades, Today, 04:57 PM
                              1 response
                              5 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Started by chbruno, Today, 04:10 PM
                              0 responses
                              3 views
                              0 likes
                              Last Post chbruno
                              by chbruno
                               
                              Started by josh18955, 03-25-2023, 11:16 AM
                              6 responses
                              436 views
                              0 likes
                              Last Post Delerium  
                              Started by FAQtrader, Today, 03:35 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post FAQtrader  
                              Started by rocketman7, Today, 09:41 AM
                              5 responses
                              19 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Working...
                              X