Ejemplo n.º 1
0
        public ChartSettingsForm(ChartForm activeChart, IList<ChartForm> allCharts)
        {
            InitializeComponent();

            Localizer.LocalizeControl(this);
            this.activeChart = activeChart;
            this.allCharts = allCharts;
            cbYAxis.Items.AddRange(EnumItem<YAxisAlignment>.items.Cast<object>().ToArray());
            cbChartType.Items.AddRange(EnumItem<StockSeries.CandleDrawMode>.items.Cast<object>().ToArray());
            cbTheme.Items.AddRange(EnumItem<ChartControl.Themes>.items.Cast<object>().ToArray());

            // компонент выбора цветовой схемы
            colorPicker = new ColorSchemePicker(pictureBoxCandle);
            colorPicker.OnPickColor += colorPicker_OnPickColor;
            cbUseMarkerPrice.Checked = activeChart == null ? true : activeChart.chart.chart.StockSeries.ShowLastQuote;
            cbAutoScroll.Checked = activeChart == null ? true : activeChart.chart.chart.StockSeries.AutoScroll;
            InitColorPicker();

            // заполнить значения полей
            if (activeChart != null)
                InitFields(activeChart);
            else
            {
                InitFields(allCharts);
                btnAccept.Enabled = false;
            }
        }
Ejemplo n.º 2
0
        public ChartSettingsForm(ChartForm activeChart, IList <ChartForm> allCharts)
        {
            InitializeComponent();

            Localizer.LocalizeControl(this);
            this.activeChart = activeChart;
            this.allCharts   = allCharts;
            cbYAxis.Items.AddRange(EnumItem <YAxisAlignment> .items.Cast <object>().ToArray());
            cbChartType.Items.AddRange(EnumItem <StockSeries.CandleDrawMode> .items.Cast <object>().ToArray());
            cbTheme.Items.AddRange(EnumItem <ChartControl.Themes> .items.Cast <object>().ToArray());

            // компонент выбора цветовой схемы
            colorPicker              = new ColorSchemePicker(pictureBoxCandle);
            colorPicker.OnPickColor += colorPicker_OnPickColor;
            cbUseMarkerPrice.Checked = activeChart == null ? true : activeChart.chart.chart.StockSeries.ShowLastQuote;
            cbAutoScroll.Checked     = activeChart == null ? true : activeChart.chart.chart.StockSeries.AutoScroll;
            InitColorPicker();

            // заполнить значения полей
            if (activeChart != null)
            {
                InitFields(activeChart);
            }
            else
            {
                InitFields(allCharts);
                btnAccept.Enabled = false;
            }
        }
Ejemplo n.º 3
0
 private void ApplySeriesSettingsToChart(ChartForm chart)
 {
     chart.chart.seriesTurnBar.fibonacciSeries        = tbTurnBarFiboSequence.Text.ToIntArrayUniform();
     chart.chart.seriesTurnBar.fibonacciMarks         = tbTurnBarFiboMarks.Text.ToIntArrayUniform();
     chart.chart.seriesTurnBar.fibonacciTurnBarFilter = tbTurnBarFilter.Text.ToInt();
     chart.chart.seriesTurnBar.DontSumDegree          = cbTurnBarsDontSumDegrees.Checked;
     chart.chart.chart.RightBars = tbShiftBars.Text.ToInt();
 }
