Example #1
0
        public static string GetKLineDBTableName(KLineType kLineType, bool isComposite)
        {
            const string kLineDay    = "KLineDay",
                         kLineDayZS  = "KLineDayZS",
                         kLineWeek   = "KLineWeek",
                         kLineMonth  = "KLineMonth",
                         kLineMinute = "KLineMinute";

            switch (kLineType)
            {
            case KLineType.Day:
                return(isComposite ? kLineDayZS : kLineDay);

            case KLineType.Week:
                return(kLineWeek);

            case KLineType.Month:
                return(kLineMonth);

            case KLineType.Minute:
                return(kLineMinute);

            default:
                throw new ArgumentOutOfRangeException("kLineType");
            }
        }
Example #2
0
        public void Delete(KLineType type, string stockCode, IEnumerable<IStockKLine> kLines)
        {
            ThrowIfTypeNotSupport(type);

            if (type == KLineType.Day)
            {
                string dbFilePath = new Day1KLineFile(stockCode).GetFilePath();
                KLineRepository repository = new KLineRepository(dbFilePath);
                repository.DeleteRange(kLines);
            }
            else
            {
                Year1KLineFile file = null;
                if (type == KLineType.Min1)
                {
                    file = new Min1KLineFile(stockCode);
                }
                else
                {
                    file = new Min5KLineFile(stockCode);
                }
                var packages = file.SplitToPackages(kLines);

                // 插入所有数据
                foreach (var package in packages)
                {
                    // 获取数据文件路径
                    string dbFilePath = file.GetFilePath(package);

                    KLineRepository repository = new KLineRepository(dbFilePath);
                    repository.DeleteRange(package.Items);
                }
            }
        }
Example #3
0
        /// <summary>
        /// 当新数据到来的时候,调用此方法
        /// </summary>
        /// <param name="kLineType"></param>
        public void OnKLineComing(KLineType kLineType)
        {
            // 未登陆和没有飞船,都无法处理新数据
            if (!_logined || _battleship == null) return;

            Decide(kLineType);
        }
 public void Add(string stockCode, KLineType kLineType, IStockKLine data)
 {
     using (var file = StockKLineFile.CreateOrOpen(stockCode, kLineType, data.Time))
     {
         StockKLineDataItem dataItem = data.Convert();
         file.Add(dataItem);
     }
 }
Example #5
0
        /// <summary>
        /// 添加新的数据
        /// </summary>
        /// <param name="type"></param>
        /// <param name="kLine"></param>
        public void AddNewData(KLineType type, IStockKLine kLine)
        {
            if(!_history.ContainsKey(type))
            {
                _history.Add(type, new List<IStockKLine>());
            }

            _history[type].Add(kLine);
        }
Example #6
0
        public void TruncateStkKLine(KLineType kLineType)
        {
            if (kLineType == KLineType.Day)
            {
                throw new ArgumentException("KLineDay need specify parm:isComposite");
            }

            this.TruncateStkKLine(kLineType, false);
        }
Example #7
0
 /// <summary>
 /// 转换为其他类型的K线
 /// </summary>
 /// <param name="self"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public static IEnumerable<IStockKLine> ConvertTo(
     this IEnumerable<IStockKLine> self, 
     KLineType type)
 {
     switch(type)
     {
         case KLineType.Min5:
             return Min1ToMin5(self);
         default:
             throw new NotSupportedException();
     }
 }
Example #8
0
 /// <summary>
 /// 判断数据是否已经存在
 /// </summary>
 /// <param name="type"></param>
 /// <param name="kLine"></param>
 /// <returns></returns>
 public bool ExistData(KLineType type, IStockKLine kLine)
 {
     if (_history.ContainsKey(type)
         && _history[type].Contains(kLine))
     {
         return true;
     }
     else
     {
         return false;
     }
 }
