Esempio n. 1
0
        // service
        // сервис

        /// <summary>
        /// constructor
        /// конструктор
        /// </summary>
        /// <param name="name"> bot name / имя робота </param>
        /// <param name="startProgram"> program that created the bot which created this connection / программа создавшая робота который создал это подключение </param>
        public ConnectorCandles(string name, StartProgram startProgram)
        {
            _name        = name;
            StartProgram = startProgram;

            TimeFrameBuilder = new TimeFrameBuilder(_name, startProgram);
            ServerType       = ServerType.None;


            if (StartProgram != StartProgram.IsOsOptimizer)
            {
                _canSave = true;
                Load();
                _emulator = new OrderExecutionEmulator();
                _emulator.MyTradeEvent     += ConnectorBot_NewMyTradeEvent;
                _emulator.OrderChangeEvent += ConnectorBot_NewOrderIncomeEvent;
            }

            if (!string.IsNullOrWhiteSpace(NamePaper))
            {
                _subscrabler = new Thread(Subscrable);
                _subscrabler.CurrentCulture = new CultureInfo("ru-RU");
                _subscrabler.Name           = "ConnectorSubscrableThread_" + UniqName;
                _subscrabler.IsBackground   = true;
                _subscrabler.Start();
            }

            if (StartProgram == StartProgram.IsTester)
            {
                PortfolioName = "GodMode";
            }
        }
Esempio n. 2
0
        // service
        // сервис

        /// <summary>
        /// constructor
        /// конструктор
        /// </summary>
        /// <param name="name"> bot name / имя робота </param>
        /// <param name="startProgram"> program that created the bot which created this connection / программа создавшая робота который создал это подключение </param>
        public ConnectorCandles(string name, StartProgram startProgram)
        {
            _name        = name;
            StartProgram = startProgram;

            TimeFrameBuilder = new TimeFrameBuilder(_name, startProgram);
            ServerType       = ServerType.None;


            if (StartProgram != StartProgram.IsOsOptimizer)
            {
                _canSave = true;
                Load();
                _emulator = new OrderExecutionEmulator();
                _emulator.MyTradeEvent     += ConnectorBot_NewMyTradeEvent;
                _emulator.OrderChangeEvent += ConnectorBot_NewOrderIncomeEvent;
            }

            if (!string.IsNullOrWhiteSpace(SecurityName))
            {
                _taskIsDead = false;
                Task.Run(Subscrable);
            }
            else
            {
                _taskIsDead = true;
            }

            if (StartProgram == StartProgram.IsTester)
            {
                PortfolioName = "GodMode";
            }
        }
