Exemplo n.º 1
0
 public float GetPercentTest(KLine line, float maxLoss)
 {
     //float lossMul = AppSetting.Ins.GetFloat("LossMul");
     if (V_Dir > 0)
     {
         if (V_Avg_Price > line.V_LowPrice)
         {
             float p = ((line.V_LowPrice - V_Avg_Price) / line.V_LowPrice) * V_Leverage * 100;
             if (p <= maxLoss)
             {
                 return(maxLoss);
             }
         }
         return(((line.V_ClosePrice - V_Avg_Price) / line.V_ClosePrice) * V_Leverage * 100);
     }
     else
     {
         if (V_Avg_Price < line.V_HightPrice)
         {
             float p = ((V_Avg_Price - line.V_HightPrice) / line.V_HightPrice) * V_Leverage * 100;
             if (p <= maxLoss)
             {
                 return(maxLoss);
             }
         }
         return(((V_Avg_Price - line.V_ClosePrice) / line.V_ClosePrice) * V_Leverage * 100);
     }
 }
Exemplo n.º 2
0
 public static void RefreshKLine(string gid, DateTime currentDate)
 {
     KLine.CreateKLineTable(gid);
     KLine[] kArr1Min = TimeLine.Create1MinKLine(gid, DateTime.Parse(currentDate.ToShortDateString()));
     KLine[] kArr     = TimeLine.AssembKLine("day", kArr1Min);
     foreach (KLine k in kArr)
     {
         k.Save();
     }
     kArr = TimeLine.AssembKLine("1hr", kArr1Min);
     foreach (KLine k in kArr)
     {
         k.Save();
     }
     kArr = TimeLine.AssembKLine("30min", kArr1Min);
     foreach (KLine k in kArr)
     {
         k.Save();
     }
     kArr = TimeLine.AssembKLine("15min", kArr1Min);
     foreach (KLine k in kArr)
     {
         k.Save();
     }
 }
Exemplo n.º 3
0
    /// <summary>
    /// 是否要平仓
    /// </summary>
    /// <param name="dir">大于0多  其余空</param>
    /// <param name="percent">当前盈利百分比值</param>
    /// <returns></returns>
    public bool ShouldCloseOrderTest(int dir, float percent, KLine line)
    {
        //float lossMul = AppSetting.Ins.GetFloat("LossMul");
        //percent *= lossMul;
        bool result = OnShouldCloseOrder(dir, percent, true);

        if (result)
        {
            bool lastResult = V_WinClose;
            V_WinClose = percent > 0;
            if (V_WinClose)
            {
                //if (lastResult)
                //{
                cooldown = AppSetting.Ins.GetInt("CoolDown");
                //}
            }
            else
            {
                //if (!lastResult)
                //{
                lossCooldown = AppSetting.Ins.GetFloat("LossCoolDown");
                //}
            }
            V_LastOpTime = line.V_Timestamp;
            V_MaxAlready = false;
        }
        return(result);
    }
Exemplo n.º 4
0
    public static float GetBoll(int length, List <KLine> data, out float upValue, out float lowValue)
    {
        float midValue = MA.GetMA(length, data);

        List <double> mulList = new List <double>();

        for (int i = 0; i < length; i++)
        {
            KLine line = data[i];
            mulList.Add(Math.Pow(line.V_ClosePrice - midValue, 2));
        }

        //标准差
        double sd = Math.Sqrt(mulList.Average());


        //上轨
        upValue = midValue + 2 * (float)sd;


        //下轨
        lowValue = midValue - 2 * (float)sd;

        return(midValue);
    }
Exemplo n.º 5
0
    public static void WatchKDJMACD()
    {
        for (; true;)
        {
            foreach (string gid in Util.GetAllGids())
            {
                if (Util.IsTransacTime(DateTime.Now))
                {
                    try
                    {
                        KLine[] kArrDay = KLine.GetLocalKLine(gid, "day");
                        KLine.ComputeRSV(kArrDay);
                        KLine.ComputeKDJ(kArrDay);
                        KLine.SearchKDJAlert(kArrDay, kArrDay.Length - 1);
                        KLine.ComputeMACD(kArrDay);
                        KLine.SearchMACDAlert(kArrDay, kArrDay.Length - 1);


                        //KLine.SearchKDJAlert(gid, "day", DateTime.Now);


                        //KLine.SearchKDJAlert(gid, "1hr", DateTime.Now);
                        //KLine.SearchKDJAlert(gid, "30min", DateTime.Now);
                        //KLine.SearchKDJAlert(gid, "15min", DateTime.Now);
                    }
                    catch
                    {
                    }
                }
            }
            Thread.Sleep(1000);
        }
    }
