public void IndicatorLabelsBuild(Bar barToPopulate, Dictionary<string, Indicator> indicators) {
			if (this.initialStaticHeight == 0) this.initialStaticHeight = this.Size.Height;
			this.SuspendLayout();
			this.IndicatorLabelsRemoveDecreaseTooltipHeight();
			this.IndicatorLabelsBuildIncreaseTooltipHeight(barToPopulate, indicators);
			this.ResumeLayout(true);
		}
		public StreamingBarFactoryUnattached(string symbol, BarScaleInterval scaleInterval) {
			Symbol = symbol;
			ScaleInterval = scaleInterval;
			LastBarFormedUnattached = null;
			StreamingBarUnattached = new Bar(this.Symbol, this.ScaleInterval, DateTime.MinValue);
			IntraBarSerno = 0;
		}
		public void PopulateTooltip(Bar barToPopulate, Dictionary<string, Indicator> indicators, List<Alert> alersForBar) {
			if (barToPopulate.IsBarStreaming) {
				this.BackColor = SystemColors.GradientActiveCaption;
			} else if (barToPopulate.IsBarStaticLast) {
				this.BackColor = SystemColors.ControlLight;
			} else {
				this.BackColor = SystemColors.Info;
			}

			string titleBlue = barToPopulate.DateTimeOpen.ToString("HH:mm ") + " #" + barToPopulate.ParentBarsIndex;
			this.lblHeaderVal.Text = titleBlue;
			this.lblDateValue.Text = barToPopulate.DateTimeOpen.ToString("ddd dd-MMM-yyyy");
			string formatPrice = "N" + barToPopulate.ParentBars.SymbolInfo.DecimalsPrice;
			this.lblOpenVal.Text = barToPopulate.Open.ToString(formatPrice);
			this.lblHighVal.Text = barToPopulate.High.ToString(formatPrice);
			this.lblLowVal.Text = barToPopulate.Low.ToString(formatPrice);
			this.lblCloseVal.Text = barToPopulate.Close.ToString(formatPrice);

			string formatVolume = "N" + barToPopulate.ParentBars.SymbolInfo.DecimalsPrice;
			this.lblVolumeVal.Text = barToPopulate.Volume.ToString(formatVolume);

			string alertsAsString = "";
			foreach (var alert in alersForBar) {
				if (alertsAsString != "") alertsAsString += "\r\n";
				alertsAsString += alert.ToStringForTooltip();
			}
			//this.toolTipAlerts.SetToolTip(this.lnkAlertsVal, alertsAsString);
			this.lnkAlertsVal.Text = alersForBar.Count + "";

			this.IndicatorLabelsBuild(barToPopulate, indicators);
		}
		public BarPerst(Bar bar) {
			this.Time = bar.DateTimeOpen.ToBinary();
			this.Open = bar.Open;
			this.High = bar.High;
			this.Low = bar.Low;
			this.Close = bar.Close;
			this.Volume = bar.Volume;
		}
		public Bar BindBarToConsumerBarsAndAppend(Bar barLastFormedUnattached) {
			if (consumer.ConsumerBarsToAppendInto == null) {
				// StreamingSolidifier will attach the Bar itself
				return barLastFormedUnattached;
			}
			Bar barDetached = barLastFormedUnattached.CloneDetached();
			Bar barAttached = consumer.ConsumerBarsToAppendInto.CreateNewOrAbsorbIntoStreaming(barDetached);
			return barAttached;
		}
		private void placePrototypeOncePositionClosed(Bar bar) {
			bool isBacktesting = this.Executor.Backtester.IsBacktestingNow;
			//WHATS_THE_DIFFERENCE? if (isBacktesting) return;

			if (bar.ParentBarsIndex == 138) {
				//Debugger.Break();
			}

			if (base.HasPositionsOpenNow) return;

			if (base.HasAlertsPending) {
				// only kill pending entries, but leave activated SL & TP for an open position UNTOUCHED !!!!
				ExecutionDataSnapshot snap = this.Executor.ExecutionDataSnapshot;
				List<Alert> pendings = snap.AlertsPendingSafeCopy;
				if (pendings.Count > 0) {
					string msg = pendings.Count + " last AlertsPending[" + snap.AlertsPending[pendings.Count - 1] + "]";
					//PrintDebug(msg);
					foreach (Alert alert in pendings) {
						int wasntFilledDuringPastNbars = bar.ParentBarsIndex - alert.PlacedBarIndex;
						if (wasntFilledDuringPastNbars >= 30) {
							//if (alert.PositionAffected.Prototype != null) {}
							//base.Executor.CallbackAlertKilledInvokeScript(alert);
							base.AlertKillPending(alert);
						}
					}
				}
				return;
			}

			double protoPlacementOffsetPct = 1;
			double TPpct = 2;
			double SLpct = -1;
			double SLApct = -0.8;

			double protoPlacement = bar.Close + bar.Close * protoPlacementOffsetPct / 100;
			double TP = bar.Close * TPpct / 100;
			double SL = bar.Close * SLpct / 100;
			double SLactivation = bar.Close * SLApct / 100;
			SLactivation = 0;	// when SLactivation == 0 Prototype generates Stop alert instead of StopLoss

			PositionPrototype protoLong = new PositionPrototype(this.Bars.Symbol, PositionLongShort.Long, protoPlacement, TP, SL, SLactivation);
			PositionPrototype protoShort = new PositionPrototype(this.Bars.Symbol, PositionLongShort.Short, -protoPlacement, TP, SL, SLactivation);
			//PositionPrototype protoFixed = new PositionPrototype(this.Bars.Symbol, PositionLongShort.Long, 158000, +150.0, -50.0, -40.0);

			//PositionPrototype proto = barNewStaticArrived.Close < 158000 ? protoLong : protoShort;
			PositionPrototype proto = protoLong;
			base.Executor.PositionPrototypeActivator.PlaceOnce(proto);
		}
		public void ConsumeBarLastStraticJustFormedWhileStreamingBarWithOneQuoteAlreadyAppended(Bar barLastFormed) {
			if (barLastFormed == null) {
				string msg = "Backtester starts generating quotes => first StreamingBar is added; for first four Quotes there's no static barsFormed yet!! Isi";
				return;
			}
			//INVOCATION_WONT_DO_ANY_JOB this.simulatePendingFillPreExecuteEveryTick(null);
			ExecutionDataSnapshot snap = this.backtester.Executor.ExecutionDataSnapshot;
			foreach (Indicator indicator in snap.Indicators.Values) {
				if (indicator.NotOnChartBarsKey == null) {
					indicator.OnNewStaticBarFormed(barLastFormed);
				} else {
					string msg = "Generate quotes for the Non-Chart-Bars and feed them into your indicators!";
				}
			}

			this.backtester.Executor.Strategy.Script.OnBarStaticLastFormedWhileStreamingBarWithOneQuoteAlreadyAppendedCallback(barLastFormed);
		}
		public void IndicatorLabelsBuildIncreaseTooltipHeight(Bar barToPopulate, Dictionary<string, Indicator> indicators) {
			Label ethalonName = this.lblVolume;
			Label ethalonValue = this.lblVolumeVal;
			
			int ethalonNameX = ethalonName.Location.X;
			int ethalonValueX = ethalonValue.Location.X;
			Size ethalonNameSize = ethalonName.Size;
			Size ethalonValueSize = ethalonValue.Size;
			
			int lastStaticTooltipLabelY = ethalonName.Location.Y + this.spacingVerticalBeforeAnyDynamicIndicatorLabels;
			int dynamicLabelY = lastStaticTooltipLabelY + this.lineIncrement;
			int expandTooltipHeightBy = 0;

			foreach (Indicator indicator in indicators.Values) {
				Label lblIndicatorName = new Label();
				lblIndicatorName.Name = dynamicItemPrefix + "_Name_" + indicator.NameWithParameters;
				lblIndicatorName.Text = indicator.Name;	//indicator.NameWithParameters;
				lblIndicatorName.Location = new Point(ethalonNameX, dynamicLabelY);
				lblIndicatorName.Size = ethalonNameSize;
				lblIndicatorName.AutoSize = true;
				lblIndicatorName.ForeColor = indicator.LineColor;
				
				Label lblIndicatorValue = new Label();
				lblIndicatorValue.Name = dynamicItemPrefix + "_Value_" + indicator.NameWithParameters;
				lblIndicatorValue.Text = indicator.FormatValueForBar(barToPopulate);
				lblIndicatorValue.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
				lblIndicatorValue.Anchor = ((AnchorStyles)((AnchorStyles.Top | AnchorStyles.Right)));
				lblIndicatorValue.Location = new System.Drawing.Point(ethalonValueX, dynamicLabelY);
				lblIndicatorValue.Size = ethalonValueSize;

				this.Controls.Add(lblIndicatorName);
				this.Controls.Add(lblIndicatorValue);

				dynamicLabelY += this.lineIncrement;
				expandTooltipHeightBy += this.lineIncrement; 
			}
			
			if (expandTooltipHeightBy > 0) {
				expandTooltipHeightBy += spacingVerticalBeforeAnyDynamicIndicatorLabels;
				this.Size = new Size(this.Size.Width, this.initialStaticHeight + expandTooltipHeightBy);
			}
		}
		public override void OnBarStaticLastFormedWhileStreamingBarWithOneQuoteAlreadyAppendedCallback(Bar barStaticFormed) {
			Bar barStreaming = barStaticFormed.ParentBars.BarStreaming;
			if (barStaticFormed.ParentBarsIndex <= this.PeriodLargestAmongMAs) return;

			double maSlowThis = this.MAslow.OwnValuesCalculated[barStaticFormed.ParentBarsIndex];
			double maSlowPrev = this.MAslow.OwnValuesCalculated[barStaticFormed.ParentBarsIndex - 1];

			double maFastThis = this.MAfast.OwnValuesCalculated[barStaticFormed.ParentBarsIndex];
			double maFastPrev = this.MAfast.OwnValuesCalculated[barStaticFormed.ParentBarsIndex - 1];

			bool fastCrossedUp = false;
			if (maFastThis > maSlowThis && maFastPrev < maSlowPrev) fastCrossedUp = true; 
				
			bool fastCrossedDown = false;
			if (maFastThis < maSlowThis && maFastPrev > maSlowPrev) fastCrossedDown = true;

			if (fastCrossedUp && fastCrossedDown) {
				string msg = "TWO_CROSSINGS_SHOULD_NEVER_HAPPEN_SIMULTANEOUSLY";
				Assembler.PopupException(msg);
				Debugger.Break();
			}
			bool crossed = fastCrossedUp || fastCrossedDown;
				
			Position lastPos = base.LastPosition;
			bool isLastPositionNotClosedYet = base.IsLastPositionNotClosedYet;
			if (isLastPositionNotClosedYet && crossed) {
				string msg = "ExitAtMarket@" + barStaticFormed.ParentBarsIdent;
				Alert exitPlaced = ExitAtMarket(barStreaming, lastPos, msg);
			}

			if (fastCrossedUp) {
				string msg = "BuyAtMarket@" + barStaticFormed.ParentBarsIdent;
				Position buyPlaced = BuyAtMarket(barStreaming, msg);
			}
			if (fastCrossedDown) {
				string msg = "ShortAtMarket@" + barStaticFormed.ParentBarsIdent;
				Position shortPlaced = ShortAtMarket(barStreaming, msg);
			}
		}
		public override void OnNewQuoteOfStreamingBarCallback(Quote quote) {
			//double slowStreaming = this.MAslow.BarClosesProxied.StreamingValue;
			double slowStatic = this.MAslow.ClosesProxyEffective.LastStaticValue;
			DateTime slowStaticDate = this.MAslow.ClosesProxyEffective.LastStaticDate;

			if (this.Executor.Backtester.IsBacktestingNow == false) {
				Bar bar = quote.ParentStreamingBar;
				int barNo = bar.ParentBarsIndex;
				if (barNo == -1) return;
				DateTime lastStaticBarDateTime = bar.ParentBars.BarStaticLast.DateTimeOpen;
				DateTime streamingBarDateTime = bar.DateTimeOpen;
				Bar barNormalizedDateTimes = new Bar(bar.Symbol, bar.ScaleInterval, quote.ServerTime);
				DateTime thisBarDateTimeOpen = barNormalizedDateTimes.DateTimeOpen;
				int a = 1;
			}
			//log("OnNewQuoteCallback(): [" + quote.ToString() + "]"); 
			string msg = "OnNewQuoteCallback(): [" + quote.ToString() + "]";
			log("EnterEveryBar.cs now=[" + DateTime.Now.ToString("ddd dd-MMM-yyyy HH:mm:ss.fff" + "]: " + msg));

			if (quote.IntraBarSerno == 0) {
				return;
			}
		}
		public override double CalculateOwnValueOnNewStaticBarFormed(Bar newStaticBar) {
			if (this.Period <= 0) return double.NaN;
			if (base.ClosesProxyEffective.Count - 1 < this.FirstValidBarIndex) return double.NaN;
			if (newStaticBar.ParentBarsIndex - 1 < this.FirstValidBarIndex) return double.NaN;

			double sum = 0;
			int slidingWindowRightBar = newStaticBar.ParentBarsIndex;
			int slidingWindowLeftBar = slidingWindowRightBar - this.Period + 1;	// FirstValidBarIndex must be Period+1
			int barsProcessedCheck = 0;
			for (int i = slidingWindowLeftBar; i <= slidingWindowRightBar; i++) {
				double eachBarCloses = base.ClosesProxyEffective[i];
				if (double.IsNaN(eachBarCloses)) {
					Debugger.Break();
					continue;
				}
				sum += eachBarCloses;
				barsProcessedCheck++;
			}
			if (barsProcessedCheck != this.Period) {
				Debugger.Break();
			}
			double ret = sum / this.Period;
			return ret;
		}
		public void TooltipPriceShowAlone(Bar barToPopulate, Rectangle barWithShadowsRectangle) {
			if (this.ChartSettings.TooltipPriceShow == false) return;
			// MouseX will never go over tooltip => PanelNamedFolding.OnMouseLeave() never invoked
			int awayFromBarXpx = this.ChartSettings.TooltipsPaddingFromBarLeftRightEdgesToAvoidMouseLeave;
			int x = barWithShadowsRectangle.Left - this.tooltipPrice.Width - awayFromBarXpx;
			if (x < 0) x = barWithShadowsRectangle.Right + awayFromBarXpx;
			int y = barWithShadowsRectangle.Top - this.ChartSettings.TooltipBordersMarginToKeepBordersVisible;
			if (y < 0) y = 0;
			if (y + this.tooltipPrice.Height > this.HeightMinusBottomHscrollbar)
				y = this.HeightMinusBottomHscrollbar - this.tooltipPrice.Height - this.ChartSettings.TooltipBordersMarginToKeepBordersVisible;
			this.tooltipPriceShowXY(barToPopulate, x, y);
		}