Esempio n. 3
0
        /// <summary>
        /// подгрузить в чарт новый инструмент
        /// </summary>
        /// <param name="security">бумага</param>
        /// <param name="timeFrameBuilder">объект хранящий в себе настройки построения свечей</param>
        /// <param name="portfolioName">портфель</param>
        /// <param name="serverType">тип сервера</param>
        public void SetNewSecurity(string security, TimeFrameBuilder timeFrameBuilder, string portfolioName, ServerType serverType)
        {
            if (ChartCandle != null)
            {
                ChartCandle.ClearDataPointsAndSizeValue();
                ChartCandle.SetNewTimeFrame(timeFrameBuilder.TimeFrameTimeSpan, timeFrameBuilder.TimeFrame);
            }

            if (_securityOnThisChart == security &&
                _timeFrameSecurity == timeFrameBuilder.TimeFrame)
            {
                return;
            }

            string          lastSecurity = _securityOnThisChart;
            List <Position> positions    = _myPosition;

            _timeFrameBuilder    = timeFrameBuilder;
            _securityOnThisChart = security;
            _timeFrameSecurity   = timeFrameBuilder.TimeFrame;
            _serverType          = serverType;

            Clear();
            PaintLabelOnSlavePanel();

            if (lastSecurity == security && positions != null)
            {
                SetPosition(positions);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// delete object settings
        /// удалить настройки объекта
        /// </summary>
        public void Delete()
        {
            TimeFrameBuilder.Delete();
            if (File.Exists(@"Engine\" + _name + @"ConnectorPrime.txt"))
            {
                File.Delete(@"Engine\" + _name + @"ConnectorPrime.txt");
            }

            if (_mySeries != null)
            {
                _mySeries.Stop();
                _mySeries.Clear();
            }

            if (_emulator != null)
            {
                _emulator.MyTradeEvent     += ConnectorBot_NewMyTradeEvent;
                _emulator.OrderChangeEvent += ConnectorBot_NewOrderIncomeEvent;
            }

            if (_myServer != null)
            {
                _myServer.NewBidAscIncomeEvent  -= ConnectorBotNewBidAscIncomeEvent;
                _myServer.NewMyTradeEvent       -= ConnectorBot_NewMyTradeEvent;
                _myServer.NewOrderIncomeEvent   -= ConnectorBot_NewOrderIncomeEvent;
                _myServer.NewMarketDepthEvent   -= ConnectorBot_NewMarketDepthEvent;
                _myServer.NewTradeEvent         -= ConnectorBot_NewTradeEvent;
                _myServer.TimeServerChangeEvent -= myServer_TimeServerChangeEvent;
                _myServer.NeadToReconnectEvent  -= _myServer_NeadToReconnectEvent;
            }

            _neadToStopThread = true;
        }
Esempio n. 5
0
        /// <summary>
        /// take candle history for period
        /// взять историю свечек за период
        /// </summary>
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder,
                                                     DateTime startTime, DateTime endTime, DateTime actualTime)
        {
            int curStartTime = (int)(startTime - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;

            List <Candle> candles = new List <Candle>();

            while (true)
            {
                List <Candle> newCandles = _clientRest.GetCandles(security.Name, timeFrameBuilder.TimeFrameTimeSpan, curStartTime);

                if (newCandles == null ||
                    newCandles.Count == 0)
                {
                    break;
                }

                Candle lastCandle = newCandles[newCandles.Count - 1];

                candles.Merge(newCandles);

                if (newCandles.Count == 1)
                {
                    break;
                }

                curStartTime = (int)(lastCandle.TimeStart - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
            }

            return(candles);
        }
        public override List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime,
                                                              DateTime actualTime)
        {
            List <Candle> candles = new List <Candle>();

            int oldInterval = Convert.ToInt32(timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes);

            var step = new TimeSpan(0, (int)(oldInterval * 2000), 0);

            actualTime = startTime;

            var midTime = actualTime + step;

            while (true)
            {
                if (actualTime >= endTime)
                {
                    break;
                }

                List <Candle> newCandles = GetCandles(oldInterval, security.Name, actualTime, midTime);

                if (candles.Count != 0 && newCandles != null && newCandles.Count != 0)
                {
                    for (int i = 0; i < newCandles.Count; i++)
                    {
                        if (candles[candles.Count - 1].TimeStart >= newCandles[i].TimeStart)
                        {
                            newCandles.RemoveAt(i);
                            i--;
                        }
                    }
                }

                if (newCandles == null)
                {
                    continue;
                }

                if (newCandles.Count == 0)
                {
                    return(candles);
                }

                candles.AddRange(newCandles);

                actualTime = candles[candles.Count - 1].TimeStart;
                midTime    = actualTime + step;
                Thread.Sleep(1000);
            }

            if (candles.Count == 0)
            {
                return(null);
            }

            return(candles);
        }
Esempio n. 7
0
        /// <summary>
        /// Запрос из Subscribe
        /// </summary>
        /// <param name="namePaper"></param>
        /// <param name="timeFrameBuilder"></param>
        /// <returns></returns>
        public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder)
        {
            lock (_starterLocker)
            {
                var          security = _securities.Find(securiti => securiti.Name == namePaper);
                CandleSeries series   = new CandleSeries(timeFrameBuilder, security, StartProgram.IsOsTrader);

                _candleManager.StartSeries(series);

                return(series);
            }
        }
        /// <summary>
        /// take candle history for period
        /// взять историю свечек за период
        /// </summary>
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder,
                                                     DateTime startTime, DateTime endTime, DateTime actualTime)
        {
            List <Candle> candles = new List <Candle>();

            actualTime = startTime;

            while (actualTime < endTime)
            {
                List <Candle> newCandles = _client.GetCandlesForTimes(security.Name,
                                                                      timeFrameBuilder.TimeFrameTimeSpan,
                                                                      actualTime, endTime);

                if (newCandles != null && candles.Count != 0 && newCandles.Count != 0)
                {
                    for (int i = 0; i < newCandles.Count; i++)
                    {
                        if (candles[candles.Count - 1].TimeStart >= newCandles[i].TimeStart)
                        {
                            newCandles.RemoveAt(i);
                            i--;
                        }
                    }
                }

                if (newCandles == null)
                {
                    actualTime = actualTime.AddDays(5);
                    continue;
                }

                if (newCandles.Count == 0)
                {
                    return(candles);
                }

                candles.AddRange(newCandles);

                actualTime = candles[candles.Count - 1].TimeStart;

                Thread.Sleep(60);
            }

            if (candles.Count == 0)
            {
                return(null);
            }

            return(candles);
        }
        /// <summary>
        /// take candle history for period
        /// взять историю свечек за период
        /// </summary>
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime, DateTime actualTime)
        {
            if (endTime > DateTime.Now - new TimeSpan(0, 0, 1, 0))
            {
                endTime = DateTime.Now - new TimeSpan(0, 0, 1, 0);
            }

            int interval = 500 * (int)timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes;

            List <Candle> candles = new List <Candle>();

            var startTimeStep = startTime;
            var endTimeStep   = startTime;

            while (endTime > endTimeStep)
            {
                endTimeStep = endTimeStep + new TimeSpan(0, 0, interval, 0);

                DateTime realEndTime = endTimeStep;

                if (realEndTime > DateTime.Now - new TimeSpan(0, 0, (int)timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes, 0))
                {
                    realEndTime = DateTime.Now - new TimeSpan(0, 0, (int)timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes, 0);
                }

                List <Candle> stepCandles = _client.GetCandlesForTimes(security.Name, timeFrameBuilder.TimeFrameTimeSpan, startTimeStep, realEndTime);

                if (stepCandles != null)
                {
                    candles.AddRange(stepCandles);
                }


                startTimeStep = endTimeStep + new TimeSpan(0, 0, (int)timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes, 0);

                if (endTime < endTimeStep)
                {
                    break;
                }

                Thread.Sleep(300);
            }

            if (candles.Count == 0)
            {
                return(null);
            }

            return(candles);
        }
Esempio n. 10
0
        /// <summary>
        /// take candle history for period
        /// взять историю свечек за период
        /// </summary>
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder,
                                                     DateTime startTime, DateTime endTime, DateTime actualTime)
        {
            return(null);

            /*  List<Candle> candles = new List<Candle>();
             *
             * actualTime = startTime;
             *
             * while (actualTime < endTime)
             * {
             *    List<Candle> newCandles = _client.GetCandlesForTimes(security.Name,
             *        timeFrameBuilder.TimeFrameTimeSpan,
             *        actualTime, endTime);
             *
             *    if (candles.Count != 0 && newCandles.Count != 0)
             *    {
             *        for (int i = 0; i < newCandles.Count; i++)
             *        {
             *            if (candles[candles.Count - 1].TimeStart >= newCandles[i].TimeStart)
             *            {
             *                newCandles.RemoveAt(i);
             *                i--;
             *            }
             *
             *        }
             *    }
             *
             *    if (newCandles == null)
             *    {
             *        continue;
             *    }
             *
             *    if (newCandles.Count == 0)
             *    {
             *        return candles;
             *    }
             *
             *    candles.AddRange(newCandles);
             *
             *    actualTime = candles[candles.Count - 1].TimeStart;
             * }
             *
             * if (candles.Count == 0)
             * {
             *    return null;
             * }
             *
             * return candles;*/
        }
Esempio n. 11
0
        public override List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder time_frame_builder, DateTime start_time, DateTime end_time, DateTime actual_time)
        {
            List <Candle> candles = new List <Candle>();

            int old_interval = Convert.ToInt32(time_frame_builder.TimeFrameTimeSpan.TotalMinutes);

            candles = GetCandles(old_interval, security.Name, start_time, end_time);

            if (candles.Count == 0)
            {
                return(null);
            }

            return(candles);
        }
