Пример #1
0
        /// <summary>
        /// 把 count 个 Bar 合并成一个新的 Bar
        /// </summary>
        /// <param name="series"></param>
        /// <param name="inst"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static BarSeries MergeCompress(this BarSeries series, Instrument inst, long count)
        {
            if (series.Count == 0 || count < 2)
            {
                return(new BarSeries());
            }
            var  selector    = new TimeRangeSelector(inst);
            bool emitOnClose = !(series[0].Size >= QuantBoxConst.DayBarSize);

            var bars  = new BarSeries();
            Bar last  = null;
            var index = 0;

            foreach (var bar in series)
            {
                var range = selector.Get(bar.DateTime.Date);
                if (index == 0)
                {
                    last       = bar;
                    last.Size *= count;
                }
                else
                {
                    QBHelper.MergeBar(last, bar);
                }
                ++index;
                if (index == count || (emitOnClose && bar.CloseDateTime.TimeOfDay == range.CloseTime))
                {
                    bars.Add(last);
                    last  = null;
                    index = 0;
                }
            }
            return(bars);
        }
Пример #2
0
        public Instrument GetInstument(InstrumentField field)
        {
            var inst = new Instrument((InstrumentType)field.Type, field.Symbol);

            inst.AltId.Add(new AltId(_provider.Id, field.InstrumentID, field.ExchangeID));
            inst.PutCall     = (PutCall)field.OptionsType;
            inst.Strike      = field.StrikePrice;
            inst.Exchange    = field.ExchangeID;
            inst.CurrencyId  = CurrencyId.CNY;
            inst.TickSize    = field.PriceTick;
            inst.Factor      = field.VolumeMultiple;
            inst.PriceFormat = "F" + QBHelper.GetPrecision(field.PriceTick);
            inst.Maturity    = field.ExpireDate();
            if (!string.IsNullOrEmpty(field.UnderlyingInstrID) &&
                field.UnderlyingInstrID != field.ProductID &&
                !field.InstrumentID.EndsWith("efp"))
            {
                var underlying = _provider.InstrumentManager.Get(field.UnderlyingInstrID);
                if (underlying == null)
                {
                    //_provider.Logger.Warn($"没有找到合约标的物{field.UnderlyingInstrID},请先导入合约标的物");
                }
                else
                {
                    OpenQuant.Helper.AddLeg(inst, new Leg(underlying));
                }
            }
            return(inst);
        }
Пример #3
0
        protected override XProviderSettings LoadSettings()
        {
            var defaultSettings = new XProviderSettings {
                Id              = 61,
                Name            = ProviderName,
                Url             = "www.thanf.com",
                Description     = "QuantBox CTP 插件",
                UserProductInfo = "OpenQuant",
                Connections     = new List <ConnectionInfo>(),
                Users           = new List <UserInfo>(),
                Servers         = new List <ServerInfo>(),
            };

            var settings = XProviderSettings.Load(QBHelper.GetConfigPath(GetSettingsFileName()));

            if (settings == null)
            {
                settings = defaultSettings;
            }
            else
            {
                settings.Id          = defaultSettings.Id;
                settings.Url         = defaultSettings.Url;
                settings.Description = defaultSettings.Description;
                settings.Name        = ProviderName;
            }
            return(settings);
        }
Пример #4
0
        public static ServerInfo Load(JToken token)
        {
            var server = new ServerInfo();

            QBHelper.LoadFromJson(server, typeof(ServerInfo), token);
            return(server);
        }
Пример #5
0
        public static UserInfo Load(JToken token)
        {
            var user = new UserInfo();

            QBHelper.LoadFromJson(user, typeof(UserInfo), token);
            return(user);
        }
