コード例 #1
0
        private void ShowChartClick(object sender, RoutedEventArgs e)
        {
            var security = SelectedSecurity;

            CandleSeries series;

            if (IsRealTime.IsChecked == true)
            {
                var type = CandleType.GetSelectedValue <CandleTypes>().Value;

                switch (type)
                {
                case CandleTypes.TimeFrame:
                    series = new CandleSeries(typeof(TimeFrameCandle), security, TimeFrame.Value.Value.TimeOfDay);
                    break;

                case CandleTypes.Tick:
                    series = new CandleSeries(typeof(TickCandle), security, VolumeCtrl.Text.To <int>());
                    break;

                case CandleTypes.Volume:
                    series = new CandleSeries(typeof(VolumeCandle), security, VolumeCtrl.Text.To <decimal>());
                    break;

                case CandleTypes.Range:
                    series = new CandleSeries(typeof(RangeCandle), security, PriceRange.Value);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else
            {
                var timeFrame = (TimeSpan)HistoryInterval.SelectedItem;
                series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);
            }

            _chartWindows.SafeAdd(series, key =>
            {
                var wnd = new ChartWindow
                {
                    Title = "{0} {1} {2}".Put(security.Code, series.CandleType.Name.Replace("Candle", string.Empty), series.Arg)
                };

                wnd.MakeHideable();

                var area = new ChartArea();
                wnd.Chart.Areas.Add(area);

                var candlesElem = new ChartCandleElement();
                area.Elements.Add(candlesElem);

                series.ProcessCandle += candle => wnd.Chart.Draw(candlesElem, candle);

                return(wnd);
            }).Show();

            _candleManager.Start(series, (DateTime)From.Value, (DateTime)To.Value);
        }
コード例 #2
0
ファイル: MainWindow.xaml.cs プロジェクト: zyhong/StockSharp
        public MainWindow()
        {
            InitializeComponent();

            CandleSettingsEditor.Settings = new CandleSeries
            {
                CandleType = typeof(TimeFrameCandle),
                Arg        = TimeSpan.FromMinutes(5),
            };
            CandleSettingsEditor.SettingsChanged += CandleSettingsChanged;

            _logManager = new LogManager();
            _logManager.Listeners.Add(new GuiLogListener(Log));

            _logManager.Sources.Add(_realConnector);

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candlesElem = new ChartCandleElement();
            area.Elements.Add(_candlesElem);

            InitRealConnector();
            InitEmuConnector();

            GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles);
        }
コード例 #3
0
        public ChartWindow(CandleSeries candleSeries)
        {
            if (candleSeries == null)
            {
                throw new ArgumentNullException(nameof(candleSeries));
            }

            InitializeComponent();

            _candleSeries = candleSeries;
            _connector    = MainWindow.Instance.Connector;

            Chart.ChartTheme = ChartThemes.ExpressionDark;

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candleElem = new ChartCandleElement
            {
                AntiAliasing    = false,
                UpFillColor     = Colors.White,
                UpBorderColor   = Colors.Black,
                DownFillColor   = Colors.Black,
                DownBorderColor = Colors.Black,
            };

            area.Elements.Add(_candleElem);

            _connector.CandleSeriesProcessing += ProcessNewCandle;
            _connector.SubscribeCandles(_candleSeries);
        }
コード例 #4
0
        public HistoryCandlesWindow(Security security)
        {
            if (security == null)
            {
                throw new ArgumentNullException(nameof(security));
            }

            _security = security;

            InitializeComponent();
            Title = _security.Code + LocalizedStrings.Str3747;

            TimeFramePicker.ItemsSource   = IQFeedMarketDataMessageAdapter.TimeFrames;
            TimeFramePicker.SelectedIndex = 1;

            DateFromPicker.Value = DateTime.Today.AddDays(-7);
            DateToPicker.Value   = DateTime.Today;

            var area = new ChartArea();

            _candlesElem = new ChartCandleElement();
            area.Elements.Add(_candlesElem);

            Chart.Areas.Add(area);
        }
コード例 #5
0
        private void InitCharts()
        {
            Chart.ClearAreas();

            _areaComb = new ChartArea();

            var yAxis = _areaComb.YAxises.First();

            yAxis.AutoRange    = true;
            Chart.IsAutoRange  = true;
            Chart.IsAutoScroll = true;

            Chart.AddArea(_areaComb);

            _timeframe = int.Parse((string)((ComboBoxItem)Timeframe.SelectedItem).Tag);

            var series = new CandleSeries(
                typeof(TimeFrameCandle),
                _security,
                TimeSpan.FromMinutes(_timeframe));

            _candleElement1 = new ChartCandleElement()
            {
                FullTitle = "Candles"
            };
            Chart.AddElement(_areaComb, _candleElement1, series);
        }
コード例 #6
0
		public HistoryCandlesWindow(Security security)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			_security = security;

			InitializeComponent();
			Title = _security.Code + LocalizedStrings.Str3747;

			TimeFramePicker.ItemsSource = new[]
			{
				TimeSpan.FromMinutes(1),
				TimeSpan.FromMinutes(5),
				TimeSpan.FromMinutes(15),
				TimeSpan.FromMinutes(60),
				TimeSpan.FromDays(1),
				TimeSpan.FromDays(7),
				TimeSpan.FromTicks(TimeHelper.TicksPerMonth)
			};
			TimeFramePicker.SelectedIndex = 1;

			DateFromPicker.Value = DateTime.Today.AddDays(-7);
			DateToPicker.Value = DateTime.Today;

			var area = new ChartArea();
			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);

			Chart.Areas.Add(area);
		}
コード例 #7
0
ファイル: ChartWindow.xaml.cs プロジェクト: zishe/StockSharp
        public ChartWindow(CandleSeries candleSeries, DateTimeOffset?from = null, DateTimeOffset?to = null)
        {
            InitializeComponent();

            _candleSeries = candleSeries ?? throw new ArgumentNullException(nameof(candleSeries));
            _trader       = MainWindow.Instance.Trader;

            Chart.ChartTheme = ChartThemes.ExpressionDark;

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candleElem = new ChartCandleElement
            {
                AntiAliasing    = false,
                UpFillColor     = Colors.White,
                UpBorderColor   = Colors.Black,
                DownFillColor   = Colors.Black,
                DownBorderColor = Colors.Black,
            };

            area.Elements.Add(_candleElem);

            _trader.CandleSeriesProcessing += ProcessNewCandle;
            _trader.SubscribeCandles(_candleSeries, from, to);

            Title = candleSeries.ToString();
        }
コード例 #8
0
        private void ShowChartClick(object sender, RoutedEventArgs e)
        {
            var security = SelectedSecurity;

            var series = new CandleSeries(CandlesSettings.Settings.CandleType, security, CandlesSettings.Settings.Arg);

            _chartWindows.SafeAdd(series, key =>
            {
                var wnd = new ChartWindow
                {
                    Title = "{0} {1} {2}".Put(security.Code, series.CandleType.Name, series.Arg)
                };

                wnd.MakeHideable();

                var area = new ChartArea();
                wnd.Chart.Areas.Add(area);

                var candlesElem = new ChartCandleElement();
                area.Elements.Add(candlesElem);

                return(wnd);
            }).Show();

            _candleManager.Start(series);
        }
コード例 #9
0
        public ChartWindow(CandleSeries candleSeries)
        {
            InitializeComponent();

            if (candleSeries == null)
            {
                throw new ArgumentNullException(nameof(candleSeries));
            }

            _candleSeries = candleSeries;
            _connector    = MainWindow.Instance.Connector;

            Chart.ChartTheme = ChartThemes.ExpressionDark;

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candleElem = new ChartCandleElement
            {
                AntiAliasing    = false,
                UpFillColor     = Colors.White,
                UpBorderColor   = Colors.Black,
                DownFillColor   = Colors.Black,
                DownBorderColor = Colors.Black,
            };

            area.Elements.Add(_candleElem);

            var tf = (TimeSpan)candleSeries.Arg;

            _connector.CandleSeriesProcessing += ProcessNewCandles;
            _connector.SubscribeCandles(_candleSeries, tf.Ticks == 1 ? DateTime.Today : DateTime.Now.Subtract(TimeSpan.FromTicks(tf.Ticks * 10000)), DateTimeOffset.MaxValue);
        }
