public override List <string> OnQuotesReceived(string[] names, CandleDataBidAsk[] quotes, bool isHistoryStartOff) { var evtList = new List <string>(); var deltaMils = lastCheckTime.HasValue ? (DateTime.Now - lastCheckTime.Value).TotalMilliseconds : int.MaxValue; if (deltaMils >= IntervalCheckMils) { lastState = CheckDeposit(); lastCheckTime = DateTime.Now; } if (lastState == StateCode.OK) { return(evtList); } // осуществить стопаут? var countStopout = new Cortege2 <int, int>(0, 0); if (lastState == StateCode.Stopout) { countStopout = PerformStopout(); } // разослать сообщение PerformDelivery(countStopout); if (countStopout.a > 0) { Logger.InfoFormat("DrawDownStopoutChecker: закрыто {0} сделок из {1}", countStopout.a, countStopout.a + countStopout.b); } return(evtList); }
/// <summary> /// обойти дерево, найдя его первую ветвь по определенным критериям /// </summary> public static SolutionNode ResolveTree(SolutionNode root, Spieler pov, Board board) { if (root.children == null || root.children.Count == 0) { return(null); } if (root.children.Count == 1) { return(root.children[0]); } var rootScore = root.children.Select(c => new Cortege2 <SolutionNode, int>(c, GetBranchScore(c, true, pov))).ToList(); // скорректировать счет оценкой ситуации !после первого же хода! if (rootScore.Count > 1) { for (var i = 0; i < rootScore.Count; i++) { var deltaScore = ComputerMind.GetScoreForProbableTurn(board, rootScore[i].a); rootScore[i] = new Cortege2 <SolutionNode, int>(rootScore[i].a, rootScore[i].b + deltaScore); } } // выбрать наибольший из меньших результатов var ind = rootScore.IndexOfMin(s => - s.b); root.BestIndex = ind; ShowChainAndLastBoard(root); var nodeBest = rootScore[ind].a; return(nodeBest); }
/// <summary> /// вернуть изображение из кеша либо /// создать изображение нужной окраски, поместить в кеш и вернуть /// из кеша /// </summary> public Bitmap GetImage(byte alpha, Color tint) { var key = new Cortege2<int, Color>(alpha, tint); if (images.ContainsKey(key)) return images[key]; var img = (Bitmap)BitmapConversion.GetOpaqueColoredImage(bmpSrc, alpha, tint); images.Add(key, img); return img; }
public QuoteHistoryFillLineControl(string ticker, Cortege2<DateTime, DateTime> interval, Image imageCancel, Action onCancel) : this() { Ticker = ticker; Interval = interval; this.imageCancel = imageCancel; this.onCancel = onCancel; }
public QuoteHistoryFillLineControl(string ticker, Cortege2 <DateTime, DateTime> interval, Image imageCancel, Action onCancel) : this() { Ticker = ticker; Interval = interval; this.imageCancel = imageCancel; this.onCancel = onCancel; }
/// <summary> /// вернуть изображение из кеша либо /// создать изображение нужной окраски, поместить в кеш и вернуть /// из кеша /// </summary> public Bitmap GetImage(byte alpha, Color tint) { var key = new Cortege2 <int, Color>(alpha, tint); if (images.ContainsKey(key)) { return(images[key]); } var img = (Bitmap)BitmapConversion.GetOpaqueColoredImage(bmpSrc, alpha, tint); images.Add(key, img); return(img); }
public SymbolArchiveInfo(string symbol, Cortege2 <DateTime, DateTime>?dateRange) { Symbol = symbol; if (dateRange.HasValue) { DateStart = dateRange.Value.a; DateEnd = dateRange.Value.b; } var record = GapMap.Instance.GetServerGaps(symbol); if (record != null && record.serverGaps != null && record.serverGaps.Count > 0) { GapsTotalString = new TimeSpan(0, (int)record.serverGaps.Sum(g => g.TotalMinutes), 0).ToStringUniform(false, false); } }
private void ExtraPriceMarkText(StringBuilder priceMarkContent) { if (!showExtraPriceMark) { return; } try { if (!dayOpenPrice.HasValue || dayOpenPrice.Value.a != DateTime.Today) { dayOpenPrice = new Cortege2 <DateTime, float?>( DateTime.Today, Chart.CandleRange.GetStartDayPrice(DateTime.Today)); } var startDayPrice = dayOpenPrice.Value.b; if (startDayPrice.HasValue && CurrentPrice != null) { var deltaPrice = DalSpot.Instance.GetPointsValue(Chart.Symbol, CurrentPrice.Value - startDayPrice.Value); var deltaPriceText = $"{deltaPrice:F0} пп"; priceMarkContent.AppendLine(deltaPriceText); if (startDayPrice.Value != 0) { var deltaPricePercent = (CurrentPrice.Value - startDayPrice.Value) * 100 / startDayPrice.Value; var deltaPricePercentText = deltaPricePercent.ToString("F2") + " %"; priceMarkContent.AppendLine(deltaPricePercentText); } } else { priceMarkContent.AppendLine("- пп"); priceMarkContent.AppendLine("- %"); } } catch (Exception ex) { Logger.Error(ex.Message, ex); } }
public void OnMarkerMoved(ChartObjectMarker marker) { var markerIndex = 0; for (var i = 0; i < markers.Length; i++) { if (markers[i] != marker) { continue; } markerIndex = i; break; } marker.RecalculateModelCoords(Owner.Owner.WorldRect, Owner.Owner.CanvasRect); var pointIndex = points.Count == 2 ? markerIndex : 0; points[pointIndex] = new Cortege2 <int, float>((int)marker.centerModel.X, (float)marker.centerModel.Y); // пересчитать отметки Фибоначчи CalculateProjections(); }
private void PerformDelivery(Cortege2 <int, int> countClosed) { if (!DeliveryEnabled) { return; } // проверка на зафлаживание var minsSinceMessage = !lastMessageTime.HasValue ? int.MaxValue : (DateTime.Now - lastMessageTime.Value).TotalMinutes; if (lastState == StateCode.Warning && minsSinceMessage < MinMinutesBetweenWarning) { return; } if (lastState == StateCode.Stopout && minsSinceMessage < MinMinutesBetweenStopout) { return; } lastMessageTime = DateTime.Now; // сформировать текст сообщения var equity = robotContext.AccountInfo.Equity; var message = lastState == StateCode.Warning ? string.Format( "Account {0}: equity is {1}, HWM is {2}. Loss is {3:f2}% - stopout is to be at {4:f2}%", robotContext.AccountInfo.ID, (int)equity, HighWaterMark, 100 * (HighWaterMark - equity) / HighWaterMark, PercentRed) : string.Format( "Account {0}: equity is {1}, HWM is {2}. Loss is {3:f2}% - stopout performed {4} closed of total {5}", robotContext.AccountInfo.ID, (int)equity, HighWaterMark, 100 * (HighWaterMark - equity) / HighWaterMark, countClosed.a, countClosed.a + countClosed.b); // разослать SendSms(message); }
private void UpdateLastQuotes(List <TickerQuoteData> quotes) { foreach (var quote in quotes) { var price = quote.bid > 0 && quote.ask > 0 ? (quote.bid + quote.ask) * 0.5f : quote.ask > 0 ? quote.ask : quote.bid; if (price == 0) { continue; } var quoteData = new Cortege2 <float, DateTime>(price, DateTime.Now); if (!lastQuotes.ContainsKey(quote.Ticker)) { lastQuotes.Add(quote.Ticker, quoteData); } else { lastQuotes[quote.Ticker] = quoteData; } } SaveLastQuotes(); }
public void Draw(Graphics g, RectangleD worldRect, Rectangle canvasRect, Brush brush, Font fnt, PenStorage penStorage, bool doDrawText) { spansProjScreenCoords.Clear(); rectanglesTextScreenCoords.Clear(); var pen = penStorage.GetPen(Color, Selected ? 2f : 1f, DashStyle.Dot); var screenPoints = points.Select(point => Conversion.WorldToScreen(new PointD(point.a, point.b), worldRect, canvasRect)).ToList(); // сохранить координаты начального отрезка (для проверки попадания) if (screenPoints.Count > 1) { spanBaseScreenCoords = new Cortege2 <Point, Point>(screenPoints[0].ToPoint(), screenPoints[1].ToPoint()); } // соединить if (Completed && HideLine == false) { g.DrawLine(pen, (float)screenPoints[0].X, (float)screenPoints[0].Y, (float)screenPoints[1].X, (float)screenPoints[1].Y); } // нарисовать кружки foreach (var point in screenPoints) { g.FillEllipse(brush, (float)point.X - 3, (float)point.Y - 3, 6, 6); g.DrawEllipse(pen, (float)point.X - 3, (float)point.Y - 3, 6, 6); } // нарисовать проекции if (points.Count < 2 || points[0].b == points[1].b || pricesProj == null) { return; } visibleParts = new List <ProjectionLinePart>(); if (IsExtension) { foreach (var price in pricesProj) { visibleParts.Add(new ProjectionLinePart(StartIndex, EndIndex, price)); } } if (IsCorrection) { foreach (var price in pricesCorr) { visibleParts.Add(new ProjectionLinePart(StartIndex, EndIndex, price)); } } // скрыть "лишние" кусочки if (HideFarParts) { DoHideFarParts(visibleParts); } foreach (var part in visibleParts) { var ptScrLeft = Conversion.WorldToScreen(new PointD(part.left, part.price), worldRect, canvasRect); var ptScrRight = Conversion.WorldToScreen(new PointD(part.right, part.price), worldRect, canvasRect); part.x1 = (float)ptScrLeft.X; part.y1 = (float)ptScrLeft.Y; part.x2 = (float)ptScrRight.X; part.y2 = (float)ptScrRight.Y; g.DrawLine(pen, (float)ptScrLeft.X, (float)ptScrLeft.Y, (float)ptScrRight.X, (float)ptScrRight.Y); // сохранить координаты spansProjScreenCoords.Add(new Cortege2 <Point, Point>( new Point((int)ptScrLeft.X, (int)ptScrLeft.Y), new Point((int)ptScrRight.X, (int)ptScrRight.Y))); } if (doDrawText) { using (var fontBrush = new SolidBrush(Color)) { var strFormat = new StringFormat { LineAlignment = StringAlignment.Center }; foreach (var part in visibleParts) { if (part.left == part.right) { continue; } var priceStr = part.price.ToStringUniformPriceFormat(false); var textSz = g.MeasureString(priceStr, fnt); if (Markers == MarkerPlacement.Слева || Markers == MarkerPlacement.ДвеМетки) { g.DrawString(priceStr, fnt, fontBrush, part.x1 - textSz.Width - 2, part.y1, strFormat); rectanglesTextScreenCoords.Add(new Rectangle((int)(part.x1 - textSz.Width - 2), (int)(part.y1 - textSz.Height / 2), (int)textSz.Width, (int)textSz.Height)); } if (Markers == MarkerPlacement.Справа || Markers == MarkerPlacement.ДвеМетки) { g.DrawString(priceStr, fnt, fontBrush, part.x2 + 2, part.y2, strFormat); rectanglesTextScreenCoords.Add(new Rectangle((int)(part.x2 + 2), (int)(part.y2 - textSz.Height / 2), (int)textSz.Width, (int)textSz.Height)); } } } } if (Selected) { DrawMarkers(g, worldRect, canvasRect); } }
private void AppendTickerData(string tickerName, Cortege2<DateTime, decimal> tickerData) { AppendTickerData(tickerName, new List<Cortege2<DateTime, decimal>> {tickerData}); }
private void AppendTickerData(string tickerName, Cortege2 <DateTime, decimal> tickerData) { AppendTickerData(tickerName, new List <Cortege2 <DateTime, decimal> > { tickerData }); }
/// <summary> /// построить эллипс по двум точкам так, чтобы он опоясывал тени свечей в своих пределах /// </summary> private bool BuildEllipseAuto(ChartEllipse editedEllipse) { if (editedEllipse.points[0].X == editedEllipse.points[1].X) { return(false); // эллипс вырожден } if (Owner.CanvasRect.Width == 0 || Owner.CanvasRect.Height == 0 || Owner.WorldRect.Width == 0 || Owner.WorldRect.Height == 0) { return(false); } // если точки эллипса следуют задом наперед - поменять их местами if (editedEllipse.points[0].X > editedEllipse.points[1].X) { var pt = editedEllipse.points[1]; editedEllipse.points[1] = editedEllipse.points[0]; editedEllipse.points[0] = pt; } // координаты в масштабе экрана PointF a = editedEllipse.points[0], b = editedEllipse.points[1]; PointF aScale = Conversion.WorldToScreen(new PointD(a.X, a.Y), Owner.WorldRect, Owner.CanvasRect).ToPointF(); PointF bScale = Conversion.WorldToScreen(new PointD(b.X, b.Y), Owner.WorldRect, Owner.CanvasRect).ToPointF(); var candles = Chart.StockSeries.Data.Candles; var start = Math.Max((int)a.X + 1, 0); var end = Math.Min((int)b.X - 1, candles.Count - 1); if (start >= end) { return(false); } // по каждой свече - эллипс должен охватывать оную Cortege2 <PointF, float>?maxEllipsePtrs = null; for (var i = start; i <= end; i++) { // кончик свечки (хай или лоу) PointF candleTip = Conversion.WorldToScreen(new PointD(i, (double)candles[i].high), Owner.WorldRect, Owner.CanvasRect).ToPointF(); var ellipsePtrs = TryMakeChartEllipse(aScale, bScale, candleTip, true); if (!maxEllipsePtrs.HasValue && ellipsePtrs.HasValue) { maxEllipsePtrs = ellipsePtrs; } else { if (ellipsePtrs.HasValue) { if (ellipsePtrs.Value.b > maxEllipsePtrs.Value.b) { maxEllipsePtrs = ellipsePtrs; } } } // тупой копипаст для лоу candleTip = Conversion.WorldToScreen(new PointD(i, (double)candles[i].low), Owner.WorldRect, Owner.CanvasRect).ToPointF(); ellipsePtrs = TryMakeChartEllipse(aScale, bScale, candleTip, true); if (!maxEllipsePtrs.HasValue && ellipsePtrs.HasValue) { maxEllipsePtrs = ellipsePtrs; } else { if (ellipsePtrs.HasValue) { if (ellipsePtrs.Value.b > maxEllipsePtrs.Value.b) { maxEllipsePtrs = ellipsePtrs; } } } } // если описывающий эллипс существует if (maxEllipsePtrs.HasValue) { var pt = Conversion.ScreenToWorld(new PointD(maxEllipsePtrs.Value.a.X, maxEllipsePtrs.Value.a.Y), Owner.WorldRect, Owner.CanvasRect).ToPointF(); if (editedEllipse.points.Count == 2) { editedEllipse.points.Add(pt); } else { editedEllipse.points[2] = pt; } } else { if (editedEllipse.points.Count == 3) { editedEllipse.points.RemoveAt(editedEllipse.points.Count - 1); } } return(true); }
public void Draw(Graphics g, RectangleD worldRect, Rectangle canvasRect, Font font, PenStorage penDic, BrushesStorage brushStorage) { spansInScreenCoords.Clear(); Draw(g, worldRect, canvasRect, penDic, brushStorage); if (linePoints.Count == 2) {// сохранить экранные координаты задающего отрезка spansInScreenCoords.Add(new Cortege2 <Point, Point>( new Point((int)screenPointA.X, (int)screenPointA.Y), new Point((int)screenPointB.X, (int)screenPointB.Y))); } if (!Point3.HasValue) { return; } PointD oldPoint0 = linePoints[0], oldPoint1 = linePoints[1]; // параллельно перенести прямую по уровням var pointC = ProjectDotOnSpan(worldRect, canvasRect); var vector = new PointD(Point3.Value.X - pointC.X, Point3.Value.Y - pointC.Y); // начальная прямая linePoints[0] = oldPoint0 + vector; linePoints[1] = oldPoint1 + vector; Draw(g, worldRect, canvasRect, penDic, brushStorage); spansInScreenCoords.Add(new Cortege2 <Point, Point>( new Point((int)screenPointA.X, (int)screenPointA.Y), new Point((int)screenPointB.X, (int)screenPointB.Y))); // нормаль var vectorScale = series.Count == 0 ? 1.0 : series[series.Count - 1] + 1; var pointC2 = pointC + vector * vectorScale; var pointArrow = Conversion.WorldToScreen(pointC + vector, worldRect, canvasRect); var screenC = Conversion.WorldToScreen(pointC, worldRect, canvasRect); var screenC2 = Conversion.WorldToScreen(pointC2, worldRect, canvasRect); using (var pen = new Pen(LineColor) { DashStyle = DashStyle.Dot }) { g.DrawLine(pen, screenC.ToPointF(), screenC2.ToPointF()); g.DrawPolygon(pen, GetArrowPoints(screenC, pointArrow)); // сохранить экранные координаты нормали spanNormalScreenCoords = new Cortege2 <Point, Point>(screenC.ToPoint(), screenC2.ToPoint()); } // ряд прямых var rectPen = penDic.GetPen(LineColor); foreach (var level in series) { var vectorScaled = vector * (1 + level); linePoints[0] = oldPoint0 + vectorScaled; linePoints[1] = oldPoint1 + vectorScaled; Draw(g, worldRect, canvasRect, penDic, brushStorage); // сохранить координаты (для проверки попадания) spansInScreenCoords.Add(new Cortege2 <Point, Point>( new Point((int)screenPointA.X, (int)screenPointA.Y), new Point((int)screenPointB.X, (int)screenPointB.Y))); // вывести подпись в рамке if (DrawText) { var whiteBrush = brushStorage.GetBrush(Color.White); var brush = brushStorage.GetBrush(LineColor); var ptText = pointC + vectorScaled; ptText = Conversion.WorldToScreen(ptText, worldRect, canvasRect); var textSz = g.MeasureString(level.ToString(), font); var textRect = new Rectangle((int)(ptText.X - textSz.Width / 2 - 2), (int)(ptText.Y - textSz.Height / 2 - 2), (int)textSz.Width + 4, (int)textSz.Height + 4); g.FillRectangle(whiteBrush, textRect); g.DrawRectangle(rectPen, textRect); g.DrawString(level.ToString(), font, brush, (float)ptText.X, (float)ptText.Y, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }); } } // восстановить начальные точки linePoints[0] = oldPoint0; linePoints[1] = oldPoint1; }
private Cortege2<double, TimeSpan> CalculateStep(Cortege2<double, DateTime> start, Point o, Point tip) { if (Step.HasValue) return Step.Value; var len = Direction == FastAxisDirection.X ? Math.Abs(tip.X - o.X) : Math.Abs(tip.Y - o.Y); var numMinSteps = len / minPixelsPerPoint; if (!IsDateTime) { var fractStep = (MaxValue.a - start.a) / numMinSteps; Math. } var fractSpan = (MaxValue.b - start.b).TotalSeconds / numMinSteps; if (fractSpan < 1) return new Cortege2<double, TimeSpan>(0, new TimeSpan(0, 0, 0, 0, (int)(fractSpan * 1000))); if (fractSpan < 60) return new Cortege2<double, TimeSpan>(0, new TimeSpan(0, 0, 5 * ((int)fractSpan / 5))); }
private void BuildSummaryOL() { if (options.Count == 0) return; // count date - level * [OI | Volume], sum OI, sum Volume var dicSumCall = new Dictionary<DateTime, Cortege3<float, float, float>>(); var dicSumPut = new Dictionary<DateTime, Cortege3<float, float, float>>(); foreach (var opt in options) { if ((AllowedOptionStyles == AllowedOptionStyle.American && opt.Style == OptionStyle.European) || (AllowedOptionStyles == AllowedOptionStyle.European && opt.Style == OptionStyle.American)) continue; var multiplier = WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? opt.OpenInterest : opt.Volume; if (opt.Type == OptionType.CALL) { var sumCall = opt.OptionLevelClose*multiplier; if (!dicSumCall.ContainsKey(opt.DatePublished)) dicSumCall.Add(opt.DatePublished, new Cortege3<float, float, float>(sumCall, opt.OpenInterest, opt.Volume)); else { sumCall += dicSumCall[opt.DatePublished].a; var totalOI = dicSumCall[opt.DatePublished].b + opt.OpenInterest; var totalVolume = dicSumCall[opt.DatePublished].c + opt.Volume; dicSumCall[opt.DatePublished] = new Cortege3<float, float, float>(sumCall, totalOI, totalVolume); } } else { var sumPut = opt.OptionLevelClose*multiplier; if (!dicSumPut.ContainsKey(opt.DatePublished)) dicSumPut.Add(opt.DatePublished, new Cortege3<float, float, float>(sumPut, opt.OpenInterest, opt.Volume)); else { sumPut += dicSumPut[opt.DatePublished].a; var totalOI = dicSumPut[opt.DatePublished].b + opt.OpenInterest; var totalVolume = dicSumPut[opt.DatePublished].c + opt.Volume; dicSumPut[opt.DatePublished] = new Cortege3<float, float, float>(sumPut, totalOI, totalVolume); } } } var sumOpts = new List<OptionData>(); foreach (var date in dicSumCall) { if (date.Value.a == 0) continue; var strike = date.Value.a/(WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? date.Value.b : date.Value.c); var opt = new OptionData(OptionType.CALL, OptionStyle.American, options[0].BaseActive, date.Key, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), strike, 0, 0, 0, (int) date.Value.b, (int) date.Value.c); sumOpts.Add(opt); } foreach (var date in dicSumPut) { if (date.Value.a == 0) continue; var strike = date.Value.a/(WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? date.Value.b : date.Value.c); var opt = new OptionData(OptionType.PUT, OptionStyle.American, options[0].BaseActive, date.Key, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), strike, 0, 0, 0, (int) date.Value.b, (int) date.Value.c); sumOpts.Add(opt); } // медианный уровень List<Cortege2<DateTime, float>> channelCall = null, channelPut = null, channelMid = null; if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) { channelCall = new List<Cortege2<DateTime, float>>(); channelPut = new List<Cortege2<DateTime, float>>(); channelMid = new List<Cortege2<DateTime, float>>(); } foreach (var callData in dicSumCall) { if (!dicSumPut.ContainsKey(callData.Key)) continue; var putData = dicSumPut[callData.Key]; var oi = callData.Value.b + putData.b; var volume = callData.Value.c + putData.c; var denominator = WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? oi : volume; var strike = (callData.Value.a + putData.a)/denominator; var opt = new OptionData(WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? callData.Value.b > putData.b ? OptionType.CALL : OptionType.PUT : callData.Value.c > putData.c ? OptionType.CALL : OptionType.PUT, OptionStyle.American, options[0].BaseActive, callData.Key, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), strike, 0, 0, 0, (int) oi, (int) volume); // добавить мед. уровень if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) channelMid.Add(new Cortege2<DateTime, float>( opt.DatePublished, opt.OptionLevelClose)); else AddOptionLevel(opt, true); } foreach (var opt in sumOpts) { if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) { var pivot = new Cortege2<DateTime, float>(opt.DatePublished, opt.OptionLevelClose); if (opt.Type == OptionType.CALL) channelCall.Add(pivot); else channelPut.Add(pivot); } else AddOptionLevel(opt, false); } // построить каналы a-la Bollinger? if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) { BuildLineSeriesFromPivots(channelCall, seriesChannelCall); BuildLineSeriesFromPivots(channelPut, seriesChannelPut); BuildLineSeriesFromPivots(channelMid, seriesChannelMid); } }
public void Draw(Graphics g, RectangleD worldRect, Rectangle canvasRect, Font font, PenStorage penDic, BrushesStorage brushStorage) { spansInScreenCoords.Clear(); Draw(g, worldRect, canvasRect, penDic, brushStorage); if (linePoints.Count == 2) {// сохранить экранные координаты задающего отрезка spansInScreenCoords.Add(new Cortege2<Point, Point>( new Point((int) screenPointA.X, (int) screenPointA.Y), new Point((int) screenPointB.X, (int) screenPointB.Y))); } if (!Point3.HasValue) return; PointD oldPoint0 = linePoints[0], oldPoint1 = linePoints[1]; // параллельно перенести прямую по уровням var pointC = ProjectDotOnSpan(worldRect, canvasRect); var vector = new PointD(Point3.Value.X - pointC.X, Point3.Value.Y - pointC.Y); // начальная прямая linePoints[0] = oldPoint0 + vector; linePoints[1] = oldPoint1 + vector; Draw(g, worldRect, canvasRect, penDic, brushStorage); spansInScreenCoords.Add(new Cortege2<Point, Point>( new Point((int)screenPointA.X, (int)screenPointA.Y), new Point((int)screenPointB.X, (int)screenPointB.Y))); // нормаль var vectorScale = series.Count == 0 ? 1.0 : series[series.Count - 1] + 1; var pointC2 = pointC + vector * vectorScale; var pointArrow = Conversion.WorldToScreen(pointC + vector, worldRect, canvasRect); var screenC = Conversion.WorldToScreen(pointC, worldRect, canvasRect); var screenC2 = Conversion.WorldToScreen(pointC2, worldRect, canvasRect); using (var pen = new Pen(LineColor) { DashStyle = DashStyle.Dot }) { g.DrawLine(pen, screenC.ToPointF(), screenC2.ToPointF()); g.DrawPolygon(pen, GetArrowPoints(screenC, pointArrow)); // сохранить экранные координаты нормали spanNormalScreenCoords = new Cortege2<Point, Point>(screenC.ToPoint(), screenC2.ToPoint()); } // ряд прямых var rectPen = penDic.GetPen(LineColor); foreach (var level in series) { var vectorScaled = vector * (1 + level); linePoints[0] = oldPoint0 + vectorScaled; linePoints[1] = oldPoint1 + vectorScaled; Draw(g, worldRect, canvasRect, penDic, brushStorage); // сохранить координаты (для проверки попадания) spansInScreenCoords.Add(new Cortege2<Point, Point>( new Point((int)screenPointA.X, (int)screenPointA.Y), new Point((int)screenPointB.X, (int)screenPointB.Y))); // вывести подпись в рамке if (DrawText) { var whiteBrush = brushStorage.GetBrush(Color.White); var brush = brushStorage.GetBrush(LineColor); var ptText = pointC + vectorScaled; ptText = Conversion.WorldToScreen(ptText, worldRect, canvasRect); var textSz = g.MeasureString(level.ToString(), font); var textRect = new Rectangle((int) (ptText.X - textSz.Width/2 - 2), (int) (ptText.Y - textSz.Height/2 - 2), (int) textSz.Width + 4, (int) textSz.Height + 4); g.FillRectangle(whiteBrush, textRect); g.DrawRectangle(rectPen, textRect); g.DrawString(level.ToString(), font, brush, (float) ptText.X, (float) ptText.Y, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }); } } // восстановить начальные точки linePoints[0] = oldPoint0; linePoints[1] = oldPoint1; }
private void SaveFarmSettings() { var acIds = richTextBoxAccountIds.Text.ToIntArrayUniform(); if (acIds.Length == 0) acIds = accountIds.ToArray(); if (acIds.Length == 0) { MessageBox.Show("Не указаны номера счетов"); return; } XmlDocument robotsDoc = null; if (!string.IsNullOrEmpty(tbPortfolioSetsPath.Text)) { try { robotsDoc = new XmlDocument(); using (var sr = new StreamReader(tbPortfolioSetsPath.Text, Encoding.UTF8)) robotsDoc.Load(sr); if (robotsDoc.DocumentElement == null) robotsDoc = null; else if (robotsDoc.DocumentElement.ChildNodes.Count == 0) robotsDoc = null; } catch (Exception ex) { robotsDoc = null; MessageBox.Show("Ошибка загрузка документа роботов: " + ex.Message); } } var robotCountProb = tbRobotsCount.Text.ToIntArrayUniform(); for (var i = 1; i < robotCountProb.Length; i++) robotCountProb[i] += robotCountProb[i - 1]; var tickerProb = tbTickerProb.Lines.Select(new Func<string, Cortege2<string, int>?>( l => { if (string.IsNullOrEmpty(l)) return null; var pair = l.Split(new[] {':', ' ', ';', (char) Keys.Tab}, StringSplitOptions.RemoveEmptyEntries); if (pair.Length != 2) return null; return new Cortege2<string, int>(pair[0], pair[1].ToIntSafe() ?? 25); })).Where(pro => pro != null).Cast<Cortege2<string, int>>().ToArray(); for (var i = 1; i < tickerProb.Length; i++) tickerProb[i] = new Cortege2<string, int>(tickerProb[i].a, tickerProb[i - 1].b + tickerProb[i].b); var doc = new XmlDocument(); var docNode = doc.AppendChild(doc.CreateElement("farm")); using (var conn = DatabaseContext.Instance.Make()) foreach (var acId in acIds) { var accountId = acId; var owner = (from pa in conn.PLATFORM_USER_ACCOUNT join u in conn.PLATFORM_USER on pa.PlatformUser equals u.ID where pa.Account == accountId && pa.RightsMask == (int) AccountRights.Управление select u).FirstOrDefault(); if (owner == null) continue; var nodeAccount = (XmlElement) docNode.AppendChild(doc.CreateElement("Account")); var nodeAcId = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("AccountId")); nodeAcId.Attributes.Append(doc.CreateAttribute("value")).Value = acId.ToString(); var nodeLogin = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("UserLogin")); nodeLogin.Attributes.Append(doc.CreateAttribute("value")).Value = owner.Login; var nodePwrd = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("UserPassword")); nodePwrd.Attributes.Append(doc.CreateAttribute("value")).Value = owner.Password; var nodeTrade = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("TradeEnabled")); nodeTrade.Attributes.Append(doc.CreateAttribute("value")).Value = "True"; // роботы if (robotsDoc == null) continue; var rVal = rand.Next(100); var robotsCount = robotCountProb.FindIndex(v => rVal < v) + 1; for (var i = 0; i < robotsCount; i++) { var robItem = (XmlElement)robotsDoc.DocumentElement.ChildNodes[rand.Next(robotsDoc.DocumentElement.ChildNodes.Count)]; // настроить тикер (ТФ не менять) var nodeTicker = robItem.ChildNodes.Cast<XmlElement>().First(n => n.Name == "Robot.TimeSeries"); var valAttr = nodeTicker.Attributes["value"]; var pairTimeframe = valAttr.Value.Split(new[] { ' ', ',', ':', ';', '.', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (pairTimeframe.Length == 2) { rVal = rand.Next(100); var ticker = tickerProb.First(p => rVal < p.b).a; valAttr.Value = ticker + ":" + pairTimeframe[1]; } // добавить робота var imported = doc.ImportNode(robItem, true); nodeAccount.AppendChild(imported); } } // сохранить документ if (saveFarmsetsDialog.ShowDialog() != DialogResult.OK) return; tbFarmSetsPath.Text = saveFarmsetsDialog.FileName; using (var sw = new StreamWriter(saveFarmsetsDialog.FileName, false, Encoding.UTF8)) using (var xtw = new XmlTextWriter(sw) { Indentation = 4, Formatting = Formatting.Indented }) doc.Save(xtw); }
public static List<Cortege2<int, float>> GetPivots(IList<CandleData> candles, float thresholdPercent, int endIndex, ZigZagSource srcType) { var pivots = new List<Cortege2<int, float>>(); if (candles.Count == 0) return pivots; var lastPivot = new Cortege2<int, float> { a = 0, b = candles[0].open }; int lastSign = 0; // занести вершины int i = 1; for (; i <= endIndex; i++) { var candle = candles[i]; var high = srcType == ZigZagSource.HighLow ? candle.high : System.Math.Max(candle.open, candle.close); var low = srcType == ZigZagSource.HighLow ? candle.low : System.Math.Min(candle.open, candle.close); var deltaPlus = high - lastPivot.b; var deltaMinus = lastPivot.b - low; deltaPlus = deltaPlus > 0 ? 100 * deltaPlus / lastPivot.b : 0; deltaMinus = deltaMinus > 0 ? 100 * deltaMinus / lastPivot.b : 0; if (deltaPlus > thresholdPercent && ((deltaPlus > deltaMinus && lastSign == 0) || lastSign < 0)) { pivots.Add(lastPivot); lastPivot = new Cortege2<int, float> { a = i, b = high }; lastSign = 1; continue; } if (deltaMinus > thresholdPercent && ((deltaPlus <= deltaMinus && lastSign == 0) || lastSign > 0)) { pivots.Add(lastPivot); lastPivot = new Cortege2<int, float> { a = i, b = low }; lastSign = -1; continue; } if (lastSign > 0 && high > lastPivot.b) { lastPivot.b = high; lastPivot.a = i; continue; } if (lastSign < 0 && low < lastPivot.b) { lastPivot.b = low; lastPivot.a = i; continue; } } // последняя вершина if (lastSign != 0) { //var candleLast = candles[endIndex]; //var lastHigh = srcType == ZigZagSource.HighLow ? candleLast.high : // System.Math.Max(candleLast.open, candleLast.close); //var lastLow = srcType == ZigZagSource.HighLow ? candleLast.low : // System.Math.Min(candleLast.open, candleLast.close); //pivots.Add(new Cortege2<int, float> //{ // a = endIndex, // b = lastSign > 0 ? lastHigh : lastLow //}); pivots.Add(lastPivot); } return pivots; }
public Cortege2<DateTime, DateTime>? LoadFromFile(string quoteDir, string symbol) { if (string.IsNullOrEmpty(quoteDir)) throw new ArgumentException("LoadFromFile - директория пуста", "quoteDir"); if (string.IsNullOrEmpty(symbol)) throw new ArgumentException("LoadFromFile - котировка не указана", "symbol"); var fileName = quoteDir + "\\" + symbol + ".quote"; if (!File.Exists(fileName)) return null; // прочитать файл List<CandleData> fileCandles; try { fileCandles = CandleData.LoadFromFile(fileName, symbol); } catch (Exception ex) { Logger.ErrorFormat("Ошибка в AtomCandleStorage.LoadFromFile({0}): {1}", symbol, ex); return null; } if (fileCandles == null || fileCandles.Count == 0) return null; if (!locker.TryEnterWriteLock(LockTimeout)) { Logger.ErrorFormat("Ошибка в AtomCandleStorage.LoadFromFile({0}): невозможно получить доступ на запись", symbol); return null; } // записать в словарь var dates = new Cortege2<DateTime, DateTime>(fileCandles[0].timeOpen, fileCandles[fileCandles.Count - 1].timeOpen); try { if (candles.ContainsKey(symbol)) candles[symbol] = new ThreadSafeCandleList(fileCandles); else candles.Add(symbol, new ThreadSafeCandleList(fileCandles)); } finally { locker.ExitWriteLock(); } return dates; }
public Cortege2 <DateTime, DateTime>?LoadFromFile(string quoteDir, string symbol) { if (string.IsNullOrEmpty(quoteDir)) { throw new ArgumentException("LoadFromFile - директория пуста", "quoteDir"); } if (string.IsNullOrEmpty(symbol)) { throw new ArgumentException("LoadFromFile - котировка не указана", "symbol"); } var fileName = quoteDir + "\\" + symbol + ".quote"; if (!File.Exists(fileName)) { return(null); } // прочитать файл List <CandleData> fileCandles; try { fileCandles = CandleData.LoadFromFile(fileName, symbol); } catch (Exception ex) { Logger.ErrorFormat("Ошибка в AtomCandleStorage.LoadFromFile({0}): {1}", symbol, ex); return(null); } if (fileCandles == null || fileCandles.Count == 0) { return(null); } if (!locker.TryEnterWriteLock(LockTimeout)) { Logger.ErrorFormat("Ошибка в AtomCandleStorage.LoadFromFile({0}): невозможно получить доступ на запись", symbol); return(null); } // записать в словарь var dates = new Cortege2 <DateTime, DateTime>(fileCandles[0].timeOpen, fileCandles[fileCandles.Count - 1].timeOpen); try { if (candles.ContainsKey(symbol)) { candles[symbol] = new ThreadSafeCandleList(fileCandles); } else { candles.Add(symbol, new ThreadSafeCandleList(fileCandles)); } } finally { locker.ExitWriteLock(); } return(dates); }
private void UpdateLastQuotes(List<TickerQuoteData> quotes) { foreach (var quote in quotes) { var price = quote.bid > 0 && quote.ask > 0 ? (quote.bid + quote.ask)*0.5f : quote.ask > 0 ? quote.ask : quote.bid; if (price == 0) continue; var quoteData = new Cortege2<float, DateTime>(price, DateTime.Now); if (!lastQuotes.ContainsKey(quote.Ticker)) lastQuotes.Add(quote.Ticker, quoteData); else lastQuotes[quote.Ticker] = quoteData; } SaveLastQuotes(); }
public void Draw(Graphics g, RectangleD worldRect, Rectangle canvasRect, Brush brush, Font fnt, PenStorage penStorage, bool doDrawText) { spansProjScreenCoords.Clear(); rectanglesTextScreenCoords.Clear(); var pen = penStorage.GetPen(Color, Selected ? 2f : 1f, DashStyle.Dot); var screenPoints = points.Select(point => Conversion.WorldToScreen(new PointD(point.a, point.b), worldRect, canvasRect)).ToList(); // сохранить координаты начального отрезка (для проверки попадания) if (screenPoints.Count > 1) spanBaseScreenCoords = new Cortege2<Point, Point>(screenPoints[0].ToPoint(), screenPoints[1].ToPoint()); // соединить if (Completed && HideLine == false) g.DrawLine(pen, (float)screenPoints[0].X, (float)screenPoints[0].Y, (float)screenPoints[1].X, (float)screenPoints[1].Y); // нарисовать кружки foreach (var point in screenPoints) { g.FillEllipse(brush, (float)point.X - 3, (float)point.Y - 3, 6, 6); g.DrawEllipse(pen, (float)point.X - 3, (float)point.Y - 3, 6, 6); } // нарисовать проекции if (points.Count < 2 || points[0].b == points[1].b || pricesProj == null) return; visibleParts = new List<ProjectionLinePart>(); if (IsExtension) { foreach (var price in pricesProj) { visibleParts.Add(new ProjectionLinePart(StartIndex, EndIndex, price)); } } if (IsCorrection) { foreach (var price in pricesCorr) { visibleParts.Add(new ProjectionLinePart(StartIndex, EndIndex, price)); } } // скрыть "лишние" кусочки if (HideFarParts) DoHideFarParts(visibleParts); foreach (var part in visibleParts) { var ptScrLeft = Conversion.WorldToScreen(new PointD(part.left, part.price), worldRect, canvasRect); var ptScrRight = Conversion.WorldToScreen(new PointD(part.right, part.price), worldRect, canvasRect); part.x1 = (float)ptScrLeft.X; part.y1 = (float)ptScrLeft.Y; part.x2 = (float)ptScrRight.X; part.y2 = (float)ptScrRight.Y; g.DrawLine(pen, (float)ptScrLeft.X, (float)ptScrLeft.Y, (float)ptScrRight.X, (float)ptScrRight.Y); // сохранить координаты spansProjScreenCoords.Add(new Cortege2<Point, Point>( new Point((int)ptScrLeft.X, (int)ptScrLeft.Y), new Point((int)ptScrRight.X, (int)ptScrRight.Y))); } if (doDrawText) { using (var fontBrush = new SolidBrush(Color)) { var strFormat = new StringFormat { LineAlignment = StringAlignment.Center }; foreach (var part in visibleParts) { if (part.left == part.right) continue; var priceStr = part.price.ToStringUniformPriceFormat(false); var textSz = g.MeasureString(priceStr, fnt); if (Markers == MarkerPlacement.Слева || Markers == MarkerPlacement.ДвеМетки) { g.DrawString(priceStr, fnt, fontBrush, part.x1 - textSz.Width - 2, part.y1, strFormat); rectanglesTextScreenCoords.Add(new Rectangle((int)(part.x1 - textSz.Width - 2), (int)(part.y1 - textSz.Height / 2), (int)textSz.Width, (int)textSz.Height)); } if (Markers == MarkerPlacement.Справа || Markers == MarkerPlacement.ДвеМетки) { g.DrawString(priceStr, fnt, fontBrush, part.x2 + 2, part.y2, strFormat); rectanglesTextScreenCoords.Add(new Rectangle((int)(part.x2 + 2), (int)(part.y2 - textSz.Height / 2), (int)textSz.Width, (int)textSz.Height)); } } } } if (Selected) DrawMarkers(g, worldRect, canvasRect); }
public override List<string> OnQuotesReceived(string[] names, CandleDataBidAsk[] quotes, bool isHistoryStartOff) { var evtList = new List<string>(); var deltaMils = lastCheckTime.HasValue ? (DateTime.Now - lastCheckTime.Value).TotalMilliseconds : int.MaxValue; if (deltaMils >= IntervalCheckMils) { lastState = CheckDeposit(); lastCheckTime = DateTime.Now; } if (lastState == StateCode.OK) return evtList; // осуществить стопаут? var countStopout = new Cortege2<int, int>(0, 0); if (lastState == StateCode.Stopout) countStopout = PerformStopout(); // разослать сообщение PerformDelivery(countStopout); if (countStopout.a > 0) { Logger.InfoFormat("DrawDownStopoutChecker: закрыто {0} сделок из {1}", countStopout.a, countStopout.a + countStopout.b); } return evtList; }
public void OnMarkerMoved(ChartObjectMarker marker) { var markerIndex = 0; for (var i = 0; i < markers.Length; i++) { if (markers[i] != marker) continue; markerIndex = i; break; } marker.RecalculateModelCoords(Owner.Owner.WorldRect, Owner.Owner.CanvasRect); var pointIndex = points.Count == 2 ? markerIndex : 0; points[pointIndex] = new Cortege2<int, float>((int)marker.centerModel.X, (float)marker.centerModel.Y); // пересчитать отметки Фибоначчи CalculateProjections(); }
private void PerformDelivery(Cortege2<int, int> countClosed) { if (!DeliveryEnabled) return; // проверка на зафлаживание var minsSinceMessage = !lastMessageTime.HasValue ? int.MaxValue : (DateTime.Now - lastMessageTime.Value).TotalMinutes; if (lastState == StateCode.Warning && minsSinceMessage < MinMinutesBetweenWarning) return; if (lastState == StateCode.Stopout && minsSinceMessage < MinMinutesBetweenStopout) return; lastMessageTime = DateTime.Now; // сформировать текст сообщения var equity = robotContext.AccountInfo.Equity; var message = lastState == StateCode.Warning ? string.Format( "Account {0}: equity is {1}, HWM is {2}. Loss is {3:f2}% - stopout is to be at {4:f2}%", robotContext.AccountInfo.ID, (int) equity, HighWaterMark, 100*(HighWaterMark - equity)/HighWaterMark, PercentRed) : string.Format( "Account {0}: equity is {1}, HWM is {2}. Loss is {3:f2}% - stopout performed {4} closed of total {5}", robotContext.AccountInfo.ID, (int) equity, HighWaterMark, 100*(HighWaterMark - equity)/HighWaterMark, countClosed.a, countClosed.a + countClosed.b); // разослать SendSms(message); }
private Cortege2<double, TimeSpan> CalculateStep(Cortege2<double, DateTime> start, Point o, Point tip) { if (Step.HasValue) return Step.Value; try { var len = Direction == FastAxisDirection.X ? Math.Abs(tip.X - o.X) : Math.Abs(tip.Y - o.Y); var numMinSteps = len/minPixelsPerPoint; if (numMinSteps < 1) return new Cortege2<double, TimeSpan>(0, TimeSpan.Zero); if (!IsDateTime) { var fractStep = (MaxValue.a - start.a)/numMinSteps; return new Cortege2<double, TimeSpan>(NearestCeilingStep(fractStep), TimeSpan.MinValue); } var fractSpan = (MaxValue.b - start.b).TotalMilliseconds/numMinSteps; var span = NearestCeilingTimeSpan(fractSpan); return new Cortege2<double, TimeSpan>(0, span); } catch { return new Cortege2<double, TimeSpan>(0, TimeSpan.MaxValue); } }
public static List <Cortege2 <int, float> > GetPivots(IList <CandleData> candles, float thresholdPercent, int endIndex, ZigZagSource srcType) { var pivots = new List <Cortege2 <int, float> >(); if (candles.Count == 0) { return(pivots); } var lastPivot = new Cortege2 <int, float> { a = 0, b = candles[0].open }; int lastSign = 0; // занести вершины int i = 1; for (; i <= endIndex; i++) { var candle = candles[i]; var high = srcType == ZigZagSource.HighLow ? candle.high : System.Math.Max(candle.open, candle.close); var low = srcType == ZigZagSource.HighLow ? candle.low : System.Math.Min(candle.open, candle.close); var deltaPlus = high - lastPivot.b; var deltaMinus = lastPivot.b - low; deltaPlus = deltaPlus > 0 ? 100 * deltaPlus / lastPivot.b : 0; deltaMinus = deltaMinus > 0 ? 100 * deltaMinus / lastPivot.b : 0; if (deltaPlus > thresholdPercent && ((deltaPlus > deltaMinus && lastSign == 0) || lastSign < 0)) { pivots.Add(lastPivot); lastPivot = new Cortege2 <int, float> { a = i, b = high }; lastSign = 1; continue; } if (deltaMinus > thresholdPercent && ((deltaPlus <= deltaMinus && lastSign == 0) || lastSign > 0)) { pivots.Add(lastPivot); lastPivot = new Cortege2 <int, float> { a = i, b = low }; lastSign = -1; continue; } if (lastSign > 0 && high > lastPivot.b) { lastPivot.b = high; lastPivot.a = i; continue; } if (lastSign < 0 && low < lastPivot.b) { lastPivot.b = low; lastPivot.a = i; continue; } } // последняя вершина if (lastSign != 0) { //var candleLast = candles[endIndex]; //var lastHigh = srcType == ZigZagSource.HighLow ? candleLast.high : // System.Math.Max(candleLast.open, candleLast.close); //var lastLow = srcType == ZigZagSource.HighLow ? candleLast.low : // System.Math.Min(candleLast.open, candleLast.close); //pivots.Add(new Cortege2<int, float> //{ // a = endIndex, // b = lastSign > 0 ? lastHigh : lastLow //}); pivots.Add(lastPivot); } return(pivots); }
private void SaveFarmSettings() { var acIds = richTextBoxAccountIds.Text.ToIntArrayUniform(); if (acIds.Length == 0) { acIds = accountIds.ToArray(); } if (acIds.Length == 0) { MessageBox.Show("Не указаны номера счетов"); return; } XmlDocument robotsDoc = null; if (!string.IsNullOrEmpty(tbPortfolioSetsPath.Text)) { try { robotsDoc = new XmlDocument(); using (var sr = new StreamReader(tbPortfolioSetsPath.Text, Encoding.UTF8)) robotsDoc.Load(sr); if (robotsDoc.DocumentElement == null) { robotsDoc = null; } else if (robotsDoc.DocumentElement.ChildNodes.Count == 0) { robotsDoc = null; } } catch (Exception ex) { robotsDoc = null; MessageBox.Show("Ошибка загрузка документа роботов: " + ex.Message); } } var robotCountProb = tbRobotsCount.Text.ToIntArrayUniform(); for (var i = 1; i < robotCountProb.Length; i++) { robotCountProb[i] += robotCountProb[i - 1]; } var tickerProb = tbTickerProb.Lines.Select(new Func <string, Cortege2 <string, int>?>( l => { if (string.IsNullOrEmpty(l)) { return(null); } var pair = l.Split(new[] { ':', ' ', ';', (char)Keys.Tab }, StringSplitOptions.RemoveEmptyEntries); if (pair.Length != 2) { return(null); } return(new Cortege2 <string, int>(pair[0], pair[1].ToIntSafe() ?? 25)); })).Where(pro => pro != null).Cast <Cortege2 <string, int> >().ToArray(); for (var i = 1; i < tickerProb.Length; i++) { tickerProb[i] = new Cortege2 <string, int>(tickerProb[i].a, tickerProb[i - 1].b + tickerProb[i].b); } var doc = new XmlDocument(); var docNode = doc.AppendChild(doc.CreateElement("farm")); using (var conn = DatabaseContext.Instance.Make()) foreach (var acId in acIds) { var accountId = acId; var owner = (from pa in conn.PLATFORM_USER_ACCOUNT join u in conn.PLATFORM_USER on pa.PlatformUser equals u.ID where pa.Account == accountId && pa.RightsMask == (int)AccountRights.Управление select u).FirstOrDefault(); if (owner == null) { continue; } var nodeAccount = (XmlElement)docNode.AppendChild(doc.CreateElement("Account")); var nodeAcId = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("AccountId")); nodeAcId.Attributes.Append(doc.CreateAttribute("value")).Value = acId.ToString(); var nodeLogin = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("UserLogin")); nodeLogin.Attributes.Append(doc.CreateAttribute("value")).Value = owner.Login; var nodePwrd = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("UserPassword")); nodePwrd.Attributes.Append(doc.CreateAttribute("value")).Value = owner.Password; var nodeTrade = (XmlElement)nodeAccount.AppendChild(doc.CreateElement("TradeEnabled")); nodeTrade.Attributes.Append(doc.CreateAttribute("value")).Value = "True"; // роботы if (robotsDoc == null) { continue; } var rVal = rand.Next(100); var robotsCount = robotCountProb.FindIndex(v => rVal < v) + 1; for (var i = 0; i < robotsCount; i++) { var robItem = (XmlElement)robotsDoc.DocumentElement.ChildNodes[rand.Next(robotsDoc.DocumentElement.ChildNodes.Count)]; // настроить тикер (ТФ не менять) var nodeTicker = robItem.ChildNodes.Cast <XmlElement>().First(n => n.Name == "Robot.TimeSeries"); var valAttr = nodeTicker.Attributes["value"]; var pairTimeframe = valAttr.Value.Split(new[] { ' ', ',', ':', ';', '.', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (pairTimeframe.Length == 2) { rVal = rand.Next(100); var ticker = tickerProb.First(p => rVal < p.b).a; valAttr.Value = ticker + ":" + pairTimeframe[1]; } // добавить робота var imported = doc.ImportNode(robItem, true); nodeAccount.AppendChild(imported); } } // сохранить документ if (saveFarmsetsDialog.ShowDialog() != DialogResult.OK) { return; } tbFarmSetsPath.Text = saveFarmsetsDialog.FileName; using (var sw = new StreamWriter(saveFarmsetsDialog.FileName, false, Encoding.UTF8)) using (var xtw = new XmlTextWriter(sw) { Indentation = 4, Formatting = Formatting.Indented }) doc.Save(xtw); }
private string Cortege2String(Cortege2<double, DateTime> c) { return IsDateTime ? c.b.ToString("dd.MM.yyyy HH:mm:ss") : c.a.ToString("f5"); }
private void BuildSummaryOL() { if (options.Count == 0) { return; } // count date - level * [OI | Volume], sum OI, sum Volume var dicSumCall = new Dictionary <DateTime, Cortege3 <float, float, float> >(); var dicSumPut = new Dictionary <DateTime, Cortege3 <float, float, float> >(); foreach (var opt in options) { if ((AllowedOptionStyles == AllowedOptionStyle.American && opt.Style == OptionStyle.European) || (AllowedOptionStyles == AllowedOptionStyle.European && opt.Style == OptionStyle.American)) { continue; } var multiplier = WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? opt.OpenInterest : opt.Volume; if (opt.Type == OptionType.CALL) { var sumCall = opt.OptionLevelClose * multiplier; if (!dicSumCall.ContainsKey(opt.DatePublished)) { dicSumCall.Add(opt.DatePublished, new Cortege3 <float, float, float>(sumCall, opt.OpenInterest, opt.Volume)); } else { sumCall += dicSumCall[opt.DatePublished].a; var totalOI = dicSumCall[opt.DatePublished].b + opt.OpenInterest; var totalVolume = dicSumCall[opt.DatePublished].c + opt.Volume; dicSumCall[opt.DatePublished] = new Cortege3 <float, float, float>(sumCall, totalOI, totalVolume); } } else { var sumPut = opt.OptionLevelClose * multiplier; if (!dicSumPut.ContainsKey(opt.DatePublished)) { dicSumPut.Add(opt.DatePublished, new Cortege3 <float, float, float>(sumPut, opt.OpenInterest, opt.Volume)); } else { sumPut += dicSumPut[opt.DatePublished].a; var totalOI = dicSumPut[opt.DatePublished].b + opt.OpenInterest; var totalVolume = dicSumPut[opt.DatePublished].c + opt.Volume; dicSumPut[opt.DatePublished] = new Cortege3 <float, float, float>(sumPut, totalOI, totalVolume); } } } var sumOpts = new List <OptionData>(); foreach (var date in dicSumCall) { if (date.Value.a == 0) { continue; } var strike = date.Value.a / (WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? date.Value.b : date.Value.c); var opt = new OptionData(OptionType.CALL, OptionStyle.American, options[0].BaseActive, date.Key, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), strike, 0, 0, 0, (int)date.Value.b, (int)date.Value.c); sumOpts.Add(opt); } foreach (var date in dicSumPut) { if (date.Value.a == 0) { continue; } var strike = date.Value.a / (WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? date.Value.b : date.Value.c); var opt = new OptionData(OptionType.PUT, OptionStyle.American, options[0].BaseActive, date.Key, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), strike, 0, 0, 0, (int)date.Value.b, (int)date.Value.c); sumOpts.Add(opt); } // медианный уровень List <Cortege2 <DateTime, float> > channelCall = null, channelPut = null, channelMid = null; if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) { channelCall = new List <Cortege2 <DateTime, float> >(); channelPut = new List <Cortege2 <DateTime, float> >(); channelMid = new List <Cortege2 <DateTime, float> >(); } foreach (var callData in dicSumCall) { if (!dicSumPut.ContainsKey(callData.Key)) { continue; } var putData = dicSumPut[callData.Key]; var oi = callData.Value.b + putData.b; var volume = callData.Value.c + putData.c; var denominator = WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? oi : volume; var strike = (callData.Value.a + putData.a) / denominator; var opt = new OptionData(WeightType == OptionLevelWeightType.ОткрытыйИнтерес ? callData.Value.b > putData.b ? OptionType.CALL : OptionType.PUT : callData.Value.c > putData.c ? OptionType.CALL : OptionType.PUT, OptionStyle.American, options[0].BaseActive, callData.Key, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), strike, 0, 0, 0, (int)oi, (int)volume); // добавить мед. уровень if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) { channelMid.Add(new Cortege2 <DateTime, float>( opt.DatePublished, opt.OptionLevelClose)); } else { AddOptionLevel(opt, true); } } foreach (var opt in sumOpts) { if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) { var pivot = new Cortege2 <DateTime, float>(opt.DatePublished, opt.OptionLevelClose); if (opt.Type == OptionType.CALL) { channelCall.Add(pivot); } else { channelPut.Add(pivot); } } else { AddOptionLevel(opt, false); } } // построить каналы a-la Bollinger? if (SummaryLevelStyle == SummaryLevelLineStyle.Каналы) { BuildLineSeriesFromPivots(channelCall, seriesChannelCall); BuildLineSeriesFromPivots(channelPut, seriesChannelPut); BuildLineSeriesFromPivots(channelMid, seriesChannelMid); } }
private string DeriveFormatFromStep(Cortege2<double, TimeSpan> step) { if (!string.IsNullOrEmpty(LabelFormat)) return LabelFormat; if (!IsDateTime) { var abs = Math.Abs(step.a); if (abs > 100) return "f0"; if (abs > 15) return "f1"; if (abs > 1) return "f2"; if (abs > 0.1) return "f3"; if (abs > 0.01) return "f4"; return "g"; } if (step.b > new TimeSpan(30, 0, 0, 0)) return LongTimeString ? "dd.MM.yyyy" : "dd.MM"; if (step.b > new TimeSpan(1, 0, 0, 0)) return LongTimeString ? "dd.MM HH:mm" : "dd.MM"; if (step.b > new TimeSpan(0, 8, 0, 0)) return LongTimeString ? "dd.MM HH:mm" : "dd HH:mm"; if (step.b > new TimeSpan(0, 1, 0, 0)) return LongTimeString ? "dd HH:mm" : "HH:mm"; if (step.b > new TimeSpan(0, 0, 0, 5)) return LongTimeString ? "HH:mm:ss" : "mm:ss"; return LongTimeString ? "mm:ss:ffff" : "ss:ffff"; }