コード例 #1
0
        /// <summary>
        /// CTP合约数据转换。
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        private USeInstrumentDetail InsturmentFiledToUSeInstrumentDetail(InstrumentField field)
        {
            USeMarket market = CtpProtocol.CtpExchangeToUSeMarket(field.ExchangeID);

            USeInstrumentDetail entity = new USeInstrumentDetail();

            entity.Instrument = new USeInstrument(field.InstrumentID,
                                                  field.InstrumentName,
                                                  market);
            entity.OpenDate   = DateTime.ParseExact(field.OpenDate, "yyyyMMdd", null);
            entity.ExpireDate = DateTime.ParseExact(field.ExpireDate, "yyyyMMdd", null);
            if (string.IsNullOrEmpty(field.StartDelivDate) == false)
            {
                entity.StartDelivDate = DateTime.ParseExact(field.StartDelivDate, "yyyyMMdd", null);
            }
            else
            {
                entity.StartDelivDate = entity.ExpireDate.AddDays(1);
            }
            entity.EndDelivDate             = DateTime.ParseExact(field.EndDelivDate, "yyyyMMdd", null);
            entity.VolumeMultiple           = Convert.ToInt32(field.VolumeMultiple);
            entity.IsTrading                = field.IsTrading == IntBoolType.Yes;
            entity.Varieties                = field.ProductID;
            entity.PriceTick                = Convert.ToDecimal(field.PriceTick);
            entity.ProductClass             = CtpProtocol.CtpProductClassToUSeProductClass(field.ProductClass);
            entity.MaxMarketOrderVolume     = Convert.ToInt32(field.MaxMarketOrderVolume);
            entity.MinMarketOrderVolume     = Convert.ToInt32(field.MinMarketOrderVolume);
            entity.MaxLimitOrderVolume      = Convert.ToInt32(field.MaxLimitOrderVolume);
            entity.MinLimitOrderVolume      = Convert.ToInt32(field.MinLimitOrderVolume);
            entity.ExchangeLongMarginRatio  = Convert.ToDecimal(field.LongMarginRatio);
            entity.ExchangeShortMarginRatio = Convert.ToDecimal(field.ShortMarginRatio);

            return(entity);
        }
コード例 #2
0
ファイル: USeMarket.cs プロジェクト: handayu/TFS-WebKit
        /// <summary>
        /// 市场中文描述。
        /// </summary>
        /// <param name="market"></param>
        /// <returns></returns>
        public static string ToDescription(this USeMarket market)
        {
            switch (market)
            {
            case USeMarket.CFFEX: return("中金所");

            case USeMarket.CZCE: return("郑商所");

            case USeMarket.DCE: return("大商所");

            case USeMarket.SHFE: return("上期所");

            case USeMarket.INE: return("能源中心");

            case USeMarket.SH: return("上交所");

            case USeMarket.SZ: return("深交所");

            case USeMarket.LME: return("伦敦金属");

            case USeMarket.COMEX: return("纽约商业");

            case USeMarket.TOCOM: return("东京交易所");

            case USeMarket.SGX: return("新加坡交易所");

            default: return(string.Empty);
            }
        }
コード例 #3
0
        /// <summary>
        /// 获取数据表名。
        /// </summary>
        /// <param name="kLine"></param>
        /// <returns></returns>
        private string GetDBTableName(USeCycleType cycle, USeMarket market)
        {
            string tableName = string.Empty;

            if (cycle == USeCycleType.Day)
            {
                tableName = "day_kline";
            }
            else if (cycle == USeCycleType.Min1)
            {
                switch (market)
                {
                case USeMarket.CFFEX:
                case USeMarket.CZCE:
                case USeMarket.DCE:
                case USeMarket.SHFE:
                    tableName = string.Format("min1_kline_{0}", market.ToString().ToLower());
                    break;

                default:
                    Debug.Assert(false);
                    throw new Exception("Invalid market:" + market.ToString());
                }
            }
            else
            {
                throw new Exception("Invalid cycel:" + cycle.ToString());
            }
            return(tableName);
        }