コード例 #10
0
        private void OnChartPanelSubscribeCandleElement(ChartCandleElement element, CandleSeries candleSeries)
        {
            _drawTimer.Cancel();

            _elements.Add(new RefPair <IChartElement, int>(element, 0));
            _drawTimer.Activate();
        }
コード例 #11
0
        private void InitCharts()
        {
            Chart.ClearAreas();

            _areaComb = new ChartArea();

            _areaComb.YAxises.Add(new ChartAxis
            {
                Id            = _chartMainYAxis,
                AutoRange     = false,
                AxisType      = ChartAxisType.Numeric,
                AxisAlignment = ChartAxisAlignment.Right,
            });

            Chart.AddArea(_areaComb);

            _timeframe = int.Parse((string)((ComboBoxItem)Timeframe.SelectedItem).Tag);
            var step = (decimal)PriceStep.Value.Value;

            var series = new CandleSeries(
                typeof(TimeFrameCandle),
                _security,
                TimeSpan.FromMinutes(_timeframe));

            _candleElement1 = new ChartCandleElement(_timeframe, step)
            {
                FullTitle = "Candles", YAxisId = _chartMainYAxis
            };
            Chart.AddElement(_areaComb, _candleElement1, series);

            var ns = typeof(IIndicator).Namespace;

            var rendererTypes = typeof(Chart).Assembly
                                .GetTypes()
                                .Where(t => !t.IsAbstract && typeof(BaseChartIndicatorPainter).IsAssignableFrom(t))
                                .ToDictionary(t => t.Name);

            var indicators = typeof(IIndicator).Assembly
                             .GetTypes()
                             .Where(t => t.Namespace == ns && !t.IsAbstract && typeof(IIndicator).IsAssignableFrom(t))
                             .Select(t =>
            {
                var name = t.Name;
                var p    = rendererTypes.TryGetValue(name + "Painter");
                if (p == null)
                {
                    if (t.Name.EndsWith("Indicator"))
                    {
                        name = name.Substring(0, name.Length - "Indicator".Length);
                    }

                    p = rendererTypes.TryGetValue(name + "Painter");
                }

                return(new IndicatorType(t, p));
            })
                             .ToArray();

            Chart.IndicatorTypes.AddRange(indicators);
        }
コード例 #12
0
        public ChartWindow(CandleSeries candleSeries, DateTime from, DateTime to)
        {
            InitializeComponent();

            if (candleSeries == null)
            {
                throw new ArgumentNullException(nameof(candleSeries));
            }

            _candleSeries = candleSeries;
            _trader       = MainWindow.Instance.Trader;

            Chart.ChartTheme = ChartThemes.ExpressionDark;

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candleElem = new ChartCandleElement
            {
                AntiAliasing    = false,
                UpFillColor     = Colors.White,
                UpBorderColor   = Colors.Black,
                DownFillColor   = Colors.Black,
                DownBorderColor = Colors.Black,
            };

            area.Elements.Add(_candleElem);

            _manager             = new CandleManager(_trader);
            _manager.Processing += ProcessNewCandles;
            _manager.Start(_candleSeries, from, to);
        }
コード例 #13
0
        public ChartWindow(CandleSeries candleSeries)
        {
            InitializeComponent();

            if (candleSeries == null)
            {
                throw new ArgumentNullException(nameof(candleSeries));
            }

            _candleSeries = candleSeries;
            _trader       = MainWindow.Instance.Trader;

            Chart.ChartTheme = "ExpressionDark";

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candleElem = new ChartCandleElement
            {
                AntiAliasing    = false,
                UpFillColor     = Colors.White,
                UpBorderColor   = Colors.Black,
                DownFillColor   = Colors.Black,
                DownBorderColor = Colors.Black,
            };

            area.Elements.Add(_candleElem);

            _trader.NewCandles += ProcessNewCandles;
            _trader.SubscribeCandles(_candleSeries, DateTime.Today - TimeSpan.FromTicks(((TimeSpan)candleSeries.Arg).Ticks * 100), DateTimeOffset.MaxValue);
        }
コード例 #14
0
		public ChartWindow(CandleSeries candleSeries)
		{
			InitializeComponent();

			if (candleSeries.IsNull())
				throw new ArgumentNullException("candleSeries");

			_candleSeries = candleSeries;
			_trader = MainWindow.Instance.Trader;

			Chart.ChartTheme = "ExpressionDark";

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candleElem = new ChartCandleElement
			{
				Antialiasing = false, 
				UpFillColor = Colors.White,
				UpBorderColor = Colors.Black,
				DownFillColor = Colors.Black,
				DownBorderColor = Colors.Black,
			};

			area.Elements.Add(_candleElem);

			_trader.NewCandles += ProcessNewCandles;
			_trader.SubscribeCandles(_candleSeries, DateTime.Today - TimeSpan.FromTicks(((TimeSpan)candleSeries.Arg).Ticks * 100), DateTimeOffset.MaxValue);
		}
コード例 #15
0
        private void InitChart(CandleSeries series)
        {
            Chart.ClearAreas();
            _area = new ChartArea();
            var yAxis = _area.YAxises.First();
            var xAxis = _area.XAxises.First();

            yAxis.AutoRange    = true;
            Chart.IsAutoRange  = true;
            Chart.IsAutoScroll = true;
            Chart.ShowOverview = true;

            _sma = new SimpleMovingAverage()
            {
                Length = (int)IntegerUpDown.Value
            };

            _candleElement = new ChartCandleElement()
            {
                FullTitle = "Candles"
            };
            _indicatorElement = new ChartIndicatorElement()
            {
                FullTitle = "SMA"
            };

            Chart.AddArea(_area);
            Chart.AddElement(_area, _candleElement, series);
            Chart.AddElement(_area, _indicatorElement);
        }
コード例 #16
0
ファイル: ChartPane.xaml.cs プロジェクト: hbwjz/StockSharp
		private void OnChartPanelSubscribeCandleElement(ChartCandleElement element, CandleSeries candleSeries)
		{
			_drawTimer.Cancel();

			_elements.Add(new RefPair<IChartElement, int>(element, 0));
			_drawTimer.Activate();
		}
コード例 #17
0
        public HistoryCandlesWindow(Security security)
        {
            if (security == null)
            {
                throw new ArgumentNullException("security");
            }

            _security = security;

            InitializeComponent();
            Title = _security.Code + LocalizedStrings.Str3747;

            TimeFramePicker.ItemsSource = new[]
            {
                TimeSpan.FromMinutes(1),
                TimeSpan.FromMinutes(5),
                TimeSpan.FromMinutes(15),
                TimeSpan.FromMinutes(60),
                TimeSpan.FromDays(1),
                TimeSpan.FromDays(7),
                TimeSpan.FromTicks(TimeHelper.TicksPerMonth)
            };
            TimeFramePicker.SelectedIndex = 1;

            DateFromPicker.Value = DateTime.Today.AddDays(-7);
            DateToPicker.Value   = DateTime.Today;

            var area = new ChartArea();

            _candlesElem = new ChartCandleElement();
            area.Elements.Add(_candlesElem);

            Chart.Areas.Add(area);
        }
コード例 #18
0
		public UnSubscribeCandleElementCommand(ChartCandleElement element)
		{
			if (element == null)
				throw new ArgumentNullException(nameof(element));

			Element = element;
		}
