示例#1
0
        public void Delete(string Name)
        {
            stockInfo stock = CodeManager.Instance.GetNameFromInfo(Name);

            for (int i = 0; i < setRealRegs.Count; i++)
            {
                if (setRealRegs[i].Delete(stock.stockCode) == 0)
                {
                    break;
                }
            }
            int FirstCheck = 0;

            for (int i = 0; i < setRealRegs.Count; i++)
            {
                if (setRealRegs[i].Count() == 0)
                {
                    FirstCheck++;
                }
            }

            if (FirstCheck != MonitorMaxCount - 1)
            {
                sRealType = "0";
            }
        }
        private parameterPair getBestParameters(stockInfo stock)
        {
            double        max                  = -10;
            parameterPair bestPara             = new parameterPair();
            double        k1Max                = 0;
            double        k2Max                = 0;
            double        trailingParameterMax = 0;
            var           myTradeDays          = dateRepo.GetStockTransactionDate(stock.startDate, stock.endDate);
            Dictionary <DateTime, parameterPair> parameters = new Dictionary <DateTime, parameterPair>();

            for (double k1 = 1; k1 <= 3; k1 = k1 + 0.2)
            {
                for (double k2 = 1; k2 <= 3; k2 = k2 + 0.2)
                {
                    for (double trailingParameter = 0.004; trailingParameter <= 0.03; trailingParameter = trailingParameter + 0.002)
                    {
                        parameters = new Dictionary <DateTime, parameterPair>();
                        foreach (var date in myTradeDays)
                        {
                            parameterPair para = new parameterPair();
                            para.parameter1         = k1;
                            para.parameter2         = k2;
                            para.parameter3         = trailingParameter;
                            para.date               = date;
                            para.strategy           = "DualTrust";
                            para.code               = stock.code;
                            para.existGoodParameter = true;
                            parameters.Add(date, para);
                        }
                        List <netvalueDaily>       nv = new List <netvalueDaily>();
                        List <OneByOneTransaction> transactionData = new List <OneByOneTransaction>();
                        dualTrust(stock, parameters, ref nv, ref transactionData);
                        double sharpe = Utilities.strategyPerformance.sharpeRatioByDailyNetValue(nv.Select(s => s.netvalue).ToList());
                        if (sharpe > max)
                        {
                            max   = sharpe;
                            k1Max = k1;
                            k2Max = k2;
                            trailingParameterMax = trailingParameter;
                            //Console.WriteLine("sharpe:{0}, k1:{1}, k2:{2}, trailing:{3}", max, k1Max, k2Max, trailingParameterMax);
                        }
                    }
                }
            }
            bestPara.parameter1 = k1Max;
            bestPara.parameter2 = k2Max;
            bestPara.parameter3 = trailingParameterMax;
            bestPara.strategy   = "DualTrust";
            bestPara.code       = stock.code;
            bestPara.bestSharpe = max;
            if (max > 0)
            {
                bestPara.existGoodParameter = true;
            }
            else
            {
                bestPara.existGoodParameter = false;
            }
            return(bestPara);
        }
 /*
  * add stock into the dictionary with initail shares 1000 and up-to-date price from Yahoo.
  * This function is private. Use writeNewStockData() to both add new stock in memory and file
  */
 public bool addToTheStockList(string stockName)
 {
     stockInfo info = new stockInfo();
     info.price = getPriceFromYahoo(stockName);
     if (info.price != null)
     {
         info.shares = 1000;
         this.m_stocksDictionary.Add(stockName, info);
         return true;
     }
     return false;
 }