Пример #6
0
        protected override XProviderSettings LoadSettings()
        {
            var defaultSettings = new XProviderSettings {
                Id              = QuantBoxConst.PIdCtp,
                Name            = ProviderName,
                Url             = "www.quntbox.cn",
                Description     = "QuantBox Ctpse 插件",
                UserProductInfo = "OpenQuant",
                Connections     = new List <ConnectionInfo>(),
                Users           = new List <UserInfo>(),
                Servers         = new List <ServerInfo>(),
            };

            var settings = XProviderSettings.Load(QBHelper.GetConfigPath(base.GetSettingsFileName()));

            if (settings == null)
            {
                settings = defaultSettings;
            }
            else
            {
                settings.Id          = defaultSettings.Id;
                settings.Url         = defaultSettings.Url;
                settings.Description = defaultSettings.Description;
                settings.Name        = ProviderName;
            }
            return(IsThanfVersion() ? MergeSettings(settings) : settings);
        }
Пример #7
0
        private void LoadCalendar()
        {
            try {
                var file = GetCalendarDataFile();
                if (File.Exists(file))
                {
                    var list      = JToken.Parse(QBHelper.ReadOnlyAllText(file));
                    var firstDate = ParseDateTime(list.First);
                    var days      = new TradingDayList(firstDate.AddDays(-firstDate.DayOfYear + 1), CalendarEnd);
                    var current   = list.First;
                    while (current != null)
                    {
                        var date = ParseDateTime(current);
                        days[date] = true;
                        current    = current.Next;
                    }
                    days.SetHoliday();
                    DayList = days;
                }
            }
            catch (Exception e) {
                Logger.Warn($@"LoadCalendar [{e}]");
            }

            DateTime ParseDateTime(JToken current)
            {
                return(DateTime.ParseExact((string)current, "yyyyMMdd", null));
            }
        }
Пример #8
0
        protected internal virtual string GetApiPath(string path)
        {
            var dllPath = QBHelper.MakeAbsolutePath(path, Installation.ConfigDir.FullName);

            if (!File.Exists(dllPath))
            {
                dllPath = QBHelper.MakeAbsolutePath(path);
            }
            return(dllPath);
        }
        private static List <T> LoadItems <T>(string path, string name)
        {
            var file = Path.Combine(Path.GetDirectoryName(path), $"{Path.GetFileNameWithoutExtension(path)}.{name}.json");

            if (File.Exists(file))
            {
                return(JsonConvert.DeserializeObject <List <T> >(QBHelper.ReadOnlyAllText(file)));
            }
            return(new List <T>());
        }
Пример #10
0
        public static OrderAgentInfo Load()
        {
            var settingsFile = GetSettingsFile();

            if (File.Exists(settingsFile))
            {
                return(JsonConvert.DeserializeObject <OrderAgentInfo>(QBHelper.ReadOnlyAllText(settingsFile)));
            }
            return(new OrderAgentInfo());
        }
 public static XProviderSettings Load(string path)
 {
     if (File.Exists(path))
     {
         var settings = JsonConvert.DeserializeObject <XProviderSettings>(QBHelper.ReadOnlyAllText(path));
         settings.Users        = LoadItems <UserInfo>(path, nameof(Users));
         settings.Servers      = LoadItems <ServerInfo>(path, nameof(Servers));
         settings.Connections  = LoadItems <ConnectionInfo>(path, nameof(Connections));
         settings.SessionTimes = LoadItems <TimeRange>(path, nameof(SessionTimes));
         return(settings);
     }
     return(null);
 }
Пример #12
0
 private void LoadTimeRange()
 {
     try {
         var file = GetTimeRangeDataFile();
         if (File.Exists(file))
         {
             var manager = new TradingTimeManager();
             manager.Load(JsonConvert.DeserializeObject <string[][]>(QBHelper.ReadOnlyAllText(file)));
             TimeManager = manager;
         }
     }
     catch (Exception e) {
         Logger.Warn($@"LoadTimeRange [{e}]");
     }
 }