コード例 #19
0
ファイル: MainWindow.xaml.cs プロジェクト: simiden/StockSharp
        private void ShowChartClick(object sender, RoutedEventArgs e)
        {
            var security = Security.SelectedSecurity;
            var series   = new CandleSeries(typeof(TimeFrameCandle), security, TimeSpan.FromMinutes(5));

            _chartWindows.SafeAdd(series, key =>
            {
                var wnd = new ChartWindow
                {
                    Title = "{0} {1}".Put(security.Code, series.Arg)
                };

                wnd.MakeHideable();

                var area = new ChartArea();
                wnd.Chart.Areas.Add(area);

                var candlesElem = new ChartCandleElement();
                area.Elements.Add(candlesElem);

                _candleManager.Processing += (s, candle) => wnd.Chart.Draw(candlesElem, candle);

                return(wnd);
            }).Show();

            _candleManager.Start(series);
        }
コード例 #20
0
ファイル: ChartWindow.xaml.cs プロジェクト: hbwjz/StockSharp
		public ChartWindow(CandleSeries candleSeries, DateTime from, DateTime to)
		{
			InitializeComponent();

			if (candleSeries == null)
				throw new ArgumentNullException("candleSeries");

			_candleSeries = candleSeries;
			_trader = MainWindow.Instance.Trader;

			Chart.ChartTheme = "ExpressionDark";

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candleElem = new ChartCandleElement
			{
				Antialiasing = false, 
				UpFillColor = Colors.White,
				UpBorderColor = Colors.Black,
				DownFillColor = Colors.Black,
				DownBorderColor = Colors.Black,
			};

			area.Elements.Add(_candleElem);

			_trader.NewCandles += ProcessNewCandles;
			_trader.SubscribeCandles(_candleSeries, from, to);
		}
コード例 #21
0
        public ChartWindow(CandleSeries candleSeries, DateTime from, DateTime to)
        {
            InitializeComponent();

            if (candleSeries.IsNull())
            {
                throw new ArgumentNullException("candleSeries");
            }

            _candleSeries = candleSeries;
            _trader       = MainWindow.Instance.Trader;

            Chart.ChartTheme = "ExpressionDark";

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candleElem = new ChartCandleElement
            {
                Antialiasing    = false,
                UpFillColor     = Colors.White,
                UpBorderColor   = Colors.Black,
                DownFillColor   = Colors.Black,
                DownBorderColor = Colors.Black,
            };

            area.Elements.Add(_candleElem);

            _trader.NewCandles += ProcessNewCandles;
            _trader.SubscribeCandles(_candleSeries, from, to);
        }
コード例 #22
0
ファイル: MainWindow.xaml.cs プロジェクト: 351zyf/StockSharp
        private void InitCharts()
        {
            Chart.ClearAreas();
            Chart.OrderCreationMode = true;

            _area = new ChartArea();

            var yAxis = _area.YAxises.First();

            yAxis.AutoRange    = true;
            Chart.IsAutoRange  = true;
            Chart.IsAutoScroll = true;

            Chart.AddArea(_area);

            var series = new CandleSeries(
                typeof(TimeFrameCandle),
                _security,
                TimeSpan.FromMinutes(_timeframe));

            _candleElement = new ChartCandleElement
            {
                FullTitle = "Candles"
            };
            Chart.AddElement(_area, _candleElement, series);

            _activeOrdersElement = new ChartActiveOrdersElement
            {
                FullTitle = "Active orders"
            };
            Chart.AddElement(_area, _activeOrdersElement);
        }
コード例 #23
0
        public UnSubscribeCandleElementCommand(ChartCandleElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            Element = element;
        }
コード例 #24
0
        private void RefreshCharts()
        {
            if (Dispatcher.CheckAccess())
            {
                _dataThreadActions.Add(RefreshCharts);
                return;
            }

            this.GuiSync(() =>
            {
                Chart.ClearAreas();

                _areaComb = new ChartArea();

                var yAxis = _areaComb.YAxises.First();

                yAxis.AutoRange    = true;
                Chart.IsAutoRange  = true;
                Chart.IsAutoScroll = true;

                Chart.AddArea(_areaComb);

                var id = (SecurityId)Securities.SelectedItem;

                _security = new Security
                {
                    Id        = id.ToStringId(),
                    Code      = id.SecurityCode,
                    Type      = SecurityTypes.Future,
                    PriceStep = id.SecurityCode.StartsWith("RI", StringComparison.InvariantCultureIgnoreCase) ? 10 :
                                id.SecurityCode.Contains("ES") ? 0.25m :
                                0.01m,
                    Board = ExchangeBoard.Associated
                };

                _securityProvider.Clear();
                _securityProvider.Add(_security);

                _tradeGenerator = new RandomWalkTradeGenerator(id);
                _tradeGenerator.Init();
                _tradeGenerator.Process(_security.ToMessage());

                var series = new CandleSeries(
                    SeriesEditor.Settings.CandleType,
                    _security,
                    SeriesEditor.Settings.Arg)
                {
                    IsCalcVolumeProfile = true
                };

                _candleElement = new ChartCandleElement {
                    FullTitle = "Candles"
                };
                Chart.AddElement(_areaComb, _candleElement, series);
            });
        }
コード例 #25
0
		public ChartWindow()
		{
			InitializeComponent();

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);
		}
コード例 #26
0
        public FuturesStrategy(IChart chart, ChartCandleElement candlesElem, ChartTradeElement tradesElem,
                               ICollection <Tuple <string, BaseIndicator, ChartIndicatorElement> > indicators, CandleSeries series)
        {
            strategyChart        = chart;
            strategyCandlesChart = candlesElem;
            strategyTradesChart  = tradesElem;

            strategyIndicators = indicators;
            strategySeries     = series;
        }
コード例 #27
0
        public ChartWindow()
        {
            InitializeComponent();

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candlesElem = new ChartCandleElement();
            area.Elements.Add(_candlesElem);
        }
コード例 #28
0
		public SubscribeCandleElementCommand(ChartCandleElement element, CandleSeries candleSeries)
		{
			if (element == null)
				throw new ArgumentNullException(nameof(element));

			if (candleSeries == null)
				throw new ArgumentNullException(nameof(candleSeries));

			Element = element;
			CandleSeries = candleSeries;
		}
コード例 #29
0
        private void Chart_OnSubscribeCandleElement(ChartCandleElement el, CandleSeries ser)
        {
            _currCandle    = null;
            _historyLoaded = false;
            _allCandles.Clear();
            _updatedCandles.Clear();
            _dataThreadActions.Clear();

            Chart.Reset(new[] { el });

            LoadData(ser);
        }
コード例 #30
0
        private void ShowChartClick(object sender, RoutedEventArgs e)
        {
            var security = SelectedSecurity;

            CandleSeries series;

            if (IsRealTime.IsChecked == true)
            {
                series = new CandleSeries(RealTimeSettings.Settings.CandleType, security, RealTimeSettings.Settings.Arg);
            }
            else
            {
                var timeFrame = (TimeSpan)HistoryInterval.SelectedItem;
                series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);
            }

            _chartWindows.SafeAdd(series, key =>
            {
                var wnd = new ChartWindow
                {
                    Title = "{0} {1} {2}".Put(security.Code, series.CandleType.Name.Remove("Candle"), series.Arg)
                };

                wnd.MakeHideable();

                var area = new ChartArea();
                wnd.Chart.Areas.Add(area);

                var candlesElem = new ChartCandleElement();
                area.Elements.Add(candlesElem);

                _candleManager.Processing += (s, candle) =>
                {
                    if (s == series)
                    {
                        wnd.Chart.Draw(candlesElem, candle);
                    }
                };

                return(wnd);
            }).Show();

            if (IsRealTime.IsChecked == true)
            {
                _candleManager.Start(series, DateTime.Today, null);
            }
            else
            {
                _candleManager.Start(series, From.Value, To.Value);
            }
        }
コード例 #31
0
        private void Load_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/SettingsStorage.xml"))
            {
                var settingsStorage =
                    new XmlSerializer <SettingsStorage>().Deserialize(
                        AppDomain.CurrentDomain.BaseDirectory + "/SettingsStorage.xml");
                Chart.Load(settingsStorage);

                _area                = Chart.Areas.First();
                _candleElement       = Chart.Elements.OfType <ChartCandleElement>().First();
                _activeOrdersElement = Chart.Elements.OfType <ChartActiveOrdersElement>().First();
            }
        }
