示例#1
0
        private int GetLotSize(int insID)
        {
            if (_insID_lotSize == null)
            {
                _insID_lotSize = new Dictionary <int, int>();
            }

            if (_insID_lotSize.ContainsKey(insID))
            {
                return(_insID_lotSize[insID]);
            }
            else
            {
                Instrum ins = _instrumBL.GetInstrumByID(insID);
                if (ins != null)
                {
                    _insID_lotSize.Add(ins.InsID, ins.LotSize);
                    return(ins.LotSize);
                }
                else
                {
                    _insID_lotSize.Add(insID, 1);
                    return(1);
                }
            }
        }
示例#2
0
文件: InstrumDA.cs 项目: vlshl/leech
        /// <summary>
        /// Get instrument by id or ticker
        /// </summary>
        /// <param name="insID">Instrument id or 0</param>
        /// <param name="ticker">Ticker or null/empty string</param>
        /// <returns></returns>
        public CommonData.Instrum GetInstrum(int insID, string ticker = null)
        {
            Instrum ins = null;

            if (insID > 0)
            {
                ins = _da.DbContext.Table <Instrum>().FirstOrDefault(s => s.InsID == insID);
            }
            else if (ticker != null && ticker.Length > 0)
            {
                ins = _da.DbContext.Table <Instrum>().FirstOrDefault(s => s.Ticker == ticker);
            }
            if (ins == null)
            {
                return(null);
            }

            return(new CommonData.Instrum()
            {
                InsID = ins.InsID,
                Ticker = ins.Ticker,
                ShortName = ins.ShortName,
                Name = ins.Name,
                LotSize = ins.LotSize,
                Decimals = ins.Decimals,
                PriceStep = ins.PriceStep
            });
        }
示例#3
0
        /// <summary>
        /// Последние сделки за текущую торговую сессию
        /// </summary>
        /// <param name="today">Дата торговой сессии (без времени)</param>
        /// <param name="instrum">Инструмент</param>
        /// <param name="skip">Сколько сделок пропустить</param>
        /// <returns>Массив сделок для указанного инструмента на текущий момент, если null - ошибка, пустой массив - нет новых сделок</returns>
        public async Task <Tick[]> GetLastTicks(DateTime today, Instrum instrum, int skip)
        {
            var res = await _core.SendMessageAsync(_pipe, Encoding.UTF8.GetBytes("GetLastTicks " + instrum.Ticker + " " + skip.ToString()));

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

            if (res.Length == 1 && res[0] != 0)
            {
                return(null);
            }
            if (res.Length == 1 && res[0] == 0)
            {
                return new Tick[] { }
            }
            ;

            AllTradesEncoding enc = new AllTradesEncoding(instrum.Decimals);

            try
            {
                var list = enc.Decode(res, false);

                return(list.Select(r => new Tick(0, today.Date.AddSeconds(r.Second), instrum.InsID, r.Lots, r.Price)).ToArray());
            }
            catch
            {
                return(null);
            }
        }
    }
