예제 #1
0
파일: Quotation.cs 프로젝트: botvs/QTS
 public Quotation(ThostFtdcDepthMarketDataField field)
 {
     this.InstrumentID = field.InstrumentID;
     this.AskPrice = field.AskPrice1;
     this.BidPrice = field.BidPrice1;
     this.LastPrice = field.LastPrice;
 }
예제 #2
0
 public static void ProcessMarketDataField(ThostFtdcDepthMarketDataField field)
 {
     var quotation = new Quotation(field);
     int volume = 0;
     Quotation preQuotation;
     if (quotationDic.TryGetValue(quotation.InstrumentID, out preQuotation) && preQuotation.TradingDay == quotation.TradingDay)
     {
         volume = quotation.Volume - preQuotation.Volume;
     }
     quotationDic[quotation.InstrumentID] = quotation;
     CandleCenter.ProcessQuotation(quotation, volume);
     DataSaver.AddQuotation(quotation);
     IQuotationReceiver[] receivers;
     lock (subscribeDic)
     {
         List<IQuotationReceiver> receiverList;
         if (!subscribeDic.TryGetValue(quotation.InstrumentID, out receiverList))
         {
             return;
         }
         receivers = receiverList.ToArray();
     }
     foreach (var item in receivers)
     {
         item.ProcessQuotation(quotation, volume);
     }
 }
예제 #3
0
        /// <summary>
        /// 深度行情通知
        /// </summary>
        /// <param name="pDepthMarketData"></param>
        void OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
        {
            string s = string.Format("{0,-6} : UpdateTime = {1}.{2:D3},  LasPrice = {3}", pDepthMarketData.InstrumentID, pDepthMarketData.UpdateTime, pDepthMarketData.UpdateMillisec, pDepthMarketData.LastPrice);

            Debug.WriteLine(s);
            Console.WriteLine(s);
        }
예제 #4
0
파일: Trader.cs 프로젝트: jiangjihua/Trade
 public void OnQuote(CTP.ThostFtdcDepthMarketDataField e)
 {
     if (e.InstrumentID == instrumentID)
     {
         lastQuote = e;
     }
 }
예제 #5
0
 private void ReaderOnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
 {
     if (OnMarketDataReceived != null)
     {
         OnMarketDataReceived(this, pDepthMarketData);
     }
 }