示例#4
0
        private stockInfo getStockByName(string name, DateTime dt_st, DateTime dt_et, BathDBDataContext db)
        {
            stockInfo stockinfo        = new stockInfo(0, 0);
            double    number_Ins       = 0;
            double    money_Ins        = 0;
            double    number_Outs      = 0;
            double    number_OrderOuts = 0;
            double    number_pans      = 0;
            double    number_Total     = 0;
            double    unitPrice        = 0;
            var       mainStock        = db.Stock.FirstOrDefault(x => x.main != null && x.main.Value);

            var name_stockIns = db.StockIn.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date >= dt_st && x.date <= dt_et);

            if (name_stockIns.Any())
            {
                number_Ins = name_stockIns.Sum(x => x.amount).Value;
                money_Ins  = name_stockIns.Sum(x => x.money).Value;
                if (number_Ins != 0)
                {
                    unitPrice = Math.Round(money_Ins / number_Ins, 2);
                }
            }

            var name_stockOuts = db.StockOut.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date <= dt_et && x.date >= dt_st);

            if (name_stockOuts.Any())
            {
                number_Outs = MConvert <double> .ToTypeOrDefault(name_stockOuts.Sum(x => x.amount), 0);
            }

            var name_orderStockOuts = db.OrderStockOut.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date <= dt_et && x.date >= dt_st);

            if (name_orderStockOuts.Any())
            {
                number_OrderOuts = MConvert <double> .ToTypeOrDefault(name_orderStockOuts.Sum(x => x.amount), 0);
            }

            var name_pans = db.Pan.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date <= dt_et && x.date >= dt_st);

            if (name_pans.Any())
            {
                number_pans = MConvert <double> .ToTypeOrDefault(name_pans.Sum(x => x.amount), 0);
            }

            number_Total = number_Ins + number_pans - number_Outs - number_OrderOuts;

            stockinfo.stockleft  = number_Total;
            stockinfo.unitPrice  = unitPrice;
            stockinfo.totalMoney = Math.Round(number_Total * unitPrice, 2);
            return(stockinfo);
        }
        //算出一年的最优参数,给后面N天使用
        private double rollingByTime(stockInfo stock, int trainingSetDuration = 120, int testSetDuration = 10)
        {
            stockInfo stockRollInfo = new stockInfo();
            Dictionary <DateTime, parameterPair> parameters = new Dictionary <DateTime, parameterPair>();
            DateTime startDate   = stock.startDate;
            DateTime endDate     = stock.endDate;
            var      myTradeDays = dateRepo.GetStockTransactionDate(stock.startDate, stock.endDate);
            int      length      = tradedays.Count();

            for (int i = 0; i < length - trainingSetDuration; i = i + testSetDuration)
            {
                DateTime trainStart     = tradedays[i];
                DateTime trainEnd       = tradedays[i + trainingSetDuration];
                int      testStartIndex = i + trainingSetDuration + 1;
                int      testEndIndex   = i + trainingSetDuration + testSetDuration;
                if (i == 0)
                {
                    testStartIndex = 0;
                }
                if (testEndIndex >= length)
                {
                    testEndIndex = length - 1;
                }
                stockRollInfo.code      = stock.code;
                stockRollInfo.startDate = trainStart;
                stockRollInfo.endDate   = trainEnd;
                var bestPara = getBestParameters(stockRollInfo);
                Console.WriteLine("start:{0}, end:{1}, bestSharpe:{2}, para1:{3}, para2:{4}, para3:{5}", trainStart, trainEnd, bestPara.bestSharpe, bestPara.parameter1, bestPara.parameter2, bestPara.parameter3);
                for (int j = testStartIndex; j <= testEndIndex; j++)
                {
                    parameterPair para = new parameterPair();
                    para.code               = stock.code;
                    para.date               = tradedays[j];
                    para.parameter1         = bestPara.parameter1;
                    para.parameter2         = bestPara.parameter2;
                    para.parameter3         = bestPara.parameter3;
                    para.strategy           = bestPara.strategy;
                    para.existGoodParameter = bestPara.existGoodParameter;
                    parameters.Add(para.date, para);
                }
            }
            List <netvalueDaily>       nv = new List <netvalueDaily>();
            List <OneByOneTransaction> transactionData = new List <OneByOneTransaction>();

            dualTrust(stock, parameters, ref nv, ref transactionData);
            double sharpe = Utilities.strategyPerformance.sharpeRatioByDailyNetValue(nv.Select(s => s.netvalue).ToList());

            return(sharpe);
        }