コード例 #4
0
        /// <summary>
        /// 从数据库中获得合约表。
        /// </summary>
        /// <param name="monitorMarketes"></param>
        /// <returns></returns>
        private List <USeInstrument> GetSubscribeInstruments(List <USeMarket> monitorMarketes)
        {
            List <USeInstrument> instrumentList = new List <USeInstrument>();

            string strSel = string.Format(@"select contract,contract_name,exchange, open_date,expire_date,is_trading from {0}.contracts 
                              where product_class ='Futures' and UNIX_TIMESTAMP(CURDATE()) >= UNIX_TIMESTAMP(open_date) and  UNIX_TIMESTAMP(CURDATE()) <= UNIX_TIMESTAMP(expire_date);", m_dbName);

            DataTable table = new DataTable();

            using (MySqlConnection connection = new MySqlConnection(m_dbConnStr))
            {
                connection.Open();
                MySqlDataAdapter adapter = new MySqlDataAdapter(strSel, connection);
                adapter.Fill(table);
            }

            foreach (DataRow row in table.Rows)
            {
                USeMarket market = (USeMarket)Enum.Parse(typeof(USeMarket), row["exchange"].ToString());

                USeInstrument instrument = new USeInstrument(row["contract"].ToString(),
                                                             row["contract_name"].ToString(),
                                                             market);

                instrumentList.Add(instrument);
            }
            return(instrumentList);
        }
コード例 #5
0
        private void ProcessUSeMarketData(USeMarketData marketData)
        {
            Debug.Assert(marketData.QuoteDay.HasValue);
            Debug.Assert(marketData.QuoteTime.HasValue);

            if (USeManager.Instance.DayNightType == DayNightType.Night)
            {
                USeMarket market = USeMarket.Unknown;
                if (m_instrumentDic.TryGetValue(marketData.Instrument.InstrumentCode, out market) == false)
                {
                    Debug.Assert(false);
                }

                if (market == USeMarket.SHFE || market == USeMarket.DCE)// 如果是上期所,大连
                {
                    DateTime preTradeDay = USeManager.Instance.TradeCalendarManager.GetPreTradingDate(marketData.QuoteDay.Value);
                    if (marketData.QuoteTime.Value > new TimeSpan(20, 45, 0))
                    {
                        marketData.UpdateTime = preTradeDay.Add(marketData.QuoteTime.Value);
                    }
                    else
                    {
                        marketData.UpdateTime = preTradeDay.AddDays(1).Add(marketData.QuoteTime.Value);
                    }
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// 获取主力合约列表。
        /// </summary>
        /// <returns></returns>
        private List <MainContractEntity> GetMainContractList()
        {
            string cmdText = string.Format(@"select varieties, exchange, settlement_date, main_contract from {0}.main_contract
where settlement_date >= '{1:yyyy-MM-dd}' and settlement_date <= '{2:yyyy-MM-dd}'
order by settlement_date, exchange, varieties;",
                                           m_alphaDBName, m_beginDate, m_endDate);

            DataTable table = new DataTable();

            using (MySqlConnection connection = new MySqlConnection(m_dbConStr))
            {
                MySqlDataAdapter adapter = new MySqlDataAdapter(cmdText, connection);
                adapter.Fill(table);
            }

            List <MainContractEntity> mainContractList = new List <MainContractEntity>();

            foreach (DataRow row in table.Rows)
            {
                USeMarket          exchange     = (USeMarket)Enum.Parse(typeof(USeMarket), row["exchange"].ToString());
                MainContractEntity mainContract = new MainContractEntity()
                {
                    Varieties        = row["varieties"].ToString(),
                    Exchange         = exchange,
                    SettlementDate   = Convert.ToDateTime(row["settlement_date"]),
                    BaseContract     = row["main_contract"].ToString(),
                    MainContractCode = USeTraderProtocol.GetMainContractCode(row["varieties"].ToString(), exchange).InstrumentCode
                };
                mainContractList.Add(mainContract);
            }

            return(mainContractList);
        }
コード例 #7
0
        private void SaveClosePrice2Data(USeMarket market, List <ClosePrice2Entity> closePriceList)
        {
            using (MySqlConnection connection = new MySqlConnection(m_dbConStr))
            {
                connection.Open();


                StringBuilder sb = new StringBuilder();
                foreach (ClosePrice2Entity closePrice in closePriceList)
                {
                    string cmdText = CreateClosePrice2UpdateSql(closePrice);
                    sb.Append(cmdText);

                    if (sb.Length > 6000)
                    {
                        MySqlCommand command = new MySqlCommand(sb.ToString(), connection);
                        int          result  = command.ExecuteNonQuery();
                        sb.Clear();
                    }
                    //int result = command.ExecuteNonQuery();
                }

                if (sb.Length > 0)
                {
                    MySqlCommand command = new MySqlCommand(sb.ToString(), connection);
                    int          result  = command.ExecuteNonQuery();
                    sb.Clear();
                }
            }
        }
コード例 #8
0
ファイル: USeManager.cs プロジェクト: handayu/TFS-WebKit
        private void LoadMonitorMarket()
        {
            string marketConfig = ConfigurationManager.AppSettings["MonitorMarket"];

            try
            {
                List <USeMarket> marketList = new List <USeMarket>();

                string[] items = marketConfig.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string marketValue in items)
                {
                    USeMarket market = (USeMarket)Enum.Parse(typeof(USeMarket), marketValue);
                    marketList.Add(market);
                }

                if (marketList.Count <= 0)
                {
                    throw new Exception("MonitorMarket is empty");
                }

                m_monitorMarketes = marketList;
            }
            catch (Exception ex)
            {
                string text = "Load MonitorMarketConfig failed, " + ex.Message;
                throw new ApplicationException(text, ex);
            }
        }
コード例 #9
0
        /// <summary>
        /// 获取品种所有合约明细。
        /// </summary>
        /// <returns></returns>
        public List <USeInstrument> GetAllInstruments(string productId, USeMarket exchange)
        {
            List <USeInstrument> list = (from i in m_instrumentList
                                         where i.Varieties == productId && i.Instrument.Market == exchange
                                         select i.Instrument.Clone()).ToList();

            return(list);
        }
コード例 #10
0
        /// <summary>
        /// 获取产品明细。
        /// </summary>
        /// <param name="instrumentCode">合约代码。</param>
        /// <param name="exchange">市场。</param>
        /// <returns></returns>
        public USeInstrumentDetail GetInstrumentDetail(string instrumentCode, USeMarket exchange)
        {
            USeInstrumentDetail detail = (from i in m_instrumentList
                                          where i.Instrument.InstrumentCode == instrumentCode && i.Instrument.Market == exchange
                                          select i).FirstOrDefault();

            return(detail);
        }
コード例 #11
0
ファイル: KLineImporter.cs プロジェクト: handayu/TFS-WebKit
        public KLineImporter(LogFileInfo fileInfo)
        {
            m_logFileInfo = fileInfo;

            m_filePath       = fileInfo.FileInfo.FullName;
            m_cycle          = fileInfo.Cycle;
            m_market         = fileInfo.Market;
            m_instrumentCode = fileInfo.InstrumentCode;
        }
コード例 #12
0
        private TimeSpan m_logNoonTime    = new TimeSpan(11 + 3, 32, 00); //午盘时间 前推三个小时
        #endregion

        public ClosePrice2Importer(LogFileInfo fileInfo)
        {
            Debug.Assert(fileInfo.Cycle == USeCycleType.Min1);
            m_logFileInfo = fileInfo;

            m_filePath       = fileInfo.FileInfo.FullName;
            m_cycle          = fileInfo.Cycle;
            m_market         = fileInfo.Market;
            m_instrumentCode = fileInfo.InstrumentCode;
        }
コード例 #13
0
ファイル: LogProtocol.cs プロジェクト: handayu/TFS-WebKit
 private static string GetOfficeInstrumentCode(string instrumentCode, USeMarket market)
 {
     if (market == USeMarket.CZCE)
     {
         return(instrumentCode.Remove(instrumentCode.Length - 4, 1));
     }
     else
     {
         return(instrumentCode);
     }
 }
コード例 #14
0
        /// <summary>
        /// 初始化方法
        /// </summary>
        public void Initialize()
        {
            string strSel = string.Format(@"select * from {0}.contracts;",
                                          m_alphaDBName, USeTraderProtocol.GetInternalFutureMarketSqlString());

            DataTable table = MySQLDriver.GetTableFromDB(m_dbConnStr, strSel);

            List <USeInstrumentDetail> instrumentList = new List <USeInstrumentDetail>();

            foreach (DataRow row in table.Rows)
            {
                try
                {
                    if (row["exchange_long_margin_ratio"] == DBNull.Value ||
                        row["exchange_short_margin_ratio"] == DBNull.Value)
                    {
                        continue;
                    }

                    USeMarket exchange = (USeMarket)Enum.Parse(typeof(USeMarket), row["exchange"].ToString());

                    USeInstrumentDetail instrument = new USeInstrumentDetail();

                    instrument.Instrument = new USeInstrument(row["contract"].ToString(),
                                                              row["contract_name"].ToString(),
                                                              exchange);
                    instrument.OpenDate                 = Convert.ToDateTime(row["open_date"]);
                    instrument.ExpireDate               = Convert.ToDateTime(row["expire_date"]);
                    instrument.StartDelivDate           = Convert.ToDateTime(row["start_deliv_date"]);
                    instrument.EndDelivDate             = Convert.ToDateTime(row["end_deliv_date"]);
                    instrument.VolumeMultiple           = Convert.ToInt32(row["volume_multiple"]);
                    instrument.IsTrading                = true;
                    instrument.Varieties                = row["varieties"].ToString();
                    instrument.PriceTick                = Convert.ToDecimal(row["price_tick"]);
                    instrument.ExchangeLongMarginRatio  = (row["exchange_long_margin_ratio"] != DBNull.Value) ? Convert.ToDecimal(row["exchange_long_margin_ratio"]) : 0m;
                    instrument.ExchangeShortMarginRatio = (row["exchange_short_margin_ratio"] != DBNull.Value) ? Convert.ToDecimal(row["exchange_short_margin_ratio"]) : 0m;
                    instrument.ProductClass             = (USeProductClass)Enum.Parse(typeof(USeProductClass), row["product_class"].ToString());
                    instrument.UnderlyingInstrument     = (row["underlying_instrument"] != DBNull.Value)? row["underlying_instrument"].ToString():"";
                    instrument.MaxMarketOrderVolume     = (row["max_market_order_volume"] != DBNull.Value) ? Convert.ToInt16(row["max_market_order_volume"]) : 0;
                    instrument.MinMarketOrderVolume     = (row["min_market_order_volume"] != DBNull.Value) ? Convert.ToInt16(row["min_market_order_volume"]) : 0;
                    instrument.MaxLimitOrderVolume      = (row["max_limit_order_volume"] != DBNull.Value) ? Convert.ToInt16(row["max_limit_order_volume"]) : 0;
                    instrument.MinLimitOrderVolume      = (row["min_limit_order_volume"] != DBNull.Value) ? Convert.ToInt16(row["min_limit_order_volume"]) : 0;

                    instrumentList.Add(instrument);
                }
                catch (Exception ex)
                {
                    throw new Exception("初始化合约信息异常:" + ex.Message);
                }
            }

            m_instrumentList = instrumentList;
        }
コード例 #15
0
        private void SaveKLineData(USeMarket market, USeCycleType cycle, string instrumentCode,
                                   DateTime beginDate, DateTime endDate, List <USeKLine> klineList)
        {
            using (MySqlConnection connection = new MySqlConnection(m_dbConStr))
            {
                connection.Open();

                string tableName = GetDBTableName(cycle, market);
                string cmdText   = string.Format(@"delete from {0}.{1} where contract = '{2}' 
and date_time >= '{3:yyyy-MM-dd}' and date_time < '{4:yyyy-MM-dd}'",
                                                 m_alphaDBName, tableName, instrumentCode, beginDate, endDate.AddDays(1));
                MySqlCommand command = new MySqlCommand(cmdText, connection);
                command.ExecuteNonQuery();

                StringBuilder sb = new StringBuilder();
                foreach (USeKLine kLine in klineList)
                {
                    cmdText = CreateKLineInsertSql2(kLine);
                    sb.Append(cmdText);
                    //command = new MySqlCommand(cmdText, connection);
                    //command.Parameters.AddWithValue("@contract", kLine.InstrumentCode);
                    //command.Parameters.AddWithValue("@exchange", kLine.Market.ToString());
                    //command.Parameters.AddWithValue("@date_time", kLine.DateTime);
                    //command.Parameters.AddWithValue("@price_open", kLine.Open);
                    //command.Parameters.AddWithValue("@price_high", kLine.High);
                    //command.Parameters.AddWithValue("@price_low", kLine.Low);
                    //command.Parameters.AddWithValue("@price_close", kLine.Close);
                    //command.Parameters.AddWithValue("@volumn", kLine.Volumn);
                    //command.Parameters.AddWithValue("@turnover", kLine.Turnover);
                    //command.Parameters.AddWithValue("@openinterest", kLine.OpenInterest);

                    //if (kLine.Cycle == USeCycleType.Day)
                    //{
                    //    command.Parameters.AddWithValue("@pre_settlement_price", kLine.PreSettlementPrice);
                    //    command.Parameters.AddWithValue("@settlement_price", kLine.SettlementPrice);
                    //}
                    if (sb.Length > 6000)
                    {
                        command = new MySqlCommand(sb.ToString(), connection);
                        int result = command.ExecuteNonQuery();
                        sb.Clear();
                    }
                    //int result = command.ExecuteNonQuery();
                }

                if (sb.Length > 0)
                {
                    command = new MySqlCommand(sb.ToString(), connection);
                    int result = command.ExecuteNonQuery();
                    sb.Clear();
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// 获取产品。
        /// </summary>
        /// <param name="instrumentCode">合约代码。</param>
        /// <param name="exchange">市场。</param>
        /// <returns></returns>
        public USeInstrument GetInstrument(string instrumentCode, USeMarket exchange)
        {
            USeInstrumentDetail detail = (from i in m_instrumentList
                                          where i.Instrument.InstrumentCode == instrumentCode && i.Instrument.Market == exchange
                                          select i).FirstOrDefault();

            if (detail != null)
            {
                return(detail.Instrument.Clone());
            }
            else
            {
                return(null);
            }
        }
コード例 #17
0
        /// <summary>
        /// USe市场转换为Ctp市场。
        /// </summary>
        /// <param name="market">USeMarket对象</param>
        /// <returns>Ctp市场字符串</returns>
        public string USeMarketToFtdcExchange(USeMarket market)
        {
            switch (market)
            {
            case USeMarket.DCE: return("DCE");

            case USeMarket.SHFE: return("SHFE");

            case USeMarket.CZCE: return("CZCE");

            case USeMarket.CFFEX: return("CFFEX");

            default: return(string.Empty);
            }
        }
コード例 #18
0
        /// <summary>
        /// 加载主力合约信息。
        /// </summary>
        private void LoadMainContract()
        {
            try
            {
                TradeCalendar tradeCalendar = GetTradeCalendar();

                DateTime tradeDay = DateTime.Today;
                //[yangming]强制设定17点为一天的分隔点,后续在完善
                if (DateTime.Now.TimeOfDay > new TimeSpan(17, 0, 0))
                {
                    tradeDay = tradeCalendar.NextTradeDay;
                }

                string strSel = string.Format(@"select * from {0}.main_contract
where settlement_date = '{1:yyyy-MM-dd}' and exchange in ({2});",
                                              m_alphaDBName, tradeDay, USeTraderProtocol.GetInternalFutureMarketSqlString());

                DataTable table = new DataTable();
                using (MySqlConnection connection = new MySqlConnection(m_dbConnStr))
                {
                    MySqlDataAdapter adapter = new MySqlDataAdapter(strSel, connection);
                    adapter.Fill(table);
                    adapter.Dispose();
                }

                Dictionary <string, USeInstrument> mainContractDic = new Dictionary <string, USeInstrument>();

                foreach (DataRow row in table.Rows)
                {
                    string    varieties        = row["varieties"].ToString();
                    string    mainContractCode = row["main_contract"].ToString();
                    USeMarket exchange         = (USeMarket)Enum.Parse(typeof(USeMarket), row["exchange"].ToString());

                    if (string.IsNullOrEmpty(mainContractCode) == false)
                    {
                        USeInstrument mainContract = new USeInstrument(mainContractCode, mainContractCode, exchange);
                        mainContractDic.Add(varieties, mainContract);
                    }
                }

                m_mainContractDic = mainContractDic;
            }
            catch (Exception ex)
            {
                throw new Exception("加载主力合约信息失败," + ex.Message);
            }
        }
コード例 #19
0
        /// <summary>
        /// CTP InstrumentField To USeInstrumentDetail。
        /// </summary>
        /// <param name="filed"></param>
        /// <returns></returns>
        private USeInstrumentDetail CtpInstrumentFieldToUSeInstrumentDetail(InstrumentField filed)
        {
            USeMarket market = CtpProtocol.FtdcExchangeToUSeMarket(filed.ExchangeID);

            Debug.Assert(market != USeMarket.Unknown, "CtpInstrumentFieldToUSeInstrumentDetail(),market is unknown.");

            USeInstrumentDetail detail = new USeInstrumentDetail();

            detail.Instrument = new USeInstrument(filed.InstrumentID,
                                                  filed.InstrumentName,
                                                  market);
            try
            {
                detail.OpenDate   = DateTime.ParseExact(filed.OpenDate, "yyyyMMdd", null);
                detail.ExpireDate = DateTime.ParseExact(filed.ExpireDate, "yyyyMMdd", null);
                if (string.IsNullOrEmpty(filed.StartDelivDate) == false)
                {
                    detail.StartDelivDate = DateTime.ParseExact(filed.StartDelivDate, "yyyyMMdd", null);
                }
                else
                {
                    //[yangming] 有的合约查询不到开始交割日,暂时用到期日下一天
                    detail.StartDelivDate = detail.ExpireDate.AddDays(1);
                }
                detail.EndDelivDate             = DateTime.ParseExact(filed.EndDelivDate, "yyyyMMdd", null);
                detail.VolumeMultiple           = filed.VolumeMultiple;
                detail.IsTrading                = filed.IsTrading == IntBoolType.Yes;
                detail.Varieties                = filed.ProductID;
                detail.PriceTick                = filed.PriceTick.ToDecimal();
                detail.ExchangeLongMarginRatio  = filed.LongMarginRatio.ToDecimal();
                detail.ExchangeShortMarginRatio = filed.ShortMarginRatio.ToDecimal();

                detail.MaxMarketOrderVolume = filed.MaxMarketOrderVolume;
                detail.MinMarketOrderVolume = filed.MinMarketOrderVolume;
                detail.MaxLimitOrderVolume  = filed.MaxLimitOrderVolume;
                detail.MinLimitOrderVolume  = filed.MinLimitOrderVolume;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "CtpInstrumentFieldToUSeInstrumentDetail() convet failed," + ex.Message);
            }

            return(detail);
        }
コード例 #20
0
        /// <summary>
        /// 获取一分钟K线表名。
        /// </summary>
        /// <param name="market"></param>
        /// <returns></returns>
        private string GetMin1KLineTableName(USeMarket market)
        {
            string tableName = string.Empty;

            switch (market)
            {
            case USeMarket.CFFEX:
            case USeMarket.CZCE:
            case USeMarket.DCE:
            case USeMarket.SHFE:
                tableName = string.Format("min1_kline_{0}", market.ToString().ToLower());
                break;

            default:
                Debug.Assert(false);
                throw new Exception("Invalid market:" + market.ToString());
            }
            return(tableName);
        }
コード例 #21
0
        /// <summary>
        /// 初始化方法。
        /// </summary>
        public void Initialize(DateTime tradeDay)
        {
            string strSel = string.Format(@"select * from {0}.contracts
where open_date <= '{1}' and expire_date >= '{1}' and exchange in({2});",
                                          m_alphaDBName, tradeDay.ToString("yyyy-MM-dd"), USeTraderProtocol.GetInternalFutureMarketSqlString());

            DataTable table = MySQLDriver.GetTableFromDB(m_dbConnStr, strSel);

            List <USeInstrumentDetail> instrumentList = new List <USeInstrumentDetail>();

            foreach (DataRow row in table.Rows)
            {
                USeMarket exchange = (USeMarket)Enum.Parse(typeof(USeMarket), row["exchange"].ToString());

                USeInstrumentDetail instrument = new USeInstrumentDetail()
                {
                    Instrument = new USeInstrument(row["contract"].ToString(),
                                                   row["contract_name"].ToString(),
                                                   exchange),
                    OpenDate                 = Convert.ToDateTime(row["open_date"]),
                    ExpireDate               = Convert.ToDateTime(row["expire_date"]),
                    StartDelivDate           = Convert.ToDateTime(row["start_deliv_date"]),
                    EndDelivDate             = Convert.ToDateTime(row["end_deliv_date"]),
                    VolumeMultiple           = Convert.ToInt32(row["volume_multiple"]),
                    IsTrading                = true,
                    Varieties                = row["varieties"].ToString(),
                    PriceTick                = Convert.ToDecimal(row["price_tick"]),
                    ExchangeLongMarginRatio  = Convert.ToDecimal(row["exchange_long_margin_ratio"]),
                    ExchangeShortMarginRatio = Convert.ToDecimal(row["exchange_short_margin_ratio"]),
                    ProductClass             = (USeProductClass)Enum.Parse(typeof(USeProductClass), row["product_class"].ToString()),
                    UnderlyingInstrument     = row["underlying_instrument"].ToString(),
                    MaxMarketOrderVolume     = Convert.ToInt16(row["max_market_order_volume"]),
                    MinMarketOrderVolume     = Convert.ToInt16(row["min_market_order_volume"]),
                    MaxLimitOrderVolume      = Convert.ToInt16(row["max_limit_order_volume"]),
                    MinLimitOrderVolume      = Convert.ToInt16(row["min_limit_order_volume"])
                };
                instrumentList.Add(instrument);
            }

            m_instrumentList = instrumentList;
        }
コード例 #22
0
        /// <summary>
        /// 匹配交易所
        /// </summary>
        /// <param name="instrumentCode"></param>
        /// <returns></returns>
        private USeMarket FromCodeToMarket(string instrumentCode)
        {
            USeMarket market = USeMarket.Unknown;

            Debug.Assert(m_productList != null);

            if (m_productList == null)
            {
                return(USeMarket.Unknown);
            }

            foreach (USeProduct product in m_productList)
            {
                if (product.ProductCode == GetVarietiesName(instrumentCode))
                {
                    return(product.Market);
                }
            }

            return(market);
        }
コード例 #23
0
        /// <summary>
        /// 获取USe主力合约编码。
        /// </summary>
        /// <param name="varieties">品种。</param>
        /// <param name="exchange">市场。</param>
        /// <returns>主力合约编码。</returns>
        public static USeInstrument GetMainContractCode(string varieties, USeMarket exchange)
        {
            string contractCode = string.Format("{0}9999", varieties);

            return(new USeInstrument(contractCode, varieties + "主力", exchange));

            //string contractCode = string.Empty;
            //switch (exchange)
            //{
            //    case USeMarket.CZCE:
            //        contractCode = string.Format("{0}999", varieties);
            //        break;
            //    case USeMarket.CFFEX:
            //    case USeMarket.SHFE:
            //    case USeMarket.DCE:
            //        contractCode = string.Format("{0}9999", varieties);
            //        break;
            //    default:
            //        throw new NotSupportedException(string.Format("不支持{0}市场主力合约编码", exchange));
            //}

            //return new USeInstrument(contractCode, varieties+"主力", exchange);
        }
コード例 #24
0
        /// <summary>
        /// 获取USe品种指数编码。
        /// </summary>
        /// <param name="varieties">品种。</param>
        /// <param name="exchange">市场。</param>
        /// <returns>品种指数编码。</returns>
        public static USeInstrument GetVarietiesIndexCode(string varieties, USeMarket exchange)
        {
            string indexCode = string.Format("{0}8888", varieties);

            return(new USeInstrument(indexCode, varieties + "指数", exchange));

            //string indexCode = string.Empty;
            //switch (exchange)
            //{
            //    case USeMarket.CZCE:
            //        indexCode = string.Format("{0}888", varieties);
            //        break;
            //    case USeMarket.CFFEX:
            //    case USeMarket.SHFE:
            //    case USeMarket.DCE:
            //        indexCode = string.Format("{0}8888", varieties);
            //        break;
            //    default:
            //        throw new NotSupportedException(string.Format("不支持{0}市场品种指数编码", exchange));
            //}

            //return new USeInstrument(indexCode, varieties + "指数", exchange);
        }
コード例 #25
0
        /// <summary>
        /// 保存合约结算价数据。
        /// </summary>
        /// <param name="DepthMarketDataFieldinstrumentList"></param>
        /// <returns></returns>
        private void SaveInstumentsSettlementPriceToDB(DepthMarketDataField item, string instrumentID, USeMarket market, DateTime settlementDate, double settlementPrice)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(m_dbConStr))
                {
                    connection.Open();

                    string cmdText = string.Format(@"update {0}.day_kline set settlement_price = @settlement_price 
where contract = @contract AND exchange = @exchange AND date_time = @date_time;", m_alphaDBName);

//                    string cmdText = string.Format(@"update {0}.day_kline set settlement_price ={1}
//where contract = '{2}' AND exchange = '{3}' AND date_time = '{4:yyyy-MM-dd}';", m_alphaDBName,settlementPrice,instrumentID,mar);

                    MySqlCommand command = new MySqlCommand(cmdText, connection);

                    command.Parameters.AddWithValue("@contract", instrumentID);
                    command.Parameters.AddWithValue("@exchange", market.ToString());
                    command.Parameters.AddWithValue("@date_time", settlementDate);
                    command.Parameters.AddWithValue("@settlement_price", settlementPrice);
                    int result = command.ExecuteNonQuery();
                    //Debug.Assert(result == 1);
                }
            }
            catch (Exception ex)
            {
                string text = "保存结算价失败:" + ex.Message;
                WriteConsoleLog(text);
            }
        }
コード例 #26
0
ファイル: USeInstrument.cs プロジェクト: handayu/TFS-WebKit
 /// <summary>
 /// 构造USeProduct实例。
 /// </summary>
 /// <param name="instrumentCode">合约代码。</param>
 /// <param name="instrumentName">合约名称。</param>
 /// <param name="market">所属市场。</param>
 public USeInstrument(string instrumentCode, string instrumentName, USeMarket market)
 {
     this.InstrumentCode = instrumentCode;
     this.InstrumentName = instrumentName;
     this.Market         = market;
 }
コード例 #27
0
        private void RefreashSendimentaryMoney(DepthMarketDataField item, string instrumentID, USeMarket market, DateTime settlementDate, double settlementPrice)
        {
            //计算资金沉淀用结算价

            decimal sendimentaryMoney = 0m;

            foreach (USeInstrumentDetail insDetail in m_insDetailList)
            {
                if (instrumentID == insDetail.Instrument.InstrumentCode)
                {
                    int     perSharesContract       = insDetail.VolumeMultiple;                                                                                  //合约规模
                    decimal exchangeLongMarginRatio = insDetail.ExchangeLongMarginRatio;                                                                         //保证金
                    sendimentaryMoney = Convert.ToDecimal(item.OpenInterest) * Convert.ToDecimal(settlementPrice) * perSharesContract * exchangeLongMarginRatio; //资金沉淀
                    break;
                }
            }

            Debug.Assert(sendimentaryMoney != 0m);

            try
            {
                using (MySqlConnection connection = new MySqlConnection(m_dbConStr))
                {
                    connection.Open();

                    string cmdText = string.Format(@"update {0}.day_kline set sendimentary_money = @sendimentary_money 
where contract = @contract AND exchange = @exchange AND date_time = @date_time;", m_alphaDBName);

                    MySqlCommand command = new MySqlCommand(cmdText, connection);

                    command.Parameters.AddWithValue("@contract", instrumentID);
                    command.Parameters.AddWithValue("@exchange", market.ToString());
                    command.Parameters.AddWithValue("@date_time", settlementDate);
                    command.Parameters.AddWithValue("@sendimentary_money", sendimentaryMoney);
                    int result = command.ExecuteNonQuery();
                    Debug.Assert(result == 1);

                    string text = string.Format("用结算价更新资金沉淀成功,合约:{0} 结算价:{1}", item.InstrumentID, settlementPrice);
                    WriteConsoleLog(text);
                    m_eventLogger.WriteInformation(text);
                }
            }
            catch (Exception ex)
            {
                string text = "用结算价更新资金沉淀失败:" + ex.Message;
                WriteConsoleLog(text);
            }
        }
コード例 #28
0
        /// <summary>
        /// 启动午盘休盘价下载。
        /// </summary>
        public int Start()
        {
            try
            {
                m_eventLogger = AppLogger.InitInstance();
            }
            catch
            {
                m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger");
            }

            m_eventLogger.LineFeed();
            string text = "开始下载午盘收盘价服务";

            m_eventLogger.WriteInformation(text);
            USeConsole.WriteLine(text);

            if (ReadConfig() == false)
            {
                return(-1);
            }

            CtpOrderQuerier ctpApp = new CtpOrderQuerier();

            try
            {
                ctpApp.Connect(m_ctpDriverConfig.Address, m_ctpDriverConfig.Port,
                               m_ctpDriverConfig.LoginTimeOut, m_ctpDriverConfig.QueryTimeOut);
                text = "连接CTP交易服务器成功";
                USeConsole.WriteLine(text);
                m_eventLogger.WriteInformation(text);
            }
            catch (Exception ex)
            {
                text = "连接CTP交易服务器失败," + ex.Message;
                USeConsole.WriteLine(text);
                m_eventLogger.WriteError(text);
                ctpApp.Disconnect();
                return(-1);
            }

            try
            {
                ctpApp.Login(m_ctpAccountConfig.ID, m_ctpAccountConfig.Password, m_ctpAccountConfig.BrokerID);
                text = "登陆CTP交易服务器成功";
                USeConsole.WriteLine(text);
                m_eventLogger.WriteInformation(text);
            }
            catch (Exception ex)
            {
                text = "登陆CTP交易服务器失败," + ex.Message;
                USeConsole.WriteLine(text);
                m_eventLogger.WriteError(text);
                ctpApp.Disconnect();
                return(-1);
            }


            try
            {
                List <InstrumentField> instrumentList = ctpApp.QueryInstument();

                foreach (InstrumentField item in instrumentList)
                {
                    if (item.ProductClass != ProductClass.Futures)
                    {
                        continue;
                    }
                    USeInstrumentDetail entity = InsturmentFiledToUSeInstrumentDetail(item);
                    instrumentDic.Add(entity.Instrument.InstrumentCode, entity);
                }

                text = string.Format("查询期货合约数据完成,共计{0}个合约", instrumentDic.Count);
                USeConsole.WriteLine(text);
                m_eventLogger.WriteInformation(text);
            }
            catch (Exception ex)
            {
                text = "查询期货合约数据失败," + ex.Message;
                USeConsole.WriteLine(text);
                m_eventLogger.WriteError(text);
                ctpApp.Disconnect();
                return(-1);
            }


            List <DepthMarketDataField> depthMarketDataFieldList = new List <DepthMarketDataField>();

            depthMarketDataFieldList = ctpApp.QueryDepthMarketData();
            //while (true)
            //{
            //    depthMarketDataFieldList = ctpApp.QueryDepthMarketData();

            //    //返回大于下午开盘的行情时间
            //    if (VerfiyIsNoonBeginTime(depthMarketDataFieldList) == true)
            //    {
            //        text = string.Format("[{0}]行情已经进入下午开盘时间不在午盘时间内", DateTime.Now);
            //        USeConsole.WriteLine(text);
            //        m_eventLogger.WriteError(text);
            //        ctpApp.Disconnect();
            //        return -1;
            //    }

            //    //未找到大于11:30:00。
            //    if (VerfiyIsNoonEndTime(depthMarketDataFieldList) == false)
            //    {
            //        Thread.Sleep(m_queryFrequence);
            //        continue;
            //    }
            //    else
            //    {
            //        break;
            //    }
            //}

            ctpApp.Disconnect();

            try
            {
                foreach (DepthMarketDataField marketData in depthMarketDataFieldList)
                {
                    if (instrumentDic.ContainsKey(marketData.InstrumentID))
                    {
                        USeMarket market = instrumentDic[marketData.InstrumentID].Instrument.Market;
                        //保存收盘价
                        SaveClosePriceToDB(marketData, marketData.InstrumentID, market, DateTime.Today, marketData.LastPrice);
                        instrumentDic.Remove(marketData.InstrumentID);

                        USeConsole.WriteLine(string.Format("保存{0}成功", marketData.InstrumentID));
                    }
                }

                RefrashPriceCloseDownLoad(DateTime.Today, 1);
            }
            catch (Exception ex)
            {
                text = string.Format("查询,保存当日午盘数据异常:{0}", ex.Message);
                USeConsole.WriteLine(text);
                m_eventLogger.WriteInformation(text);
                return(-1);
            }


            return(0);
        }
コード例 #29
0
        /// <summary>
        /// 保存合约结算价数据。
        /// </summary>
        /// <param name="DepthMarketDataFieldinstrumentList"></param>
        /// <returns></returns>
        private void SaveClosePriceToDB(DepthMarketDataField item, string instrumentID, USeMarket market, DateTime dateTime, double priceClose)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(m_dbConStr))
                {
                    connection.Open();

                    string cmdText = string.Empty;
                    cmdText = CreateClosePrice2UpdateSql();

                    MySqlCommand command = new MySqlCommand(cmdText, connection);

                    command.Parameters.AddWithValue("@contract", instrumentID);
                    command.Parameters.AddWithValue("@exchange", market.ToString());
                    command.Parameters.AddWithValue("@date_time", dateTime);
                    command.Parameters.AddWithValue("@price_close2", (decimal)priceClose);
                    int result = command.ExecuteNonQuery();
                    //Debug.Assert(result == 1);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #30
0
        private TimeSpan m_nextDayRange = new TimeSpan(18, 0, 0); // 下一交易日的时间分界点
        #endregion                                                // member

        #region methods
        /// <summary>
        /// 启动结算价下载。
        /// </summary>
        public int Start()
        {
            //确定更新结算价成功之后,需要再次计算资金沉淀,盘中的时候用的是最新价计算,有结算价之后,就改为结算价重新刷新一遍计算
            //计算公式:资金沉淀=品种持仓量*结算价*合约规模*交易所多头保证金比例
            //计算资金总沉淀(盘中就用最新价计算资金沉淀,待下午结算价出来之后,按照结算价再更新一次)
            //int perSharesContract = GetInstrumentPerSharesContract(marketData.Instrument.InstrumentCode);//合约规模
            //decimal exchangeLongMarginRatio = GetExchangeLongMarginRatio(marketData.Instrument.InstrumentCode);//保证金
            //m_kLine.SendimentaryMoney = marketData.OpenInterest * marketData.LastPrice * perSharesContract * exchangeLongMarginRatio;//资金沉淀
            //取出UseinstrumentDetail品种合约信息取出合约规模和保证金额比例,再次执行SQL语句

            try
            {
                m_eventLogger = AppLogger.InitInstance();
            }
            catch
            {
                m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger");
            }

            m_eventLogger.LineFeed();
            string text = "开始下载结算价服务";

            m_eventLogger.WriteInformation(text);
            WriteConsoleLog(text);

            if (ReadConfig() == false)
            {
                return(-1);
            }

            //下载所有合约详情,失败直接退出因为后面需要基础数据
            try
            {
                USeTradingInstrumentManager tradingInsManager = CreateInstrumentManager();
                m_insDetailList = tradingInsManager.GetAllInstrumentDetails();
                Debug.Assert(m_insDetailList != null);
            }
            catch (Exception ex)
            {
                text = "下载数据库所有合约详情InstrumentDetail失败," + ex.Message;
                WriteConsoleLog(text);
                m_eventLogger.WriteError(text);
                return(-1);
            }

            CtpOrderQuerier ctpApp = new CtpOrderQuerier();

            try
            {
                ctpApp.Connect(m_ctpDriverConfig.Address, m_ctpDriverConfig.Port,
                               m_ctpDriverConfig.LoginTimeOut, m_ctpDriverConfig.QueryTimeOut);
                text = "连接CTP交易服务器成功";
                WriteConsoleLog(text);
                m_eventLogger.WriteInformation(text);
            }
            catch (Exception ex)
            {
                text = "连接CTP交易服务器失败," + ex.Message;
                WriteConsoleLog(text);
                m_eventLogger.WriteError(text);
                ctpApp.Disconnect();
                return(-1);
            }

            try
            {
                ctpApp.Login(m_ctpAccountConfig.ID, m_ctpAccountConfig.Password, m_ctpAccountConfig.BrokerID);
                text = "登陆CTP交易服务器成功";
                WriteConsoleLog(text);
                m_eventLogger.WriteInformation(text);
            }
            catch (Exception ex)
            {
                text = "登陆CTP交易服务器失败," + ex.Message;
                WriteConsoleLog(text);
                m_eventLogger.WriteError(text);
                ctpApp.Disconnect();
                return(-1);
            }


            try
            {
                List <InstrumentField> instrumentList = ctpApp.QueryInstument();

                foreach (InstrumentField item in instrumentList)
                {
                    if (item.ProductClass != ProductClass.Futures)
                    {
                        continue;
                    }
                    USeInstrumentDetail entity = InsturmentFiledToUSeInstrumentDetail(item);
                    instrumentDic.Add(entity.Instrument.InstrumentCode, entity);
                }

                text = string.Format("查询期货合约数据完成,共计{0}个合约", instrumentDic.Count);
                WriteConsoleLog(text);
                m_eventLogger.WriteInformation(text);
            }
            catch (Exception ex)
            {
                text = "查询期货合约数据失败," + ex.Message;
                WriteConsoleLog(text);
                m_eventLogger.WriteError(text);
                ctpApp.Disconnect();
                return(-1);
            }


            DateTime tradingDate = GetTradingDay();

            if (m_refrashDate == QueryDay.Today)
            {
                int queryNum = m_queryNum;
                while (queryNum > 0)
                {
                    try
                    {
                        List <DepthMarketDataField> tempDepthMarketDataFieldList = ctpApp.QueryDepthMarketData();

                        Debug.Assert(tempDepthMarketDataFieldList != null);
                        foreach (DepthMarketDataField marketData in tempDepthMarketDataFieldList)
                        {
                            if (marketData.SettlementPrice <= 0d || marketData.SettlementPrice == double.MaxValue)
                            {
                                continue;
                            }
                            if (instrumentDic.ContainsKey(marketData.InstrumentID))
                            {
                                //[hanyu]未防返回的MarketData没有ExchangeID,改用查询回来的合约交易所信息
                                USeMarket market = instrumentDic[marketData.InstrumentID].Instrument.Market;
                                SaveInstumentsSettlementPriceToDB(marketData, marketData.InstrumentID, market, tradingDate, marketData.SettlementPrice);

                                //保存完一笔的同时刷新一次资金沉淀[暂时不在这里处理,改用直接在特定时间执行SQL语句,因为涉及到8888指数和9999主力合约也需要刷新资金沉淀的问题]
                                //RefreashSendimentaryMoney(marketData, marketData.InstrumentID, market, tradingDate,marketData.SettlementPrice);

                                instrumentDic.Remove(marketData.InstrumentID);

                                USeConsole.WriteLine(string.Format("保存{0}成功", marketData.InstrumentID));
                            }
                        }

                        if (instrumentDic.Count <= 0)
                        {
                            //所有合约存储完毕,退出
                            break;
                        }

                        queryNum--;
                        if (queryNum > 0)
                        {
                            Thread.Sleep(m_queryFrequence);
                        }
                    }
                    catch (Exception ex)
                    {
                        text = string.Format("查询,保存当日结算价异常:{0}", ex.Message);
                        WriteConsoleLog(text);
                        m_eventLogger.WriteInformation(text);
                        ctpApp.Disconnect();
                        return(-1);
                    }
                }
            }
            else
            {
                try
                {
                    List <DepthMarketDataField> tempDepthMarketDataFieldList = ctpApp.QueryDepthMarketData();

                    Debug.Assert(tempDepthMarketDataFieldList != null);

                    foreach (DepthMarketDataField marketData in tempDepthMarketDataFieldList)
                    {
                        if (marketData.PreSettlementPrice <= 0d || marketData.PreSettlementPrice == double.MaxValue)
                        {
                            continue;
                        }
                        if (instrumentDic.ContainsKey(marketData.InstrumentID))
                        {
                            //[hanyu]未防返回的MarketData没有ExchangeID,改用查询回来的合约交易所信息
                            USeMarket market = instrumentDic[marketData.InstrumentID].Instrument.Market;

                            //保存结算价
                            SaveInstumentsSettlementPriceToDB(marketData, marketData.InstrumentID, market, tradingDate, marketData.PreSettlementPrice);

                            //RefreashSendimentaryMoney(marketData, marketData.InstrumentID, market, tradingDate,marketData.PreSettlementPrice);

                            instrumentDic.Remove(marketData.InstrumentID);

                            USeConsole.WriteLine(string.Format("保存{0}成功", marketData.InstrumentID));
                        }
                    }
                }
                catch (Exception ex)
                {
                    text = string.Format("保存昨日结算价异常:{0}", ex.Message);
                    WriteConsoleLog(text);
                    m_eventLogger.WriteInformation(text);
                    ctpApp.Disconnect();
                    return(-1);
                }
            }

            if (ctpApp != null)
            {
                ctpApp.Disconnect();
            }

            if (instrumentDic.Count > 0)
            {
                //未查询到的合约写入文件
                foreach (USeInstrumentDetail field in instrumentDic.Values)
                {
                    text = string.Format("[{0}]结算价查询失败", field.Instrument.InstrumentCode);
                    WriteConsoleLog(text);
                    m_eventLogger.WriteInformation(text);
                }
            }
            else
            {
                try
                {
#if DEBUG
                    bool iDownLoadResult = VerifyDBSettlementPrice(tradingDate);
                    Debug.Assert(iDownLoadResult == true);
#endif
                    RefreshDBSettlementDownLoad(tradingDate, true);
                }
                catch (Exception ex)
                {
                    text = string.Format("更新结算状态失败,错误:{0}", ex.Message);
                    WriteConsoleLog(text);
                    m_eventLogger.WriteInformation(text);
                }
            }
            return(0);
        }