Example #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_pair"></param>
        /// <param name="_type"></param>
        /// <param name="_values">0:limit 1:start</param>
        /// <returns></returns>
        public override KLine[] GetKLines(string _pair, KLineType _type, params string[] _values)
        {
            string _typeText = "";

            switch (_type)
            {
            case KLineType.M1: _typeText = "1m"; break;

            case KLineType.M5: _typeText = "5m"; break;

            case KLineType.H1: _typeText = "h"; break;

            case KLineType.D1: _typeText = "1d"; break;

            default: throw new Exception($"KLine type:{_type.ToString()} not supported.");
            }

            string _url = $"/api/v1/trade/bucketed?binSize={_typeText}&partial=true&symbol={_pair}&count={_values[0]}&reverse=true";

            if (_values.Length > 1)
            {
                _url += $"&start={_values[1]}";
            }

            JToken _token = base.HttpCall(HttpCallMethod.Get, "GET", _url);

            if (_token == null)
            {
                return(null);
            }

            IList <KLine> _result = new List <KLine>();
            JArray        _trades = _token.Value <JArray>();

            foreach (JToken _item in _trades)
            {
                KLine _line = new KLine();
                _line.DateTime = _item["timestamp"].Value <DateTime>();
                _line.Pair     = _pair;
                _line.Open     = _item["open"].Value <decimal>();
                _line.Close    = _item["close"].Value <decimal>();
                _line.High     = _item["high"].Value <decimal>();
                _line.Low      = _item["low"].Value <decimal>();
                _line.Volume   = _item["volume"].Value <decimal>();
                _line.Volume2  = _item["homeNotional"].Value <decimal>();
                _line.Count    = _item["trades"].Value <decimal>();

                _result.Add(_line);
            }

            return(_result.ToArray());
        }
Example #10
0
 internal void AddDatas(KLineType type, IEnumerable<IStockKLine> kLines)
 {
     var datas = kLines.ToList();
     if (_history.ContainsKey(type))
     {
         // 将数据补充进去
         var existData = _history[type];
         var needAddData = datas.Except(existData);
         _history[type].AddRange(needAddData);
     }
     else
     {
         _history.Add(type, datas);
     }
 }
        public IStockKLine GetData(string stockCode, KLineType kLineType, DateTime dt)
        {
            string filepath = PathHelper.GetKLineDataFilePath(stockCode, kLineType, dt);

            if (File.Exists(filepath))
            {
                var file = new StockKLineFile(filepath);
                var lstAll = file.ReadAll();
                var lstQuery = lstAll.Where(x => x.Time == dt).ToList();
                if (lstQuery != null && lstQuery.Count > 0)
                    return lstQuery.First();
            }

            return null;
        }
Example #12
0
        public override KLine[] GetKLines(string _pair, KLineType _type, params string[] _values)
        {
            string _typeText = "";

            switch (_type)
            {
            case KLineType.M1: _typeText = "1"; break;

            case KLineType.H1: _typeText = "60"; break;

            case KLineType.D1: _typeText = "D"; break;

            default: throw new Exception($"KLine type:{_type.ToString()} not supported.");
            }

            string _url = $"/GET/v1/api/kline?pair={_pair}&type={_typeText}";

            if (_values.Length > 0)
            {
                _url += $"&count={_values[0]}";
            }

            JToken _token = base.HttpCall(HttpCallMethod.Get, "GET", _url);

            if (_token == null)
            {
                return(null);
            }

            IList <KLine> _result = new List <KLine>();
            JArray        _trades = _token.Value <JArray>();

            foreach (JToken _item in _trades)
            {
                KLine _line = new KLine();
                _line.DateTime = DateTimePlus.JSTime2DateTime(_token[0].Value <long>() / 1000);
                _line.Pair     = _pair;
                _line.Open     = _item[1].Value <decimal>();
                _line.Close    = _item[4].Value <decimal>();
                _line.High     = _item[2].Value <decimal>();
                _line.Low      = _item[3].Value <decimal>();
                _line.Volume   = _item[5].Value <decimal>();

                _result.Add(_line);
            }

            return(_result.ToArray());
        }
Example #13
0
        public IEnumerable<IStockKLine> GetKLine(string stockCode, KLineType type)
        {
            string filePath = PathHelper.GetKLineFilePath(stockCode, Market.XSHG, type);
            if (!File.Exists(filePath))
            {
                filePath = PathHelper.GetKLineFilePath(stockCode, Market.XSHE, type);
            }

            if (!File.Exists(filePath))
            {
                return null;
            }

            var file = new KLineFile(filePath);
            return file.GetItems();
        }