Пример #13
0
		// TODO: don't be lazy and move to StreamingProvider.QuoteAbsnoForSymbol<string Symbol, int Absno> and init it on Backtester.RunSimulation
		//public void AbsnoReset() { Quote.AbsnoStaticCounter = 0; }
		public void SetParentBar(Bar parentBar) {
			if (this.Symbol != parentBar.Symbol) {
				string msg = "here is the problem for a streaming bar to carry another symbol!";
			}
			this.ParentStreamingBar = parentBar;
		}
		public override void OnBarStaticLastFormedWhileStreamingBarWithOneQuoteAlreadyAppendedCallback(Bar barNewStaticArrived) {
			//this.placePrototypeOncePositionClosed(barNewStaticArrived);
		}
Пример #15
0
		void generateQuotesForBarAndPokeStreaming(Bar bar) {
			if (bar == null) return;
			if (bar.IsBarStreaming && double.IsNaN(bar.Open)) {
				string msg = "it's ok for Bars.LastBar from StaticProvider doesn't contain PartialValues;"
					+ " filled by Streaming, NA for Backtest, skipping LastBar";
				//throw new Exception(msg);
				return;
			}
			List<Quote> quotesGenerated = this.QuotesGenerator.GenerateQuotesFromBar(bar);
			if (quotesGenerated == null) return;
			for (int i = 0; i < quotesGenerated.Count; i++) {
				Quote quote = quotesGenerated[i];
				this.BacktestDataSource.BacktestStreamingProvider.SpreadModeler.GenerateFillBidAskSymmetricallyFromLastPrice(quote);

				//if (this.Executor.Bars.Count == 186) {
				//	Debugger.Break();
				//}

				int pendingsToFillInitially = this.Executor.ExecutionDataSnapshot.AlertsPending.Count;
				int quotesInjected = this.QuotesGenerator.InjectQuotesToFillPendingAlerts(quote);
				if (quotesInjected == 0) {
					string msg = "SEEMS_ONLY_STOP_ALERTS_FAR_BEYOND_TARGET_ARE_ON_THE_WAY; pendingsToFillInitially[" + pendingsToFillInitially + "]"
						+ "STOPS_ARE_TOO_FAR OR_WILL_BE_FILLED_NEXT_THING_UPSTACK";
				}
				if (quotesInjected == pendingsToFillInitially) {
					int pendingsLeft = this.Executor.ExecutionDataSnapshot.AlertsPending.Count;
					string msg = "GENERATED_EXACTLY_AS_MANY_AS_PENDINGS; PENDINGS_UNFILLED_LEFT_" + pendingsLeft;
				}
				int pendingsStrategyJustGenerated = quotesInjected - pendingsToFillInitially;
				if (pendingsStrategyJustGenerated > 0) {
					string msg = "SEEMS_STRATEGY_GENERATED_NEW_ALERTS_ON_NEW_QUOTES"
						+ "; quotesInjected[" + quotesInjected + "] > pendingsToFillInitially[" + pendingsToFillInitially + "]";
				}
				if (pendingsStrategyJustGenerated < 0) {
					string msg = "STOP_ALERTS_IGNORED_OTHERS_FILLED";
				}

				int pendingsLeftAfterInjected = this.Executor.ExecutionDataSnapshot.AlertsPending.Count;

				this.BacktestDataSource.BacktestStreamingProvider.GeneratedQuoteEnrichSymmetricallyAndPush(quote);
				int pendingsLeftAfterTargetQuote = this.Executor.ExecutionDataSnapshot.AlertsPending.Count;

				//stats, nothing poductive, only monitoring
				if (pendingsToFillInitially == 0) {
					continue;
				}

				int pendingsFilledByInjected = pendingsLeftAfterInjected - pendingsToFillInitially;
				if (pendingsFilledByInjected > 0) {
					string msg = "SEEMS_LIKE_INJECTING_DOES_ITS_JOB; pendingsFilledByInjected[" + pendingsFilledByInjected + "]";
				}
				int targetQuoteIsntExpectedToFillAnything = pendingsLeftAfterTargetQuote - pendingsLeftAfterInjected;
				if (targetQuoteIsntExpectedToFillAnything > 0) {
					string msg = "SEEMS_LIKE_TARGET_QUOTE_HAD_OWN_FILL POSSIBLE_BUT_UNLIKELY";
				}
			}
		}
		public virtual void LineDrawModify(string id, Color color, int width, Bar barStart, double priceStart, Bar barEnd, double priceEnd) {
			throw new NotImplementedException();
		}
