/// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { id = ToDay(Time[0]).ToString(); if (String.Compare(id, previd) == 0) { TheHigh.Set(h); TheLow.Set(l); return; //don't do the same day again, wait for new day } int BarDay = Time[0].Day; int BarMonth = Time[0].Month; int BarYear = Time[0].Year; int StartBar = CurrentBar - Bars.GetBar(new DateTime(BarYear, BarMonth, BarDay, startTimeHr, startTimeMinute, 0)); int EndBar = CurrentBar - Bars.GetBar(new DateTime(BarYear, BarMonth, BarDay, endTimeHr, endTimeMinute, 0)); if (StartBar == EndBar) //if the time range is not on the chart, exit { TheHigh.Set(h); //carry forward the last known h and l values TheLow.Set(l); return; } if (EndBar >= 0) //if the end of the timeframe has already arrived { h = High[StartBar]; l = Low[StartBar]; for (int i = StartBar - 1; i >= EndBar; i--) { if (High[i] > h) { h = High[i]; } if (Low[i] < l) { l = Low[i]; } } if (StartBar < CurrentBar && EndBar < CurrentBar && StartBar > 0) { //DrawRectangle("R"+Time[0].ToString(),false,StartBar,h,EndBar,l,Color.Blue, Color.Transparent, 1); previd = id; if (pShowCrossingLines) { DrawLine("L1" + id, false, StartBar, h, EndBar, l, Color.Blue, DashStyle.Dot, 1); DrawLine("L2" + id, false, StartBar, l, EndBar, h, Color.Blue, DashStyle.Dot, 1); } DrawLine("L3" + id, false, EndBar, l, EndBar, h, Color.Green, DashStyle.Dot, 3); DrawLine("L4" + id, false, StartBar, l, StartBar, h, Color.Red, DashStyle.Dot, 3); } } TheHigh.Set(h); TheLow.Set(l); }
/// <summary> /// Transform a market series data to a Bar objects collection /// </summary> /// <param name="bars">Market series</param> /// <returns>List<Bar></returns> public static List <OhlcBar> GetBars(this Bars bars) { var result = new List <OhlcBar>(); for (var iBarIndex = 0; iBarIndex < bars.ClosePrices.Count; iBarIndex++) { var bar = bars.GetBar(iBarIndex); result.Add(bar); } return(result); }
protected override void OnBarUpdate() { // Check to make sure the end time is not earlier than the start time if (EndHour < StartHour) { return; } //Do not calculate the high or low value when the ending time of the desired range is less than the current time of the bar being processed if (ToTime(EndHour, EndMinute, 0) > ToTime(Time[0])) { return; } // If the stored date time date is not the same date as the bar time date, create a new DateTime object if (startDateTime.Date != Time[0].Date) { startDateTime = new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, StartHour, StartMinute, 0); endDateTime = new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, EndHour, EndMinute, 0); snrRanges.Add(snrRange); snrRange = null; } // Calculate the number of bars ago for the start and end bars of the specified time range int startBarsAgo = Bars.GetBar(startDateTime); int endBarsAgo = Bars.GetBar(endDateTime); /* Now that we have the start and end bars ago values for the specified time range we can calculate the highest high for this range * * Note: We add 1 to the period range for MAX and MIN to compensate for the difference between "period" logic and "bars ago" logic. * "Period" logic means exactly how many bars you want to check including the current bar. * "Bars ago" logic means how many bars we are going to go backwards. The current bar is not counted because on that bar we aren't going back any bars so it would be "bars ago = 0" */ double highestHigh = MAX(High, endBarsAgo - startBarsAgo + 1)[CurrentBar - endBarsAgo]; // Now that we have the start and end bars ago values for the specified time range we can calculate the lowest low for this range double lowestLow = MIN(Low, endBarsAgo - startBarsAgo + 1)[CurrentBar - endBarsAgo]; // Set the plot values HighestHigh[0] = highestHigh; LowestLow[0] = lowestLow; if (snrRange == null) { SupportResistanceLine rstLine = new SupportResistanceLine(); rstLine.NewSupportResistanceLine(startBarsAgo, endBarsAgo, SupportResistanceType.Resistance, HighestHigh[0]); SupportResistanceLine sptLine = new SupportResistanceLine(); sptLine.NewSupportResistanceLine(startBarsAgo, endBarsAgo, SupportResistanceType.Support, LowestLow[0]); snrRange = NewSupportResistanceRange(rstLine, sptLine); } }
protected override void OnBarUpdate() { if (Bars == null) { return; } if (!BarsType.GetInstance(Bars.Period.Id).IsIntraday) { return; } if (Bars.Period.Id == PeriodType.Minute && Bars.Period.Value > _minutes / 2) { return; } if (!_isLoaded && !_isInit) { _isInit = true; _intradayBars = Bars.GetBars(Bars.Instrument, new Period(PeriodType.Minute, _minutes, MarketDataType.Last), Bars.From, Bars.To, (Session)Bars.Session.Clone(), Bars.SplitAdjust, Bars.DividendAdjust); _existsHistHourlyData = (_intradayBars.Count <= 1) ? false : true; _isInit = false; _isLoaded = true; } if (!_existsHistHourlyData) { return; } DateTime intradayBarTime = Time[0].AddMinutes(-_minutes); IBar intradayBar = _intradayBars.Get(_intradayBars.GetBar(intradayBarTime)); double high = intradayBar.High; double low = intradayBar.Low; double close = intradayBar.Close; Hpp.Set((high + low + close) / 3); Hs1.Set(2 * Hpp[0] - high); Hr1.Set(2 * Hpp[0] - low); Hs2.Set(Hpp[0] - (high - low)); Hr2.Set(Hpp[0] + (high - low)); }
protected override void OnCalculate() { if (IsProcessingBarIndexLast) { //if (!this.Instrument.IsInMarketHours(DateTime.Now)) //{ // Plot_Performance_Indicator.Set(0); //} //else //{ //} IBar b = null; switch (this.PerformanceCalculationType) { case PerformanceCalculationType.BarCount: b = Bars[this.BarsCount]; break; case PerformanceCalculationType.ThisYear: b = Bars.Where(x => x.Time.Year != DateTime.Now.Year).LastOrDefault(); break; case PerformanceCalculationType.SelectedDate: b = Bars.GetBar(this.SelectedDate); break; } if (b != null) { Plot_Performance_Indicator.Set(((Close[0] - b.Close) * 100) / b.Close); } if (Chart != null) { IEnumerable <IBar> list = Bars.Where(x => x.Time >= b.Time).Where(x => x.Time <= Time[0]); AddChartRectangle("ORBRect" + b.Time.Ticks, true, b.Time, list.Where(x => x.Low == list.Min(y => y.Low)).LastOrDefault().Low, Time[0], list.Where(x => x.High == list.Max(y => y.High)).LastOrDefault().High, Color.Aquamarine, Color.Aquamarine, 50); } } }
/// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { if (CurrentBars[0] < BarsRequired || CurrentBars[1] < BarsRequired) { return; } if (BarsInProgress == 1) { if (CurrentBar < 2 * period) { return; } Bars.Session.GetNextBeginEnd(Times[1][0], out sessionBegin, out sessionEnd); //sessionDate = Date(sessionBegin); //sessionBegin = sessionBegin = Convert.ToDateTime(start); sessionEnd = Convert.ToDateTime(start); Print("Session Start: " + sessionBegin + "Session End: " + sessionEnd); DateTime barTime = Times[1][0]; TimeSpan inSessionTime = barTime.Subtract(sessionBegin); int inSessionMinutes = 60 * inSessionTime.Hours + inSessionTime.Minutes; int cutoff = inSessionMinutes % period; DateTime cutoffTime = barTime.Subtract(new TimeSpan(0, cutoff, 0)); int barsAgo = CurrentBar - Bars.GetBar(cutoffTime); high = MAX(Highs[1], period)[barsAgo]; low = MIN(Lows[1], period)[barsAgo]; close = Closes[1][barsAgo]; pp = (high + low + close) / 3; range = high - low; r1 = 2 * pp - low; r2 = pp + range; r3 = r1 + range; r4 = r3 + (pp - low); s1 = 2 * pp - high; s2 = pp - range; s3 = s1 - range; s4 = s3 - (high - pp); } if (BarsInProgress == 0) { if (CurrentBar == 0) { return; } if (pp != 0.0) { PP.Set(pp); R1.Set(r1); R2.Set(r2); R3.Set(r3); R4.Set(r4); S1.Set(s1); S2.Set(s2); S3.Set(s3); S4.Set(s4); if (pp != PP[1] || r1 != R1[1] || s1 != S1[1]) { PlotColors[0][0] = Color.Transparent; PlotColors[1][0] = Color.Transparent; PlotColors[2][0] = Color.Transparent; PlotColors[3][0] = Color.Transparent; PlotColors[4][0] = Color.Transparent; PlotColors[5][0] = Color.Transparent; PlotColors[6][0] = Color.Transparent; PlotColors[7][0] = Color.Transparent; PlotColors[8][0] = Color.Transparent; } } } }
/*------------------------------------------------*/ // setup function void getNextSetup() { if (CurrentBar < 9) { return; } /* ---------- BUY SETUP PHASE ---------------------------------------------- */ // search for a buy setup as long as the bars found are less than 9 if (bSetupCounter < 9) { // if we have a setup evolving and the current bar doesnt meet the condtion then reset counter and delete previously drawn texts if (bSetupCounter >= 1 && (Close[0] < Close[4] != true)) { // delete unfinished setup for (int i = 1; i <= bSetupCounter; i++) { // CANCELED // dont draw since its a combo and I always combine sequential with combo // CANCELED DrawText("B" + (bSC - (i - 1)), true, "", bSetupBarsTime[i], Low[bSetupBarsTime[i]], -nFont.Height, Color.Black, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); DrawText("B" + (bSC - (i - 1)), true, "", 0, 0, -nFont.Height, Color.Black, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } bSetupCounter = 0; //reset counter } // ensures that the first bar of the setup has got a price flip if (bSetupCounter == 0 && Close[0] < Close[4] && Close[1] > Close[5]) { bSetupCounter++; // counter from 1 to 9 bSC++; // counter for the unique name of the tags buySetupLowsArr[bSetupCounter] = Low[0]; // save the current low into the buy setup array bSetupBarsTime[bSetupCounter] = CurrentBar - Bars.GetBar(Time[0]); // we have a setup evolving get the current bar index based on time // Draw the numbers based on the buy setup counter // CANCELED // dont draw since its a combo and I always combine sequential with combo // CANCELED DrawText("B" + bSC, true, "" + bSetupCounter, 0, Low[0], -nFont.Height, Color.Aqua, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); // else if the counter is above 0 then continue with ordinary conditions } else { if (bSetupCounter >= 1) { // check if we have a bar meets the condition to add to the buy setup if (Close[0] < Close[4]) { bSetupCounter++; // counter from 1 to 9 bSC++; // counter for the unique name of the tags buySetupLowsArr[bSetupCounter] = Low[0]; // save the current low into the buy setup array bSetupBarsTime[bSetupCounter] = CurrentBar - Bars.GetBar(Time[0]); // we have a setup evolving get the current bar index based on time // Draw the numbers based on the buy setup counter // CANCELED // dont draw since its a combo and I always combine sequential with combo DrawText("B" + bSC, true, "" + bSetupCounter, 0, Low[0], -nFont.Height, Color.Aqua, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } } } // if we have a finished buy setup and buy count down is already started but not yet finished and countdown cancellation qualifier I or II is active then reset the count down //if(bSetupCounter==9 && isBuyCountDownStarted == true ){ if ((bSetupCounter == 9 && isBuyCountDownStarted == true) && (((getSetupRange("b") >= lastBuySetupRange) && (getSetupRange("b") / lastBuySetupRange <= 1.618) || getSetupHighLow("h") <= pBuySetupThigh && getSetupHighLow("l") >= pBuySetupTlow))) { //delete the previusly drawn buy count down for (int i = 1; i <= bCountDownCounter; i++) { DrawText("Bc" + (bCDC - (i - 1)), true, "", 0, bCDBarsLows[i], -nFont.Height * 2, Color.Black, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } bCountDownCounter = 0; // reset the sell countdown counter deleteBCTDRiskArrays(); // delete the buy countdown Td Risk Level Arraylists } // if we have a finished buy setup and sell count down is already started but not yet finished then reset the sell count down // and delete the previusly drawn sell count down if (bSetupCounter == 9 && isSellCountDownStarted == true) { //delete the previusly drawn count down for (int i = 1; i <= sCountDownCounter; i++) { DrawText("Sc" + (sCDC - (i - 1)), true, "", 0, 0, nFont.Height * 2, Color.Black, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } isSellSetup = false; // this stops the sell countdown from continueing isSellCountDownStarted = false; // SEEMS USELESS sCountDownCounter = 0; // reset the sell countdown counter deleteSCTDRiskArrays(); // delete the buy countdown Td Risk Level Arraylists } // if we have a finished buy setup then reset the counter if (bSetupCounter == 9) { bSetupCounter = 0; // reset the counter isBuySetup = true; // turn on th buysetup switch so countdown can begin bSetupArrow = false; // set to false to searh for a perfected buy setup(Up Arrow) again starting from this recent finished setup // CANCELED // dont draw since its a combo and I always combine sequential with combo drawBuyTDST(); // draw the Buy TDST drawBuyTDRisk(); // draw the TD buy Risk level lastBuySetupRange = getSetupRange("b"); // save the current setup range into the lastBuySetupRange variable //isBearishFlip = false; } } /* ----------------------------------------------------------------------------------*/ /*---------------SELL SETUP PHASE ---------------------------------------------------*/ // search for a sell setup as long as the bars found are less than 9 if (sSetupCounter < 9) { // if we have a setup evolving and the current bar doesnt meet the condtion then reset counter and delete previously drawn texts if (sSetupCounter >= 1 && (Close[0] > Close[4] != true)) { // delete unfinished setup for (int i = 1; i <= sSetupCounter; i++) { DrawText("S" + (sSC - (i - 1)), true, "", sSetupBarsTime[i], High[sSetupBarsTime[i]], +nFont.Height, Color.Black, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } sSetupCounter = 0; //reset counter } // ensures that the first bar of the setup has got a price flip if (sSetupCounter == 0 && Close[0] > Close[4] && Close[1] < Close[5]) { sSetupCounter++; // counter from 1 to 9 sSC++; // counter for the unique name of the tags sellSetupHighsArr[sSetupCounter] = High[0]; // save the current low into the buy setup array sSetupBarsTime[sSetupCounter] = CurrentBar - Bars.GetBar(Time[0]); // we have a setup evolving get the current bar index based on time // Draw the numbers based on the sell setup counter // CANCELED // dont draw since its a combo and I always combine sequential with combo DrawText("S" + sSC, true, "" + sSetupCounter, 0, High[0], +nFont.Height, Color.Aqua, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); // else if the counter is above 0 then continue with ordinary conditions } else { if (sSetupCounter >= 1) { // check if we have a bar meets the condition to add to the sell setup if (Close[0] > Close[4]) { sSetupCounter++; // counter from 1 to 9 sSC++; // counter for the unique name of the tags sellSetupHighsArr[sSetupCounter] = High[0]; // save the current low into the buy setup array sSetupBarsTime[sSetupCounter] = CurrentBar - Bars.GetBar(Time[0]); // we have a setup evolving get the current bar index based on time // Draw the numbers based on the sell setup counter // CANCELED // dont draw since its a combo and I always combine sequential with combo DrawText("S" + sSC, true, "" + sSetupCounter, 0, High[0], +nFont.Height, Color.Aqua, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } } } // if we have a finished sell setup and a sell count down is already started but not yet finished and countdown cancellation qualifier I or II is active, then reset the count down //if(sSetupCounter==9 && isSellCountDownStarted == true ){ if ((sSetupCounter == 9 && isSellCountDownStarted == true) && (((getSetupRange("s") >= lastSellSetupRange) && (getSetupRange("s") / lastSellSetupRange <= 1.618)) || (getSetupHighLow("h") <= pSellSetupThigh && getSetupHighLow("l") >= pSellSetupTlow))) { //delete the previusly drawn sell count down for (int i = 1; i <= sCountDownCounter; i++) { DrawText("Sc" + (sCDC - (i - 1)), true, "", 0, 0, nFont.Height * 2, Color.Black, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } sCountDownCounter = 0; // reset the sell countdown counter deleteSCTDRiskArrays(); // delete the sell countdown Td Risk Level Arraylists } // if we have a finished sell setup and buy count down is already started but not yet finished then reset the buy count down // and delete the previusly drawn buy count down if (sSetupCounter == 9 && isBuyCountDownStarted == true) { //delete the previusly drawn count down for (int i = 1; i <= bCountDownCounter; i++) { DrawText("Bc" + (bCDC - (i - 1)), true, "", 0, 0, -nFont.Height * 2, Color.Black, nFont, StringAlignment.Center, Color.Black, Color.Black, 10); } isBuySetup = false; // this stops the sell countdown from continueing isBuyCountDownStarted = false; // SEEMS USELESS bCountDownCounter = 0; // reset the sell countdown counter deleteBCTDRiskArrays(); // delete the buy countdown Td Risk Level Arraylists } // if we have a finished sell setup then reset the counter if (sSetupCounter == 9) { sSetupCounter = 0; // reset the counter isSellSetup = true; // turn on th sellsetup switch so countdown can begin sSetupArrow = false; // set to false to searh for a perfected sell setup(Down Arrow) again starting from this recent finished setup // CANCELED // dont draw since its a combo and I always combine sequential with combo drawSellTDST(); // draw the Sell TDST drawSellTDRisk(); // Draw sell TD Risk level lastSellSetupRange = getSetupRange("s"); // save the current setup range into the lastBuySetupRange variable } } /* ------------------------------------------------------------------------*/ }
/// <summary> /// </summary> /// <param name="graphics"></param> /// <param name="bounds"></param> /// <param name="min"></param> /// <param name="max"></param> public override void Plot(Graphics graphics, Rectangle bounds, double min, double max) { if (Bars == null || ChartControl == null) { return; } // plot error if data not complete if (textBrush.Color != ChartControl.AxisColor || textFont != ChartControl.Font) { textBrush.Color = ChartControl.AxisColor; textFont = ChartControl.Font; SizeF errorSize = graphics.MeasureString(errorData, textFont); errorTextWidth = errorSize.Width + 5; errorTextHeight = errorSize.Height + 5; } if (priorDayHLC == HLCCalculationMode.CalcFromIntradayData) { DateTime lastBarDate = (Bars.Count == 0) ? Cbi.Globals.MaxDate : ChartControl.EquidistantBars ? Bars.GetTime(Math.Min(Bars.Count - 1, ChartControl.LastBarPainted)).Date : Bars.GetTime(Math.Min(Bars.Count - 1, Bars.GetBar(ChartControl.LastBarTimePainted))).Date; if ((lastBarDate == Cbi.Globals.MaxDate) || (Bars.BarsType.BuiltFrom == PeriodType.Minute && ((pivotRangeType == PivotRange.Monthly && Bars.Count > 0 && Bars.GetTime(0).AddSeconds(-1).Date >= new DateTime(lastBarDate.Year, lastBarDate.Month, 1).AddMonths(-1)) || (pivotRangeType == PivotRange.Weekly && Bars.Count > 0 && Bars.GetTime(0).AddSeconds(-1).Date >= lastBarDate.AddDays(-(((int)lastBarDate.DayOfWeek) + 1) % 7).AddDays(-7)) || (pivotRangeType == PivotRange.Daily && Bars.Count > 0 && Bars.GetTime(0).AddSeconds(-1).Date >= lastBarDate.AddDays(-1)))) || (Bars.BarsType.BuiltFrom != PeriodType.Minute && ((pivotRangeType == PivotRange.Monthly && Bars.Count > 0 && Bars.GetTime(0).Date >= new DateTime(lastBarDate.Year, lastBarDate.Month, 1).AddMonths(-1)) || (pivotRangeType == PivotRange.Weekly && Bars.Count > 0 && Bars.GetTime(0).Date >= lastBarDate.AddDays(-(((int)lastBarDate.DayOfWeek) + 1) % 7).AddDays(-7)) || (pivotRangeType == PivotRange.Daily && Bars.Count > 0 && Bars.GetTime(0).Date >= lastBarDate.AddDays(-1))))) { graphics.DrawString(errorData, ChartControl.Font, textBrush, bounds.X + bounds.Width - errorTextWidth, bounds.Y + bounds.Height - errorTextHeight, stringFormatNear); } } else if (priorDayHLC == HLCCalculationMode.DailyBars && existsHistDailyData) { DateTime lastBarDate = (dailyBars.Count == 0) ? Cbi.Globals.MaxDate : ChartControl.EquidistantBars ? dailyBars.GetTime(Math.Min(dailyBars.Count - 1, ChartControl.LastBarPainted)).Date : dailyBars.GetTime(Math.Min(dailyBars.Count - 1, dailyBars.GetBar(ChartControl.LastBarTimePainted))).Date; if ((lastBarDate == Cbi.Globals.MaxDate) || (pivotRangeType == PivotRange.Monthly && dailyBars.GetTime(0).Date >= new DateTime(lastBarDate.Year, lastBarDate.Month, 1).AddMonths(-1)) || (pivotRangeType == PivotRange.Weekly && dailyBars.GetTime(0).Date >= lastBarDate.AddDays(-(((int)lastBarDate.DayOfWeek) + 1) % 7).AddDays(-7)) || (pivotRangeType == PivotRange.Daily && dailyBars.GetTime(0).Date >= lastBarDate.AddDays(-1))) { graphics.DrawString(errorData, ChartControl.Font, textBrush, bounds.X + bounds.Width - errorTextWidth, bounds.Y + bounds.Height - errorTextHeight, stringFormatNear); } } float textHeight = ChartControl.Font.GetHeight(); for (int seriesCount = 0; seriesCount < Values.Length; seriesCount++) { SolidBrush brush = brushes[seriesCount]; int firstBarIdxToPaint = -1; int lastX = -1; int lastY = -1; SmoothingMode oldSmoothingMode = graphics.SmoothingMode; Gui.Chart.Plot plot = Plots[seriesCount]; DataSeries series = (DataSeries)Values[seriesCount]; for (int i = newSessionBarIdxArr.Count - 1; i >= 0; i--) { int prevSessionBreakIdx = (int)newSessionBarIdxArr[i]; if (prevSessionBreakIdx <= this.LastBarIndexPainted) { firstBarIdxToPaint = prevSessionBreakIdx; break; } } using (GraphicsPath path = new GraphicsPath()) { if (brush.Color != plot.Pen.Color) { brush = new SolidBrush(plot.Pen.Color); } for (int idx = this.LastBarIndexPainted; idx >= Math.Max(this.FirstBarIndexPainted, this.LastBarIndexPainted - Width); idx--) { if (idx - Displacement < 0 || idx - Displacement >= Bars.Count || (!ChartControl.ShowBarsRequired && idx - Displacement < BarsRequired)) { continue; } else if (!series.IsValidPlot(idx)) { continue; } if (idx < firstBarIdxToPaint) { break; } double val = series.Get(idx); int x = ChartControl.GetXByBarIdx(BarsArray[0], idx); int y = ChartControl.GetYByValue(this, val); if (lastX >= 0) { if (y != lastY) // Problem here is, that last bar of old day has date of new day { y = lastY; } path.AddLine(lastX - plot.Pen.Width / 2, lastY, x - plot.Pen.Width / 2, y); } lastX = x; lastY = y; } graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.DrawPath(plot.Pen, path); graphics.SmoothingMode = oldSmoothingMode; graphics.DrawString(plot.Name, ChartControl.Font, brush, lastX, lastY - textHeight / 2, stringFormatFar); } } }
/// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { if (Bars == null) { return; } if (!Bars.BarsType.IsIntraday && Bars.Period.Id != PeriodType.Day) { return; } if (Bars.Period.Id == PeriodType.Day && pivotRangeType == PivotRange.Daily) { return; } if (Bars.Period.Id == PeriodType.Day && Bars.Period.Value > 1) { return; } // pivots only work for // - intraday // - 1 day chart with PivotRange Weekly or Monthly if (!isDailyDataLoaded) { if (priorDayHLC == HLCCalculationMode.DailyBars && Bars.BarsType.IsIntraday) { Enabled = false; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(GetBarsNow)); return; } existsHistDailyData = false; isDailyDataLoaded = true; } IBar dailyBar; if (existsHistDailyData) { sessionDateDaily = GetLastBarSessionDate(Time[0], Bars, PivotRange.Daily); dailyBar = dailyBars.Get(dailyBars.GetBar(sessionDateDaily)); if (dailyBar.Time.Date > sessionDateDaily.Date) { for (DateTime i = sessionDateDaily; i >= dailyBars.GetTime(0); i = i.AddDays(-1)) { dailyBar = dailyBars.Get(dailyBars.GetBar(i)); if (dailyBar.Time.Date == i.Date) { break; } } } } else { dailyBar = null; } double high = existsHistDailyData ? dailyBar.High : High[0]; double low = existsHistDailyData ? dailyBar.Low : Low[0]; double close = existsHistDailyData ? dailyBar.Close : Close[0]; DateTime lastBarTimeStamp = GetLastBarSessionDate(Time[0], Bars, pivotRangeType); if ((currentDate != Cbi.Globals.MinDate && pivotRangeType == PivotRange.Daily && lastBarTimeStamp != currentDate) || (currentWeek != Cbi.Globals.MinDate && pivotRangeType == PivotRange.Weekly && lastBarTimeStamp != currentWeek) || (currentMonth != Cbi.Globals.MinDate && pivotRangeType == PivotRange.Monthly && lastBarTimeStamp != currentMonth)) { pp = (currentHigh + currentLow + currentClose) / 3; s1 = 2 * pp - currentHigh; r1 = 2 * pp - currentLow; s2 = pp - (currentHigh - currentLow); r2 = pp + (currentHigh - currentLow); s3 = pp - 2 * (currentHigh - currentLow); r3 = pp + 2 * (currentHigh - currentLow); ppr1 = (pp + r1) / 2; pps1 = (pp + s1) / 2; r1r2 = (r1 + r2) / 2; s1s2 = (s1 + s2) / 2; r2r3 = (r2 + r3) / 2; s2s3 = (s2 + s3) / 2; currentClose = (priorDayHLC == HLCCalculationMode.UserDefinedValues) ? userDefinedClose : close; currentHigh = (priorDayHLC == HLCCalculationMode.UserDefinedValues) ? userDefinedHigh : high; currentLow = (priorDayHLC == HLCCalculationMode.UserDefinedValues) ? userDefinedLow : low; } else { currentClose = (priorDayHLC == HLCCalculationMode.UserDefinedValues) ? userDefinedClose : close; currentHigh = (priorDayHLC == HLCCalculationMode.UserDefinedValues) ? userDefinedHigh : Math.Max(currentHigh, high); currentLow = (priorDayHLC == HLCCalculationMode.UserDefinedValues) ? userDefinedLow : Math.Min(currentLow, low); } if (pivotRangeType == PivotRange.Daily) { currentDate = lastBarTimeStamp; } if (pivotRangeType == PivotRange.Weekly) { currentWeek = lastBarTimeStamp; } if (pivotRangeType == PivotRange.Monthly) { currentMonth = lastBarTimeStamp; } if ((pivotRangeType == PivotRange.Daily && currentDate != Cbi.Globals.MinDate) || (pivotRangeType == PivotRange.Weekly && currentWeek != Cbi.Globals.MinDate) || (pivotRangeType == PivotRange.Monthly && currentMonth != Cbi.Globals.MinDate)) { PP.Set(pp); R1.Set(r1); S1.Set(s1); R2.Set(r2); S2.Set(s2); R3.Set(r3); S3.Set(s3); // PPR1.Set(ppr1); // PPS1.Set(pps1); // R1R2.Set(r1r2); // S1S2.Set(s1s2); // R2R3.Set(r2r3); // S2S3.Set(s2s3); } }
public int GetBarNoByDateTime(DateTime dt) { return(Bars.GetBar(dt)); }
protected override void OnBarUpdate() { if (CurrentBars[0] < 121) { return; } if (Bars == null) { return; } if (!Data.BarsType.GetInstance(Bars.Period.Id).IsIntraday) { return; } if (Bars.Period.Id == PeriodType.Minute && Bars.Period.Value > minutes / 2) { return; } if (!isLoaded && !isInit) { isInit = true; hourlyBars = Data.Bars.GetBars(Bars.Instrument, new Period(PeriodType.Minute, minutes, MarketDataType.Last), Bars.From, Bars.To, (Session)Bars.Session.Clone(), Data.Bars.SplitAdjust, Data.Bars.DividendAdjust); existsHistHourlyData = (hourlyBars.Count <= 1) ? false : true; isInit = false; isLoaded = true; } IBar hourlyBar; if (CurrentBar == 0) { return; } if (existsHistHourlyData) { DateTime intradayBarTime = Time[0].AddMinutes(-minutes); hourlyBar = hourlyBars.Get(hourlyBars.GetBar(intradayBarTime)); double high = hourlyBar.High; double low = hourlyBar.Low; double close = hourlyBar.Close; HPP.Set((high + low + close) / 3); if (HPP[0] != HPP[1]) { DrawRay("pp", true, 1, HPP[0], 0, HPP[0], Plots[0].Pen.Color, Plots[0].Pen.DashStyle, (int)Plots[0].Pen.Width); } HS1.Set(2 * HPP[0] - high); if (HS1[0] != HS1[1]) { DrawRay("hs1", true, 1, HS1[0], 0, HS1[0], Plots[1].Pen.Color, Plots[1].Pen.DashStyle, (int)Plots[1].Pen.Width); } HR1.Set(2 * HPP[0] - low); if (HR1[0] != HR1[1]) { DrawRay("hr1", true, 1, HR1[0], 0, HR1[0], Plots[4].Pen.Color, Plots[4].Pen.DashStyle, (int)Plots[4].Pen.Width); } HS2.Set(HPP[0] - (high - low)); if (HS2[0] != HS2[1]) { DrawRay("hs2", true, 1, HS2[0], 0, HS2[0], Plots[2].Pen.Color, Plots[2].Pen.DashStyle, (int)Plots[2].Pen.Width); } HR2.Set(HPP[0] + (high - low)); if (HR2[0] != HR2[1]) { DrawRay("hr2", true, 1, HR2[0], 0, HR2[0], Plots[5].Pen.Color, Plots[5].Pen.DashStyle, (int)Plots[5].Pen.Width); } HS3.Set(HS2[0] - (high - low)); if (HS3[0] != HS3[1]) { DrawRay("hs3", true, 1, HS2[0], 0, HS2[0], Plots[3].Pen.Color, Plots[3].Pen.DashStyle, (int)Plots[3].Pen.Width); } HR3.Set(HR1[0] + (high - low)); if (HR3[0] != HR3[1]) { DrawRay("hr3", true, 1, HR2[0], 0, HR2[0], Plots[6].Pen.Color, Plots[6].Pen.DashStyle, (int)Plots[6].Pen.Width); } } else { return; } }
/// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { //If we are not processing the current bar, return if (CurrentBar != Bars.GetBar(DateTime.Now)) { return; } //Get current bid double bid = Bars.GetClose(Bars.GetBar(DateTime.Now)); if (previous_bid < 0) { previous_bid = bid; } IDrawObject drawing_object = DrawObjects[trendLineTag]; //Reset if drawing object is deleted or does not exist... if (drawing_object == null) { Type = null; AlertDone = false; } if (drawing_object != null && (drawing_object.DrawType == DrawType.Ray || drawing_object.DrawType == DrawType.ExtendedLine || drawing_object.DrawType == DrawType.Line)) { double y1, y2; int bar1, bar2; DateTime time1, time2; if (drawing_object.DrawType == DrawType.Ray) { IRay ray = (IRay)drawing_object; y1 = ray.Anchor1Y; y2 = ray.Anchor2Y; time1 = ray.Anchor1Time; time2 = ray.Anchor2Time; bar1 = ray.Anchor1BarsAgo; bar2 = ray.Anchor2BarsAgo; } else if (drawing_object.DrawType == DrawType.ExtendedLine) { IExtendedLine line = (IExtendedLine)drawing_object; y1 = line.StartY; y2 = line.EndY; time1 = line.StartTime; time2 = line.EndTime; bar1 = line.StartBarsAgo; bar2 = line.EndBarsAgo; } else { ILine line = (ILine)drawing_object; y1 = line.StartY; y2 = line.EndY; time1 = line.StartTime; time2 = line.EndTime; bar1 = line.StartBarsAgo; bar2 = line.EndBarsAgo; } //Reset alert if object has moved if ((time1 != this.sTime1 || time2 != this.sTime2 || y1 != this.sY1 || y2 != this.sY2) && this.sTime1 != null && this.sTime2 != null) { Type = null; AlertDone = false; } if (AlertDone == false) { //Store anchor to detect if object has moved this.sTime1 = time1; this.sTime2 = time2; this.sY1 = y1; this.sY2 = y2; //Calculate price target double y = y2 - y1; double x = bar1 - bar2; double slope = y / x; double deltaY = bar2 * slope; //time difference in ticks * slope double price_target = Math.Round(y2 + deltaY, 5); //IF price is below current price target or straddles it, THEN we alert when the bid>=price_target if (Type == null && (price_target - previous_bid) >= 0) { Type = "up"; } if (Type == null && (previous_bid - price_target) >= 0) { Type = "down"; } previous_bid = bid; if (Type == "up" && bid >= price_target) { Alert("TrendLineAlert", NinjaTrader.Cbi.Priority.High, "Reached Trend Line @ " + price_target, AlertSound, 10, Color.Black, Color.Yellow); AlertDone = true; } if (Type == "down" && bid <= price_target) { Alert("TrendLineAlert", NinjaTrader.Cbi.Priority.High, "Reached Trend Line @ " + price_target, AlertSound, 10, Color.Black, Color.Yellow); AlertDone = true; } } } }
// Override OnBarUpdate method protected override void OnBarUpdate() { // Protect against too few bars if (Bars == null) { return; } if (!Data.BarsType.GetInstance(Bars.Period.Id).IsIntraday) { return; } if (Bars.Period.Id == PeriodType.Minute && Bars.Period.Value > timeFrame / 2) { return; } if (!full && !apt) { apt = true; periodBars = Data.Bars.GetBars(Bars.Instrument, new Period(PeriodType.Minute, timeFrame, MarketDataType.Last), Bars.From, Bars.To, (Session)Bars.Session.Clone(), Data.Bars.SplitAdjust, Data.Bars.DividendAdjust); apt = false; full = true; } // Remove calculation for first time span after open IBar periodBar; Bars.Session.GetNextBeginEnd(Time[0], out sessionBegin, out sessionEnd); if (Time[0] >= sessionBegin && Time[0] <= sessionBegin.AddMinutes(timeFrame)) { Pivot.Reset(); Resistance1.Reset(); Support1.Reset(); Resistance2.Reset(); Support2.Reset(); Resistance3.Reset(); Support3.Reset(); Resistance4.Reset(); Support4.Reset(); Resistance5.Reset(); Support5.Reset(); } else { // Determine open, high, low, and close DateTime intradayBarTime = Time[0].AddMinutes(-timeFrame); periodBar = periodBars.Get(periodBars.GetBar(intradayBarTime)); double Open = periodBar.Open; double High = periodBar.High; double Low = periodBar.Low; double Close = periodBar.Close; double pivot = periodBar.Close; // Switch central pivot calculation switch (centralPivotCalculation) { // Standard calculation case case CentralPivotCalculation.Standard: { pivot = (High + Low + Close) / 3; break; } // Open included calculation case case CentralPivotCalculation.OpenIncluded: { pivot = (Open + High + Low + Close) / 4; break; } // Close weighted calculation case case CentralPivotCalculation.CloseWeighted: { pivot = (High + Low + Close + Close) / 4; break; } // High weighted calculation case case CentralPivotCalculation.HighWeighted: { pivot = (High + High + Low + Close) / 4; break; } // Low weighted calculation case case CentralPivotCalculation.LowWeighted: { pivot = (High + Low + Low + Close) / 4; break; } } // Switch round to tick option switch (roundToTick) { // Rounding case case RoundToTick.Yes: { // Set all additional pivots, rounded Pivot.Set(Instrument.MasterInstrument.Round2TickSize(pivot)); Resistance1.Set(Instrument.MasterInstrument.Round2TickSize(2 * Pivot[0] - Low)); Support1.Set(Instrument.MasterInstrument.Round2TickSize(2 * Pivot[0] - High)); Resistance2.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] + (High - Low))); Support2.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] - (High - Low))); Resistance3.Set(Instrument.MasterInstrument.Round2TickSize(High + 2 * (Pivot[0] - Low))); Support3.Set(Instrument.MasterInstrument.Round2TickSize(Low - 2 * (High - Pivot[0]))); Resistance4.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] + 2 * (High - Low))); Support4.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] - 2 * (High - Low))); Resistance5.Set(Instrument.MasterInstrument.Round2TickSize(2 * (Pivot[0] + High) - 3 * Low)); Support5.Set(Instrument.MasterInstrument.Round2TickSize(2 * (Pivot[0] + Low) - 3 * High)); break; } // No rounding case case RoundToTick.No: { // Set all additional pivots, not rounded Pivot.Set(pivot); Resistance1.Set(2 * Pivot[0] - Low); Support1.Set(2 * Pivot[0] - High); Resistance2.Set(Pivot[0] + (High - Low)); Support2.Set(Pivot[0] - (High - Low)); Resistance3.Set(High + 2 * (Pivot[0] - Low)); Support3.Set(Low - 2 * (High - Pivot[0])); Resistance4.Set(Pivot[0] + 2 * (High - Low)); Support4.Set(Pivot[0] - 2 * (High - Low)); Resistance5.Set(2 * (Pivot[0] + High) - 3 * Low); Support5.Set(2 * (Pivot[0] + Low) - 3 * High); break; } } } }