Hi All,

I had posted something about detecting new bars, and sidartha70 responded with 
some good thoughts. I said I would post the code, so here is the snippet I use 
to detect that the bar has changed. Please note, for this to work, you want to 
have the timestamp for a bar correspond with the start and not the end of the 
bar (a configurable option).

// -- Prepare to write file. File will contain price information my
//    order entry app will use to put an order in through NT
sHdr = "Instrument,TimeStamp,H,L,TradeDirection,LLV4,HHV4,TickSize";
tInt = Interval(2);
sFName = "C:\\Documents and Settings\\grose\\My Documents\\NinjaTrader 
6.5\\AB-" + Name() + "-" + tInt;

// -- Detect new bar
LastDateTimeNum = StaticVarGet("LastDateTimeNum");
// -- Initialize if necessary
if (IsEmpty(LastDateTimeNum) OR IsNull(LastDateTimeNum)) 
{  
  StaticVarSet("LastDateTimeNum", LastValue(DT));
  LastTimeNum = StaticVarGet("LastDateTimeNum");
  fh = fopen(sFName + ".log", "w");
  if (fh) {
    fputs(sHdr + "\r\n", fh);
    fclose(fh);
  }
  _TRACE("Initializing LastDateTimeNum: " + WriteVal(LastDateTimeNum, 
formatDateTime));
}

// -- Detect that bar has changed. I limit this code to work only if
//    using RT database, e.g. eSignal in my case
if (LastValue(DT) != LastDateTimeNum AND StrFind(GetDatabaseName(), "eSignal") 
>= 0) 
{

  StaticVarSet("LastDateTimeNum", LastValue(DT));

  // -- Originally, I worked with BarIndex() and could
  //    get funky results seeming to have to do with 
  //    timing. The ValueWhen() approach has worked consistently.
  LastBarOpen = LastValue(ValueWhen(DT==LastDateTimeNum, O));
  LastBarHigh = LastValue(ValueWhen(DT==LastDateTimeNum, H));
  LastBarLow = LastValue(ValueWhen(DT==LastDateTimeNum, L));
  LastBarClose = LastValue(ValueWhen(DT==LastDateTimeNum, C));
  LastBarLLV4 = LastValue(ValueWhen(DT==LastDateTimeNum, LLV(L, 4)));
  LastBarHHV4 = LastValue(ValueWhen(DT==LastDateTimeNum, HHV(H, 4)));
  TradeDir = WriteIf(LastBarClose > LastBarOpen, "long", "short");
   
  sLine = Name() + "," + WriteVal(LastDateTimeNum, formatDateTime) + "," + 
      WriteVal(LastBarHigh) + "," + WriteVal(LastBarLow) + "," + 
      TradeDir + "," + WriteVal(LastBarLLV4) + "," + WriteVal(LastBarHHV4) + 
",.25";

  fh = fopen(sFName + ".txt", "w");

  if (fh) {
    fputs(sHdr + "\r\n", fh);
    fputs(sLine, fh); 
    fclose(fh);
  }

}

Reply via email to