Ejemplo n.º 4
0
        private void InitFields(ChartForm chart)
        {
            InitFieldsSeries(new List <ChartForm> {
                chart
            });
            tbShiftBars.Text          = chart.chart.chart.StockSeries.BarOffset.ToString();
            cbChartType.SelectedIndex = EnumItem <StockSeries.CandleDrawMode> .items.FindIndex(m => m.Value == chart.chart.chart.StockSeries.BarDrawMode);

            cbTheme.SelectedIndex = EnumItem <ChartControl.Themes> .items.FindIndex(s => s.Value == chart.chart.chart.visualSettings.Theme);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Получение шаблона из toolset.xml и применение его к графику
        /// </summary>
        /// <param name="templateName">имя щаблона, который нужно применить</param>
        /// <param name="child">форма, на которой распологается график</param>
        private static void ApplyTemplate(string templateName, ChartForm child)
        {
            var childTemplate = ChartTemplate.GetChartTemplate(templateName);
            if (childTemplate == null) return;
            if (childTemplate.Attributes[ChartTemplate.AttributeChartSize] != null)
            child.Size = ChartTemplate.StringToSize(childTemplate.Attributes[ChartTemplate.AttributeChartSize].Value).Value;

            child.chart.LoadIndicatorSettings(childTemplate);
            child.chart.UpdateIndicatorPanesAndSeries();
        }
Ejemplo n.º 6
0
        private void AddRobotHintLineOnChart(RobotHint hint, ChartForm chart)
        {
            var pivotIndex = chart.chart.chart.StockSeries.GetIndexByCandleOpen(
                hint.Time.Value);

            var line = new TrendLine
                {
                    Comment = hint.Text,
                    DateStart = hint.Time.Value,
                    LineColor = hint.ColorLine ?? chart.chart.chart.visualSettings.SeriesForeColor,
                    ShapeFillColor = hint.ColorFill ?? chart.chart.chart.visualSettings.SeriesBackColor,
                    LineStyle = TrendLine.TrendLineStyle.Отрезок,
                    Owner = chart.chart.seriesTrendLine
                };
            if (!string.IsNullOrEmpty(hint.HintCode))
                line.Name = hint.HintCode;
            line.AddPoint(pivotIndex, hint.Price.Value);
            // точку конца отрезка сместить вправо на N свечек
            line.AddPoint(pivotIndex + 10, hint.Price.Value);
            chart.chart.seriesTrendLine.data.Add(line);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// добавить на график отрезок или звездочку, согласно размышлениям робота
        /// </summary>
        private void AddOrRemoveRobotHintOnChart(RobotMark hint, ChartForm chart)
        {
            // добавить комментарий на график?
            if (hint is RobotHint)
            {
                AddRobotHintOnChart((RobotHint)hint, chart);
                return;
            }

            // убрать комментарий с графика?
            var markClear = (RobotMarkClear) hint;
            if (hint.RobotHintType == RobotMark.HintType.Линия)
            {
                var linesToRemove = chart.chart.seriesTrendLine.data.Where(l => l.Name == markClear.HintCode).ToList();
                foreach (var line in linesToRemove)
                    chart.chart.seriesTrendLine.RemoveObjectFromList(line);
            }
            else
            {
                var asteriskToRemove = chart.chart.seriesAsteriks.data.Where(l => l.Name == markClear.HintCode).ToList();
                foreach (var asteriks in asteriskToRemove)
                    chart.chart.seriesAsteriks.RemoveObjectFromList(asteriks);
            }
        }
Ejemplo n.º 8
0
 private static ChartWindowSettings GetChildSettings(ChartForm child)
 {
     var childSets = new ChartWindowSettings
                         {
                             WindowSize = new Size(
                                 child.WindowState != FormWindowState.Normal ?
                                         child.RestoreBounds.Width : child.Width,
                                 child.WindowState != FormWindowState.Normal  ?
                                         child.RestoreBounds.Height : child.Height),
                             WindowPos = new Point(
                                 child.WindowState != FormWindowState.Normal ?
                                 child.RestoreBounds.Left : child.Left,
                                 child.WindowState != FormWindowState.Normal ?
                                 child.RestoreBounds.Top : child.Top),
                             WindowState = child.WindowState.ToString(),
                             UniqueId = child.UniqueId,
                             TabPageId = child.bookmarkId
                         };
     child.InitChartSettings(childSets);
     return childSets;
 }
Ejemplo n.º 9
0
 /// <summary>
 /// закрыть окно инструмента и снова открыть его
 /// не подгружать котировки с сервера
 /// </summary>        
 public void ReopenChild(ChartForm child)
 {
     // получить настройки графика
     var childSets = GetChildSettings(child);
     UserSettings.Instance.ChartSetsList.Add(childSets);
     // закрыть окошко
     child.Close();
     // открыть окошко
     // !! не загружаются объекты и индикаторы
     LoadChildChart(childSets, null, null, null, null, false);
 }
Ejemplo n.º 10
0
        private void SetupChartForm(ChartForm child)
        {
            child.MdiParent = this;
            child.bookmarkId = bookmarkStrip.SelectedBookmark.Id;
            child.chart.receiveMarketOrders += () => MarketOrdersStorage.Instance.MarketOrders;
            child.chart.receivePendingOrders += () => MarketOrdersStorage.Instance.PendingOrders;
            child.chart.enforceClosedOrdersUpdate += HistoryOrderStorage.Instance.HurryUpUpdate;
            child.chart.getOuterCharts += GetChartsListByIds;
            child.chart.EnableExtendedVisualStyles = UserSettings.Instance.EnableExtendedThemes;
            child.chart.OnScaleChanged += ChartScaleChanged;
            child.chart.CursorCrossIsUpdated += ChartCrossChanged;
            child.chart.ChartToolChanged += OnChartToolChanged;
            child.chart.PublishTradeSignal += OnPublishTradeSignal;
            child.chart.MakeNewTextSignal += OnMakeNewSignalMessage;
            child.chart.ScriptMenuItemActivated += ChartScriptMenuItemActivated;
            child.chart.getRobotsByTicker += ticker =>
                {
                    var allRobots = RobotFarm.GetRobotCopies();
                    return allRobots.Where(r => r.Graphics.Any(g => g.a == ticker)).Select(r => r.GetUniqueName()).ToList();
                };
            child.chart.onRobotSelected += robotUniqueName =>
                {
                    var state = robotFarm.State;
                    if (state == RobotFarm.RobotFarmState.Started)
                        ShowRobotStateDialog(robotUniqueName);
                    else if (state == RobotFarm.RobotFarmState.Stopped)
                        ShowRobotPortfolioDialog(robotUniqueName);
                };

            AddScriptsToChart(child.chart);

            child.chart.getAccountId += () =>
                {
                    if (AccountStatus.Instance.isAuthorized)
                        return AccountStatus.Instance.accountID;
                    OpenLoginDialog();
                    if (AccountStatus.Instance.isAuthorized)
                        return AccountStatus.Instance.accountID;
                    return null;
                };
            child.chart.makeTrade += MakeTrade;
            child.chart.NewOrder += PlaceNewOrder;
            child.chart.ShowQuoteArchive += delegate(string symbol)
                                                {
                                                    new QuoteBaseForm(symbol).ShowDialog();
                                                };
            child.chart.SyncQuoteHistory += delegate(List<string> tickers, DateTime timeStart, bool showIntervalDlg)
                                                {
                                                    UpdateTickersCacheForRobotsChooseIntervals(
                                                        tickers.ToDictionary(t => t,
                                                                             t => timeStart), showIntervalDlg, true);
                                                };
            child.chart.EditMarketOrders += orderIds => new MultyOrdersEditForm(orderIds).ShowDialog();
            child.chart.getDefaultFastDealVolumes += () => UserSettings.Instance.FastDealVolumes;
            child.chart.getFavoriteIndicators += () => UserSettings.Instance.FavoriteIndicators;
            child.chart.getAllNewsByChannel += channel => NewsLocalStorage.Instance.GetNews(channel);
            child.chart.FavoriteIndicatorsAreUpdated += indis =>
                                                            {
                                                                UserSettings.Instance.FavoriteIndicators = indis.Distinct().ToList();
                                                                UserSettings.Instance.SaveSettings();
                                                            };
            child.chart.UpdateFastVolumes += volumes =>
                                                        {
                                                            UserSettings.Instance.FastDealVolumes = volumes;
                                                            UserSettings.Instance.SaveSettings();
                                                        };
            child.chart.ProfitByTickerRequested += s =>
                                                   new ProfitByTickerForm(s).ShowDialog();
            child.chart.OpenScriptSettingsDialog += () =>
                new ChartToolsSetupForm(lstGlyph32, ChartToolsSetupForm.ChartToolsFormTab.Scripts).ShowDialog();
            child.chart.VisualSettingsSetupCalled += ShowVisualSettingsDialog;
            child.chart.OnShowWindowEditMarketOrder += order => new OrderDlg(OrderDlg.OrderDialogMode.OrderEditMarket, order.ID).ShowDialog();
            child.chart.OnShowWindowInfoOnClosedOrder += order => new PositionForm(order).ShowDialog();
            child.chart.OnEditMarketOrderRequest += order => SendEditMarketRequestSafe(order);
            child.chart.PendingOrdersUpdated += OnPendingOrdersUpdatedChanged;
            child.chart.MarketOrdersUpdated += OnMarketOrdersChanged;
            child.chart.CloseMarketOrders += delegate(List<int> orderList)
                {
                    if (orderList.Count == 0) return;
                    if (orderList.Count == 1)
                    {
                        var accountId = AccountStatus.Instance.accountID;
                        if (accountId == 0) return;
                        if (MessageBox.Show(Localizer.GetString("MessageCloseDealQuestion"), Localizer.GetString("TitleConfirmation"),
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                            return;
                        SendCloseRequestSafe(accountId, orderList[0], PositionExitReason.ClosedFromUI);
                        return;
                    }

                    if (MessageBox.Show(
                        string.Format(Localizer.GetString("MessageCloseNDealsQuestion"), orderList.Count),
                        Localizer.GetString("TitleConfirmation"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                        DialogResult.No)
                        return;
                    var dlg = new ClosePositionsForm(orderList);
                    dlg.ShowDialog();
                };
            child.formMoved += OnChildMove;
            child.resizeEnded += OnChildResizeEnd;
            // иконки-кнопки
            var iconSet = UserSettings.Instance.SelectedChartIcons;
            child.chart.ChooseChartIconsToShow(iconSet);

            HistoryOrderStorage.Instance.OrdersUpdated += child.UpdateClosedOrdersListAsynch;
        }
Ejemplo n.º 11
0
        private void MenuNewChartClick(object sender, EventArgs e)
        {
            var dlg = new NewChartForm();
            if (dlg.ShowDialog() == DialogResult.Cancel) return;
            var smb = dlg.Ticker;
            var timeframe = dlg.Timeframe;

            // если символ введен с несоблюдением регистра - заменить на оригинал
            // если символ отсутствует - ругнуться
            var allSymbols = DalSpot.Instance.GetTickerNames();
            var chartSmb = allSymbols.FirstOrDefault(s => s.Equals(smb, StringComparison.OrdinalIgnoreCase));
            if (string.IsNullOrEmpty(chartSmb))
            {
                MessageBox.Show(string.Format(Localizer.GetString("MessageSymbolSNotFound"), smb), Localizer.GetString("TitleError"));
                return;
            }

            var child = new ChartForm(this, chartSmb)
                            {
                                chart = {Timeframe = timeframe},
                                prefferedCountDaysInRequest = dlg.DaysInRequest
                            };
            SetupChartForm(child);

            ApplyTemplate(dlg.TemplateName, child);

            child.Show();
            child.LoadQuotesAndBuildChart(true);
        }
Ejemplo n.º 12
0
        private void MainFormMdiChildActivate(object sender, EventArgs e)
        {
            if (ActiveMdiChild == null) return;
            if (ActiveMdiChild is ChartForm == false) return;

            var chart = (ChartForm) ActiveMdiChild;
            lastActiveChart = chart;

            for (var i = 0; i < cbTimeFrame.Items.Count; i++)
            {
                var tf = (ObjectWithTag<BarSettings>) cbTimeFrame.Items[i];
                if ((tf.value == chart.chart.Timeframe) == false) continue;
                // показать таймфрейм
                cbTimeFrame.SelectedIndexChanged -= CbTimeFrameSelectedIndexChanged;
                cbTimeFrame.SelectedIndex = i;
                cbTimeFrame.SelectedIndexChanged += CbTimeFrameSelectedIndexChanged;
                // показать заголовок
                return;
            }
        }
Ejemplo n.º 13
0
        private void LoadChildChart(ChartWindowSettings chartInf, XmlElement nodeObjects,
            XmlElement nodeIndi, bool loadQuotesFromServer)
        {
            foreach (var childold in Charts.Where(childold => childold.UniqueId == chartInf.UniqueId
                && childold.bookmarkId == chartInf.TabPageId && childold.chart.Symbol == chartInf.Symbol))
            {
                childold.Close();
            }

            ChartForm child;
            using (new TimeLogger("new ChartForm"))
            {
                child = new ChartForm(this, chartInf) { UniqueId = chartInf.UniqueId };
                SetupChartForm(child);
                child.bookmarkId = chartInf.TabPageId;
                // если окно ссылается на несуществующую вкладку - приписать его к существующей
                var bookmark = BookmarkStorage.Instance[child.bookmarkId];
                if (bookmark == null)
                    child.bookmarkId = BookmarkStorage.Instance.bookmarks[0].Id;
            }

            using (new TimeLogger("nodeObjects"))
            {
                if (!string.IsNullOrEmpty(chartInf.Timeframe))
                    child.chart.Timeframe = new BarSettings(chartInf.Timeframe);

                // указать ветку объектов для документа
                if (nodeObjects != null) child.xmlRootObjects = nodeObjects;

                // загрузить индюки для чарта
                if (nodeIndi != null)
                {
                    child.chart.LoadIndicatorSettings(nodeIndi);
                    child.chart.UpdateIndicatorPanesAndSeries();
                }
            }

            using (new TimeLogger("child.Show()"))
            {
                // выставить размеры панелей
                child.LoadPaneLocations(chartInf);

                // применить тему оформления
                child.chart.chart.visualSettings.ApplyTheme();

                child.Show();
            }
            using (new TimeLogger("LoadQuotesAndBuildChart"))
                child.LoadQuotesAndBuildChart(loadQuotesFromServer);
            if (chartInf.FirstCandleIndex == chartInf.LastCandleIndex)
                child.chart.chart.FitChart();
            // выставить размеры и позицию
            if (chartInf.WindowSize.Width > 20 && chartInf.WindowSize.Height > 10)
                child.SetBounds(chartInf.WindowPos.X, chartInf.WindowPos.Y,
                                chartInf.WindowSize.Width, chartInf.WindowSize.Height);
            child.WindowState = (FormWindowState)Enum.Parse(typeof(FormWindowState), chartInf.WindowState);
            //tabCtrl.SelectedTab = tp;
        }
Ejemplo n.º 14
0
 private void InitFields(ChartForm chart)
 {
     InitFieldsSeries(new List<ChartForm> { chart });
     tbShiftBars.Text = chart.chart.chart.StockSeries.BarOffset.ToString();
     cbChartType.SelectedIndex = EnumItem<StockSeries.CandleDrawMode>.items.FindIndex(m => m.Value == chart.chart.chart.StockSeries.BarDrawMode);
     cbTheme.SelectedIndex = EnumItem<ChartControl.Themes>.items.FindIndex(s => s.Value == chart.chart.chart.visualSettings.Theme);
 }
Ejemplo n.º 15
0
 private void ApplySeriesSettingsToChart(ChartForm chart)
 {
     chart.chart.seriesTurnBar.fibonacciSeries = tbTurnBarFiboSequence.Text.ToIntArrayUniform();
     chart.chart.seriesTurnBar.fibonacciMarks = tbTurnBarFiboMarks.Text.ToIntArrayUniform();
     chart.chart.seriesTurnBar.fibonacciTurnBarFilter = tbTurnBarFilter.Text.ToInt();
     chart.chart.seriesTurnBar.DontSumDegree = cbTurnBarsDontSumDegrees.Checked;
     chart.chart.chart.RightBars = tbShiftBars.Text.ToInt();
 }
Ejemplo n.º 16
0
        private void AddRobotHintOnChart(RobotHint hint, ChartForm chart)
        {
            // добавить отрезочек с комментарием
            if (hint.RobotHintType == RobotMark.HintType.Линия)
            {
                AddRobotHintLineOnChart(hint, chart);
                return;
            }

            // добавить звездочку
            var toolTip = new AsteriskTooltip(hint.Title, hint.Text)
                              {
                                  Owner = chart.chart.seriesAsteriks,
                                  Price = hint.Price.Value,
                                  CandleIndex =
                                      chart.chart.chart.StockSeries.GetIndexByCandleOpen(
                                          hint.Time.Value),
                                  DateStart = hint.Time.Value,
                                  Sign = hint.Sign,
                                  Radius = 5,
                                  Shape =
                                      hint.RobotHintType == RobotMark.HintType.Стоп
                                          ? AsteriskTooltip.ShapeType.Квадрат
                                          : hint.RobotHintType == RobotMark.HintType.Тейк
                                                ? AsteriskTooltip.ShapeType.Квадрат
                                                : hint.RobotHintType == RobotMark.HintType.Покупка
                                                      ? AsteriskTooltip.ShapeType.СтрелкаВверх
                                                      : hint.RobotHintType == RobotMark.HintType.Продажа
                                                            ? AsteriskTooltip.ShapeType.СтрелкаВниз
                                                            : hint.RobotHintType ==
                                                              RobotMark.HintType.Поджатие
                                                                  ? AsteriskTooltip.ShapeType.Звезда
                                                                  : AsteriskTooltip.ShapeType.Круг
                              };
            if (!string.IsNullOrEmpty(hint.HintCode))
                toolTip.Name = hint.HintCode;
            if (hint.ColorFill.HasValue) toolTip.ColorFill = hint.ColorFill.Value;
            if (hint.ColorLine.HasValue) toolTip.ColorLine = hint.ColorLine.Value;
            if (hint.ColorText.HasValue) toolTip.ColorText = hint.ColorText.Value;

            chart.chart.seriesAsteriks.data.Add(toolTip);
        }