NexusFi: Find Your Edge


Home Menu

 





foreach BarsInProgress?


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one ShruggedAtlas with 6 posts (1 thanks)
    2. looks_two vvhg with 2 posts (0 thanks)
    3. looks_3 bukkan with 1 posts (1 thanks)
    4. looks_4 Fat Tails with 1 posts (1 thanks)
      Best Posters
    1. looks_one bukkan with 1 thanks per post
    2. looks_two jeremytang with 1 thanks per post
    3. looks_3 Fat Tails with 1 thanks per post
    4. looks_4 ShruggedAtlas with 0.2 thanks per post
    1. trending_up 4,105 views
    2. thumb_up 4 thanks given
    3. group 3 followers
    1. forum 11 posts
    2. attach_file 0 attachments




 
Search this Thread

foreach BarsInProgress?

  #1 (permalink)
 
ShruggedAtlas's Avatar
 ShruggedAtlas 
Bloomington
 
Experience: Beginner
Platform: NinjaTrader
Broker: Interactive Brokers
Trading: Stocks
Posts: 191 since Apr 2011
Thanks Given: 78
Thanks Received: 75

Is it possible to use something like a foreach loop on the BarsInProgress? I have a complicated procedure that i need to do for 4 different time frames. it's a lot of code that could be made simpler if I could apply the same code to each data stream.

Any ideas for how this might be done?

the basic idea behind the code is that I'm checking some conditions on each of the 4 time frames, then making an evaluation based on those conditions and then tracking a total score for the 4 different conditions as evaluated together. The part of the code that checks for conditions could be much tidier if it were compressed into a single code block.

any ideas?

"I've missed more than 9,000 shots in my career. I've lost almost 300 games. 26 times, I've been trusted to take the game-winning shot and missed. I've failed over and over and over again in my life. And that is why I succeed."
- Michael Jordan, 5-Time NBA Most Valuable Player, 6-Time NBA Champion
Visit my NexusFi Trade Journal Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
Quant vue
Trading Reviews and Vendors
REcommedations for programming help
Sierra Chart
Better Renko Gaps
The Elite Circle
Cheap historycal L1 data for stocks
Stocks and ETFs
How to apply profiles
Traders Hideout
 
  #3 (permalink)
 
vvhg's Avatar
 vvhg 
Northern Germany
 
Experience: Intermediate
Platform: NT
Trading: FDAX, CL
Posts: 1,583 since Mar 2011
Thanks Given: 1,016
Thanks Received: 2,824


I think you could do that by just not specifying the barsinprogress, in that case the code fires for all barsinprogress....

Vvhg


Sent from my iPad using Tapatalk HD

Hic Rhodos, hic salta.
Reply With Quote
  #4 (permalink)
 
ShruggedAtlas's Avatar
 ShruggedAtlas 
Bloomington
 
Experience: Beginner
Platform: NinjaTrader
Broker: Interactive Brokers
Trading: Stocks
Posts: 191 since Apr 2011
Thanks Given: 78
Thanks Received: 75

Thx vvhg that might work if I work with BarsArray[] but it may end up being too complicated for me to work with. Still not sure. NT support on the NT forum gave me an option that uses a for loop to loop through each BarsInProgress. I couldn't get foreach to work with BarsInProgress so I assumed I couldn't use other loops. Apparently a for loop works just fine.

Code he gave as an example is shown below:


if(CurrentBar < 0 || CurrentBars[1] < 0 || CurrentBars[2] < 0) return;

for (int x = 0; x <= 2; x++)
{
if (BarsInProgress == x)
Print("Closing price for " + Instrument.FullName + ": " + Close[0]);
}


It looks like I'll probably work with this option since it's easy to work with will allow me to change my existing code the least.

Thx for your help!!

"I've missed more than 9,000 shots in my career. I've lost almost 300 games. 26 times, I've been trusted to take the game-winning shot and missed. I've failed over and over and over again in my life. And that is why I succeed."
- Michael Jordan, 5-Time NBA Most Valuable Player, 6-Time NBA Champion
Visit my NexusFi Trade Journal Started this thread Reply With Quote
  #5 (permalink)
 
vvhg's Avatar
 vvhg 
Northern Germany
 
Experience: Intermediate
Platform: NT
Trading: FDAX, CL
Posts: 1,583 since Mar 2011
Thanks Given: 1,016
Thanks Received: 2,824


ShruggedAtlas View Post
Thx vvhg that might work if I work with BarsArray[] but it may end up being too complicated for me to work with. Still not sure. NT support on the NT forum gave me an option that uses a for loop to loop through each BarsInProgress. I couldn't get foreach to work with BarsInProgress so I assumed I couldn't use other loops. Apparently a for loop works just fine.

Code he gave as an example is shown below:


if(CurrentBar < 0 || CurrentBars[1] < 0 || CurrentBars[2] < 0) return;

for (int x = 0; x <= 2; x++)
{
if (BarsInProgress == x)
Print("Closing price for " + Instrument.FullName + ": " + Close[0]);
}


