private DateTime TimeToBarTimeMinute(Bars bars, DateTime time, bool isBar) { if (SessionIterator.IsNewSession(time, isBar)) { SessionIterator.GetNextSession(time, isBar); } if (bars.IsResetOnNewTradingDay || !bars.IsResetOnNewTradingDay && bars.Count == 0) { DateTime barTimeStamp = isBar ? SessionIterator.ActualSessionBegin.AddMinutes(Math.Ceiling(Math.Ceiling(Math.Max(0, time.Subtract(SessionIterator.ActualSessionBegin).TotalMinutes)) / bars.BarsPeriod.BaseBarsPeriodValue) * bars.BarsPeriod.BaseBarsPeriodValue) : SessionIterator.ActualSessionBegin.AddMinutes(bars.BarsPeriod.BaseBarsPeriodValue + Math.Floor(Math.Floor(Math.Max(0, time.Subtract(SessionIterator.ActualSessionBegin).TotalMinutes)) / bars.BarsPeriod.BaseBarsPeriodValue) * bars.BarsPeriod.BaseBarsPeriodValue); if (bars.TradingHours.Sessions.Count > 0 && barTimeStamp > SessionIterator.ActualSessionEnd) // Cut last bar in session down to session end on odd session end time { barTimeStamp = SessionIterator.ActualSessionEnd; } return(barTimeStamp); } else { DateTime lastBarTime = bars.GetTime(bars.Count - 1); DateTime barTimeStamp = isBar ? lastBarTime.AddMinutes(Math.Ceiling(Math.Ceiling(Math.Max(0, time.Subtract(lastBarTime).TotalMinutes)) / bars.BarsPeriod.BaseBarsPeriodValue) * bars.BarsPeriod.BaseBarsPeriodValue) : lastBarTime.AddMinutes(bars.BarsPeriod.BaseBarsPeriodValue + Math.Floor(Math.Floor(Math.Max(0, time.Subtract(lastBarTime).TotalMinutes)) / bars.BarsPeriod.BaseBarsPeriodValue) * bars.BarsPeriod.BaseBarsPeriodValue); if (bars.TradingHours.Sessions.Count > 0 && barTimeStamp > SessionIterator.ActualSessionEnd) { DateTime saveActualSessionEnd = SessionIterator.ActualSessionEnd; SessionIterator.GetNextSession(SessionIterator.ActualSessionEnd.AddSeconds(1), isBar); barTimeStamp = SessionIterator.ActualSessionBegin.AddMinutes((int)barTimeStamp.Subtract(saveActualSessionEnd).TotalMinutes); } return(barTimeStamp); } }
public static void DrawVerticalLineBlinking(NinjaTrader.NinjaScript.NinjaScriptBase indi_or_strat, int idx) { try{ int rand = new Random().Next(100000); RemoveDrawObject(indi_or_strat, "Debugger_CurrentBarVLine" + randLast); int clicked_Bar = indi_or_strat.CurrentBars[0] - idx + (indi_or_strat.BarsPeriod.BarsPeriodType == BarsPeriodType.Day ? 1 : 0); //don't know, on daily was displaced Bars bars = indi_or_strat.BarsArray[0]; if (clicked_Bar + 1 >= indi_or_strat.Bars.Count) { return; //I donno, I couldn't make it work on last bar, so just hide it } //NinjaTrader.NinjaScript.DrawingTools.Draw.VerticalLine(indi_or_strat, "Debugger_CurrentBarVLine"+rand, idx, Brushes.Orange, DashStyleHelper.DashDot, 2); var time = bars.GetTime(clicked_Bar).AddSeconds(-ChartInSeconds(indi_or_strat) / 6); NinjaTrader.NinjaScript.DrawingTools.Draw.VerticalLine(indi_or_strat, "Debugger_CurrentBarVLine" + rand, time, Brushes.Orange, DashStyleHelper.DashDot, 2); // in 5 seconds, remove it System.Threading.Timer timer = null; timer = new System.Threading.Timer( (object state) => { RemoveDrawObject(indi_or_strat, "Debugger_CurrentBarVLine" + rand); timer.Dispose(); } , null // no state required , TimeSpan.FromSeconds(5) // Do it in x seconds , TimeSpan.FromMilliseconds(-1) ); // don't repeat randLast = rand; } catch (Exception ex) { indi_or_strat.Print(ex.ToString()); } }
protected override void OnBarUpdate() { if (CurrentBar < 0) { return; } if (IsFirstTickOfBar) { if (CurrentBar == (Count - 2)) { System.Windows.Forms.MessageBox.Show("My message here"); } DateTime timeValue = Bars.GetTime(CurrentBar); string xCB = CurrentBar.ToString(); if (CurrentBar % 2 == 0) { Draw.Text(this, "Even " + xCB, xCB, 0, High[0] + iOffset); } else { Draw.Text(this, "Odd " + xCB, xCB, 0, Low[0] - iOffset); } } }
//grafische Darstellung Einstieg Short private void PrepareTradeShort() { string strArrowDown = "ArrowDown" + Bars.GetTime(ProcessingBarIndex); AddChartArrowDown(strArrowDown, true, Bars.GetTime(Count - 1), Bars.GetOpen(ProcessingBarIndex) + 100 * TickSize, Color.Red); GapTradeShort = true; }
//grafische Darstellung Einstieg Long private void PrepareTradeLong() { string strArrowUp = "ArrowUp" + Bars.GetTime(ProcessingBarIndex); AddChartArrowUp(strArrowUp, true, Bars.GetTime(Count - 1), Bars.GetOpen(ProcessingBarIndex) - 100 * TickSize, Color.Green); GapTradeLong = true; }
private void HandleProfitChasing() { if (PosFlat()) { // this is not possible Debug.Assert(!PosFlat(), "ASSERT: Position is flat while HandleProfitChasing"); return; } // if market trend go against profit positions, then flatten position and take profits if (PosLong()) { if (Close[0] < chasePrice) { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " HandleProfitChasing::" + " currPos=" + currPos.ToString() + " closedPrice=" + closedPrice.ToString() + " Close[0]=" + Close[0].ToString() + " chasePrice=" + chasePrice.ToString() + " closedPrice + profitChasing=" + (closedPrice + profitChasing * TickSize).ToString() + " Profits=" + (Close[0] - closedPrice).ToString()); AiFlat(); } else { chasePrice = Close[0]; } } if (PosShort()) { if (Close[0] > chasePrice) { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " HandleProfitChasing::" + " currPos=" + currPos.ToString() + " closedPrice=" + closedPrice.ToString() + " Close[0]=" + Close[0].ToString() + " chasePrice=" + chasePrice.ToString() + " closedPrice - profitChasing=" + (closedPrice - profitChasing * TickSize).ToString() + " Profits=" + (closedPrice - Close[0]).ToString()); AiFlat(); } else { chasePrice = Close[0]; } } }
private bool TouchedProfitChasing() { profitChasingFlag = false; if (PosLong()) { if (Close[0] >= (closedPrice + profitChasing * TickSize)) { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " TouchedProfitChasing"); profitChasingFlag = true; chasePrice = Close[0]; return(profitChasingFlag); } } if (PosShort()) { if (Close[0] <= (closedPrice - profitChasing * TickSize)) { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " TouchedProfitChasing"); profitChasingFlag = true; chasePrice = Close[0]; return(profitChasingFlag); } } return(profitChasingFlag); }
protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError) { // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order. // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected. // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not gauranteed to be complete if it is referenced immediately after submitting if (order.Name == "Long" || order.Name == "Short") { entryOrder = order; if (order.Filled == 1) { closedPrice = order.AverageFillPrice; if (order.Name == "Long") { currPos = Position.posLong; } if (order.Name == "Short") { currPos = Position.posShort; } Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " *********Order filed, order name=" + order.Name + " currPos=" + currPos.ToString()); } // Reset the entryOrder object to null if order was cancelled without any fill if (order.OrderState == OrderState.Cancelled && order.Filled == 0) { entryOrder = null; sumFilled = 0; } } }
private void HandleSoftDeck(string signal) { if (PosFlat()) { // this is not possible Debug.Assert(!PosFlat(), "ASSERT: Position is flat while HandleSoftDeck"); return; } // if there is an existing position, handle them in the tick by tick section of the OnBarUpdate() if (PosLong()) { if (signal != "2") { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " HandleSoftDeck:: signal= " + signal.ToString() + " current price=" + Close[0] + " closedPrice=" + closedPrice.ToString() + " soft deck=" + (softDeck * TickSize).ToString()); AiFlat(); } return; } if (PosShort()) { if (signal != "0") { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " HandleSoftDeck:: signal= " + signal.ToString() + " current price=" + Close[0] + " closedPrice=" + closedPrice.ToString() + " soft deck=" + (softDeck * TickSize).ToString()); AiFlat(); } return; } }
//grafische Darstellung Einstieg Long private void PrepareTradeLong() { string strArrowUp = "ArrowUp" + Bars.GetTime(CurrentBar); DrawArrowUp(strArrowUp, true, Bars.GetTime(Count - 1), Bars.GetOpen(CurrentBar) - 100 * TickSize, Color.Green); GapTradeLong = true; }
//grafische Darstellung Einstieg Short private void PrepareTradeShort() { string strArrowDown = "ArrowDown" + Bars.GetTime(CurrentBar); DrawArrowDown(strArrowDown, true, Bars.GetTime(Count - 1), Bars.GetOpen(CurrentBar) + 100 * TickSize, Color.Red); GapTradeShort = true; }
public override void Plot(Graphics graphics, Rectangle bounds, double min, double max) { if (Bars == null) { return; } // Recalculate the proper string size should the chart control object font and axis color change if (textBrush.Color != ChartControl.AxisColor || textFont != ChartControl.Font) { textBrush.Color = ChartControl.AxisColor; textFont = (Font)ChartControl.Font.Clone(); SizeF size = graphics.MeasureString("Time remaining = -00:-00:-00", textFont); textWidth = size.Width + 5; textHeight = size.Height + 5; SizeF noTickSize = graphics.MeasureString(errorIntraday, textFont); noTickTextWidth = noTickSize.Width + 5; noTickTextHeight = noTickSize.Height + 5; SizeF noConSize = graphics.MeasureString(errorDisabled, textFont); noConTextWidth = noConSize.Width + 5; noConTextHeight = noConSize.Height + 5; } // Plot the time remaining message to the lower right hand corner of the chart if (Bars.Period.Id == PeriodType.Minute || Bars.Period.Id == PeriodType.Second) { if (DisplayTime()) { if (timer != null && !timer.Enabled) { timer.Enabled = true; } TimeSpan barTimeLeft = Bars.GetTime(Bars.Count - 1).Subtract(Now); string timeLeft = (barTimeLeft.Ticks < 0 ? "0:00" : barTimeLeft.Minutes.ToString() + ":" + barTimeLeft.Seconds.ToString("00")); //graphics.DrawString(timeLeft, ChartControl.Font, textBrush, bounds.X + bounds.Width - textWidth, emaValue, stringFormat); //DrawText("barTimer", timeLeft, -4, emaTimerOffset, Color.Gray); DrawText("barTimer", timeLeft, -4, EMA(20)[1], Color.Gray); } else { //graphics.DrawString(errorDisabled, ChartControl.Font, textBrush, bounds.X + bounds.Width - noConTextWidth, bounds.Y + bounds.Height - noConTextHeight, stringFormat); graphics.DrawString("", ChartControl.Font, textBrush, bounds.X + bounds.Width - noConTextWidth, bounds.Y + bounds.Height - noConTextHeight, stringFormat); } } else { graphics.DrawString(errorIntraday, ChartControl.Font, textBrush, bounds.X + bounds.Width - noTickTextWidth, bounds.Y + bounds.Height - noTickTextHeight, stringFormat); if (timer != null) { timer.Enabled = false; } } }
//private void onKeyUp(object sender, KeyEventArgs e) { isKeyPressed=false; Print("keyup");} private void OnMouseDownEvent(object sender, MouseButtonEventArgs e) { if (checkForDeregister()) { return; } Point cPos = chartControl.MouseDownPoint; int posX = (int)ChartingExtensions.ConvertToHorizontalPixels(cPos.X - chartControl.BarWidthArray[0], chartControl.PresentationSource); int slot = (int)chartControl.GetSlotIndexByX(posX); //if clicked on visible if (slot >= chartBars.FromIndex && slot <= chartBars.ToIndex) { int clicked_Bar = slot; if (System.Windows.Forms.Control.ModifierKeys == Keys.Shift) //isKeyPressed { //isKeyPressed=false; destroyForm(false); createForm(); logForm.Show(); } if (logForm.Visible) { if (indi_or_strat != null) { if (indi_or_strat.BarsArray[0] != null) { Bars bars = indi_or_strat.BarsArray[0]; int barIdx = indi_or_strat.CurrentBars[0] - clicked_Bar - 1; //indi.CurrentBars[0] string bn = Library_PuvoxSoftware.Methods.barIdentifier(indi_or_strat, barIdx); string bn_prev = Library_PuvoxSoftware.Methods.barIdentifier(indi_or_strat, barIdx + 1); //IBar thebar = GetBarFromX(e.X); string primary = (primaryDict.ContainsKey(bn) ? primaryDict[bn] : ""); /* * string secondary= ( secondaryDict.ContainsKey(bn_prev) ? secondaryDict[ bn_prev ] : "" ); * string final_text = (secondary == "" ? "" : secondary + nl + "<<< BarsInProgress: 0 >>>"+ nl) + primary ; */ string warning_message = nl + "############ Warning ############" + nl + "The following BIP data is used to form the next Primary BAR." + nl + "To understand DataSeries better, read: - https://goo.gl/ScpDkN" + nl + "##############################" + nl; string secondary = (secondaryDict.ContainsKey(bn) ? warning_message + secondaryDict[bn] : ""); string final_text = primary + secondary; textarea.Text = final_text; DrawVerticalLine(bars.GetTime(clicked_Bar + 1)); } } } } }
protected override void OnBarUpdate() { // smaFast = SMA(5); // smaSlow = SMA(20); if (CurrentBar > 1) { if (Bars.GetHigh(CurrentBar) - Bars.GetHigh(CurrentBar - 1) < 0 && direction > 0) { max.Add(Bars.GetHigh(CurrentBar - 1)); maxIndex.Add(CurrentBar - 1); upperLines.Clear(); if (min.Count > 15) { min.RemoveAt(0); } if (max.Count > 15) { max.RemoveAt(0); upperTrend(); } } if (Bars.GetLow(CurrentBar) - Bars.GetLow(CurrentBar - 1) > 0 && direction < 0) { min.Add(Bars.GetLow(CurrentBar - 1)); minIndex.Add(CurrentBar - 1); } direction = Bars.GetHigh(CurrentBar) - Bars.GetHigh(CurrentBar - 1); if (max.Count > 15) { max.RemoveAt(0); maxIndex.RemoveAt(0); } PrintTo = PrintTo.OutputTab1; Print(Bars.GetTime(CurrentBar - 1) + ": " + trendState()); if (upperLines.Count > 0) { PrintTo = PrintTo.OutputTab2; Print(Bars.GetTime(CurrentBar) + ": " + upperLines[upperLines.Count - 1].slope + " " + upperLines[upperLines.Count - 1].intercept + " " + upperLines.Count + " " + upperLines[upperLines.Count - 1].tipCount); upperTest = upperLines[upperLines.Count - 1].slope * (CurrentBar - upperLines[upperLines.Count - 1].index) + upperLines[upperLines.Count - 1].intercept; // bottomTest = bottomSlope*(CurrentBar - bottomIndex) + bottomIntercept; if (Bars.GetClose(CurrentBar) > upperTest) { // stopLoss = Math.Round((upperTest - bottomTest)/0.25); //targetProfit = stopLoss*2; SetProfitTarget(CalculationMode.Ticks, 4); SetStopLoss(CalculationMode.Ticks, 4); EnterLong(3); upperLines.RemoveAt(upperLines.Count - 1); } } } }
private void plotSwings(Dictionary <int, string> reducedPivots, string prefix) { List <int> orderedMarkers = reducedPivots.Keys.ToList(); orderedMarkers.Sort(); int objnum = 0; int previousMarker = 0; double previousValue = 0; string previous = ""; foreach (int marker in orderedMarkers) { double value = 0; if (reducedPivots[marker].Equals(MIN_MAX) && previous.Equals(MIN)) { value = Bars.GetHigh(marker); } else if (reducedPivots[marker].Equals(MIN_MAX) && previous.Equals(MAX)) { value = Bars.GetLow(marker); } else if (reducedPivots[marker].Equals(MAX)) { value = Bars.GetHigh(marker); } else { value = Bars.GetLow(marker); } if (objnum == 0) { previousMarker = marker; previousValue = value; objnum++; continue; } DateTime startTimeValue = Bars.GetTime(previousMarker); DateTime endTimeValue = Bars.GetTime(marker); Draw.Line(this, objnum.ToString() + prefix + "PivotLine", false, startTimeValue, previousValue, endTimeValue, value, Brushes.White, DashStyleHelper.Dot, 1, true); objnum++; previousValue = value; previousMarker = marker; previous = reducedPivots[marker]; } }
private void UpdateStopEnBar() { if (StopEnBarIndex < 0) { return; } //Draw.ArrowUp(this, "tag1", true, 0, Lows[0][0] - TickSize, Brushes.Red); RemoveDrawObject(tagLoPriceArrow); RemoveDrawObject(tagInfoTextField); Draw.Diamond(this, tagLoPriceArrow, true, Bars.GetTime(StopEnBarIndex), Bars.GetLow(StopEnBarIndex) - TickSize, Brushes.Yellow); //Draw.Diamond(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Red); //giChartTrader.SetStopPrice(Bars.GetLow(StopEnBarIndex).ToString()); Draw.TextFixed(this, tagInfoTextField, "Button ?\r\n Clicked", TextPosition.BottomLeft, Brushes.Green, new Gui.Tools.SimpleFont("Arial", 12), Brushes.Transparent, Brushes.Transparent, 100); }
private void OnTimerTick(object sender, EventArgs e) { ForceRefresh(); if (DisplayTime()) { if (timer != null && !timer.IsEnabled) { timer.IsEnabled = true; } if (connected) { if (SessionIterator.IsInSession(Now, false, true)) { if (hasRealtimeData) { TimeSpan barTimeLeft = Bars.GetTime(Bars.Count - 1).Subtract(Now); timeLeft = (barTimeLeft.Ticks < 0 ? "00:00:00" : barTimeLeft.Hours.ToString("00") + ":" + barTimeLeft.Minutes.ToString("00") + ":" + barTimeLeft.Seconds.ToString("00")); Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerTimeRemaining + timeLeft, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0); } else { Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerWaitingOnDataError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0); } } else { Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerSessionTimeError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0); } } else { Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerDisconnectedError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0); if (timer != null) { timer.IsEnabled = false; } } } }
private void HandleEOD() { if (PosLong()) { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " HandleEOD:: " + " current price=" + Close[0] + " closedPrice=" + closedPrice.ToString() + " Close[0]=" + Close[0].ToString() + " P/L= " + (Close[0] - closedPrice).ToString()); AiFlat(); return; } if (PosShort()) { Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " HandleEOD:: " + " current price=" + Close[0] + " closedPrice=" + closedPrice.ToString() + " Close[0]=" + Close[0].ToString() + " P/L= " + (closedPrice - Close[0]).ToString()); AiFlat(); return; } }
void activateBearSwing(int firstIndex, int secondIndex, int thirdIndex) { //Take last 3 //Check if bear swing double firstBarValue = Bars.GetHigh(firstIndex); double secondBarValue = Bars.GetLow(secondIndex); double thirdBarValue = Bars.GetHigh(thirdIndex); bool firstIsMoreThanThird = firstBarValue > thirdBarValue; if (!firstIsMoreThanThird) { return; } bool secondLower = secondBarValue < firstBarValue && secondBarValue < thirdBarValue; if (!secondLower) { return; } if (thirdIndex > lastPatternIndex) { observePattern = OBSERVE_BEAR; observeTrigger = secondBarValue; lastPatternIndex = thirdIndex; triggerStatus = WAITING_FOR_TRIGGER; triggerRisk = (thirdBarValue - secondBarValue) * 1.2; DateTime startTimeValue = Bars.GetTime(firstIndex); DateTime endTimeValue = Bars.GetTime(secondIndex); Draw.Line(this, "ActiveSwing1", false, startTimeValue, firstBarValue, endTimeValue, secondBarValue, Brushes.Yellow, DashStyleHelper.Solid, 2, true); startTimeValue = Bars.GetTime(secondIndex); endTimeValue = Bars.GetTime(thirdIndex); Draw.Line(this, "ActiveSwing2", false, startTimeValue, secondBarValue, endTimeValue, thirdBarValue, Brushes.Yellow, DashStyleHelper.Solid, 2, true); } }
private void AiFlat() { Print("AiFlat: currPos = " + currPos.ToString()); if (PosLong()) { ExitLong("ExitLong", "Long"); Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " AiFlat::ExitLong"); Print("---------------------------------------------------------------------------------"); } if (PosShort()) { ExitShort("ExitShort", "Short"); Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " AiFlat::ExitShort"); Print("---------------------------------------------------------------------------------"); } //reset global flags currPos = Position.posFlat; profitChasingFlag = false; }
protected override void OnBarUpdate() { if (Bars != null && Bars.Count > 0 && TimeFrame.Periodicity == DatafeedHistoryPeriodicity.Minute && TimeFrame.PeriodicityValue == 1) { } else { return; } if (Bars.GetTime(CurrentBar).Minute % 2 == 0) //Es ist eine gerade Minute { Value.Set(100); } else { Value.Set(0); } }
protected override void OnBarUpdate() { if (Bars != null && Bars.Count > 0 && TimeFrame.Periodicity == DatafeedHistoryPeriodicity.Minute && TimeFrame.PeriodicityValue == 1) { // } else { return; } //Using modulus to check if there is an even minute. if (Bars.GetTime(CurrentBar).Minute % 2 == 0) { Value.Set(100); } else { Value.Set(0); } }
protected override void OnDataPoint(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isBar, double bid, double ask) { if (SessionIterator == null) { SessionIterator = new SessionIterator(bars); } if (bars.Count == 0 && tmpTime != Core.Globals.MinDate) // Reset caching when live request trimmed existing bars { tmpTime = Core.Globals.MinDate; } bool endOfBar = true; if (tmpTime == Core.Globals.MinDate) { tmpTime = time; tmpDayCount = 1; tmpTickCount = 1; } else if (bars.Count < tmpCount && bars.Count == 0) // Reset cache when bars are trimmed { tmpTime = Core.Globals.MinDate; tmpVolume = 0; tmpDayCount = 0; tmpTickCount = 0; } else if (bars.Count < tmpCount && bars.Count > 0) // Reset cache when bars are trimmed { tmpTime = bars.GetTime(bars.Count - 1); tmpVolume = bars.GetVolume(bars.Count - 1); tmpTickCount = bars.TickCount; tmpDayCount = bars.DayCount; } switch (BarsPeriod.BaseBarsPeriodType) { case BarsPeriodType.Day: { if (bars.Count == 0 || bars.Count > 0 && (bars.LastBarTime.Month < time.Month || bars.LastBarTime.Year < time.Year)) { tmpTime = time.Date; bars.LastPrice = close; newSession = true; } else { tmpTime = time.Date; tmpVolume += volume; bars.LastPrice = close; tmpDayCount++; if (tmpDayCount < BarsPeriod.BaseBarsPeriodValue || bars.Count > 0 && bars.LastBarTime.Date == time.Date) { endOfBar = false; } } break; } case BarsPeriodType.Minute: { if (bars.Count == 0 || SessionIterator.IsNewSession(time, isBar) && bars.IsResetOnNewTradingDay) { tmpTime = TimeToBarTimeMinute(bars, time, isBar); newSession = true; tmpVolume = 0; } else { if (!isBar && time < bars.LastBarTime || isBar && time <= bars.LastBarTime) { tmpTime = bars.LastBarTime; endOfBar = false; } else { tmpTime = TimeToBarTimeMinute(bars, time, isBar); } tmpVolume += volume; } break; } case BarsPeriodType.Month: { if (tmpTime == Core.Globals.MinDate) { tmpTime = TimeToBarTimeMonth(time, BarsPeriod.BaseBarsPeriodValue); if (bars.Count == 0) { break; } endOfBar = false; } else if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } break; } case BarsPeriodType.Second: { if (SessionIterator.IsNewSession(time, isBar)) { tmpTime = TimeToBarTimeSecond(bars, time, isBar); if (bars.Count == 0) { break; } endOfBar = false; newSession = true; } else if (time <= tmpTime) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } else { tmpTime = TimeToBarTimeSecond(bars, time, isBar); } break; } case BarsPeriodType.Tick: { if (SessionIterator.IsNewSession(time, isBar)) { SessionIterator.GetNextSession(time, isBar); newSession = true; tmpTime = time; tmpTickCount = 1; if (bars.Count == 0) { break; } endOfBar = false; } else if (BarsPeriod.BaseBarsPeriodValue > 1 && tmpTickCount < BarsPeriod.BaseBarsPeriodValue) { tmpTime = time; tmpVolume += volume; tmpTickCount++; bars.LastPrice = close; endOfBar = false; } else { tmpTime = time; } break; } case BarsPeriodType.Volume: { if (SessionIterator.IsNewSession(time, isBar)) { SessionIterator.GetNextSession(time, isBar); newSession = true; } else if (bars.Count == 0 && volume > 0) { break; } else { tmpVolume += volume; if (tmpVolume < BarsPeriod.BaseBarsPeriodValue) { bars.LastPrice = close; endOfBar = false; } else if (tmpVolume == 0) { endOfBar = false; } } tmpTime = time; break; } case BarsPeriodType.Week: { if (tmpTime == Core.Globals.MinDate) { tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, BarsPeriod.BaseBarsPeriodValue); if (bars.Count == 0) { break; } endOfBar = false; } else if (time.Date <= tmpTime.Date) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } break; } case BarsPeriodType.Year: { if (tmpTime == Core.Globals.MinDate) { tmpTime = TimeToBarTimeYear(time, BarsPeriod.BaseBarsPeriodValue); if (bars.Count == 0) { break; } endOfBar = false; } else if (time.Year <= tmpTime.Year) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } break; } } if (bars.Count > 0 && tmpTime < bars.GetTime(bars.Count - 1) && BarsPeriod.BaseBarsPeriodType == BarsPeriodType.Second) { tmpTime = bars.GetTime(bars.Count - 1); } if (bars.Count == 0 || newSession && IsIntraday) { AddBar(bars, open, close, close, close, tmpTime, volume); upTrend = open < close; newSessionIdx = bars.Count - 1; newSession = false; firstBarOfSession = true; anchorPrice = close; switchPrice = open; } else if (firstBarOfSession && endOfBar == false) { double prevOpen = bars.GetOpen(bars.Count - 1); RemoveLastBar(bars); if (SessionIterator.IsNewSession(tmpTime, true)) { SessionIterator.GetNextSession(tmpTime, true); } AddBar(bars, prevOpen, close, close, close, tmpTime, tmpVolume); upTrend = prevOpen < close; anchorPrice = close; } else { int breakCount = BarsPeriod.Value; double breakMax = double.MinValue; double breakMin = double.MaxValue; if (firstBarOfSession) { AddBar(bars, anchorPrice, close, close, close, tmpTime, volume); firstBarOfSession = false; tmpVolume = volume; tmpTime = Core.Globals.MinDate; return; } if (bars.Count - newSessionIdx - 1 < breakCount) { breakCount = bars.Count - (newSessionIdx + 1); } for (int k = 1; k <= breakCount; k++) { breakMax = Math.Max(breakMax, bars.GetOpen(bars.Count - k - 1)); breakMax = Math.Max(breakMax, bars.GetClose(bars.Count - k - 1)); breakMin = Math.Min(breakMin, bars.GetOpen(bars.Count - k - 1)); breakMin = Math.Min(breakMin, bars.GetClose(bars.Count - k - 1)); } bars.LastPrice = close; if (upTrend) { if (endOfBar) { bool adding = false; if (bars.Instrument.MasterInstrument.Compare(bars.GetClose(bars.Count - 1), anchorPrice) > 0) { anchorPrice = bars.GetClose(bars.Count - 1); switchPrice = bars.GetOpen(bars.Count - 1); tmpVolume = volume; adding = true; } else if (bars.Instrument.MasterInstrument.Compare(breakMin, bars.GetClose(bars.Count - 1)) > 0) { anchorPrice = bars.GetClose(bars.Count - 1); switchPrice = bars.GetOpen(bars.Count - 1); tmpVolume = volume; upTrend = false; adding = true; } if (adding) { double tmpOpen = upTrend ? Math.Min(Math.Max(switchPrice, close), anchorPrice) : Math.Max(Math.Min(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, volume); } else { RemoveLastBar(bars); double tmpOpen = Math.Min(Math.Max(switchPrice, close), anchorPrice); if (SessionIterator.IsNewSession(tmpTime, true)) { SessionIterator.GetNextSession(tmpTime, true); } AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume); } } else { RemoveLastBar(bars); double tmpOpen = Math.Min(Math.Max(switchPrice, close), anchorPrice); if (SessionIterator.IsNewSession(tmpTime, true)) { SessionIterator.GetNextSession(tmpTime, true); } AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume); } } else if (endOfBar) { bool adding = false; if (bars.Instrument.MasterInstrument.Compare(bars.GetClose(bars.Count - 1), anchorPrice) < 0) { anchorPrice = bars.GetClose(bars.Count - 1); switchPrice = bars.GetOpen(bars.Count - 1); tmpVolume = volume; adding = true; } else if (bars.Instrument.MasterInstrument.Compare(breakMax, bars.GetClose(bars.Count - 1)) < 0) { anchorPrice = bars.GetClose(bars.Count - 1); switchPrice = bars.GetOpen(bars.Count - 1); tmpVolume = volume; upTrend = true; adding = true; } if (adding) { double tmpOpen = upTrend ? Math.Min(Math.Max(switchPrice, close), anchorPrice) : Math.Max(Math.Min(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, volume); } else { RemoveLastBar(bars); double tmpOpen = Math.Max(Math.Min(switchPrice, close), anchorPrice); if (SessionIterator.IsNewSession(tmpTime, true)) { SessionIterator.GetNextSession(tmpTime, true); } AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume); } } else { RemoveLastBar(bars); double tmpOpen = Math.Max(Math.Min(switchPrice, close), anchorPrice); if (SessionIterator.IsNewSession(tmpTime, true)) { SessionIterator.GetNextSession(tmpTime, true); } AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume); } } if (endOfBar) { tmpTime = Core.Globals.MinDate; } tmpCount = bars.Count; }
/// <summary> /// </summary> /// <param name="bars"></param> /// <param name="open"></param> /// <param name="high"></param> /// <param name="low"></param> /// <param name="close"></param> /// <param name="time"></param> /// <param name="volume"></param> /// <param name="isRealtime"></param> public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime) { #region Building Bars from Base Period if (bars.Count != tmpCount) // reset cache when bars are trimmed { if (bars.Count == 0) { tmpTime = Cbi.Globals.MinDate; tmpVolume = 0; tmpDayCount = 0; tmpTickCount = 0; } else { tmpTime = bars.GetTime(bars.Count - 1); tmpVolume = bars.GetVolume(bars.Count - 1); tmpTickCount = bars.TickCount; tmpDayCount = bars.DayCount; bars.LastPrice = anchorPrice = bars.GetClose(bars.Count - 1); } } switch (bars.Period.BasePeriodType) { case PeriodType.Day: if (bars.Count == 0) { if (isRealtime && bars.Session.SessionsOfDay.Length > 0) { DateTime barTime; bars.Session.GetSessionDate(time, false, out barTime, out cacheSessionEnd); AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, barTime, volume, true); } else { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time.Date, volume, isRealtime); } } else { DateTime barTime; if (!isRealtime) { barTime = time.Date; } else if (time >= cacheSessionEnd /* on realtime include60 is always false */) { bars.Session.GetSessionDate(time, false, out barTime, out cacheSessionEnd); if (barTime < bars.TimeLastBar.Date) { barTime = bars.TimeLastBar.Date; // make sure timestamps are ascending } } else { barTime = bars.TimeLastBar.Date; // make sure timestamps are ascending } if (bars.DayCount < bars.Period.Value || (!isRealtime && bars.Count > 0 && barTime == bars.TimeLastBar.Date) || (isRealtime && bars.Count > 0 && barTime <= bars.TimeLastBar.Date)) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, barTime, volume, isRealtime); } else { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, barTime, volume, isRealtime); } } break; case PeriodType.Minute: if (bars.Count == 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.Value, isRealtime), volume, isRealtime); } else { if (isRealtime && time < bars.TimeLastBar) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, bars.TimeLastBar, volume, true); } else if (!isRealtime && time <= bars.TimeLastBar) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, bars.TimeLastBar, volume, false); } else { time = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.Value, isRealtime); AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, volume, isRealtime); } } break; case PeriodType.Volume: if (bars.Count == 0) { while (volume > bars.Period.Value) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, bars.Period.Value, isRealtime); volume -= bars.Period.Value; } if (volume > 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, volume, isRealtime); } } else { long volumeTmp = 0; if (!bars.IsNewSession(time, isRealtime)) { volumeTmp = Math.Min(bars.Period.Value - bars.GetVolume(bars.Count - 1), volume); if (volumeTmp > 0) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, volumeTmp, isRealtime); } } volumeTmp = volume - volumeTmp; while (volumeTmp > 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, Math.Min(volumeTmp, bars.Period.Value), isRealtime); volumeTmp -= bars.Period.Value; } } break; case PeriodType.Month: if (bars.Count == 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeMonth(time, bars.Period.Value), volume, isRealtime); } else { if ((time.Month <= bars.TimeLastBar.Month && time.Year == bars.TimeLastBar.Year) || time.Year < bars.TimeLastBar.Year) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, bars.TimeLastBar, volume, isRealtime); } else { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeMonth(time, bars.Period.Value), volume, isRealtime); } } break; case PeriodType.Second: if (bars.Count == 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeSecond(bars, time, new DateTime(bars.Session.NextBeginTime.Year, bars.Session.NextBeginTime.Month, bars.Session.NextBeginTime.Day, bars.Session.NextBeginTime.Hour, bars.Session.NextBeginTime.Minute, 0), bars.Period.Value), volume, isRealtime); } else { if ((bars.Period.Value > 1 && time < bars.TimeLastBar) || (bars.Period.Value == 1 && time <= bars.TimeLastBar)) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, bars.TimeLastBar, volume, isRealtime); } else { time = TimeToBarTimeSecond(bars, time, bars.Session.NextBeginTime, bars.Period.Value); AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, volume, isRealtime); } } break; case PeriodType.Tick: if (bars.Count == 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, volume, isRealtime); } else { if (bars.Count > 0 && !bars.IsNewSession(time, isRealtime) && bars.Period.Value > 1 && bars.TickCount < bars.Period.Value) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, volume, isRealtime); } else { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, time, volume, isRealtime); } } break; case PeriodType.Week: if (bars.Count == 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeWeek(time, time.AddDays((6 - (((int)time.DayOfWeek + 1) % 7)) + ((bars.Period.Value - 1) * 7)), bars.Period.Value), volume, isRealtime); } else if (time.Date <= bars.TimeLastBar.Date) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, bars.TimeLastBar, volume, isRealtime); } else { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeWeek(time.Date, bars.TimeLastBar.Date, bars.Period.Value), volume, isRealtime); } break; case PeriodType.Year: if (bars.Count == 0) { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeYear(time, bars.Period.Value), volume, isRealtime); } else { if (time.Year <= bars.TimeLastBar.Year) { UpdateBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, bars.TimeLastBar, volume, isRealtime); } else { AddBar(bars, 0 - open, 0 - low, 0 - high, 0 - close, TimeToBarTimeYear(time.Date, bars.Period.Value), volume, isRealtime); } } break; default: break; } #endregion }
protected override void OnDataPoint(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isBar, double bid, double ask) { if (SessionIterator == null) { SessionIterator = new SessionIterator(bars); } bool isNewSession = SessionIterator.IsNewSession(time, isBar); if (isNewSession) { SessionIterator.GetNextSession(time, isBar); } #region Building Bars from Base Period if (bars.Count != tmpCount) // Reset cache when bars are trimmed { if (bars.Count == 0) { tmpTime = Core.Globals.MinDate; tmpVolume = 0; tmpDayCount = 0; tmpTickCount = 0; } else { tmpTime = bars.GetTime(bars.Count - 1); tmpVolume = bars.GetVolume(bars.Count - 1); tmpTickCount = bars.TickCount; tmpDayCount = bars.DayCount; bars.LastPrice = anchorPrice = bars.GetClose(bars.Count - 1); } } switch (BarsPeriod.BaseBarsPeriodType) { case BarsPeriodType.Day: tmpTime = time.Date; if (!isBar) { tmpDayCount++; if (tmpTime < time.Date) { tmpTime = time.Date; // Make sure timestamps are ascending } } if (isBar && prevTimeD != tmpTime) { tmpDayCount++; } if (isBar && bars.Count > 0 && tmpTime == bars.LastBarTime.Date || !isBar && bars.Count > 0 && tmpTime <= bars.LastBarTime.Date || tmpDayCount < BarsPeriod.BaseBarsPeriodValue) { endOfBar = false; } else { prevTime = prevTimeD == Core.Globals.MinDate ? tmpTime : prevTimeD; prevTimeD = tmpTime; endOfBar = true; } break; case BarsPeriodType.Minute: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeMinute(bars, time, isBar); } if (isBar && time <= tmpTime || !isBar && time < tmpTime) { endOfBar = false; } else { prevTime = tmpTime; tmpTime = TimeToBarTimeMinute(bars, time, isBar); endOfBar = true; } break; case BarsPeriodType.Volume: if (tmpTime == Core.Globals.MinDate) { tmpVolume = volume; endOfBar = tmpVolume >= BarsPeriod.BaseBarsPeriodValue; prevTime = tmpTime = time; if (endOfBar) { tmpVolume = 0; } break; } tmpVolume += volume; endOfBar = tmpVolume >= BarsPeriod.BaseBarsPeriodValue; if (endOfBar) { prevTime = tmpTime; tmpVolume = 0; tmpTime = time; } break; case BarsPeriodType.Month: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeMonth(time, BarsPeriod.BaseBarsPeriodValue); } if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year) { endOfBar = false; } else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeMonth(time, BarsPeriod.BaseBarsPeriodValue); } break; case BarsPeriodType.Second: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeSecond(bars, time, isBar); } if (time <= tmpTime) { endOfBar = false; } else { prevTime = tmpTime; tmpTime = TimeToBarTimeSecond(bars, time, isBar); endOfBar = true; } break; case BarsPeriodType.Tick: if (tmpTime == Core.Globals.MinDate || BarsPeriod.BaseBarsPeriodValue == 1) { prevTime = tmpTime; if (prevTime == Core.Globals.MinDate) { prevTime = time; } tmpTime = time; endOfBar = BarsPeriod.BaseBarsPeriodValue == 1; break; } if (tmpTickCount < BarsPeriod.BaseBarsPeriodValue) { tmpTime = time; endOfBar = false; tmpTickCount++; } else { prevTime = tmpTime; tmpTime = time; endOfBar = true; tmpTickCount = 1; } break; case BarsPeriodType.Week: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, BarsPeriod.BaseBarsPeriodValue); } if (time.Date <= tmpTime.Date) { endOfBar = false; } else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, BarsPeriod.BaseBarsPeriodValue); } break; case BarsPeriodType.Year: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeYear(time, BarsPeriod.BaseBarsPeriodValue); } if (time.Year <= tmpTime.Year) { endOfBar = false; } else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeYear(time, BarsPeriod.BaseBarsPeriodValue); } break; } #endregion #region P&F logic double tickSize = bars.Instrument.MasterInstrument.TickSize; boxSize = Math.Floor(10000000.0 * BarsPeriod.Value * tickSize) / 10000000.0; reversalSize = BarsPeriod.Value2 * boxSize; if (bars.Count == 0 || IsIntraday && bars.IsResetOnNewTradingDay && isNewSession) { if (bars.Count > 0) { double lastHigh = bars.GetHigh(bars.Count - 1); double lastLow = bars.GetLow(bars.Count - 1); double lastClose = bars.GetClose(bars.Count - 1); DateTime lastTime = bars.GetTime(bars.Count - 1); bars.LastPrice = anchorPrice = lastClose; if (bars.Count == tmpCount) { CalculatePfBar(bars, lastHigh, lastLow, lastClose, prevTime == Core.Globals.MinDate ? time : prevTime, lastTime); } } AddBar(bars, close, close, close, close, tmpTime, volume); anchorPrice = close; trend = Trend.Undetermined; prevTime = tmpTime; volumeCount = 0; bars.LastPrice = close; tmpCount = bars.Count; tmpHigh = high; tmpLow = low; return; } double c = bars.GetClose(bars.Count - 1); double h = bars.GetHigh(bars.Count - 1); double l = bars.GetLow(bars.Count - 1); DateTime t = bars.GetTime(bars.Count - 1); if (endOfBar) { CalculatePfBar(bars, h, l, c, prevTime, t); volumeCount = volume; tmpHigh = high; tmpLow = low; } else { tmpHigh = high > tmpHigh ? high : tmpHigh; tmpLow = low < tmpLow ? low : tmpLow; volumeCount += volume; } bars.LastPrice = close; tmpCount = bars.Count; #endregion }
protected override void OnBarUpdate() { /* When working with multiple bar series objects it is important to understand the sequential order in which the * OnBarUpdate() method is triggered. The bars will always run with the primary first followed by the secondary and * so on. * * Important: Primary bars will always execute before the secondary bar series. * If a bar is timestamped as 12:00PM on the 5min bar series, the call order between the equally timestamped 12:00PM * bar on the 1min bar series is like this: * 12:00PM 5min * 12:00PM 1min * 12:01PM 1min * 12:02PM 1min * 12:03PM 1min * 12:04PM 1min * 12:05PM 5min * 12:05PM 1min * * When the OnBarUpdate() is called from the primary bar series (2000 ticks series in this example), do the following */ if (BarsInProgress == 0) { if (CurrentBar < BarsRequiredToTrade) { return; } //Print("Current Bar time=" + Bars.GetTime(CurrentBar).ToString("HHmmss")); // if the bar elapsed time span across 12 mid night DateTime t1 = Bars.GetTime(CurrentBar - 1); DateTime t2 = Bars.GetTime(CurrentBar); if (TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay) > 0) { Print("EOD Session"); HandleEOD(); string resetString = "-1"; byte[] resetMsg = Encoding.UTF8.GetBytes(resetString); // Send reset string of "-1" to the server int resetSent = sender.Send(resetMsg); lineNo = 0; //reset global flags currPos = Position.posFlat; profitChasingFlag = false; stopLossEncountered = false; return; } // prior Stop-Loss observed, construct the lineNo with special code before sending msg to the server - so that the server will flatten the position if (stopLossEncountered) { lineNo += 10000; } // construct the string buffer to be sent to DLNN string bufString = lineNo.ToString() + ',' + Bars.GetTime(CurrentBar - 1).ToString("HHmmss") + ',' + Bars.GetTime(CurrentBar).ToString("HHmmss") + ',' + Bars.GetOpen(CurrentBar).ToString() + ',' + Bars.GetClose(CurrentBar).ToString() + ',' + Bars.GetHigh(CurrentBar).ToString() + ',' + Bars.GetLow(CurrentBar).ToString() + ',' + Bars.GetVolume(CurrentBar).ToString() + ',' + SMA(9)[0].ToString() + ',' + SMA(20)[0].ToString() + ',' + SMA(50)[0].ToString() + ',' + MACD(12, 26, 9).Diff[0].ToString() + ',' + RSI(14, 3)[0].ToString() + ',' + Bollinger(2, 20).Lower[0].ToString() + ',' + Bollinger(2, 20).Upper[0].ToString() + ',' + CCI(20)[0].ToString() + ',' + Bars.GetHigh(CurrentBar).ToString() + ',' + Bars.GetLow(CurrentBar).ToString() + ',' + Momentum(20)[0].ToString() + ',' + DM(14).DiPlus[0].ToString() + ',' + DM(14).DiMinus[0].ToString() + ',' + VROC(25, 3)[0].ToString() + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0'; //Print("CurrentBar = " + CurrentBar + ": " + "bufString = " + bufString); byte[] msg = Encoding.UTF8.GetBytes(bufString); // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); // prior Stop-Loss observed, hence ignore the returned signal from server and move on to the next bar, reset lineNo to next counter and reset stopLossEncountered flag if (stopLossEncountered) { lineNo -= 10000; lineNo++; stopLossEncountered = false; //svrSignal = ExtractResponse(System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length)); svrSignal = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length).Split(',')[1]; Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " Ignore Post STOP-LOSS Server response= <" + svrSignal + "> Current Bar: Open=" + Bars.GetOpen(CurrentBar) + " Close=" + Bars.GetClose(CurrentBar) + " High=" + Bars.GetHigh(CurrentBar) + " Low=" + Bars.GetLow(CurrentBar)); return; } //svrSignal = ExtractResponse(System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length)); svrSignal = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length).Split(',')[1]; Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " Server response= <" + svrSignal + "> Current Bar: Open=" + Bars.GetOpen(CurrentBar) + " Close=" + Bars.GetClose(CurrentBar) + " High=" + Bars.GetHigh(CurrentBar) + " Low=" + Bars.GetLow(CurrentBar)); //Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " Server response= <" + svrSignal + ">"); // Return signal from DLNN is not we expected, close outstanding position and restart if (bytesRec == -1) { lineNo = 0; // TODO: close current position? } else { lineNo++; } // Start processing signal after 8th signal and beyond, otherwise ignore if (lineNo >= 8) { ExecuteAITrade(svrSignal); // if position is flat, no need to do anything if (currPos == Position.posFlat) { return; } // handle stop loss or profit chasing if there is existing position and order action is either SellShort or Buy if (entryOrder != null && (entryOrder.OrderAction == OrderAction.Buy || entryOrder.OrderAction == OrderAction.SellShort) && (entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled)) { // if Close[0] violates soft deck, if YES handle stop loss accordingly if (ViolateSoftDeck()) { HandleSoftDeck(svrSignal); } // if profitChasingFlag is TRUE or TouchedProfitChasing then handle profit chasing if ((profitChasingFlag || TouchedProfitChasing())) { HandleProfitChasing(); } } } } // When the OnBarUpdate() is called from the secondary bar series, in our case for each tick, handle stop loss and profit chasing accordingly else { return; } }
private void AiLong() { EnterLong(lotSize, "Long"); Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " Server Signal=" + svrSignal + " Long"); }
protected override void OnDataPoint(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isBar, double bid, double ask) { if (SessionIterator == null) { SessionIterator = new SessionIterator(bars); } #region Building Bars from Base Period if (bars.Count != tmpCount) // Reset cache when bars are trimmed { if (bars.Count == 0) { tmpTime = Core.Globals.MinDate; tmpVolume = 0; tmpDayCount = 0; tmpTickCount = 0; } else { tmpTime = bars.GetTime(bars.Count - 1); tmpVolume = bars.GetVolume(bars.Count - 1); tmpTickCount = bars.TickCount; tmpDayCount = bars.DayCount; bars.LastPrice = bars.GetClose(bars.Count - 1); anchorPrice = bars.LastPrice; } } bool isNewSession = SessionIterator.IsNewSession(time, isBar); bool isCalculateTradingDayDone = false; switch (bars.BarsPeriod.BaseBarsPeriodType) { case BarsPeriodType.Day: tmpTime = time.Date; // Will be modified for realtime only if (!isBar && time >= cacheSessionEnd /* on realtime includesEndTimeStamp is always false */) { if (isNewSession) { SessionIterator.GetNextSession(time, isBar); isCalculateTradingDayDone = true; } cacheSessionEnd = SessionIterator.ActualSessionEnd; if (tmpTime < time.Date) { tmpTime = time.Date; // Make sure timestamps are ascending } } if (prevTime != tmpTime) { tmpDayCount++; } if (tmpDayCount < bars.BarsPeriod.BaseBarsPeriodValue || isBar && bars.Count > 0 && tmpTime == bars.LastBarTime.Date || !isBar && bars.Count > 0 && tmpTime <= bars.LastBarTime.Date) { endOfBar = false; } else { prevTime = tmpTime; endOfBar = true; } break; case BarsPeriodType.Minute: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeMinute(bars, time, isBar); } if (isBar && time <= tmpTime || !isBar && time < tmpTime) { endOfBar = false; } else { prevTime = tmpTime; tmpTime = TimeToBarTimeMinute(bars, time, isBar); endOfBar = true; } break; case BarsPeriodType.Volume: if (tmpTime == Core.Globals.MinDate) { tmpVolume = volume; endOfBar = tmpVolume >= bars.BarsPeriod.BaseBarsPeriodValue; prevTime = tmpTime = time; if (endOfBar) { tmpVolume = 0; } break; } tmpVolume += volume; endOfBar = tmpVolume >= bars.BarsPeriod.BaseBarsPeriodValue; if (endOfBar) { prevTime = tmpTime; tmpVolume = 0; } tmpTime = time; break; case BarsPeriodType.Tick: if (tmpTime == Core.Globals.MinDate || bars.BarsPeriod.BaseBarsPeriodValue == 1) { prevTime = tmpTime == Core.Globals.MinDate ? time : tmpTime; tmpTime = time; tmpTickCount = bars.BarsPeriod.BaseBarsPeriodValue == 1 ? 0 : 1; endOfBar = bars.BarsPeriod.BaseBarsPeriodValue == 1; break; } if (tmpTickCount < bars.BarsPeriod.BaseBarsPeriodValue) { tmpTime = time; endOfBar = false; tmpTickCount++; } else { prevTime = tmpTime; tmpTime = time; endOfBar = true; tmpTickCount = 1; } break; case BarsPeriodType.Month: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeMonth(time, bars.BarsPeriod.BaseBarsPeriodValue); } if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year) { endOfBar = false; } else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeMonth(time, bars.BarsPeriod.BaseBarsPeriodValue); } break; case BarsPeriodType.Second: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeSecond(bars, time, isBar); } if (bars.BarsPeriod.BaseBarsPeriodValue > 1 && time < tmpTime || bars.BarsPeriod.BaseBarsPeriodValue == 1 && time <= tmpTime) { endOfBar = false; } else { prevTime = tmpTime; tmpTime = TimeToBarTimeSecond(bars, time, isBar); endOfBar = true; } break; case BarsPeriodType.Week: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.BarsPeriod.BaseBarsPeriodValue); } if (time.Date <= tmpTime.Date) { endOfBar = false; } else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.BarsPeriod.BaseBarsPeriodValue); } break; case BarsPeriodType.Year: if (tmpTime == Core.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeYear(time, bars.BarsPeriod.Value); } if (time.Year <= tmpTime.Year) { endOfBar = false; } else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeYear(time, bars.BarsPeriod.Value); } break; } #endregion #region Kagi Logic reversalPoint = bars.BarsPeriod.ReversalType == ReversalType.Tick ? bars.BarsPeriod.Value * bars.Instrument.MasterInstrument.TickSize : bars.BarsPeriod.Value / 100.0 * anchorPrice; if (bars.Count == 0 || IsIntraday && (bars.BarsPeriod.BaseBarsPeriodType != BarsPeriodType.Second && bars.IsResetOnNewTradingDay && isNewSession || bars.BarsPeriod.BaseBarsPeriodType == BarsPeriodType.Second && bars.IsResetOnNewTradingDay && isNewSession)) { if (isNewSession && !isCalculateTradingDayDone) { SessionIterator.GetNextSession(tmpTime, isBar); } if (bars.Count > 0) { double lastOpen = bars.GetOpen(bars.Count - 1); double lastHigh = bars.GetHigh(bars.Count - 1); double lastLow = bars.GetLow(bars.Count - 1); double lastClose = bars.GetClose(bars.Count - 1); if (bars.Count == tmpCount) { CalculateKagiBar(bars, lastOpen, lastHigh, lastLow, lastClose, prevTime, volume); } } AddBar(bars, close, close, close, close, tmpTime, volume); anchorPrice = close; trend = Trend.Undetermined; prevTime = tmpTime; volumeCount = 0; bars.LastPrice = close; tmpCount = bars.Count; return; } double c = bars.GetClose(bars.Count - 1); double o = bars.GetOpen(bars.Count - 1); double h = bars.GetHigh(bars.Count - 1); double l = bars.GetLow(bars.Count - 1); if (endOfBar) { CalculateKagiBar(bars, o, h, l, c, prevTime, volume); } else { volumeCount += volume; } bars.LastPrice = close; tmpCount = bars.Count; #endregion }
/// <summary> /// /// </summary> /// <param name="bars"></param> /// <param name="open"></param> /// <param name="high"></param> /// <param name="low"></param> /// <param name="close"></param> /// <param name="time"></param> /// <param name="volume"></param> /// <param name="isRealtime"></param> public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime) { if (bars.Count == 0 && tmpTime != Cbi.Globals.MinDate) // reset caching when live request trimmed existing bars tmpTime = Cbi.Globals.MinDate; bool endOfBar = true; if (tmpTime == Cbi.Globals.MinDate) { tmpTime = time; tmpDayCount = 1; tmpTickCount = 1; } else if (bars.Count < tmpCount && bars.Count == 0) // reset cache when bars are trimmed { tmpTime = Cbi.Globals.MinDate; tmpVolume = 0; tmpDayCount = 0; tmpTickCount = 0; } else if (bars.Count < tmpCount && bars.Count > 0) // reset cache when bars are trimmed { tmpTime = bars.GetTime(bars.Count - 1); tmpVolume = bars.GetVolume(bars.Count - 1); tmpTickCount = bars.TickCount; tmpDayCount = bars.DayCount; } switch (bars.Period.BasePeriodType) { case PeriodType.Day: { if (bars.Count == 0 || (bars.Count > 0 && (bars.TimeLastBar.Month < time.Month || bars.TimeLastBar.Year < time.Year))) { tmpTime = time.Date; bars.LastPrice = close; newSession = true; } else { tmpTime = time.Date; tmpVolume += volume; bars.LastPrice = close; tmpDayCount++; if (tmpDayCount < bars.Period.BasePeriodValue || (bars.Count > 0 && bars.TimeLastBar.Date == time.Date)) endOfBar = false; } break; } case PeriodType.Minute: { if (bars.Count == 0 || bars.IsNewSession(time, isRealtime)) { tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime); newSession = true; tmpVolume = 0; } else { if (isRealtime && time < bars.TimeLastBar || !isRealtime && time <= bars.TimeLastBar) { tmpTime = bars.TimeLastBar; endOfBar = false; } else tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime); tmpVolume += volume; } break; } case PeriodType.Month: { if (tmpTime == Cbi.Globals.MinDate) { tmpTime = TimeToBarTimeMonth(time, bars.Period.BasePeriodValue); if (bars.Count == 0) break; endOfBar = false; } else if ((time.Month <= tmpTime.Month && time.Year == tmpTime.Year) || time.Year < tmpTime.Year) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } break; } case PeriodType.Second: { if (bars.IsNewSession(time, isRealtime)) { tmpTime = TimeToBarTimeSecond(bars, time, new DateTime(bars.Session.NextBeginTime.Year, bars.Session.NextBeginTime.Month, bars.Session.NextBeginTime.Day, bars.Session.NextBeginTime.Hour, bars.Session.NextBeginTime.Minute, 0), bars.Period.BasePeriodValue); if (bars.Count == 0) break; endOfBar = false; newSession = true; } else if (time <= tmpTime) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } else tmpTime = TimeToBarTimeSecond(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue); break; } case PeriodType.Tick: { if (bars.IsNewSession(time, isRealtime)) { newSession = true; tmpTime = time; tmpTickCount = 1; if (bars.Count == 0) break; endOfBar = false; } else if (bars.Period.BasePeriodValue > 1 && tmpTickCount < bars.Period.BasePeriodValue) { tmpTime = time; tmpVolume += volume; tmpTickCount++; bars.LastPrice = close; endOfBar = false; } else tmpTime = time; // there can't be a situation when new ticks go into old bar, this would mean peeking into future. Fixed in NT7B14 20100416 CH break; } case PeriodType.Volume: { if (bars.IsNewSession(time, isRealtime)) newSession = true; else if (bars.Count == 0 && volume > 0) break; else { tmpVolume += volume; if (tmpVolume < bars.Period.BasePeriodValue) { bars.LastPrice = close; endOfBar = false; } else if (tmpVolume == 0) endOfBar = false; } tmpTime = time; // there can't be a situation when new ticks go into old bar, this would mean peeking into future. Fixed in NT7B14 20100416 CH break; } case PeriodType.Week: { if (tmpTime == Cbi.Globals.MinDate) { tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue); if (bars.Count == 0) break; endOfBar = false; } else if (time.Date <= tmpTime.Date) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } break; } case PeriodType.Year: { if (tmpTime == Cbi.Globals.MinDate) { tmpTime = TimeToBarTimeYear(time, bars.Period.Value); if (bars.Count == 0) break; endOfBar = false; } else if (time.Year <= tmpTime.Year) { tmpVolume += volume; bars.LastPrice = close; endOfBar = false; } break; } default: break; } if (bars.Count == 0 || (newSession && IsIntraday)) { AddBar(bars, open, close, close, close, tmpTime, volume, isRealtime); upTrend = (open < close); newSessionIdx = bars.Count - 1; newSession = false; firstBarOfSession = true; anchorPrice = close; switchPrice = open; } else if (firstBarOfSession && endOfBar == false) { double prevOpen = bars.GetOpen(bars.Count - 1); bars.RemoveLastBar(isRealtime); AddBar(bars, prevOpen, close, close, close, tmpTime, tmpVolume, isRealtime); upTrend = (prevOpen < close); anchorPrice = close; } else { int breakCount = bars.Period.Value; Bar bar = (Bar)bars.Get(bars.Count - 1); double breakMax = double.MinValue; double breakMin = double.MaxValue; if (firstBarOfSession) { AddBar(bars, anchorPrice, close, close, close, tmpTime, volume, isRealtime); firstBarOfSession = false; tmpVolume = volume; tmpTime = Cbi.Globals.MinDate; return; } if (bars.Count - newSessionIdx - 1 < breakCount) breakCount = bars.Count - (newSessionIdx + 1); for (int k = 1; k <= breakCount; k++) { Bar tmp = (Bar)bars.Get(bars.Count - k - 1); breakMax = Math.Max(breakMax, tmp.Open); breakMax = Math.Max(breakMax, tmp.Close); breakMin = Math.Min(breakMin, tmp.Open); breakMin = Math.Min(breakMin, tmp.Close); } bars.LastPrice = close; if (upTrend) if (endOfBar) { bool adding = false; if (bars.Instrument.MasterInstrument.Compare(bar.Close, anchorPrice) > 0) { anchorPrice = bar.Close; switchPrice = bar.Open; tmpVolume = volume; adding = true; } else if (bars.Instrument.MasterInstrument.Compare(breakMin, bar.Close) > 0) { anchorPrice = bar.Close; switchPrice = bar.Open; tmpVolume = volume; upTrend = false; adding = true; } if (adding) { double tmpOpen = upTrend ? Math.Min(Math.Max(switchPrice, close), anchorPrice) : Math.Max(Math.Min(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, volume, isRealtime); } else { bars.RemoveLastBar(isRealtime); double tmpOpen = Math.Min(Math.Max(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime); } } else { bars.RemoveLastBar(isRealtime); double tmpOpen = Math.Min(Math.Max(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime); } else if (endOfBar) { bool adding = false; if (bars.Instrument.MasterInstrument.Compare(bar.Close, anchorPrice) < 0) { anchorPrice = bar.Close; switchPrice = bar.Open; tmpVolume = volume; adding = true; } else if (bars.Instrument.MasterInstrument.Compare(breakMax, bar.Close) < 0) { anchorPrice = bar.Close; switchPrice = bar.Open; tmpVolume = volume; upTrend = true; adding = true; } if (adding) { double tmpOpen = upTrend ? Math.Min(Math.Max(switchPrice, close), anchorPrice) : Math.Max(Math.Min(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, volume, isRealtime); } else { bars.RemoveLastBar(isRealtime); double tmpOpen = Math.Max(Math.Min(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime); } } else { bars.RemoveLastBar(isRealtime); double tmpOpen = Math.Max(Math.Min(switchPrice, close), anchorPrice); AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime); } } if (endOfBar) tmpTime = Cbi.Globals.MinDate; tmpCount = bars.Count; }
protected void OnTradeByChartTrader(object sender, IndicatorEventArgs e) { this.Update(); IndicatorSignal isig = e.IndSignal; Print(String.Format("{0}:OnTradeByChartTrader {1} Bip={2}, CurrentBar[0]={3}, DrawingTool.GetCurrentBar={4}, \r\n Bars.GetTime(CurrentBars[0])={5}, Time[BarsInProgress][0]={6}, Time[0][0]={7}", CurrentBars[BarsInProgress], isig.SignalName, BarsInProgress, CurrentBars[0], DrawingTool.GetCurrentBar(this), Bars.GetTime(CurrentBars[0]), Times[BarsInProgress][0], Times[0][0])); if (isig.SignalAction != null) { if (isig.SignalAction.SignalActionType == SignalActionType.BarToLeft) { StopEnBarIndex = StopEnBarIndex < 1? CurrentBars[0] : StopEnBarIndex - 1; } else if (isig.SignalAction.SignalActionType == SignalActionType.BarToRight) { StopEnBarIndex = StopEnBarIndex > CurrentBars[0]? 1 : StopEnBarIndex + 1; } } UpdateStopEnBar(); UpdateHiLoPrice(); }
/// <summary> /// </summary> /// <param name="bars"></param> /// <param name="open"></param> /// <param name="high"></param> /// <param name="low"></param> /// <param name="close"></param> /// <param name="time"></param> /// <param name="volume"></param> /// <param name="isRealtime"></param> public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime) { #region Building Bars from Base Period if (bars.Count != tmpCount) // reset cache when bars are trimmed if (bars.Count == 0) { tmpTime = Cbi.Globals.MinDate; tmpVolume = 0; tmpDayCount = 0; tmpTickCount = 0; } else { tmpTime = bars.GetTime(bars.Count - 1); tmpVolume = bars.GetVolume(bars.Count - 1); tmpTickCount = bars.TickCount; tmpDayCount = bars.DayCount; bars.LastPrice = anchorPrice = bars.GetClose(bars.Count - 1); } switch (bars.Period.BasePeriodType) { case PeriodType.Day: tmpTime = time.Date; if (isRealtime && time >= cacheSessionEnd) { tmpDayCount++; bars.Session.GetSessionDate(time, false, out tmpTime, out cacheSessionEnd); if (tmpTime < time.Date) tmpTime = time.Date; // make sure timestamps are ascending } if (!isRealtime && prevTimeD != tmpTime) tmpDayCount++; if ((!isRealtime && bars.Count > 0 && tmpTime == bars.TimeLastBar.Date) || (isRealtime && bars.Count > 0 && tmpTime <= bars.TimeLastBar.Date) || tmpDayCount < bars.Period.BasePeriodValue) endOfBar = false; else { prevTime = prevTimeD == Cbi.Globals.MinDate ? tmpTime : prevTimeD; prevTimeD = tmpTime; endOfBar = true; } break; case PeriodType.Minute: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime); if (!isRealtime && time <= tmpTime || isRealtime && time < tmpTime) endOfBar = false; else { prevTime = tmpTime; tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime); endOfBar = true; } break; case PeriodType.Volume: if (tmpTime == Cbi.Globals.MinDate) { tmpVolume = volume; endOfBar = tmpVolume >= bars.Period.BasePeriodValue; prevTime = tmpTime = time; if (endOfBar) tmpVolume = 0; break; } tmpVolume += volume; endOfBar = tmpVolume >= bars.Period.BasePeriodValue; if (endOfBar) { prevTime = tmpTime; tmpVolume = 0; tmpTime = time; } break; case PeriodType.Month: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeMonth(time, bars.Period.BasePeriodValue); if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year) endOfBar = false; else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeMonth(time, bars.Period.BasePeriodValue); } break; case PeriodType.Second: if (tmpTime == Cbi.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeSecond(bars, time, new DateTime(bars.Session.NextBeginTime.Year, bars.Session.NextBeginTime.Month, bars.Session.NextBeginTime.Day, bars.Session.NextBeginTime.Hour, bars.Session.NextBeginTime.Minute, 0), bars.Period.BasePeriodValue); } if (time <= tmpTime) endOfBar = false; else { prevTime = tmpTime; tmpTime = TimeToBarTimeSecond(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue); endOfBar = true; } break; case PeriodType.Tick: if (tmpTime == Cbi.Globals.MinDate || bars.Period.BasePeriodValue == 1) { prevTime = tmpTime = time; tmpTickCount = bars.Period.BasePeriodValue == 1 ? 0 : 1; endOfBar = bars.Period.BasePeriodValue == 1; break; } if (tmpTickCount < bars.Period.BasePeriodValue) { tmpTime = time; endOfBar = false; tmpTickCount++; } else { prevTime = tmpTime; tmpTime = time; endOfBar = true; tmpTickCount = 1; } break; case PeriodType.Week: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue); if (time.Date <= tmpTime.Date) endOfBar = false; else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue); } break; case PeriodType.Year: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeYear(time, bars.Period.Value); if (time.Year <= tmpTime.Year) endOfBar = false; else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeYear(time, bars.Period.Value); } break; default: break; } #endregion #region P&F logic double tickSize = bars.Instrument.MasterInstrument.TickSize; boxSize = Math.Floor(10000000.0 * bars.Period.Value * tickSize) / 10000000.0; reversalSize = bars.Period.Value2 * boxSize; if (bars.Count == 0 || (IsIntraday && bars.IsNewSession(time, isRealtime))) { if (bars.Count > 0) { double lastOpen = bars.GetOpen(bars.Count - 1); double lastHigh = bars.GetHigh(bars.Count - 1); double lastLow = bars.GetLow(bars.Count - 1); double lastClose = bars.GetClose(bars.Count - 1); DateTime lastTime = bars.GetTime(bars.Count - 1); bars.LastPrice = anchorPrice = lastClose; if (bars.Count == tmpCount) CalculatePfBar(bars, lastOpen, lastHigh, lastLow, lastClose, prevTime, lastTime, isRealtime); } AddBar(bars, close, close, close, close, tmpTime, volume, isRealtime); anchorPrice = close; trend = Trend.Undetermined; prevTime = tmpTime; volumeCount = 0; bars.LastPrice = close; tmpCount = bars.Count; tmpHigh = high; tmpLow = low; return; } Bar bar = (Bar)bars.Get(bars.Count - 1); double c = bar.Close; double o = bar.Open; double h = bar.High; double l = bar.Low; DateTime t = bar.Time; if (endOfBar) { CalculatePfBar(bars, o, h, l, c, prevTime, t, isRealtime); volumeCount = volume; tmpHigh = high; tmpLow = low; } else { tmpHigh = (high > tmpHigh ? high : tmpHigh); tmpLow = (low < tmpLow ? low : tmpLow); volumeCount += volume; } bars.LastPrice = close; tmpCount = bars.Count; #endregion }
//protected override void OnBarUpdate() //{ // //TODO: Write your owner OnBarUpdate handling // //DrawArrowUp("Arrowup" + CurrentBar, true, Bars.GetTime(Count - 1), Bars.GetLow(CurrentBar) - 300 * TickSize, Color.Red); // //DrawArrowDown("Arrowdown" + CurrentBar, true, Bars.GetTime(Count - 1), Bars.GetHigh(CurrentBar) + 300 * TickSize, Color.Green); // //Occurred.Set(-1); // //Entry.Set(Close[0]); //} protected override void OnBarUpdate() { //MyGap.Set(Input[0]); if (Bars != null && Bars.Count > 0) // && TimeFrame.Periodicity == DatafeedHistoryPeriodicity.Minute // && TimeFrame.PeriodicityValue == 15) { } else { return; } if (Bars.BarsSinceSession == 0) { sessionprocessed = false; } //08.00, 08.15, 08.30, 08.45, 09.00 sind abgeschlossen -> es ist 09.15) // if(Bars.BarsSinceSession == 5) if (ToTime(Bars.GetTime(CurrentBar)) > 90000 && //größer 09.00 geht für 15M und 1Std (und 1Tag?) sessionprocessed == false) //Tag noch nicht verarbeitet { sessionprocessed = true; GapTradeLong = GapTradeShort = false; IBar GapOpenBar = Bars.Where(x => x.Time.Date == Bars[0].Time.Date).FirstOrDefault(); //liefert erster kerze des tages double GapOpen = GapOpenBar.Open; double LastDayClose = PriorDayOHLC().PriorClose[0]; double GapSize = GapOpen - LastDayClose; DateTime LastDayCloseDate = Bars.GetTime(Count - 7); DateTime LastPeriod = Time[1]; if (LastDayClose != null && Math.Abs(LastDayClose - GapOpen) > _PunkteGapMin && Math.Abs(LastDayClose - GapOpen) < _PunkteGapMax) { //Wenn Gap größer 50 und kleiner 100 existgap = true; //Gap markieren (08.00 - 09.15) string strMyRect = "MyRect" + Count; string strMyGapSize = "MyGapSize" + Count; if (LastDayClose - GapOpen < 0) //Long { //Long //DrawRectangle(strMyRect, true, LastDayCloseDate, LastDayClose, LastPeriod, HighestHighPrice(5)[0], _col_gap, _col_gap, 70); DrawText(strMyGapSize, true, Math.Round(GapSize, 1).ToString(), LastDayCloseDate, LastDayClose + 25, 9, Color.Black, new Font("Areal", 9), StringAlignment.Center, Color.Black, Color.Azure, 1); // if (LinReg(5)[0] > GapOpen) if (LinReg(Closes[0], 5)[0] > GapOpen) { //Chancenreicher SuccessTrade string strArrowUp = "ArrowUp" + Bars.GetTime(CurrentBar); DrawArrowUp(strArrowUp, true, Bars.GetTime(Count - 1), Bars.GetOpen(CurrentBar) - 300 * TickSize, Color.Green); GapTradeLong = true; Occurred.Set(1); Entry.Set(Bars.GetOpen(CurrentBar)); } } else { //Short //DrawRectangle(strMyRect, true, LastDayCloseDate, LastDayClose, LastPeriod, LowestLowPrice(5)[0], Color.Pink, Color.Pink, 70); DrawText(strMyGapSize, true, Math.Round(GapSize, 1).ToString(), LastDayCloseDate, LastDayClose - 25, 9, Color.Black, new Font("Areal", 9), StringAlignment.Center, Color.Black, Color.Azure, 1); if (LinReg(Closes[0], 5)[0] < GapOpen) { ////Chancenreicher SuccessTrade string strArrowDown = "ArrowDown" + Bars.GetTime(CurrentBar); DrawArrowDown(strArrowDown, true, Bars.GetTime(Count - 1), Bars.GetOpen(CurrentBar) + 300 * TickSize, Color.Red); GapTradeShort = true; Occurred.Set(-1); Entry.Set(Bars.GetOpen(CurrentBar)); } } if (GapTradeShort == true || GapTradeLong == true) { Print("------------------" + Time[5] + "------------------"); Print("LineReg: " + Math.Round(LinReg(5)[0]), 1); Print("Gap Open: " + GapOpen); } } else { existgap = false; } } //09.15. - 09.30 Kerze else if (Bars.BarsSinceSession == 6 && existgap == true) { //Auswertung decimal GapTradeResult; Color colorTextBox; GapTradeResult = (decimal)Bars.GetClose(CurrentBar - 1) - (decimal)Bars.GetOpen(CurrentBar - 1); if (GapTradeLong == true) { //Long GapTradeCounterLong += 1; GapTradeResultTotalLong = GapTradeResultTotalLong + GapTradeResult; string strGapeTradeLong = "GapTradeLong" + CurrentBar; string strTradeResultLong; if (GapTradeResult < 0) { Print("FAAAAAAAAAAAAAAAIIIIIIIIIIIIIILLLLLLLLLL"); GapTradeFailCounterLong += 1; strTradeResultLong = "Fail " + GapTradeResult.ToString(); colorTextBox = colFail; } else { GapTradeWinCounterLong += 1; strTradeResultLong = "Win " + GapTradeResult.ToString(); colorTextBox = colWin; } DrawText(strGapeTradeLong, true, strTradeResultLong, Time[1], Bars.GetHigh(CurrentBar - 1) + 10, 9, Color.Black, new Font("Areal", 9), StringAlignment.Center, Color.Black, colorTextBox, 70); } else if (GapTradeShort == true) { //Short GapTradeCounterShort += 1; GapTradeResultTotalShort = GapTradeResultTotalShort - GapTradeResult; string strGapeTradeShort = "GapTradeLong" + CurrentBar; string strTradeResultShort; if (GapTradeResult > 0) { Print("FAAAAAAAAAAAAAAAIIIIIIIIIIIIIILLLLLLLLLL"); GapTradeFailCounterShort += 1; strTradeResultShort = "Fail " + GapTradeResult.ToString(); colorTextBox = colFail; } else { GapTradeWinCounterShort += 1; strTradeResultShort = "Win " + GapTradeResult.ToString(); colorTextBox = colWin; } DrawText(strGapeTradeShort, true, strTradeResultShort, Time[1], Bars.GetLow(CurrentBar - 1) - 10, 9, Color.Black, new Font("Areal", 9), StringAlignment.Center, Color.Black, colorTextBox, 70); } Print("Gap Trade Result: " + GapTradeResult); } if (Count == Bars.Count - 1) { Print("Total Trades Long: " + GapTradeCounterLong); Print("Wins Long: " + GapTradeWinCounterLong); Print("Fails Long: " + GapTradeFailCounterLong); Print("Total Trades Short: " + GapTradeCounterShort); Print("Wins Short: " + GapTradeWinCounterShort); Print("Fails Short: " + GapTradeFailCounterShort); if (GapTradeCounterLong > 0) { Print("Avg Long: " + (GapTradeResultTotalLong / GapTradeCounterLong)); } if (GapTradeCounterShort > 0) { Print("Avg Short: " + (GapTradeResultTotalShort / GapTradeCounterShort)); } } }
/// <summary> /// </summary> /// <param name="bars"></param> /// <param name="open"></param> /// <param name="high"></param> /// <param name="low"></param> /// <param name="close"></param> /// <param name="time"></param> /// <param name="volume"></param> /// <param name="isRealtime"></param> public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime) { #region Building Bars from Base Period if (bars.Count != tmpCount) // reset cache when bars are trimmed if (bars.Count == 0) { tmpTime = Cbi.Globals.MinDate; tmpVolume = 0; tmpDayCount = 0; tmpTickCount = 0; } else { tmpTime = bars.GetTime(bars.Count - 1); tmpVolume = bars.GetVolume(bars.Count - 1); tmpTickCount = bars.TickCount; tmpDayCount = bars.DayCount; bars.LastPrice = bars.GetClose(bars.Count - 1); anchorPrice = bars.LastPrice; } switch (bars.Period.BasePeriodType) { case PeriodType.Day: tmpTime = time.Date; // will be modified for realtime only if (isRealtime && time >= cacheSessionEnd /* on realtime include60 is always false */) { bars.Session.GetSessionDate(time, false, out tmpTime, out cacheSessionEnd); if (tmpTime < time.Date) tmpTime = time.Date; // make sure timestamps are ascending } if (prevTime != tmpTime) tmpDayCount++; if (tmpDayCount < bars.Period.BasePeriodValue || (!isRealtime && bars.Count > 0 && tmpTime == bars.TimeLastBar.Date) || (isRealtime && bars.Count > 0 && tmpTime <= bars.TimeLastBar.Date)) endOfBar = false; else { prevTime = tmpTime; endOfBar = true; } break; case PeriodType.Minute: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime); if (!isRealtime && time <= tmpTime || isRealtime && time < tmpTime) endOfBar = false; else { prevTime = tmpTime; tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime); endOfBar = true; } break; case PeriodType.Volume: if (tmpTime == Cbi.Globals.MinDate) { tmpVolume = volume; endOfBar = tmpVolume >= bars.Period.BasePeriodValue; prevTime = tmpTime = time; if (endOfBar) tmpVolume = 0; break; } tmpVolume += volume; endOfBar = tmpVolume >= bars.Period.BasePeriodValue; if (endOfBar) { prevTime = tmpTime; tmpVolume = 0; } tmpTime = time; break; case PeriodType.Tick: if (tmpTime == Cbi.Globals.MinDate || bars.Period.BasePeriodValue == 1) { prevTime = tmpTime == Cbi.Globals.MinDate ? time : tmpTime; tmpTime = time; tmpTickCount = bars.Period.BasePeriodValue == 1 ? 0 : 1; endOfBar = bars.Period.BasePeriodValue == 1; break; } if (tmpTickCount < bars.Period.BasePeriodValue) { tmpTime = time; endOfBar = false; tmpTickCount++; } else { prevTime = tmpTime; tmpTime = time; endOfBar = true; tmpTickCount = 1; } break; case PeriodType.Month: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeMonth(time, bars.Period.BasePeriodValue); if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year) endOfBar = false; else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeMonth(time, bars.Period.BasePeriodValue); } break; case PeriodType.Second: if (tmpTime == Cbi.Globals.MinDate) { prevTime = tmpTime = TimeToBarTimeSecond(bars, time, new DateTime( bars.Session.NextBeginTime.Year, bars.Session.NextBeginTime.Month, bars.Session.NextBeginTime.Day, bars.Session.NextBeginTime.Hour, bars.Session.NextBeginTime.Minute, 0), bars.Period.BasePeriodValue); } if ((bars.Period.Value > 1 && time < tmpTime) || (bars.Period.Value == 1 && time <= tmpTime)) endOfBar = false; else { prevTime = tmpTime; tmpTime = TimeToBarTimeSecond(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue); endOfBar = true; } break; case PeriodType.Week: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue); if (time.Date <= tmpTime.Date) endOfBar = false; else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue); } break; case PeriodType.Year: if (tmpTime == Cbi.Globals.MinDate) prevTime = tmpTime = TimeToBarTimeYear(time, bars.Period.Value); if (time.Year <= tmpTime.Year) endOfBar = false; else { prevTime = tmpTime; endOfBar = true; tmpTime = TimeToBarTimeYear(time, bars.Period.Value); } break; } #endregion #region Kagi Logic reversalPoint = bars.Period.ReversalType == ReversalType.Tick ? bars.Period.Value * bars.Instrument.MasterInstrument.TickSize : bars.Period.Value * 0.01 * anchorPrice; if (bars.Count == 0 || (IsIntraday && ((bars.Period.BasePeriodType != PeriodType.Second && bars.IsNewSession(time, isRealtime)) || (bars.Period.BasePeriodType == PeriodType.Second && bars.IsNewSession(tmpTime, isRealtime))))) { if (bars.Count > 0) { double lastOpen = bars.GetOpen(bars.Count - 1); double lastHigh = bars.GetHigh(bars.Count - 1); double lastLow = bars.GetLow(bars.Count - 1); double lastClose = bars.GetClose(bars.Count - 1); if (bars.Count == tmpCount) CalculateKagiBar(bars, lastOpen, lastHigh, lastLow, lastClose, prevTime, volume, isRealtime); } AddBar(bars, close, close, close, close, tmpTime, volume, isRealtime); anchorPrice = close; trend = Trend.Undetermined; prevTime = tmpTime; volumeCount = 0; bars.LastPrice = close; tmpCount = bars.Count; return; } Bar bar = (Bar)bars.Get(bars.Count - 1); double c = bar.Close; double o = bar.Open; double h = bar.High; double l = bar.Low; if (endOfBar) CalculateKagiBar(bars, o, h, l, c, prevTime, volume, isRealtime); else volumeCount += volume; bars.LastPrice = close; tmpCount = bars.Count; #endregion }