示例#4
0
        /// <summary>
        /// Сохранение данных по всем сделкам для всех инструментов
        /// </summary>
        /// <param name="tickDispatcher">Диспетчер тиковых данных</param>
        /// <param name="sessionDbPath">Каталог данных текущей сессии (определяется датой)</param>
        public void SaveData(ITickDispatcher tickDispatcher, string sessionDbPath)
        {
            if (tickDispatcher == null)
            {
                throw new ArgumentNullException("tickDispatcher");
            }
            if (string.IsNullOrWhiteSpace(sessionDbPath))
            {
                throw new ArgumentException("SessionDbPath is empty, session not opened.");
            }

            _logger.AddInfo("AllTradesData", "Save data ...");
            try
            {
                var allTradesDir = Path.Combine(sessionDbPath, "AllTrades");

                if (!Directory.Exists(allTradesDir))
                {
                    Directory.CreateDirectory(allTradesDir);
                }

                var insIDs = tickDispatcher.GetInstrumIDs();
                foreach (var insID in insIDs)
                {
                    Instrum ins = _instrumTable.GetInstrum(insID);
                    if (ins == null)
                    {
                        continue;
                    }
                    var ticks = tickDispatcher.GetTicks(insID);
                    if (ticks == null || !ticks.Any())
                    {
                        continue;
                    }

                    var encoder = new AllTradesEncoder(ins.Decimals);
                    var persist = new AllTradesPersist();
                    persist.Initialize(allTradesDir, ins.Ticker);
                    _insStoreData.InitInsStores(insID);

                    foreach (Tick tick in ticks)
                    {
                        uint   seconds = (uint)(tick.Time.Hour * 60 * 60 + tick.Time.Minute * 60 + tick.Time.Second);
                        byte[] buf     = encoder.AddTick(seconds, tick.Price, tick.Lots);
                        persist.Write(buf);
                        _insStoreData.AddTick(insID, tick.Time, tick.Price, tick.Lots);
                    }
                    persist.Close();
                }
                _insStoreData.SaveData();
            }
            catch (Exception ex)
            {
                _logger.AddException("AllTradesData", ex);
            }
            _logger.AddInfo("AllTradesData", "Data saved");
        }
示例#5
0
        /// <summary>
        /// Инициализация графика
        /// </summary>
        /// <param name="xdChart">Данные для инициализации</param>
        public void Initialize(XDocument xdChart = null)
        {
            if (xdChart == null)
            {
                xdChart = new XDocument(new XElement("Chart"));
            }

            var xnSources = xdChart.Root.Element("Sources");

            if (xnSources != null)
            {
                foreach (var xnSrc in xnSources.Elements())
                {
                    if (xnSrc.Name == "BarRow")
                    {
                        int    insID = 0;
                        string guid  = xnSrc.Attribute("Id").Value;
                        int.TryParse(xnSrc.Attribute("InsID").Value, out insID);
                        int tf = 0;
                        int.TryParse(xnSrc.Attribute("Tf").Value, out tf);
                        if (insID == 0)
                        {
                            continue;
                        }
                        Instrum ins = _instrumBL.GetInstrumByID(insID);
                        if (ins == null)
                        {
                            continue;
                        }

                        CreateBarRowSource(ins, (Timeframes)tf, guid);
                    }
                }
            }

            _indicators.Clear();
            var xnIndicators = xdChart.Root.Element("Indicators");

            if (xnIndicators != null)
            {
                foreach (var xnIndic in xnIndicators.Elements())
                {
                    var indic = _factory.CreateIndicator(xnIndic.Name.ToString());
                    if (indic == null)
                    {
                        continue;
                    }

                    indic.Initialize(new XDocument(xnIndic));
                    AddIndicator(indic);
                }
            }
        }
示例#6
0
        private void UpdateInstrum(Instrum ins, string shortname, string name, int lotsize, int decimals, decimal pricestep)
        {
            if (ins.ShortName == shortname && ins.Name == name && ins.LotSize == lotsize && ins.Decimals == decimals && ins.PriceStep == pricestep)
            {
                return;
            }

            ins.ShortName = shortname;
            ins.Name      = name;
            ins.LotSize   = lotsize;
            ins.Decimals  = decimals;
            ins.PriceStep = pricestep;
            _da.UpdateInstrum(ins);
        }
示例#7
0
文件: InstrumDA.cs 项目: vlshl/leech
        /// <summary>
        /// Update instrum object
        /// </summary>
        /// <param name="ins">Instrum object with InsID > 0</param>
        public void UpdateInstrum(CommonData.Instrum ins)
        {
            Instrum db_ins = new Instrum()
            {
                InsID     = ins.InsID,
                Ticker    = ins.Ticker,
                ShortName = ins.ShortName,
                Name      = ins.Name,
                LotSize   = ins.LotSize,
                Decimals  = ins.Decimals,
                PriceStep = ins.PriceStep
            };

            _da.DbContext.Update(db_ins);
        }