Пример #17
0
		public void FillExitWith(Bar exitBar, double exitFillPrice, double exitFillQty, double exitSlippage, double exitCommission) {
			string msig = " FillExitWith(" + exitBar + ", " + exitFillPrice + ", " + exitFillQty + ", " + exitSlippage + ", " + exitCommission + ")";
			// 1) absolutely acceptable to have a limit order beoynd the bar;
			// 2) Market order must be filled now at SpreadGenerator-generated ANY price while StreamingBar may contain only 1 quote (height=0)
			//if (exitBar.ContainsPrice(exitFillPrice) == false) {
			//	string msg = "PRICE_FILLED_POSITION_EXIT_DOESNT_EXIST_IN_EXITBAR exitFilledPrice[" + exitFillPrice + "] exitBar[" + exitBar + "]";
			//	throw new Exception(msg + msig);
			//}
			if (exitBar.Volume < exitFillQty) {
				string msg = "VOLUME_FILLED_POSITION_EXIT_NEVER_TRADED_DURING_THE_EXITBAR exitFilledQty[" + exitFillQty + "] exitBar.Volume[" + exitBar.Volume + "]";
				throw new Exception(msg + msig);
			}
			if (this.EntryFilledBarIndex == -1) {
				string msg = "ATTEMPT_TO_CLOSE_NON_OPENED_POSITION this.EntryBarIndex=-1 " + this;
				throw new Exception(msg + msig);
			}
			if (this.EntryFilledBarIndex > exitBar.ParentBarsIndex) {
				string msg = "ATTEMPT_TO_CLOSE_POSITION_AT_BAR_EARLIER_THAN_POSITION_WAS_OPENED this.EntryBarIndex[" + this.EntryFilledBarIndex + "] > exitBar.ParentBarsIndex[" + exitBar.ParentBarsIndex + "]";
				throw new Exception(msg + msig);
			}
			if (this.ExitFilledBarIndex != -1) {
				string alertClosedThisPosition = (this.ExitAlert == null) ? "NO_EXIT_ALERT" : this.ExitAlert.ToString();
				string msg = "PositionExit was already filled earlier @ExitBar[" + this.ExitFilledBarIndex + "]"
						+ ", you can't override it with [" + exitBar + "]; alertClosedThisPosition[" + alertClosedThisPosition + "]";
				throw new Exception(msg);
			}
			this.ExitFilledBarIndex = exitBar.ParentBarsIndex;
			if (this.ExitBar == null) {
				string msg = "BARINDEX_FILLED_POSITION_EXIT_DOESNT_BELONG_TO_ITS_OWN_PARENT_BARS_CHECK_Position.EntryBar_PROPERTY exitBar[" + exitBar + "] this.Bars[" + this.Bars + "]";
				throw new Exception(msg + msig);
			}
			if (exitBar.Open != this.ExitBar.Open) {
				string msg = "BAR_FILLED_POSITION_EXIT_DOESNT_HAVE_SAME_OPEN_CHECK_Position.EntryBar_PROPERTY exitBar.Open[" + exitBar.Open + "] this.Bars[" + this.ExitFilledBarIndex + "].Open[" + exitBar.Open + "]";
				throw new Exception(msg + msig);
			}
			if (exitBar.ParentBars != this.EntryBar.ParentBars) {
				string msg = "PARENTS_OF_BAR_FILLED_POSITION_EXIT_MUST_BE_SAME_AS_ENTRY_BAR_PARENTS exitBar.ParentBars[" + exitBar.ParentBars + "] != this.EntryBar.ParentBars[" + this.EntryBar.ParentBars + "]";
				throw new Exception(msg + msig);
			}
			this.ExitFilledPrice = exitFillPrice;
			this.ExitFilledQty = exitFillQty;
			this.ExitFilledSlippage = exitSlippage;
			this.ExitFilledCommission = exitCommission;
		}
		// overridable proxy methods routed by default to DataDistributor
		public virtual void ConsumerBarRegister(string symbol, BarScaleInterval scaleInterval, IStreamingConsumer consumer, Bar PartialBarInsteadOfEmpty) {
			this.ConsumerBarRegister(symbol, scaleInterval, consumer);
			SymbolScaleDistributionChannel channel = this.DataDistributor.GetDistributionChannelFor(symbol, scaleInterval);
			channel.StreamingBarFactoryUnattached.InitWithStreamingBarInsteadOfEmpty(PartialBarInsteadOfEmpty);
		}
		public virtual Quote EnrichQuoteWithSernoUpdateStreamingBarCreateNewBar(Quote quoteClone) {
			if (quoteClone.PriceLastDeal == 0) {
				string msg = "quote.PriceLastDeal[" + quoteClone.PriceLastDeal + "] == 0;"
					+ "what kind of quote is that?... (" + quoteClone + ")";
				throw new Exception(msg);
				//return;
			}

			if (this.StreamingBarUnattached.Symbol != quoteClone.Symbol) {
				string msg = "StreamingBar.Symbol=[" + this.StreamingBarUnattached.Symbol + "]!=quote.Symbol["
					+ quoteClone.Symbol + "] (" + quoteClone + ")";
				throw new Exception(msg);
				//return;
			}

			// included in if (quoteClone.ServerTime >= StreamingBar.DateTimeNextBarOpenUnconditional) !!!
			// on very first quote StreamingBar.DateTimeNextBarOpenUnconditional = DateTime.MinValue
			//SEE_BELOW if (StreamingBar.DateTimeOpen == DateTime.MinValue)
			//SEE_BELOW 	this.initStreamingBarResetIntraBarSerno(quoteClone.ServerTime, quoteClone.PriceLastDeal, quoteClone.Size);
			//SEE_BELOW }

			if (quoteClone.ServerTime >= this.StreamingBarUnattached.DateTimeNextBarOpenUnconditional) {
				this.LastBarFormedUnattached = this.StreamingBarUnattached.Clone();	//beware! on very first quote LastBarFormed.DateTimeOpen == DateTime.MinValue
				this.initStreamingBarResetIntraBarSerno(quoteClone.ServerTime, quoteClone.PriceLastDeal, quoteClone.Size);

				// quoteClone.IntraBarSerno doesn't feel new Bar; can contain 100004 for generatedQuotes;
				// I only want to reset to 0 when it's attributed to a new Bar; it's unlikely to face a new bar here for generatedQuotes;
				if (this.IntraBarSerno != 0) {
					string msg = "STREAMING_JUST_INITED_TO_ZERO WHY_NOW_IT_IS_NOT?";
					Debugger.Break();
				}
				if (quoteClone.IntraBarSerno != 0) {
					if (quoteClone.IntraBarSerno >= Quote.IntraBarSernoShiftForGeneratedTowardsPendingFill) {
						string msg = "GENERATED_QUOTES_ARENT_SUPPOSED_TO_GO_TO_NEXT_BAR";
						Debugger.Break();
					}
					quoteClone.IntraBarSerno = this.IntraBarSerno;
				}
				if (this.IntraBarSerno >= Quote.IntraBarSernoShiftForGeneratedTowardsPendingFill) {
					string msg = "BAR_FACTORY_INTRABAR_SERNO_NEVER_GOES_TO_SYNTHETIC_ZONE";
					Debugger.Break();
				}
			} else {
				if (Double.IsNaN(this.StreamingBarUnattached.Open) || this.StreamingBarUnattached.Open == 0.0) {
					throw new Exception("nonsense! we should've had StreamingBar already initialized with first quote of a bar");
					//log.Warn("Initializing OHL as quote.PriceLastDeal[" + quoteClone.PriceLastDeal + "];"
					//	+ " following previous InitWithStreamingBarInsteadOfEmpty message"
					//	+ " (if absent then never initialized)");
					//StreamingBar.Open = quoteClone.PriceLastDeal;
					//StreamingBar.High = quoteClone.PriceLastDeal;
					//StreamingBar.Low = quoteClone.PriceLastDeal;
				}
				this.StreamingBarUnattached.MergeExpandHLCVforStreamingBarUnattached(quoteClone);
				this.IntraBarSerno++;
			}
			if (quoteClone.ParentStreamingBar != null) {
				string msg = "QUOTE_ALREADY_ENRICHED_WITH_PARENT_STREAMING_BAR; I think it's a pre- bindStreamingBarForQueue() atavism";
				//Assembler.PopupException(msg);
			} else {
				quoteClone.SetParentBar(this.StreamingBarUnattached);
			}
			return quoteClone;
		}
		public int BarAppend(Bar barLastFormed) {
			Bars allBars = this.BarsLoadAllThreadSafe();
			if (allBars == null) {
				allBars = new Bars(barLastFormed.Symbol, barLastFormed.ScaleInterval, "DUMMY: LoadBars()=null");
			}
			//allBars.DumpPartialInitFromStreamingBar(bar);

			// this happens on a very first quote - this.pushBarToConsumers(StreamingBarFactory.LastBarFormed.Clone());
			if (allBars.BarStaticLast.DateTimeOpen == barLastFormed.DateTimeOpen) return 0;

			// not really needed to clone to save it in a file, but we became strict to eliminate other bugs
			barLastFormed = barLastFormed.CloneDetached();

			// SetParentForBackwardUpdateAutoindex used within Bar only()
			//barLastFormed.SetParentForBackwardUpdateAutoindex(allBars);
			if (allBars.BarStaticLast.DateTimeOpen == barLastFormed.DateTimeOpen) {
				return 0;
			}

			allBars.BarAppendBindStatic(barLastFormed);
			int barsSaved = this.BarsSaveThreadSafe(allBars);
			return barsSaved;
		}