Пример #13
0
 private void SendInstrumentDefinition(InstrumentDefinitionRequest request, Instrument[] insts)
 {
     try {
         var data       = QBHelper.FilterInstrument(request, insts);
         var definition = new InstrumentDefinition();
         definition.Instruments = data;
         definition.ProviderId  = Id;
         definition.RequestId   = request.Id;
         definition.TotalNum    = data.Length;
         EmitInstrumentDefinition(definition);
         EmitInstrumentDefinitionEnd(request.Id, RequestResult.Completed, string.Empty);
     }
     catch (Exception ex) {
         CancelInstrumentRequest(request, ex.Message);
     }
 }
        private void LoadTimeRange(string file = null)
        {
            file = file ?? GetTimeRangeDataFile();
            if (!File.Exists(file))
            {
                return;
            }
            var content = QBHelper.ReadOnlyAllText(file);

            try {
                var manager = new TradingTimeManager();
                manager.Load(JsonConvert.DeserializeObject <string[][]>(content));
                TimeManager = manager;
            }
            catch (Exception e) {
                Logger.Warn($"LoadTimeRange [{e.Message}]");
            }
        }
Пример #15
0
        /// <summary>
        /// 把 count 个 Bar 合并成一个新的 Bar
        /// </summary>
        /// <param name="series"></param>
        /// <param name="inst"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static BarSeries MergeCompress(this BarSeries series, Instrument inst, long count)
        {
            if (series.Count == 0 || count < 2)
            {
                return(new BarSeries());
            }
            var selector    = new TimeRangeSelector(inst);
            var emitOnClose = true;
            var bar         = series[0];

            if (bar.Size >= QuantBoxConst.DayBarSize)
            {
                emitOnClose = false;
            }

            var bars  = new BarSeries();
            Bar last  = null;
            var index = 0;

            for (int i = 0; i < series.Count; i++)
            {
                var range = selector.Get(series[i].DateTime.Date);
                if (index == 0)
                {
                    last       = series[i];
                    last.Size *= count;
                }
                else
                {
                    QBHelper.MergeBar(last, series[i]);
                }
                ++index;
                if (index == count || (emitOnClose && series[i].CloseDateTime.TimeOfDay == range.CloseTime))
                {
                    bars.Add(last);
                    last  = null;
                    index = 0;
                    continue;
                }
            }
            return(bars);
        }