示例#8
0
        /// <summary>
        /// Загрузка исторических данных в BarRow.
        /// Наиболее подходящий InsStore определяется автоматически.
        /// </summary>
        /// <param name="bars">BarRow</param>
        /// <param name="insID">Инструмент</param>
        /// <param name="date1">Нач дата</param>
        /// <param name="date2">Кон дата</param>
        /// <param name="insStoreID">Поток данных для загрузки (если null, то поток будет определен автоматически)</param>
        /// <returns>Асинхронная задача загрузки. Общее число баров после загрузки.</returns>
        public async Task <int> LoadHistoryAsync(BarRow bars, int insID, DateTime date1, DateTime date2, int?insStoreID = null)
        {
            Instrum instrum = _instrumBL.GetInstrumByID(insID);

            if (instrum == null)
            {
                return(0);
            }

            if (insStoreID == null)
            {
                var insStore = GetLoadHistoryInsStore(insID, bars.Timeframe);
                if (insStore != null)
                {
                    insStoreID = insStore.InsStoreID;
                }
            }
            if (insStoreID == null)
            {
                return(0);
            }

            int k    = (int)Math.Pow(10, instrum.Decimals);
            var list = await _insStoreDA.GetHistoryAsync(insStoreID.Value, date1, date2);

            return(await Task.Run(() =>
            {
                bars.SuspendEvents();
                foreach (var bar in list)
                {
                    DateTime time = StorageLib.ToDateTime(bar.Time);
                    decimal openPrice = (decimal)bar.OpenPrice / k;
                    decimal lowPrice = (decimal)(bar.OpenPrice + bar.LowDelta) / k;
                    decimal highPrice = (decimal)(bar.OpenPrice + bar.HighDelta) / k;
                    decimal closePrice = (decimal)(bar.OpenPrice + bar.CloseDelta) / k;

                    bars.AddTick(time, openPrice, 0);
                    bars.AddTick(time, lowPrice, 0);
                    bars.AddTick(time, highPrice, 0);
                    bars.AddTick(time, closePrice, bar.Volume);
                }
                bars.CloseLastBar();
                bars.ResumeEvents();

                return bars.Count;
            }));
        }
示例#9
0
        public int InsertInstrum(string ticker, string shortName, string name, int lotSize, int decimals, decimal priceStep)
        {
            Instrum instrum = new Instrum()
            {
                InsID     = nextID++,
                Ticker    = ticker,
                ShortName = shortName,
                Name      = name,
                LotSize   = lotSize,
                Decimals  = decimals,
                PriceStep = priceStep
            };

            _id_instrum.Add(instrum.InsID, instrum);

            return(instrum.InsID);
        }
示例#10
0
        public Instrum AddInstrum(string ticker, string shortName)
        {
            var ins = new Instrum()
            {
                InsID     = _instrums.Count + 1,
                Ticker    = ticker,
                ShortName = shortName,
                Name      = shortName,
                Decimals  = 1,
                PriceStep = 0.01m,
                LotSize   = 1
            };

            _instrums.Add(ins);

            return(ins);
        }
示例#11
0
        /// <summary>
        /// Get instrument by id or ticker
        /// </summary>
        /// <param name="insID">Instrument id or 0</param>
        /// <param name="ticker">Ticker or null/empty string</param>
        /// <returns></returns>
        public Instrum GetInstrum(int insID, string ticker = null)
        {
            Instrum ins = null;

            using (var db = new DaContext(_options))
            {
                if (insID > 0)
                {
                    ins = db.Instrum.Find(insID);
                }
                else if (ticker != null && ticker.Length > 0)
                {
                    ins = db.Instrum.FirstOrDefault(s => s.Ticker == ticker);
                }
            }

            return(ins);
        }