Пример #21
0
		internal int BarAppend(Bar barLastFormed) {
			int ret = -1;
			if (this.ScaleInterval != barLastFormed.ScaleInterval) return ret;
			if (this.Symbols.Contains(barLastFormed.Symbol) == false) return ret;
			if (this.BarsRepository == null) return ret;
			ret = this.BarsRepository.DataFileForSymbol(barLastFormed.Symbol).BarAppend(barLastFormed);
			return ret;
		}
		void IStreamingConsumer.ConsumeBarLastStraticJustFormedWhileStreamingBarWithOneQuoteAlreadyAppended(Bar barLastFormed) {
			if (this.DataSource == null) return;
			int barsSaved = this.DataSource.BarAppend(barLastFormed);
			string msg = "Saved [ " + barsSaved + "] bars; DataSource[" + this.DataSource.Name + "] received barLastFormed[" + barLastFormed + "] from streaming";
		}
Пример #23
0
		public void FillPositionAffectedEntryOrExitRespectively(Bar barFill, int barFillRelno,
				double priceFill, double qtyFill, double slippageFill, double commissionFill) {
			//if (this.BarRelnoFilled != -1) {
			if (this.FilledBar != null) {
				string msg = "ALERT_ALREADY_FILLED_EARLIER_CANT_OVERRIDE @FilledBarIndex[" + this.FilledBarIndex + "]"
						+ ", duplicateFill @[" + barFill + "]";
				throw new Exception(msg);
			}
			this.FilledBar = barFill;
			this.FilledBarIndex = barFillRelno;
			if (this.PositionAffected == null) {
				//if (this.IsExecutorBacktestingNow) return;
				throw new Exception("Backtesting or Realtime, an alert always has a PositionAffected, oder?...");
			}
			if (this.IsEntryAlert) {
				this.PositionAffected.FillEntryWith(barFill, priceFill, qtyFill, slippageFill, commissionFill);
			} else {
				this.PositionAffected.FillExitWith(barFill, priceFill, qtyFill, slippageFill, commissionFill);
			}
		}