Example #14
0
        internal static IEnumerable<string> GetKLineDataFilePath(string stockCode, KLineType kLineType, DateTime bgnDt, DateTime endDt)
        {
            if (bgnDt > endDt)
            {
                throw new ArgumentOutOfRangeException("startDay", "startDay is less than endDay");
            }

            if (bgnDt == endDt)
            {
                return new List<string>() { GetKLineDataFilePath(stockCode, kLineType, bgnDt) };
            }

            List<string> result = new List<string>();
            string fileFolder = string.Format(@"{0}\{1}\{2}", StockKLineFolder, stockCode, kLineType.ToString());
            //方案1
            while (bgnDt.Year <= endDt.Year)
            {
                result.Add(fileFolder + string.Format(@"\{0}.dat", bgnDt.ToString("yyyy")));
                bgnDt = bgnDt.AddYears(1);
            }
            //方案2
            //switch (kLineType)
            //{
            //    /// 日线
            //    case KLineType.Daily:
            //        while (bgnDt.Year <= endDt.Year)
            //        {
            //            result.Add(fileFolder + string.Format(@"\{0}.dat", bgnDt.ToString("yyyy")));
            //            bgnDt = bgnDt.AddYears(1);
            //        }
            //        break;
            //    /// 1分钟线
            //    case KLineType.Min1:
            //    /// 5分钟线
            //    case KLineType.Min5:
            //        while ((12 * bgnDt.Year + bgnDt.Month) <= (12 * endDt.Year + endDt.Month))
            //        {
            //            result.Add(fileFolder + string.Format(@"\{0}.dat", bgnDt.ToString("yyyyMM")));
            //            bgnDt = bgnDt.AddMonths(1);
            //        }
            //        break;
            //}

            return result;
        }
Example #15
0
        public void AddIfNotExist(KLineType type, string stockCode, IEnumerable<IStockKLine> kLines)
        {
            ThrowIfTypeNotSupport(type);

            // 将待插入数据排序
            var orderedKLines = kLines.OrderBy(p => p.Time).ToList();
            if(orderedKLines.Count < 1)
            {
                return;
            }

            // 根据需要插入数据的时间段,获取数据库内这段时间的所有数据的时间
            var dateTimesInDb = Get(type, stockCode, orderedKLines.First().Time, orderedKLines.Last().Time).Select(p => p.Time).ToList();
            // 判断哪些数据需要插入
            var needsInsertKLines = orderedKLines.Where(p => !dateTimesInDb.Contains(p.Time));
            // 批量插入不存在的数据
            Add(type, stockCode, needsInsertKLines);
        }
        public IEnumerable<IStockKLine> GetData(string stockCode, KLineType kLineType, DateTime bgnDt, DateTime endDt)
        {
            List<string> pathList = PathHelper.GetKLineDataFilePath(stockCode, kLineType, bgnDt, endDt).ToList();

            List<StockKLineDataItem> result = new List<StockKLineDataItem>();
            foreach (string path in pathList)
            {
                if (File.Exists(path))
                {
                    var file = new StockKLineFile(path);
                    var lstAll = file.ReadAll();
                    var lstQuery = lstAll.Where(x => x.Time >= bgnDt && x.Time <= endDt);
                    result.AddRange(lstQuery);
                }
            }

            return result.Cast<IStockKLine>();
        }
        public IEnumerable<IStockKLine> GetLatest(IEnumerable<string> stockCodes, KLineType kLineType)
        {
            List<IStockKLine> result = new List<IStockKLine>();
            foreach (string code in stockCodes)
            {
                string filePath = string.Empty;
                if (PathHelper.GetLatestKLineDataFilePath(code, kLineType, ref filePath))
                {
                    var file = new StockKLineFile(filePath);
                    var lstAll = from it in file.ReadAll()
                                 orderby it.Time descending
                                 select it;
                    IStockKLine fst = lstAll.First();
                    if (fst != null)
                        result.Add(fst);
                }
            }

            return result.Cast<IStockKLine>();
        }
Example #18
0
        internal static string GetKLineDataFilePath(string stockCode, KLineType kLineType, DateTime dt)
        {
            //方案1
            return string.Format(@"{0}\{1}\{2}\{3}.dat", StockKLineFolder, stockCode, kLineType.ToString(), dt.ToString("yyyy"));

            //方案2
            //string filepath = null;
            //switch (kLineType)
            //{
            //    /// 日线
            //    case KLineType.Daily:
            //        filepath = string.Format(@"{0}\{1}\{2}\{3}.dat", StockKLineFolder, stockCode, kLineType.ToString(), dt.ToString("yyyy"));
            //        break;
            //    /// 1分钟线
            //    case KLineType.Min1:
            //    /// 5分钟线
            //    case KLineType.Min5:
            //        filepath = string.Format(@"{0}\{1}\{2}\{3}.dat", StockKLineFolder, stockCode, kLineType.ToString(), dt.ToString("yyyyMM"));
            //        break;
            //}
            //return filepath;
        }