Exemplo n.º 6
0
        /// <summary>
        /// 计算向下的反转点,数据长度小于回望周期时为0,代表空值
        /// </summary>
        /// <param name="dataSeries"></param>
        /// <param name="Ndays"></param>
        /// <param name="lengthOfBackLooking"></param>
        /// <returns></returns>
        public static List <double> findDownReversionPoint(List <KLine> dataSeries, int Ndays, int lengthOfBackLooking)
        {
            List <double> indexList = new List <double>();

            for (int i = 0; i < dataSeries.Count; i++)
            {
                if (i < lengthOfBackLooking - 1)
                {
                    indexList.Add(0);//空值记为0
                    continue;
                }
                else
                {
                    KLine highestPoint = new KLine();
                    //var itemOfHighestPoint = dataSeries.Where((item, index) => index <= i && index >= i - lengthOfBackLooking - 1).Select((m, index) => new { index, m }).OrderByDescending(n => n.m.high).Take(1).ToList();
                    var itemOfHighestPoint = dataSeries.GetRange(i - (lengthOfBackLooking - 1), lengthOfBackLooking).OrderByDescending(n => n.high).Take(1).ToList();
                    highestPoint = itemOfHighestPoint[0];
                    int indexOfHighestPoint = dataSeries.FindIndex(x => x.time == highestPoint.time);
                    if (indexOfHighestPoint - Ndays < 0)
                    {
                        indexList.Add(0);//空值记为0
                    }
                    else
                    {
                        indexList.Add(dataSeries[indexOfHighestPoint - Ndays].low);
                    }
                }
            }

            return(indexList);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            NDapperLog.Receive += msg;

            string ConnectionStr = "server=(local);UID=sa;PWD=sa;database=test";
            string mysqlhost     = "Host = 127.0.0.1; UserName = root; Password = @; Database = KLine; Port = 3316; CharSet = utf8; Allow Zero Datetime = true;";

            NDapper dbss  = DapperManager.CreateDatabase(ConnectionStr, DBType.SqlServer);
            var     state = dbss.State();
            var     list  = dbss.Query <KLine>("select id,symbol from pp2009_min10");

            NDapper dbss1 = DapperManager.CreateDatabase(ConnectionStr, DBType.SqlServer);
            var     list1 = dbss1.QueryAsync <KLine>("select id,symbol from pp2009_min11");

            NDapper dbss2 = DapperManager.CreateDatabase(ConnectionStr, DBType.SqlServer);
            var     list2 = dbss2.Query <KLine>("select id,symbol from pp2009_min12");

            KLine k = new KLine();

            dbss2.Query <KLine>("select UserName,Email from User  where UserId=@UserId", new KLine()
            {
                ID = 1
            });

            NDapper dbSqlLite = DapperManager.CreateDatabase(@"symbo3.db", DBType.SqlLite);
            //ConnectionState DapperState = dbSqlLite.State();
            string createtb = "create table  hsi1903_min1 (id int, symbol varchar(50))";
            int    x        = dbSqlLite.Execute(createtb);
            int    xs       = dbSqlLite.Execute("insert into hsi1903_min1(id,symbol)values('1','122')");
            var    listSS   = dbSqlLite.Query <KLine>("select id,symbol from hsi1903_min1");

            Console.ReadKey();
        }