Esempio n. 12
0
        public CandleSeries StartThisSecurity(string securityName, TimeFrameBuilder timeFrameBuilder, string securityClass)
        {
            lock (_starterLocker)
            {
                var security = _securities.Find(securiti => securiti.Name == securityName);

                if (security == null)
                {
                    return(null);
                }

                CandleSeries series = new CandleSeries(timeFrameBuilder, security, StartProgram.IsOsTrader);

                _candleManager.StartSeries(series);

                return(series);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// take candle history for period
        /// взять историю свечек за период
        /// </summary>
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime,
                                                     DateTime actualTime)
        {
            List <Candle> candles = new List <Candle>();

            List <Candle> lastCandles =
                GetCandleHistory(security.Name, timeFrameBuilder.TimeFrameTimeSpan, 5000, DateTime.MinValue, DateTime.MaxValue);

            candles.AddRange(lastCandles);

            DateTime curEnd = candles[0].TimeStart;

            while (curEnd <= startTime == false)
            {
                List <Candle> newCandles =
                    GetCandleHistory(security.Name, timeFrameBuilder.TimeFrameTimeSpan, 2000, startTime, curEnd);

                if (candles.Count != 0 && newCandles.Count != 0)
                {
                    if (newCandles[newCandles.Count - 1].TimeStart >= candles[0].TimeStart)
                    {
                        newCandles.RemoveAt(newCandles.Count - 1);
                    }
                }

                if (newCandles.Count == 0)
                {
                    return(candles);
                }

                candles.InsertRange(0, newCandles);

                curEnd = candles[0].TimeStart;
            }

            if (candles.Count == 0)
            {
                return(null);
            }

            return(candles);
        }
Esempio n. 14
0
// сервис

        /// <summary>
        /// конструктор
        /// </summary>
        /// <param name="name">имя робота</param>
        public Connector(string name)
        {
            _name = name;

            TimeFrameBuilder = new TimeFrameBuilder(_name);
            ServerType       = ServerType.Unknown;
            Load();
            _canSave = true;

            if (!string.IsNullOrWhiteSpace(NamePaper))
            {
                _subscrabler = new Thread(Subscrable);
                _subscrabler.CurrentCulture = new CultureInfo("ru-RU");
                _subscrabler.Name           = "ConnectorSubscrableThread_" + UniqName;
                _subscrabler.IsBackground   = true;
                _subscrabler.Start();
            }

            _emulator = new OrderExecutionEmulator();
            _emulator.MyTradeEvent     += ConnectorBot_NewMyTradeEvent;
            _emulator.OrderChangeEvent += ConnectorBot_NewOrderIncomeEvent;
        }
Esempio n. 15
0
        /// <summary>
        /// удалить настройки объекта
        /// </summary>
        public void Delete()
        {
            TimeFrameBuilder.Delete();
            if (File.Exists(@"Engine\" + _name + @"ConnectorPrime.txt"))
            {
                File.Delete(@"Engine\" + _name + @"ConnectorPrime.txt");
            }

            if (_mySeries != null)
            {
                _mySeries.Stop();
            }

            if (_myServer != null)
            {
                _myServer.NewBidAscIncomeEvent  -= ConnectorBotNewBidAscIncomeEvent;
                _myServer.NewMyTradeEvent       -= ConnectorBot_NewMyTradeEvent;
                _myServer.NewOrderIncomeEvent   -= ConnectorBot_NewOrderIncomeEvent;
                _myServer.NewMarketDepthEvent   -= ConnectorBot_NewMarketDepthEvent;
                _myServer.NewTradeEvent         -= ConnectorBot_NewTradeEvent;
                _myServer.TimeServerChangeEvent -= myServer_TimeServerChangeEvent;
                _myServer.NeadToReconnectEvent  -= _myServer_NeadToReconnectEvent;
            }

            if (_subscrabler != null)
            {
                try
                {
                    if (_subscrabler.IsAlive)
                    {
                        _subscrabler.Abort();
                    }
                }
                catch
                {
                    //SendNewLogMessage(error.ToString(), LogMessageType.Error);
                }
            }
        }
Esempio n. 16
0
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime,
                                                     DateTime actualTime)
        {
            lock (locker)
            {
                string minutes = "";

                if (timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes == 1)
                {
                    minutes = "1";
                }
                if (timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes == 5)
                {
                    minutes = "2";
                }
                if (timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes == 10)
                {
                    minutes = "3";
                }
                if (timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes == 15)
                {
                    minutes = "4";
                }
                if (timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes == 30)
                {
                    minutes = "5";
                }
                if (timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes == 60)
                {
                    minutes = "6";
                }

                List <Candle> candles = GetCandles(security, startTime, endTime, minutes);
                return(candles);
            }
        }
Esempio n. 17
0
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime,
                                                     DateTime actualTime)
        {
            lock (locker)
            {
                List <Candle> candles = new List <Candle>();

                int minutesInTf = Convert.ToInt32(timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes);

                if (minutesInTf >= 1 &&
                    minutesInTf < 10)
                {
                    List <Candle> sourseCandle = GetAllCandles(security, startTime, 1, endTime);
                    candles = ConcateCandles(sourseCandle, 1, minutesInTf);
                }
                else if (minutesInTf == 15 ||
                         minutesInTf == 45)
                {
                    List <Candle> sourseCandle = GetAllCandles(security, startTime, 1, endTime);
                    candles = ConcateCandles(sourseCandle, 1, minutesInTf);
                }
                else if (minutesInTf >= 10 &&
                         minutesInTf < 60)
                {
                    List <Candle> sourseCandle = GetAllCandles(security, startTime, 10, endTime);
                    candles = ConcateCandles(sourseCandle, 10, minutesInTf);
                }
                else if (minutesInTf >= 60)
                {
                    List <Candle> sourseCandle = GetAllCandles(security, startTime, 60, endTime);
                    candles = ConcateCandles(sourseCandle, 60, minutesInTf);
                }

                return(candles);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// место работы потока создающего новый файл
        /// </summary>
        private void WorkerSpace()
        {
            if (string.IsNullOrWhiteSpace(_sourceFile))
            {
                SendNewLogMessage(" Процедура конвертации не может быть запущеана. Не указан файл с исходными данными", LogMessageType.System);
                return;
            }
            else if (string.IsNullOrWhiteSpace(_exitFile))
            {
                SendNewLogMessage("Процедура конвертации не может быть запущеана. Не указан файл с выходными данными", LogMessageType.System);
                return;
            }

            if (!File.Exists(_exitFile))
            {
                File.Create(_exitFile);
            }

            StreamReader reader = new StreamReader(_sourceFile);

            SendNewLogMessage("Процедура конвертации начата", LogMessageType.System);

            SendNewLogMessage("Загружаем тики из файла", LogMessageType.System);

            List <Trade> trades = new List <Trade>();

            int currentWeek = 0;

            bool isNotFirstTime = false;

            try
            {
                while (!reader.EndOfStream)
                {
                    Trade trade = new Trade();
                    trade.SetTradeFromString(reader.ReadLine());

                    int partMonth = 1;

                    if (trade.Time.Day <= 10)
                    {
                        partMonth = 1;
                    }
                    else if (trade.Time.Day > 10 &&
                             trade.Time.Day < 20)
                    {
                        partMonth = 2;
                    }

                    else if (trade.Time.Day >= 20)
                    {
                        partMonth = 3;
                    }

                    if (currentWeek == 0)
                    {
                        SendNewLogMessage("Грузим неделю № " + partMonth + " Месяц " + trade.Time.Month, LogMessageType.System);
                        currentWeek = partMonth;
                    }


                    if (partMonth != currentWeek || reader.EndOfStream)
                    {
                        SendNewLogMessage("Неделя " + currentWeek + " Месяц " + trade.Time.Month + " подгружен. Создаём серии свечек", LogMessageType.System);

                        TimeFrameBuilder timeFrameBuilder = new TimeFrameBuilder();
                        timeFrameBuilder.TimeFrame = TimeFrame;

                        CandleSeries series = new CandleSeries(timeFrameBuilder, new Security()
                        {
                            Name = "Unknown"
                        });

                        series.IsStarted = true;

                        series.SetNewTicks(trades);

                        List <Candle> candles = series.CandlesAll;

                        if (candles == null)
                        {
                            continue;
                        }

                        StreamWriter writer = new StreamWriter(_exitFile, isNotFirstTime);

                        for (int i = 0; i < candles.Count; i++)
                        {
                            writer.WriteLine(candles[i].StringToSave);
                        }

                        writer.Close();

                        SendNewLogMessage("Сохранение завершено", LogMessageType.System);

                        isNotFirstTime = true;

                        trades = new List <Trade>();
                        series.Clear();

                        currentWeek = partMonth;

                        SendNewLogMessage("Грузим неделю № " + partMonth + " Месяц " + trade.Time.Month, LogMessageType.System);
                    }
                    else
                    {
                        trades.Add(trade);
                    }
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage("Скачивание прервано. В файле данных не верный формат", LogMessageType.System);
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
                reader.Close();
                return;
            }

            reader.Close();



            SendNewLogMessage("Сохранение завершено", LogMessageType.System);
        }
Esempio n. 19
0
        /// <summary>
        /// место работы потока создающего новый файл
        /// </summary>
        private void WorkerSpace()
        {
            if (string.IsNullOrWhiteSpace(_sourceFile))
            {
                SendNewLogMessage(OsLocalization.Converter.Message2, LogMessageType.System);
                return;
            }
            else if (string.IsNullOrWhiteSpace(_exitFile))
            {
                SendNewLogMessage(OsLocalization.Converter.Message3, LogMessageType.System);
                return;
            }

            if (!File.Exists(_exitFile))
            {
                File.Create(_exitFile);
            }

            StreamReader reader = new StreamReader(_sourceFile);

            SendNewLogMessage(OsLocalization.Converter.Message4, LogMessageType.System);

            SendNewLogMessage(OsLocalization.Converter.Message5, LogMessageType.System);

            List <Trade> trades = new List <Trade>();

            int currentWeek = 0;

            bool isNotFirstTime = false;

            try
            {
                while (!reader.EndOfStream)
                {
                    Trade trade = new Trade();
                    trade.SetTradeFromString(reader.ReadLine());

                    int partMonth = 1;

                    if (trade.Time.Day <= 10)
                    {
                        partMonth = 1;
                    }
                    else if (trade.Time.Day > 10 &&
                             trade.Time.Day < 20)
                    {
                        partMonth = 2;
                    }

                    else if (trade.Time.Day >= 20)
                    {
                        partMonth = 3;
                    }

                    if (currentWeek == 0)
                    {
                        SendNewLogMessage(
                            OsLocalization.Converter.Message6 + partMonth +
                            OsLocalization.Converter.Message7 + trade.Time.Month, LogMessageType.System);
                        currentWeek = partMonth;
                    }


                    if (partMonth != currentWeek || reader.EndOfStream)
                    {
                        SendNewLogMessage(OsLocalization.Converter.Message6 + currentWeek +
                                          OsLocalization.Converter.Message7 + trade.Time.Month +
                                          OsLocalization.Converter.Message8, LogMessageType.System);

                        TimeFrameBuilder timeFrameBuilder = new TimeFrameBuilder();
                        timeFrameBuilder.TimeFrame = TimeFrame;

                        CandleSeries series = new CandleSeries(timeFrameBuilder, new Security()
                        {
                            Name = "Unknown"
                        }, StartProgram.IsOsConverter);

                        series.IsStarted = true;

                        series.SetNewTicks(trades);

                        List <Candle> candles = series.CandlesAll;

                        if (candles == null)
                        {
                            continue;
                        }

                        StreamWriter writer = new StreamWriter(_exitFile, isNotFirstTime);

                        for (int i = 0; i < candles.Count; i++)
                        {
                            writer.WriteLine(candles[i].StringToSave);
                        }

                        writer.Close();

                        SendNewLogMessage(OsLocalization.Converter.Message9, LogMessageType.System);

                        isNotFirstTime = true;

                        trades = new List <Trade>();
                        series.Clear();

                        currentWeek = partMonth;

                        SendNewLogMessage(OsLocalization.Converter.Message6 + partMonth +
                                          OsLocalization.Converter.Message7 + trade.Time.Month, LogMessageType.System);
                    }
                    else
                    {
                        trades.Add(trade);
                    }
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(OsLocalization.Converter.Message10, LogMessageType.System);
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
                reader.Close();
                return;
            }

            reader.Close();



            SendNewLogMessage(OsLocalization.Converter.Message9, LogMessageType.System);
        }
Esempio n. 20
0
 public CandleSeries GetCandleDataToSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder, DateTime startTime,
                                             DateTime endTime, DateTime actualTime, bool neadToUpdate)
 {
     return(StartThisSecurity(namePaper, timeFrameBuilder));
 }
Esempio n. 21
0
 /// <summary>
 /// take candle history for period
 /// взять историю свечек за период
 /// </summary>
 public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder,
                                              DateTime startTime, DateTime endTime, DateTime actualTime)
 {
     return(null);
 }
        /// <summary>
        /// начать выкачивать данный иснтрументн
        /// </summary>
        /// <param name="namePaper"> название инструмента</param>
        /// <param name="timeFrameBuilder">объект несущий в себе данные о ТаймФрейме нужном для серии</param>
        /// <returns>в случае успешного запуска возвращает CandleSeries, объект генерирующий свечи</returns>
        public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder)
        {
            try
            {
                if (_lastStartServerTime.AddSeconds(15) > DateTime.Now)
                {
                    return(null);
                }

                if (_startListeningPortfolios == false)
                {
                    return(null);
                }
                lock (_lockerStarter)
                {
                    if (namePaper == "")
                    {
                        return(null);
                    }
                    // надо запустить сервер если он ещё отключен
                    if (ServerStatus != ServerConnectStatus.Connect)
                    {
                        //MessageBox.Show("Сервер не запущен. Скачивание данных прервано. Инструмент: " + namePaper);
                        return(null);
                    }

                    if (_securities == null || _portfolios == null)
                    {
                        Thread.Sleep(5000);
                        return(null);
                    }
                    if (_lastStartServerTime != DateTime.MinValue &&
                        _lastStartServerTime.AddSeconds(15) > DateTime.Now)
                    {
                        return(null);
                    }

                    Security security = null;

                    for (int i = 0; _securities != null && i < _securities.Count; i++)
                    {
                        if (_securities[i].Name == namePaper)
                        {
                            security = _securities[i];
                            break;
                        }
                    }

                    if (security == null)
                    {
                        return(null);
                    }

                    CandleSeries series = new CandleSeries(timeFrameBuilder, security, StartProgram.IsOsTrader);

                    _clientBitStamp.SubscribleTradesAndDepths(security);

                    Thread.Sleep(300);

                    _candleManager.StartSeries(series);

                    SendLogMessage("Инструмент " + series.Security.Name + "ТаймФрейм" + series.TimeFrame +
                                   " успешно подключен на получение данных и прослушивание свечек", LogMessageType.System);

                    if (_tickStorage != null)
                    {
                        _tickStorage.SetSecurityToSave(security);
                    }

                    return(series);
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
                return(null);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Начать выгрузку данных по инструменту.
        /// </summary>
        /// <param name="namePaper">имя бумаги которую будем запускать</param>
        /// <param name="timeFrameBuilder">объект несущий в себе данные о таймФрейме</param>
        /// <returns>В случае удачи возвращает CandleSeries
        /// в случае неудачи null</returns>
        public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder)
        {
            try
            {
                if (_lastStartServerTime.AddSeconds(15) > DateTime.Now)
                {
                    return(null);
                }

                // дальше по одному
                lock (_lockerStarter)
                {
                    if (namePaper == "")
                    {
                        return(null);
                    }
                    // надо запустить сервер если он ещё отключен
                    if (ServerStatus != ServerConnectStatus.Connect)
                    {
                        //MessageBox.Show("Сервер не запущен. Скачивание данных прервано. Инструмент: " + namePaper);
                        return(null);
                    }

                    if (_securities == null || _portfolios == null)
                    {
                        Thread.Sleep(5000);
                        return(null);
                    }
                    if (_lastStartServerTime != DateTime.MinValue &&
                        _lastStartServerTime.AddSeconds(15) > DateTime.Now)
                    {
                        return(null);
                    }

                    Security security = null;


                    for (int i = 0; _securities != null && i < _securities.Count; i++)
                    {
                        if (_securities[i].Name == namePaper)
                        {
                            security = _securities[i];
                            break;
                        }
                    }

                    if (security == null)
                    {
                        return(null);
                    }


                    CandleSeries series = new CandleSeries(timeFrameBuilder, security);

                    lock (_serverLocker)
                    {
                        AstsServer.ListenBidAsks(security);
                    }

                    Thread.Sleep(2000);

                    _candleManager.StartSeries(series);

                    SendLogMessage("Инструмент " + series.Security.Name + "ТаймФрейм" + series.TimeFrame +
                                   " успешно подключен на получение данных и прослушивание свечек",
                                   LogMessageType.System);

                    return(series);
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
                return(null);
            }
        }
Esempio n. 24
0
 /// <summary>
 /// take candle history for period
 /// взять историю свечек за период
 /// </summary>
 public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder,
                                              DateTime from, DateTime to, DateTime actualTime)
 {
     return(_client.GetCandleHistory(security.NameId, timeFrameBuilder.TimeFrame, from, to));
 }
        public override List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime,
                                                              DateTime actualTime)
        {
            List <Candle> candles = new List <Candle>();

            int oldInterval = Convert.ToInt32(timeFrameBuilder.TimeFrameTimeSpan.TotalMinutes);

            var step = new TimeSpan(0, (int)(oldInterval * 1000), 0);

            actualTime = startTime;

            var midTime = actualTime + step;

            while (true)
            {
                if (actualTime >= endTime)
                {
                    break;
                }

                string name = security.NameId;

                if (security.NameId.Contains("CW") ||
                    security.NameId.Contains("NW") ||
                    security.NameId.Contains("CQ") ||
                    security.NameId.Contains("NQ"))
                {
                    name = security.Name;
                }

                List <Candle> newCandles = GetCandlesByRest(oldInterval, name, actualTime, midTime);

                if (candles.Count != 0 && newCandles != null && newCandles.Count != 0)
                {
                    for (int i = 0; i < newCandles.Count; i++)
                    {
                        if (candles[candles.Count - 1].TimeStart >= newCandles[i].TimeStart)
                        {
                            newCandles.RemoveAt(i);
                            i--;
                        }
                    }
                }

                if (newCandles == null ||
                    newCandles.Count == 0)
                {
                    actualTime = actualTime.AddDays(5);
                    midTime    = actualTime + step;
                    continue;
                }

                candles.AddRange(newCandles);

                actualTime = candles[candles.Count - 1].TimeStart;
                midTime    = actualTime + step;
            }

            if (candles.Count == 0)
            {
                return(null);
            }

            return(candles);
        }
Esempio n. 26
0
        /// <summary>
        /// Начать выгрузку данных по инструменту.
        /// </summary>
        /// <param name="namePaper">имя бумаги которую будем запускать</param>
        /// <param name="timeFrameBuilder">объект несущий в себе данные о таймФрейме</param>
        /// <returns>В случае удачи возвращает CandleSeries
        /// в случае неудачи null</returns>
        public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder)
        {
            if (_lastStartServerTime.AddSeconds(30) > DateTime.Now)
            {
                return(null);
            }

            // дальше по одному
            lock (_lockerStarter)
            {
                if (namePaper == "")
                {
                    return(null);
                }
                // надо запустить сервер если он ещё отключен
                if (ServerStatus != ServerConnectStatus.Connect)
                {
                    //MessageBox.Show("Сервер не запущен. Скачивание данных прервано. Инструмент: " + namePaper);
                    return(null);
                }

                if (_securities == null || _portfolios == null)
                {
                    Thread.Sleep(5000);
                    return(null);
                }
                if (_lastStartServerTime != DateTime.MinValue &&
                    _lastStartServerTime.AddSeconds(15) > DateTime.Now)
                {
                    return(null);
                }

                Security security = null;

                for (int i = 0; _securities != null && i < _securities.Count; i++)
                {
                    if (_securities[i].Name == namePaper)
                    {
                        security = _securities[i];
                        break;
                    }
                }

                if (security == null)
                {
                    return(null);
                }

                CandleSeries series = new CandleSeries(timeFrameBuilder, security);

                _plazaController.StartMarketDepth(security);
                Thread.Sleep(5000);

                _candleManager.StartSeries(series);

                if (LogMessageEvent != null)
                {
                    LogMessageEvent("Инструмент " + series.Security.Name + "ТаймФрейм " + series.TimeFrame +
                                    " успешно подключен на получение данных и прослушивание свечек",
                                    LogMessageType.System);
                }

                if (_tickStorage != null)
                {
                    _tickStorage.SetSecurityToSave(security);
                }


                return(series);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Начать выгрузку данных по инструменту.
        /// </summary>
        /// <param name="namePaper">имя бумаги которую будем запускать</param>
        /// <param name="timeFrameBuilder">объект несущий </param>
        /// <returns>В случае удачи возвращает CandleSeries
        /// в случае неудачи null</returns>
        public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder)
        {
            try
            {
                if (_lastStartServerTime.AddSeconds(15) > DateTime.Now)
                {
                    return(null);
                }

                lock (_lockerStarter)
                {
                    if (namePaper == "")
                    {
                        return(null);
                    }
                    // надо запустить сервер если он ещё отключен
                    if (ServerStatus != ServerConnectStatus.Connect)
                    {
                        //MessageBox.Show("Сервер не запущен. Скачивание данных прервано. Инструмент: " + namePaper);
                        return(null);
                    }

                    if (_securities == null || _portfolios == null)
                    {
                        Thread.Sleep(5000);
                        return(null);
                    }
                    if (_lastStartServerTime != DateTime.MinValue &&
                        _lastStartServerTime.AddSeconds(15) > DateTime.Now)
                    {
                        return(null);
                    }

                    Security security = null;


                    for (int i = 0; _securities != null && i < _securities.Count; i++)
                    {
                        if (_securities[i].Name == namePaper)
                        {
                            security = _securities[i];
                            break;
                        }
                    }

                    if (security == null)
                    {
                        return(null);
                    }

                    if (_connectedContracts == null)
                    {
                        _connectedContracts = new List <string>();
                    }

                    if (_connectedContracts.Find(s => s == security.Name) == null)
                    {
                        _connectedContracts.Add(security.Name);
                    }

                    _tickStorage.SetSecurityToSave(security);

                    // 2 создаём серию свечек
                    CandleSeries series = new CandleSeries(timeFrameBuilder, security);

                    if (NeadToGetCandles(timeFrameBuilder.TimeFrame))
                    {    // подгружаем в серию свечки, если коннектор это позволяет
                        short  count       = 500;
                        string price       = "MBA";
                        string instrument  = security.Name;
                        string granularity = GetTimeFrameInOandaFormat(timeFrameBuilder.TimeFrame).ToString();

                        var parameters = new Dictionary <string, string>();
                        parameters.Add("price", price);
                        parameters.Add("granularity", granularity);
                        parameters.Add("count", count.ToString());

                        Task <List <CandlestickPlus> > result = Rest20.GetCandlesAsync(instrument, parameters);

                        while (!result.IsCanceled &&
                               !result.IsCompleted &&
                               !result.IsFaulted)
                        {
                            Thread.Sleep(10);
                        }

                        List <CandlestickPlus> candleOanda = result.Result;

                        List <Candle> candlesOsEngine = new List <Candle>();

                        for (int i = 0; i < candleOanda.Count; i++)
                        {
                            Candle newCandle = new Candle();
                            newCandle.Open      = Convert.ToDecimal(candleOanda[i].bid.o);
                            newCandle.High      = Convert.ToDecimal(candleOanda[i].bid.h);
                            newCandle.Low       = Convert.ToDecimal(candleOanda[i].bid.l);
                            newCandle.Close     = Convert.ToDecimal(candleOanda[i].bid.c);
                            newCandle.TimeStart = DateTime.Parse(candleOanda[i].time);
                            newCandle.State     = CandleStates.Finished;
                            newCandle.Volume    = candleOanda[i].volume;

                            candlesOsEngine.Add(newCandle);
                        }
                        series.CandlesAll = candlesOsEngine;
                    }

                    _candleManager.StartSeries(series);

                    SendLogMessage("Инструмент " + series.Security.Name + "ТаймФрейм " + series.TimeFrame +
                                   " успешно подключен на получение данных и прослушивание свечек",
                                   LogMessageType.System);

                    return(series);
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
                return(null);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// начать выкачивать данный иснтрументн
        /// </summary>
        /// <param name="namePaper"> название инструмента</param>
        /// <param name="timeFrameBuilder">объект несущий в себе данные о ТаймФрейме нужном для серии</param>
        /// <returns>в случае успешного запуска возвращает CandleSeries, объект генерирующий свечи</returns>
        public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder)
        {
            try
            {
                lock (_lockerStarter)
                {
                    if (namePaper == "")
                    {
                        return(null);
                    }

                    if (Portfolios == null || Securities == null)
                    {
                        return(null);
                    }

                    if (_lastStartServerTime != DateTime.MinValue &&
                        _lastStartServerTime.AddSeconds(15) > DateTime.Now)
                    {
                        return(null);
                    }

                    if (ServerStatus != ServerConnectStatus.Connect)
                    {
                        return(null);
                    }

                    if (_candleManager == null)
                    {
                        return(null);
                    }

                    Security security = null;

                    for (int i = 0; _securities != null && i < _securities.Count; i++)
                    {
                        if (_securities[i].Name == namePaper)
                        {
                            security = _securities[i];
                            break;
                        }
                    }

                    if (security == null)
                    {
                        return(null);
                    }

                    CandleSeries series = new CandleSeries(timeFrameBuilder, security, StartProgram.IsOsTrader);

                    ServerRealization.Subscrible(security);

                    Thread.Sleep(300);

                    _candleManager.StartSeries(series);

                    SendLogMessage(OsLocalization.Market.Message14 + series.Security.Name +
                                   OsLocalization.Market.Message15 + series.TimeFrame +
                                   OsLocalization.Market.Message16, LogMessageType.System);

                    if (_tickStorage != null)
                    {
                        _tickStorage.SetSecurityToSave(security);
                    }

                    return(series);
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
                return(null);
            }
        }
Esempio n. 29
0
 /// <summary>
 /// take candle history for period
 /// взять историю свечек за период
 /// </summary>
 public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime,
                                              DateTime actualTime)
 {
     return(GetCandleHistory(security.Name, timeFrameBuilder.TimeFrameTimeSpan, 5000));
 }
Esempio n. 30
0
        public override List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder, DateTime startTime, DateTime endTime, DateTime actualTime)
        {
            int oldInterval = Convert.ToInt32(timeFrameBuilder.TimeFrameTimeSpan.TotalSeconds);

            return(GetCandles(oldInterval, security.Name, startTime, endTime));
        }