コード例 #32
0
        private void ShowChartClick(object sender, RoutedEventArgs e)
        {
            var type     = SelectedCandleType;
            var security = SelectedSecurity;

            CandleSeries series;

            switch (type)
            {
            case CandleTypes.TimeFrame:
                series = new CandleSeries(typeof(TimeFrameCandle), security, TimeFrame.Value.Value.TimeOfDay);
                break;

            case CandleTypes.Tick:
                series = new CandleSeries(typeof(TickCandle), security, VolumeCtrl.Text.To <int>());
                break;

            case CandleTypes.Volume:
                series = new CandleSeries(typeof(VolumeCandle), security, VolumeCtrl.Text.To <decimal>());
                break;

            case CandleTypes.Range:
                series = new CandleSeries(typeof(RangeCandle), security, PriceRange.Value.Clone().SetSecurity(security));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            _chartWindows.SafeAdd(series, key =>
            {
                var wnd = new ChartWindow
                {
                    Title = "{0} {1} {2}".Put(security.Code, type, series.Arg)
                };

                wnd.MakeHideable();

                var area = new ChartArea();
                wnd.Chart.Areas.Add(area);

                var candlesElem = new ChartCandleElement();
                area.Elements.Add(candlesElem);

                return(wnd);
            }).Show();

            _candleManager.Start(series);
        }
コード例 #33
0
        private void SetSource(ChartCandleElement element, CandleSeries candleSeries)
        {
            lock (_syncRoot)
            {
                var isNew = !_elementsBySeries.ContainsKey(candleSeries);

                if ((isNew || !CanProcess) && isNew)
                {
                    SubscribeSeries(candleSeries);
                }

                _elementsInfo.SafeAdd(element, e => RefTuple.Create(DateTimeOffset.MinValue, candleSeries));
                _elementsBySeries.SafeAdd(candleSeries).Add(element);
            }
        }
コード例 #34
0
		public MainWindow()
		{
			InitializeComponent();

			_logManager = new LogManager();
			_logManager.Listeners.Add(new GuiLogListener(Log));

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);

			GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles);
		}
コード例 #35
0
        private void InitChart()
        {
            Chart.ClearAreas();

            var area = new ChartArea();

            _candleElement = new ChartCandleElement();
            _tradesElem    = new ChartTradeElement {
                FullTitle = "Trade"
            };

            Chart.AddArea(area);
            Chart.AddElement(area, _candleElement);
            Chart.AddElement(area, _tradesElem);
        }
コード例 #36
0
        public SubscribeCandleElementCommand(ChartCandleElement element, CandleSeries candleSeries)
        {
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            if (candleSeries == null)
            {
                throw new ArgumentNullException(nameof(candleSeries));
            }

            Element      = element;
            CandleSeries = candleSeries;
        }
コード例 #37
0
        public MainWindow()
        {
            InitializeComponent();

            _logManager = new LogManager();
            _logManager.Listeners.Add(new GuiLogListener(Log));

            var area = new ChartArea();

            Chart.Areas.Add(area);

            _candlesElem = new ChartCandleElement();
            area.Elements.Add(_candlesElem);

            GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles);
        }
コード例 #38
0
ファイル: SmaStrategy.cs プロジェクト: reddream/StockSharp
		public SmaStrategy(IChart chart, ChartCandleElement candlesElem, ChartTradeElement tradesElem, 
			SimpleMovingAverage shortMa, ChartIndicatorElement shortElem,
			SimpleMovingAverage longMa, ChartIndicatorElement longElem,
			CandleSeries series)
		{
			_chart = chart;
			_candlesElem = candlesElem;
			_tradesElem = tradesElem;
			_shortElem = shortElem;
			_longElem = longElem;
			
			_series = series;

			ShortSma = shortMa;
			LongSma = longMa;
		}
コード例 #39
0
ファイル: SmaStrategy.cs プロジェクト: teddyDeveloper/Testing
        public SmaStrategy(IChart chart, ChartCandleElement candlesElem, ChartTradeElement tradesElem,
                           SimpleMovingAverage shortMa, ChartIndicatorElement shortElem,
                           SimpleMovingAverage longMa, ChartIndicatorElement longElem,
                           CandleSeries series)
        {
            _chart       = chart;
            _candlesElem = candlesElem;
            _tradesElem  = tradesElem;
            _shortElem   = shortElem;
            _longElem    = longElem;

            _series = series;

            ShortSma = shortMa;
            LongSma  = longMa;
        }
コード例 #40
0
		public MainWindow()
		{
			InitializeComponent();

			_logManager = new LogManager();
			_logManager.Listeners.Add(new GuiLogListener(Log));

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);

			GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles);

			Level1AddressCtrl.Text = IQFeedAddresses.DefaultLevel1Address.To<string>();
			Level2AddressCtrl.Text = IQFeedAddresses.DefaultLevel2Address.To<string>();
			LookupAddressCtrl.Text = IQFeedAddresses.DefaultLookupAddress.To<string>();
		}
コード例 #41
0
		public HistoryCandlesWindow(Security security)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			_security = security;

			InitializeComponent();
			Title = _security.Code + LocalizedStrings.Str3747;

			TimeFramePicker.ItemsSource = IQFeedMarketDataMessageAdapter.TimeFrames;
			TimeFramePicker.SelectedIndex = 1;

			DateFromPicker.Value = DateTime.Today.AddDays(-7);
			DateToPicker.Value = DateTime.Today;

			var area = new ChartArea();
			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);

			Chart.Areas.Add(area);
		}
コード例 #42
0
		private void SetSource(ChartCandleElement element, CandleSeries candleSeries)
		{
			lock (_syncRoot)
			{
				var isNew = !_elementsBySeries.ContainsKey(candleSeries);

				if ((isNew || !CanProcess) && isNew)
					SubscribeSeries(candleSeries);

				_elementsInfo.SafeAdd(element, e => RefTuple.Create(DateTimeOffset.MinValue, candleSeries));
				_elementsBySeries.SafeAdd(candleSeries).Add(element);
			}
		}
コード例 #43
0
		private void OnChartPanelSubscribeCandleElement(ChartCandleElement element, CandleSeries candleSeries)
		{
			AddElement(element, candleSeries);
		}
コード例 #44
0
		private void OnLoaded()
		{
			SecurityPicker.SecurityProvider = ConfigManager.GetService<ISecurityProvider>();

			_mainArea = ChartPanel.Areas.FirstOrDefault();

			if (_mainArea == null)
				_bufferedChart.AddArea(_mainArea = new ChartArea { Title = LocalizedStrings.Panel + " 1" });

			_candleElement = _mainArea.Elements.OfType<ChartCandleElement>().FirstOrDefault();

			if (_candleElement == null)
				_bufferedChart.AddElement(_mainArea, _candleElement = new ChartCandleElement(), CreateSeries());

			_mainArea
				.Elements
				.OfType<ChartIndicatorElement>()
				.Where(e => _indicators.TryGetValue(e) is CandlePartIndicator)
				.ForEach(e => _sourceElements.Add(((CandleSeries)_bufferedChart.GetSource(e)).Security, e));

			_bufferedChart.AddAction(() =>
			{
				_isLoaded = true;

				if (!HasError)
					StartSeries();
			});
		}
コード例 #45
0
		private void OnChartPanelSubscribeCandleElement(ChartCandleElement element, CandleSeries candleSeries)
		{
			new SubscribeCandleElementCommand(element, candleSeries).Process(this);
		}