示例#12
0
文件: InstrumDA.cs 项目: vlshl/leech
        /// <summary>
        /// Insert Instrum object into db
        /// </summary>
        /// <param name="ins">Instrum object with id = 0</param>
        /// <returns>New Id and set this value to InsID</returns>
        public int InsertInstrum(CommonData.Instrum ins)
        {
            Instrum db_ins = new Instrum()
            {
                InsID     = ins.InsID,
                Ticker    = ins.Ticker,
                ShortName = ins.ShortName,
                Name      = ins.Name,
                LotSize   = ins.LotSize,
                Decimals  = ins.Decimals,
                PriceStep = ins.PriceStep
            };

            _da.DbContext.Insert(db_ins);
            ins.InsID = db_ins.InsID;

            return(ins.InsID);
        }
示例#13
0
        public PosManager(int insID, IInstrumTable instrums, IHoldingTable holdings, IOrderTable orders, IAccountTable accounts, AlorTradeWrapper alorTrade)
        {
            _holdings = holdings;
            _orders   = orders;
            _instrum  = instrums.GetInstrum(insID);
            if (_instrum == null)
            {
                throw new Exception("Инструмент не найден");
            }

            _account = accounts.GetDefaultAccount();
            if (_account == null)
            {
                throw new Exception("Не найден торговый счет");
            }

            _alorTrade = alorTrade;
        }
示例#14
0
        public InstrumBLMock()
        {
            _instrums = new List <Instrum>();

            Instrum instrum1 = new Instrum()
            {
                InsID     = 1,
                Ticker    = "ticker1",
                Name      = "name1",
                ShortName = "shortname1",
                Decimals  = 0,
                LotSize   = 1,
                PriceStep = 0.01m
            };

            _instrums.Add(instrum1);

            Instrum instrum2 = new Instrum()
            {
                InsID     = 2,
                Ticker    = "ticker2",
                Name      = "name2",
                ShortName = "shortname2",
                Decimals  = 0,
                LotSize   = 1,
                PriceStep = 0.01m
            };

            _instrums.Add(instrum2);

            Instrum instrum3 = new Instrum()
            {
                InsID     = 3,
                Ticker    = "ticker3",
                Name      = "name3",
                ShortName = "shortname3",
                Decimals  = 0,
                LotSize   = 1,
                PriceStep = 0.01m
            };

            _instrums.Add(instrum3);
        }
示例#15
0
        /// <summary>
        /// Insert new instrum to db
        /// </summary>
        /// <param name="ticker">Ticker</param>
        /// <param name="shortName">Short name</param>
        /// <param name="name">Full name</param>
        /// <param name="lotSize">Lot size</param>
        /// <param name="decimals">Decimals</param>
        /// <param name="priceStep">Price step</param>
        /// <returns>New instrum identity</returns>
        public int InsertInstrum(string ticker, string shortName, string name, int lotSize, int decimals, decimal priceStep)
        {
            Instrum ins = new Instrum()
            {
                Ticker    = ticker,
                ShortName = shortName,
                Name      = name,
                LotSize   = lotSize,
                Decimals  = decimals,
                PriceStep = priceStep
            };

            using (var db = new DaContext(_options))
            {
                db.Instrum.Add(ins);
                db.SaveChanges();
            }

            return(ins.InsID);
        }
示例#16
0
        private void CreateBarRowSource(Instrum ins, Timeframes tf, string guid)
        {
            BarRow bars = new BarRow(tf, ins.InsID);

            _chartData = new ChartData(bars.Dates, ins.Decimals, _isDynamic);
            _chartData.AddPrices(bars, new ChartBrush(0, 0, 0));
            _guid_source.Add(guid, new PriceSource()
            {
                Bars = bars, Instrum = ins
            });

            _srcProv.Initialize(new List <ValueRowSource>()
            {
                new ValueRowSource(guid + ":O", "Open", bars.Open, bars),
                new ValueRowSource(guid + ":H", "High", bars.High, bars),
                new ValueRowSource(guid + ":L", "Low", bars.Low, bars),
                new ValueRowSource(guid + ":C", "Close", bars.Close, bars),
                new ValueRowSource(guid + ":T", "Typical", bars.Typical, bars),
                new ValueRowSource(guid + ":M", "Median", bars.Median, bars)
            });
        }
示例#17
0
        /// <summary>
        /// Список инструментов на дату, для которых имеются исторические тиковые данные
        /// </summary>
        /// <param name="date">Дата</param>
        /// <returns>Список инструментов или пустой список</returns>
        public IEnumerable <Instrum> GetInstrumsByDate(DateTime date)
        {
            var insIDs = _tickHistoryDA.GetInstrums(date);

            if (insIDs == null)
            {
                return(new List <Instrum>());
            }

            List <Instrum> instrums = new List <Instrum>();

            foreach (var insID in insIDs)
            {
                Instrum instrum = _instrumBL.GetInstrumByID(insID);
                if (instrum != null)
                {
                    instrums.Add(instrum);
                }
            }

            return(instrums);
        }
示例#18
0
 /// <summary>
 /// Синхронизировать фин. инструмент (изменить или создать новый)
 /// </summary>
 /// <param name="ticker">Тикер</param>
 /// <param name="shortname">Краткое наименование</param>
 /// <param name="name">Полное наименование</param>
 /// <param name="lotsize">Размер лота</param>
 /// <param name="decimals">Кол-во десятичных знаков после запятой в цене</param>
 /// <param name="pricestep">Шаг цены</param>
 /// <returns>Фин. инструмент после синхронизации</returns>
 public Instrum SyncInstrum(string ticker, string shortname, string name, int lotsize, int decimals, decimal pricestep)
 {
     if (!_ticker_instrum.ContainsKey(ticker))
     {
         Instrum db_ins = _da.GetInstrum(0, ticker);
         if (db_ins == null)
         {
             var ins = new Instrum
             {
                 InsID     = 0,
                 Ticker    = ticker,
                 ShortName = shortname,
                 Name      = name,
                 LotSize   = lotsize,
                 Decimals  = decimals,
                 PriceStep = pricestep
             };
             _da.InsertInstrum(ins);
             _ticker_instrum.Add(ticker, ins);
             _insID_instrum.Add(ins.InsID, ins);
             return(ins);
         }
         else
         {
             UpdateInstrum(db_ins, shortname, name, lotsize, decimals, pricestep);
             _ticker_instrum.Add(ticker, db_ins);
             _insID_instrum.Add(db_ins.InsID, db_ins);
             return(db_ins);
         }
     }
     else
     {
         var ins = _ticker_instrum[ticker];
         UpdateInstrum(ins, shortname, name, lotsize, decimals, pricestep);
         return(ins);
     }
 }
示例#19
0
 public void SaveInstrum(Instrum ins)
 {
     throw new NotImplementedException();
 }
示例#20
0
        private IEnumerable <Tick> SynTicks(Bar bar, Instrum instrum)
        {
            decimal     p1 = 0, p2 = 0, p3 = 0, q = 0;
            int         n1 = 0; int n2 = 0; int n3 = 0;
            List <Tick> ticks = new List <Tick>();

            DateTime time     = bar.Time;
            DateTime lastTime = bar.NextBarTime.AddSeconds(-1);
            decimal  price    = bar.Open;
            long     ls       = (long)(bar.Volume / instrum.LotSize);
            int      lots     = (ls > int.MaxValue) ? int.MaxValue : (ls < int.MinValue) ? int.MinValue : (int)ls;
            int      lot_step = lots / 60;

            if (bar.Open <= bar.Close) // while bar
            {
                p1 = bar.Open - bar.Low;
                p2 = bar.High - bar.Low;
                p3 = bar.High - bar.Close;
                q  = (p1 + p2 + p3) / 60m;
                if (q != 0)
                {
                    n1 = (int)(p1 / q);
                    n3 = (int)(p3 / q);
                }
                if (n1 <= 0)
                {
                    n1 = 1;
                }
                if (n3 <= 0)
                {
                    n3 = 1;
                }

                for (int i = 0; i < n1; i++)
                {
                    decimal pr = Math.Round(price, instrum.Decimals);
                    if (pr > bar.High)
                    {
                        pr = bar.High;
                    }
                    if (pr < bar.Low)
                    {
                        pr = bar.Low;
                    }
                    ticks.Add(new Tick(0, time, instrum.InsID, lot_step, pr));
                    price -= q;
                    lots  -= lot_step;
                    if (time < lastTime)
                    {
                        time = time.AddSeconds(1);
                    }
                }

                n2    = 60 - n1 - n3 - 1;
                price = bar.Low;
                for (int i = 0; i < n2; i++)
                {
                    decimal pr = Math.Round(price, instrum.Decimals);
                    if (pr > bar.High)
                    {
                        pr = bar.High;
                    }
                    if (pr < bar.Low)
                    {
                        pr = bar.Low;
                    }
                    ticks.Add(new Tick(0, time, instrum.InsID, lot_step, pr));
                    price += q;
                    lots  -= lot_step;
                    if (time < lastTime)
                    {
                        time = time.AddSeconds(1);
                    }
                }

                price = bar.High;
                for (int i = 0; i < n3; i++)
                {
                    decimal pr = Math.Round(price, instrum.Decimals);
                    if (pr > bar.High)
                    {
                        pr = bar.High;
                    }
                    if (pr < bar.Low)
                    {
                        pr = bar.Low;
                    }
                    ticks.Add(new Tick(0, time, instrum.InsID, lot_step, pr));
                    price -= q;
                    lots  -= lot_step;
                    if (time < lastTime)
                    {
                        time = time.AddSeconds(1);
                    }
                }
            }
            else // black bar
            {
                p1 = bar.High - bar.Open;
                p2 = bar.High - bar.Low;
                p3 = bar.Close - bar.Low;
                q  = (p1 + p2 + p3) / 60m;
                if (q != 0)
                {
                    n1 = (int)(p1 / q);
                    n3 = (int)(p3 / q);
                }
                if (n1 <= 0)
                {
                    n1 = 1;
                }
                if (n3 <= 0)
                {
                    n3 = 1;
                }

                for (int i = 0; i < n1; i++)
                {
                    decimal pr = Math.Round(price, instrum.Decimals);
                    if (pr > bar.High)
                    {
                        pr = bar.High;
                    }
                    if (pr < bar.Low)
                    {
                        pr = bar.Low;
                    }
                    ticks.Add(new Tick(0, time, instrum.InsID, lot_step, pr));
                    price += q;
                    lots  -= lot_step;
                    if (time < lastTime)
                    {
                        time = time.AddSeconds(1);
                    }
                }

                n2    = 60 - n1 - n3 - 1;
                price = bar.High;
                for (int i = 0; i < n2; i++)
                {
                    decimal pr = Math.Round(price, instrum.Decimals);
                    if (pr > bar.High)
                    {
                        pr = bar.High;
                    }
                    if (pr < bar.Low)
                    {
                        pr = bar.Low;
                    }
                    ticks.Add(new Tick(0, time, instrum.InsID, lot_step, pr));
                    price -= q;
                    lots  -= lot_step;
                    if (time < lastTime)
                    {
                        time = time.AddSeconds(1);
                    }
                }

                price = bar.Low;
                for (int i = 0; i < n3; i++)
                {
                    decimal pr = Math.Round(price, instrum.Decimals);
                    if (pr > bar.High)
                    {
                        pr = bar.High;
                    }
                    if (pr < bar.Low)
                    {
                        pr = bar.Low;
                    }
                    ticks.Add(new Tick(0, time, instrum.InsID, lot_step, pr));
                    price += q;
                    lots  -= lot_step;
                    if (time < lastTime)
                    {
                        time = time.AddSeconds(1);
                    }
                }
            }
            ticks.Add(new Tick(0, time, instrum.InsID, lots > 0 ? lots : 0, bar.Close));

            return(ticks);
        }