It looks like I'll probably work with this option since it's easy to work with will allow me to change my existing code the least.

Thx for your help!!

I'm not a good coder, so I would have to look it up, but I thought that if you don't specify the barsinprogress index, it would fire regardless of the bar series....But I might have that completely wrong.

As to loops, it is often a quick way to code sth, but I have no idea what the optimum would be in regards to syntax performance...but there can be huge performance differences.....
Other loops you could use here would be while loop or do loop with break. Disadvantage with do loops is that you better not forget to exit the loop at some point....

Vvhg


Sent from my iPad using Tapatalk HD

Hic Rhodos, hic salta.
Reply With Quote
  #6 (permalink)
 
ShruggedAtlas's Avatar
 ShruggedAtlas 
Bloomington
 
Experience: Beginner
Platform: NinjaTrader
Broker: Interactive Brokers
Trading: Stocks
Posts: 191 since Apr 2011
Thanks Given: 78
Thanks Received: 75

public class MyCustomStrategy : Strategy
{
#region Variables
// Wizard generated variables
private int myInput0 = 1; // Default setting for MyInput0
// User defined variables (add any user defined variables below)
#endregion
int LongScore = 0; //keeps track of probablilities for Long success
int ShortScore = 0; //keeps track of probablilities for Short success

protected override void Initialize()
{
CalculateOnBarClose = false; //score must be calculated at each tick
Add(PeriodType.Minute, 10); //adding 10 minute data
Add(PeriodType.Minute, 60); //adding 60 minute data
Add(PeriodType.Day, 1); //adding daily data
}

protected override void OnBarUpdate()
{
if (CurrentBars[0] <= BarsRequired ||
CurrentBars[1] <= BarsRequired ||
CurrentBars[2] <= BarsRequired ||
CurrentBars[3] <= BarsRequired)
return;

int DailyScore = 1; int HourlyScore = 2; //score to be added for each time frame
int TenMinScore = 6; int TwoMinScore = 18; //score to be added for each time frame

for (int x = 0; x <= 3; x++)
{
if (BarsInProgress == x) //for each time frame
{

//local variables used to track indicator states
bool MaUp; //tracks if EMA is above SMA - bullish sign
bool SmaRising; //tracks if SMA is rising
bool PriceAboveMedian; //tracks if price is above the median of regression channel
int PriceToRcUp = 0; //tracks how far price is above upper regression channel
int PriceToRcDown = 0; //tracks how far price is above the lower regression channel
string LongOrShort; //used to track if the entry should be long or short
double[] ChannelSD = new double[] {2, 2.5, 3, 3.5};
//regression channels standard deviations

// check to see if price is above the median of channel - bullish
if (Close[0] > RegressionChannel(150, 2)[0])
{
PriceAboveMedian = true;
}
else PriceAboveMedian = false;

//check to see if longer term trendline is rising - bullish
if (Rising(SMA(25)))
{
SmaRising = true;
}
else SmaRising = false;

//check to see if EMA is above SMA - bullish
if (EMA(8)[0] > SMA(25)[0])
{
MaUp = true;
}
else MaUp = false;

/// for each standard deviation on the regression channels
/// add a number to PriceToRc so we can track where price is
/// relative to the regresion channel extrememes
foreach (double i in ChannelSD)
if(Close[0] > RegressionChannel(150, i).Upper[0])
{
PriceToRcUp = PriceToRcUp + 1;
}

foreach (double i in ChannelSD)
if(Close[0] < RegressionChannel(150, i).Lower[0])
{
PriceToRcDown = PriceToRcDown + 1;
}

//evaluate which direction trade should go - long or short?
if(PriceAboveMedian && SmaRising && MaUp && PriceToRcUp > 0)
{
LongOrShort = "SHORT";
}
else
if(PriceAboveMedian == false && SmaRising == false && PriceToRcDown > 0)
{
LongOrShort = "LONG";
}
else LongOrShort = "NOTRADE";

// set probability of success score based on evaluation
if(LongOrShort == "LONG")
{
switch(x)
{
case 0:
LongScore = LongScore + DailyScore;
ShortScore = ShortScore - DailyScore;
break;
case 1:
LongScore = LongScore + HourlyScore;
ShortScore = ShortScore - HourlyScore;
break;
case 2:
LongScore = LongScore + TenMinScore;
ShortScore = ShortScore - TenMinScore;
break;
case 3:
LongScore = LongScore + TwoMinScore;
ShortScore = ShortScore - TwoMinScore;
break;
}

}
else
if(LongOrShort == "SHORT")
{
switch (x)
{
case 0:
LongScore = LongScore - DailyScore;
ShortScore = ShortScore + DailyScore;
break;
case 1:
LongScore = LongScore - HourlyScore;
ShortScore = ShortScore + HourlyScore;
break;
case 2:
LongScore = LongScore - TenMinScore;
ShortScore = ShortScore + TenMinScore;
break;
case 3:
LongScore = LongScore - TwoMinScore;
ShortScore = ShortScore + TwoMinScore;
break;
}

}

Print("LongScore is " + LongScore);
Print("ShortScore is " + ShortScore);

}

}
}

#region Properties
[Description("")]
[GridCategory("Parameters")]
public int MyInput0
{
get { return myInput0; }
set { myInput0 = Math.Max(1, value); }
}
#endregion
}
}