コード例 #46
0
		private void ShowChartClick(object sender, RoutedEventArgs e)
		{
			var type = SelectedCandleType;
			var security = SelectedSecurity;

			CandleSeries series;

			switch (type)
			{
				case CandleTypes.TimeFrame:
					series = new CandleSeries(typeof(TimeFrameCandle), security, TimeFrame.Value.Value.TimeOfDay);
					break;
				case CandleTypes.Tick:
					series = new CandleSeries(typeof(TickCandle), security, VolumeCtrl.Text.To<int>());
					break;
				case CandleTypes.Volume:
					series = new CandleSeries(typeof(VolumeCandle), security, VolumeCtrl.Text.To<decimal>());
					break;
				case CandleTypes.Range:
					series = new CandleSeries(typeof(RangeCandle), security, PriceRange.Value.Clone().SetSecurity(security));
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}

			_chartWindows.SafeAdd(series, key =>
			{
				var wnd = new ChartWindow
				{
					Title = "{0} {1} {2}".Put(security.Code, type, series.Arg)
				};

				wnd.MakeHideable();

				var area = new ChartArea();
				wnd.Chart.Areas.Add(area);

				var candlesElem = new ChartCandleElement();
				area.Elements.Add(candlesElem);

				return wnd;
			}).Show();

			_candleManager.Start(series);
		}
コード例 #47
0
		private void StartClick(object sender, RoutedEventArgs e)
		{
			if (_strategy == null)
			{
				if (Portfolios.SelectedPortfolio == null)
				{
					MessageBox.Show(this, LocalizedStrings.Str3009);
					return;
				}

				// регистрируем наш тайм-фрейм
				var series = new CandleSeries(typeof(TimeFrameCandle), _lkoh, _timeFrame);

				// создаем торговую стратегию, скользящие средние на 80 5-минуток и 10 5-минуток
				_strategy = new SmaStrategy(series, new SimpleMovingAverage { Length = 80 }, new SimpleMovingAverage { Length = 10 })
				{
					Volume = 1,
					Security = _lkoh,
					Portfolio = Portfolios.SelectedPortfolio,
					Connector = _trader,
				};
				_strategy.Log += OnLog;
				_strategy.PropertyChanged += OnStrategyPropertyChanged;

				_candlesElem = new ChartCandleElement();
				_area.Elements.Add(_candlesElem);

				_longMaElem = new ChartIndicatorElement
				{
					Title = LocalizedStrings.Long,
					Color = Colors.OrangeRed
				};
				_area.Elements.Add(_longMaElem);

				_shortMaElem = new ChartIndicatorElement
				{
					Title = LocalizedStrings.Short,
					Color = Colors.RoyalBlue
				};
				_area.Elements.Add(_shortMaElem);

				IEnumerable<Candle> candles = CultureInfo.InvariantCulture.DoInCulture(() => File.ReadAllLines("LKOH_history.txt").Select(line =>
				{
					var parts = line.Split(',');
					var time = (parts[0] + parts[1]).ToDateTime("yyyyMMddHHmmss").ApplyTimeZone(TimeHelper.Moscow);
					return (Candle)new TimeFrameCandle
					{
						OpenPrice = parts[2].To<decimal>(),
						HighPrice = parts[3].To<decimal>(),
						LowPrice = parts[4].To<decimal>(),
						ClosePrice = parts[5].To<decimal>(),
						TimeFrame = _timeFrame,
						OpenTime = time,
						CloseTime = time + _timeFrame,
						TotalVolume = parts[6].To<decimal>(),
						Security = _lkoh,
						State = CandleStates.Finished,
					};
				}).ToArray());

				var lastCandleTime = default(DateTimeOffset);

				// начинаем вычислять скользящие средние
				foreach (var candle in candles)
				{
					ProcessCandle(candle);
					lastCandleTime = candle.OpenTime;
				}

				_candleManager.Start(series);

				// вычисляем временные отрезки текущей свечи
				var bounds = _timeFrame.GetCandleBounds(series.Security.ToExchangeTime(_trader.CurrentTime));

				candles = _candleManager.Container.GetCandles(series, new Range<DateTimeOffset>(lastCandleTime + _timeFrame, bounds.Min));

				foreach (var candle in candles)
				{
					ProcessCandle(candle);
				}

				_isTodaySmaDrawn = true;

				Report.IsEnabled = true;
			}

			if (_strategy.ProcessState == ProcessStates.Stopped)
			{
				// запускаем процесс получения стакана, необходимый для работы алгоритма котирования
				_trader.RegisterMarketDepth(_strategy.Security);
				_strategy.Start();
				Start.Content = LocalizedStrings.Str242;
			}
			else
			{
				_trader.UnRegisterMarketDepth(_strategy.Security);
				_strategy.Stop();
				Start.Content = LocalizedStrings.Str2421;
			}
		}
コード例 #48
0
        private void Download_OnClick(object sender, RoutedEventArgs e)
        {
            var year = SelectedYear;
            var from = From.Value ?? year.Days.First();
            var to = (To.Value ?? year.Days.Last()).EndOfDay();
            var trader = SelectedTrader;
            var tf = SelectedTimeFrame;

            var seriesSet = _securityCtrls
                .Where(pair => pair.Key.SelectedSecurity != null)
                .Select(pair => Tuple.Create(new CandleSeries(typeof(TimeFrameCandle), pair.Key.SelectedSecurity, tf), pair.Value))
                .ToArray();

            BusyIndicator.BusyContent = "Подготовка данных...";
            BusyIndicator.IsBusy = true;

            _candles.Clear();

            var trades = new Dictionary<Security, Dictionary<DateTimeOffset, Tuple<MyTrade[], MyTrade>>>();

            var worker = new BackgroundWorker { WorkerReportsProgress = true };

            worker.DoWork += (o, ea) =>
            {
                foreach (var series in seriesSet)
                {
                    var security = series.Item1.Security;
                    var candleStorage = _dataRegistry.GetCandleStorage(series.Item1, format: StorageFormats.Csv);
                    var secCandles = _candles.SafeAdd(security);

                    secCandles.Clear();
                    secCandles.AddRange(candleStorage.Load(from, to));

                    var candlesDatesCache = _candlesDates.SafeAdd(Tuple.Create(security, tf), k => new DatesCache(Path.Combine(((LocalMarketDataDrive)candleStorage.Drive.Drive).GetSecurityPath(security.ToSecurityId()), "{0}min_date.bin".Put((int)tf.TotalMinutes))));

                    var minCandleDate = candlesDatesCache.MinValue;
                    var maxCandleDate = candlesDatesCache.MaxValue;

                    if (from >= minCandleDate && to <= maxCandleDate)
                        continue;

                    var finamFrom = from;
                    var finamTo = to;

                    if (maxCandleDate != null && finamFrom >= minCandleDate && finamFrom <= maxCandleDate)
                        finamFrom = maxCandleDate.Value + TimeSpan.FromDays(1);

                    if (minCandleDate != null && finamTo >= minCandleDate && finamTo <= maxCandleDate)
                        finamTo = minCandleDate.Value - TimeSpan.FromDays(1);

                    if (finamTo <= finamFrom)
                        continue;

                    worker.ReportProgress(1, Tuple.Create(security, finamFrom, finamTo));

                    var newCandles = (tf.Ticks == 1
                        ? finamFrom.Range(finamTo, TimeSpan.FromDays(1)).SelectMany(day => _finamHistorySource.GetTrades(security, day, day)).ToEx().ToCandles<TimeFrameCandle>(tf)
                        : _finamHistorySource.GetCandles(security, tf, finamFrom, finamTo)
                        ).ToArray();

                    candleStorage.Save(newCandles);

                    foreach (var date in newCandles.Select(c => c.OpenTime.Date).Distinct())
                        candlesDatesCache.Add(date);

                    candlesDatesCache.Save();

                    // TODO
                    secCandles.AddRange(newCandles);
                }

                var traderDrive = new LocalMarketDataDrive(trader);
                var traderStorage = _traderStorages.SafeAdd(trader, key => new StorageRegistry { DefaultDrive = traderDrive });

                foreach (var series in seriesSet)
                {
                    var security = series.Item1.Security;

                    var olStorage = traderStorage.GetOrderLogStorage(security, format: StorageFormats.Csv);
                    var tradeDatesCache = _tradesDates.SafeAdd(trader, k => new DatesCache(Path.Combine(traderDrive.Path, "dates.bin")));

                    var secTrades = from
                        .Range(to, TimeSpan.FromDays(1))
                        .Intersect(year.Days)
                        .SelectMany(date =>
                        {
                            if (olStorage.Dates.Contains(date))
                                return olStorage.Load(date);

                            if (tradeDatesCache.Contains(date))
                                return Enumerable.Empty<OrderLogItem>();

                            worker.ReportProgress(2, date);

                            var loadedTrades = year.GetTrades(_securityStorage, trader, date);

                            var dateTrades = Enumerable.Empty<OrderLogItem>();

                            foreach (var group in loadedTrades.GroupBy(t => t.Order.Security))
                            {
                                var sec = group.Key;

                                traderStorage
                                    .GetOrderLogStorage(sec, format: StorageFormats.Csv)
                                    .Save(group.OrderBy(i => i.Order.Time));

                                if (group.Key == security)
                                    dateTrades = group;
                            }

                            tradeDatesCache.Add(date);
                            tradeDatesCache.Save();

                            return dateTrades;
                        })
                        .GroupBy(ol =>
                        {
                            var time = ol.Order.Time;

                            var period = security.Board.WorkingTime.GetPeriod(time.ToLocalTime(security.Board.Exchange.TimeZoneInfo));
                            if (period != null && period.Times.Length > 0)
                            {
                                var last = period.Times.Last().Max;

                                if (time.TimeOfDay >= last)
                                    time = time.AddTicks(-1);
                            }

                            return time.Truncate(tf);
                        })
                        .ToDictionary(g => g.Key, g =>
                        {
                            var candleTrades = g.Select(ol => new MyTrade
                            {
                                Order = ol.Order,
                                Trade = ol.Trade
                            })
                            .ToArray();

                            if (candleTrades.Length == 0)
                                return null;

                            var order = candleTrades[0].Order;
                            var volume = candleTrades.Sum(t1 => t1.Trade.Volume * (t1.Order.Direction == Sides.Buy ? 1 : -1));

                            if (volume == 0)
                                return Tuple.Create(candleTrades, (MyTrade)null);

                            var side = volume > 0 ? Sides.Buy : Sides.Sell;

                            volume = volume.Abs();

                            var availableVolume = volume;
                            var avgPrice = 0m;

                            foreach (var trade in candleTrades.Where(t1 => t1.Order.Direction == side))
                            {
                                var tradeVol = trade.Trade.Volume.Min(availableVolume);
                                avgPrice += trade.Trade.Price * tradeVol;

                                availableVolume -= tradeVol;

                                if (availableVolume <= 0)
                                    break;
                            }

                            avgPrice = avgPrice / volume;

                            return Tuple.Create(candleTrades, new MyTrade
                            {
                                Order = new Order
                                {
                                    Security = order.Security,
                                    Direction = side,
                                    Time = g.Key,
                                    Portfolio = order.Portfolio,
                                    Price = avgPrice,
                                    Volume = volume,
                                },
                                Trade = new Trade
                                {
                                    Security = order.Security,
                                    Time = g.Key,
                                    Volume = volume,
                                    Price = avgPrice
                                }
                            });
                        });

                    trades.Add(security, secTrades);
                }
            };

            worker.ProgressChanged += (o, ea) =>
            {
                switch (ea.ProgressPercentage)
                {
                    case 1:
                        BusyIndicator.BusyContent = "Скачивание {Item1.Id} свечей с {Item2:yyyy-MM-dd} по {Item3:yyyy-MM-dd}...".PutEx(ea.UserState);
                        break;

                    default:
                        BusyIndicator.BusyContent = "Скачивание сделок за {0:yyyy-MM-dd}...".Put(ea.UserState);
                        break;
                }
            };

            worker.RunWorkerCompleted += (o, ea) =>
            {
                BusyIndicator.IsBusy = false;

                if (ea.Error == null)
                {
                    Chart.ClearAreas();

                    _statisticManager.Reset();

                    var candlesArea = new ChartArea();
                    Chart.AddArea(candlesArea);

                    var positionArea = new ChartArea { Height = 200 };
                    Chart.AddArea(positionArea);
                    positionArea.YAxises.Clear();

                    const string equityYAxis = "Equity";

                    candlesArea.YAxises.Clear();
                    candlesArea.YAxises.Add(new ChartAxis
                    {
                        Id = equityYAxis,
                        AutoRange = true,
                        AxisType = ChartAxisType.Numeric,
                        AxisAlignment = ChartAxisAlignment.Left,
                    });
                    var equityElem = new ChartIndicatorElement
                    {
                        YAxisId = equityYAxis,
                        FullTitle = LocalizedStrings.PnL,
                        IndicatorPainter = new PnlPainter()
                    };
                    var equityInd = new SimpleMovingAverage { Length = 1 };
                    Chart.AddElement(candlesArea, equityElem);

                    var chartValues = new SortedDictionary<DateTimeOffset, IDictionary<IChartElement, object>>();
                    var pnlValues = new Dictionary<DateTimeOffset, decimal>();

                    foreach (var series in seriesSet)
                    {
                        var security = series.Item1.Security;

                        var candleYAxis = "Candles_Y_" + security.Id;

                        candlesArea.YAxises.Add(new ChartAxis
                        {
                            Id = candleYAxis,
                            AutoRange = true,
                            AxisType = ChartAxisType.Numeric,
                            AxisAlignment = ChartAxisAlignment.Right,
                        });

                        var candlesElem = new ChartCandleElement
                        {
                            ShowAxisMarker = false,
                            YAxisId = candleYAxis,
                        };
                        Chart.AddElement(candlesArea, candlesElem, series.Item1);

                        var tradesElem = new ChartTradeElement
                        {
                            BuyStrokeColor = Colors.Black,
                            SellStrokeColor = Colors.Black,
                            BuyColor = series.Item2.Buy,
                            SellColor = series.Item2.Sell,
                            FullTitle = LocalizedStrings.Str985 + " " + security.Id,
                            YAxisId = candleYAxis,
                        };
                        Chart.AddElement(candlesArea, tradesElem);

                        var posYAxis = "Pos_Y_" + security.Id;
                        positionArea.YAxises.Add(new ChartAxis
                        {
                            Id = posYAxis,
                            AutoRange = true,
                            AxisType = ChartAxisType.Numeric,
                            AxisAlignment = ChartAxisAlignment.Right,
                        });
                        var positionElem = new ChartIndicatorElement
                        {
                            FullTitle = LocalizedStrings.Str862 + " " + security.Id,
                            YAxisId = posYAxis,
                            Color = series.Item2.Position
                        };
                        var positionInd = new SimpleMovingAverage { Length = 1 };
                        Chart.AddElement(positionArea, positionElem);

                        var pnlQueue = new PnLQueue(security.ToSecurityId());
                        //var level1Info = new Level1ChangeMessage
                        //{
                        //	SecurityId = pnlQueue.SecurityId,
                        //}
                        //.TryAdd(Level1Fields.PriceStep, security.PriceStep)
                        //.TryAdd(Level1Fields.StepPrice, security.StepPrice);

                        //pnlQueue.ProcessLevel1(level1Info);

                        var pos = 0m;

                        var secTrades = trades[security];

                        var secValues = _candles[security]
                            .Select(c =>
                            {
                                if (c.State != CandleStates.Finished)
                                    c.State = CandleStates.Finished;

                                pnlQueue.ProcessLevel1(new Level1ChangeMessage
                                {
                                    SecurityId = security.ToSecurityId(),
                                }.TryAdd(Level1Fields.LastTradePrice, c.ClosePrice));

                                var values = new Dictionary<IChartElement, object>
                                {
                                    { candlesElem, c },
                                };

                                var candleTrade = secTrades.TryGetValue(c.OpenTime);

                                if (candleTrade != null)
                                {
                                    if (candleTrade.Item2 != null)
                                        values.Add(tradesElem, candleTrade.Item2);

                                    foreach (var myTrade in candleTrade.Item1)
                                    {
                                        pos += myTrade.Order.Direction == Sides.Buy ? myTrade.Trade.Volume : -myTrade.Trade.Volume;
                                        var pnl = pnlQueue.Process(myTrade.ToMessage());

                                        _statisticManager.AddMyTrade(pnl);
                                    }

                                    _statisticManager.AddPosition(c.OpenTime, pos);
                                    _statisticManager.AddPnL(c.OpenTime, pnlQueue.RealizedPnL + pnlQueue.UnrealizedPnL);
                                }

                                pnlValues[c.OpenTime] = pnlValues.TryGetValue(c.OpenTime) + (pnlQueue.RealizedPnL + pnlQueue.UnrealizedPnL);
                                values.Add(positionElem, positionInd.Process(pos));

                                return new RefPair<DateTimeOffset, IDictionary<IChartElement, object>>
                                {
                                    First = c.OpenTime,
                                    Second = values
                                };
                            })
                            .ToArray();

                        foreach (var pair in secValues)
                        {
                            var dict = chartValues.SafeAdd(pair.First, key => new Dictionary<IChartElement, object>());

                            foreach (var pair2 in pair.Second)
                            {
                                dict[pair2.Key] = pair2.Value;
                            }
                        }
                    }

                    foreach (var pair in pnlValues)
                    {
                        chartValues[pair.Key].Add(equityElem, equityInd.Process(pair.Value));
                    }

                    Chart.IsAutoRange = true;

                    try
                    {
                        Chart.Draw(chartValues.Select(p => RefTuple.Create(p.Key, p.Value)));
                    }
                    finally
                    {
                        Chart.IsAutoRange = false;
                    }
                }
                else
                {
                    new MessageBoxBuilder()
                        .Error()
                        .Owner(this)
                        .Text(ea.Error.ToString())
                        .Show();
                }
            };

            worker.RunWorkerAsync();
        }
コード例 #49
0
ファイル: MainWindow.xaml.cs プロジェクト: pantov/StockSharp
		private void InitCharts()
		{
			_candle = null;
			_lastPrice = 0m;
			_allCandles.Clear();
			_chartCombined.ClearAreas();

			_chartBindVisibleRange.ClearAreas();

			_areaComb = new ChartArea();
			_areaBVR1 = new ChartArea();
			_areaBVR2 = new ChartArea();

			_areaComb.YAxises.Add(new ChartAxis
			{
				Id = _chartMainYAxis,
				AutoRange = false,
				AxisType = ChartAxisType.Numeric,
				AxisAlignment = ChartAxisAlignment.Right,
			});

			_areaBVR2.YAxises.Add(new ChartAxis
			{
				Id = _chartMainYAxis,
				AutoRange = false,
				AxisType = ChartAxisType.Numeric,
				AxisAlignment = ChartAxisAlignment.Right,
			});

			_chartCombined.AddArea(_areaComb);
			_chartBindVisibleRange.AddArea(_areaBVR1);
			_chartBindVisibleRange.AddArea(_areaBVR2);

			_timeframe = int.Parse((string)((ComboBoxItem)_comboMainTimeframe.SelectedItem).Tag);
			var step = (decimal)_updownPriceStep.Value.Value;

			var series = new CandleSeries(
				typeof(TimeFrameCandle),
				_security,
				TimeSpan.FromMinutes(_timeframe));

			_candleElement1 = new ChartCandleElement { FullTitle = "Candles", YAxisId = _chartMainYAxis };
			_chartCombined.AddElement(_areaComb, _candleElement1, series);

			_bvElement = new ChartBoxVolumeElement(_timeframe, step) { FullTitle = "BoxVolume", YAxisId = _chartMainYAxis };
			_chartCombined.AddElement(_areaComb, _bvElement);

			_cpElement = new ChartClusterProfileElement(_timeframe, step) { FullTitle = "Cluster profile" };
			_chartBindVisibleRange.AddElement(_areaBVR1, _cpElement);

			_candleElement2 = new ChartCandleElement { FullTitle = "Candles", YAxisId = _chartMainYAxis };
			_chartBindVisibleRange.AddElement(_areaBVR2, _candleElement2, series);

			var ns = typeof(IIndicator).Namespace;

			var rendererTypes = typeof(Chart).Assembly
				.GetTypes()
				.Where(t => !t.IsAbstract && typeof(BaseChartIndicatorPainter).IsAssignableFrom(t))
				.ToDictionary(t => t.Name);

			var indicators = typeof(IIndicator).Assembly
				.GetTypes()
				.Where(t => t.Namespace == ns && !t.IsAbstract && typeof(IIndicator).IsAssignableFrom(t))
				.Select(t =>
				{
					var name = t.Name;
					var p = rendererTypes.TryGetValue(name + "Painter");
					if (p == null)
					{
						if (t.Name.EndsWith("Indicator"))
							name = name.Substring(0, name.Length - "Indicator".Length);

						p = rendererTypes.TryGetValue(name + "Painter");
					}

					return new IndicatorType(t, p);
				})
				.ToArray();

			_chartCombined.IndicatorTypes.AddRange(indicators);
			_chartBindVisibleRange.IndicatorTypes.AddRange(indicators);
		}
コード例 #50
0
ファイル: MainWindow.xaml.cs プロジェクト: yoykiee/StockSharp
		private void InitChart()
		{
			_bufferedChart.ClearAreas();
			Curve.Clear();
			PositionCurve.Clear();

			_area = new ChartArea();
			_bufferedChart.AddArea(_area);

			_candlesElem = new ChartCandleElement { ShowAxisMarker = false };
			_bufferedChart.AddElement(_area, _candlesElem);

			_tradesElem = new ChartTradeElement { FullTitle = "Сделки" };
			_bufferedChart.AddElement(_area, _tradesElem);
		}
コード例 #51
0
ファイル: MainWindow.xaml.cs プロジェクト: osya/StockSharp
		private void ShowChartClick(object sender, RoutedEventArgs e)
		{
			var security = SelectedSecurity;

			var series = new CandleSeries(CandlesSettings.Settings.CandleType, security, CandlesSettings.Settings.Arg);

			_chartWindows.SafeAdd(series, key =>
			{
				var wnd = new ChartWindow
				{
					Title = "{0} {1} {2}".Put(security.Code, series.CandleType.Name, series.Arg)
				};

				wnd.MakeHideable();

				var area = new ChartArea();
				wnd.Chart.Areas.Add(area);

				var candlesElem = new ChartCandleElement();
				area.Elements.Add(candlesElem);

				return wnd;
			}).Show();

			_candleManager.Start(series);
		}
コード例 #52
0
ファイル: MainWindow.xaml.cs プロジェクト: hbwjz/StockSharp
		private void ShowChartClick(object sender, RoutedEventArgs e)
		{
			var security = Security.SelectedSecurity;
			var series = new CandleSeries(typeof(TimeFrameCandle), security, TimeSpan.FromMinutes(5));

			_chartWindows.SafeAdd(series, key =>
			{
				var wnd = new ChartWindow
				{
					Title = "{0} {1}".Put(security.Code, series.Arg)
				};

				wnd.MakeHideable();

				var area = new ChartArea();
				wnd.Chart.Areas.Add(area);

				var candlesElem = new ChartCandleElement();
				area.Elements.Add(candlesElem);

				series.ProcessCandle += candle => wnd.Chart.Draw(candlesElem, candle);

				return wnd;
			}).Show();

			_candleManager.Start(series);
		}
コード例 #53
0
ファイル: MainWindow.xaml.cs プロジェクト: hbwjz/StockSharp
		private void ShowChartClick(object sender, RoutedEventArgs e)
		{
			var security = SelectedSecurity;

			CandleSeries series;

			if (IsRealTime.IsChecked == true)
			{
				series = new CandleSeries(RealTimeSettings.Settings.CandleType, security, RealTimeSettings.Settings.Arg);
			}
			else
			{
				var timeFrame = (TimeSpan)HistoryInterval.SelectedItem;
				series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);
			}

			_chartWindows.SafeAdd(series, key =>
			{
				var wnd = new ChartWindow
				{
					Title = "{0} {1} {2}".Put(security.Code, series.CandleType.Name.Replace("Candle", string.Empty), series.Arg)
				};

				wnd.MakeHideable();

				var area = new ChartArea();
				wnd.Chart.Areas.Add(area);

				var candlesElem = new ChartCandleElement();
				area.Elements.Add(candlesElem);

				series.ProcessCandle += candle => wnd.Chart.Draw(candlesElem, candle);

				return wnd;
			}).Show();

			if (IsRealTime.IsChecked == true)
				_candleManager.Start(series, DateTime.Today, DateTimeOffset.MaxValue);
			else
				_candleManager.Start(series, (DateTimeOffset)From.Value, (DateTimeOffset)To.Value);
		}
コード例 #54
0
ファイル: MainWindow.xaml.cs プロジェクト: osya/StockSharp
		private void ShowChartClick(object sender, RoutedEventArgs e)
		{
			var security = SelectedSecurity;

			CandleSeries series;

			if (IsRealTime.IsChecked == true)
			{
				var type = CandleType.GetSelectedValue<CandleTypes>().Value;

				switch (type)
				{
					case CandleTypes.TimeFrame:
						series = new CandleSeries(typeof(TimeFrameCandle), security, TimeFrame.Value.Value.TimeOfDay);
						break;
					case CandleTypes.Tick:
						series = new CandleSeries(typeof(TickCandle), security, VolumeCtrl.Text.To<int>());
						break;
					case CandleTypes.Volume:
						series = new CandleSeries(typeof(VolumeCandle), security, VolumeCtrl.Text.To<decimal>());
						break;
					case CandleTypes.Range:
						series = new CandleSeries(typeof(RangeCandle), security, PriceRange.Value);
						break;
					default:
						throw new ArgumentOutOfRangeException();
				}
			}
			else
			{
				var timeFrame = (TimeSpan)HistoryInterval.SelectedItem;
				series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);
			}

			_chartWindows.SafeAdd(series, key =>
			{
				var wnd = new ChartWindow
				{
					Title = "{0} {1} {2}".Put(security.Code, series.CandleType.Name.Replace("Candle", string.Empty), series.Arg)
				};

				wnd.MakeHideable();

				var area = new ChartArea();
				wnd.Chart.Areas.Add(area);

				var candlesElem = new ChartCandleElement();
				area.Elements.Add(candlesElem);

				series.ProcessCandle += candle => wnd.Chart.Draw(candlesElem, candle);

				return wnd;
			}).Show();

			_candleManager.Start(series, (DateTime)From.Value, (DateTime)To.Value);
		}
コード例 #55
0
		private void StartClick(object sender, RoutedEventArgs e)
		{
			// если были получены и инструмент, и портфель
			if (_strategy == null)
			{
				if (Portfolios.SelectedPortfolio == null)
				{
					MessageBox.Show(this, LocalizedStrings.Str3009);
					return;
				}

				// создаем скользящие средние, на 80 5-минуток и 10 5-минуток
				var longSma = new SimpleMovingAverage { Length = 80 };
				var shortSma = new SimpleMovingAverage { Length = 10 };

				// регистрируем наш тайм-фрейм
				var series = new CandleSeries(typeof(TimeFrameCandle), _lkoh, _timeFrame);

				// создаем торговую стратегию
				_strategy = new SmaStrategy(_candleManager, series, longSma, shortSma)
				{
					Volume = 1,
					Security = _lkoh,
					Portfolio = Portfolios.SelectedPortfolio,
					Connector = _trader,
				};
				_logManager.Sources.Add(_strategy);
				//_strategy.Log += OnLog;
				_strategy.PropertyChanged += OnStrategyPropertyChanged;

				_candlesElem = new ChartCandleElement();
				_area.Elements.Add(_candlesElem);

				_longMaElem = new ChartIndicatorElement
				{
					Title = LocalizedStrings.Long,
					Color = Colors.OrangeRed
				};
				_area.Elements.Add(_longMaElem);

				_shortMaElem = new ChartIndicatorElement
				{
					Title = LocalizedStrings.Short,
					Color = Colors.RoyalBlue
				};
				_area.Elements.Add(_shortMaElem);

				var marketTime = _trader.CurrentTime;

				// начинаем получать свечи за период в 5 дней
				_candleManager.Start(series, DateTime.Today - TimeSpan.FromDays(5), marketTime);

				_lastHistoryCandle = _timeFrame.GetCandleBounds(marketTime).Min;

				Report.IsEnabled = true;
			}

			if (_strategy.ProcessState == ProcessStates.Stopped)
			{
				// запускаем процесс получения стакана, необходимый для работы алгоритма котирования
				_trader.RegisterMarketDepth(_strategy.Security);
				_strategy.Start();
				Start.Content = LocalizedStrings.Str242;
			}
			else
			{
				_trader.UnRegisterMarketDepth(_strategy.Security);
				_strategy.Stop();
				Start.Content = LocalizedStrings.Str2421;
			}
		}
コード例 #56
0
ファイル: ChartPane.xaml.cs プロジェクト: hbwjz/StockSharp
		public void Draw(CandleSeries series, IEnumerable<Candle> candles)
		{
			if (series == null)
				throw new ArgumentNullException("series");

			if (candles == null)
				throw new ArgumentNullException("candles");

			Series = series;
			_candles = candles;

			//_candlesCount = 0;

			var ohlcArea = new ChartArea { Height = 210 };
			ChartPanel.AddArea(ohlcArea);

			_candlesElem = new ChartCandleElement();
			ChartPanel.AddElement(ohlcArea, _candlesElem, series);

			var volumeArea = new ChartArea { Height = 130 };
			ChartPanel.AddArea(volumeArea);

			_volumeElem = new ChartIndicatorElement
			{
				IndicatorPainter = new VolumePainter(),
			};
			var indicator = new VolumeIndicator();
			ChartPanel.AddElement(volumeArea, _volumeElem, series, indicator);

			CancelButton.Visibility = Visibility.Visible;

			_drawTimer.Activate();
		}
コード例 #57
0
        private void InitChart(EMAEventModelStrategy strategy)
        {
            _longMA = new ExponentialMovingAverage { Length = strategy.LongMA.Length};
            _shortMA = new ExponentialMovingAverage { Length = strategy.ShortMA.Length };
            _filterMA = new ExponentialMovingAverage { Length = strategy.FilterMA.Length };

            _area.Elements.Clear();

            _candlesElem = new ChartCandleElement()
            {
                DownBodyColor = Color.FromRgb(133, 133, 133),
                UpBodyColor = Color.FromRgb(255, 255, 255)
            };
            _area.Elements.Add(_candlesElem);

            _longMaElem = new ChartIndicatorElement
            {
                Title = "LongMA",
                Indicator = _longMA,
                Color = Color.FromRgb(120, 199, 130)
            };
            _area.Elements.Add(_longMaElem);

            _shortMaElem = new ChartIndicatorElement
            {
                Title = "ShortMA",
                Indicator = _shortMA,
                Color = Color.FromRgb(193, 53, 45)
            };
            _area.Elements.Add(_shortMaElem);

            _filterMaElem = new ChartIndicatorElement
            {
                Title = "FilterMA",
                Indicator = _filterMA,
                Color = Color.FromRgb(0, 124, 207)
            };
            _area.Elements.Add(_filterMaElem);

            _tradeElem = new ChartTradeElement()
            {
                BuyColor = Color.FromRgb(255, 0, 0),
                SellColor = Color.FromRgb(0, 0, 255),
                IsLegend = true
            };
            _area.Elements.Add(_tradeElem);
        }