Exemplo n.º 8
0
        //从1分钟数据中提取出15K数据,如果取数成功返回整理过后的list文件否则返回空
        private List <KLine> Get15KData(List <KLine> todayData)
        {
            //每当index/15=0时进行写数据,记录第1分钟的开盘,最后1分钟的收盘和时间,总成交量、额,持仓
            int          index = 0;
            double       volume = 0, amount = 0;
            List <KLine> newData = new List <KLine>(new KLine[16]);

            for (int i = 0; i < 16; ++i)
            {
                newData[i] = new KLine();
            }

            if (todayData == null)
            {
                log.Info("Get15KData函数传入参数,data为空!返回null");
                return(null);
            }

            //每次需要加入的15K数据
            //KLine data15K = new KLine();
            for (index = 0; index < 240; ++index)
            {
                //对每个15K的成交量、额数据进行累加
                volume += todayData[index].volume;
                amount += todayData[index].amount;

                if (index % 15 == 0 || index == 239)
                {
                    if (index == 0)
                    {
                        newData[0].open = todayData[index].open;
                        newData[0].high = todayData[index].high;
                        newData[0].low  = todayData[index].low;
                    }
                    else
                    {
                        //注意这里取不到成交量最大值和最小值,需要在策略程序中写出这个功能
                        //先给这个
                        newData[index / 15 - 1].time         = todayData[index - 1].time;
                        newData[index / 15 - 1].close        = todayData[index - 1].close;
                        newData[index / 15 - 1].high         = GetHigh(todayData, index - 15, index - 1);
                        newData[index / 15 - 1].low          = GetLow(todayData, index - 15, index - 1);
                        newData[index / 15 - 1].volume       = volume;
                        newData[index / 15 - 1].amount       = amount;
                        newData[index / 15 - 1].openInterest = todayData[index].openInterest;
                        //newData.Add(data15K);

                        //重新给data15K更新值
                        newData[index / 15].open = todayData[index].open;
                        newData[index / 15].high = todayData[index].high;
                    }
                    if (index != 0)
                    {
                        volume = 0; amount = 0;
                    }
                }
            }

            return(newData);
        }
Exemplo n.º 9
0
    int ShouldOrderByOldAvg()
    {
        KLine curLine = V_Cache.V_KLineData[0];

        if (curLine.V_ClosePrice < V_Cache.V_KLineData[V_CycleList[2]].V_ClosePrice)
        {
            if (V_Cache.V_KLineData[V_CycleList[2] - V_CycleList[1]].V_ClosePrice > V_Cache.V_KLineData[V_CycleList[2]].V_ClosePrice)
            {
                return(-1);
            }
        }

        if (curLine.V_ClosePrice > V_Cache.V_KLineData[V_CycleList[0]].V_ClosePrice)
        {
            if (V_Cache.V_KLineData[V_CycleList[2] - V_CycleList[1]].V_ClosePrice < V_Cache.V_KLineData[V_CycleList[2]].V_ClosePrice)
            {
                return(1);
            }
        }


        //if (V_Cache.V_KLineData[V_CycleList[1] - V_CycleList[0]].V_ClosePrice < V_Cache.V_KLineData[V_CycleList[1]].V_ClosePrice)
        //{
        //    return -1;
        //}

        //if (V_Cache.V_KLineData[V_CycleList[1] - V_CycleList[0]].V_ClosePrice > V_Cache.V_KLineData[V_CycleList[1]].V_ClosePrice)
        //{
        //    return 1;
        //}


        return(0);
    }
Exemplo n.º 10
0
        /// <summary>
        /// 月k
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }
            SecurityPropertiesSet securities = repository.Securities;
            List <String>         codes      = securities.Codes;
            int num = 0;

            foreach (String code in codes)
            {
                if (code == null || code == "")
                {
                    continue;
                }
                TimeSerialsDataSet tsd = repository[code];
                if (tsd == null || tsd.DayKLine == null || tsd.DayKLine.Count <= 0)
                {
                    continue;
                }
                showText(code + "...");


                KLine monthKline = (KLine)tsd.Create("kline", TimeUnit.month, checkBox2.Checked);
            }
        }
