private ArbitrageOrderSettlement CalculateSettlementResult() { USeArbitrageOrder arbitrageOrder = null; lock (m_syncObj) { arbitrageOrder = m_arbitrageOrder.Clone(); } List <USeOrderBook> orderBookList = arbitrageOrder.GetAllOrderBooks(); USeInstrument buyInstrument = arbitrageOrder.OpenArgument.BuyInstrument; USeInstrument sellInstrument = arbitrageOrder.OpenArgument.SellInstrument; USeMarketData buyMarketData = USeManager.Instance.QuoteDriver.Query(buyInstrument); USeMarketData sellMarketData = USeManager.Instance.QuoteDriver.Query(sellInstrument); USeInstrumentDetail buyInstrumentDetail = USeManager.Instance.OrderDriver.QueryInstrumentDetail(buyInstrument); USeInstrumentDetail sellInstrumentDetail = USeManager.Instance.OrderDriver.QueryInstrumentDetail(sellInstrument); decimal buyProfit = CalculateProfit(orderBookList, buyInstrumentDetail, buyMarketData); decimal sellProfit = CalculateProfit(orderBookList, sellInstrumentDetail, sellMarketData); decimal totalProfit = buyProfit + sellProfit; ArbitrageOrderSettlement settlemt = new ArbitrageOrderSettlement() { BuyInstrumentProfit = buyProfit, SellInstrumentProfit = sellProfit, Profit = totalProfit }; return(settlemt); }
/// <summary> /// 计算平仓损益。 /// </summary> /// <param name="arbitrageOrder"></param> /// <returns></returns> private ProfitResult CalculatCloseProfit(USeArbitrageOrder arbitrageOrder) { USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; USeQuoteDriver quoteDriver = USeManager.Instance.QuoteDriver; Debug.Assert(orderDriver != null); Debug.Assert(quoteDriver != null); ArbitrageTaskGroup closeTaskGroup = arbitrageOrder.CloseTaskGroup; List <USeOrderBook> orderBookList = arbitrageOrder.GetAllOrderBooks(); USeMarketData buyMarketData = USeManager.Instance.QuoteDriver.Query(closeTaskGroup.BuyInstrument); USeMarketData sellMarketData = USeManager.Instance.QuoteDriver.Query(closeTaskGroup.SellInstrument); USeInstrumentDetail buyInstrumentDetail = USeManager.Instance.OrderDriver.QueryInstrumentDetail(closeTaskGroup.BuyInstrument); USeInstrumentDetail sellInstrumentDetail = USeManager.Instance.OrderDriver.QueryInstrumentDetail(closeTaskGroup.SellInstrument); decimal buyProfit = CalculateProfitByOrderBook(orderBookList, buyInstrumentDetail, buyMarketData); decimal sellProfit = CalculateProfitByOrderBook(orderBookList, sellInstrumentDetail, sellMarketData); decimal totalProfit = buyProfit + sellProfit; ProfitResult result = new ProfitResult() { BuyProfit = buyProfit, SellProfit = sellProfit }; return(result); }
/// <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); }
/// <summary> /// 评估创建套利单需要保证金。 /// </summary> /// <param name="openArg"></param> /// <returns></returns> public decimal EvaluateMargin(ArbitrageOpenArgument openArg) { USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; USeQuoteDriver quoteDriver = USeManager.Instance.QuoteDriver; USeInstrumentDetail buyInstrumentDetail = orderDriver.QueryInstrumentDetail(openArg.BuyInstrument); USeInstrumentDetail sellInstrumentDetail = orderDriver.QueryInstrumentDetail(openArg.SellInstrument); USeMarketData buyMarketData = quoteDriver.Query(openArg.BuyInstrument); USeMarketData sellMarketData = quoteDriver.Query(openArg.SellInstrument); USeMargin buyMarginRate = orderDriver.QueryInstrumentMargin(openArg.BuyInstrument); USeMargin sellMarginRate = orderDriver.QueryInstrumentMargin(openArg.SellInstrument); decimal buyMargin = (openArg.TotalOrderQty * buyMarginRate.BrokerLongMarginRatioByVolume) + (buyMarketData.LastPrice * openArg.TotalOrderQty * buyInstrumentDetail.VolumeMultiple * buyMarginRate.BrokerLongMarginRatioByMoney); decimal sellMargin = (openArg.TotalOrderQty * sellMarginRate.BrokerShortMarginRatioByVolume) + (sellMarketData.LastPrice * openArg.TotalOrderQty * sellInstrumentDetail.VolumeMultiple * sellMarginRate.BrokerShortMarginRatioByMoney); if (openArg.BuyInstrument.Market == USeMarket.SHFE && openArg.SellInstrument.Market == USeMarket.SHFE) { return(Math.Max(buyMargin, sellMargin)); } else { return(buyMargin + sellMargin); } }
/// <summary> /// 获取当前K线前一个交易日的资金沉淀去用于计算资金流入流出 /// </summary> /// <param name="kline"></param> /// <returns></returns> private decimal GetLastTradingDayInsSendimentaryMoney(USeKLine kline, USeInstrumentDetail insDetail) { decimal lastTradingDaySendimentaryMoney = 0m; DateTime preTradingDay = m_tradeCalendarManager.GetPreTradingDate(kline.DateTime); string strSel = string.Format(@"select * from {0}.day_kline where contract='{1}' AND date_time='{2:yyyy-MM-dd 00:00:00}';", m_alphaDBName, kline.InstrumentCode, preTradingDay); DataTable table = MySQLDriver.GetTableFromDB(m_dbConnStr, strSel); foreach (DataRow row in table.Rows) { try { USeKLine tempKline = new USeKLine(); tempKline.InstrumentCode = row["contract"].ToString(); tempKline.Market = (USeMarket)Enum.Parse(typeof(USeMarket), row["exchange"].ToString()); tempKline.Close = Convert.ToDecimal(row["price_close"]); tempKline.DateTime = Convert.ToDateTime(row["date_time"]); tempKline.OpenInterest = Convert.ToDecimal(row["openinterest"]); tempKline.SettlementPrice = (row["settlement_price"] != DBNull.Value) ? Convert.ToDecimal(row["settlement_price"]) : 0m; tempKline.SendimentaryMoney = tempKline.OpenInterest * tempKline.SettlementPrice * insDetail.VolumeMultiple * insDetail.ExchangeLongMarginRatio; return(lastTradingDaySendimentaryMoney = tempKline.SendimentaryMoney); } catch (Exception ex) { throw new Exception("初始化当天交易日的K线:" + ex.Message); } } return(lastTradingDaySendimentaryMoney); }
/// <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); }
/// <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; }
/// <summary> /// 查询合约的合约乘数。 /// </summary> /// <param name="instrument">合约。</param> /// <returns>合约乘数。</returns> public override int QueryInstrumentVolumeMultiple(USeInstrument instrument) { USeInstrumentDetail detail = QueryInstrumentDetail(instrument); if (detail != null) { return(detail.VolumeMultiple); } else { return(0); } //return m_dataBuffer.GetVolumeMultiple(instrument); }
/// <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); } }
/// <summary> /// 处理过期组合合约。 /// </summary> /// <returns></returns> private bool ProcessExpireCombineInstrument() { List <ArbitrageCombineInstrument> arbitrageInstrumentList = null; try { arbitrageInstrumentList = m_dataAccessor.GetCombineInstruments(m_loginUser.BrokerId, m_loginUser.Account); } catch (Exception ex) { throw new Exception("从文件获取套利组合合约异常:" + ex.Message); } bool processFlag = false; for (int i = 0; i < arbitrageInstrumentList.Count; i++) { USeInstrument firstInstrument = arbitrageInstrumentList[i].FirstInstrument; USeInstrument secondInstrument = arbitrageInstrumentList[i].SecondInstrument; List <USeInstrumentDetail> instrumentDetailList = USeManager.Instance.OrderDriver.QueryInstrumentDetail(arbitrageInstrumentList[i].ProductID); USeInstrumentDetail insDetailFir = (from d in instrumentDetailList where d.Instrument.InstrumentCode == firstInstrument.InstrumentCode select d).FirstOrDefault(); USeInstrumentDetail insDetailSec = (from d in instrumentDetailList where d.Instrument.InstrumentCode == secondInstrument.InstrumentCode select d).FirstOrDefault(); if (insDetailFir != null && insDetailSec != null) { continue; } else { arbitrageInstrumentList.Remove(arbitrageInstrumentList[i]); processFlag = true; } } if (processFlag == true) { m_dataAccessor.SaveCombineInstruments(m_loginUser.BrokerId, m_loginUser.Account, arbitrageInstrumentList); } return(true); }
public USeInstrumentDetail GetInstrumentDetail(USeInstrument instrument) { USeInstrumentDetail ins_detail = new USeInstrumentDetail(); if (instrument == null) { return(null); } ins_detail = (from p in GetInstrumentDetail() where p.Instrument == instrument select p).FirstOrDefault(); if (ins_detail == null) { return(null); } return(ins_detail); }
public void AllTrade(USeOrderNum orderNum, int slipPoint) { USeOrderBook orderBook = (from p in m_dataBuffer.OrderBookList where p.OrderNum.Equals(orderNum) select p).FirstOrDefault(); if (orderBook == null) { return; } USeInstrumentDetail instrumentDetail = QueryInstrumentDetail(orderBook.Instrument); int tradeQty = (orderBook.OrderQty - orderBook.TradeQty); decimal tradePrice = 0; if (orderBook.OrderSide == USeOrderSide.Buy) { tradePrice = orderBook.OrderPrice - instrumentDetail.PriceTick * slipPoint; } else if (orderBook.OrderSide == USeOrderSide.Sell) { tradePrice = orderBook.OrderPrice + instrumentDetail.PriceTick * slipPoint; } int volumeMultiple = instrumentDetail.VolumeMultiple; int orderBookTradeQty = orderBook.TradeQty + tradeQty; orderBook.TradeQty = orderBookTradeQty; orderBook.TradeAmount = tradePrice * orderBookTradeQty * volumeMultiple; orderBook.TradePrice = tradePrice; orderBook.TradeFee = 5 * orderBookTradeQty; orderBook.CancelQty = 0; orderBook.Memo = orderBook.Memo; orderBook.OrderTime = DateTime.Now; orderBook.OrderStatus = USeOrderStatus.AllTraded; USeTradeBook tradeBook = CreateTradeBook(orderBook, tradeQty, tradePrice, tradeQty * tradePrice * volumeMultiple, 5 * tradeQty); USePosition positionBook = CreatePositionBook(tradeBook); m_pushTradeBookList.Enqueue(tradeBook); m_pushOrderBookList.Enqueue(orderBook.Clone()); //推送持仓信息 m_pushPositionList.Enqueue(positionBook.Clone()); }
/// <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); }
/// <summary> /// 查询委托回报。 /// </summary> /// <returns></returns> private List <OrderBookCalcItem> QueryOrderBooks() { USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; List <USeOrderBook> orderBookList = orderDriver.QueryOrderBooks(); List <OrderBookCalcItem> list = new List <OrderBookCalcItem>(); if (orderBookList == null) { return(list); } foreach (USeOrderBook orderBookItem in orderBookList) { USeInstrumentDetail detail = orderDriver.QueryInstrumentDetail(orderBookItem.Instrument); USeMargin productMargin = orderDriver.QueryInstrumentMargin(orderBookItem.Instrument); USeFee productFee = orderDriver.QueryInstrumentFee(orderBookItem.Instrument); OrderBookCalcItem calcItem = new OrderBookCalcItem() { InstrumentDetail = detail, MarginRate = productMargin, FeeRate = productFee, OrderNum = orderBookItem.OrderNum, Account = orderBookItem.Account, Instrument = orderBookItem.Instrument, OrderQty = orderBookItem.OrderQty, OrderPrice = orderBookItem.OrderPrice, TradeQty = orderBookItem.TradeQty, TradeAmount = orderBookItem.TradeAmount, TradePrice = orderBookItem.TradePrice, TradeFee = orderBookItem.TradeFee, OrderStatus = orderBookItem.OrderStatus, CancelQty = orderBookItem.CancelQty, OrderSide = orderBookItem.OrderSide, OffsetType = orderBookItem.OffsetType, Memo = orderBookItem.Memo, OrderTime = orderBookItem.OrderTime }; list.Add(calcItem); } return(list); }
/// <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; }
/// <summary> /// 近远月比较 /// </summary> /// <param name="firIns"></param> /// <param name="secIns"></param> /// <returns></returns> private bool CompareExpireDateSecUpperFir(USeInstrument nearInstrument, USeInstrument farInstrument) { if (nearInstrument == null || farInstrument == null) { return(false); } try { string productIDFir = USeTraderProtocol.GetVarieties(nearInstrument.InstrumentCode); string ProductIDSec = USeTraderProtocol.GetVarieties(farInstrument.InstrumentCode); Debug.Assert(productIDFir.Equals(ProductIDSec)); List <USeInstrumentDetail> instrumentDetailList = USeManager.Instance.OrderDriver.QueryInstrumentDetail(productIDFir); USeInstrumentDetail nearDetail = (from d in instrumentDetailList where nearInstrument.InstrumentCode == d.Instrument.InstrumentCode select d).FirstOrDefault(); USeInstrumentDetail farDetail = (from d in instrumentDetailList where farInstrument.InstrumentCode == d.Instrument.InstrumentCode select d).FirstOrDefault(); Debug.Assert(nearDetail != null); Debug.Assert(farDetail != null); if (nearDetail.ExpireDate >= farDetail.ExpireDate) { return(false); } else { return(true); } } catch (Exception ex) { USeFuturesSpiritUtility.ShowWarningMessageBox(this, "合约设定有误" + ex.Message); return(false); } }
/// <summary> /// 查询持仓明细。 /// </summary> /// <returns></returns> private List <PositionDetailCalcItem> QueryPositonDetails() { USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; USeQuoteDriver quoteDriver = USeManager.Instance.QuoteDriver; List <USePositionDetail> positonList = orderDriver.QueryPositionDetail(); List <PositionDetailCalcItem> list = new List <PositionDetailCalcItem>(); if (positonList == null) { return(list); } foreach (USePositionDetail posItem in positonList) { USeInstrumentDetail detail = orderDriver.QueryInstrumentDetail(posItem.Instrument); USeMargin productMargin = orderDriver.QueryInstrumentMargin(posItem.Instrument); USeMarketData marketData = quoteDriver.Query(posItem.Instrument); PositionDetailCalcItem calcItem = new PositionDetailCalcItem() { InstrumentDetail = detail, Margin = productMargin, MarketData = marketData, ID = posItem.ID, Instrument = posItem.Instrument.Clone(), Direction = posItem.Direction, PositionType = posItem.PositionType, OpenQty = posItem.OpenQty, OpenPrice = posItem.OpenPrice, OpenTime = posItem.OpenTime, CloseQty = posItem.CloseQty, CloseAmount = posItem.CloseAmount, ClosePrice = posItem.ClosePrice }; list.Add(calcItem); } return(list); }
private decimal CalculateProfit(List <USeOrderBook> orderBookList, USeInstrumentDetail instrumentDetail, USeMarketData marketData) { Debug.Assert(instrumentDetail.Instrument.Equals(marketData.Instrument)); if (orderBookList == null || orderBookList.Count < 0) { return(0m); } List <USeOrderBook> list = (orderBookList.Where(o => o.Instrument.Equals(instrumentDetail.Instrument))).ToList(); int buyQty = 0; int sellQty = 0; decimal buyAmount = 0m; decimal sellAmount = 0m; foreach (USeOrderBook orderBook in list) { if (orderBook.OrderSide == USeOrderSide.Buy) { buyQty += orderBook.TradeQty; buyAmount += orderBook.TradeAmount; } else if (orderBook.OrderSide == USeOrderSide.Sell) { sellQty += orderBook.TradeQty; sellAmount += orderBook.TradeAmount; } } if (marketData.LastPrice <= 0) { //没行情暂时不计算 return(0m); } else { decimal profit = (buyQty - sellQty) * marketData.LastPrice * instrumentDetail.VolumeMultiple + sellAmount - buyAmount; return(profit); } }
/// <summary> /// 计算当前套利单占用的保证金。 /// </summary> /// <returns></returns> public decimal CalculatUseMargin() { ArbitrageOpenArgument openArg = null; lock (m_syncObj) { if (m_arbitrageOrder.State == ArbitrageOrderState.Finish || m_arbitrageOrder.State == ArbitrageOrderState.Closed) { //平仓完成套利单不占用保证金 return(0m); } openArg = m_arbitrageOrder.OpenArgument.Clone(); } USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; USeQuoteDriver quoteDriver = USeManager.Instance.QuoteDriver; USeInstrumentDetail buyInstrumentDetail = orderDriver.QueryInstrumentDetail(openArg.BuyInstrument); USeInstrumentDetail sellInstrumentDetail = orderDriver.QueryInstrumentDetail(openArg.SellInstrument); USeMarketData buyMarketData = quoteDriver.Query(openArg.BuyInstrument); USeMarketData sellMarketData = quoteDriver.Query(openArg.SellInstrument); USeMargin buyMarginRate = orderDriver.QueryInstrumentMargin(openArg.BuyInstrument); USeMargin sellMarginRate = orderDriver.QueryInstrumentMargin(openArg.SellInstrument); decimal buyMargin = (openArg.TotalOrderQty * buyMarginRate.BrokerLongMarginRatioByVolume) + (buyMarketData.LastPrice * openArg.TotalOrderQty * buyInstrumentDetail.VolumeMultiple * buyMarginRate.BrokerLongMarginRatioByMoney); decimal sellMargin = (openArg.TotalOrderQty * sellMarginRate.BrokerShortMarginRatioByVolume) + (sellMarketData.LastPrice * openArg.TotalOrderQty * sellInstrumentDetail.VolumeMultiple * sellMarginRate.BrokerShortMarginRatioByMoney); if (openArg.BuyInstrument.Market == USeMarket.SHFE && openArg.SellInstrument.Market == USeMarket.SHFE) { return(Math.Max(buyMargin, sellMargin)); } else { return(buyMargin + sellMargin); } }
public USeInstrumentDetail GetInstrument_1708() { USeInstrumentDetail cuInstrument_1708 = new USeInstrumentDetail(); USeInstrument instrument_cu1708 = new USeInstrument("cu1708", "沪铜1708", USeMarket.SHFE); cuInstrument_1708.Instrument = instrument_cu1708; cuInstrument_1708.OpenDate = DateTime.Now; cuInstrument_1708.ExpireDate = DateTime.Now; cuInstrument_1708.EndDelivDate = DateTime.Now; cuInstrument_1708.VolumeMultiple = 5; cuInstrument_1708.IsTrading = true; cuInstrument_1708.Varieties = "cu"; cuInstrument_1708.PriceTick = 10; cuInstrument_1708.ExchangeLongMarginRatio = 0; cuInstrument_1708.ExchangeShortMarginRatio = 0; cuInstrument_1708.ProductClass = USeProductClass.Futures; cuInstrument_1708.UnderlyingInstrument = "cu"; cuInstrument_1708.StrikePrice = 0; cuInstrument_1708.OptionsType = USeOptionsType.None; cuInstrument_1708.InstrumentSerial = "cu"; return(cuInstrument_1708); }
/// <summary> /// 根据最小变动单位修剪下单价格。 /// 【朝优先成交方向优化,买入向上,卖出向下修剪】。 /// </summary> /// <param name="instrument">合约。</param> /// <param name="orderPrice">下单价格。</param> /// <param name="orderSide">买卖方向。</param> /// <returns></returns private decimal TrimOrderPrice(USeInstrument instrument, decimal orderPrice, USeOrderSide orderSide) { USeInstrumentDetail instrumentDetail = m_orderDriver.QueryInstrumentDetail(instrument); decimal trimPrice = (int)(orderPrice / instrumentDetail.PriceTick) * instrumentDetail.PriceTick; if (orderPrice != trimPrice) { if (orderSide == USeOrderSide.Buy) { Debug.Assert(trimPrice < orderPrice); // 买入价格高一个最小变动单位 trimPrice = trimPrice + instrumentDetail.PriceTick; } else { Debug.Assert(orderSide == USeOrderSide.Sell); trimPrice = trimPrice - instrumentDetail.PriceTick; // 卖出价格低一个最小变动单位 } } return(trimPrice); }
/// <summary> /// 查询成交回报。 /// </summary> /// <returns></returns> private List <TradeBookCalcItem> QueryTradeBooks() { USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; List <USeTradeBook> tradeBookList = orderDriver.QueryTradeBooks(); List <TradeBookCalcItem> list = new List <TradeBookCalcItem>(); if (tradeBookList == null) { return(list); } foreach (USeTradeBook tradeItem in tradeBookList) { USeInstrumentDetail detail = orderDriver.QueryInstrumentDetail(tradeItem.Instrument); //USeMargin productMargin = orderDriver.QueryInstrumentMargin(tradeItem.Instrument); TradeBookCalcItem calcItem = new TradeBookCalcItem() { InstrumentDetail = detail, TradeNum = tradeItem.TradeNum, Instrument = tradeItem.Instrument, OrderNum = tradeItem.OrderNum, OrderSide = tradeItem.OrderSide, OffsetType = tradeItem.OffsetType, Price = tradeItem.Price, Qty = tradeItem.Qty, Amount = tradeItem.Amount, Fee = tradeItem.Fee, TradeTime = tradeItem.TradeTime, Account = tradeItem.Account }; list.Add(calcItem); } return(list); }
private USeFundDetail CalculFoundBeforeTrade() { USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; USeQuoteDriver quoteDriver = USeManager.Instance.QuoteDriver; try { List <USeTradeBook> tradeBookList = orderDriver.QueryTradeBooks(); List <USePositionDetail> tradeAccountPosList = orderDriver.QueryPositionDetail(); List <USeOrderBook> orderBookList = orderDriver.QueryOrderBooks(); USeFund accountInfo = orderDriver.QueryFundInfo(); if (tradeBookList == null || tradeAccountPosList == null || orderBookList == null || accountInfo == null) { return(null); } #region 读取 decimal preBalance = accountInfo.PreBalance; //上日客户权益(读取)即上日结算准备金 decimal preCredit = accountInfo.PreCredit; // 上日信用额度 decimal preMortgage = accountInfo.PreMortgage; // 上次质押金额 decimal mortgage = accountInfo.Mortgage; // 质押金额 decimal withDraw = accountInfo.WithDraw; // 今日出金 decimal deposit = accountInfo.Deposit; // 今日入金 decimal deliveryMargin = accountInfo.DeliveryMargin; //交割保证金 #endregion 读取 // 静态权益 = 上日结存 - 上次信用额度 - 上次质押金额 // + 质押金额(可能有延时)- 今日出金(可能有延时) + 今日入金(可能有延时) decimal staticBenefit = preBalance - preCredit - preMortgage + mortgage - withDraw + deposit; #region 成交回报推算 decimal holdHistoryMargin = 0m; decimal holdMargin = 0m; foreach (USePositionDetail posItem in tradeAccountPosList) { USeInstrumentDetail detail = orderDriver.QueryInstrumentDetail(posItem.Instrument); int volumeMultiple = detail.VolumeMultiple; USeMargin productMargin = orderDriver.QueryInstrumentMargin(posItem.Instrument); USeMarketData marketData = quoteDriver.Query(posItem.Instrument); if (posItem.RemainQty > 0) // 有持仓 { if (posItem.PositionType == USePositionType.Yestorday && posItem.Direction == USeDirection.Long) { // 历史多头持仓保证金 = 上日结算价 × 合约乘数 × 持仓手数 × 交易所多头保证金率 decimal margin = (marketData.PreSettlementPrice * volumeMultiple * posItem.RemainQty * productMargin.BrokerLongMarginRatioByMoney) + (posItem.RemainQty * productMargin.BrokerLongMarginRatioByVolume); holdHistoryMargin += margin; } else if (posItem.PositionType == USePositionType.Yestorday && posItem.Direction == USeDirection.Short) { decimal margin = (marketData.PreSettlementPrice * volumeMultiple * posItem.RemainQty * productMargin.BrokerShortMarginRatioByMoney) + (posItem.RemainQty * productMargin.BrokerLongMarginRatioByVolume); holdHistoryMargin += margin; } else { Debug.Assert(false); } } } holdMargin = holdHistoryMargin; #endregion // 动态权益 = 静态权益 decimal dynamicBenefit = staticBenefit; decimal frozon = 0; decimal closeProfit = 0m; decimal holdProfit = 0m; decimal tradeFee = 0m; decimal available = dynamicBenefit - holdMargin - frozon - deliveryMargin; //风险度 = (占用保证金 + 交割保证金) / 动态权益 decimal risk = decimal.Divide((holdMargin + deliveryMargin), dynamicBenefit); decimal preferCash = available; if (tradeBookList.Count != 0 || tradeAccountPosList.Count != 0) { preferCash = (decimal)(preferCash * 7 / 10); } USeFundDetail fundDetail = new USeFundDetail(); fundDetail.AccountID = string.Empty; fundDetail.Available = available; fundDetail.Deposit = deposit; fundDetail.Mortgage = mortgage; fundDetail.PreBalance = preBalance; fundDetail.PreCredit = preCredit; fundDetail.PreMortgage = preMortgage; fundDetail.WithDraw = withDraw; fundDetail.StaticBenefit = staticBenefit; fundDetail.CloseProfit = closeProfit; fundDetail.TradeFee = tradeFee; fundDetail.HoldProfit = holdProfit; fundDetail.HoldMargin = holdMargin; fundDetail.DynamicBenefit = dynamicBenefit; fundDetail.FrozonMargin = 0; fundDetail.AccountID = string.Empty; fundDetail.Available = available; fundDetail.Deposit = deposit; fundDetail.Mortgage = mortgage; fundDetail.PreBalance = preBalance; fundDetail.PreCredit = preCredit; fundDetail.PreMortgage = preMortgage; fundDetail.WithDraw = withDraw; fundDetail.StaticBenefit = staticBenefit; fundDetail.CloseProfit = closeProfit; fundDetail.TradeFee = tradeFee; fundDetail.HoldProfit = holdProfit; fundDetail.HoldMargin = holdMargin; fundDetail.DynamicBenefit = dynamicBenefit; fundDetail.FrozonMargin = 0; fundDetail.FrozonFee = 0; fundDetail.Fronzon = frozon; fundDetail.Risk = risk; fundDetail.PreferCash = preferCash; return(fundDetail); } catch (Exception ex) { Debug.Assert(false, ex.Message); return(null); } }
/// <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); WriteConsoleLog(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交易服务器成功"; WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "连接CTP交易服务器失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); 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); return(-1); } List <USeInstrumentDetail> entityList = new List <USeInstrumentDetail>(); try { List <InstrumentField> instrumentList = ctpApp.QueryInstument(); foreach (InstrumentField item in instrumentList) { if (item.ProductClass != ProductClass.Futures) { continue; } try { USeInstrumentDetail entity = InsturmentFiledToUSeInstrumentDetail(item); entityList.Add(entity); } catch (Exception eee) { Debug.Assert(false, eee.Message); } } text = string.Format("查询期货合约数据完成,共计{0}个合约", entityList.Count); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); ctpApp.Disconnect(); } catch (Exception ex) { text = "查询期货合约数据失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { SaveInstumentsToDB(entityList); text = string.Format("保存期货合约信息完成,共计{0}个合约", entityList.Count); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "保存期货合约信息失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); return(-1); } return(0); }
/// <summary> /// 从Ctp查询手续费。 /// </summary> /// <param name="instrumentCode">合约代码。</param> /// <returns></returns> private InstrumentCommissionRateField QueryCommissionRateFieldFromCtp(string instrumentCode) { List <InstrumentCommissionRateField> commissionFields = new List <InstrumentCommissionRateField>(); int requestID = m_requetSeqIDCreator.Next(); try { USeResetEvent queryEvent = new USeResetEvent(requestID); queryEvent.Tag = commissionFields; m_eventDic.Add(queryEvent.EventID, queryEvent); QryInstrumentCommissionRateField requestFields = new QryInstrumentCommissionRateField(); requestFields.BrokerID = m_brokerID; requestFields.InvestorID = m_investorID; requestFields.InstrumentID = instrumentCode; m_ctpUser.ReqQryInstrumentCommissionRate(ref requestFields, requestID); while (true) { if (queryEvent.IsError) { Debug.Assert(queryEvent.Tag != null); RspInfoField rspInfo = (RspInfoField)queryEvent.Tag; throw new Exception(string.Format("({0}){1}", rspInfo.ErrorID, rspInfo.ErrorMsg)); } if (queryEvent.IsFinish) { break; } if (queryEvent.WaitOne(m_queryTimeOut) == false) { throw new Exception(string.Format("({0}){1}", "99", "time out")); } } } catch (Exception ex) { m_logger.WriteError(string.Format("{0}.QueryCommissionRateFieldFromCtp() failed,Error:{1}.", ToString(), ex.Message)); throw new Exception(string.Format("Query [{0}] commission rate failed,Error:{1}.", instrumentCode, ex.Message)); } finally { m_eventDic.Remove(requestID); } if (commissionFields.Count > 0) { Debug.Assert(commissionFields.Count == 1); return(commissionFields[0]); } else { //查询有应答但无值,构造一个空的手续费 USeInstrumentDetail instrumentDetail = m_dataBuffer.GetInstrumentDetail(instrumentCode); Debug.Assert(instrumentDetail != null); InstrumentCommissionRateField rateField = new InstrumentCommissionRateField(); rateField.BrokerID = m_brokerID; rateField.CloseRatioByMoney = 0d; rateField.CloseRatioByVolume = 0d; rateField.CloseTodayRatioByMoney = 0d; rateField.CloseTodayRatioByVolume = 0d; rateField.InstrumentID = instrumentDetail.Varieties; rateField.InvestorID = m_investorID; rateField.InvestorRange = InvestorRangeType.All; rateField.OpenRatioByMoney = 0d; rateField.OpenRatioByVolume = 0d; return(rateField); } }
private void btnOK_Click(object sender, EventArgs e) { List <ErrorUSeOrderBook> result = new List <ErrorUSeOrderBook>(); try { //如果存在未被处理的委托单,提示处理 foreach (DataRow row in m_dataTable.Rows) { string errorMessage = string.Empty; if (IsMatchRule(row, out errorMessage) == false) { USeFuturesSpiritUtility.ShowErrrorMessageBox(this, "请处理异常委托单"); return; } } USeOrderDriver orderDriver = USeManager.Instance.OrderDriver; Debug.Assert(orderDriver != null); //根据界面生成结果保存到Result foreach (DataRow row in m_dataTable.Rows) { USeInstrument instrument = row["Instrument"] as USeInstrument; Debug.Assert(instrument != null); USeInstrumentDetail instrumentDetail = orderDriver.QueryInstrumentDetail(instrument); //[yangming]合约过期后可能查不到了,此处可以考虑用品种信息获取合约乘数 Debug.Assert(instrumentDetail != null); int orderQty = Convert.ToInt32(row["OrderQty"]); int tradeQty = Convert.ToInt32(row["TradeQty"]); int cancelQty = orderQty - tradeQty; Debug.Assert(cancelQty >= 0); decimal tradePrice = Convert.ToDecimal(row["TradePrice"]); decimal tradeFee = Convert.ToDecimal(row["TradeFee"]); decimal tradeAmount = tradePrice * tradeQty * instrumentDetail.VolumeMultiple; USeOrderStatus selectedOrderStatus = (USeOrderStatus)row["SelectedOrderStatus"]; USeOrderStatus status = USeOrderStatus.Unknown; if (selectedOrderStatus == USeOrderStatus.AllTraded) { status = USeOrderStatus.AllTraded; } else if (selectedOrderStatus == USeOrderStatus.AllCanceled) { if (cancelQty == orderQty) { status = USeOrderStatus.AllCanceled; } else { status = USeOrderStatus.PartCanceled; } } USeOrderNum orderNum = row["OrderNum"] as USeOrderNum; ErrorUSeOrderBook erroOrderBook = row["ErrorUSeOrderBook"] as ErrorUSeOrderBook; erroOrderBook.OrderBook.OrderStatus = status; erroOrderBook.OrderBook.CancelQty = cancelQty; erroOrderBook.OrderBook.TradeQty = tradeQty; erroOrderBook.OrderBook.TradePrice = tradePrice; erroOrderBook.OrderBook.TradeAmount = tradeAmount; erroOrderBook.OrderBook.TradeFee = tradeFee; result.Add(erroOrderBook); } this.Result = result; } catch (Exception ex) { USeFuturesSpiritUtility.ShowWarningMessageBox(this, ex.Message); return; } this.DialogResult = DialogResult.Yes; this.Close(); }
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); }
/// <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); }