Example #19
0
        /// <summary>
        /// 构造一条模拟K线的数据
        /// </summary>
        /// <param name="type">只支持Day, Min1, Min5</param>
        /// <param name="startTime"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static IEnumerable<IStockKLine> CreateRandomKLines(KLineType type, DateTime startTime, int count)
        {
            if(type != KLineType.Day && type != KLineType.Min1)
            {
                throw new NotSupportedException(string.Format("Only support {0}, {1}", KLineType.Day, KLineType.Min1));
            }
            if(count < 1)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            List<IStockKLine> result = new List<IStockKLine>();

            result.Add(CreateFirstData(type, startTime));

            for (int i = 1; i < count; i++)
            {
                AppendNewData(type, ref result);
            }

            return result;
        }
Example #20
0
        public static string GetKLineFilePath(string stockCode, Market market, KLineType tyep)
        {
            string strMarket = market == Market.XSHG ? _shangHai : _shenZhen;
            string strTypeFolder = string.Empty;
            string strTypeExt = string.Empty;
            switch(tyep)
            {
                case KLineType.Day:
                    strTypeFolder = _day;
                    strTypeExt = _dayExt;
                    break;
                case KLineType.Min1:
                    strTypeFolder = _min1;
                    strTypeExt = _min1Ext;
                    break;
                case KLineType.Min5:
                    strTypeFolder = _min5;
                    strTypeExt = _min5Ext;
                    break;
            }

            return Path.Combine(_dataFolder, strMarket, strTypeFolder, stockCode + strTypeExt);
        }
Example #21
0
        public static IEnumerable<IStockKLine> CreateRandomKLines(KLineType type, DateTime startTime, DateTime endTime)
        {
            if (type != KLineType.Day && type != KLineType.Min1)
            {
                throw new NotSupportedException(string.Format("Only support {0}, {1}", KLineType.Day, KLineType.Min1));
            }
            if (startTime > endTime)
            {
                throw new ArgumentOutOfRangeException("endTime");
            }

            List<IStockKLine> result = new List<IStockKLine>();

            result.Add(CreateFirstData(type, startTime));

            do
            {
                AppendNewData(type, ref result);
            } while (result.Last().Time <= endTime);

            result.RemoveAt(result.Count - 1);

            return result;
        }
Example #22
0
 private IEnumerable<IStockKLine> GetDataFromTongHuaShun(string stockCode, KLineType type)
 {
     try
     {
         IEnumerable<IStockKLine> result = _tongHuaShunApi.GetKLine(stockCode, type);
         return result == null ? new List<IStockKLine>() : result;
     }
     catch
     {
         // todo:因为同花顺数据可能不包含目前security的所有code,所以可能出现异常
         return new List<IStockKLine>();
     }
 }
Example #23
0
 public static string GetDataFolder(KLineType type)
 {
     throw new NotImplementedException();
 }
Example #24
0
 public override KLine[] GetKLines(string _pair, KLineType _type, params string[] _values)
 {
     throw new NotImplementedException();
 }
Example #25
0
 private void SaveIfNotExist(KLineType type, string stockCode, IEnumerable<IStockKLine> kLines)
 {
     try
     {
         _saveDataService.AddIfNotExist(type, stockCode, kLines);
     }
     catch (Exception ex)
     {
         LogHelper.Logger.WriteLine(string.Format("Save stock[{0}] data error.", stockCode), this.ServiceName);
         LogHelper.Logger.WriteLine(ex.ToString(), this.ServiceName);
     }
 }
Example #26
0
        /// <summary>
        /// 获取K线数据
        /// </summary>
        /// <param name="type"></param>
        /// <param name="stockCode"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public IEnumerable<IStockKLine> GetStockKLine(
            KLineType type, string stockCode, 
            DateTime startTime, DateTime endTime)
        {
            KLineArgs args = new KLineArgs
            {
                StockCode = stockCode,
                StartDate = startTime,
                EndDate = endTime
            };

            string controllerName;
            switch(type)
            {
                case KLineType.Day:
                    controllerName = "KLineDay";
                    break;
                case KLineType.Week:
                    controllerName = "KLineWeek";
                    break;
                case KLineType.Month:
                    controllerName = "KLineMonth";
                    break;
                case KLineType.Quarter:
                    controllerName = "KLineQuarter";
                    break;
                case KLineType.Year:
                    controllerName = "KLineYear";
                    break;
                case KLineType.Min1:
                    controllerName = "KLineMin1";
                    break;
                case KLineType.Min5:
                    controllerName = "KLineMin5";
                    break;
                case KLineType.Min15:
                    controllerName = "KLineMin15";
                    break;
                case KLineType.Min30:
                    controllerName = "KLineMin30";
                    break;
                case KLineType.Min60:
                    controllerName = "KLineMin60";
                    break;
                default:
                    controllerName = string.Empty;
                    break;
            }

            var result = _httpClient.PostAndReadAs<IEnumerable<StockKLineDto>, KLineArgs>(controllerName, args);
            return result;
        }
 public override IEnumerable<IStockKLine> GetKLines(ISecurity security, KLineType type, DateTime startTime, DateTime endTime)
 {
     return Domain.MarketData.Simulation.CreateRandomKLines(type, startTime, endTime);
 }
Example #28
0
        private void bkgDataImport_DoWork(object sender, DoWorkEventArgs e)
        {
            // < 覆盖,指数,TDX文件,K线级别 >
            TupleValue <bool, bool, bool, KLineType> arg = (TupleValue <bool, bool, bool, KLineType>)e.Argument;
            BLLDataImport bllDaImpt   = new BLLDataImport(CommProp.ConnectionString);
            bool          isConvert   = arg.Value1;
            bool          isComposite = arg.Value2;
            bool          useTDXFile  = arg.Value3;
            KLineType     kLineType   = arg.Value4;

            UIInProcess(true);
            _processCancel = false;

            if (useTDXFile)
            {
                this.LoadFileList_TDXDayFile(isComposite);
            }
            else
            {
                this.LoadFileList_exportFile();
            }

            // List<TupleValue<完整文件名, StockHead>>
            List <TupleValue <string, StockHead> > lstStockData = bllDaImpt.LoadMrkTypeAndCodeFromDataFile(AllFile, isComposite, useTDXFile);

            if (lstStockData.Count > 0)
            {
                Stopwatch stopWatch = Stopwatch.StartNew();

                try
                {
                    bllDaImpt.OpenConnection();
                    int    count        = lstStockData.Count;
                    int    insLineCount = 0;
                    string msgString    = string.Empty;

                    // 显示百分比提示信息
                    Action <int, int, int> showMsg = ((per, all, lineCnt) =>
                    {
                        SysFunction.BackspaceInConsole(msgString, txtConsole);
                        msgString = string.Format("{0} / {1},已导入:{2} 行)", per, all, lineCnt.ToString("N0"));
                        Console.Write(msgString);
                    });

                    Console.Write("正在导入...(");
                    // 是否需要删表动作,如果表中无记录,则省去 Delete 动作
                    bool haveRecord = bllDaImpt.GetTableRecordCount(BLL.GetKLineDBTableName(kLineType, isComposite)) > 0;
                    for (int i = 0; i < count; i++)
                    {
                        showMsg(i + 1, count, insLineCount);

                        // TupleValue<完整文件名, StockHead>
                        TupleValue <string, StockHead> stkData = lstStockData[i];

                        insLineCount += bllDaImpt.InsertStkKLine(stkData, isConvert, isComposite, useTDXFile, kLineType, haveRecord);

                        // 最后一批完成后,再刷一下
                        if (i == count - 1)
                        {
                            showMsg(i + 1, count, insLineCount);
                        }

                        if (_processCancel)
                        {
                            break;
                        }
                    }

                    if (_processCancel)
                    {
                        Console.WriteLine("  导入终止!");
                    }
                    else
                    {
                        Console.WriteLine("  导入完成!");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    bllDaImpt.CloseConnection();
                    _processCancel = false;
                    Console.WriteLine("总耗时:{0}", stopWatch.Elapsed);
                }
            }

            UIInProcess(false);
        }
Example #29
0
        private void Decide(KLineType kLineType)
        {
            bool isBuy = false;
            bool isSell = false;

            // 运算所有买指标的结果
            var buyResult = _keys
                .Where(p => p.KeyType == KeyType.Buy)
                .Select(p => p.Match(_battleship.Link))
                .Distinct().ToList();
            if(buyResult.Count == 1 &&
                buyResult[0] == true)
            {
                isBuy = true;
            }

            if(isBuy == false) // 如果已经决定要买了,就不用判断卖了
            {
                var sellResult = _keys
                    .Where(p => p.KeyType == KeyType.Sell)
                    .Select(p => p.Match(_battleship.Link))
                    .Distinct().ToList();

                if (sellResult.Count == 1 &&
                sellResult[0] == true)
                {
                    isSell = true;
                }
            }

            if(!isBuy && !isSell)
            {
                return; // 不买不卖就不进行操作了
            }

            Bullet bullet = new Bullet
            {
                Quantity = GetQuantity(isBuy),
                IsUp = isBuy
            };

            // todo: 内部系统的交易
            // Trinity

            OnShootted(bullet);
        }
Example #30
0
        public void TruncateStkKLine(KLineType kLineType, bool isComposite)
        {
            string tableName = BLL.GetKLineDBTableName(kLineType, isComposite);

            _dbo.TruncateTable(tableName);
        }
Example #31
0
        public override KLine[] GetKLines(string _pair, KLineType _type, params string[] _values)
        {
            string _typeText = "";

            switch (_type)
            {
            case KLineType.M1: _typeText = "M1"; break;

            case KLineType.M5: _typeText = "M5"; break;

            case KLineType.M15: _typeText = "M15"; break;

            case KLineType.M30: _typeText = "M30"; break;

            case KLineType.H1: _typeText = "H1"; break;

            case KLineType.H4: _typeText = "H4"; break;

            case KLineType.H6: _typeText = "H6"; break;

            case KLineType.D1: _typeText = "D1"; break;

            case KLineType.D7: _typeText = "W1"; break;

            case KLineType.MM: _typeText = "WN"; break;

            default: throw new Exception($"KLine type:{_type.ToString()} not supported.");
            }

            string _url = $"/v2/market/candles/{_typeText}/{_pair}";

            if (_values.Length > 0)
            {
                _url += $"?limit={_values[0]}";
            }
            if (_values.Length > 1)
            {
                _url += $"&before={_values[1]}";
            }

            JToken _token = base.HttpCall(HttpCallMethod.Get, "GET", _url);

            if (_token == null)
            {
                return(null);
            }

            IList <KLine> _result = new List <KLine>();
            JArray        _trades = _token.Value <JArray>();

            foreach (JToken _item in _trades)
            {
                KLine _line = new KLine();
                _line.DateTime = DateTimePlus.JSTime2DateTime(_item["id"].Value <long>() / 1000);
                _line.Pair     = _pair;
                _line.Open     = _item["open"].Value <decimal>();
                _line.Close    = _item["close"].Value <decimal>();
                _line.High     = _item["high"].Value <decimal>();
                _line.Low      = _item["low"].Value <decimal>();
                _line.Count    = _item["count"].Value <decimal>();
                _line.Volume   = _item["base_vol"].Value <decimal>();
                _line.Volume2  = _item["quote_vol"].Value <decimal>();

                _result.Add(_line);
            }

            return(_result.ToArray());
        }
Example #32
0
        public override KLine[] GetKLines(string _pair, KLineType _type, params string[] _values)
        {
            string _typeText = "";

            switch (_type)
            {
            case KLineType.M1: _typeText = "1min"; break;

            case KLineType.M5: _typeText = "5min"; break;

            case KLineType.M15: _typeText = "15min"; break;

            case KLineType.M30: _typeText = "30min"; break;

            case KLineType.H1: _typeText = "1hour"; break;

            case KLineType.H4: _typeText = "4hour"; break;

            case KLineType.H6: _typeText = "6hour"; break;

            case KLineType.D1: _typeText = "1day"; break;

            case KLineType.D7: _typeText = "1week"; break;

            default: throw new Exception($"KLine type:{_type.ToString()} not supported.");
            }

            string _url = $"/v1/market/kline?market={_pair}&type={_typeText}";

            if (_values.Length > 0)
            {
                _url += $"?limit={_values[0]}";
            }
            if (_values.Length > 1)
            {
                _url += $"&before={_values[1]}";
            }

            JToken _token = base.HttpCall(HttpCallMethod.Get, "GET", _url);

            if (_token == null)
            {
                return(null);
            }

            IList <KLine> _result = new List <KLine>();
            JArray        _trades = _token.Value <JArray>();

            foreach (JToken _item in _trades)
            {
                KLine _line = new KLine();
                _line.DateTime = DateTimePlus.JSTime2DateTime(_item[0].Value <long>());
                _line.Pair     = _pair;
                _line.Open     = _item[1].Value <decimal>();
                _line.Close    = _item[2].Value <decimal>();
                _line.High     = _item[3].Value <decimal>();
                _line.Low      = _item[4].Value <decimal>();
                _line.Volume   = _item[5].Value <decimal>();
                _line.Volume2  = _item[6].Value <decimal>();

                _result.Add(_line);
            }

            return(_result.ToArray());
        }
Example #33
0
 /// <summary>
 /// 获取指定类型的数据,如果无法获取到数据,返回null
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 internal IEnumerable<IStockKLine> GetData(KLineType type)
 {
     if(_history.ContainsKey(type))
     {
         return _history[type];
     }
     else
     {
         return null;
     }
 }
Example #34
0
 internal bool ContainsType(KLineType type)
 {
     return _history.ContainsKey(type);
 }
 public bool Exists(string stockCode, KLineType kLineType, DateTime dt)
 {
     var query = GetData(stockCode, kLineType, dt);
     return (query != null);
 }
Example #36
0
        /// <summary>
        /// GetKLines
        /// </summary>
        /// <param name="_pair"></param>
        /// <param name="_type"></param>
        /// <param name="_values">0:limit 1:sort 2:start 3:end</param>
        /// <returns></returns>
        public override KLine[] GetKLines(string _pair, KLineType _type, params string[] _values)
        {
            string _typeText = "";

            switch (_type)
            {
            case KLineType.M1: _typeText = "1m"; break;

            case KLineType.M5: _typeText = "5m"; break;

            case KLineType.M15: _typeText = "15m"; break;

            case KLineType.M30: _typeText = "30m"; break;

            case KLineType.H1: _typeText = "1h"; break;

            case KLineType.H6: _typeText = "6h"; break;

            case KLineType.H12: _typeText = "12h"; break;

            case KLineType.D1: _typeText = "1D"; break;

            case KLineType.D7: _typeText = "7D"; break;

            case KLineType.D14: _typeText = "14D"; break;

            case KLineType.MM: _typeText = "1M"; break;

            default: throw new Exception($"KLine type:{_type.ToString()} not supported.");
            }

            string _url = $"/v2/candles/trade:{_typeText}:t{_pair.ToUpper()}/hist";

            if (_values.Length > 0)
            {
                _url += $"?limit={_values[0]}";
            }
            if (_values.Length > 1)
            {
                _url += $"&sort={_values[1]}";
            }
            if (_values.Length > 2)
            {
                _url += $"&start={_values[2]}";
            }
            if (_values.Length > 4)
            {
                _url += $"&end={_values[3]}";
            }

            JToken _token = base.HttpCall(HttpCallMethod.Get, "GET", _url);

            if (_token == null)
            {
                return(null);
            }

            IList <KLine> _result = new List <KLine>();
            JArray        _trades = _token.Value <JArray>();

            foreach (JToken _item in _trades)
            {
                KLine _line = new KLine();
                _line.DateTime = DateTimePlus.JSTime2DateTime(_item[0].Value <long>() / 1000);
                _line.Pair     = _pair;
                _line.Open     = _item[1].Value <decimal>();
                _line.Close    = _item[2].Value <decimal>();
                _line.High     = _item[3].Value <decimal>();
                _line.Low      = _item[4].Value <decimal>();
                _line.Volume   = _item[5].Value <decimal>();

                _result.Add(_line);
            }

            return(_result.ToArray());
        }
Example #37
0
        private static void AppendNewData(KLineType type, ref List<IStockKLine> existData)
        {
            var preData = existData.Last();

            DateTime tradingTime;
            if (type == KLineType.Min1)
            {
                tradingTime = preData.Time.ToNextTradingMinute();
            }
            else
            {
                tradingTime = preData.Time.ToNextTradingDate();
            }

            var newData = CreateRandomItem(tradingTime, preData.Close, preData.Volume);

            existData.Add(newData);
        }
Example #38
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_pair"></param>
        /// <param name="_type"></param>
        /// <param name="_values">0:size</param>
        /// <returns></returns>
        public override KLine[] GetKLines(string _pair, KLineType _type, params string[] _values)
        {
            string _typeText = "";

            switch (_type)
            {
            case KLineType.M1: _typeText = "1min"; break;

            case KLineType.M5: _typeText = "5min"; break;

            case KLineType.M15: _typeText = "15min"; break;

            case KLineType.M30: _typeText = "30min"; break;

            case KLineType.H1: _typeText = "60min"; break;

            case KLineType.D1: _typeText = "1day"; break;

            case KLineType.D7: _typeText = "1week"; break;

            case KLineType.MM: _typeText = "1mon"; break;

            case KLineType.YY: _typeText = "1year"; break;

            default: throw new Exception($"KLine type:{_type.ToString()} not supported.");
            }

            string _url = $" /market/history/kline?symbol={_pair}&period={_typeText}";

            if (_values.Length > 0)
            {
                _url += $"&size={_values[0]}";
            }

            JToken _token = base.HttpCall(HttpCallMethod.Get, "GET", _url);

            if (_token == null)
            {
                return(null);
            }

            IList <KLine> _result = new List <KLine>();
            JArray        _trades = _token["data"].Value <JArray>();

            foreach (JToken _item in _trades)
            {
                KLine _line = new KLine();
                _line.DateTime = DateTimePlus.JSTime2DateTime(_token["id"].Value <long>() / 1000);
                _line.Pair     = _pair;
                _line.Open     = _item["open"].Value <decimal>();
                _line.Close    = _item["close"].Value <decimal>();
                _line.High     = _item["high"].Value <decimal>();
                _line.Low      = _item["low"].Value <decimal>();
                _line.Count    = _item["count"].Value <decimal>();
                _line.Volume   = _item["vol"].Value <decimal>();
                _line.Volume2  = _item["amount"].Value <decimal>();

                _result.Add(_line);
            }

            return(_result.ToArray());
        }
Example #39
0
 public IEnumerable<string> GetStockCodes(KLineType type)
 {
     throw new NotImplementedException();
 }
Example #40
0
        private static IStockKLine CreateFirstData(KLineType type, DateTime startTime)
        {
            double preClose = GetRandomPrice();
            double preVolume = _random.Next(100000, 10000000);
            DateTime tradingTime;
            if (type == KLineType.Min1)
            {
                tradingTime = startTime.IsTradingTime() ? startTime.Date.AddHours(startTime.Hour).AddMinutes(startTime.Minute) : startTime.ToNextTradingMinute();
            }
            else
            {
                tradingTime = startTime.IsTradingDate() ? startTime.Date : startTime.ToNextTradingDate();
            }

            var kLine = CreateRandomItem(tradingTime, preClose, preVolume);
            return kLine;
        }
Example #41
0
        public int InsertStkKLine(TupleValue <string, StockHead> stkInfo, bool isConvert, bool isComposite, bool useTDXFile, KLineType kLineType, bool haveRecord = true)
        {
            string    fileFullName = stkInfo.Value1;
            StockHead stkHead      = stkInfo.Value2;
            string    tableName    = BLL.GetKLineDBTableName(kLineType, isComposite);
            DateTime  existMaxDay  = DateTime.MinValue;
            DataTable insTable     = _dbo.GetEmptyTable(tableName);

            if (haveRecord)
            {
                if (isConvert)
                {
                    _dbo.DeleteTable(tableName, stkHead);
                }
                else
                {
                    existMaxDay = _dbo.FindMaxExistTradeDay(tableName, stkHead);
                }
            }

            if (useTDXFile)
            {
                this.LoadDayLineFileData_TDXDayFile(fileFullName, stkHead, existMaxDay, ref insTable);
            }
            else
            {
                this.LoadDayLineFileData_exportFile(fileFullName, stkHead, existMaxDay, ref insTable);
            }

            _dbo.BulkWriteTable(insTable, DataRowState.Added);

            return(insTable.Rows.Count);
        }
Example #42
0
        internal static bool GetLatestKLineDataFilePath(string stockCode, KLineType kLineType, ref string latestFilePath)
        {
            latestFilePath = string.Empty;

            string todayFilePath = GetKLineDataFilePath(stockCode, kLineType, DateTime.Now);
            if (File.Exists(todayFilePath))
            {
                latestFilePath = todayFilePath;
                return true;
            }

            string fileFolder = string.Format(@"{0}\{1}\{2}", StockKLineFolder, stockCode, kLineType.ToString());
            if (Directory.Exists(fileFolder))
            {
                DirectoryInfo dir = new DirectoryInfo(fileFolder);
                FileInfo file = dir.GetFiles().OrderBy(p => p.CreationTime).LastOrDefault();
                if (file != null)
                {
                    latestFilePath = file.FullName;
                    return true;
                }
            }

            return false;
        }