Exemplo n.º 11
0
 public static KLine GetTodayKLine(string stockCode)
 {
     if (Util.IsTransacDay(DateTime.Now))
     {
         DateTime nowDate = DateTime.Parse(DateTime.Now.ToShortDateString());
         string   sqlStr  = " select  * from " + stockCode.Trim() + "_timeline  where ticktime >= '" + nowDate.ToShortDateString()
                            + "' and ticktime < '" + nowDate.AddDays(1).ToShortDateString() + "' order by ticktime desc ";
         DataTable dt = DBHelper.GetDataTable(sqlStr);
         if (dt.Rows.Count > 1)
         {
             KLine k = new KLine();
             k.type          = "day";
             k.startDateTime = nowDate;
             k.startPrice    = double.Parse(dt.Rows[0]["open"].ToString());
             k.highestPrice  = double.Parse(dt.Rows[0]["high"].ToString());
             k.lowestPrice   = double.Parse(dt.Rows[0]["low"].ToString());
             k.endPrice      = double.Parse(dt.Rows[0]["buy"].ToString());
             if (k.endPrice == 0)
             {
                 k.endPrice = double.Parse(dt.Rows[0]["sell"].ToString());
             }
             k.gid = stockCode;
             return(k);
         }
         else
         {
             return(null);
         }
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 12
0
    public static KLine[] AssembKLine(string type, KLine[] kArr)
    {
        int span = 15;

        switch (type)
        {
        case "15min":
            span = 15;
            break;

        case "30min":
            span = 30;
            break;

        case "1hr":
            span = 60;
            break;

        case "day":
            span = 240;
            break;

        default:
            break;
        }
        int kLineNum = ((kArr.Length / span) * span == kArr.Length) ?  (kArr.Length / span) : (1 + kArr.Length / span);

        KLine[] newKArr = new KLine[kLineNum];
        for (int i = 0; i < kLineNum; i++)
        {
            newKArr[i]               = new KLine();
            newKArr[i].gid           = kArr[0].gid;
            newKArr[i].type          = type;
            newKArr[i].startDateTime = DateTime.MinValue;
            newKArr[i].startPrice    = 0;
            newKArr[i].endPrice      = 0;
            newKArr[i].highestPrice  = double.MinValue;
            newKArr[i].lowestPrice   = double.MaxValue;
            newKArr[i].volume        = 0;
            newKArr[i].amount        = 0;
            for (int j = 0; j < span && (i * span + j) < kArr.Length; j++)
            {
                if (j == 0)
                {
                    newKArr[i].startDateTime = kArr[i * span + j].startDateTime;
                    newKArr[i].startPrice    = kArr[i * span + j].startPrice;
                }
                newKArr[i].highestPrice = Math.Max(newKArr[i].highestPrice, kArr[i * span + j].highestPrice);
                newKArr[i].lowestPrice  = Math.Min(newKArr[i].lowestPrice, kArr[i * span + j].lowestPrice);
                newKArr[i].volume       = newKArr[i].volume + kArr[i * span + j].volume;
                newKArr[i].amount       = newKArr[i].amount + kArr[i * span + j].amount;
                if (j == span - 1 || i * span + j == kArr.Length - 1)
                {
                    newKArr[i].endPrice = kArr[i * span + j].endPrice;
                }
            }
        }
        return(newKArr);
    }
Exemplo n.º 13
0
        /// <summary>
        /// 读取日线数据
        /// </summary>
        public void LoadDayKLine()
        {
            String dayFilename = datapath + (code.StartsWith("6") ? "SH" : "SZ") + code + ".csv";
            KLine  dayLine     = new KLine(code, TimeUnit.day);

            dayLine.Load(dayFilename, false, ",", new String[] { "时间", "开盘", "最高", "最低", "收盘", "成交量", "成交额" });
            klineDay = dayLine;
        }
Exemplo n.º 14
0
    public List <KLine> GetMergeKLine(int scale)
    {
        List <KLine> result = new List <KLine>();

        bool refresh = false;

        KLine data = new KLine();

        KLine oldData = new KLine();

        for (int i = 0; i < V_KLineData.Count; i++)
        {
            oldData = V_KLineData[i];

            if (i % scale == 0)
            {
                refresh = true;
            }
            else
            {
                refresh = false;
            }

            if (refresh)
            {
                data            = new KLine();
                data.V_LowPrice = oldData.V_LowPrice;

                data.V_ClosePrice = oldData.V_ClosePrice;
                data.V_Timestamp  = oldData.V_Timestamp;
            }

            data.V_Vol += oldData.V_Vol;

            if (data.V_LowPrice > oldData.V_LowPrice)
            {
                data.V_LowPrice = oldData.V_LowPrice;
            }

            if (data.V_HightPrice < oldData.V_HightPrice)
            {
                data.V_HightPrice = oldData.V_HightPrice;
            }

            if (i % scale == scale - 1 || i == V_KLineData.Count - 1)
            {
                data.V_OpenPrice = oldData.V_OpenPrice;
                result.Add(data);
            }
        }

        return(result);
    }
Exemplo n.º 15
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());
        }
Exemplo n.º 16
0
    public static KLine[] GetKLineDayFromSohu(string gid, DateTime startDate, DateTime endDate)
    {
        string kLineJsonStr = GetKLineDayJSONFromSohu(gid, startDate, endDate).Trim();

        if (kLineJsonStr.Trim().Equals("{}"))
        {
            return(new KLine[0]);
        }
        if (kLineJsonStr.StartsWith("["))
        {
            kLineJsonStr = kLineJsonStr.Remove(0, 1);
        }
        if (kLineJsonStr.EndsWith("]"))
        {
            kLineJsonStr = kLineJsonStr.Remove(kLineJsonStr.Length - 1, 1);
        }
        object[] oArr     = Util.GetArrayFromJsonByKey(kLineJsonStr, "hq");
        KLine[]  kLineArr = new KLine[oArr.Length];
        for (int i = 0; i < oArr.Length; i++)
        {
            object[] kLineData = (object[])oArr[i];
            KLine    kLine     = new KLine();
            kLine.type                    = "day";
            kLine.startDateTime           = DateTime.Parse(kLineData[0].ToString());
            kLine.startPrice              = double.Parse(kLineData[1].ToString());
            kLine.endPrice                = double.Parse(kLineData[2].ToString());
            kLine.highestPrice            = double.Parse(kLineData[6].ToString());
            kLine.lowestPrice             = double.Parse(kLineData[5].ToString());
            kLine.gid                     = gid.Trim();
            kLine.deal                    = double.Parse(kLineData[7].ToString());
            kLine.volume                  = double.Parse(kLineData[8].ToString());
            kLine.change                  = double.Parse(kLineData[9].ToString().Replace("%", ""));
            kLineArr[oArr.Length - 1 - i] = kLine;
        }
        if (endDate == DateTime.Parse(DateTime.Now.ToShortDateString()) && Util.IsTransacDay(endDate) &&
            kLineArr[kLineArr.Length - 1].startDateTime < endDate)
        {
            KLine k = GetTodayKLine(gid);
            if (k != null)
            {
                KLine[] kLineArrNew = new KLine[kLineArr.Length + 1];

                for (int i = 0; i < kLineArr.Length; i++)
                {
                    kLineArrNew[i] = kLineArr[i];
                }
                kLineArrNew[kLineArr.Length] = k;
                return(kLineArrNew);
            }
        }
        return(kLineArr);
    }
Exemplo n.º 17
0
 public static void  RefreshTodayKLine()
 {
     foreach (string gid in GetAllGids())
     {
         try
         {
             KLine.RefreshKLine(gid, DateTime.Parse(DateTime.Now.ToShortDateString()));
         }
         catch
         {
         }
     }
 }
Exemplo n.º 18
0
 public static KLine[] GetSubKLine(KLine[] kArr, int startIndex, int num)
 {
     if (startIndex + num > kArr.Length)
     {
         return(null);
     }
     KLine[] subArr = new KLine[num];
     for (int i = 0; i < num; i++)
     {
         subArr[i] = kArr[startIndex + i];
     }
     return(subArr);
 }
Exemplo n.º 19
0
        /// <summary>
        /// 资金动向创建
        /// </summary>
        /// <param name="tu"></param>
        /// <returns></returns>
        public TimeSeries <ITimeSeriesItem <List <double> > > FundTrendCreate(TimeUnit tu)
        {
            KLine kline = KLineCreateOrLoad(tu);
            TimeSeries <ITimeSeriesItem <List <double> > > r = kline.executeIndicator();

            r.Save(GetFullFileName(IndicatorMetaCollection.META_FUND_TREND, tu));

            if (!timeSerials.ContainsKey(tu))
            {
                timeSerials.Add(tu, new ConcurrentDictionary <string, object>());
            }
            timeSerials[tu][IndicatorMetaCollection.META_FUND_TREND.NameInfo.Name] = r;
            return(r);
        }
Exemplo n.º 20
0
    public static KLine[] GetKLine(string type, string gid, DateTime startDateTime, DateTime endDateTime)
    {
        KLine[] kLineArr = new KLine[0];
        switch (type.Trim())
        {
        case "day":
            kLineArr = GetKLineDayFromSohu(gid, startDateTime, endDateTime);
            break;

        default:
            break;
        }
        return(kLineArr);
    }
Exemplo n.º 21
0
    public static List <KLine> GetAListFormJContainer(JContainer jcontainer)
    {
        List <KLine> result = new List <KLine>();
        JToken       temp   = jcontainer.First;

        while (temp != null)
        {
            Dictionary <string, string> content = temp.ToObject <Dictionary <string, string> >();
            KLine line = new KLine();
            line.SetData(content);
            result.Add(line);
            temp = temp.Next;
        }
        return(result);
    }
Exemplo n.º 22
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());
        }
Exemplo n.º 23
0
        public static KLine[] GetKLine(MarketType _type, MarketPeriod _period)
        {
            string _url = "";
            switch (_type)
            {
                case MarketType.BTC: _url = "https://market.huobi.com/staticmarket/kline{0}.html"; break;
                case MarketType.LTC: _url = "https://market.huobi.com/staticmarket/kline_ltc{0}.html"; break;
            }
            switch (_period)
            {
                case MarketPeriod.M1: _url = string.Format(_url, "001"); break;
                case MarketPeriod.M5: _url = string.Format(_url, "005"); break;
                case MarketPeriod.M15: _url = string.Format(_url, "015"); break;
                case MarketPeriod.M30: _url = string.Format(_url, "030"); break;
                case MarketPeriod.M60: _url = string.Format(_url, "060"); break;
                case MarketPeriod.D: _url = string.Format(_url, "100"); break;
                case MarketPeriod.W: _url = string.Format(_url, "200"); break;
                case MarketPeriod.M: _url = string.Format(_url, "300"); break;
                case MarketPeriod.Y: _url = string.Format(_url, "400"); break;
            }

            string _result = Get(_url);
            IList<KLine> _klines = new List<KLine>();
            string[] _lines = _result.Split('\n');
            foreach (string _line in _lines)
            {
                string[] _item = _line.Replace("\r", "").Split(',');
                if (_item.Length != 8) { continue; }
                KLine _kline = new KLine();
                _kline.DateTime = DateTime.Parse(string.Format("{0}-{1}-{2} {3}:{4}:{5}",
                    _item[0].Substring(0,4),
                    _item[0].Substring(4,2),
                    _item[0].Substring(6,2),
                    _item[1].Substring(0,2),
                    _item[1].Substring(2,2),
                    _item[1].Substring(4,2)));
                _kline.Open = decimal.Parse(_item[2]);
                _kline.High = decimal.Parse(_item[3]);
                _kline.Low = decimal.Parse(_item[4]);
                _kline.Close = decimal.Parse(_item[5]);
                _kline.Volume = decimal.Parse(_item[6]);
                _kline.Total = decimal.Parse(_item[7]);
                _klines.Add(_kline);
            }
            return _klines.ToArray();
        }
Exemplo n.º 24
0
            /// <summary>
            /// 根据个股S点卖出
            /// </summary>
            /// <param name="bouts"></param>
            /// <param name="ds"></param>
            /// <param name="strategyParam"></param>
            /// <param name="backtestParam"></param>
            public void DoSell1(TradeRecords tradeRecords, TimeSerialsDataSet ds, Properties strategyParam, BacktestParameter backtestParam)
            {
                TimeSeries <ITimeSeriesItem <char> > dayTradePt = ds.CubePtCreateOrLoad();

                if (dayTradePt == null)
                {
                    return;
                }
                if (tradeRecords == null || tradeRecords.Bouts == null || tradeRecords.Bouts.Count <= 0)
                {
                    return;
                }
                KLine dayLine = ds.DayKLine;

                if (dayLine == null)
                {
                    return;
                }
                foreach (TradeBout bout in tradeRecords.Bouts)
                {
                    DateTime buyDate = bout.BuyInfo.TradeDate;
                    KeyValuePair <int, ITimeSeriesItem> dayTradePtItem = dayTradePt.GetNearest(buyDate, false);
                    if (dayTradePtItem.Key < 0)
                    {
                        continue;
                    }
                    if (dayTradePtItem.Value == null)
                    {
                        continue;
                    }
                    int index = dayTradePt.IndexOf(dayTradePtItem.Value.Date);
                    for (int k = index; k < dayTradePt.Count; k++)
                    {
                        if (dayTradePt[k].Value == 'S')
                        {
                            KLineItem dayLineItem = dayLine[dayTradePt[k].Date];
                            if (dayLineItem == null)
                            {
                                break;
                            }
                            bout.RecordTrade(2, dayLineItem.Date, TradeDirection.Sell, dayLineItem.CLOSE, bout.BuyInfo.Amount, 0, 0, "发S点");
                            break;
                        }
                    }
                }
            }
Exemplo n.º 25
0
        /// <summary>
        /// 根据K线生成立体买卖
        /// </summary>
        /// <param name="tu"></param>
        /// <returns></returns>
        public TradingLine CubeCreate(TimeUnit tu = TimeUnit.day, bool forced = true)
        {
            KLine       kline     = KLineCreateOrLoad(tu);
            TradingLine tradeline = kline.indicator_trading_stereo1();

            tradeline.buyLine.Save(GetFullFileName(IndicatorMetaCollection.META_CUBEBUY, tu));
            tradeline.sellLine.Save(GetFullFileName(IndicatorMetaCollection.META_CUBESELL, tu));
            tradeline.buysellPoints.Save(GetFullFileName(IndicatorMetaCollection.META_CUBEPT, tu));

            if (!timeSerials.ContainsKey(tu))
            {
                timeSerials.Add(tu, new ConcurrentDictionary <string, object>());
            }
            timeSerials[tu][IndicatorMetaCollection.META_CUBEBUY.NameInfo.Name]  = tradeline.buyLine;
            timeSerials[tu][IndicatorMetaCollection.META_CUBESELL.NameInfo.Name] = tradeline.sellLine;
            timeSerials[tu][IndicatorMetaCollection.META_CUBEPT.NameInfo.Name]   = tradeline.buysellPoints;
            return(tradeline);
        }
Exemplo n.º 26
0
    /// <summary>
    /// 刷新历史数据
    /// </summary>
    public virtual async Task RunHistory()
    {
        Console.WriteLine(V_Instrument_id + ":获取历史数据");

        Debugger.Log(V_Instrument_id + ":获取历史数据");

        if (V_HistoryCache == null)
        {
            V_HistoryCache = new KLineCache();
        }

        List <KLine> history_data = new List <KLine>();

        SwapApi api = CommonData.Ins.V_SwapApi;

        int length = V_Min;

        DateTime t_start = DateTime.Now.AddMinutes(-length * 2000);

        DateTime t_end = DateTime.Now;

        while (t_start.AddMinutes(length * 200) < t_end)
        {
            JContainer con = await api.getCandlesDataAsync(V_Instrument_id, t_start, t_start.AddMinutes(length * 200), length * 60);

            List <KLine> d = KLine.GetListFormJContainer(con);

            d.AddRange(history_data);

            history_data.Clear();

            history_data.AddRange(d);

            t_start = t_start.AddMinutes(length * 200);
        }

        Console.WriteLine(V_Instrument_id + ":历史数据 " + history_data.Count + "条");

        Debugger.Log(V_Instrument_id + ":历史数据 " + history_data.Count + "条");

        V_HistoryCache.RefreshData(history_data);
        V_LastOpTime = history_data[history_data.Count - 1].V_Timestamp;
    }
Exemplo n.º 27
0
    /// <summary>
    /// 平仓
    /// </summary>
    public virtual void CloseOrder(KLine kline, int dir, float percent = 1, bool limit = true)
    {
        if (V_Positions == null || V_Positions.Count <= 0)
        {
            return;
        }

        Position removeItem = null;

        foreach (var item in V_Positions)
        {
            if (item.V_Dir == dir)
            {
                removeItem = item;
                break;
            }
        }

        if (removeItem == null)
        {
            return;
        }

        float p = removeItem.GetPercentTest(kline, limit?helper.V_LossPercent:-10000);

        //p = p;

        float temp = 0;

        temp          = (p * 0.01f + percent) * removeItem.V_AllVol;
        V_LeaveMoney += temp;
        temp          = p * 0.01f * removeItem.V_AllVol;
        //Console.WriteLine("{0}  :  平仓价格:{1}  盈利:{2}  资金:{3}  百分比:{4}  仓位:{5}", kline.V_Timestamp, kline.V_ClosePrice, temp, V_LeaveMoney, p, percent*100);
        if (percent >= 1)
        {
            V_Positions.Remove(removeItem);
        }
        else
        {
            removeItem.V_AllVol  *= 1 - percent;
            removeItem.V_AvailVol = removeItem.V_AllVol;
        }
    }
Exemplo n.º 28
0
 /// <summary>
 /// 生成指标数据
 /// </summary>
 /// <returns></returns>
 public bool doGenerateIndicator()
 {
     showBeginMessage("开始生成指标...");
     if (repository == null)
     {
         repository = new IndicatorRepository(FileUtils.GetDirectory(props.Get <String>("repository")));
         repository.Initilization();
     }
     try
     {
         List <String> codes = repository.Securities.Codes;
         foreach (String code in codes)
         {
             TimeSerialsDataSet ds = repository[code];
             if (ds == null)
             {
                 continue;
             }
             showProgressMessage(code);
             KLine       kline     = ds.DayKLine;
             TradingLine tradeLine = ds.DayTradeLine;
             ds.Create("kline", TimeUnit.week);
             ds.Create("kline", TimeUnit.month);
             ds.CubeCreate();
             ds.CubeCreate(TimeUnit.week);
             ds.CubeCreate(TimeUnit.month);
             ds.FundTrendCreate(TimeUnit.day);
             ds.FundTrendCreate(TimeUnit.week);
             ds.FundTrendCreate(TimeUnit.month);
             ds.FundTrendCrossCreate(TimeUnit.day);
             ds.FundTrendCrossCreate(TimeUnit.week);
             ds.FundTrendCrossCreate(TimeUnit.month);
         }
         showResultMessage("");
         return(true);
     }
     catch (Exception e)
     {
         showResultMessage("生成指标失败", -1, e.Message);
         return(false);
     }
 }
Exemplo n.º 29
0
    public static KLine[] LoadLocalKLine(string gid, string type)
    {
        DataTable dt = DBHelper.GetDataTable(" select * from " + gid.Trim() + "_k_line where  type = '" + type + "' order by start_date ");

        KLine[] kArr = new KLine[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            kArr[i]               = new KLine();
            kArr[i].gid           = gid.Trim();
            kArr[i].startDateTime = DateTime.Parse(dt.Rows[i]["start_date"].ToString());
            kArr[i].type          = type.Trim();
            kArr[i].startPrice    = double.Parse(dt.Rows[i]["open"].ToString());
            kArr[i].endPrice      = double.Parse(dt.Rows[i]["settle"].ToString());
            kArr[i].highestPrice  = double.Parse(dt.Rows[i]["highest"].ToString());
            kArr[i].lowestPrice   = double.Parse(dt.Rows[i]["lowest"].ToString());
            kArr[i].volume        = int.Parse(dt.Rows[i]["volume"].ToString());
            kArr[i].amount        = double.Parse(dt.Rows[i]["amount"].ToString());
        }
        return(kArr);
    }
Exemplo n.º 30
0
        /// <summary>
        /// VAR0:=(2*CLOSE+HIGH+LOW)/4;
        /// B:=XMA((VAR0-LLV(LOW,30))/(HHV(HIGH,30)-LLV(LOW,30))*100,12);
        /// 主力做多资金:EMA(B,3),LINETHICK2,COLORWHITE;
        /// </summary>
        /// <param name="kline"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static TimeSeries <ITimeSeriesItem <double> > indicator_fund_main1(this KLine kline, int begin = 0, int end = 0, PropertyDescriptorCollection param = null)
        {
            TimeSeries <ITimeSeriesItem <double> > close = kline.Select <double>("CLOSE", begin, end);
            TimeSeries <ITimeSeriesItem <double> > open  = kline.Select <double>("OPEN", begin, end);
            TimeSeries <ITimeSeriesItem <double> > high  = kline.Select <double>("HIGH", begin, end);
            TimeSeries <ITimeSeriesItem <double> > low   = kline.Select <double>("LOW", begin, end);
            TimeSeries <ITimeSeriesItem <double> > VAR0  = (close * 2.0 + open + low) / 4;


            TimeSeries <ITimeSeriesItem <double> > t1 = VAR0 - low.LLV(30);
            TimeSeries <ITimeSeriesItem <double> > t2 = high.HHV(30) - low.LLV(30);

            TimeSeries <ITimeSeriesItem <double> > t3 = (t1 / t2) * 100;

            TimeSeries <ITimeSeriesItem <double> > B = t3.XMA(12);

            TimeSeries <ITimeSeriesItem <double> > results = B.EMA(3);

            return(results);
        }
Exemplo n.º 31
0
        /// <summary>
        /// 生成MACD
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button10_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }
            SecurityPropertiesSet securities = repository.Securities;
            List <String>         codes      = securities.Codes;
            int num = 0;

            foreach (String code in codes)
            {
                if (code == null || code == "")
                {
                    continue;
                }
                TimeSerialsDataSet tsd = repository[code];
                if (tsd == null)
                {
                    continue;
                }
                KLine dayLine = tsd.DayKLine;
                if (dayLine != null)
                {
                    tsd.Create("macd", TimeUnit.day, checkBox1.Checked);
                }
                KLine weekLine = tsd.WeekKLine;
                if (weekLine != null)
                {
                    tsd.Create("macd", TimeUnit.week, checkBox1.Checked);
                }
                if (tsd == null || tsd.DayKLine == null || tsd.DayKLine.Count <= 0)
                {
                    continue;
                }
                showText(code + "...");
            }
        }