CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 44

Thread: count++

  1. #1
    Join Date
    Aug 2013
    Posts
    25

    count++

    Is there a way I can get count++ to function on multiple variables simultaneously.

    Say I have variable X, Y & Z and X occurs have it count and store 1 occurrence for X and 2 occurrences for Y etc..

    But instead of having just variableX count++ and variableY count++ separate, have them combined something like..

    variable()++ where whatever is inside () it will track and store for example 1 occurrence of X, 2 occurrences of Y etc.

    What would I have to put inside the () to do this? Or if that's completely off is there anyway to accomplish this?

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: count++

    Not really since the ++ operator only increments the variable its used on.

    What you can do is create a class method that can act on multiple variables (i.e. Properties).
    Code:
        class Test
        {
            public int X { get; private set; }
            public int Y { get; private set; }
            public int Z { get; private set; }
    
            public void Increment()
            {
                X++;
                Y++;
                Z++;
            }
            public override string ToString() { return String.Format("X: {0} Y: {1} Z: {2}", X, Y, Z); }
        }
    Code:
        class Program
        {
            static void Main(string[] args)
            {
                var test = new Test();
                Console.WriteLine(test);
    
                test.Increment();
                Console.WriteLine(test);
    
            }
        }
    Output:
    Code:
    X: 0 Y: 0 Z: 0
    X: 1 Y: 1 Z: 1
    Last edited by Arjay; August 23rd, 2013 at 08:56 PM.

  3. #3
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    Thanks for this, best info I've received so far. If what I'm trying to count is the # of times the three stock ticker symbols below are triggered for a trade. Would I have to make a seperate variable for each of these below or can I somehow use info from the below initialize section without having to create a new variable for each. The method below is standard to the trading software called Ninja Trader that I use.

    protected override void Initialize()
    {
    #region
    //5min price bars
    Add("MSFT",PeriodType.Minute, 5); //In 0 placeholder position
    Add("AAPL",PeriodType.Minute, 5); //In 1 placeholder position
    Add("NFLX",PeriodType.Minute, 5); //In 2 placeholder position

    There method for entering a trade is
    EnterLong()

    So every time after one of the tickers enters long I'm looking for it to count and store it.

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: count++

    So you are saying that an EnterLong() method gets called for each of the Add("stock"...) entries?

    Or does a single EnterLong(....) method gets called that lets you know the count and the stock that was updated?

    Btw, there are lot's of ways to structure this, but one simple way is to use a dictionary.

    Code:
    Dictionary<string, int> _stockCounts = new Dictionary<string, int>();
    you initially add some stocks.
    Code:
    _stockCounts.Add("MSFT", 0);
    _stockCounts.Add("AAPL", 0);
    to increment a count...
    Code:
    _stockCounts["MSFT"]++;
    So if EnterLong(....) passed in the stock, you could do something like:

    Code:
    public override void EnterLong( string stockSymbol )
    {
      if(_stockCounts.ContainsKey(stockSymbol))
      {
        _stockCounts[stockSymbol]++;
      }
    }
    Last edited by Arjay; August 28th, 2013 at 12:04 AM.

  5. #5
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    Ya, you actually understand what im trying to do thats great. EnterLong() gets called for any stock that meets the entry conditions. Each stock 0 thru 2 is passed thru the entry conditions via the for loop below. 0 being 1st stock, 1 being 2nd stock and so on. I used series instead of stock below. Then the software uses BarsInProgress below I guess to call each Added stock from the initialize section.

    for (int series = 0; series < 3; series++)
    if (BarsInProgress == series)

    //conditions for stock entry where "series" is plugged in.
    EnterLong() //enters long for any stock/series thats passing thru at the moment that met conditions
    //here count & hold # entries for each particular stock/series that triggered

    where you have [stockSymbol] above will that pull each stock in the dictionary through?

    and what is ContainsKey?

    I will have 100's of stocks so thats why Im trying to loop all stocks through limited code and not have to repeat EnterLong() for each individual stock over and over.

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: count++

    To answer your questions, you need to better define what this is:

    There method for entering a trade is
    EnterLong()
    Does this get called by the framework you are using? and, if so...
    Does a separate EnterLong() method get called for each stock?
    or
    Does a single EnterLong() method get called for all the stocks? If so, how do you know which stock is getting updated?

  7. #7
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    Yes a single EnterLong() method gets called for all stocks. That for loop that loops the script through 0,1,2... that proceeds BarsInProgress == 0, then goes to BarsInProgress == 1 then BarsInProgress == 2 and so on and dictates which stock is running through. So when 0 is looping through the script the first stock is routing through all the code and ultimately to EnterLong(), then 1 is looping through which is the second stock and so on.

    0 is.. Add("1st stock", 0)
    1 is.. Add("2nd stock", 0)

    BarsInProgress is just basically the Stock.
    Last edited by zirjeo; August 29th, 2013 at 09:43 PM.

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: count++

    Can you post the code within the single EnterLong() method?

  9. #9
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    Oh boy well here goes, hope it doesn't scare you away. I used NumEntries++ any place where I was wanting it to count and store entries, but that's not anything that actually functions. After it counts I was wanting it to route back to the bool statement that you will see below to make sure number of entries is < 1.

    Code:
    protected override void Initialize()
    {
    #region Primary 5min
    
      //Primary 5min
      Add("ACE",PeriodType.Minute, 5);
      Add("ACN",PeriodType.Minute, 5);
      Add("ADT",PeriodType.Minute, 5);
      Add("SCTY",PeriodType.Minute, 5);
    #endregion
    
    #region Secondary 1min
      //Secondary 1min
      Add("ABC",PeriodType.Minute, 1);
      Add("ACE",PeriodType.Minute, 1);
      Add("ACN",PeriodType.Minute, 1);
      Add("ADT",PeriodType.Minute, 1);
      Add("SCTY",PeriodType.Minute, 1);
    #endregion
    
      Add(SMA(Fast));
      Add(SMA(Slow));
    
      EntriesPerDirection = 1;
      EntryHandling = EntryHandling.UniqueEntries;
      CalculateOnBarClose = true;
    
    }
    
    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
      //for loop to iterate each instrument through, "series" is 5min of each instrument, "series + 5" is 1min of each instrument.
      for (int series = 0; series < 5; series++)
    {
        if (BarsInProgress == series + 5) //OnBarUpdate called for 1min bars
        {  
          bool enterTrade = false;
          if (NumEntries < 1)
          {
            enterTrade = true;
          }
          else
          {
            enterTrade = BarsSinceEntry(series, "", 0) > 2; 
          } 
    
          if (enterTrade)
          {
              // Condition set 1 Long Entry, fast MA cross above slow MA & current price > high of bar at cross.
              if (SMA(BarsArray[series],Fast)[1] > SMA(BarsArray[series],Slow)[1] 
                  && SMA(BarsArray[series],Fast)[2] < SMA(BarsArray[series],Slow)[2]
                  && Closes[series + 5][0] > Highs[series][1] + distance
                  && SMA(BarsArray[series],Slow)[1] > SMA(BarsArray[series],Slow)[2] + .01 )
       {
               EnterLong(200);
               NumEntries++;
       }
          }
    } }
    Last edited by Arjay; August 30th, 2013 at 03:56 PM.

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: count++

    I took the liberty of formatting your code a bit. I also added curly braces because without them, it's easy to introduce error because a for loop will only act on the first line of code immediately following the for loop (or the if statement). Maybe it works right now without the extra braces, but you might add a line of code and then it won't work as you expect. Better to get into the practice of adding curly braces after for and if statements. Then it's clear to all how the code should work.

    That being said, I took a guess as to where the placement of the NumEntries++; statement should go. I probably got it wrong (which is why you should use curly braces).

    As far as the code scaring me. I'm not scared, but I really don't know what you are accomplishing with this code. In earlier posts, you mentioned that EnterLong() method gets called. Well, the way you have that coded, you always pass in a value of 200, so I'm not sure what that does.

    Also, what is NumEntries? Is that the number of stocks or the number of tick counts? Or the number of times something meets your criteria?

    Getting back to what we discussed earlier with keeping track of counts for a particular stock. Looking at your code, you are tracking the stock by it's index (i.e. the series variable), right? Therefore if a stock meets the criteria and you want to increment its count, you can use a dictionary like I described before (except make it a Dictionary<int, int>) and then change your code to:

    Code:
              // Condition set 1 Long Entry, fast MA cross above slow MA & current price > high of bar at cross.
              if (SMA(BarsArray[series],Fast)[1] > SMA(BarsArray[series],Slow)[1] 
                  && SMA(BarsArray[series],Fast)[2] < SMA(BarsArray[series],Slow)[2]
                  && Closes[series + 5][0] > Highs[series][1] + distance
                  && SMA(BarsArray[series],Slow)[1] > SMA(BarsArray[series],Slow)[2] + .01 )
       {
          _stockCounts[series]++;
    //           EnterLong(200);
    //           NumEntries++;
       }
    That will increment the count on the stock (by its series index) when it meets your criteria. Then if you need to find out the count elsewhere, just retrieve the count for a stock by calling

    Code:
    var singleStockCount = _stockCounts[series];
    There are actually a better ways to do this, but this approach is very simple.

  11. #11
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    I just missed a curly bracket when I was copying and pasting and moving things around, sorry about that. And NumEntries++ is just the number of times a particular stock or index meets the criteria and Enters the stock Long. The 200 is just the # of shares to buy. EnterLong(int quantity).

    Yes tracking by the index which I named series(could have just named index instead).

    Thanks alot! I will experiment with this over the weekend and let you know how I make out.

  12. #12
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    I'm getting some compile errors. Do I put the Dictionary in the initialize() section above all the add's as I have below or is there something else basic I'm missing?

    It's telling me type or namespace Dictionary could not be found, and _stockCounts does not exist in current context. Also I'm not sure if I used the ContainsKey() statement near EnterLong() correctly?

    Code:
    protected override void Initialize()
            {
    Dictionary<int, int> _stockCounts = new Dictionary<int, int>();
    			
    #region Primary 5min			
    //Primary 5min
    _stockCounts.Add("ACE",PeriodType.Minute, 5);
    _stockCounts.Add("ACN",PeriodType.Minute, 5);
    _stockCounts.Add("ADT",PeriodType.Minute, 5);
    _stockCounts.Add("SCTY",PeriodType.Minute, 5);
    #endregion
    
    #region Secondary 1min
    //Secondary 1min
    _stockCounts.Add("ABC",PeriodType.Minute, 1);
    _stockCounts.Add("ACE",PeriodType.Minute, 1);
    _stockCounts.Add("ACN",PeriodType.Minute, 1);
    _stockCounts.Add("ADT",PeriodType.Minute, 1);
    _stockCounts.Add("SCTY",PeriodType.Minute, 1);
    #endregion
    			
    			Add(SMA(Fast));
                Add(SMA(Slow));
    			
    			EntriesPerDirection = 1;
    			EntryHandling = EntryHandling.UniqueEntries;
    							
                CalculateOnBarClose = true;
    
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {	
    	
    		
              //for loop to iterate each instrument through, "series" is 5min of each instrument, "series + 5" is 1min of each instrument.
    			for (int series = 0; series < 5; series++)
    			if (BarsInProgress == series + 5) //OnBarUpdate called for 1min bars
    			{	 
    				var singleStockCount = _stockCounts[series];
    				bool enterTrade = false;
    				
    			    if (singleStockCount < 1)
    				{
    				enterTrade = true;
    				}
    				else
    				{
    				enterTrade = BarsSinceEntry(series, "", 0) > 2; 
    				} 
    
                    if (enterTrade)
    				  {  // Condition set 1 Long Entry, fast MA cross above slow MA & current price > high of bar at cross.
    	                if (SMA(BarsArray[series],Fast)[1] > SMA(BarsArray[series],Slow)[1] && 
    					SMA(BarsArray[series],Fast)[2] < SMA(BarsArray[series],Slow)[2] && Closes[series + 5][0] > Highs[series][1] + distance 
    					&& SMA(BarsArray[series],Slow)[1] > SMA(BarsArray[series],Slow)[2] + .01 )
    
                                 EnterLong(200);
    				{
                                      if(_stockCounts.ContainsKey(series))
                                       {
                                          _stockCounts[series]++;
                                         }
    				}
    		      }
                } 
    		
    }
    Last edited by zirjeo; September 2nd, 2013 at 12:03 PM.

  13. #13
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    I solved the namespace issue by adding using System.Collections.Generic;

    But using this... _stockCounts.Add("ACE",PeriodType.Minute, 5);

    I don't think I can use...

    Dictionary<string, int> _stockCounts = new Dictionary<string, int>();

    Dictionary only has 2 arguments I need a string, PeriodType, and int. Someone suggested using a list of struct's but I'm not sure what the heck that means.

    Any idea?

    Thanks

  14. #14
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: count++

    You can use an dictionary of structs, but you can also keep it simple. Instead of supplying a string, period type and value, can get rid of the period type by converting everything to the lowest unit. For example if you only track hours and seconds (and don't need milli-seconds), convert the hours to seconds and store everything in seconds. Therefore the dictionary will be <string, int> where the int represents the seconds.

    Btw, using a struct is a good idea, but try to get this approach working first.

  15. #15
    Join Date
    Aug 2013
    Posts
    25

    Re: count++

    I don't believe it will allow me to do that, it appears from the software manual below that it requires 3 arguments, otherwise I would think I will get a compile error...

    The following syntax allows you to add another Bars object for a different instrument to the script.
    Add(string instrumentName, PeriodType periodType, int period)

    The only way I could have 2 arguments is if I left out the 1st argument as below...
    Add(PeriodType periodType, int period)

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured