private Task saveStockElementToDB(StockDataElement element)
        {
            return(Task.Run(() =>
            {
                lock (contextVol)
                {
                    //Int64 stockID = (from s in dbStocks
                    //                 where s.ticker == element.ticker
                    //                 select s.id).FirstOrDefault();
                    //if (stockID == 0)
                    //{
                    //    stocks ns = new stocks();
                    //    ns.ticker = element.ticker;
                    //    ns.enddate = null;
                    //    ns.pricestep = 100;
                    //    ns.active = true;
                    //    contextVol.stocks.InsertOnSubmit(ns);
                    //    contextVol.SubmitChanges();

                    //    dbStocks = from s in contextVol.stocks
                    //               where s.active == true
                    //               select s;
                    //    stockID = (from s in dbStocks
                    //               where s.ticker == element.ticker
                    //               select s.id).FirstOrDefault();
                    //}

                    volquotes nq = new volquotes();

                    nq.stock = stockID;
                    nq.timeframe = currentTimeFrameId;
                    nq.datetime = element.date;

                    nq.high = element.high;
                    nq.low = element.low;

                    nq.open = element.open;
                    nq.close = element.close;

                    nq.middle = element.middle;

                    nq.volume = element.Volume;
                    nq.volumebuy = element.VolumeBuy;
                    nq.volumesell = element.VolumeSell;

                    contextVol.volquotes.InsertOnSubmit(nq);
                    contextVol.SubmitChanges();
                }
            }));
        }
Example #2
0
        }                                                        // получение данных

        public override void ProcessTrade(Trade trade)
        {
            // получение данных из таблицы сделок
            while (working)
            {
            }   // wait for order will be processed

            var order = (from o in contextDb.orders
                         where o.OrderNum == trade.OrderNum &&
                         o.TradeNum == null
                         select o).FirstOrDefault();

            if (order == null)
            {
                //MessageBox.Show("В базе данных нет ордеров с номером - " + trade.OrderNum + ".", "Ошибка в программе " + cfg.FullProgName);
                return;
            }


            var posit = (from p in contextDb.positions
                         where p.stocks.ticker == trade.SecCode &&
                         p.active == true
                         select p).FirstOrDefault();

            // open position
            if (trade.Op == TradeOp.Buy)
            {
                if (posit != null)              // position
                {
                    if (posit.tradetypeid == 1) //bought
                    {
                        posit.priceopen = (posit.priceopen * posit.qty + trade.RawPrice * trade.Quantity) / (posit.qty + trade.Quantity);
                        posit.qty      += trade.Quantity;
                    }
                    else
                    if (posit.tradetypeid == 2)              //sold
                    {
                        if (posit.qty - trade.Quantity == 0) // close
                        {
                            posit.priceclose = trade.RawPrice;
                            posit.qty        = 0;
                            posit.closed     = trade.DateTime;
                            posit.active     = false;
                        }
                        else // downgrade position qty
                        {
                            posit.priceopen = (posit.priceopen * posit.qty.Value + trade.RawPrice * trade.Quantity) / (posit.qty.Value + trade.Quantity);
                            posit.qty      -= trade.Quantity;
                            if (posit.qty < 0)
                            {
                                posit.tradetypeid = 1; // если позиция перевернулась
                                posit.qty         = posit.qty * -1;
                            }
                        }
                    }
                }
                else // new position
                {
                    positions positNew = new positions();
                    var       stock    = (from s in contextDb.stocks
                                          where s.ticker == trade.SecCode
                                          select s).FirstOrDefault();
                    positNew.stock       = stock.id;
                    positNew.tradetypeid = 1;
                    positNew.opened      = trade.DateTime;
                    positNew.priceopen   = trade.RawPrice;
                    positNew.qty         = trade.Quantity;
                    positNew.openqty     = trade.Quantity;
                    positNew.active      = true;
                    contextDb.positions.InsertOnSubmit(positNew);
                }
            }
            else
            //close position
            if (trade.Op == TradeOp.Sell)
            {
                if (posit != null)                           // position
                {
                    if (posit.tradetypeid == 1)              //bought
                    {
                        if (posit.qty - trade.Quantity == 0) // close
                        {
                            posit.priceclose = trade.RawPrice;
                            posit.qty        = 0;
                            posit.closed     = trade.DateTime;
                            posit.active     = false;
                        }
                        else // downgrade position qty
                        {
                            posit.priceopen = (posit.priceopen * posit.qty + trade.RawPrice * trade.Quantity) / (posit.qty + trade.Quantity);
                            posit.qty      -= trade.Quantity;
                            if (posit.qty < 0)
                            {
                                posit.tradetypeid = 2; // если позиция перевернулась
                                posit.qty         = posit.qty * -1;
                            }
                        }
                    }
                    else
                    if (posit.tradetypeid == 2)     //sold
                    {
                        posit.priceopen = (posit.priceopen * posit.qty + trade.RawPrice * trade.Quantity) / (posit.qty + trade.Quantity);
                        posit.qty      += trade.Quantity;
                    }
                }
                else // new position
                {
                    positions positNew = new positions();
                    var       stock    = (from s in contextDb.stocks
                                          where s.ticker == trade.SecCode
                                          select s).FirstOrDefault();
                    positNew.stock       = stock.id;
                    positNew.tradetypeid = 2;
                    positNew.opened      = trade.DateTime;
                    positNew.priceopen   = trade.RawPrice;
                    positNew.qty         = trade.Quantity;
                    positNew.openqty     = trade.Quantity;
                    positNew.active      = true;
                    contextDb.positions.InsertOnSubmit(positNew);
                }
            }
            else
            {
                MessageBox.Show("Транзакция из QUIK с типом - " + trade.Op.ToString() + " не реализована.", "Ошибка в программе " + cfg.FullProgName);
                return;
            }

            long trdNum = 0;

            Int64.TryParse(trade.TradeNum.ToString(), out trdNum);
            order.TradeNum = trdNum;

            contextDb.SubmitChanges();
        }
        private Task saveSettingElementToDB(SettingDataElement element)
        {
            return(Task.Run(() =>
            {
                if (element.MatDate == null)
                {
                    return;
                }

                lock (contextSet)
                {
                    //Int64 stockID = (from s in dbStocks
                    //                 where s.ticker == element.SecCode
                    //                 select s.id).FirstOrDefault();
                    //if (stockID == 0)
                    //{
                    //    stocks ns = new stocks();
                    //    ns.ticker = element.SecCode;
                    //    ns.enddate = null;
                    //    ns.pricestep = 50;
                    //    ns.active = true;
                    //    contextSet.stocks.InsertOnSubmit(ns);
                    //    contextSet.SubmitChanges();

                    //    dbStocks = from s in contextSet.stocks
                    //               where s.active == true
                    //               select s;
                    //    stockID = (from s in dbStocks
                    //               where s.ticker == element.SecCode
                    //               select s.id).FirstOrDefault();
                    //}

                    settingquotes nq = new settingquotes();

                    nq.stock = stockID;
                    nq.timeframe = currentTimeFrameId;
                    nq.datetime = element.DateTime;

                    nq.seccode = element.SecCode;                     // код бумаги
                    nq.classcode = element.ClassCode;                 // код класса
                    nq.classname = element.ClassName;                 // класс бумаги
                    nq.optionbase = element.OptionBase;               // +1 базовый актив опциона
                    nq.matdate = element.MatDate;                     // +1 дата погашения
                    nq.daystomatdate = element.DaysToMatDate;         // дней до погашения

                    nq.numbidsopen = element.NumbidsOpen;             // количество заявкок на покупку
                    nq.numbidshigh = element.NumbidsHigh;             // количество заявкок на покупку
                    nq.numbidslow = element.NumbidsLow;               // количество заявкок на покупку
                    nq.numbidsclose = element.NumbidsClose;           // количество заявкок на покупку

                    nq.numoffersopen = element.NumoffersOpen;         // количество заявок на продажу
                    nq.numoffershigh = element.NumoffersHigh;         // количество заявок на продажу
                    nq.numofferslow = element.NumoffersLow;           // количество заявок на продажу
                    nq.numoffersclose = element.NumoffersClose;       // количество заявок на продажу

                    nq.biddepthtopen = element.BiddepthtOpen;         // суммарный спрос контрактов
                    nq.biddepththigh = element.BiddepthtHigh;         // суммарный спрос контрактов
                    nq.biddepthtlow = element.BiddepthtLow;           // суммарный спрос контрактов
                    nq.biddepthtclose = element.BiddepthtClose;       // суммарный спрос контрактов

                    nq.offerdepthtopen = element.OfferdepthtOpen;     // суммарное предложение контрактов
                    nq.offerdepththigh = element.OfferdepthtHigh;     // суммарное предложение контрактов
                    nq.offerdepthtlow = element.OfferdepthtLow;       // суммарное предложение контрактов
                    nq.offerdepthtclose = element.OfferdepthtClose;   // суммарное предложение контрактов

                    nq.voltoday = element.Voltoday;                   // количество во всех сделках
                    nq.valtoday = element.Valtoday;                   // текущий оборот в деньгах
                    nq.numtrades = element.Numtrades;                 // количество сделок за сегодня

                    nq.numcontractsopen = element.NumcontractsOpen;   // количество открытых позиций (Открытый Интерес)
                    nq.numcontractshigh = element.NumcontractsHigh;   // количество открытых позиций (Открытый Интерес)
                    nq.numcontractslow = element.NumcontractsLow;     // количество открытых позиций (Открытый Интерес)
                    nq.numcontractsclose = element.NumcontractsClose; // количество открытых позиций (Открытый Интерес)

                    nq.selldepo = element.Selldepo;                   // ГО продавца
                    nq.buydepo = element.Buydepo;                     // ГО покупателя
                    nq.strike = element.Strike;                       // +1 цена страйк
                    nq.optiontype = element.OptionType;               // +1 тип опциона CALL PUT
                    nq.volatility = element.Volatility;               // +1 волатильность опциона


                    contextSet.settingquotes.InsertOnSubmit(nq);
                    contextSet.SubmitChanges();
                }
            }));
        }
        private Task createNew_VAT(string SecCode)
        {
            return(Task.Run(() =>
            {
                lock (contextVaR)
                {
                    // 2. Value-At-Risk

                    var lastVaR = (from v in contextVaR.valueatrisk
                                   where v.stock == stockID &&
                                   v.timeframe == currentTimeFrameId
                                   orderby v.datetime descending
                                   select v).FirstOrDefault();

                    Int64 varIDforAllSelect = 0;
                    Int64 lastVarQuoteID = 0;
                    DateTime lastVarDateTime = DateTime.Today;
                    if (lastVaR != null)
                    {
                        varIDforAllSelect = 1000;
                        if (lastVaR.volquoteid < 1000)
                        {
                            varIDforAllSelect = lastVaR.volquoteid;
                        }

                        lastVarQuoteID = lastVaR.volquoteid;
                        lastVarDateTime = lastVaR.datetime.Value;
                    }

                    var allQuotes2_tmp = from q in contextVaR.volquotes
                                         where q.stock == stockID &&
                                         q.timeframe == currentTimeFrameId &&
                                         q.id > varIDforAllSelect
                                         orderby q.id ascending
                                         select q;
                    var allQuotes2 = allQuotes2_tmp.ToArray();

                    var countQuotes2_tmp = from q in contextVaR.volquotes
                                           where q.stock == stockID &&
                                           q.timeframe == currentTimeFrameId &&
                                           q.id > lastVarQuoteID
                                           orderby q.id ascending
                                           select q;

                    var setting_tmp = from s in contextVaR.settingquotes
                                      where s.stock == stockID &&
                                      s.timeframe == currentTimeFrameId &&
                                      s.datetime > lastVarDateTime
                                      select s;
                    if (setting_tmp.Count() == 0)
                    {
                        return;
                    }

                    foreach (volquotes quote in countQuotes2_tmp)
                    {
                        var allQuotes3 = from q in allQuotes2
                                         where q.datetime <= quote.datetime
                                         orderby q.datetime ascending
                                         select q;
                        double[] close = new double[allQuotes3.Count()];
                        int i = 0;
                        foreach (volquotes quote2 in allQuotes3)
                        {
                            close[i] = quote2.close.Value;
                            i++;
                        }

                        var setting = (from s in setting_tmp
                                       where s.stock == stockID &&
                                       s.datetime <= quote.datetime
                                       select s).FirstOrDefault();
                        if (setting == null)
                        {
                            continue; // не создаем Value At Risk
                        }
                        double ValueSum = setting.buydepo.Value;

                        int begIdx = 0;
                        int NBElement = 0;
                        double[] real = null;

                        ValueAtRiskUtils.stdDev((close.Count() - 35), (close.Count() - 1), close, 10, 1, out begIdx, out NBElement, out real);

                        int time = 1; // 1 день

                        double W = real[34] / close[close.Count() - 1];
                        double VaR = ValueAtRiskUtils.getStockVaR(W, ValueSum, time);

                        valueatrisk vAr = new valueatrisk();
                        vAr.stock = stockID;
                        vAr.timeframe = currentTimeFrameId;
                        vAr.datetime = quote.datetime;
                        vAr.volquoteid = quote.id;
                        vAr.value = VaR;
                        vAr.buydepo = ValueSum;
                        contextVaR.valueatrisk.InsertOnSubmit(vAr);
                        contextVaR.SubmitChanges();
                    }
                }
            }));
        }