Пример #16
0
        public void ProcessMarketData(DepthMarketDataField field)
        {
            if (field == null)
            {
                return;
            }

            if (_provider.EnableMarketLog)
            {
                //_provider.Logger.Debug($"{field.InstrumentID},{field.UpdateTime},{field.Bids[0].Price},{field.Bids[0].Size},{field.Asks[0].Price},{field.Asks[0].Size},{field.LastPrice},{field.Volume}.");
                _provider.Logger.Debug($"{field.InstrumentID},{field.UpdateTime},{field.LastPrice},{field.Volume}.");
            }

            _instDictCache.TryGetValue(field.InstrumentID, out var inst);
            if (inst == null)
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.Logger.Debug($"unsubscribed tick: {field.InstrumentID}.");
                }
                return;
            }

            var instId       = inst.Id;
            var localTime    = DateTime.Now;
            var exchangeTime = field.ExchangeDateTime();

            if (exchangeTime.Year == DateTime.MaxValue.Year)
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.Logger.Debug($"empty trading time, {field.InstrumentID}");
                }
                exchangeTime = localTime;
            }
            else
            {
                if (_provider.NightTradingTimeCorrection)
                {
                    exchangeTime = QBHelper.CorrectionActionDay(localTime, exchangeTime);
                }
            }

            var time = exchangeTime.TimeOfDay;

            if (_provider.MaxTimeDiffExchangeLocal > 0)
            {
                var diff = Math.Abs((localTime.TimeOfDay - time).TotalMinutes);
                if (diff > _provider.MaxTimeDiffExchangeLocal)
                {
                    if (_provider.EnableMarketLog)
                    {
                        _provider.Logger.Debug($"time diff ={diff},{field.InstrumentID}");
                    }
                    return;
                }
            }

            var range = _timeRanges[instId];

            if (!_instOpenFlag[instId])
            {
                if (range.InRange(time))
                {
                    if (_instCloseFlag[instId] && range.IsClose(time))
                    {
                        if (_provider.EnableMarketLog)
                        {
                            _provider.Logger.Debug($"already closed, {field.InstrumentID}.");
                        }
                        return;
                    }
                    inst.SetMarketData(field);
                    _instOpenFlag[instId]  = true;
                    _instCloseFlag[instId] = false;
                    if (_provider.EnableMarketLog)
                    {
                        _provider.Logger.Debug($"market open, {field.InstrumentID}.");
                    }
                }
                else
                {
                    if (_provider.EnableMarketLog)
                    {
                        _provider.Logger.Debug($"market no open, {field.InstrumentID}.");
                    }
                    return;
                }
            }

            var last = _marketData[instId];

            if (range.IsClose(time) && field.ClosePrice > 0)
            {
                inst.SetMarketData(field);
                _instCloseFlag[instId] = true;
                _instOpenFlag[instId]  = false;
                _marketData[instId]    = EmptyMarketData;
                if (_provider.EnableMarketLog)
                {
                    _provider.Logger.Debug($"market close, {field.InstrumentID}.");
                }
            }
            else
            {
                if (_czceInstFlag[inst.Id])
                {
                    field.ClosePrice = 0;
                }
                _marketData[instId] = field;
            }

            if (field.Asks?.Length > 0 && field.Asks[0].Size > 0)
            {
#if Compatibility
                var ask = OpenQuant.Helper.NewTick <Ask>(localTime, exchangeTime, _provider.Id, instId, field.Asks[0].Price, field.Asks[0].Size);
#else
                var ask = new Ask(localTime, exchangeTime, _provider.Id, instId, field.Asks[0].Price, field.Asks[0].Size);
#endif
                _provider.ProcessMarketData(ask);
            }
            if (field.Bids?.Length > 0 && field.Bids[0].Size > 0)
            {
#if Compatibility
                var bid = OpenQuant.Helper.NewTick <Bid>(localTime, exchangeTime, _provider.Id, instId, field.Bids[0].Price, field.Bids[0].Size);
#else
                var bid = new Bid(localTime, exchangeTime, _provider.Id, instId, field.Bids[0].Price, field.Bids[0].Size);
#endif

                _provider.ProcessMarketData(bid);
            }

            if (!(field.LastPrice > double.Epsilon))
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.Logger.Debug($"empty price, {field.InstrumentID}.");
                }
                return;
            }

            var size = _provider.VolumeIsAccumulated ? field.Volume - last.Volume : field.Volume;
            if (_provider.DiscardEmptyTrade &&
                _provider.VolumeIsAccumulated &&
                Math.Abs(size) < double.Epsilon &&
                _instOpenFlag[instId])
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.Logger.Debug($"empty trade, {field.InstrumentID}.");
                }
                return;
            }
#if Compatibility
            var trade = OpenQuant.Helper.NewTick <Trade>(localTime, exchangeTime, _provider.Id, instId, field.LastPrice, size);
#else
            var trade = new Trade(localTime, exchangeTime, _provider.Id, instId, field.LastPrice, (int)size);
#endif
            var turnover = double.NaN;
            if (_provider.VolumeIsAccumulated)
            {
                if (field.Turnover > last.Turnover)
                {
                    turnover = field.Turnover - last.Turnover;
                }
                else
                {
                    turnover = (field.Turnover / field.Volume) * size;
                }
            }
            else
            {
                turnover = field.Turnover;
            }
            if (!_czceInstFlag[instId])
            {
                turnover /= inst.Factor;
            }
            trade.SetMarketData(field);
            trade.SetMarketData(turnover, field.OpenInterest);
            _provider.ProcessMarketData(trade);
        }
Пример #17
0
 private static string GetSettingsFile()
 {
     return(QBHelper.GetConfigPath("orderagent"));
 }
Пример #18
0
 protected internal virtual void SaveSettings()
 {
     Settings?.Save(QBHelper.GetConfigPath(GetSettingsFileName()));
 }
Пример #19
0
 static XProvider()
 {
     QBHelper.InitNLog();
     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
 }
Пример #20
0
 static XProvider()
 {
     QBHelper.InitNLog();
     AssemblyResolver.AddPath(QBHelper.BasePath);
 }