예제 #6
0
        public static void ProcessMarketDataField(ThostFtdcDepthMarketDataField field)
        {
            var       quotation = new Quotation(field);
            int       volume    = 0;
            Quotation preQuotation;

            if (quotationDic.TryGetValue(quotation.InstrumentID, out preQuotation) && preQuotation.TradingDay == quotation.TradingDay)
            {
                volume = quotation.Volume - preQuotation.Volume;
            }
            quotationDic[quotation.InstrumentID] = quotation;
            CandleCenter.ProcessQuotation(quotation, volume);
            DataSaver.AddQuotation(quotation);
            IQuotationReceiver[] receivers;
            lock (subscribeDic)
            {
                List <IQuotationReceiver> receiverList;
                if (!subscribeDic.TryGetValue(quotation.InstrumentID, out receiverList))
                {
                    return;
                }
                receivers = receiverList.ToArray();
            }
            foreach (var item in receivers)
            {
                item.ProcessQuotation(quotation, volume);
            }
        }
        private void QuoteAdapter_OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
        {
            try
            {
                lock (Utils.LockerQuote)
                {
                    if (Utils.promptForm._trader == null)
                    {
                        Utils.promptForm._trader = _trader;
                    }

                    var dtNow = DateTime.Now;

                    if (Utils.CurrentChannel != ChannelType.模拟24X7)
                    {
                        //排除登录时推送的过期行情
                        if ((dtNow.Hour == 6 && dtNow.Minute >= 45 && dtNow.Minute <= 58) || (dtNow.Hour == 18 && dtNow.Minute >= 45 && dtNow.Minute <= 58))
                        {
                            return;
                        }
                    }

                    Utils.WriteQuote(pDepthMarketData);
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #8
0
파일: Quotation.cs 프로젝트: botvs/QTS
 public Quotation(ThostFtdcDepthMarketDataField field)
 {
     this.TradingDay = DateTimeHelper.ConvertTradingDay(field.TradingDay);
     this.InstrumentID = field.InstrumentID;
     this.ExchangeID = field.ExchangeID;
     this.ExchangeInstID = field.ExchangeInstID;
     this.LastPrice = field.LastPrice;
     this.PreSettlementPrice = field.PreSettlementPrice;
     this.PreClosePrice = field.PreClosePrice;
     this.PreOpenInterest = field.PreOpenInterest;
     this.OpenPrice = field.OpenPrice;
     this.HighestPrice = field.HighestPrice;
     this.LowestPrice = field.LowestPrice;
     this.Volume = field.Volume;
     this.Turnover = field.Turnover;
     this.OpenInterest = field.OpenInterest;
     this.ClosePrice = field.ClosePrice;
     this.SettlementPrice = field.SettlementPrice;
     this.UpperLimitPrice = field.UpperLimitPrice;
     this.LowerLimitPrice = field.LowerLimitPrice;
     this.PreDelta = field.PreDelta;
     this.CurrDelta = field.CurrDelta;
     this.Time = GetTime(field.ActionDay, field.UpdateTime, field.UpdateMillisec);
     this.BidPrice1 = field.BidPrice1;
     this.BidVolume1 = field.BidVolume1;
     this.AskPrice1 = field.AskPrice1;
     this.AskVolume1 = field.AskVolume1;
     this.AveragePrice = field.AveragePrice;
 }
예제 #9
0
        /// <summary>
        /// 行情返回回调
        /// </summary>
        /// <param name="pDepthMarketData"></param>
        public void HandleOnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
        {
            var tick = new TickData();

            tick.gatewayName   = this.Gateway.gatewayName;
            tick.symbol        = pDepthMarketData.InstrumentID;
            tick.vtSymbol      = pDepthMarketData.InstrumentID;
            tick.exchange      = "";
            tick.lastPrice     = pDepthMarketData.LastPrice;
            tick.volume        = pDepthMarketData.Volume;
            tick.openInterest  = (int)pDepthMarketData.OpenInterest;
            tick.time          = pDepthMarketData.UpdateTime;
            tick.openPrice     = pDepthMarketData.OpenPrice;
            tick.highPrice     = pDepthMarketData.HighestPrice;
            tick.lowPrice      = pDepthMarketData.LowestPrice;
            tick.preClosePrice = pDepthMarketData.PreClosePrice;
            tick.upperLimit    = pDepthMarketData.UpperLimitPrice;
            tick.lowerLimit    = pDepthMarketData.LowerLimitPrice;
            tick.bidPrice1     = pDepthMarketData.BidPrice1;
            tick.bidVolume1    = pDepthMarketData.BidVolume1;
            tick.bidPrice2     = pDepthMarketData.BidPrice2;
            tick.bidVolume2    = pDepthMarketData.BidVolume2;
            tick.bidPrice3     = pDepthMarketData.BidPrice3;
            tick.bidVolume3    = pDepthMarketData.BidVolume3;
            tick.bidPrice4     = pDepthMarketData.BidPrice4;
            tick.bidVolume4    = pDepthMarketData.BidVolume4;
            tick.bidPrice5     = pDepthMarketData.BidPrice5;
            tick.bidVolume5    = pDepthMarketData.BidVolume5;
            ///行情推送
            this.Gateway.MainController.MainEvent._OnTick.Invoke(tick);
        }
        private void QuoteAdapter_OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
        {
            try
            {
                lock (Utils.LockerQuote)
                {
                    if (Utils.promptForm._trader == null)
                    {
                        Utils.promptForm._trader = _trader;
                    }

                    var dtNow = DateTime.Now;

                    if (Utils.CurrentChannel != ChannelType.模拟24X7 &&
                        ((dtNow.Hour >= 0 && dtNow.Hour <= 8) || (dtNow.Hour >= 16 && dtNow.Hour <= 20) ||
                         dtNow.DayOfWeek == DayOfWeek.Saturday || dtNow.DayOfWeek == DayOfWeek.Sunday)) //排除无效时段的行情
                    {
                        return;
                    }

                    Utils.WriteQuote(pDepthMarketData);
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #11
0
파일: Quotation.cs 프로젝트: damoye/QTS
 public Quotation(ThostFtdcDepthMarketDataField field)
 {
     this.TradingDay         = DateTimeHelper.ConvertTradingDay(field.TradingDay);
     this.InstrumentID       = field.InstrumentID;
     this.ExchangeID         = field.ExchangeID;
     this.ExchangeInstID     = field.ExchangeInstID;
     this.LastPrice          = field.LastPrice;
     this.PreSettlementPrice = field.PreSettlementPrice;
     this.PreClosePrice      = field.PreClosePrice;
     this.PreOpenInterest    = field.PreOpenInterest;
     this.OpenPrice          = field.OpenPrice;
     this.HighestPrice       = field.HighestPrice;
     this.LowestPrice        = field.LowestPrice;
     this.Volume             = field.Volume;
     this.Turnover           = field.Turnover;
     this.OpenInterest       = field.OpenInterest;
     this.ClosePrice         = field.ClosePrice;
     this.SettlementPrice    = field.SettlementPrice;
     this.UpperLimitPrice    = field.UpperLimitPrice;
     this.LowerLimitPrice    = field.LowerLimitPrice;
     this.PreDelta           = field.PreDelta;
     this.CurrDelta          = field.CurrDelta;
     this.Time         = GetTime(field.ActionDay, field.UpdateTime, field.UpdateMillisec);
     this.BidPrice1    = field.BidPrice1;
     this.BidVolume1   = field.BidVolume1;
     this.AskPrice1    = field.AskPrice1;
     this.AskVolume1   = field.AskVolume1;
     this.AveragePrice = field.AveragePrice;
 }
예제 #12
0
 public Quotation(ThostFtdcDepthMarketDataField field)
 {
     this.InstrumentID = field.InstrumentID;
     this.AskPrice     = field.AskPrice1;
     this.BidPrice     = field.BidPrice1;
     this.LastPrice    = field.LastPrice;
 }
예제 #13
0
        void OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
        {
            //DebugPrintFunc(new StackTrace());

            //DateTime now = DateTime.Parse(pDepthMarketData.UpdateTime);
            //now.AddMilliseconds(pDepthMarketData.UpdateMillisec);
            string s = string.Format("{0,-6} : UpdateTime = {1}.{2:D3},  LasPrice = {3}", pDepthMarketData.InstrumentID, pDepthMarketData.UpdateTime, pDepthMarketData.UpdateMillisec, pDepthMarketData.LastPrice);

            Debug.WriteLine(s);
            Console.WriteLine(s);
        }
예제 #14
0
 public static string ToString2(this ThostFtdcDepthMarketDataField field)
 {
     return(string.Format("{0} {1},{2} {3},{4},{5},{6}",
                          field.TradingDay,
                          field.UpdateTime,
                          field.UpdateMillisec,
                          field.InstrumentID,
                          field.LastPrice,
                          field.AskPrice1,
                          field.BidPrice1
                          ));
 }
예제 #15
0
        private void CheckOpenOrClose()
        {
            try
            {
                lock (Utils.Locker)
                {
                    Utils.WriteLine("检查是否需要开平仓...");

                    foreach (var kv in Utils.InstrumentToQuotes)
                    {
                        var movingAverageCount = 10;

                        if (kv.Value.Count >= movingAverageCount)
                        {
                            var listTemp = new List <ThostFtdcDepthMarketDataField>();
                            for (var i = kv.Value.Count - 1; i >= kv.Value.Count - movingAverageCount; i--)
                            {
                                //行情里面会有空值
                                if (kv.Value[i] != null && kv.Value[i].LastPrice >= kv.Value[i].LowerLimitPrice &&
                                    kv.Value[i].LastPrice <= kv.Value[i].UpperLimitPrice)
                                {
                                    listTemp.Add(kv.Value[i]);
                                }
                            }

                            var depthMarketDataField = new ThostFtdcDepthMarketDataField
                            {
                                InstrumentID       = kv.Key,
                                LastPrice          = listTemp.Average(p => p.LastPrice),
                                AveragePrice       = listTemp.Average(p => Utils.GetAveragePrice(p)),
                                UpperLimitPrice    = listTemp.Average(p => p.UpperLimitPrice),
                                LowerLimitPrice    = listTemp.Average(p => p.LowerLimitPrice),
                                PreSettlementPrice = listTemp.Average(p => p.PreSettlementPrice),
                                PreClosePrice      = listTemp.Average(p => p.PreClosePrice)
                            };

                            BuyOrSell(depthMarketDataField);
                        }
                    }

                    Utils.SaveInstrumentTotalPrices();
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #16
0
파일: MdAdapter.cs 프로젝트: damoye/QTS
 private static void PublishQuotation()
 {
     while (true)
     {
         if (marketDataFieldQueue.Count == 0)
         {
             Thread.Sleep(1);
             continue;
         }
         ThostFtdcDepthMarketDataField field = marketDataFieldQueue.Dequeue();
         if (field.LastPrice == 0)
         {
             LogCenter.Log("过滤价格为0的数据:" + field.InstrumentID);
             continue;
         }
         ArbitrageViewModel.Instance.ProcessQuotation(new Quotation(field));
     }
 }
예제 #17
0
        private static DateTime CalculateTimeStamp(ThostFtdcDepthMarketDataField field)
        {
            DateTime result     = DateTime.MinValue;
            TimeSpan updateTime = CTPMarketDataHelper.GetUpdateTime(field.UpdateTime);

            if (updateTime > CTPMarketDataHelper.nightTimeSpan)
            {
                result = CTPMarketDataHelper.PreTradingDay.Add(updateTime).AddMilliseconds((double)field.UpdateMillisec);
            }
            else if (updateTime > CTPMarketDataHelper.dayTimeSpan)
            {
                result = CTPMarketDataHelper.GetDate(field.TradingDay).Add(updateTime).AddMilliseconds((double)field.UpdateMillisec);
            }
            else
            {
                result = CTPMarketDataHelper.PreTradingDay.AddDays(1.0).Add(updateTime).AddMilliseconds((double)field.UpdateMillisec);
            }
            return(result);
        }
예제 #18
0
 private void _doProcessMarketDataQuote()
 {
     while (true)
     {
         ThostFtdcDepthMarketDataField quote = null;
         if (_dataReceiver.MarketDataQueue.TryDequeue(out quote))
         {
             Tick tick = CTPMarketDataHelper.ConvertToTick(quote);
             if (_dictQuote.ContainsKey(tick.InstrumentID))
             {
                 if (!_dictQuote[tick.InstrumentID].ContainsKey(tick.UpdateTime))
                 {
                     if (_dictQuote[tick.InstrumentID].TryAdd(tick.UpdateTime, tick))
                     {
                         // 添加一个Tick
                         OnTick(tick);
                     }
                 }
                 else
                 {
                     _dictQuote[tick.InstrumentID][tick.UpdateTime] = tick;
                 }
             }
             else
             {
                 ConcurrentDictionary <string, Tick> dict = new ConcurrentDictionary <string, Tick>();
                 if (dict.TryAdd(tick.UpdateTime, tick))
                 {
                     if (_dictQuote.TryAdd(tick.InstrumentID, dict))
                     {
                         // 添加一个Tick
                         OnTick(tick);
                     }
                 }
             }
         }
     }
 }
예제 #19
0
        /*
         * --------------------------------------------------------------
         * 行情通知
         * --------------------------------------------------------------
         */
        private void OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
        {
            if (HandleRawMarketDataDel != null)
            {
                HandleRawMarketDataDel(pDepthMarketData);
            }

            if (HandleMarketDataDel != null)
            {
                CustomMarketData m = new CustomMarketData();
                m.StockCode = pDepthMarketData.InstrumentID;
                m.Exchange  = PublicDefine.EXCHANGE_SYMBOL_EN[6];
                m.Time      = int.Parse(pDepthMarketData.UpdateTime.Replace(":", ""));
                m.MilliSec  = pDepthMarketData.UpdateMillisec;
                m.NewPrice  = pDepthMarketData.LastPrice;
                m.Buy       = new double[] { pDepthMarketData.BidPrice1, pDepthMarketData.BidPrice2, pDepthMarketData.BidPrice3, pDepthMarketData.BidPrice4, pDepthMarketData.BidPrice5 };
                m.BuyVol    = new int[] { pDepthMarketData.BidVolume1, pDepthMarketData.BidVolume2, pDepthMarketData.BidVolume3, pDepthMarketData.BidVolume4, pDepthMarketData.BidVolume5 };
                m.Sell      = new double[] { pDepthMarketData.AskPrice1, pDepthMarketData.AskPrice2, pDepthMarketData.AskPrice3, pDepthMarketData.AskPrice4, pDepthMarketData.AskPrice5 };
                m.SellVol   = new int[] { pDepthMarketData.AskVolume1, pDepthMarketData.AskVolume2, pDepthMarketData.AskVolume3, pDepthMarketData.AskVolume4, pDepthMarketData.AskVolume5 };

                HandleMarketDataDel(m);
            }
        }
예제 #20
0
        public static Tick ConvertToTick(ThostFtdcDepthMarketDataField field)
        {
            return(new Tick
            {
                InstrumentID = field.InstrumentID,
                ExchangeID = field.ExchangeID,
                ExchangeInstID = field.ExchangeID,
                LastPrice = CTPMarketDataHelper.GetDoubleValue(field.LastPrice),
                PreSettlementPrice = CTPMarketDataHelper.GetDoubleValue(field.PreSettlementPrice),
                PreClosePrice = CTPMarketDataHelper.GetDoubleValue(field.PreClosePrice),
                OpenPrice = CTPMarketDataHelper.GetDoubleValue(field.OpenPrice),
                HighestPrice = CTPMarketDataHelper.GetDoubleValue(field.HighestPrice),
                LowestPrice = CTPMarketDataHelper.GetDoubleValue(field.LowestPrice),
                Volume = field.Volume,
                Turnover = CTPMarketDataHelper.GetDoubleValue(field.Turnover),
                OpenInterest = CTPMarketDataHelper.GetDoubleValue(field.OpenInterest),
                ClosePrice = CTPMarketDataHelper.GetDoubleValue(field.ClosePrice),
                SettlementPrice = CTPMarketDataHelper.GetDoubleValue(field.SettlementPrice),

                // HighLimitedPrice = CTPMarketDataHelper.GetDoubleValue(field.UpperLimitPrice),
                // LowLimitedPrice = CTPMarketDataHelper.GetDoubleValue(field.LowerLimitPrice),

                PreDelta = CTPMarketDataHelper.GetDoubleValue(field.PreDelta),
                CurrDelta = CTPMarketDataHelper.GetDoubleValue(field.CurrDelta),
                UpdateTime = field.UpdateTime,
                UpdateMillisec = field.UpdateMillisec,
                BidPrice1 = CTPMarketDataHelper.GetDoubleValue(field.BidPrice1),
                BidVolume1 = field.BidVolume1,
                AskPrice1 = CTPMarketDataHelper.GetDoubleValue(field.AskPrice1),
                AskVolume1 = field.AskVolume1,
                AveragePrice = CTPMarketDataHelper.GetDoubleValue(field.AveragePrice),
                PreOpenInterest = field.PreOpenInterest,

                // LastVolume = (long)field.Volume - lastVolume,
                // TimeStamp = CTPMarketDataHelper.CalculateTimeStamp(field)
            });
        }
예제 #21
0
파일: MdAdapter.cs 프로젝트: damoye/QTS
 public void PublishQuotation()
 {
     while (true)
     {
         if (marketDataFieldQueue.Count == 0)
         {
             Thread.Sleep(1);
             continue;
         }
         this.lastQuotationTime = DateTime.Now;
         ThostFtdcDepthMarketDataField field = marketDataFieldQueue.Dequeue();
         if (field.LastPrice == 0)
         {
             Debug.WriteLine("Filter data with no price: " + field.InstrumentID);
             continue;
         }
         field.TradingDay = this.GetTradingDay();
         if (field.ActionDay == string.Empty)
         {
             var today   = DateTime.Today;
             var builder = new StringBuilder(today.Year.ToString());
             if (today.Month < 10)
             {
                 builder.Append(0);
             }
             builder.Append(today.Month);
             if (today.Day < 10)
             {
                 builder.Append(0);
             }
             builder.Append(today.Day);
             field.ActionDay = builder.ToString();
         }
         QuotationCenter.ProcessMarketDataField(field);
     }
 }
        private void BuyOrSell(ThostFtdcDepthMarketDataField data)
        {
            if (!Utils.IsInInstrumentTradingTime(data.InstrumentID))
            {
                return;
            }

            try
            {
                if (Utils.InstrumentUpDownCount.ContainsKey(data.InstrumentID))
                {
                    var countXX = Utils.InstrumentUpDownCount[data.InstrumentID];

                    //上涨信号出现,平空仓 开多仓
                    if (countXX.UpCount >= 3)
                    {
                        var reason = string.Format("{0}看多信号,平空", data.InstrumentID);
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                        //暂时不设置涨跌幅条件限制
                        //if ((data.LastPrice / data.PreClosePrice) > 0.98)
                        //{
                        reason = string.Format("{0}看多信号,开多", data.InstrumentID);
                        _trader.OpenLongPositionByInstrument(data.InstrumentID, reason, 0, true, true, 0);
                        //}
                    }
                    //下跌信号出现,平多仓 开空仓
                    if (countXX.DownCount >= 3)
                    {
                        var reason = string.Format("{0}看空信号,平多", data.InstrumentID);
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);

                        //if ((data.LastPrice / data.PreClosePrice) < 1.02)
                        //{
                        reason = string.Format("{0}看空信号,开空", data.InstrumentID);
                        _trader.OpenShortPositionByInstrument(data.InstrumentID, reason, 9999, true, true, 0);
                        //}
                    }
                }

                if (Utils.InstrumentToStopLossPrices.ContainsKey(data.InstrumentID))
                {
                    var stopLossPrices = Utils.InstrumentToStopLossPrices[data.InstrumentID];

                    var stopLossValue = 10;

                    //多仓止损
                    if (data.LastPrice < stopLossPrices.CostLong - stopLossValue)
                    {
                        var reason = string.Format("{0}从多仓的成本价{1}跌到了绝对止损值{2}以下,即{3},平掉多仓", data.InstrumentID,
                                                   stopLossPrices.CostLong, stopLossValue, data.LastPrice);
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);
                    }

                    //空仓止损
                    if (data.LastPrice > stopLossPrices.CostShort + stopLossValue)
                    {
                        var reason = string.Format("{0}从空仓的成本价{1}涨到了绝对止损值{2}以上,即{3},平掉空仓", data.InstrumentID,
                                                   stopLossPrices.CostShort, stopLossValue, data.LastPrice);
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                    }

                    var longDistance               = stopLossPrices.ForLong - stopLossPrices.CostLong;
                    var currentLongDistance        = data.LastPrice - stopLossPrices.CostLong;
                    var movingStopLossValueForLong = longDistance * 0.5;

                    //多仓止损
                    if (longDistance > 10 && longDistance <= 20 && data.LastPrice < stopLossPrices.ForLong - movingStopLossValueForLong)
                    {
                        var reason = string.Format("{0}从多仓的最高盈利价{1}跌到了移动止损价{2}以下,即{3},平掉多仓", data.InstrumentID,
                                                   stopLossPrices.ForLong, stopLossPrices.ForLong - movingStopLossValueForLong, data.LastPrice);
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);
                    }
                    else
                    {
                        if (longDistance > 20 && currentLongDistance < 10)
                        {
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, "移动止损,平掉多仓");
                        }
                    }

                    var shortDistance               = stopLossPrices.CostShort - stopLossPrices.ForShort;
                    var currentShortDistance        = stopLossPrices.CostShort - data.LastPrice;
                    var movingStopLossValueForShort = shortDistance * 0.5;

                    //空仓止损
                    if (shortDistance > 10 && shortDistance <= 20 && data.LastPrice > stopLossPrices.ForShort + movingStopLossValueForShort)
                    {
                        var reason = string.Format("{0}从空仓的最高盈利价{1}涨到了移动止损价{2}以上,即{3},平掉空仓", data.InstrumentID,
                                                   stopLossPrices.ForShort, stopLossPrices.ForShort + movingStopLossValueForShort, data.LastPrice);
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                    }
                    else
                    {
                        if (shortDistance > 20 && currentShortDistance < 10)
                        {
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, "移动止损,平掉空仓");
                        }
                    }

                    if (stopLossPrices.ForLong - stopLossPrices.CostLong >= 20)
                    {
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, "多仓止盈");
                    }

                    if (stopLossPrices.CostShort - stopLossPrices.ForShort >= 20)
                    {
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, "空仓止盈");
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #23
0
 private void MD_OnTick(ThostFtdcDepthMarketDataField md)
 {
     if (this.InstrumentID == md.InstrumentID)
     {
         this.LastMarket = md;
     }
 }
예제 #24
0
 /// <summary>
 /// 更新行情信息
 /// </summary>
 public void UpdateMarket(ThostFtdcDepthMarketDataField MarketData)
 {
     this.PreMarketData = this.MarketData;
     this.MarketData = MarketData;
     if (this.MarketUpdated != null)
     {
         this.MarketUpdated(this, EventArgs.Empty);
     }
 }
예제 #25
0
 /// <summary>
 /// 行情到达时的处理
 /// </summary>
 /// <param name="MarketData"></param>
 void marketer_OnRtnDepthMarketData(ThostFtdcDepthMarketDataField MarketData)
 {
     ActiveContract activeContract;
     if (MarketManeger.ActiveContractDictionary.TryGetValue(MarketData.InstrumentID, out activeContract))
     {
         activeContract.UpdateMarket(MarketData);
     }
 }
예제 #26
0
        /// <summary>
        /// 有行情到来时的处理逻辑
        /// </summary>
        /// <param name="md"></param>
        private void MD_OnTick(ThostFtdcDepthMarketDataField md)
        {
            if (this.option.InstrumentID == md.InstrumentID)
            {
                this.option.LastMarket = md;
                //计算期权理论价格
                OptionPricingModelParams optionPricingModelParams = new OptionPricingModelParams(this.option.OptionType,
                    MainForm.Future.LastMarket.LastPrice, this.option.StrikePrice, GlobalValues.InterestRate, GlobalValues.Volatility,
                    StaticFunction.GetDaysToMaturity(this.option.InstrumentID));
                this.option.OptionValue = OptionPricingModel.EuropeanBS(optionPricingModelParams);
                ////计算隐含波动率
                if (MainForm.Future.LastMarket != null)
                {
                    this.option.ImpliedVolatility = StaticFunction.CalculateImpliedVolatilityBisection(MainForm.Future.LastMarket.LastPrice, this.option.StrikePrice,
                        StaticFunction.GetDaysToMaturity(this.option.InstrumentID), GlobalValues.InterestRate, md.LastPrice, this.option.OptionType);

                    string[] updateDateTimeString = md.UpdateTime.Split(':');
                    DateTime updateDateTime = new DateTime();
                    updateDateTime = updateDateTime.AddHours(double.Parse(updateDateTimeString[0]));
                    updateDateTime = updateDateTime.AddMinutes(double.Parse(updateDateTimeString[1]));
                    updateDateTime = updateDateTime.AddSeconds(double.Parse(updateDateTimeString[2]));
                    if ((updateDateTime - lastUpdateDateTime).TotalSeconds > this.ReplaceOrderDuration)
                    {
                        //撤单
                        this.CancelOrder();
                        //计算报价
                        double[] quote = this.CalculateQuote();
                        if (isRunning)
                        {
                            this.ReplaceOrderDuration = 11;
                            this.lastUpdateDateTime = updateDateTime;
                            this.PlaceOrder(quote);
                        }
                        else if (hasForQuote)
                        {
                            this.ReplaceOrderDuration = 11;
                            this.lastUpdateDateTime = updateDateTime;
                            hasForQuote = false;
                            this.PlaceOrder(quote);
                        }
                    }
                }
            }
        }
        private void BuyOrSell(ThostFtdcDepthMarketDataField data)
        {
            try
            {
                var instrumentId = data.InstrumentID;
                var dateTime     = Convert.ToDateTime(data.UpdateTime);
                var currentSwing = (data.HighestPrice - data.LowestPrice) / data.PreClosePrice;

                if (dateTime.Hour == 14 && dateTime.Minute == 59 && dateTime.Second >= 50)
                {
                    var bProcessed = false;

                    Utils.WriteLine(string.Format("当前价:{0},前收价:{1},开盘价:{2},最高价:{3},最低价:{4}", data.LastPrice, data.PreClosePrice, data.OpenPrice, data.HighestPrice, data.LowestPrice), true);

                    if (data.LastPrice < data.PreClosePrice && data.LastPrice < data.OpenPrice && _trader.ContainsPositionByInstrument(instrumentId, EnumPosiDirectionType.Long) && data.LastPrice < data.LowestPrice * 1.01)
                    {
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, "平多", false, 0);
                        Thread.Sleep(2000);
                    }

                    if (data.LastPrice > data.PreClosePrice && data.LastPrice > data.OpenPrice && _trader.ContainsPositionByInstrument(instrumentId, EnumPosiDirectionType.Short) && data.LastPrice > data.HighestPrice * 0.99)
                    {
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, "平空", false, 9999);
                        Thread.Sleep(2000);
                    }

                    if (data.LastPrice / data.OpenPrice > 1.0095 && data.LastPrice > data.HighestPrice * 0.99)
                    {
                        var reason = string.Format("{0}收盘看多信号,开多", instrumentId);
                        if (noOpening)
                        {
                            noOpening = false;
                            _trader.OpenLongPositionByInstrument(instrumentId, reason, 0, true, true, 0, data.UpperLimitPrice);
                            bProcessed = true;
                            noOpening  = true;
                        }
                        else
                        {
                            Utils.WriteLine("正在开仓", true);
                        }
                    }

                    if (data.LastPrice / data.OpenPrice < 0.9905 && data.LastPrice < data.LowestPrice * 1.01)
                    {
                        var reason = string.Format("{0}收盘看空信号,开空", instrumentId);
                        if (noOpening)
                        {
                            _trader.OpenShortPositionByInstrument(instrumentId, reason, 9999, true, true, 0, data.LowerLimitPrice);
                            bProcessed = true;
                            noOpening  = true;
                        }
                        else
                        {
                            Utils.WriteLine("正在开仓", true);
                        }
                    }

                    if (bProcessed)
                    {
                        _timerOrder.Stop();
                    }
                }
                else
                {
                    var highestPriceFile = Utils.AssemblyPath + "highestPrice.ini";
                    if (_trader.ContainsPositionByInstrument(instrumentId, EnumPosiDirectionType.Long))
                    {
                        //读取持仓高点
                        var highestPrice = data.HighestPrice;

                        if (File.Exists(highestPriceFile))
                        {
                            bool store = false;
                            var  sr    = new StreamReader(highestPriceFile, Encoding.UTF8);
                            var  line  = sr.ReadLine();
                            if (line != null)
                            {
                                var storedPrice = Convert.ToDouble(line);
                                if (storedPrice < highestPrice)
                                {
                                    store = true;
                                }
                                else
                                {
                                    highestPrice = storedPrice;
                                }
                            }
                            sr.Close();

                            if (store)
                            {
                                Utils.StorePrice(highestPriceFile, highestPrice);
                            }
                        }
                        else
                        {
                            Utils.StorePrice(highestPriceFile, data.HighestPrice);
                        }

                        if (data.LastPrice / highestPrice < 0.982 && currentSwing > 0.02)
                        {
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, "最高价回落,平多", false, 0);
                        }

                        if (data.LastPrice / data.OpenPrice < 0.982)
                        {
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, "平多", false, 0);
                        }
                    }
                    else
                    {
                        Utils.DeleteStorePrice(highestPriceFile);
                    }

                    var lowestPriceFile = Utils.AssemblyPath + "lowestPrice.ini";
                    if (_trader.ContainsPositionByInstrument(instrumentId, EnumPosiDirectionType.Short))
                    {
                        //读取持仓低点
                        var lowestPrice = data.LowestPrice;

                        if (File.Exists(lowestPriceFile))
                        {
                            bool store = false;
                            var  sr    = new StreamReader(lowestPriceFile, Encoding.UTF8);
                            var  line  = sr.ReadLine();
                            if (line != null)
                            {
                                var storedPrice = Convert.ToDouble(line);
                                if (storedPrice > lowestPrice)
                                {
                                    store = true;
                                }
                                else
                                {
                                    lowestPrice = storedPrice;
                                }
                            }
                            sr.Close();

                            if (store)
                            {
                                Utils.StorePrice(lowestPriceFile, lowestPrice);
                            }
                        }
                        else
                        {
                            Utils.StorePrice(lowestPriceFile, data.LowestPrice);
                        }

                        if (data.LastPrice / data.LowestPrice > 1.018 && currentSwing > 0.02)
                        {
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, "最低价上涨,平空", false, 9999);
                        }

                        if (data.LastPrice / data.OpenPrice > 1.018)
                        {
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, "平空", false, 9999);
                        }
                    }
                    else
                    {
                        Utils.DeleteStorePrice(lowestPriceFile);
                    }

                    if (data.LastPrice / data.OpenPrice > 1.015 && data.LastPrice > data.HighestPrice * 0.99)
                    {
                        var reason = string.Format("{0}盘中看多信号,开多", instrumentId);
                        if (noOpening)
                        {
                            noOpening = false;
                            _trader.OpenLongPositionByInstrument(instrumentId, reason, 0, true, true, 0, data.UpperLimitPrice);
                            noOpening = true;
                        }
                        else
                        {
                            Utils.WriteLine("正在开仓", true);
                        }
                    }

                    if (data.LastPrice / data.OpenPrice < 0.985 && data.LastPrice < data.LowestPrice * 1.01)
                    {
                        var reason = string.Format("{0}盘中看空信号,开空", instrumentId);
                        if (noOpening)
                        {
                            noOpening = false;
                            _trader.OpenShortPositionByInstrument(instrumentId, reason, 9999, true, true, 0, data.LowerLimitPrice);
                            noOpening = true;
                        }
                        else
                        {
                            Utils.WriteLine("正在开仓", true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #28
0
 private void QuoteAdapter_OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
 {
 }
예제 #29
0
 public void OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
 {
     cMainForm.SetMDDepthMarketData((object)pDepthMarketData);
 }
        private void BuyOrSell(ThostFtdcDepthMarketDataField data)
        {
            try
            {
                #region 平仓策略

                if (Utils.InstrumentToStopLossPrices.ContainsKey(data.InstrumentID))
                {
                    var stopLossPrices = Utils.InstrumentToStopLossPrices[data.InstrumentID];

                    var stopLossValue = 2;

                    //多仓止损
                    if (data.LastPrice < stopLossPrices.CostLong - stopLossValue)
                    {
                        var reason = string.Format("{0}从多仓的成本价{1}跌到了绝对止损值{2}以下,即{3},平掉多仓", data.InstrumentID,
                                                   stopLossPrices.CostLong, stopLossValue, data.LastPrice);
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);
                    }

                    //空仓止损
                    if (data.LastPrice > stopLossPrices.CostShort + stopLossValue)
                    {
                        var reason = string.Format("{0}从空仓的成本价{1}涨到了绝对止损值{2}以上,即{3},平掉空仓", data.InstrumentID,
                                                   stopLossPrices.CostShort, stopLossValue, data.LastPrice);
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                    }

                    var minuteByMinute = Utils.InstrumentToMinuteByMinuteChart[data.InstrumentID];

                    Tuple <bool, double, double> isPointingUpMinuteLong2   = new Tuple <bool, double, double>(false, 0, 0);
                    Tuple <bool, double, double> isPointingDownMinuteLong2 = new Tuple <bool, double, double>(false, 0, 0);
                    Tuple <bool, double, double> isPointingUpMinuteHalf    = new Tuple <bool, double, double>(false, 0, 0);
                    Tuple <bool, double, double> isPointingDownMinuteHalf  = new Tuple <bool, double, double>(false, 0, 0);

                    if (minuteByMinute.Count >= Utils.MinuteByMinuteSizeLong)
                    {
                        var sizeHalf = Utils.MinuteByMinuteSizeLong / 2;
                        var count    = minuteByMinute.Count;

                        var minuteByMinuteQuotesLong = new List <double>();
                        for (var i = count - Utils.MinuteByMinuteSizeLong; i < count; i++)
                        {
                            if (minuteByMinute[i] != null)
                            {
                                minuteByMinuteQuotesLong.Add(minuteByMinute[i].Item2.LastPrice);
                            }
                        }

                        var minuteByMinuteQuotesHalf = new List <double>();
                        for (var i = count - sizeHalf; i < count; i++)
                        {
                            if (minuteByMinute[i] != null)
                            {
                                minuteByMinuteQuotesHalf.Add(minuteByMinute[i].Item2.LastPrice);
                            }
                        }

                        isPointingUpMinuteLong2 = MathUtils.IsPointingUp(Utils.MinuteLongXData,
                                                                         minuteByMinuteQuotesLong, MathUtils.Slope2);
                        isPointingDownMinuteLong2 = MathUtils.IsPointingDown(Utils.MinuteLongXData,
                                                                             minuteByMinuteQuotesLong, MathUtils.Slope2);

                        Utils.WriteLine(string.Format("检查当前长角度{0}", isPointingUpMinuteLong2.Item3));

                        var minuteHalfXData = new List <double>();

                        for (var i = 0; i < sizeHalf; i++)
                        {
                            minuteHalfXData.Add(i);
                        }

                        isPointingUpMinuteHalf = MathUtils.IsPointingUp(minuteHalfXData, minuteByMinuteQuotesHalf,
                                                                        MathUtils.Slope2);
                        isPointingDownMinuteHalf = MathUtils.IsPointingDown(minuteHalfXData, minuteByMinuteQuotesHalf,
                                                                            MathUtils.Slope2);
                        Utils.WriteLine(string.Format("检查当前短角度{0}", isPointingUpMinuteHalf.Item3));
                    }

                    double openTrendStartPoint = 0;

                    //从多仓的最高盈利跌了一定幅度,平掉多仓,保护盈利,忽略掉小波动
                    if (stopLossPrices.CostLong > 0 && stopLossPrices.ForLong > stopLossPrices.CostLong &&
                        stopLossPrices.ForLong > data.LastPrice)
                    {
                        var keyLongPosition = Utils.GetOpenTrendStartPointKey(data.InstrumentID,
                                                                              EnumPosiDirectionType.Long);

                        if (Utils.InstrumentToOpenTrendStartPoint.ContainsKey(keyLongPosition))
                        {
                            openTrendStartPoint = Utils.InstrumentToOpenTrendStartPoint[keyLongPosition];
                        }

                        var highestDistance = stopLossPrices.ForLong - stopLossPrices.CostLong;
                        var currentDistance = data.LastPrice - stopLossPrices.CostLong;

                        var keyLongAngle = Utils.GetOpenPositionKey(data.InstrumentID, EnumDirectionType.Buy);
                        //double limitAngle = 0;
                        //if (Utils.InstrumentToOpenAngle.ContainsKey(keyLongAngle))
                        //{
                        //    limitAngle = Utils.InstrumentToOpenAngle[keyLongAngle];
                        //}

                        if (currentDistance >= 2 && isPointingUpMinuteLong2.Item3 < MathUtils.Slope2)
                        {
                            var reason = string.Format("{0}的多仓开仓角度开始减小,平掉多仓,当前角{1},界限角{2}", data.InstrumentID, isPointingUpMinuteLong2.Item3, MathUtils.Slope2);
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);
                        }

                        //if (isPointingUpMinuteLong2.Item3 > limitAngle)
                        //{
                        //    Utils.InstrumentToOpenAngle[keyLongAngle] = limitAngle;
                        //}

                        if (highestDistance >= 5 && isPointingUpMinuteHalf.Item3 < MathUtils.Slope2 / 2)
                        {
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, "多仓止盈");
                            Thread.Sleep(2000);
                            Utils.WriteLine("盈利目标达到,退出...", true);
                            Email.SendMail("盈利目标达到,退出...", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                            Utils.Exit(_trader);
                        }
                    }

                    //从空仓的最高盈利跌了一半,平掉空仓,保护盈利,忽略掉小波动
                    if (stopLossPrices.CostShort > 0 && stopLossPrices.ForShort < stopLossPrices.CostShort &&
                        stopLossPrices.ForShort < data.LastPrice)
                    {
                        var keyShortPosition = Utils.GetOpenTrendStartPointKey(data.InstrumentID,
                                                                               EnumPosiDirectionType.Short);

                        if (Utils.InstrumentToOpenTrendStartPoint.ContainsKey(keyShortPosition))
                        {
                            openTrendStartPoint = Utils.InstrumentToOpenTrendStartPoint[keyShortPosition];
                        }

                        var highestDistance = stopLossPrices.CostShort - stopLossPrices.ForShort;
                        var currentDistance = stopLossPrices.CostShort - data.LastPrice;

                        var keyShortAngle = Utils.GetOpenPositionKey(data.InstrumentID, EnumDirectionType.Sell);
                        //double limitAngle = 0;
                        //if (Utils.InstrumentToOpenAngle.ContainsKey(keyShortAngle))
                        //{
                        //    limitAngle = Utils.InstrumentToOpenAngle[keyShortAngle];
                        //}

                        if (currentDistance >= 2 && isPointingDownMinuteLong2.Item3 > -MathUtils.Slope2)
                        {
                            var reason = string.Format("{0}的空仓开仓角度开始减小,平掉空仓,当前角{1},界限角{2}", data.InstrumentID, isPointingDownMinuteLong2.Item3, -MathUtils.Slope2);
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                        }

                        //if (isPointingDownMinuteLong2.Item3 < limitAngle)
                        //{
                        //    Utils.InstrumentToOpenAngle[keyShortAngle] = limitAngle;
                        //}

                        if (highestDistance >= 5 && isPointingDownMinuteHalf.Item3 > -MathUtils.Slope2 / 2)
                        {
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, "空仓止盈");
                            Thread.Sleep(2000);
                            Utils.WriteLine("盈利目标达到,退出...", true);
                            Email.SendMail("盈利目标达到,退出...", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                            Utils.Exit(_trader);
                        }
                    }
                }

                //接近涨停价,平掉空仓
                var upperLimitRange = (data.UpperLimitPrice + data.LowerLimitPrice) / 2;
                var lowerLimitRange = upperLimitRange;

                if (data.LastPrice > data.PreSettlementPrice + upperLimitRange * Utils.LimitCloseRange)
                {
                    var reason = string.Format("{0}最新价{1}上涨到了涨停价{2}的{3}以上,平掉空仓", data.InstrumentID, data.LastPrice,
                                               data.UpperLimitPrice, Utils.LimitCloseRange);
                    _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                }

                //接近跌停价,平掉多仓
                if (data.LastPrice < data.PreSettlementPrice - lowerLimitRange * Utils.LimitCloseRange)
                {
                    var reason = string.Format("{0}最新价{1}下跌到了跌停价{2}的{3}以下,平掉多仓", data.InstrumentID, data.LastPrice,
                                               data.LowerLimitPrice, Utils.LimitCloseRange);
                    _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);
                }

                #endregion

                #region 开仓策略

                if (Utils.InstrumentToMinuteByMinuteChart.ContainsKey(data.InstrumentID))
                {
                    lock (Utils.Locker2)
                    {
                        OpenStrategy(data, false);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #31
0
        private void OpenStrategy(ThostFtdcDepthMarketDataField data, bool ma)
        {
            try
            {
                var minuteByMinute = Utils.InstrumentToMinuteByMinuteChart[data.InstrumentID];

                if (minuteByMinute.Count >= Utils.MinuteByMinuteSizeLong)
                {
                    //当前大趋势,大趋势向上只开多仓,大趋势向下,只开空仓
                    var minuteAllXData = new List <double>();
                    var minuteAllYData = new List <double>();
                    for (var i = 0; i < minuteByMinute.Count; i++)
                    {
                        if (minuteByMinute[i] != null)
                        {
                            minuteAllXData.Add(i);
                            minuteAllYData.Add(minuteByMinute[i].Item2.LastPrice);
                        }
                    }

                    var isPointingUpMinuteAll   = MathUtils.IsPointingUp(minuteAllXData, minuteAllYData, 0.4);
                    var isPointingDownMinuteAll = MathUtils.IsPointingDown(minuteAllXData, minuteAllYData, 0.4);

                    var sizeHalf = Utils.MinuteByMinuteSizeLong / 2;
                    var count    = minuteByMinute.Count;

                    var minuteByMinuteQuotesLong = new List <double>();
                    for (var i = count - Utils.MinuteByMinuteSizeLong; i < count; i++)
                    {
                        if (minuteByMinute[i] != null)
                        {
                            minuteByMinuteQuotesLong.Add(minuteByMinute[i].Item2.LastPrice);
                        }
                    }

                    var minuteByMinuteQuotesHalf = new List <double>();
                    for (var i = count - sizeHalf; i < count; i++)
                    {
                        if (minuteByMinute[i] != null)
                        {
                            minuteByMinuteQuotesHalf.Add(minuteByMinute[i].Item2.LastPrice);
                        }
                    }

                    var isPointingUpMinuteLong2 = MathUtils.IsPointingUp(Utils.MinuteLongXData,
                                                                         minuteByMinuteQuotesLong, MathUtils.Slope2);
                    var isPointingDownMinuteLong2 = MathUtils.IsPointingDown(Utils.MinuteLongXData,
                                                                             minuteByMinuteQuotesLong, MathUtils.Slope2);

                    var minuteHalfXData = new List <double>();

                    for (var i = 0; i < sizeHalf; i++)
                    {
                        minuteHalfXData.Add(i);
                    }

                    var isPointingUpMinuteHalf = MathUtils.IsPointingUp(minuteHalfXData, minuteByMinuteQuotesHalf,
                                                                        MathUtils.Slope2);
                    var isPointingDownMinuteHalf = MathUtils.IsPointingDown(minuteHalfXData, minuteByMinuteQuotesHalf,
                                                                            MathUtils.Slope2);

                    //根据分时图走势下单
                    if (isPointingUpMinuteAll.Item1 && isPointingUpMinuteLong2.Item1 && isPointingUpMinuteHalf.Item1)
                    {
                        var min = minuteByMinuteQuotesLong.Min(p => p);
                        var keyMissedLongOpenTrendStartPoint = Utils.GetOpenPositionKey(data.InstrumentID,
                                                                                        EnumDirectionType.Buy);
                        if (Utils.InstrumentToMissedOpenTrendStartPoint.ContainsKey(keyMissedLongOpenTrendStartPoint))
                        {
                            min = Math.Min(min,
                                           Utils.InstrumentToMissedOpenTrendStartPoint[keyMissedLongOpenTrendStartPoint]);
                        }
                        else
                        {
                            Utils.SetMissedOpenStartPoint(data.InstrumentID, EnumPosiDirectionType.Long, min);
                        }
                        var reason = string.Format("{0}最近长趋势向上{1},开出多仓,移动均价开仓{2},开仓启动点{3}", data.InstrumentID,
                                                   isPointingUpMinuteLong2, ma, min);
                        _trader.OpenLongPositionByInstrument(data.InstrumentID, reason, min, true, false);
                        return;
                    }

                    if (!isPointingUpMinuteAll.Item1 && isPointingUpMinuteLong2.Item1 && isPointingUpMinuteHalf.Item1)
                    {
                        Utils.WriteLine("虽然长趋势向上,中趋势向上,但是大趋势不是,不开多仓", true);
                    }

                    if (!isPointingUpMinuteHalf.Item1 && isPointingUpMinuteLong2.Item1)
                    {
                        Utils.WriteLine("虽然长趋势向上,但是中趋势不是,不开多仓", true);
                    }

                    if (isPointingDownMinuteAll.Item1 && isPointingDownMinuteLong2.Item1 && isPointingDownMinuteHalf.Item1)
                    {
                        var max = minuteByMinuteQuotesLong.Max(p => p);
                        var keyMissedShortOpenTrendStartPoint = Utils.GetOpenPositionKey(data.InstrumentID,
                                                                                         EnumDirectionType.Sell);
                        if (Utils.InstrumentToMissedOpenTrendStartPoint.ContainsKey(keyMissedShortOpenTrendStartPoint))
                        {
                            max = Math.Max(max,
                                           Utils.InstrumentToMissedOpenTrendStartPoint[keyMissedShortOpenTrendStartPoint]);
                        }
                        else
                        {
                            Utils.SetMissedOpenStartPoint(data.InstrumentID, EnumPosiDirectionType.Short, max);
                        }
                        var reason = string.Format("{0}最近长趋势向下{1},开出空仓,移动均价开仓{2},开仓启动点{3}", data.InstrumentID,
                                                   isPointingDownMinuteLong2, ma, max);
                        _trader.OpenShortPositionByInstrument(data.InstrumentID, reason, max, true, false);
                        return;
                    }

                    if (!isPointingDownMinuteAll.Item1 && isPointingDownMinuteLong2.Item1 && isPointingDownMinuteHalf.Item1)
                    {
                        Utils.WriteLine("虽然长趋势向下,中趋势向下,但是大趋势不是,不开空仓", true);
                    }

                    if (!isPointingDownMinuteHalf.Item1 && isPointingDownMinuteLong2.Item1)
                    {
                        Utils.WriteLine("虽然长趋势向下,但是中趋势不是,不开空仓", true);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #32
0
        private void sqlitedb(object s)
        {
            MainForm cMainForm = (MainForm)s;
            ThostFtdcDepthMarketDataField pDepthMarketData = new ThostFtdcDepthMarketDataField();
            QueueSendData Data = new QueueSendData();
            bool bCommit=false;
            while (Queue_SQLite.bUse)
            {
                if (Queue_SQLite.DataQ.Count == 0)
                {
                    Queue_SQLite.Are.WaitOne();
                    Queue_SQLite.Are.Reset();
                    if(bCommit)
                        MemDB.Commit();
                }
                else
                {
                    Data = Queue_SQLite.DataQ.Dequeue();
                    Queue_SQLite.m_lReceiveNum++;
                    #region 这里写策略
                    switch (Data.QueueType)
                    {
                        case EnumQueueType.DepthMarketData:
                            pDepthMarketData = (ThostFtdcDepthMarketDataField)Data.QueueData;
                            if (pDepthMarketData.TradingDay == "" || pDepthMarketData.InstrumentID == "")
                            {
                                Queue_SQLite.m_lDropNum++;
                                Queue_SQLite.Are.Reset();
                            }
                            #region 数据入内存数据库
                            if (sTradingDay != pDepthMarketData.TradingDay || sTableName == string.Empty)
                            {
                                sTableName = "TIP_" + pDepthMarketData.TradingDay;
                                sTradingDay = pDepthMarketData.TradingDay;
                                if (!MemDB.existTable(sTableName))
                                {
                                    string vSQL = string.Format(sDeepRspTableSql, sTableName);
                                    MemDB.setSQL(vSQL);
                                    MemDB.Execute();
                                    MemDB.Commit();
                                }
                            }
                            string sSql = "insert into " + sTableName + "(ActionDay,BidPrice1,BidPrice2,BidPrice3,BidPrice4,BidPrice5,BidVolume1,BidVolume2,BidVolume3,BidVolume4,BidVolume5,AveragePrice,AskPrice1,AskPrice2,AskPrice3,AskPrice4,AskPrice5,AskVolume1,AskVolume2,AskVolume3,AskVolume4,AskVolume5,ClosePrice,CurrDelta,ExchangeID,ExchangeInstID,HighestPrice,InstrumentID,LastPrice,LowerLimitPrice,LowestPrice,OpenInterest,OpenPrice,PreClosePrice,PreDelta,PreOpenInterest,PreSettlementPrice,SettlementPrice,TradingDay,Turnover,UpdateMillisec,UpdateTime,UpperLimitPrice,Volume) values ('"
                                + pDepthMarketData.ActionDay + "','" + pDepthMarketData.BidPrice1 + "','"
                                + pDepthMarketData.BidPrice2 + "','" + pDepthMarketData.BidPrice3 + "','" + pDepthMarketData.BidPrice4 + "','" + pDepthMarketData.BidPrice5 + "','"
                                + pDepthMarketData.BidVolume1 + "','" + pDepthMarketData.BidVolume2 + "','" + pDepthMarketData.BidVolume3 + "','" + pDepthMarketData.BidVolume4 + "','"
                                + pDepthMarketData.BidVolume5 + "','" + pDepthMarketData.AveragePrice + "','" + pDepthMarketData.AskPrice1 + "','" + pDepthMarketData.AskPrice2 + "','"
                                + pDepthMarketData.AskPrice3 + "','" + pDepthMarketData.AskPrice4 + "','" + pDepthMarketData.AskPrice5 + "','" + pDepthMarketData.AskVolume1 + "','"
                                + pDepthMarketData.AskVolume2 + "','" + pDepthMarketData.AskVolume3 + "','" + pDepthMarketData.AskVolume4 + "','" + pDepthMarketData.AskVolume5 + "','"
                                + pDepthMarketData.ClosePrice + "','" + pDepthMarketData.CurrDelta + "','" + pDepthMarketData.ExchangeID + "','"
                                + pDepthMarketData.ExchangeInstID + "','" + pDepthMarketData.HighestPrice + "','" + pDepthMarketData.InstrumentID + "','"
                                + pDepthMarketData.LastPrice + "','" + pDepthMarketData.LowerLimitPrice + "','" + pDepthMarketData.LowestPrice + "','"
                                + pDepthMarketData.OpenInterest + "','" + pDepthMarketData.OpenPrice + "','" + pDepthMarketData.PreClosePrice + "','"
                                + pDepthMarketData.PreDelta + "','" + pDepthMarketData.PreOpenInterest + "','" + pDepthMarketData.PreSettlementPrice + "','"
                                + pDepthMarketData.SettlementPrice + "','" + pDepthMarketData.TradingDay + "','" + pDepthMarketData.Turnover + "','"
                                + pDepthMarketData.UpdateMillisec + "','" + pDepthMarketData.UpdateTime + "','" + pDepthMarketData.UpperLimitPrice + "','" + pDepthMarketData.Volume + "')";
                            MemDB.setSQL(sSql);
                            MemDB.Execute();
                            bCommit = true;
                            Queue_SQLite.m_lRunNum++;
                            #endregion
                            break;
                        case EnumQueueType.OnRtnOrder:
                            break;
                        case EnumQueueType.StopSign0:
                            Queue_PolicySample.bUse = false;
                            return;
                        default:
                            break;
                    }
                }
                #endregion

            }
        }
예제 #33
0
        private void BuyOrSell(ThostFtdcDepthMarketDataField data)
        {
            try
            {
                #region 平仓策略

                if (Utils.InstrumentToStopLossPrices.ContainsKey(data.InstrumentID))
                {
                    var stopLossPrices = Utils.InstrumentToStopLossPrices[data.InstrumentID];

                    //var directions = MinuteAllDirection(data.InstrumentID);

                    //if (directions.Item1)//大趋势向上,平空仓
                    //{
                    //    _trader.CloseShortPositionByInstrument(data.InstrumentID, "大趋势向上,平掉空仓");
                    //}

                    //if (directions.Item2)//大趋势向下,平多仓
                    //{
                    //    _trader.CloseLongPositionByInstrument(data.InstrumentID, "大趋势向下,平掉多仓");
                    //}

                    var stopLossValue = data.LastPrice * Utils.SwingLimit * 2;

                    //多仓止损
                    if (data.LastPrice < stopLossPrices.CostLong - stopLossValue)
                    {
                        var reason = string.Format("{0}从多仓的成本价{1}跌到了绝对止损值{2}以下,即{3},平掉多仓", data.InstrumentID,
                                                   stopLossPrices.CostLong, stopLossValue, data.LastPrice);
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);
                    }

                    //空仓止损
                    if (data.LastPrice > stopLossPrices.CostShort + stopLossValue)
                    {
                        var reason = string.Format("{0}从空仓的成本价{1}涨到了绝对止损值{2}以上,即{3},平掉空仓", data.InstrumentID,
                                                   stopLossPrices.CostShort, stopLossValue, data.LastPrice);
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                    }

                    double openTrendStartPoint = 0;

                    //从多仓的最高盈利跌了一定幅度,平掉多仓,保护盈利,忽略掉小波动
                    if (stopLossPrices.CostLong > 0 && stopLossPrices.ForLong > stopLossPrices.CostLong &&
                        stopLossPrices.ForLong > data.LastPrice)
                    {
                        var keyLongPosition = Utils.GetOpenTrendStartPointKey(data.InstrumentID,
                                                                              EnumPosiDirectionType.Long);

                        if (Utils.InstrumentToOpenTrendStartPoint.ContainsKey(keyLongPosition))
                        {
                            openTrendStartPoint = Utils.InstrumentToOpenTrendStartPoint[keyLongPosition];
                        }

                        var highestDistance = Math.Abs(stopLossPrices.ForLong - stopLossPrices.CostLong);
                        var currentDistance = Math.Abs(data.LastPrice - stopLossPrices.CostLong);
                        var trendDistance   = Math.Abs(stopLossPrices.CostLong - openTrendStartPoint);

                        if (highestDistance > data.LastPrice * Utils.HighestDistanceConsiderLimit &&
                            highestDistance > currentDistance &&
                            currentDistance <= Utils.CurrentDistanceToHighestDistanceRatioLimit * highestDistance)
                        {
                            var reason = string.Format("{0}从多仓的最高趋势点{1}跌到了{2}以下,即{3},平掉多仓,多仓成本价{4},多仓最高盈利价{5}",
                                                       data.InstrumentID, highestDistance + trendDistance,
                                                       Utils.CurrentDistanceToHighestDistanceRatioLimit, currentDistance + trendDistance,
                                                       stopLossPrices.CostLong, stopLossPrices.ForLong);
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, "移动止损平多仓");
                        }

                        if (highestDistance > data.LastPrice * Utils.StopProfitRatio)
                        {
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, "多仓止盈");
                        }
                    }

                    //从空仓的最高盈利跌了一半,平掉空仓,保护盈利,忽略掉小波动
                    if (stopLossPrices.CostShort > 0 && stopLossPrices.ForShort < stopLossPrices.CostShort &&
                        stopLossPrices.ForShort < data.LastPrice)
                    {
                        var keyShortPosition = Utils.GetOpenTrendStartPointKey(data.InstrumentID,
                                                                               EnumPosiDirectionType.Short);

                        if (Utils.InstrumentToOpenTrendStartPoint.ContainsKey(keyShortPosition))
                        {
                            openTrendStartPoint = Utils.InstrumentToOpenTrendStartPoint[keyShortPosition];
                        }

                        var highestDistance = Math.Abs(stopLossPrices.ForShort - stopLossPrices.CostShort);
                        var currentDistance = Math.Abs(data.LastPrice - stopLossPrices.CostShort);
                        var trendDistance   = Math.Abs(openTrendStartPoint - stopLossPrices.CostShort);

                        if (highestDistance > data.LastPrice * Utils.HighestDistanceConsiderLimit &&
                            highestDistance > currentDistance &&
                            currentDistance <= Utils.CurrentDistanceToHighestDistanceRatioLimit * highestDistance)
                        {
                            var reason = string.Format("{0}从空仓的最低趋势点{1}涨到了{2}以上,即{3},平掉空仓,空仓成本价{4},空仓最高盈利价{5}",
                                                       data.InstrumentID, highestDistance + trendDistance,
                                                       Utils.CurrentDistanceToHighestDistanceRatioLimit,
                                                       currentDistance + trendDistance, stopLossPrices.CostShort, stopLossPrices.ForShort);
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, "移动止损平空仓");
                        }

                        if (highestDistance > data.LastPrice * Utils.StopProfitRatio)
                        {
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, "空仓止盈");
                        }
                    }
                }

                //接近涨停价,平掉空仓
                var upperLimitRange = (data.UpperLimitPrice + data.LowerLimitPrice) / 2;
                var lowerLimitRange = upperLimitRange;

                if (data.LastPrice > data.PreSettlementPrice + upperLimitRange * Utils.LimitCloseRange)
                {
                    var reason = string.Format("{0}最新价{1}上涨到了涨停价{2}的{3}以上,平掉空仓", data.InstrumentID, data.LastPrice,
                                               data.UpperLimitPrice, Utils.LimitCloseRange);
                    _trader.CloseShortPositionByInstrument(data.InstrumentID, reason);
                }

                //接近跌停价,平掉多仓
                if (data.LastPrice < data.PreSettlementPrice - lowerLimitRange * Utils.LimitCloseRange)
                {
                    var reason = string.Format("{0}最新价{1}下跌到了跌停价{2}的{3}以下,平掉多仓", data.InstrumentID, data.LastPrice,
                                               data.LowerLimitPrice, Utils.LimitCloseRange);
                    _trader.CloseLongPositionByInstrument(data.InstrumentID, reason);
                }

                #endregion

                #region 开仓策略

                if (Utils.InstrumentToMinuteByMinuteChart.ContainsKey(data.InstrumentID))
                {
                    OpenStrategy(data, false);
                }

                #endregion
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #34
0
 private void PolicySampleRUN(object s)
 {
     MainForm cMainForm = (MainForm)s;
     ThostFtdcInputOrderField sInputOrder = new ThostFtdcInputOrderField();
     ThostFtdcDepthMarketDataField pDepthMarketData = new ThostFtdcDepthMarketDataField();
     QueueSendData Data = new QueueSendData();
     while (Queue_PolicySample.bUse)
     {
         if (Queue_PolicySample.DataQ.Count == 0)
         {
             Queue_PolicySample.Are.WaitOne();
             Queue_PolicySample.Are.Reset();
         }
         else
         {
             Data = Queue_PolicySample.DataQ.Dequeue();
             #region 这里写策略
             switch (Data.QueueType)
             {
                 case EnumQueueType.DepthMarketData:
                     Queue_PolicySample.m_lReceiveNum++;
                     pDepthMarketData = (ThostFtdcDepthMarketDataField)Data.QueueData;
                     if (pDepthMarketData.InstrumentID == "IF1309")
                     {
                         Queue_PolicySample.m_lRunNum++;
                         Queue_PolicySample.add_log("插入报单!触发单:" + pDepthMarketData.InstrumentID + " \n时间:" + pDepthMarketData.UpdateTime);
                         // cMainForm.TDReqOrderInsert(sInputOrder);
                     }
                     else
                     {
                         Queue_PolicySample.m_lDropNum++;
                     }
                     break;
                 case EnumQueueType.OnRtnOrder:
                     break;
                 case EnumQueueType.StopSign0:
                     Queue_PolicySample.bUse = false;
                     return;
                 default:
                     break;
             }
             #endregion
         }
     }
     Queue_PolicySample.bUse = false;
 }
예제 #35
0
 ///请求查询行情响应
 public void OnRspQryDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData, ThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
 {
     if (!IsErrorRspInfo(pRspInfo))
     {
     }
 }
예제 #36
0
        private void MD_OnTick(ThostFtdcDepthMarketDataField md)
        {
            if (this.longOption.InstrumentID == md.InstrumentID || this.shortOption.InstrumentID == md.InstrumentID)
            {
                if(this.longOption.InstrumentID == md.InstrumentID)
                {
                    this.longOption.LastMarket = md;
                }
                else if(this.shortOption.InstrumentID == md.InstrumentID)
                {
                    this.shortOption.LastMarket = md;
                }
                if(this.longOption.LastMarket != null && this.shortOption.LastMarket != null && MainForm.Future.LastMarket != null)
                {
                    if(this.longOption.OptionType == OptionTypeEnum.call)
                    {
                        //反向套利
                        if (this.shortOption.LastMarket.BidPrice1 < 999999 && this.longOption.LastMarket.AskPrice1 < 999999 && MainForm.Future.LastMarket.BidPrice1 < 999999)
                        {
                            this.parityInterval = (this.shortOption.LastMarket.BidPrice1 - this.longOption.LastMarket.AskPrice1) + (MainForm.Future.LastMarket.BidPrice1 - this.longOption.StrikePrice);
                            //开仓逻辑
                        }
                        else
                        {
                            this.parityInterval = 0;
                        }
                    }
                    else if(this.longOption.OptionType == OptionTypeEnum.put)
                    {
                        //正向套利
                        if (this.shortOption.LastMarket.BidPrice1 < 999999 && this.longOption.LastMarket.AskPrice1 < 999999 && MainForm.Future.LastMarket.AskPrice1 < 999999)
                        {
                            this.parityInterval = (this.shortOption.LastMarket.BidPrice1 - this.longOption.LastMarket.AskPrice1) - (MainForm.Future.LastMarket.AskPrice1 - this.longOption.StrikePrice);
                            //开仓逻辑
                        }
                        else
                        {
                            this.parityInterval = 0;
                        }
                    }
                }

            }
        }
        //private Tuple<bool, bool> MinuteAllDirection(string instrumentId)
        //{
        //    if (Utils.InstrumentToMinuteByMinuteChart.ContainsKey(instrumentId))
        //    {
        //        var minuteByMinute = Utils.InstrumentToMinuteByMinuteChart[instrumentId];

        //        //当前大趋势,大趋势向上只开多仓,大趋势向下,只开空仓
        //        var minuteAllXData = new List<double>();
        //        var minuteAllYData = new List<double>();
        //        for (var i = 0; i < minuteByMinute.Count; i++)
        //        {
        //            if (minuteByMinute[i] != null)
        //            {
        //                minuteAllXData.Add(i);
        //                minuteAllYData.Add(minuteByMinute[i].Item2.LastPrice);
        //            }
        //        }

        //        var isPointingUpMinuteAll = MathUtils.IsPointingUp(minuteAllXData, minuteAllYData, 0.4);
        //        var isPointingDownMinuteAll = MathUtils.IsPointingDown(minuteAllXData, minuteAllYData, 0.4);

        //        return new Tuple<bool, bool>(isPointingUpMinuteAll.Item1, isPointingDownMinuteAll.Item1);
        //    }

        //    return new Tuple<bool, bool>(false, false);
        //}

        /// <summary>
        /// 新策略,比最低(最高)趋势点高于(低于)一定比例,开多(空)仓
        /// </summary>
        /// <param name="data"></param>
        /// <param name="ma"></param>
        private void OpenStrategy(ThostFtdcDepthMarketDataField data, bool ma)
        {
            try
            {
                var minuteByMinute = Utils.InstrumentToMinuteByMinuteChart[data.InstrumentID];

                if (minuteByMinute.Count >= Utils.MinuteByMinuteSizeLong)
                {
                    var sizeHalf = Utils.MinuteByMinuteSizeLong / 2;
                    var count    = minuteByMinute.Count;

                    var minuteByMinuteQuotesLong = new List <double>();
                    for (var i = count - Utils.MinuteByMinuteSizeLong; i < count; i++)
                    {
                        if (minuteByMinute[i] != null)
                        {
                            minuteByMinuteQuotesLong.Add(minuteByMinute[i].Item2.LastPrice);
                        }
                    }

                    var minuteByMinuteQuotesHalf = new List <double>();
                    for (var i = count - sizeHalf; i < count; i++)
                    {
                        if (minuteByMinute[i] != null)
                        {
                            minuteByMinuteQuotesHalf.Add(minuteByMinute[i].Item2.LastPrice);
                        }
                    }

                    var isPointingUpMinuteLong2 = MathUtils.IsPointingUp(Utils.MinuteLongXData,
                                                                         minuteByMinuteQuotesLong, MathUtils.Slope2);
                    var isPointingDownMinuteLong2 = MathUtils.IsPointingDown(Utils.MinuteLongXData,
                                                                             minuteByMinuteQuotesLong, MathUtils.Slope2);

                    Utils.WriteLine(string.Format("当前长角度{0}", isPointingUpMinuteLong2.Item3));
                    //Trader.SetOpenAngle(data.InstrumentID, EnumPosiDirectionType.Long, EnumDirectionType.Buy, isPointingUpMinuteLong2.Item3);
                    //Trader.SetOpenAngle(data.InstrumentID, EnumPosiDirectionType.Short, EnumDirectionType.Sell, isPointingDownMinuteLong2.Item3);

                    var minuteHalfXData = new List <double>();

                    for (var i = 0; i < sizeHalf; i++)
                    {
                        minuteHalfXData.Add(i);
                    }

                    var isPointingUpMinuteHalf = MathUtils.IsPointingUp(minuteHalfXData, minuteByMinuteQuotesHalf,
                                                                        MathUtils.Slope2);
                    var isPointingDownMinuteHalf = MathUtils.IsPointingDown(minuteHalfXData, minuteByMinuteQuotesHalf,
                                                                            MathUtils.Slope2);
                    Utils.WriteLine(string.Format("当前短角度{0}", isPointingUpMinuteHalf.Item3));

                    //开多仓
                    if (isPointingUpMinuteLong2.Item1 && isPointingUpMinuteHalf.Item1)
                    {
                        var min = minuteByMinuteQuotesLong.Min(p => p);
                        var keyMissedLongOpenTrendStartPoint = Utils.GetOpenPositionKey(data.InstrumentID,
                                                                                        EnumDirectionType.Buy);
                        if (Utils.InstrumentToMissedOpenTrendStartPoint.ContainsKey(keyMissedLongOpenTrendStartPoint))
                        {
                            min = Math.Min(min,
                                           Utils.InstrumentToMissedOpenTrendStartPoint[keyMissedLongOpenTrendStartPoint]);
                        }
                        else
                        {
                            Utils.SetMissedOpenStartPoint(data.InstrumentID, EnumPosiDirectionType.Long, min);
                        }

                        if (data.LastPrice > min + data.LastPrice * Utils.SwingLimit && data.LastPrice <= data.UpperLimitPrice * 0.99) //接近涨停价不开多仓,盈利空间太小
                        {
                            var reason = string.Format("{0}最近趋势向上{1},且高于多仓启动点{2},开出多仓,开仓启动点{3},开仓正切{4},开仓角度{5}",
                                                       data.InstrumentID,
                                                       isPointingUpMinuteLong2, data.LastPrice * Utils.SwingLimit, min,
                                                       isPointingUpMinuteLong2.Item2, isPointingUpMinuteLong2.Item3);

                            if (Utils.InstrumentToLastPosiDirectionType.ContainsKey(data.InstrumentID) &&
                                Utils.InstrumentToLastPosiDirectionType[data.InstrumentID] ==
                                EnumPosiDirectionType.Short)
                            {
                                Utils.WriteLine("反向强制开多仓", true);
                                _trader.OpenLongPositionByInstrument(data.InstrumentID, reason, min, true, true, isPointingUpMinuteLong2.Item3);
                            }
                            else
                            {
                                _trader.OpenLongPositionByInstrument(data.InstrumentID, reason, min, true, false, isPointingUpMinuteLong2.Item3);
                            }
                        }

                        return;
                    }


                    if (!isPointingUpMinuteHalf.Item1 && isPointingUpMinuteLong2.Item1)
                    {
                        Utils.WriteLine("虽然长趋势向上,但是中趋势不是,不开多仓", true);
                    }

                    //开空仓
                    if (isPointingDownMinuteLong2.Item1 && isPointingDownMinuteHalf.Item1)
                    {
                        var max = minuteByMinuteQuotesLong.Max(p => p);
                        var keyMissedShortOpenTrendStartPoint = Utils.GetOpenPositionKey(data.InstrumentID,
                                                                                         EnumDirectionType.Sell);
                        if (Utils.InstrumentToMissedOpenTrendStartPoint.ContainsKey(keyMissedShortOpenTrendStartPoint))
                        {
                            max = Math.Max(max,
                                           Utils.InstrumentToMissedOpenTrendStartPoint[keyMissedShortOpenTrendStartPoint]);
                        }
                        else
                        {
                            Utils.SetMissedOpenStartPoint(data.InstrumentID, EnumPosiDirectionType.Short, max);
                        }

                        if (data.LastPrice < max - data.LastPrice * Utils.SwingLimit && data.LastPrice >= data.LowerLimitPrice * 1.01) //接近跌停价不开空仓,盈利空间太小
                        {
                            var reason = string.Format("{0}最近长趋势向下{1},且低于空仓启动点{2},开出空仓,开仓启动点{3},开仓正切{4},开仓角度{5}",
                                                       data.InstrumentID,
                                                       isPointingDownMinuteLong2, data.LastPrice * Utils.SwingLimit, max,
                                                       isPointingDownMinuteLong2.Item2, isPointingDownMinuteLong2.Item3);


                            if (Utils.InstrumentToLastPosiDirectionType.ContainsKey(data.InstrumentID) &&
                                Utils.InstrumentToLastPosiDirectionType[data.InstrumentID] == EnumPosiDirectionType.Long)
                            {
                                Utils.WriteLine("反向强制开空仓", true);
                                _trader.OpenShortPositionByInstrument(data.InstrumentID, reason, max, true, true, isPointingDownMinuteLong2.Item3);
                            }
                            else
                            {
                                _trader.OpenShortPositionByInstrument(data.InstrumentID, reason, max, true, false, isPointingDownMinuteLong2.Item3);
                            }
                        }

                        return;
                    }

                    if (!isPointingDownMinuteHalf.Item1 && isPointingDownMinuteLong2.Item1)
                    {
                        Utils.WriteLine("虽然长趋势向下,但是中趋势不是,不开空仓", true);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #38
0
파일: MdAdapter.cs 프로젝트: botvs/QTS
 public override void OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
 {
     this.marketDataFieldQueue.Enqueue(pDepthMarketData);
 }
예제 #39
0
파일: MdAdapter.cs 프로젝트: damoye/QTS
 public override void OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
 {
     marketDataFieldQueue.Enqueue(pDepthMarketData);
 }
예제 #40
0
 /// <summary>
 /// 深度行情通知
 /// </summary>
 /// <param name="pDepthMarketData"></param>
 void OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
 {
     string s = string.Format("{0,-6} : UpdateTime = {1}.{2:D3},  LasPrice = {3}", pDepthMarketData.InstrumentID, pDepthMarketData.UpdateTime, pDepthMarketData.UpdateMillisec, pDepthMarketData.LastPrice);
     Debug.WriteLine(s);
     Console.WriteLine(s);
 }
예제 #41
0
 /// <summary>
 /// 查询行情应答
 /// </summary>
 /// <param name="pDepthMarketData"></param>
 /// <param name="pRspInfo"></param>
 /// <param name="nRequestID"></param>
 /// <param name="bIsLast"></param>
 void OnRspQryDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData, ThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
 {
     DebugPrintFunc(new StackTrace());
     if (bIsLast && !IsErrorRspInfo(pRspInfo))
     {
         //请求查询客户通知
         ReqQryNotice();
     }
 }
예제 #42
0
        void _market_OnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData)
        {
            if (pDepthMarketData == null)
            {
                return;
            }

            var market = new Market
            {
                InstrumentID = pDepthMarketData.InstrumentID,
                PrevClose    = pDepthMarketData.PreClosePrice,
                LastPrice    = pDepthMarketData.LastPrice
            };

            var asks = new List <Quote>
            {
                new Quote {
                    Price = pDepthMarketData.AskPrice1, Qty = pDepthMarketData.AskVolume1
                },
                new Quote {
                    Price = pDepthMarketData.AskPrice2, Qty = pDepthMarketData.AskVolume2
                },
                new Quote {
                    Price = pDepthMarketData.AskPrice3, Qty = pDepthMarketData.AskVolume3
                },
                new Quote {
                    Price = pDepthMarketData.AskPrice4, Qty = pDepthMarketData.AskVolume4
                },
                new Quote {
                    Price = pDepthMarketData.AskPrice5, Qty = pDepthMarketData.AskVolume5
                }
            };
            var bids = new List <Quote>
            {
                new Quote {
                    Price = pDepthMarketData.BidPrice1, Qty = pDepthMarketData.BidVolume1
                },
                new Quote {
                    Price = pDepthMarketData.BidPrice2, Qty = pDepthMarketData.BidVolume2
                },
                new Quote {
                    Price = pDepthMarketData.BidPrice3, Qty = pDepthMarketData.BidVolume3
                },
                new Quote {
                    Price = pDepthMarketData.BidPrice4, Qty = pDepthMarketData.BidVolume4
                },
                new Quote {
                    Price = pDepthMarketData.BidPrice5, Qty = pDepthMarketData.BidVolume5
                }
            };

            market.SetAsks(asks.Where(_ => _.Qty > 0));
            market.SetBids(bids.Where(_ => _.Qty > 0));
            this._markets[market.InstrumentID] = market;

            if (!this._initialized && this._markets.Count() == this.Instruments.Count())
            {
                this._initialized = true;
                this._asyncWaiter.Set();
            }
        }
        private void BuyOrSell(ThostFtdcDepthMarketDataField data)
        {
            try
            {
                if (Utils.InstrumentToStopLossPrices.ContainsKey(data.InstrumentID))
                {
                    var stopLossPrices = Utils.InstrumentToStopLossPrices[data.InstrumentID];

                    var stopLossValue = Utils.绝对止损点数;

                    //多仓止损
                    if (data.LastPrice < stopLossPrices.CostLong - stopLossValue)
                    {
                        var reason = string.Format("{0}从多仓的成本价{1}跌到了绝对止损值{2}以下,即{3},平掉多仓", data.InstrumentID,
                                                   stopLossPrices.CostLong, stopLossValue, data.LastPrice);
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, reason, false, 0);
                    }

                    //空仓止损
                    if (data.LastPrice > stopLossPrices.CostShort + stopLossValue)
                    {
                        var reason = string.Format("{0}从空仓的成本价{1}涨到了绝对止损值{2}以上,即{3},平掉空仓", data.InstrumentID,
                                                   stopLossPrices.CostShort, stopLossValue, data.LastPrice);
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, reason, false, 99999);
                    }

                    var longDistance               = stopLossPrices.ForLong - stopLossPrices.CostLong;
                    var currentLongDistance        = data.LastPrice - stopLossPrices.CostLong;
                    var movingStopLossValueForLong = longDistance * 0.5;

                    //多仓止损
                    if (longDistance > 10 && longDistance <= 20 && data.LastPrice < stopLossPrices.ForLong - movingStopLossValueForLong)
                    {
                        var reason = string.Format("{0}从多仓的最高盈利价{1}跌到了移动止损价{2}以下,即{3},平掉多仓", data.InstrumentID,
                                                   stopLossPrices.ForLong, stopLossPrices.ForLong - movingStopLossValueForLong, data.LastPrice);
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, reason, false, 0);
                    }
                    else
                    {
                        if (longDistance > 20 && currentLongDistance < 10)
                        {
                            _trader.CloseLongPositionByInstrument(data.InstrumentID, "移动止损,平掉多仓", false, 0);
                        }
                    }

                    var shortDistance               = stopLossPrices.CostShort - stopLossPrices.ForShort;
                    var currentShortDistance        = stopLossPrices.CostShort - data.LastPrice;
                    var movingStopLossValueForShort = shortDistance * 0.5;

                    //空仓止损
                    if (shortDistance > 10 && shortDistance <= 20 && data.LastPrice > stopLossPrices.ForShort + movingStopLossValueForShort)
                    {
                        var reason = string.Format("{0}从空仓的最高盈利价{1}涨到了移动止损价{2}以上,即{3},平掉空仓", data.InstrumentID,
                                                   stopLossPrices.ForShort, stopLossPrices.ForShort + movingStopLossValueForShort, data.LastPrice);
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, reason, false, 99999);
                    }
                    else
                    {
                        if (shortDistance > 20 && currentShortDistance < 10)
                        {
                            _trader.CloseShortPositionByInstrument(data.InstrumentID, "移动止损,平掉空仓", false, 99999);
                        }
                    }

                    if (stopLossPrices.ForLong - stopLossPrices.CostLong >= 20)
                    {
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, "多仓止盈", false, 0);
                    }

                    if (stopLossPrices.CostShort - stopLossPrices.ForShort >= 20)
                    {
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, "空仓止盈", false, 99999);
                    }

                    var stop = Utils.立即平仓点数;

                    if (data.LastPrice - stopLossPrices.CostLong >= stop)
                    {
                        _trader.CloseLongPositionByInstrument(data.InstrumentID, "立即平多仓", false, stopLossPrices.CostLong + Utils.立即平仓点数);
                    }

                    if (stopLossPrices.CostShort - data.LastPrice >= stop)
                    {
                        _trader.CloseShortPositionByInstrument(data.InstrumentID, "立即平空仓", false, stopLossPrices.CostShort - Utils.立即平仓点数);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
        }
예제 #44
0
파일: Form1.cs 프로젝트: caonimagfw/VSCTP
        void DataApi_OnRtnEvent(object sender, OnRtnEventArgs e)
        {
            //Console.WriteLine("DataApi_OnRtnEvent " + e.EventType.ToString());

            var fld = Conv.P2S <ThostFtdcDepthMarketDataField>(e.Param);



            //string sData = "当前交易日:{0} 当前时间:{1}  最后修改时间:{2} 成交量:{3} 卖1价格:{4} 卖1数量:{5} 买1价格:{6} 买1数量:{7} 本次结算价:{8} 成交数量:{9} ";
            //sData = string.Format(sData, fld.TradingDay, fld.UpdateTime, fld.UpdateMillisec, vol, fld.AskPrice1, fld.AskVolume1, fld.BidPrice1, fld.BidVolume1, fld.SettlementPrice, fld.Volume);



            int    vol   = fld.Volume - lastData.Volume;
            string sLose = "";

            if (lastData.ActionDay == null)
            {
                lastData = fld;
                return;
            }
            //Console.WriteLine("{0}.{1:D3} {2} {3}", fld.UpdateTime, fld.UpdateMillisec, fld.InstrumentID, fld.LastPrice);
            //if (vol > 0)
            //{
            //双开 空换 多换 空平 多平
            string sData2 = "当前交易日:{0} 当前时间:{1} 当前价格:{2} 成交:{3} {4}";

            //多开
            double       douLose;
            ConsoleColor tColor = ConsoleColor.White;

            int intDirect = 0;

            if (fld.LastPrice > lastData.AskPrice1 || fld.LastPrice > lastData.BidPrice1)
            {
                intDirect = 1;
                tColor    = ConsoleColor.Red;
            }
            else if (fld.LastPrice < lastData.AskPrice1 || fld.LastPrice < lastData.BidPrice1)
            {
                intDirect = -1;
                tColor    = ConsoleColor.Green;
            }
            else
            {
                tColor = ConsoleColor.White;
            }
            if (vol > 0)
            {
                Console.ForegroundColor = tColor;
                //Console.WriteLine(vol);
            }

            //else {
            //    if (fld.LastPrice > fld.AskPrice1)
            //    {
            //        intDirect = 1;
            //    }
            //    else if (fld.LastPrice < fld.BidPrice1)
            //    {
            //        intDirect = -1;
            //    }
            //    else {
            //        intDirect = 0; //middle
            //    }
            //}
            double xx = 0; double yy = 0;

            if (intDirect == 1)
            {
                //仓位变化

                /*
                 *
                 * 16 16 双开 - 成交:16  空平:16 多开:0 多平:16 空开:0
                 * 14 -10 空平 - 成交:14  空平:-12 多开:2 多平:-12 空开:2
                 * 8 0 多换 成交:8  空平:-4 多开:4 多平:-4 空开:4
                 *
                 * */
                douLose = fld.OpenInterest - lastData.OpenInterest;
                #region  涨
                //1.多开 多平 空开  空平

                if (douLose != 0)
                {
                    calCtp(vol, douLose, ref xx, ref yy);
                }
                else
                {
                    xx = vol;
                    yy = vol;
                }


                sLose += " 空平:" + xx;
                sLose += " 多开:" + yy;

                #endregion
            }
            if (intDirect == -1)
            {
                /*
                 * 46  -14 多平
                 * 10 0 空换
                 * 2 -2 双平
                 */
                #region  跌
                douLose = fld.OpenInterest - lastData.OpenInterest;

                if (douLose != 0)
                {
                    calCtp(vol, douLose, ref xx, ref yy);
                }
                else
                {
                    xx = vol;
                    yy = vol;
                }



                sLose += " 多平:" + xx;
                sLose += " 空开:" + yy;
                #endregion
            }

            if (vol > 0)
            {
                Console.WriteLine(string.Format(sData2,
                                                fld.TradingDay, fld.UpdateTime, fld.LastPrice,
                                                vol, sLose)
                                  );
            }


            //if (fld.OpenInterest < lastData.OpenInterest)
            //{

            //    sLose = " 平仓: " + (fld.OpenInterest - lastData.OpenInterest );
            //}
            //else if (fld.OpenInterest == lastData.OpenInterest)
            //{

            //    sLose = " 换手: " + (lastData.Volume - fld.Volume);
            //}
            //else
            //{
            //    sLose = " 增仓: " + (lastData.Volume - fld.Volume);
            //}
            //if ( vol > 0 )
            //Console.WriteLine(string.Format(sData2,
            //            fld.TradingDay, fld.UpdateTime, fld.LastPrice,
            //            vol, sLose)

            //        );
            //}
            lastData     = fld;
            douLastPrice = fld.LastPrice;
        }
 private void BuyOrSell(ThostFtdcDepthMarketDataField data)
 {
 }