Пример #24
0
		public Alert(Bar bar, double qty, double priceScript, string signalName,
				Direction direction, MarketLimitStop marketLimitStop, OrderSpreadSide orderSpreadSide,
				Strategy strategy) : this() {

			if (direction == Direction.Unknown) {
				string msg = "ALERT_CTOR_DIRECTION_MUST_NOT_BE_UNKNOWN: when creating an Alert, direction parameter can't be null";
				throw new Exception(msg);
			}
			if (bar == null) {
				string msg = "ALERT_CTOR_BAR_MUST_NOT_BE_NULL: when creating an Alert, bar parameter can't be null";
				throw new Exception(msg);
			}
			if (bar.ParentBars == null) {
				string msg = "ALERT_CTOR_PARENT_BARS_MUST_NOT_BE_NULL: when creating an Alert, bar.ParentBars can't be null";
				throw new Exception(msg);
			}
			this.Bars = bar.ParentBars;
			this.PlacedBar = bar;
			this.PlacedBarIndex = bar.ParentBarsIndex;
			this.Symbol = bar.Symbol;
			
			this.BarsScaleInterval = this.Bars.ScaleInterval;
			if (this.Bars.SymbolInfo != null) {
				SymbolInfo symbolInfo = this.Bars.SymbolInfo;
				this.SymbolClass = (string.IsNullOrEmpty(symbolInfo.SymbolClass) == false) ? symbolInfo.SymbolClass : "UNKNOWN_CLASS";
				this.MarketOrderAs = symbolInfo.MarketOrderAs;
			}
			
			this.AccountNumber = "UNKNOWN_ACCOUNT";
			if (this.DataSource.BrokerProvider != null && this.DataSource.BrokerProvider.AccountAutoPropagate != null
			    && string.IsNullOrEmpty(this.Bars.DataSource.BrokerProvider.AccountAutoPropagate.AccountNumber) != false) {
				this.AccountNumber = this.Bars.DataSource.BrokerProvider.AccountAutoPropagate.AccountNumber;
			}
			

			this.Qty = qty;
			this.PriceScript = priceScript;
			this.SignalName = signalName;
			this.Direction = direction;
			this.MarketLimitStop = marketLimitStop;
			this.OrderSpreadSide = orderSpreadSide;

			this.Strategy = strategy;
			if (this.Strategy != null) {
				this.StrategyID = this.Strategy.Guid;
				this.StrategyName = this.Strategy.Name;
			}
			
			if (this.Strategy.Script != null) {
				string msg = "Looks like a manual Order submitted from the Chart";
				return;
			}
		}
		public void TooltipPositionAndPriceShow(AlertArrow alertArrow, Bar barToPopulate, Rectangle rectangleYarrowXbar) {
			if (this.ChartSettings.TooltipPriceShow == false) return;
			// MouseX will never go over tooltip => PanelNamedFolding.OnMouseLeave() never invoked ???
			int awayFromBarXpx = this.ChartSettings.TooltipsPaddingFromBarLeftRightEdgesToAvoidMouseLeave;
			int xPosition	= -1;
			int xPrice		= -1;

			int twoTooltipsVerticalDistance = 4;
			int twoTooltipsCombinedHeight = this.tooltipPosition.Height + twoTooltipsVerticalDistance + this.tooltipPrice.Height;

			if (alertArrow.ArrowIsForPositionEntry) {
				xPosition	= rectangleYarrowXbar.Left - this.tooltipPosition.Width - awayFromBarXpx;
				xPrice		= rectangleYarrowXbar.Left - this.tooltipPrice.Width - awayFromBarXpx;
// LET_POSITION_TOOLTIP_GO_BEHIND_LEFT_EDGE_AND_PARTIALLY_OVERLAP_I_NEED_POSITION_LINE_TO_BE_FULLY_VISIBLE_TO_HIGHLIGHT
//				if (xPrice < 0)	xPrice = rectangleYarrowXbar.Right + awayFromBarXpx;
//				if (xPosition < 0) {	// positionTooltip is wider, dont squeeze priceTooltip but take the same side as the big brother
//					xPosition	= rectangleYarrowXbar.Right + awayFromBarXpx;
//					xPrice		= rectangleYarrowXbar.Right + awayFromBarXpx;
//				}
			} else {
				xPosition	= rectangleYarrowXbar.Right + awayFromBarXpx;
				xPrice		= xPosition;
			}

			int yPrice = rectangleYarrowXbar.Top - twoTooltipsCombinedHeight / 2;
			if (yPrice <= 0) yPrice = this.ChartSettings.TooltipBordersMarginToKeepBordersVisible;
			if (yPrice + twoTooltipsCombinedHeight > this.HeightMinusBottomHscrollbar) {
				yPrice = this.HeightMinusBottomHscrollbar - twoTooltipsCombinedHeight - this.ChartSettings.TooltipBordersMarginToKeepBordersVisible;
				if (yPrice <= 0) yPrice = this.ChartSettings.TooltipBordersMarginToKeepBordersVisible;
			}
			int yPosition = yPrice + this.tooltipPrice.Height + twoTooltipsVerticalDistance;
			
			this.tooltipPriceShowXY(barToPopulate, xPrice, yPrice);
			this.tooltipPositionShowXY(alertArrow, xPosition, yPosition);
		}
		public void InitWithStreamingBarInsteadOfEmpty(Bar StreamingBarInsteadOfEmpty) {
			string msg = "";
			if (StreamingBarInsteadOfEmpty.DateTimeOpen <= this.StreamingBarUnattached.DateTimeOpen) {
				msg += "StreamingBarInsteadOfEmpty.DateTimeOpen[" + StreamingBarInsteadOfEmpty.DateTimeOpen
					+ "] <= CurrentStreamingBar.Open[" + StreamingBarUnattached.Open + "]";
				//log.Warn(msg + " // " + this);
				return;
			}
			if (StreamingBarInsteadOfEmpty.DateTimeOpen == DateTime.MinValue) {
				msg += "StreamingBarInsteadOfEmpty.DateTimeOpen[" + StreamingBarInsteadOfEmpty.DateTimeOpen + "] == DateTime.MinValue ";
			}
			if (double.IsNaN(StreamingBarInsteadOfEmpty.Open)) {
				msg += "double.IsNaN(StreamingBarInsteadOfEmpty.Open[" + StreamingBarInsteadOfEmpty.Open + "]) ";
			}
			if (StreamingBarInsteadOfEmpty.Open == 0) {
				msg += "StreamingBarInsteadOfEmpty.Open[" + StreamingBarInsteadOfEmpty.Open + "] == 0 ";
			}
			this.StreamingBarUnattached = StreamingBarInsteadOfEmpty.Clone();
			if (string.IsNullOrEmpty(msg) == false) {
				//log.Warn("InitWithStreamingBarInsteadOfEmpty: " + msg + " // " + this);
			}
		}
		private void tooltipPriceShowXY(Bar barToPopulate, int x, int y) {
			Point newLocation = new Point(x, y);
			//DOESNT_SHOWUP_MOUSE_BETWEEN_ARROW_AND_BAR
			if (this.tooltipPrice.Location == newLocation) {	//REMOVES_FLICKERING Point is a structure with Equals() overriden => we are safe to compare
				this.tooltipPrice.Visible = true;
				return;
			}

			//if (barToPopulate.IsStreamingBar)...
			List<Alert> tooltipAlertsForBar = new List<Alert>();
			//			Dictionary<int, List<Alert>> alertsForBarsFromExecution = this.executor.ExecutionDataSnapshot
			//				.AlertsPendingHistorySafeCopyForRenderer(mouseBar, mouseBar);
			//			if (alertsForBarsFromExecution.ContainsKey(mouseBar)) tooltipAlertsForBar = alertsForBarsFromExecution[mouseBar];
			Dictionary<string, Indicator> indicators = this.ScriptExecutorObjects.Indicators;
			this.tooltipPrice.PopulateTooltip(barToPopulate, indicators, tooltipAlertsForBar);
			//this.tooltipPrice.Capture = false;
			this.tooltipPrice.Location = newLocation;
			this.tooltipPrice.Visible = true;
		}
		// IStreamingConsumer
		public void ConsumeBarLastStraticJustFormedWhileStreamingBarWithOneQuoteAlreadyAppended(Bar barLastFormed) {
			this.msigForNpExceptions = "ConsumeBarLastFormed(): ";
			var barsSafe = this.Bars;
			var chartFormSafe = this.ChartForm;
			var executorSafe = this.Executor;
			
			//CHART_CONTROL_REGISTERED_HIMSELF_FOR_BAR_EVENTS_THANX chartFormSafe.ChartControl.UpdateHorizontalScrollMaximumAfterBarAdd();
			//if (this.NewBar != null) this.NewBar(this, new BarEventArgs(barLastFormed));
			//this.chartFormsManager.Executor.onNewBarEnqueueExecuteStrategyInNewThread(this, new BarEventArgs(barLastFormed));
			executorSafe.ExecuteOnNewBarOrNewQuote(null);	//new Quote());
			chartFormSafe.ChartControl.InvalidateAllPanelsFolding();
		}
		public abstract List<Quote> GenerateQuotesFromBar(Bar bar);
		public override void OnBarStaticLastFormedWhileStreamingBarWithOneQuoteAlreadyAppendedCallback(Bar barStaticFormed) {
			Bar barStreaming = base.Bars.BarStreaming;
			if (this.Executor.Backtester.IsBacktestingNow == false) {
				Debugger.Break();
			}
			if (barStaticFormed.ParentBarsIndex <= 2) return;
			if (barStaticFormed.IsBarStreaming) {
				string msg = "SHOULD_NEVER_HAPPEN [email protected][" + barStaticFormed + "] while Streaming[" + barStreaming + "]";
				Debugger.Break();
			}

			Position lastPos = base.LastPosition;
			bool isLastPositionNotClosedYet = base.IsLastPositionNotClosedYet;
			if (isLastPositionNotClosedYet) {
				if (lastPos.EntryFilledBarIndex > barStaticFormed.ParentBarsIndex) {
					string msg1 = "prev bar you placed on streaming, now that streaming is static and positionEntry is still in the future but you have it filled?...";
					Debugger.Break();
				}

				if (lastPos.ExitAlert != null) {
					string msg1 = "you want to avoid POSITION_ALREADY_HAS_AN_EXIT_ALERT_REPLACE_INSTEAD_OF_ADDING_SECOND"
						+ " ExitAtMarket by throwing [can't have two closing alerts for one positionExit] Strategy[" + this.Strategy.ToString() + "]";
					Debugger.Break();
					return;
				}

				if (barStaticFormed.ParentBarsIndex == 163) {
					Debugger.Break();
					StreamingDataSnapshot streaming = this.Executor.DataSource.StreamingProvider.StreamingDataSnapshot;
					Quote lastQuote = streaming.LastQuoteGetForSymbol(barStaticFormed.Symbol);
					double priceForMarketOrder = streaming.LastQuoteGetPriceForMarketOrder(barStaticFormed.Symbol);
				}

				string msg = "ExitAtMarket@" + barStaticFormed.ParentBarsIdent;
				Alert exitPlaced = ExitAtMarket(barStreaming, lastPos, msg);
				log("Execute(): " + msg);
			}

			ExecutionDataSnapshot snap = base.Executor.ExecutionDataSnapshot;
			int alertsPendingCount = snap.AlertsPending.Count;
			int positionsOpenNowCount = snap.PositionsOpenNow.Count;

			bool hasAlertsPendingOrPositionsOpenNow = base.HasAlertsPendingOrPositionsOpenNow;
			if (hasAlertsPendingOrPositionsOpenNow) {
				if (alertsPendingCount > 0) {
					if (snap.AlertsPending[0] == lastPos.EntryAlert) {
						string msg = "EXPECTED: I don't have open positions but I have an unfilled alert from lastPosition.EntryAlert=alertsPending[0]";
					} else if (snap.AlertsPending[0] == lastPos.ExitAlert) {
						string msg = "EXPECTED: I have and open lastPosition with .ExitAlert=alertsPending[0]";
					} else {
						string msg = "UNEXPECTED: pending alert doesn't relate to lastPosition; who is here?";
					}
				}
				if (positionsOpenNowCount > 1) {
					string msg = "EXPECTED: I got multiple positions[" + positionsOpenNowCount + "]";
					if (snap.PositionsOpenNow[0] == lastPos) {
						msg += "50/50: positionsMaster.Last = positionsOpenNow.First";
					}
				}
				return;
			}

			if (barStaticFormed.ParentBarsIndex == 30) {
				Debugger.Break();
				StreamingDataSnapshot streaming = this.Executor.DataSource.StreamingProvider.StreamingDataSnapshot;
				Quote lastQuote = streaming.LastQuoteGetForSymbol(barStaticFormed.Symbol);
				double priceForMarketOrder = streaming.LastQuoteGetPriceForMarketOrder(barStaticFormed.Symbol);
			}


			if (barStaticFormed.Close > barStaticFormed.Open) {
				string msg = "BuyAtMarket@" + barStaticFormed.ParentBarsIdent;
				Position buyPlaced = BuyAtMarket(barStreaming, msg);
				//Debugger.Break();
			} else {
				string msg = "ShortAtMarket@" + barStaticFormed.ParentBarsIdent;
				Position shortPlaced = ShortAtMarket(barStreaming, msg);
				//Debugger.Break();
			}
			//base.Executor.ChartShadow.LineDrawModify(...);
		}