示例#6
0
        public ResultInfo Add(string Name)
        {
            ResultInfo result = new ResultInfo
            {
                Code = 0,
                Msg  = "더 이상 등록 될 수 없습니다."
            };

            int  i          = 0;
            bool bRegiCheck = false;
            int  Monitor    = 0;
            int  FirstCheck = 0;

            for (i = 0; i < setRealRegs.Count; i++)
            {
                int cnt = setRealRegs[i].Count();
                if (bRegiCheck == false && cnt <= 200)
                {
                    Monitor    = i;
                    bRegiCheck = true;
                }
                if (cnt == 0)
                {
                    FirstCheck++;
                }
            }

            if (i == MonitorMaxCount - 1 && bRegiCheck == false)                       // 모니터갯수 20개 모두 200개의 종목 꽉 찼을 때
            {
                return(result);
            }

            if (FirstCheck != MonitorMaxCount - 1)
            {
                sRealType = "1";
            }

            stockInfo stock = CodeManager.Instance.GetNameFromInfo(Name);

            setRealRegs[Monitor].Add(stock, sRealType);

            string sMonitor = (Monitor + 1).ToString("D4");

            result.Code = 1;
            result.Msg  = sMonitor + "에 등록 되었습니다.";

            return(result);
        }
        //获取股票近三年列表信息
        private List <stockInfo> searchAllStocks(string stockBorad, DateTime startDate, DateTime endDate)
        {
            List <stockInfo> info       = new List <stockInfo>();
            WindReader       windReader = new WindReader();
            var dt = windReader.GetSectorconstituentByDate(stockBorad, startDate);

            foreach (DataRow dr in dt.Rows)
            {
                stockInfo stock = new stockInfo();
                stock.code      = dr[1].ToString();
                stock.startDate = startDate;
                stock.endDate   = endDate;
                info.Add(stock);
                break;
            }
            return(info);
        }
        public trendT0(StockMinuteRepository stockMinutelyRepo, StockDailyRepository stockDailyRepo, string stockBoard, DateTime startDate, DateTime endDate)
        {
            this.stockDailyRepo    = stockDailyRepo;
            this.stockMinutelyRepo = stockMinutelyRepo;
            dateRepo        = new TransactionDateTimeRepository(ConnectionType.Default);
            sqlWriter       = new SqlServerWriter(ConnectionType.Server84);
            sqlReader       = new SqlServerReader(ConnectionType.Local);
            this.stockBoard = stockBoard;
            this.startDate  = startDate;
            this.endDate    = endDate;
            this.tradedays  = dateRepo.GetStockTransactionDate(startDate, endDate);
            var list = searchAllStocks(stockBoard, startDate, endDate);

            list = new List <stockInfo>();
            stockInfo stock = new stockInfo();

            stock.code      = "IF.CFE";
            stock.startDate = startDate;
            stock.endDate   = endDate;
            list.Add(stock);
            getAllStocks(list);
            computeOnAllStocks(list);
        }
        private bool dualTrust(stockInfo stock, Dictionary <DateTime, parameterPair> parameters, ref List <netvalueDaily> nv, ref List <OneByOneTransaction> transactionData)
        {
            if (allStocks.ContainsKey(stock.code) == false)
            {
                return(false);
            }
            var    data        = allStocks[stock.code];
            double cash        = 10000;
            double position    = 0;
            var    myTradeDays = dateRepo.GetStockTransactionDate(stock.startDate, stock.endDate);
            OneByOneTransaction transaction = new OneByOneTransaction();
            //观察期限30分钟
            int duration = 30;
            int minutes  = 240;

            foreach (var date in myTradeDays)
            {
                if (data.ContainsKey(date) == false || parameters.ContainsKey(date) == false)
                {
                    return(false);
                }
                var    stockToday = data[date];
                var    para       = parameters[date];
                double k1         = para.parameter1;
                double k2         = para.parameter2;
                double trailing   = para.parameter3;
                double maxProfit  = 0;
                bool   tradable   = true;
                if (para.existGoodParameter == false)
                {
                    tradable = false;
                }
                //通过每日前30分钟计算指标
                double HH         = 0;     //最高价的最高价
                double HC         = 0;     //收盘价的最高价
                double LC         = 99999; //收盘价的最低价
                double LL         = 99999; //最低价的最低价
                double Range      = 0;
                double longPoint  = -1;
                double shortPoint = -1;
                for (int j = 0; j < duration; j++)
                {
                    var dataNow = stockToday[j];
                    if (dataNow.High > HH)
                    {
                        HH = dataNow.High;
                    }
                    if (dataNow.Close > HC)
                    {
                        HC = dataNow.Close;
                    }
                    if (dataNow.Close < LC)
                    {
                        LC = dataNow.Close;
                    }
                    if (dataNow.Low < LL)
                    {
                        LL = dataNow.Low;
                    }
                }
                Range      = Math.Max(HH - LC, HC - LL);
                longPoint  = stockToday[duration].Open + k1 * Range;
                shortPoint = stockToday[duration].Open - k2 * Range;
                for (int j = duration; j < minutes; j++)
                {
                    var    dataNow  = stockToday[j];
                    var    dataLast = stockToday[j - 1];
                    double avgPrice = dataNow.Close;
                    if (dataNow.Volume == 0)
                    {
                        tradable = false;
                    }
                    else
                    {
                        avgPrice = dataNow.Amount / dataNow.Volume / multiple;
                        if (para.existGoodParameter == true)
                        {
                            tradable = true;
                        }
                    }
                    if (position == 0 && j <= minutes - 10 && tradable)
                    {
                        //多头信号
                        if (dataNow.Open > longPoint && dataLast.Open < longPoint)
                        {
                            position              = 0.9 * Math.Floor(cash * 1000 / avgPrice) / 1000;
                            cash                  = cash - avgPrice * position - avgPrice * position * slipRatio;
                            transaction           = new OneByOneTransaction();
                            transaction.position  = position;
                            transaction.openTime  = dataNow.DateTime;
                            transaction.openPrice = avgPrice;
                            maxProfit             = 0;
                        }
                        //空头信号
                        else if (dataNow.Open < shortPoint && dataLast.Open > shortPoint)
                        {
                            position              = -0.9 * Math.Floor(cash * 1000 / avgPrice) / 1000;
                            cash                  = cash - avgPrice * position + avgPrice * position * slipRatio;
                            transaction           = new OneByOneTransaction();
                            transaction.position  = position;
                            transaction.openTime  = dataNow.DateTime;
                            transaction.openPrice = avgPrice;
                            maxProfit             = 0;
                        }
                    }
                    else if (position != 0 && j <= minutes - 5 && tradable) //非收盘前5分钟,按追踪止损平仓
                    {
                        if (position > 0)
                        {
                            if ((dataNow.Open / transaction.openPrice - 1) < maxProfit - trailing)
                            {
                                cash     = cash + avgPrice * position - avgPrice * position * slipRatio;
                                position = 0;
                                transaction.closePrice  = avgPrice;
                                transaction.closeTime   = dataNow.DateTime;
                                transaction.closeStatus = "追踪止损";
                                transactionData.Add(transaction);
                                transaction = new OneByOneTransaction();
                            }
                        }
                        if (position < 0)
                        {
                            if ((transaction.openPrice / dataNow.Open - 1) < maxProfit - trailing)
                            {
                                cash     = cash + avgPrice * position + avgPrice * position * slipRatio;
                                position = 0;
                                transaction.closePrice  = avgPrice;
                                transaction.closeTime   = dataNow.DateTime;
                                transaction.closeStatus = "追踪止损";
                                transactionData.Add(transaction);
                                transaction = new OneByOneTransaction();
                            }
                        }
                    }
                    else if (position != 0 && j > minutes - 5 && tradable)//收盘前5分钟强制平仓
                    {
                        if (position > 0)
                        {
                            cash     = cash + avgPrice * position - avgPrice * position * slipRatio;
                            position = 0;
                            transaction.closePrice  = avgPrice;
                            transaction.closeTime   = dataNow.DateTime;
                            transaction.closeStatus = "收盘强平";
                            transactionData.Add(transaction);
                            transaction = new OneByOneTransaction();
                        }
                        if (position < 0)
                        {
                            cash     = cash + avgPrice * position + avgPrice * position * slipRatio;
                            position = 0;
                            transaction.closePrice  = avgPrice;
                            transaction.closeTime   = dataNow.DateTime;
                            transaction.closeStatus = "收盘强平";
                            transactionData.Add(transaction);
                            transaction = new OneByOneTransaction();
                        }
                    }

                    //计算追踪止损的参数
                    if (position > 0)
                    {
                        if ((dataNow.Close / transaction.openPrice - 1) > maxProfit)
                        {
                            maxProfit = (dataNow.Close / transaction.openPrice - 1);
                        }
                    }
                    if (position < 0)
                    {
                        if ((transaction.openPrice / dataNow.Close - 1) > maxProfit)
                        {
                            maxProfit = (transaction.openPrice / dataNow.Close - 1);
                        }
                    }
                    if (j == minutes - 1)
                    {
                        dataNow = stockToday[j];
                        netvalueDaily nvToday = new netvalueDaily();
                        nvToday.date     = dataNow.DateTime.Date;
                        nvToday.netvalue = cash + position * dataNow.Close;
                        nv.Add(nvToday);
                    }
                }
            }
            return(true);
        }
 /*
  * get stock's information from the disk
  * only used when server is shut down and restar again
  */
 public bool getStockDataFromFile(String FileName)
 {
     try
     {
         using (StreamReader reader = new StreamReader(FileName))
         {
             string line;
             while ((line = reader.ReadLine()) != null)
             {
                 string[] words = line.Split(' ');
                 stockInfo info = new stockInfo();
                 info.price = words[1];
                 info.shares = Convert.ToInt32(words[2]);
                 stocksDictionary.Add(words[0], info);
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         return false;
     }
     return true;
 }
示例#11
0
        public void onReceiveRealData(object sender, AxKHOpenAPILib._DKHOpenAPIEvents_OnReceiveRealDataEvent e)
        {
            if (e.sRealType == "주식체결")
            {
                #region FID
                //[20] = 체결시간
                //[10] = 현재가
                //[11] = 전일대비
                //[12] = 등락율
                //[27] = (최우선) 매도호가
                //[28] = (최우선)매수호가
                //[15] = 거래량
                //[13] = 누적거래량
                //[14] = 누적거래대금
                //[16] = 시가
                //[17] = 고가
                //[18] = 저가
                //[25] = 전일대비기호
                //[26] = 전일거래량대비(계약, 주)
                //[29] = 거래대금증감
                //[30] = 전일거래량대비(비율)
                //[31] = 거래회전율
                //[32] = 거래비용
                //[228] = 체결강도
                //[311] = 시가총액(억)
                //[290] = 장구분
                //[691] = KO접근도
                //[567] = 상한가발생시간
                //[568] = 하한가발생시간
                #endregion

                stockInfo     stock      = CodeManager.Instance.GetCodeFromInfo(e.sRealKey);
                DateTime      stockTime  = DateTime.ParseExact(axKHOpenAPI1.GetCommRealData(e.sRealKey, 20), "HHmmss", System.Globalization.CultureInfo.InvariantCulture); // 체결시간
                long          stockPrice = long.Parse(axKHOpenAPI1.GetCommRealData(e.sRealKey, 10));                                                                       // 현재가
                long          volume     = long.Parse(axKHOpenAPI1.GetCommRealData(e.sRealKey, 15));                                                                       // 거래량
                StringBuilder sb         = new StringBuilder();
                //sb.AppendFormat("{0} ", stockTime.ToString("HH:mm:ss"));
                //sb.AppendFormat("현재가 : {0}, ", String.Format("{0:#,###}", stockPrice));
                //sb.AppendFormat("거래량 : {0}, ", String.Format("{0:#,###}", volume));
                //Console.WriteLine(sb.ToString());
                try
                {
                    sb.Clear();
                    sb.Append("select * from LiveTable where ");
                    sb.AppendFormat("SignTime = '{0}' ", stockTime.ToString("HH:mm:ss"));
                    sb.AppendFormat("and SignCode = '{0}' ", e.sRealKey);
                    sb.AppendFormat("and SignCodeName = '{0}' ", stock.stockName);

                    DataTable dt  = ADBEngine.Instance.fc_SqlDataAdapterQuery(sb.ToString());
                    int       Cnt = 0;
                    if (dt != null)
                    {
                        Cnt = dt.Rows.Count;
                        if (Cnt >= 2)                                    // 2개 이상은 저장안함
                        {
                            return;
                        }
                    }

                    sb.Clear();
                    sb.Append("insert into LiveTable  ");
                    sb.Append("(SignTime, SignCode, SignCodeName, SignPrice, SignPriceValue, SignPriceIdx,SignDate) VALUES(");
                    sb.AppendFormat("'{0}', ", stockTime.ToString("HH:mm:ss"));
                    sb.AppendFormat("'{0}', ", e.sRealKey);
                    sb.AppendFormat("'{0}', ", stock.stockName);
                    sb.AppendFormat("'{0}', ", String.Format("{0:#,###}", stockPrice));
                    sb.AppendFormat("'{0}', ", String.Format("{0:#,###}", volume));
                    sb.AppendFormat("{0}, ", Cnt);
                    sb.AppendFormat("'{0}') ", sDateTime);

                    ADBEngine.Instance.ExecuteNoneQuery(sb.ToString());
                    List <string> Data = new List <string>();
                    string[]      row  = new string[] { stockTime.ToString("HH:mm:ss"), e.sRealKey, stock.stockName, String.Format("{0:#,###}", stockPrice), String.Format("{0:#,###}", volume) };

                    ds1(row);
                    if (String.IsNullOrEmpty(SelectName))
                    {
                        return;
                    }
                    if (SelectName != stock.stockName)
                    {
                        return;
                    }
                    row = new string[] { stockTime.ToString("HH:mm:ss"), e.sRealKey, stock.stockName, String.Format("{0:#,###}", stockPrice), String.Format("{0:#,###}", volume) };

                    ds2(row);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("DB 관련 에러 남");
                }
            }
        }
示例#12
0
        private stockInfo getStockByName(string name, DateTime  dt_st,   DateTime dt_et, BathDBDataContext db)
        {
            stockInfo stockinfo=new stockInfo(0,0);
            double number_Ins = 0;
            double money_Ins=0;
            double number_Outs = 0;
            double number_OrderOuts = 0;
            double number_pans = 0;
            double number_Total = 0;
            double unitPrice=0;
            var mainStock = db.Stock.FirstOrDefault(x => x.main != null && x.main.Value);

            var name_stockIns = db.StockIn.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date >= dt_st && x.date <= dt_et);
            if (name_stockIns.Any())
            {
                number_Ins = name_stockIns.Sum(x => x.amount).Value;
                money_Ins=name_stockIns.Sum(x=>x.money).Value;
                if (number_Ins != 0)
                    unitPrice = Math.Round(money_Ins / number_Ins, 2);
            }

            var name_stockOuts = db.StockOut.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date <= dt_et&&x.date>=dt_st);
            if (name_stockOuts.Any())
                number_Outs = MConvert<double>.ToTypeOrDefault(name_stockOuts.Sum(x => x.amount), 0);

            var name_orderStockOuts = db.OrderStockOut.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date <= dt_et&&x.date>=dt_st);
            if (name_orderStockOuts.Any())
                number_OrderOuts = MConvert<double>.ToTypeOrDefault(name_orderStockOuts.Sum(x => x.amount), 0);

            var name_pans = db.Pan.Where(x => x.stockId == mainStock.id && x.name == name).Where(x => x.amount != null).Where(x => x.date <= dt_et&&x.date>=dt_st);
            if (name_pans.Any())
                number_pans = MConvert<double>.ToTypeOrDefault(name_pans.Sum(x => x.amount), 0);

            number_Total = number_Ins + number_pans - number_Outs - number_OrderOuts;

            stockinfo.stockleft=number_Total;
            stockinfo.unitPrice=unitPrice;
            stockinfo.totalMoney=Math.Round(number_Total*unitPrice,2);
            return stockinfo;
        }