"I've missed more than 9,000 shots in my career. I've lost almost 300 games. 26 times, I've been trusted to take the game-winning shot and missed. I've failed over and over and over again in my life. And that is why I succeed."
- Michael Jordan, 5-Time NBA Most Valuable Player, 6-Time NBA Champion
Visit my NexusFi Trade Journal Started this thread Reply With Quote
  #7 (permalink)
 
ShruggedAtlas's Avatar
 ShruggedAtlas 
Bloomington
 
Experience: Beginner
Platform: NinjaTrader
Broker: Interactive Brokers
Trading: Stocks
Posts: 191 since Apr 2011
Thanks Given: 78
Thanks Received: 75

just imagine the code in the last post...only about 4 times longer

"I've missed more than 9,000 shots in my career. I've lost almost 300 games. 26 times, I've been trusted to take the game-winning shot and missed. I've failed over and over and over again in my life. And that is why I succeed."
- Michael Jordan, 5-Time NBA Most Valuable Player, 6-Time NBA Champion
Visit my NexusFi Trade Journal Started this thread Reply With Quote
  #8 (permalink)
 
jeremytang's Avatar
 jeremytang  SharkIndicators is an official Site Sponsor
Site Sponsor

Web: SharkIndicators
AMA: Ask Me Anything
Webinars: SharkIndicators Webinars
Elite offer: Click here
 
Posts: 16 since Aug 2010
Thanks Given: 4
Thanks Received: 53

Hi ShruggedAtlas,

In the code you've provided, the for loop is redundant... so you can get the exact same effect with it removed.

My question is do you:

1) Want to perform your code on ALL time frames all the time (ie: whenever ANY of the timeframes are updated)

or

2) Only perform your code for the timeframe that is currently being updated

If you fall into category 1, then you need a for loop, and you'll have to reference all the closing prices, highs and lows etc by: Closes[x][0], Highs[x][0] etc. (note the plural).

Otherwise, if you're category 2 you can omit the for loop and access your data using Close[0], High[0] (etc) <-- no plural.

OnBarUpdate is called for each BarsInProgress in turn, and the Close, High (etc) DataSeries are changed to reflect the current BarsInProgress.

I assume you're more likely category 2, because you are referencing SMA, EMA and regressionChannel on the main timeframe (BarsInProgres == 0), am I right? Or do you intend to check the regressionChannel on every timeframe?

Jeremy

Reply With Quote
Thanked by:
  #9 (permalink)
 
Fat Tails's Avatar
 Fat Tails 
Berlin, Europe
Market Wizard
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
Posts: 9,888 since Mar 2010
Thanks Given: 4,242
Thanks Received: 27,103

Some comments on your code:

You want to calculate your score with each tick by setting CalculateOnBarClose = false. Your score uses relatively complex calculations such as a regression channel.

Are you aware that with this code you recalculate your daily regression channel with each incoming tick producing billions of calculations for a value that only needs to be recalculated once per day?

If you want a trendfilter that calculates the trend from 4 different timeframes, you need either do this in CalculateOnBarClose = true or you need to pulse the calculations, that is

-> execute the trend calculations only every minute
-> but trigger the alerts intra-bar in case that price exceeds one of the channels

But now to your original question. OnBarUpdate() is executed for each BarsInProgress. That means that the code

 
Code
for (int x = 0; x <= 3; x++)
{
       if (BarsInProgress == x)    //for each time frame
       {
           .....
       }
}
does not add anything.

It is simply redundant. If you delete those lines, the code section in brackets will be executed with each BarsInProgress.


Other suggestions:

-> daily bars are not always added at the proper location that is start at the trading day
-> daily data will not be available at the moment when the new session starts, because it has not been compiled then by the daily data provider

So you should probably emulate daily bars by using intraday data.

Reply With Quote
Thanked by:
  #10 (permalink)
 bukkan 
Calcutta, India
 
Experience: Intermediate
Platform: ArthaChitra
Posts: 278 since Jun 2009
Thanks Given: 161
Thanks Received: 271



ShruggedAtlas View Post
if(CurrentBar < 0 || CurrentBars[1] < 0 || CurrentBars[2] < 0) return;

for (int x = 0; x <= 2; x++)
{
if (BarsInProgress == x)
Print("Closing price for " + Instrument.FullName + ": " + Close[0]);
}



the above code is same as
if(CurrentBar < 0 || CurrentBars[1] < 0 || CurrentBars[2] < 0) return;
Print("Closing price for " + Instrument.FullName + ": " + Close[0]);


to get the close of the other series just uses the below code"
Print(Closes[1][0]);
Print(Closes[2][0]);

Reply With Quote
Thanked by:




Last Updated on February 17, 2012


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts