Кодusing System;
using System.Linq;
using System.Windows;
using Ecng.Common;
using StockSharp.Algo;
using StockSharp.Algo.Candles;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Xaml.Charting;
using System.Collections.Generic;
using MoreLinq;
using StockSharp.Algo.Storages;
using StockSharp.Algo.Testing;
namespace test
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private HistoryEmulationConnector _historyEmulationConnector;
        private StorageRegistry _storageRegistry;
        public List<Security> Securities;
        private Str Str;
        public MainWindow()
        {
            InitializeComponent();
            Securities=new List<Security>();
            Str = new Str(Chart);
        }
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            _storageRegistry = new StorageRegistry { DefaultDrive = new LocalMarketDataDrive(@"...") };//todo Установить путь к истории
            _storageRegistry.DefaultDrive.AvailableSecurities.ForEach(sId =>
            {
                Securities.Add(new Security()
                {
                    Id = sId.SecurityCode + "@" + sId.BoardCode,
                    Code = sId.SecurityCode,
                    Type = sId.SecurityType,
                    Board = ExchangeBoard.Micex,
                    PriceStep = 0.01m
                });
            });
            var portfolio = new Portfolio { Name = "test account", BeginValue = 1000000 };
            _historyEmulationConnector = new HistoryEmulationConnector(Securities, new[] { portfolio })
            {
                HistoryMessageAdapter =
                {
                    StorageRegistry = _storageRegistry,
                    StartDate = new DateTime(2018, 1, 1, 0, 0, 0),
                    StopDate = new DateTime(2019, 9, 20, 0, 0, 0),
                },
            };
            Str.Security = Securities[0];//todo Установить инструмент из истории
            Str.Portfolio = portfolio;
            Str.Connector = _historyEmulationConnector;
            Str.Volume = 1;
            _historyEmulationConnector.Connected += () => { Str.Start(); _historyEmulationConnector.Start(); };
            _historyEmulationConnector.Connect();
        }
    }
    class Str : Strategy
    {
        private SimpleMovingAverage LongSma { get; set; }
        private SimpleMovingAverage ShortSma { get; set; }
        private CandleSeries CandleSeries { get; set; }
        private ChartCandleElement ChartCandleElement { get; set; }
        private ChartIndicatorElement LongElement { get; set; }
        public ChartIndicatorElement ShortElement { get; set; }
        private ChartOrderElement _chartOrderElement;
        private ChartTradeElement _chartTradeElement;
        private bool _isShortLessPrev;
        private Chart Chart { get; set; }
        public Str(Chart chart)
        {
            Chart = chart;
            LongSma = new SimpleMovingAverage(){Length = 8};
            ShortSma = new SimpleMovingAverage(){Length = 4};
            _chartOrderElement = new ChartOrderElement(){Title = "Ордеры"};
            _chartTradeElement = new ChartTradeElement(){Title = "Сделки"};
            ChartCandleElement = new ChartCandleElement(){Title = "Свечи"};
            LongElement = new ChartIndicatorElement(){Title = LongSma.ToString()};
            ShortElement = new ChartIndicatorElement(){Title = ShortSma.ToString()};
            Chart.Areas.Add(new ChartArea() { Elements = { ChartCandleElement, LongElement, ShortElement, _chartTradeElement, _chartOrderElement } });
            NewMyTrade += trade =>
            {
                var chartDrawData = new ChartDrawData();
                var chartDrawDataItem = chartDrawData.Group(trade.Trade.Time);
                chartDrawDataItem.Add(_chartTradeElement, trade);
                Chart.Draw(chartDrawData);
            };
            OrderRegistered += order =>
            {
                var chartDrawData = new ChartDrawData();
                var chartDrawDataItem = chartDrawData.Group(order.Time);
                chartDrawDataItem.Add(_chartOrderElement, order);
                Chart.Draw(chartDrawData);
            };
        }
        protected override void OnStarted()
        {
            CandleSeries = new CandleSeries(typeof(TimeFrameCandle), Security, TimeSpan.FromMinutes(1));
            ((Connector) Connector).CandleSeriesProcessing += CandleManager_Processing;
            if (!((Connector)Connector).SubscribedCandleSeries.Contains(CandleSeries))
                ((Connector)Connector).SubscribeCandles(CandleSeries);
            base.OnStarted();
        }
        private void CandleManager_Processing(CandleSeries candleSeries, Candle candle)
        {
            if (candle.State != CandleStates.Finished) return;
            var ls = LongSma.Process(candle);
            var ss = ShortSma.Process(candle);
            if (LongSma.IsFormed && LongSma.IsFormed)
            {
                var isShortLessCurrent = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();
                if (isShortLessCurrent != _isShortLessPrev)
                {
                        var order = new Order()
                        {
                            Type = OrderTypes.Limit,
                            Direction = isShortLessCurrent ? Sides.Sell : Sides.Buy,
                            Price = candle.ClosePrice,
                            Portfolio = Portfolio,
                            Volume = Position != 0 ? Volume * 2 : Volume,
                            Security = Security
                        };
                        RegisterOrder(order);
                }
                _isShortLessPrev = isShortLessCurrent;
            }
            var chartDrawData = new ChartDrawData();
            var chartDrawDataItem = chartDrawData.Group(candle.OpenTime);
            chartDrawDataItem.Add(ChartCandleElement, candle);
            chartDrawDataItem.Add(ShortElement, ss);
            chartDrawDataItem.Add(LongElement, ls);
            Chart.Draw(chartDrawData);
        }
    }
}