public double handleFragCandle(BarData candle)
        {
            double arValue = 0;

            // cp the previous candle list
            List<BarData> cpList = new List<BarData>();
            cpList.AddRange(initCandleList);
            cpList.RemoveAt(0);
            cpList.Add(candle);

            // Within N day(s)(H-C) accumulation
            double sumOfHC = 0;
            // Within N day(s)(O-L) accumulation
            double sumOfOL = 0;

            // Within N day(s)(H-CY) accumulation
            double sumOfHCY = 0;
            // Within N day(s)(CY-L) accumulation
            double sumOfCYL = 0;

            BarData prevCandle = new BarData();
            foreach (BarData c in cpList) {

            // calculate AR
            double tmp = c.High - c.Open;
            sumOfHC = sumOfHC + (tmp);

            tmp = c.Open-c
                    .Low;
            sumOfOL = sumOfOL+(tmp);

            // calculate BR
            tmp = c.High-prevCandle.Close;
            sumOfHCY = sumOfHCY+(tmp);

            tmp = prevCandle.Close-c.Low;
            sumOfCYL = sumOfCYL+(tmp);

            prevCandle = c;
            }

            double ar = sumOfHC / sumOfOL * 100;
            double br = sumOfHCY/sumOfCYL*100;

            double ardouble = Double.Parse(String.Format("{0:00.00000}", ar));

            double brdouble = Double.Parse(String.Format("{0:00.00000}", br));

            Dictionary<string,double> additionalIndValue =new Dictionary<string,double>();
            additionalIndValue.Add(AR, ardouble);
            additionalIndValue.Add(BR, brdouble);
            candle.Ar = ardouble;
            candle.Br = brdouble;

            return arValue;
        }
        public double handleFullCandle(ref BarData candle, int field)
        {
            if (!this.isInitialized)
            {
                this.initCandleList.Add(candle);
                if (initCandleList.Count == this.n)
                {
                    isInitialized = true;
                }
                return 0;
            }

            if (initCandleList.Count >= this.n)
            {
                initCandleList.RemoveAt(0);
            }
            this.initCandleList.Add(candle);

            double[] arr = this.getHighLowest(initCandleList);
            double highest = arr[0];
            double lowest = arr[1];

            // [( N期内Highest Price - 当期Close) / (N期内Highest Price-n期内Lowest price)] * (-100)
            double tmp1 = highest - candle.Close;
            //Console.WriteLine(" tmp1  " + tmp1 +"  " + candle.Close);
            double tmp2 = highest - lowest;
            //Console.WriteLine(" tmp2  " + tmp2);
            double wr = (tmp1 / tmp2) * (100);
            //Console.WriteLine(" wr "+wr);

            switch (field)
            {
                case 1:
                    candle.Wr = wr;
                    break;
                case 2:
                    candle.Wr2= wr;
                    break;
            }
            return wr;
        }
        public static bool EncodeSaveFile(string path, BarData[] bars)
        {
            using (StreamWriter writer = new StreamWriter(path))
            {
                //ICrypta crypta = SecurityService.GetCrypta();
                lock (writer)
                {
                    foreach (BarData bar in bars)
                    {
                        if (bar.HasDataValues)
                        {
                            DateTime start = System.DateTime.Now;

                            StringBuilder sb = new StringBuilder( bar.DateTime.Day.ToString());
                            sb.Append( ".").Append( bar.DateTime.Month.ToString() );
                            sb.Append(".").Append(bar.DateTime.Year.ToString());
                            sb.Append(",").Append(bar.DateTime.Hour.ToString("00")).Append(":").Append(bar.DateTime.Minute.ToString("00"));

                            sb.Append(",").Append(bar.Open.ToString() );
                            sb.Append(",").Append(bar.Close.ToString());
                            sb.Append(",").Append( bar.Low.ToString() );
                            sb.Append(",").Append(bar.High.ToString());

                            //sb.Append(",").Append(bar.Arrow.ToString());

                         //   string endata =crypta.localEncrypt(sb.ToString());
                        //    writer.WriteLine(endata);
                            //}
                            DateTime end = System.DateTime.Now;
                            Console.WriteLine(" start  " + start);

                            Console.WriteLine(" end  " + end);
                            Console.WriteLine(" use @@@@@@@@@@@@@@@@  " + (end.Subtract(start)));
                        }
                    }
                    writer.Close();
                }
                //crypta = null;
            }
            return true;
        }
        /**
         *
         * @param first
         * @return
         */
        private double init(BarData first)
        {
            // Calculate第一个值

            // 初始化的时候,Since positionArea = 1,所以取Lowest price
            prevEPrice = first.High;
            prevSAR    = first.Low;

            // <---------------为下一个蜡烛Calculate --------------------->
            prevAccFactor = maxAccFactor;

            // 记录当期的Highest Price和Lowest price
            maxEPrice = minEPrice = prevEPrice;

            lastNCandleHigh.Add(prevEPrice);
            lastNCandleLow.Add(prevSAR);

            isInitialized = true;

            //IndValue contrainer = new IndValue(first);
            //contrainer.setIndValue(prevSAR);

            return(prevSAR);
        }
        /// <summary>
        /// The bar will encompas the values of the input ones, extending its values where needed.
        /// </summary>
        public static BarData CombinedBar(BarData[] bars)
        {
            BarData result = bars[0];

            double _volumeSum = 0;
            foreach (BarData bar in bars)
            {
                result._low = Math.Min(bar.Low, result.Low);
                result._high = Math.Max(bar.High, result.High);
                _volumeSum += bar.Volume;
            }

            result._close = bars[bars.Length - 1].Close;
            result._volume = _volumeSum / (float)bars.Length;

            return result;
        }
        public double handleFullCandle(ref BarData candle)
        {
            if (!isInitialized)
            {
                initCandleList.Add(candle);

                if (initCandleList.Count == this.initCandleSize)
                {
                    initial(initCandleList);
                    initCandleList = null;
                }

                return 0;
            }

            double diff = candle.Close - prevPrice;

            double avgGain = 0D;
            double avgLoss = 0D;

            double currentGain = 0D;
            double currentLoss = 0D;

            if (diff > 0)
            {
                currentGain = Math.Abs(diff);
            }
            else
            {
                currentLoss = Math.Abs(diff);
            }

            if (isFirst)
            {// 第一个RSI
                initTotalGain = initTotalGain + currentGain;
                initTotalLoss = initTotalLoss + currentLoss;

                // First Average Gain = Total of Gains during past 14 periods / 14
                avgGain = initTotalGain/n;
                // First Average Loss = Total of Losses during past 14 periods / 14
                avgLoss = initTotalLoss/n;
                isFirst = false;
            }
            else
            {
                // Average Gain = [(previous Average Gain) x 13 + current Gain] / 14
                //avgGain = prevAvgGain.multiply(new BigDecimal(n - 1)).add(
                //        currentGain).divide(new BigDecimal(n), SCALE, RMODE);
                avgGain = (prevAvgGain * (n - 1) + currentGain)/n;
                // Average Loss = [(previous Average Loss) x 13 + current Loss] / 14
                //avgLoss = prevAvgLoss.multiply(new BigDecimal(n - 1)).add(
                //        currentLoss).divide(new BigDecimal(n), SCALE, RMODE);
                avgLoss = (prevAvgLoss * (n - 1) + currentLoss)/n;
            }

            prevAvgGain = avgGain;
            prevAvgLoss = avgLoss;

            // RS = Average Gain / Average Loss
            double rs = avgGain/avgLoss;
            // RSI = 100 - 100/(1 + RS)
            Double rsi = 100-(100/(1+rs));

            rsi = Double.Parse(String.Format("{0:00.00000}", rsi));

            prevPrice = candle.Close;
            candle.Rsi = rsi;

            return rsi;
        }
 /**
  * get the middle price,there are 4 kind of arithmetic.
  *
  * 1、M=(2C+H+L)÷4 2、M=(C+H+L+O)÷4 3、M=(C+H+L)÷3 4、M=(H+L)÷2 we are now using
  * the second one : M=(C+H+L+O)÷4
  *
  * @param candle
  * @return
  */
 private double getMiddlePrice(BarData candle)
 {
     double middle = candle.Close;
     middle = middle + candle.High + candle.Low + candle.Open;
     middle = middle / 4;
     return middle;
 }
        public bool SaveCdlFile(string fpath, BarData [] barDatas , bool isEncrypt )
        {
            try
               {
               using (StreamWriter writer = new StreamWriter(fpath, false))
               {

                        int i = 0;
                       DateTime start = System.DateTime.Now;
                       Console.WriteLine(" start  " + start);
                       foreach (BarData bar in barDatas)
                       {
                           if (bar.HasDataValues)
                           {
                               StringBuilder sb = new StringBuilder(bar.DateTime.ToString("yyyy-MM-dd HH:mm"));
                               sb.Append(",").Append(bar.Open.ToString());
                               sb.Append(",").Append(bar.Close.ToString());
                               sb.Append(",").Append(bar.Low.ToString());
                               sb.Append(",").Append(bar.High.ToString());
                               //string endata = crypta.localEncrypt(sb.ToString());
                               i++;
                               writer.WriteLine(sb.ToString());
                           }
                       }
                       DateTime end = System.DateTime.Now; Console.WriteLine(" end  " + end + "  count   " + i);
                       Console.WriteLine(" use @@@@@@@@@@@@@@@@  " + (end.Subtract(start)));
                       writer.Flush();
                   writer.Close();
                   }
               }
               catch (Exception e)
               {
               Console.WriteLine(" e.StackTrace    " + e.StackTrace);
               return false;
               }
               return true;
        }
        /// <summary>
        /// 
        /// </summary>
        public double[] GetDataValues(BarData.DataValueSourceEnum valueEnum, int startingIndex, int indexCount)
        {
            int count = indexCount;
            if (count == 0)
            {
                count = _dataUnits.Count - startingIndex;
                GeneralHelper.Verify(count >= 0, "Invalid starting index.");
            }

            double[] result = new double[count];
            lock (this)
            {
                for (int i = startingIndex; i < startingIndex + count; i++)
                {
                    result[i - startingIndex] = _dataUnits[i].GetValue(valueEnum);
                }
            }

            return result;
        }
        void DrawOrders(GraphicsWrapper g, int index, PointF drawingPoint, float itemWidth, float itemMargin, 
            List<Order> openingOrders, List<Order> closingOrders, BarData orderBarData, float lastBarX)
        {
            // Width is same as items in real coordinates.
            float actualImageHeight = _imageDown.Height / Math.Abs(g.DrawingSpaceTransform.Elements[3]);

            float yToXScaling = Math.Abs(g.DrawingSpaceTransform.Elements[0] / g.DrawingSpaceTransform.Elements[3]);
            PointF updatedImageDrawingPoint = drawingPoint;
            foreach (Order order in openingOrders)
            {
                DrawOrder(g, ref updatedImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, orderBarData, lastBarX, true);
            }

            foreach (Order order in closingOrders)
            {
                DrawOrder(g, ref updatedImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, orderBarData, lastBarX, false);
            }
        }
        public double handleFullCandle(ref BarData candle)
        {
            //IndValue contrainer = new IndValue(candle);

            // 最初的一 candles
            if (!isInitialized)
            {
                return(this.init(candle));
            }

            // 1: CalculatePrice极值
            double currentEprice = -1;
            double candleLow     = candle.Low;
            bool   isNewLow      = false;
            double candleHigh    = candle.High;
            bool   isNewHigh     = false;

            if (sarArea == AREA_UP)
            {// 多头的时候,拿当前这个阶段的最高的Price
                if (candleHigh > maxEPrice)
                {
                    isNewHigh     = true;
                    currentEprice = candleHigh;

                    if (!turnPoint)
                    {// 在没有区间转变的时候,才能Calculate到本期间的最高值
                        maxEPrice = candleHigh;
                    }
                }
                else
                {
                    currentEprice = maxEPrice;
                }
            }
            else if (sarArea == AREA_DOWN)
            {// 空头的时候,拿当前这个阶段的最低的Price
                if (candleLow < minEPrice)
                {
                    isNewLow      = true;
                    currentEprice = candleLow;
                    if (!turnPoint)
                    {// 在没有区间转变的时候,才能Calculate到本期间的最低值
                        minEPrice = candleLow;
                    }
                }
                else
                {
                    currentEprice = minEPrice;
                }
            }



            // 2: Calculate当前因子
            double currentAccFactor;

            if (turnPoint)
            {// 当前是一个拐点
                currentAccFactor = accFactorIncreatement;
            }
            else if ((sarArea == AREA_UP && isNewHigh) ||
                     (sarArea == AREA_DOWN && isNewLow))
            {// 多头,并且Price创出新的最高的时候|或者空头,并且Price是新低
                currentAccFactor = prevAccFactor + accFactorIncreatement;

                if (currentAccFactor >= maxAccFactor)
                {// 不能超过0.2
                    currentAccFactor = maxAccFactor;
                }
            }
            else
            {// 保持上一个不变
                currentAccFactor = prevAccFactor;
            }

            // 3: Calculate当前的SAR
            double sar = 0;

            if (turnPoint)
            {     // 当前是一个拐点
                if (sarArea == AREA_UP)
                { // 当前是多头,SAR是前N candles的最低值
                    sar = this.getLowestInN();
                }
                else
                {
                    sar = this.getHighestInN();
                }

                minEPrice = candleLow;
                maxEPrice = candleHigh;

                // 下一根是否是拐点
                turnPoint = false;
            }
            else
            {
                // SAR(i) = SAR(i-1)+ACCELERATION(i-1)*(EPRICE(i-1)-SAR(i-1))
                double tmp = prevAccFactor * (prevEPrice - prevSAR);
                sar = prevSAR + tmp;
            }

            //double ttt = TypeFormat.parseDouble(formater.format(sar.doubleValue()));
            //sar = new double(ttt);

            //contrainer.setIndValue(ttt);

            sar = Double.Parse(String.Format(formater, sar));

            candle.Sar = sar;

            prevEPrice    = currentEprice;
            prevSAR       = sar;
            prevAccFactor = currentAccFactor;

            // 为下一 candlesCalculate做准备,主要是,是否是拐点
            if (sarArea == AREA_DOWN && candleHigh > sar)
            {
                turnPoint = true;
                sarArea   = AREA_UP;
            }
            else if (sarArea == AREA_UP && candleLow < sar)
            {
                turnPoint = true;
                sarArea   = AREA_DOWN;
            }

            if (this.lastNCandleHigh.Count >= this.n)
            {
                this.lastNCandleHigh.RemoveAt(0);
            }
            this.lastNCandleHigh.Add(candleHigh);

            if (this.lastNCandleLow.Count >= this.n)
            {
                this.lastNCandleLow.RemoveAt(0);
            }
            this.lastNCandleLow.Add(candleLow);

            // Calculate下一 candles value
            if (turnPoint)
            {     // 当前是一个拐点
                if (sarArea == AREA_UP)
                { // 当前是多头,SAR是上个区间的最低值
                    nextSAR = this.getLowestInN();
                }
                else
                {
                    nextSAR = this.getHighestInN();
                }
            }
            else
            {
                // SAR(i) = SAR(i-1)+ACCELERATION(i-1)*(EPRICE(i-1)-SAR(i-1))
                double tmp = prevAccFactor * (prevEPrice - prevSAR);
                nextSAR = prevSAR + tmp;
            }

            nextSAR = Double.Parse(String.Format(formater, nextSAR));

            //ttt = TypeFormat.parseDouble(formater.format(nextSAR.doubleValue()));
            //nextSAR =ttt;

            return(nextSAR);
        }
        public bool LoadCdlFile(string fileName, int startingRow, int rowsLimit, out List <BarData> datas, bool isDecrypt, bool isLocal)
        {
            datas = new List <BarData>();

            int i = 0;

            using (System.IO.TextReader tr = new System.IO.StreamReader(fileName))
            {
                try
                {
                    for (i = 0; i < startingRow + rowsLimit || rowsLimit == 0; i++)
                    {
                        string lineStr = tr.ReadLine();
                        if (lineStr == null)
                        {
                            break;
                        }

                        if (i >= startingRow)
                        {// Parse.
                         //if (isDecrypt)
                         //{
                         //    if( !isLocal)
                         //        lineStr = crypta.decrypt(lineStr);
                         //    else
                         //        lineStr = crypta.localDecrypt(lineStr);
                         //}

                            try
                            {
                                string[] lineSplit = Regex.Split(lineStr, ",");
                                BarData  barData   = new BarData();
                                string   date      = lineSplit[0].Trim();
                                string   time      = lineSplit[1].Trim();
                                barData.DateTime = new DateTime(int.Parse(date.Substring(0, 4)), int.Parse(date.Substring(4, 2)), int.Parse(date.Substring(6, 2)),
                                                                int.Parse(time.Substring(0, 2)), int.Parse(time.Substring(2, 2)), int.Parse(time.Substring(4, 2))); //DateTime.Parse(lineSplit[0]);//  BarDataHelper.ParseCSVDateTime(lineSplit[0], lineSplit[1]);
                                barData.Open        = double.Parse(lineSplit[2], new System.Globalization.NumberFormatInfo());
                                barData.High        = double.Parse(lineSplit[3], new System.Globalization.NumberFormatInfo());
                                barData.Low         = double.Parse(lineSplit[4], new System.Globalization.NumberFormatInfo());
                                barData.Close       = double.Parse(lineSplit[5], new System.Globalization.NumberFormatInfo());
                                barData.ExLow       = barData.Low;
                                barData.ExHigh      = barData.ExHigh;
                                barData.IsCompleted = true;
                                LogUtil.Info(" His File Loading :::: " + barData);
                                datas.Add(barData);
                            }catch (Exception e) {
                                LogUtil.Info(" His File Loading :::: " + e.StackTrace);
                            }
                        }
                    }
                    Console.WriteLine("ccccccccccccccccccccccccccc  ");
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                    datas.Clear();
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 13
0
        public double handleFullCandle(ref BarData candle, int field)
        {
            //IndValue contrainer = new IndValue(candle);

            double arValue = 0;

            if (initCandleList.Count < this.n)
            {
                initCandleList.Add(candle);
                return(arValue);
            }
            initCandleList.RemoveAt(0);
            initCandleList.Add(candle);

            // Within N day(s)(H-C) accumulation
            double sumOfHC = 0;
            // Within N day(s)(O-L) accumulation
            double sumOfOL = 0;

            // Within N day(s)(H-CY) accumulation
            double sumOfHCY = 0;
            // Within N day(s)(CY-L) accumulation
            double sumOfCYL = 0;
            //Console.WriteLine("  ARBR initCandleList  count  " + initCandleList.Count );
            BarData prevCandle = new BarData();

            foreach (BarData c in initCandleList)
            {
                // calculate AR
                double tmp = c.High - c.Open;
                sumOfHC = sumOfHC + tmp;

                tmp     = c.Open - c.Low;
                sumOfOL = sumOfOL + tmp;

                // calculate BR
                tmp      = c.High - prevCandle.Close;
                sumOfHCY = sumOfHCY + (tmp);

                tmp      = prevCandle.Close - c.Low;
                sumOfCYL = sumOfCYL + tmp;

                prevCandle = c;
                //Console.WriteLine("  ARBR sumOfHO " + sumOfHO + "  sumOfOL " + sumOfOL);
            }


            double ar = sumOfHC / sumOfOL * 100;
            double br = sumOfHCY / sumOfCYL * 100;

            double ardouble = Double.Parse(String.Format("{0:00.00000}", ar));

            double brdouble = Double.Parse(String.Format("{0:00.00000}", br));
            Dictionary <string, double> additionalIndValue = new Dictionary <string, double>();

            additionalIndValue.Add(AR, ardouble);
            additionalIndValue.Add(BR, brdouble);

            arValue = ardouble;


            switch (field)
            {
            case 1:
                candle.Ar = ardouble;
                candle.Br = brdouble;
                break;

            case 2:
                candle.Ar2 = ardouble;
                break;
            }


            return(arValue);
        }
Exemplo n.º 14
0
        public double handleFragCandle(BarData candle)
        {
            double arValue = 0;

            // cp the previous candle list
            List <BarData> cpList = new List <BarData>();

            cpList.AddRange(initCandleList);
            cpList.RemoveAt(0);
            cpList.Add(candle);

            // Within N day(s)(H-C) accumulation
            double sumOfHC = 0;
            // Within N day(s)(O-L) accumulation
            double sumOfOL = 0;

            // Within N day(s)(H-CY) accumulation
            double sumOfHCY = 0;
            // Within N day(s)(CY-L) accumulation
            double sumOfCYL = 0;

            BarData prevCandle = new BarData();

            foreach (BarData c in cpList)
            {
                // calculate AR
                double tmp = c.High - c.Open;
                sumOfHC = sumOfHC + (tmp);

                tmp = c.Open - c
                      .Low;
                sumOfOL = sumOfOL + (tmp);

                // calculate BR
                tmp      = c.High - prevCandle.Close;
                sumOfHCY = sumOfHCY + (tmp);

                tmp      = prevCandle.Close - c.Low;
                sumOfCYL = sumOfCYL + (tmp);

                prevCandle = c;
            }

            double ar = sumOfHC / sumOfOL * 100;
            double br = sumOfHCY / sumOfCYL * 100;

            double ardouble = Double.Parse(String.Format("{0:00.00000}", ar));

            double brdouble = Double.Parse(String.Format("{0:00.00000}", br));



            Dictionary <string, double> additionalIndValue = new Dictionary <string, double>();

            additionalIndValue.Add(AR, ardouble);
            additionalIndValue.Add(BR, brdouble);
            candle.Ar = ardouble;
            candle.Br = brdouble;

            return(arValue);
        }
        public double handleFullCandle(ref BarData candle, int field)
        {
            double cciVal = 0;

            if (initCandleList.Count < this.n)
            {
                initCandleList.Add(candle);
                return(cciVal);
            }

            initCandleList.RemoveAt(0);
            initCandleList.Add(candle);


            //TP = (Hight + Lowt + Closet) / 3
            double tp = (candle.High + candle.Low + candle.Close) / THREE;

            // MA= (TP1 + TP2 +... + TPn) / n
            // MA: The moving average of the typical price.
            // TPn: The typical price for the nth interval.
            // N: Number of intervals for the average.
            double ma = 0;

            for (int i = n - 1; i > this.N - 2; i--)
            {
                // calculate MA
                BarData c = initCandleList[i];
                ma += ((c.High + c.Low + c.Close) / THREE);
            }
            ma = ma / N;


            // MD= (|TPAVG1 - TP1| + ... + |TPAVG1 - TPn |) / n
            // MD: The mean deviation for this interval.
            //TPn: The typical price for the nth interval.
            // N: Number of intervals.
            double md = 0;


            for (int i = n - 1; i > this.N - 2; i--)
            {
                // calculate MD
                BarData c   = initCandleList[i];
                double  tpn = 0;
                tpn = (c.High + c.Low + c.Close) / THREE;
                double tpavg = 0;
                for (int k = i; k > i - this.N; k--)
                {
                    BarData b = initCandleList[k];
                    tpavg += ((b.High + b.Low + b.Close) / THREE);
                }

                tpavg = tpavg / N;
                //Console.WriteLine(" tpavg " + tpavg + " tpn " + tpn );
                md += Math.Abs(tpavg - tpn);
            }

            md = md / N;

            double cci = 0;

            //Console.WriteLine(" tp " + tp + " ma " + ma + " md " + md);

            // CCI = (TP - MA) / (.015 x MD)
            cci = (tp - ma) / (md * FACTOR);

            cciVal = Double.Parse(String.Format("{0:00.00000}", cci));

            switch (field)
            {
            case 1:
                candle.Cci = cciVal;
                break;

            case 2:
                candle.Cci2 = cciVal;
                break;

            case 3:
                candle.Cci3 = cciVal;
                break;
            }
            return(cciVal);
        }
        public bool LoadCdlFile(string fileName, int startingRow, int rowsLimit, out List<BarData> datas,  bool isDecrypt, bool isLocal)
        {
            datas = new List<BarData>();

            int i = 0;

            using (System.IO.TextReader tr = new System.IO.StreamReader(fileName))
            {
                try
                {
                    for (i = 0; i < startingRow + rowsLimit || rowsLimit == 0; i++)
                    {
                        string lineStr = tr.ReadLine();
                        if (lineStr == null)
                        {
                            break;
                        }

                        if (i >= startingRow)
                        {// Parse.
                            //if (isDecrypt)
                            //{
                            //    if( !isLocal)
                            //        lineStr = crypta.decrypt(lineStr);
                            //    else
                            //        lineStr = crypta.localDecrypt(lineStr);
                            //}

                            try
                            {
                                string[] lineSplit = Regex.Split(lineStr, ",");
                                BarData barData = new BarData();
                                string date = lineSplit[0].Trim();
                                string time = lineSplit[1].Trim();
                                barData.DateTime = new DateTime(int.Parse(date.Substring(0, 4)), int.Parse(date.Substring(4, 2)), int.Parse(date.Substring(6, 2)),
                int.Parse(time.Substring(0, 2)), int.Parse(time.Substring(2, 2)), int.Parse(time.Substring(4, 2)));    //DateTime.Parse(lineSplit[0]);//  BarDataHelper.ParseCSVDateTime(lineSplit[0], lineSplit[1]);
                                   barData.Open = double.Parse(lineSplit[2], new System.Globalization.NumberFormatInfo());
                                   barData.High = double.Parse(lineSplit[3], new System.Globalization.NumberFormatInfo());
                                   barData.Low = double.Parse(lineSplit[4], new System.Globalization.NumberFormatInfo());
                                   barData.Close = double.Parse(lineSplit[5], new System.Globalization.NumberFormatInfo());
                                   barData.ExLow = barData.Low;
                                   barData.ExHigh = barData.ExHigh;
                                   barData.IsCompleted = true;
                                   LogUtil.Info(" His File Loading :::: " + barData);
                                   datas.Add(barData);

                            }catch(Exception e ){
                                LogUtil.Info(" His File Loading :::: " + e.StackTrace);
                            }
                        }
                    }
                    Console.WriteLine("ccccccccccccccccccccccccccc  ");
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                    datas.Clear();
                    return false;
                }
            }

            return true;
        }
        public void Process(object sender, ElapsedEventArgs e)
        {
            lock (this)
            {
                if (isUpdateCandle && !isAddCandle && _dataUnits.Count > 0)
                {
                    Dictionary<Interval, IntervalData> currentDatas = dataCache.CurrentDatas;
                    Dictionary<Interval, DateTime> currentTimes = dataCache.CurrentTimes;
                    if (currentDatas.ContainsKey(currentTInterval))
                    {
                        BarData barData;
                        IntervalData intervData = currentDatas[currentTInterval];
                        DateTime currentTime = currentTimes[currentTInterval];
                        Console.WriteLine("  currentTime   " + currentTime);
                        barData = new BarData(currentTime, intervData.Open, intervData.Close, intervData.Min, intervData.Max, 0);
                        barData.SignalList = intervData.SignalList;
                        //barData.RefreshExValues();
                        if (_dataUnits.Count > 0 && _dataUnits[_dataUnits.Count - 1].DateTime.CompareTo(barData.DateTime) == 0)
                        {
                            barData.RefreshExValues();
                            RSI rsi = dataCache.RISs[currentTInterval];
                            RSI rsi2 = dataCache.RISs2[currentTInterval];
                            RSI rsi3 = dataCache.RISs3[currentTInterval];
                            RSI rsi4 = dataCache.RISs4[currentTInterval];
                            SAR sar= dataCache.SARs[currentTInterval];
                            CCI cci = dataCache.CCIs[currentTInterval];
                            CCI cci2 = dataCache.CCIs2[currentTInterval];

                            rsi.handleFullCandle(ref barData, false, 1);
                            rsi2.handleFullCandle(ref barData, false,2);
                            rsi3.handleFullCandle(ref barData, false,3);
                            rsi4.handleFullCandle(ref barData, false,4);
                            cci.handleFragCandle(ref barData,2);
                            cci2.handleFragCandle(ref barData,2);
                            barData.Sar=sar.getNextSAR();
                            LogUtil.Info(" Current Candle   " + barData);
                            _dataUnits[_dataUnits.Count - 1] = barData;
                            dataCache.RISs[currentTInterval]= rsi;
                        }
                    }
                    isUpdateCandle = false;
                }
                else if (isAddCandle)
                {
                    dataCache.GetDataUnits(symbol, currentTInterval, ref _dataUnits);
                    Console.WriteLine("  _dataUnits  " + _dataUnits.Count);
                    isAddCandle = false;
                    //isUpdateCandle = false;
                }
                else if (isUpdateCandleSignal)
                {
                    dataCache.GetDataUnits(symbol, currentTInterval, ref _dataUnits);
                    isUpdateCandleSignal = false;
                }
                else if (isUpdateSignal)
                {
                    dataCache.GetDataUnits(symbol, currentTInterval, ref _dataUnits);
                    Dictionary<Interval, DateTime> currentTimes = dataCache.CurrentTimes;
                    Dictionary<Interval, IntervalData> currentDatas = dataCache.CurrentDatas;
                    if (currentDatas.ContainsKey(currentTInterval))
                    {
                        BarData barData;
                        IntervalData intervData = currentDatas[currentTInterval];
                        DateTime currentTime = currentTimes[currentTInterval];
                        Console.WriteLine("  currentTime   " + currentTime);
                        barData = new BarData(currentTime, intervData.Open, intervData.Close, intervData.Min, intervData.Max, 0);
                        barData.SignalList = intervData.SignalList;
                        if (_dataUnits.Count > 0 && _dataUnits[_dataUnits.Count - 1].DateTime.CompareTo(barData.DateTime) == 0)
                        {
                            barData.RefreshExValues();
                            RSI rsi = dataCache.RISs[currentTInterval];
                            RSI rsi2 = dataCache.RISs2[currentTInterval];
                            RSI rsi3 = dataCache.RISs3[currentTInterval];
                            RSI rsi4 = dataCache.RISs4[currentTInterval];
                            SAR sar = dataCache.SARs[currentTInterval];
                            CCI cci = dataCache.CCIs[currentTInterval];
                            CCI cci2 = dataCache.CCIs2[currentTInterval];

                            rsi.handleFullCandle(ref barData, false, 1);
                            rsi2.handleFullCandle(ref barData, false, 2);
                            rsi3.handleFullCandle(ref barData, false, 3);
                            rsi4.handleFullCandle(ref barData, false, 4);
                            cci.handleFragCandle(ref barData,2);
                            cci2.handleFragCandle(ref barData,2);

                            barData.Sar = sar.getNextSAR();
                            LogUtil.Info(" isUpdateSignal Candle   " + barData);
                            _dataUnits[_dataUnits.Count - 1] = barData;
                        }
                    }
                }

                Console.WriteLine("  _dataUnits  " + _dataUnits.Count);
                isAddCandle = false;
                isUpdateCandle = false;

            }

            if (isPause && DateTime.Now.Subtract(lastActionTime) > TimeSpan.FromMinutes(1))
                isPause = false;

            Console.WriteLine("  isPause   " + isPause);
            //if (!isPause)
            RaiseValuesUpdateEvent(UpdateType.NewBar, 1, 0);
        }
        /**
         *
         * @param first
         * @return
         */
        private double init(BarData first)
        {
            // Calculate第一个值

            // 初始化的时候,Since positionArea = 1,所以取Lowest price
            prevEPrice = first.High;
            prevSAR = first.Low;

            // <---------------为下一个蜡烛Calculate --------------------->
            prevAccFactor = maxAccFactor;

            // 记录当期的Highest Price和Lowest price
            maxEPrice = minEPrice = prevEPrice;

            lastNCandleHigh.Add(prevEPrice);
            lastNCandleLow.Add(prevSAR);

            isInitialized = true;

            //IndValue contrainer = new IndValue(first);
            //contrainer.setIndValue(prevSAR);

            return prevSAR;
        }
        public double handleFullCandle(ref  BarData candle , int field)
        {
            //IndValue contrainer = new IndValue(candle);

            double arValue = 0;

            if (initCandleList.Count < this.n) {
            initCandleList.Add(candle);
            return arValue;
            }
            initCandleList.RemoveAt(0);
            initCandleList.Add(candle);

            // Within N day(s)(H-C) accumulation
            double sumOfHC = 0;
            // Within N day(s)(O-L) accumulation
            double sumOfOL = 0;

            // Within N day(s)(H-CY) accumulation
            double sumOfHCY = 0;
            // Within N day(s)(CY-L) accumulation
            double sumOfCYL = 0;
            //Console.WriteLine("  ARBR initCandleList  count  " + initCandleList.Count );
            BarData prevCandle = new BarData();
            foreach (BarData c in initCandleList) {

            // calculate AR
            double tmp =c.High-c.Open;
            sumOfHC = sumOfHC + tmp;

            tmp = c.Open-c.Low;
            sumOfOL = sumOfOL+tmp;

            // calculate BR
            tmp = c.High-prevCandle.Close;
            sumOfHCY = sumOfHCY+(tmp);

            tmp = prevCandle.Close-c.Low;
            sumOfCYL = sumOfCYL+tmp;

            prevCandle = c;
            //Console.WriteLine("  ARBR sumOfHO " + sumOfHO + "  sumOfOL " + sumOfOL);
            }

            double ar = sumOfHC / sumOfOL * 100;
            double br = sumOfHCY / sumOfCYL * 100;

            double ardouble = Double.Parse(String.Format("{0:00.00000}", ar));

            double brdouble = Double.Parse(String.Format("{0:00.00000}", br));
            Dictionary<string, double> additionalIndValue = new Dictionary<string, double>();
            additionalIndValue.Add(AR, ardouble);
            additionalIndValue.Add(BR, brdouble);

            arValue = ardouble;

            switch (field)
            {
            case 1:
                candle.Ar = ardouble;
                candle.Br = brdouble;
                break;
            case 2:
                candle.Ar2 = ardouble;
                break;
               }

            return arValue;
        }
        public static bool SaveToFile(string path, BarData[] bars)
        {
            using (StreamWriter writer = new StreamWriter(path))
            {
                lock (writer)
                {
                    foreach (BarData bar in bars)
                    {
                        if (bar.HasDataValues)
                        {
                            DateTime start = System.DateTime.Now;

                            StringBuilder sb = new StringBuilder(bar.DateTime.Day.ToString());
                            sb.Append(".").Append(bar.DateTime.Month.ToString());
                            sb.Append(".").Append(bar.DateTime.Year.ToString());
                            sb.Append(",").Append(bar.DateTime.Hour.ToString("00")).Append(":").Append(bar.DateTime.Minute.ToString("00"));
                            sb.Append(",").Append(bar.Open.ToString());
                            sb.Append(",").Append(bar.Close.ToString());
                            sb.Append(",").Append(bar.Low.ToString());
                            sb.Append(",").Append(bar.High.ToString());

                            //sb.Append(",").Append(bar.Arrow.ToString());
                             writer.WriteLine(sb.ToString());
                            //}
                            DateTime end = System.DateTime.Now;
                            Console.WriteLine(" start  " + start );

                            Console.WriteLine(" end  " + end);
                            Console.WriteLine(" use @@@@@@@@@@@@@@@@  " + (end.Subtract(start) ) );
                        }
                    }
                    writer.Close();
                }
            }
            return true;
        }
        /// <summary>
        /// A delta - the value from the previous to the current tick.
        /// This is the same as the MOMENTUM indicator.
        /// </summary>
        public double[] GetDataValuesDeltas(int startingIndex, int indecesLimit, BarData.DataValueSourceEnum valueEnum)
        {
            double[] values = GetDataValues(valueEnum, startingIndex, indecesLimit);

            for (int i = values.Length - 1; i > 0 ; i--)
            {
                values[i] = values[i] - values[i - 1];
            }

            if (values.Length > 0)
            {
                values[0] = 0;
            }

            return values;
        }
 /// <summary>
 /// 
 /// </summary>
 public double[] GetDataValues(BarData.DataValueSourceEnum valueEnum)
 {
     return GetDataValues(valueEnum, 0, _dataUnits.Count);
 }
        private void UpdateIntervalData(Interval intervSpan, ref IntervalData intvData, double[] prices, DateTime time, DataProvider provider)
        {
            if (currentTimes.ContainsKey(intervSpan) && currentDatas.ContainsKey(intervSpan))
            {
                DateTime lastTime = currentTimes[intervSpan];
                DateTime currTime = AppUtil.GetCurrentIntervalTime(lastTime, time, intervSpan);
                TimeSpan span = time.Subtract(lastTime);
                Console.WriteLine("  currentTimes[TInterval.MIN1]  span  " + span + "  lastTime " + lastTime + " real  time " + time + " currTime " + currTime);
                LogUtil.Info("  currentTimes[TInterval.MIN1]  span  " + span + "  lastTime " + lastTime + " real  time " + time + " currTime " + currTime);
                if (lastTime.CompareTo(time) > 0)
                {
                    return;
                }
                else if (span >= AppConst.AppTimeSpans[intervSpan])
                {
                    lastTime = AppUtil.GetLatestIntervalTime(lastTime, time, intervSpan);
                    Console.WriteLine("   span > interval  span:::   " + span + "  lastTime " + lastTime + " real  time " + time);
                    BarData barData = dataUnits[intervSpan][dataUnits[intervSpan].Count - 1];
                    barData.DateTime = lastTime;
                    barData.Open = intvData.Open;
                    barData.Close = intvData.Close;
                    barData.Low = intvData.Min;
                    barData.High = intvData.Max;
                    barData.SignalList = intvData.SignalList;

                    Console.WriteLine(" BarData  #### time " + barData);

                    List<CandleSignal> currSignalList = new List<CandleSignal>();
                    Signal[] signals = null;
                    lock (AppConst.SignalDatasLocker)
                    {
                        signals = new Signal[AppContext.SignalDatas.Count];
                        AppContext.SignalDatas.CopyTo(signals);
                    }
                    if (signals != null)
                    {
                        int count = 0;
                        Array.Sort(signals);
                        foreach (Signal s in signals)
                        {
                            if (s.Symbol == provider.Symbol && s.Interval == provider.CurrentTInterval)
                            {
                                if (s.ActTime.CompareTo(lastTime) == 0 && s.Arrow != 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 1);
                                    if (!barData.SignalList.Contains(cs))
                                        barData.SignalList.Add(cs);
                                }
                                if (s.Arrow != 0 && s.ActTime.CompareTo(currTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 1);
                                    currSignalList.Add(cs);
                                }
                                if (s.StopLoss != 0 && s.StopLossTime.CompareTo(lastTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 3);
                                    if (!barData.SignalList.Contains(cs))
                                        barData.SignalList.Add(cs);
                                }
                                if (s.StopLoss != 0 && s.StopLossTime.CompareTo(currTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 3);
                                    currSignalList.Add(cs);
                                }
                                if (s.GainTip != 0 && s.GainTipTime.CompareTo(lastTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 2);
                                    if (!barData.SignalList.Contains(cs))
                                        barData.SignalList.Add(cs);
                                }
                                if (s.GainTip != 0 && s.GainTipTime.CompareTo(currTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 2);
                                    currSignalList.Add(cs);
                                }
                                if (s.StopGain != 0 && s.StopGainTime.CompareTo(lastTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 4);
                                    if (!barData.SignalList.Contains(cs))
                                        barData.SignalList.Add(cs);
                                }
                                if (s.StopGain != 0 && s.StopGainTime.CompareTo(currTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 4);
                                    currSignalList.Add(cs);
                                }
                                if (count > 5) break;
                                count++;
                            }
                        }
                    }
                    barData.RefreshExValues();
                    Console.WriteLine(" BarData  ############ time " + barData);
                    LogUtil.Info(" Last BarData  #####  " + barData);
                    SAR sar = null;
                    CR cr = null;
                    RSI rsi = null;
                    RSI rsi2 = null;
                    RSI rsi3 = null;
                    RSI rsi4 = null;
                    ARBR arbr = null;
                    ARBR arbr2 = null;
                    CCI cci = null;
                    CCI cci2 = null;
                    CCI cci3 = null;
                    WR wr = null;
                    WR wr2 = null;
                    LWR lwr = null;
                    BOLL boll = null;
                    if (!provider.Initializing && provider.Initialized)
                    {
                        sar = iSARs[intervSpan];
                        cr = iCRs[intervSpan];
                        rsi = iRISs[intervSpan];
                        rsi2 = iRISs2[intervSpan];
                        rsi3 = iRISs3[intervSpan];
                        rsi4 = iRISs4[intervSpan];
                        arbr = iARBRs[intervSpan];
                        arbr2 = iARBRs2[intervSpan];
                        cci = iCCIs[intervSpan];
                        cci2 = iCCIs2[intervSpan];
                        cci3 = iCCIs3[intervSpan];
                        wr = iWRs[intervSpan];
                        wr2 = iWRs2[intervSpan];
                        lwr = iLWRs[intervSpan];
                        boll = iBOLLs[intervSpan];

                        sar.handleFullCandle(ref barData);
                        rsi.handleFullCandle(ref barData, true,1);
                        rsi2.handleFullCandle(ref barData, true,2);
                        rsi3.handleFullCandle(ref barData, true,3);
                        rsi4.handleFullCandle(ref barData, true,4);
                        cr.handleFullCandle(ref barData);
                        arbr.handleFullCandle(ref barData,1);
                        arbr2.handleFullCandle(ref barData,2);
                        cci.handleFullCandle(ref barData,1);
                        cci2.handleFullCandle(ref barData,2);
                        cci3.handleFragCandle(ref barData, 3);
                        wr.handleFullCandle(ref barData,1);
                        wr2.handleFullCandle(ref barData,2);
                        lwr.handleFullCandle(ref barData, 0);
                        boll.handleFullCandle(ref barData, 0);
                    }

                    if (dataUnits.ContainsKey(intervSpan))
                    {
                        dataUnits[intervSpan][dataUnits[intervSpan].Count - 1] = (barData);
                    }
                    else
                    {
                        List<BarData> list = new List<BarData>();
                        list.Add(barData);
                        dataUnits.Add(intervSpan, list);
                    }

                    if (provider.CurrentTInterval == intervSpan)
                    {
                        provider.IsUpdateCandle = false;
                        provider.IsAddCandle = true;
                    }

                    Console.WriteLine(" New BarData  #### time " + currTime);
                    currentTimes[intervSpan] = currTime;
                    Console.WriteLine("  currentTimes[" + intervSpan + "]  " + currentTimes[intervSpan]);
                    Console.WriteLine(" NEW RTD.symbol    time  " + time + " price " + prices[0]);
                    intvData = new IntervalData(0);
                    double p = prices[0];
                    intvData.Max = p;
                    intvData.Min = p;
                    intvData.Open = p;
                    intvData.Close = p;
                    intvData.PriceList.Clear();
                    foreach (double price in prices)
                    {
                        intvData.PriceList.Add(price);
                        intvData.Max = Math.Max(intvData.Max, price);
                        intvData.Min = Math.Min(intvData.Min, price);
                    }

                    barData = new BarData(currTime, intvData.Open, intvData.Close, intvData.Min, intvData.Max, 0);
                    barData.SignalList = currSignalList;
                    barData.RefreshExValues();

                    if (!provider.Initializing && provider.Initialized)
                    {
                        barData.Sar = sar.getNextSAR();
                        rsi.handleFullCandle(ref barData, false, 1);
                        rsi2.handleFullCandle(ref barData, false, 2);
                        rsi3.handleFullCandle(ref barData, false, 3);
                        rsi4.handleFullCandle(ref barData, false, 4);
                        cr.handleFullCandle(ref barData);
                        cci.handleFragCandle(ref barData,2);
                        cci2.handleFragCandle(ref barData,2);

                        iSARs[intervSpan] = sar;
                        iRISs[intervSpan] = rsi;
                        iRISs2[intervSpan] = rsi2;
                        iRISs3[intervSpan] = rsi3;
                        iRISs4[intervSpan] = rsi4;
                        iCRs[intervSpan] = cr;
                        iARBRs[intervSpan] = arbr;
                        iARBRs2[intervSpan] = arbr2;
                        iCCIs[intervSpan] = cci;
                        iCCIs2[intervSpan] = cci2;
                        iCCIs3[intervSpan] = cci3;
                        iWRs[intervSpan] = wr;
                        iWRs2[intervSpan] = wr2;
                        iLWRs[intervSpan] = lwr;
                        iBOLLs[intervSpan]=boll;
                    }

                    LogUtil.Info(" New BarData  ####  " + barData);
                    dataUnits[intervSpan].Add(barData);

                    Console.WriteLine(" New  intvData  ############ op " + intvData.Open + " cls " + intvData.Close + "  max  " + intvData.Max + "  low " + intvData.Min);
                    Console.WriteLine("   allDataUnits[provider.Symbol][intervSpan]..Count  ::::::::::::::::::::::::::: " + dataUnits[intervSpan].Count);
                }
                else
                {
                    Console.WriteLine(" IN  currentTimes[" + intervSpan + "]  " + currentTimes[intervSpan]);
                    foreach (double price in prices)
                    {
                        intvData.PriceList.Add(price);
                        intvData.Max = Math.Max(intvData.Max, price);
                        intvData.Min = Math.Min(intvData.Min, price);
                    }
                    Signal[] signals = null;
                    lock (AppConst.SignalDatasLocker)
                    {
                        signals = new Signal[AppContext.SignalDatas.Count];
                        AppContext.SignalDatas.CopyTo(signals);
                    }
                    if (signals != null)
                    {
                        Array.Sort(signals);
                        int count = 0;
                        foreach (Signal s in signals)
                        {
                            if (s.Symbol == provider.Symbol && s.Interval == provider.CurrentTInterval)
                            {
                                if (s.Arrow != 0 && s.ActTime.CompareTo(lastTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 1);
                                    if (!intvData.SignalList.Contains(cs))
                                        intvData.SignalList.Add(cs);
                                }
                                if (s.GainTip != 0 && s.GainTipTime.CompareTo(lastTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 2);
                                    if (!intvData.SignalList.Contains(cs))
                                        intvData.SignalList.Add(cs);
                                }
                                if (s.StopLoss != 0 && s.StopLossTime.CompareTo(lastTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 3);
                                    if (!intvData.SignalList.Contains(cs))
                                        intvData.SignalList.Add(cs);
                                }
                                if (s.StopGain != 0 && s.StopGainTime.CompareTo(lastTime) == 0)
                                {
                                    CandleSignal cs = new CandleSignal(s, 4);
                                    if (!intvData.SignalList.Contains(cs))
                                        intvData.SignalList.Add(cs);
                                }
                                if (count > 5) break;
                                count++;
                            }
                        }
                    }

                    intvData.Close = intvData.PriceList.Last<double>();

                    //intvData.isInitialized = true;
                    if (provider.CurrentTInterval == intervSpan)
                    {
                        provider.IsUpdateCandle = true;
                        provider.IsAddCandle = false;
                    }
                    LogUtil.Info(" Updated intvData  ############  " + intvData);
                }
                Console.WriteLine(" Update  intvData  ############ op " + intvData.Open + " cls " + intvData.Close + "  max  " + intvData.Max + "  low " + intvData.Min);
                //}
                //intvData.isUpdated = true;
            }
        }
 /// <summary>
 /// Deltas will return a line indicating the difference of the current bar to the previous one.
 /// This is the same as the MOMENTUM indicator.
 /// </summary>
 public double[] GetDataValuesDeltas(BarData.DataValueSourceEnum valueEnum)
 {
     return GetDataValuesDeltas(0, _dataUnits.Count, valueEnum);
 }
        void UpdateValues()
        {
            lock (this)
            {
                BarData[] bars = new BarData[_dataProvider.DataUnits.Count];
                _dataProvider.DataUnits.CopyTo(bars, 0);

                double scaling = 1;
                for (int i = 0; i < bars.Length; i++)
                {
                    BarData bar = bars[i];
                    bars[i] = new BarData(bar.DateTime, bar.Open * scaling, bar.Close * scaling, bar.Low * scaling, bar.High * scaling, bar.Volume * scaling);
                }
                if (bars.Length > 0)
                {
                    this.SetBarData(bars, _dataProvider.TimeInterval);
                }

                RaiseValuesUpdated(true);
            }
        }
        //object sender, System.Timers.ElapsedEventArgs e)
        private void SaveDataToFile()
        {
            if (provider.Initialized && !isSavingFile && dataUnits.ContainsKey(provider.CurrentTInterval))
            {
                isSavingFile = true;
                DateTime now = DateTime.Now;
                Console.WriteLine(" isSavingFile%%%%%%%%%%% ::: " + isSavingFile + " " + now.Second + " " + now.Millisecond);

                Interval interval;
                string tmpPath;
                string tmpCdlFile;
                string tmpSigFile;
                string dataFile;
                lock (provider)
                {
                    //ProviderHelper.CleanTmpDirs(provider);
                    tmpPath = ProviderHelper.GetTmpPath(provider);
                    tmpCdlFile = ProviderHelper.GetTmpCdlFilePath(provider);
                    tmpSigFile = ProviderHelper.GetTmpSigFilePath(provider);
                    dataFile = ProviderHelper.GetDataFilePath(provider);
                    Console.WriteLine(" dataFile ::: " + dataFile + " tmpFile ::: " + tmpCdlFile + " tmpPath :: " + tmpPath + " tmpSigFile   " + tmpSigFile);
                    interval = provider.CurrentTInterval;
                }

                List<BarData> intervDatas = new List<BarData>();
                lock (dataUnits[interval])
                {
                    intervDatas.AddRange(dataUnits[interval]);
                }

                List<Signal> signalDatas = new List<Signal>();
                lock (signalUnits[interval])
                {
                    signalDatas.AddRange(signalUnits[interval]);
                }

                if (intervDatas.Count - OFFSET > BASE)
                {
                    if (intervDatas.Count - OFFSET > MAXIMUM)
                    {
                        int rmc = intervDatas.Count - OFFSET - MAXIMUM;
                        intervDatas.RemoveRange(0, rmc);
                    }
                    intervDatas.RemoveRange(intervDatas.Count - OFFSET, OFFSET);
                    BarData firstData = intervDatas.First();

                    List<Signal> ctxSignals = new List<Signal>();

                    lock (AppConst.SignalDatasLocker)
                    {
                        foreach (Signal s in AppContext.SignalDatas)
                        {
                            if (s.Symbol == provider.Symbol && s.Interval == provider.CurrentTInterval)
                                ctxSignals.Add(s);
                        }
                    }

                    ctxSignals.Sort();
                    ctxSignals.Reverse();

                    foreach (Signal s in ctxSignals)
                    {
                        if (s.ProfitPrice == 0)
                            break;
                        if (!signalDatas.Contains(s))
                            signalDatas.Add(s);
                    }

                    List<Signal> obsletes = new List<Signal>();
                    foreach (Signal s in signalDatas)
                    {
                        if (s.ProfitTime.CompareTo(firstData.DateTime) < 0)
                            obsletes.Add(s);
                    }

                    foreach (Signal s in obsletes)
                    {
                        signalDatas.Remove(s);
                    }
                }

                if (intervDatas.Count > 0) // Initialized
                {
                    Console.WriteLine(" intervDatas.Count ::: " + intervDatas.Count);
                    BarData[] barDatas = new BarData[intervDatas.Count];
                    intervDatas.CopyTo(barDatas);
                    Console.WriteLine(" barDatas.Count ::: " + barDatas.Length);
                    DateTime newLastTime = intervDatas.Last<BarData>().DateTime;

                    IFileWorker fw = FileUtil.GetFileWorker();
                    Signal[] signals = null;
                    lock (signalUnits[interval])
                    {
                        signals = new Signal[signalUnits[interval].Count];
                        signalUnits[interval].CopyTo(signals);
                    }

                    signalUnits[interval].CopyTo(signals);

                    fw.SaveCdlFile(tmpCdlFile, barDatas, true);
                    fw.SaveSigFile(tmpSigFile, signals, true);
                    fw.ZipFiles(tmpPath, dataFile, null);
                    fw = null;
                    lastCdlTimes[interval] = newLastTime;
                    ProviderHelper.CleanTmpDirs(provider);
                }
                isSavingFile = false;
                now = DateTime.Now;
                Console.WriteLine(" isSavingFile%%%%%%%%%%% ::: " + isSavingFile + " " + now.Second + " " + now.Millisecond);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// 0 means no pin bar, 1 is pin bar ...
        /// </summary>
        double EvaluatePinBar(int index)
        {
            BarData prevDataUnit = this.DataProvider.DataUnits[index - 1];
            BarData dataUnit     = this.DataProvider.DataUnits[index];
            BarData nextDataUnit = this.DataProvider.DataUnits[index + 1];

            double bodyToShadowRatio, prevPinDifference, nextPinDifference;
            bool   nextUnitConditions = false;

            if (dataUnit.BarIsRising)
            {// Looking for a bottom pointing pin.
                bodyToShadowRatio  = dataUnit.BarBodyLength / dataUnit.BarBottomShadowLength;
                prevPinDifference  = prevDataUnit.Low - dataUnit.Low;
                nextPinDifference  = nextDataUnit.Low - dataUnit.Low;
                nextUnitConditions = nextDataUnit.LowerOpenClose > dataUnit.LowerOpenClose;
            }
            else
            {// Looking for a top pointing pin.
                bodyToShadowRatio  = dataUnit.BarBodyLength / dataUnit.BarTopShadowLength;
                prevPinDifference  = dataUnit.High - prevDataUnit.High;
                nextPinDifference  = dataUnit.High - nextDataUnit.High;
                nextUnitConditions = nextDataUnit.HigherOpenClose < dataUnit.HigherOpenClose;
            }

            bool isPinPrerequirements = (bodyToShadowRatio < 1) && (prevPinDifference >= (dataUnit.BarTotalLength * _surroudingBarDifferenceRequirementRatio)) &&
                                        (nextPinDifference >= (dataUnit.BarTotalLength * _surroudingBarDifferenceRequirementRatio)) &&
                                        nextUnitConditions
                                        //&& (nextDataUnit.BarIsPositive == dataUnit.BarIsPositive)
                                        && (prevDataUnit.BarIsRising != dataUnit.BarIsRising);

            if (isPinPrerequirements == false)
            {
                return(0);
            }

            if (index <= _lookBackBarsCount / 2)
            {// Too few bars have passed - too early to establish a pin bar.
                return(0);
            }

            double barLength = 0;

            // Check lowest in the last LookBackBarsCount bars.
            for (int i = index - 1; i >= 0 && i >= index - _lookBackBarsCount; i--)
            {
                barLength += DataProvider.DataUnits[i].BarTotalLength;
                if (dataUnit.BarIsRising)
                {
                    if (DataProvider.DataUnits[i].Low <= dataUnit.Low ||
                        DataProvider.DataUnits[i].LowerOpenClose <= dataUnit.LowerOpenClose)
                    {// Looking for bottom pointing pin and a lower pin was found last few bars.
                        return(0);
                    }
                }
                else
                {
                    if (DataProvider.DataUnits[i].High >= dataUnit.High ||
                        DataProvider.DataUnits[i].HigherOpenClose >= dataUnit.HigherOpenClose)
                    {// Looking for a top pointing pin and a higher pin was found in the last few bars.
                        return(0);
                    }
                }
            }

            // This now becomes the average bar length for the last few bars.
            barLength = barLength / _lookBackBarsCount;

            // Check longer than average last LookBackBarsCount bars.
            if (dataUnit.BarTotalLength > _surroundingBarAverageMinimumLengthRation * barLength)
            {
                if (dataUnit.BarIsRising)
                {
                    return((float)PinBarStates.PinBar1);
                }
                else
                {
                    return((float)PinBarStates.PinBar2);
                }
            }
            return((float)PinBarStates.Default);
        }
        public Dictionary<string, double> handleFullCandle(ref BarData candle, int field)
        {
            Dictionary<string, double> boll = new Dictionary<string, double>();
            boll.Add(UPPER, 0);
               boll.Add(MID, 0);
            boll.Add(LOWER, 0);

              if (!this.isInitialized)
            {
                this.initCandleList.Add(candle);
                if (initCandleList.Count == this.n)
                {
                    isInitialized = true;
                }
                return boll;
            }

            if (initCandleList.Count >= this.n)
            {
                initCandleList.RemoveAt(0);
            }
            this.initCandleList.Add(candle);

            // the sum of close price
            double sum = 0;
            foreach (BarData c in initCandleList) {
            sum = sum+c.Close;
            }

            // 中线
            double midBoll = sum/this.n;

            // Formula :
            // MID : MA(CLOSE,N);
            // UPPER: MID + P*STD(CLOSE,N);
            // LOWER: MID - P*STD(CLOSE,N);

            // STD -- Standard Deviation

            // Calculate上线和下线
            sum = 0;
             foreach (BarData c in initCandleList)
             {
             double close = c.Close;
            double tmp = close-midBoll;
            sum = sum + tmp * tmp;
            //Console.WriteLine(tmp + "  " + sum );
            }
             double p = 2;
             double tmp1 = sum / n;
            double d = p*  Math.Sqrt(tmp1);
            double upBoll = midBoll+(d);
            double lowBoll = midBoll-(d);

            boll[UPPER] = Double.Parse(String.Format("{0:00.000000}", upBoll)); ;
            boll[LOWER] = Double.Parse(String.Format("{0:00.000000}", lowBoll)); ; ;
            boll[MID] = Double.Parse(String.Format("{0:00.000000}", midBoll));

            ////Console.WriteLine( upBoll + "  " +midBoll+ "  " + lowBoll+ "  "+ d +  "   " +sum + "  "+ tmp1);

            candle.Boll = boll;

            return boll;
        }
Exemplo n.º 29
0
        public Dictionary <string, double> handleFragCandle(ref BarData candle, int field)
        {
            Dictionary <string, double> lwr = new Dictionary <string, double>();

            // cp the previous candle list
            List <BarData> cpLwr1List = new List <BarData>();

            cpLwr1List.AddRange(lwr1List);
            cpLwr1List.RemoveAt(0);
            cpLwr1List.Add(candle);

            List <BarData> cpLwr2List = new List <BarData>();

            cpLwr2List.AddRange(lwr2List);
            cpLwr2List.RemoveAt(0);
            cpLwr2List.Add(candle);

            // HHV(HIGH,N)
            // The highest value in last N candles
            double hhv = 0;

            // LLV(LOW,N)
            // The lowest value in last N candles
            double llv = 0;

            // RSV= (HHV(HIGH,N)-CLOSE)/(HHV(HIGH,N)-LLV(LOW,N))*100;
            double rsv = 0;

            // LWR1: SMA(RSV,M1,1);
            // LWR1=(RSV1+RSV2+ ...+RSVn)/ N
            // N =M1, M1>=1
            double lwr1 = 0;

            rsv = 0;
            for (int i = m1size - 1; i > m1size - m1 - 1; i--)
            {
                BarData cdl  = cpLwr1List[i];
                double  high = Double.MinValue;
                double  low  = Double.MaxValue;
                hhv = 0;
                llv = 0;
                for (int k = i; k > i - n; k--)
                {
                    BarData c = cpLwr1List[k];
                    high = high < c.High ? c.High : high;
                    low  = low > c.Low ? c.Low : low;
                }

                hhv = high;
                //  Console.WriteLine(" high " + hhv);
                double hcd = high - cdl.Close;
                llv = low;
                //  Console.WriteLine(" low  " + llv);
                double hld = hhv - llv;
                //  Console.WriteLine(" hhhhcccc " + hcd);
                //  Console.WriteLine(" hhhhhlllllll " + hld);
                double rsvn = hcd / hld * 100;
                rsv = rsv + rsvn;
                //  Console.WriteLine(" rsv=======  " + rsv );
            }
            //  Console.WriteLine(rsv);
            lwr1 = rsv / m1;
            //  Console.WriteLine(lwr1);

            // LWR2: SMA(LWR1,M2,1);
            // LWR2=(LWR1+LWR2+ ...+LWRn)/ N
            // N =M2, M2>=1
            double lwr2 = 0;

            for (int t = m2size - 1; t > m2size - m2 - 1; t--)
            {
                rsv = 0;
                for (int i = t; i > t - m1; i--)
                {
                    BarData cdl  = cpLwr2List[i];
                    double  high = Double.MinValue;
                    double  low  = Double.MaxValue;
                    hhv = 0;
                    llv = 0;
                    for (int k = i; k > i - n; k--)
                    {
                        BarData c = cpLwr2List[k];
                        high = high < c.High ? c.High : high;
                        low  = low > c.Low ? c.Low : low;
                    }
                    hhv = high;
                    double hcd = high - cdl.Close;
                    llv = low;
                    double hld = hhv - llv;
                    //  Console.WriteLine(" hhhhvvv " + hcd);
                    //  Console.WriteLine(" llllllvvvvv " + hld );
                    double rsvn = hcd / hld * 100;
                    rsv = rsv + rsvn;
                }
                //  Console.WriteLine(rsv);
                double lwrn = rsv / m1;
                lwr2 += lwrn;
            }
            //  Console.WriteLine(lwr2);
            lwr2 = lwr2 / m2;
            //  Console.WriteLine(lwr2);

            lwr1 = Double.Parse(String.Format("{0:00.00000}", lwr1));
            lwr2 = Double.Parse(String.Format("{0:00.00000}", lwr2));
            //contrainer.setOtherIndValues(map);

            lwr[LWR1] = lwr1;
            lwr[LWR2] = lwr2;

            candle.Lwr = lwr;
            return(lwr);
        }
        /**
         *
         */
        public double handleFullCandle(ref BarData candle)
        {
            if (!isInitialized)
            {
                initCandleList.Add(candle);
                if (initCandleList.Count == this.initCandleSize)
                {
                    this.initial(initCandleList);
                    //initCandleList = null;
                }
                return 0;
            }

            double p1 = candle.High - prevMiddlePrice;
            if(histP1.Count >= this.initCandleSize){
                histP1.RemoveAt(0);
            }

            if (p1 > 0)
            {
                histP1.Add(p1);
            }
            else
            {
                histP1.Add(0);
            }

            double sumP1 = this.getSum(histP1);

            double p2 = prevMiddlePrice - candle.Low;
            if (histP2.Count >= this.initCandleSize)
            {
                histP2.RemoveAt(0);
            }

            if (p2 > 0)
            {
                histP2.Add(p2);
            }
            else
            {
                histP2.Add(0);
            }
            double sumP2 = this.getSum(histP2);

            double cR = 0D;
            if (sumP2 != 0)
            {
                cR = sumP1 * 100 / sumP2;
            }

            cR = Double.Parse(String.Format("{0:00.00000}", cR));

            // 保存最近的20个值
            if (histCR.Count >= 20)
            {
                histCR.Remove(0);
            }
            histCR.Add(cR);

            // Calculate其平均值
            crMA5 = getAvg(histCR, 5);
            crMA10 = getAvg(histCR, 10);
            crMA20 = getAvg(histCR, 20);

            // 为下根做准备
            prevMiddlePrice = this.getMiddlePrice(candle);

            candle.Cr = crMA5;

            return cR;
        }
Exemplo n.º 31
0
        public Dictionary <string, double> handleFullCandle(ref BarData candle, int field)
        {
            Dictionary <string, double> lwr = new Dictionary <string, double>();

            lwr.Add(LWR1, 0);
            lwr.Add(LWR2, 0);

            bool rtn = false;

            if (lwr1List.Count >= this.m1size)
            {
                lwr1List.RemoveAt(0);
                lwr1List.Add(candle);
            }
            else
            {
                lwr1List.Add(candle);
                rtn = true;
            }

            if (lwr2List.Count >= this.m2size)
            {
                lwr2List.RemoveAt(0);
                lwr2List.Add(candle);
            }
            else
            {
                lwr2List.Add(candle);
                rtn = true;
            }

            if (rtn)
            {
                lwr[LWR1]  = 0;
                lwr[LWR2]  = 0;
                candle.Lwr = lwr;

                return(lwr);
            }

            // HHV(HIGH,N)
            // The highest value in last N candles
            double hhv = 0;

            // LLV(LOW,N)
            // The lowest value in last N candles
            double llv = 0;

            // RSV= (HHV(HIGH,N)-CLOSE)/(HHV(HIGH,N)-LLV(LOW,N))*100;
            double rsv = 0;

            // LWR1: SMA(RSV,M1,1);
            // LWR1=(RSV1+RSV2+ ...+RSVn)/ N
            // N =M1, M1>=1
            double lwr1 = 0;

            rsv = 0;
            for (int i = m1size - 1; i > m1size - m1 - 1; i--)
            {
                BarData cdl  = lwr1List[i];
                double  high = Double.MinValue;
                double  low  = Double.MaxValue;
                hhv = 0;
                llv = 0;
                for (int k = i; k > i - n; k--)
                {
                    BarData c = lwr1List[k];
                    high = high < c.High ? c.High : high;
                    low  = low > c.Low ? c.Low : low;
                }
                hhv = high;
                double hcd = high - cdl.Close;
                llv = low;
                double hld  = hhv - llv;
                double rsvn = hcd / hld * 100;
                rsv = rsv + rsvn;
            }
            lwr1 = rsv / m1;

            // LWR2: SMA(LWR1,M2,1);
            // LWR2=(LWR1+LWR2+ ...+LWRn)/ N
            // N =M2, M2>=1
            double lwr2 = 0;

            for (int t = m2size - 1; t > m2size - m2 - 1; t--)
            {
                rsv = 0;
                for (int i = t; i > t - m1; i--)
                {
                    BarData cdl  = lwr2List[i];
                    double  high = Double.MinValue;
                    double  low  = Double.MaxValue;
                    hhv = 0;
                    llv = 0;
                    for (int k = i; k > i - n; k--)
                    {
                        BarData c = lwr2List[k];
                        high = high < c.High ? c.High : high;
                        low  = low > c.Low ? c.Low : low;
                    }
                    hhv = high;
                    double hcd = high - cdl.Close;
                    llv = low;
                    double hld  = hhv - llv;
                    double rsvn = hcd / hld * 100;
                    rsv = rsv + rsvn;
                }

                double lwrn = rsv / m1;
                lwr2 += lwrn;
            }

            lwr2 = lwr2 / m2;


            lwr1 = Double.Parse(String.Format("{0:00.00000}", lwr1));
            lwr2 = Double.Parse(String.Format("{0:00.00000}", lwr2));


            lwr[LWR1] = lwr1;
            lwr[LWR2] = lwr2;

            candle.Lwr = lwr;
            return(lwr);
        }
        public static bool SaveToFile(FileFormat fileFormat, string path, BarData[] bars)
        {
            if (fileFormat == FileFormat.CVSDefault)
            {
                using (StreamWriter writer = new StreamWriter(path))
                {
                    foreach (BarData bar in bars)
                    {
                        if (bar.HasDataValues)
                        {
                            writer.WriteLine(bar.DateTime.Day.ToString() + "." + bar.DateTime.Month.ToString() + "." + bar.DateTime.Year.ToString()
                                + "," + bar.DateTime.Hour.ToString("00") + ":" + bar.DateTime.Minute.ToString("00")
                                + "," + bar.Open.ToString() + "," + bar.High.ToString()
                                + "," + bar.Low.ToString() + "," + bar.Close.ToString()
                                + "," + bar.Volume.ToString());
                        }
                    }
                }
                return true;
            }

            return false;
        }
 public static void ParseRtd(ref List<BarData> datas, int index, string[] msgs, Protocol p)
 {
     while (index <= msgs.Length - 2)
     {
         try
         {
             string[] rmsgs = msgs[index].Split(',');
             if (rmsgs.Length >= 5)
             {
                 BarData barData = new BarData();
                 barData.DateTime = DateTime.Parse(rmsgs[0]);
                 barData.Open = double.Parse(rmsgs[1], new System.Globalization.NumberFormatInfo());
                 barData.Close = double.Parse(rmsgs[2], new System.Globalization.NumberFormatInfo());
                 barData.Low = double.Parse(rmsgs[3], new System.Globalization.NumberFormatInfo());
                 barData.High = double.Parse(rmsgs[4], new System.Globalization.NumberFormatInfo());
                 barData.ExHigh = barData.High;
                 barData.ExLow = barData.Low;
                 if (p == Protocol.M0003_1)
                 {
                     barData.IsCompleted = true;
                 }
                 else if (rmsgs.Length >= 6)
                 {
                     barData.IsCompleted = (int.Parse(rmsgs[5], new System.Globalization.NumberFormatInfo()) == 0);
                 }
                 //Console.WriteLine(barData);
                 //LogUtil.Info(" candle data :::  " + barData);
                 datas.Add(barData);
             }
         }
         catch (Exception e)
         {
         }
         index++;
     }
 }
        public static BarData[] GenerateTestSeries(int length)
        {
            BarData[] result = new BarData[length];
            for (int i = 0; i < result.Length; i++)
            {
                if (i == 0)
                {
                    result[i] = new BarData(DateTime.Now, GeneralHelper.Random(50), GeneralHelper.Random(50), GeneralHelper.Random(50), GeneralHelper.Random(50), 10);
                }
                else
                {
                    double open = result[i - 1].Close + GeneralHelper.Random(-2, 3);
                    double close = open + GeneralHelper.Random(-30, 31);
                    result[i] = new BarData(result[i - 1].DateTime + TimeSpan.FromSeconds(1), open, close, Math.Min(open, close) - GeneralHelper.Random(15), Math.Max(open, close) + GeneralHelper.Random(10), 10);
                }
            }

            return result;
        }
        public Dictionary<string, double> handleFullCandle(ref BarData candle, int field)
        {
            Dictionary<string, double> lwr = new Dictionary<string, double>();
            lwr.Add(LWR1, 0);
            lwr.Add(LWR2, 0);

            bool rtn = false;
            if (lwr1List.Count >= this.m1size)
            {
                lwr1List.RemoveAt(0);
                lwr1List.Add(candle);
            }
            else
            {
                lwr1List.Add(candle);
                rtn = true;
            }

            if (lwr2List.Count >= this.m2size)
            {
                lwr2List.RemoveAt(0);
                lwr2List.Add(candle);
            }
            else
            {
                lwr2List.Add(candle);
                rtn = true;
            }

            if (rtn)
            {
                lwr[LWR1] = 0;
                lwr[LWR2] = 0;
                candle.Lwr = lwr;

                return lwr;
            }

            // HHV(HIGH,N)
            // The highest value in last N candles
            double hhv = 0;

            // LLV(LOW,N)
            // The lowest value in last N candles
            double llv = 0;

            // RSV= (HHV(HIGH,N)-CLOSE)/(HHV(HIGH,N)-LLV(LOW,N))*100;
            double rsv = 0;

            // LWR1: SMA(RSV,M1,1);
            // LWR1=(RSV1+RSV2+ ...+RSVn)/ N
            // N =M1, M1>=1
            double lwr1 = 0;
            rsv = 0;
            for (int i = m1size - 1; i > m1size - m1 - 1; i--)
            {
                BarData cdl = lwr1List[i];
                double high = Double.MinValue;
                double low = Double.MaxValue;
                hhv = 0;
                llv = 0;
                for (int k = i; k > i -n ; k--)
                {
                    BarData c = lwr1List[k];
                    high = high < c.High ? c.High : high;
                    low = low > c.Low ? c.Low : low;
                }
                hhv = high;
                double hcd = high - cdl.Close;
                llv = low;
                double hld = hhv-llv;
                double rsvn = hcd/hld*100;
                rsv = rsv+rsvn;
            }
            lwr1 = rsv/m1;

            // LWR2: SMA(LWR1,M2,1);
            // LWR2=(LWR1+LWR2+ ...+LWRn)/ N
            // N =M2, M2>=1
            double lwr2 = 0;

            for (int t = m2size - 1; t > m2size - m2 - 1; t--)
            {
                rsv = 0;
                for (int i = t; i >t- m1; i--)
                {
                    BarData cdl = lwr2List[i];
                    double high = Double.MinValue;
                    double low = Double.MaxValue;
                    hhv = 0;
                    llv = 0;
                    for (int k = i; k > i - n; k--)
                    {
                        BarData c = lwr2List[k];
                        high = high < c.High ? c.High : high;
                        low = low > c.Low ? c.Low : low;
                    }
                    hhv = high;
                    double hcd = high - cdl.Close;
                    llv = low;
                    double hld = hhv - llv;
                    double rsvn = hcd / hld * 100;
                    rsv = rsv + rsvn;
                }

                double lwrn = rsv/m1;
                lwr2+= lwrn;
            }

            lwr2 = lwr2/m2;

            lwr1 = Double.Parse(String.Format("{0:00.00000}", lwr1));
            lwr2 = Double.Parse(String.Format("{0:00.00000}", lwr2));

            lwr[LWR1] = lwr1;
            lwr[LWR2] = lwr2;

            candle.Lwr = lwr;
            return lwr;
        }
        public double handleFullCandle(ref BarData candle)
        {
            //IndValue contrainer = new IndValue(candle);

            // 最初的一 candles
            if (!isInitialized)
            {
                return this.init(candle);
            }

            // 1: CalculatePrice极值
            double currentEprice = -1;
            double candleLow = candle.Low;
            bool isNewLow = false;
            double candleHigh = candle.High;
            bool isNewHigh = false;

            if (sarArea == AREA_UP)
            {// 多头的时候,拿当前这个阶段的最高的Price

                if (candleHigh > maxEPrice)
                {
                    isNewHigh = true;
                    currentEprice = candleHigh;

                    if (!turnPoint)
                    {// 在没有区间转变的时候,才能Calculate到本期间的最高值
                        maxEPrice = candleHigh;
                    }
                }
                else
                {
                    currentEprice = maxEPrice;
                }
            }
            else if (sarArea == AREA_DOWN)
            {// 空头的时候,拿当前这个阶段的最低的Price

                if (candleLow < minEPrice)
                {
                    isNewLow = true;
                    currentEprice = candleLow;
                    if (!turnPoint)
                    {// 在没有区间转变的时候,才能Calculate到本期间的最低值
                        minEPrice = candleLow;
                    }
                }
                else
                {
                    currentEprice = minEPrice;
                }
            }

            // 2: Calculate当前因子
            double currentAccFactor;

            if (turnPoint)
            {// 当前是一个拐点
                currentAccFactor = accFactorIncreatement;
            }
            else if ((sarArea == AREA_UP && isNewHigh)
                    || (sarArea == AREA_DOWN && isNewLow))
            {// 多头,并且Price创出新的最高的时候|或者空头,并且Price是新低

                currentAccFactor = prevAccFactor+accFactorIncreatement;

                if (currentAccFactor >= maxAccFactor)
                {// 不能超过0.2
                    currentAccFactor = maxAccFactor;
                }
            }
            else
            {// 保持上一个不变
                currentAccFactor = prevAccFactor;
            }

            // 3: Calculate当前的SAR
            double sar = 0;
            if (turnPoint)
            {// 当前是一个拐点
                if (sarArea == AREA_UP)
                {// 当前是多头,SAR是前N candles的最低值
                    sar = this.getLowestInN();
                }
                else
                {
                    sar = this.getHighestInN();
                }

                minEPrice = candleLow;
                maxEPrice = candleHigh;

                // 下一根是否是拐点
                turnPoint = false;
            }
            else
            {
                // SAR(i) = SAR(i-1)+ACCELERATION(i-1)*(EPRICE(i-1)-SAR(i-1))
                double tmp = prevAccFactor * (prevEPrice - prevSAR);
                sar = prevSAR + tmp;
            }

            //double ttt = TypeFormat.parseDouble(formater.format(sar.doubleValue()));
            //sar = new double(ttt);

            //contrainer.setIndValue(ttt);

            sar = Double.Parse(String.Format(formater, sar));

            candle.Sar = sar;

            prevEPrice = currentEprice;
            prevSAR = sar;
            prevAccFactor = currentAccFactor;

            // 为下一 candlesCalculate做准备,主要是,是否是拐点
            if (sarArea == AREA_DOWN && candleHigh > sar)
            {
                turnPoint = true;
                sarArea = AREA_UP;
            }
            else if (sarArea == AREA_UP && candleLow < sar)
            {
                turnPoint = true;
                sarArea = AREA_DOWN;
            }

            if (this.lastNCandleHigh.Count >= this.n)
            {
                this.lastNCandleHigh.RemoveAt(0);
            }
            this.lastNCandleHigh.Add(candleHigh);

            if (this.lastNCandleLow.Count >= this.n)
            {
                this.lastNCandleLow.RemoveAt(0);
            }
            this.lastNCandleLow.Add(candleLow);

            // Calculate下一 candles value
            if (turnPoint)
            {// 当前是一个拐点
                if (sarArea == AREA_UP)
                {// 当前是多头,SAR是上个区间的最低值
                    nextSAR = this.getLowestInN();
                }
                else
                {
                    nextSAR = this.getHighestInN();
                }
            }
            else
            {
                // SAR(i) = SAR(i-1)+ACCELERATION(i-1)*(EPRICE(i-1)-SAR(i-1))
                double tmp = prevAccFactor * (prevEPrice - prevSAR);
                nextSAR = prevSAR + tmp;
            }

            nextSAR = Double.Parse(String.Format(formater, nextSAR));

            //ttt = TypeFormat.parseDouble(formater.format(nextSAR.doubleValue()));
            //nextSAR =ttt;

            return nextSAR;
        }
        public Dictionary<string, double> handleFragCandle(ref BarData candle, int field)
        {
            Dictionary<string, double> lwr = new Dictionary<string, double>();

            // cp the previous candle list
            List<BarData> cpLwr1List = new List<BarData>();
            cpLwr1List.AddRange(lwr1List);
            cpLwr1List.RemoveAt(0);
            cpLwr1List.Add(candle);

            List<BarData> cpLwr2List = new List<BarData>();
            cpLwr2List.AddRange(lwr2List);
            cpLwr2List.RemoveAt(0);
            cpLwr2List.Add(candle);

            // HHV(HIGH,N)
            // The highest value in last N candles
            double hhv = 0;

            // LLV(LOW,N)
            // The lowest value in last N candles
            double llv = 0;

            // RSV= (HHV(HIGH,N)-CLOSE)/(HHV(HIGH,N)-LLV(LOW,N))*100;
            double rsv = 0;

            // LWR1: SMA(RSV,M1,1);
            // LWR1=(RSV1+RSV2+ ...+RSVn)/ N
            // N =M1, M1>=1
            double lwr1 = 0;
            rsv = 0;
            for (int i = m1size - 1; i > m1size - m1 - 1; i--)
            {
                BarData cdl = cpLwr1List[i];
                double high = Double.MinValue;
                double low = Double.MaxValue;
                hhv = 0;
                llv = 0;
                for (int k = i; k > i - n; k--)
                {
                    BarData c = cpLwr1List[k];
                    high = high < c.High ? c.High : high;
                    low = low > c.Low ? c.Low : low;
                }

                hhv = high;
                //  Console.WriteLine(" high " + hhv);
                double hcd = high - cdl.Close;
                llv = low;
                //  Console.WriteLine(" low  " + llv);
                double hld = hhv - llv;
                //  Console.WriteLine(" hhhhcccc " + hcd);
                //  Console.WriteLine(" hhhhhlllllll " + hld);
                double rsvn = hcd / hld * 100;
                rsv = rsv + rsvn;
                //  Console.WriteLine(" rsv=======  " + rsv );
            }
            //  Console.WriteLine(rsv);
            lwr1 = rsv / m1;
            //  Console.WriteLine(lwr1);

            // LWR2: SMA(LWR1,M2,1);
            // LWR2=(LWR1+LWR2+ ...+LWRn)/ N
            // N =M2, M2>=1
            double lwr2 = 0;

            for (int t = m2size - 1; t > m2size - m2 - 1; t--)
            {
                rsv = 0;
                for (int i = t; i > t - m1; i--)
                {
                    BarData cdl = cpLwr2List[i];
                    double high = Double.MinValue;
                    double low = Double.MaxValue;
                    hhv = 0;
                    llv = 0;
                    for (int k = i; k > i - n; k--)
                    {
                        BarData c = cpLwr2List[k];
                        high = high < c.High ? c.High : high;
                        low = low > c.Low ? c.Low : low;
                    }
                    hhv = high;
                    double hcd = high - cdl.Close;
                    llv = low;
                    double hld = hhv - llv;
                    //  Console.WriteLine(" hhhhvvv " + hcd);
                    //  Console.WriteLine(" llllllvvvvv " + hld );
                    double rsvn = hcd / hld * 100;
                    rsv = rsv + rsvn;
                }
                //  Console.WriteLine(rsv);
                double lwrn = rsv / m1;
                lwr2 += lwrn;
            }
            //  Console.WriteLine(lwr2);
            lwr2 = lwr2 / m2;
            //  Console.WriteLine(lwr2);

            lwr1 = Double.Parse(String.Format("{0:00.00000}", lwr1));
            lwr2 = Double.Parse(String.Format("{0:00.00000}", lwr2));
            //contrainer.setOtherIndValues(map);

            lwr[LWR1] = lwr1;
            lwr[LWR2] = lwr2;

            candle.Lwr = lwr;
            return lwr;
        }
        //void InitializeTaLibIndicator(MethodInfo methodInfo, string indicatorName, bool? isTradeable, bool? isScaledToQuotes, params object[] inputParameters)
        //{
        //    InitializeTaLibIndicator(methodInfo, indicatorName, isTradeable, isScaledToQuotes, null, null, inputParameters);
        //}
        void InitializeTaLibIndicator(MethodInfo methodInfo, string indicatorName, bool? isTradeable, 
            bool? isScaledToQuotes, BarData.DataValueSourceEnum? inRealSource, BarData.DataValueSourceEnum? inReal1Source, params object[] inputParameters)
        {
            lock (this)
            {
                GenericTALibIndicator indicator = GenericTALibIndicator.CreateInstance(methodInfo, indicatorName, isTradeable, isScaledToQuotes);

                if (indicator == null)
                {
                    Console.WriteLine("Creating indicator [" + indicator.Name + "] failed.");
                    return;
                }

                Console.WriteLine(indicator.SetInputParameters(inputParameters));

                _indicatorsGroups[IndicatorGroups.Fxpa].Add(indicator.Name, indicator);
                indicator.RealInputArraySource = inRealSource;
                indicator.Real1InputArraySource = inReal1Source;
            }
        }
        void DrawOrder(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin,
            float yToXScaling, BarData orderBarData, float lastBarX, bool drawOpening)
        {
            Image image = _imageUp;
            Brush brush = Brushes.Green;
            Pen dashedPen = _buyDashedPen;
            Pen pen = Pens.GreenYellow;
            if (order.IsBuy == false)
            {
                image = _imageDown;
                brush = Brushes.Red;
                pen = Pens.Red;
                dashedPen = _sellDashedPen;
            }

            if (drawOpening == false)
            {
                image = _imageCross;
            }

            float price = (float)order.OpenPrice;
            if (drawOpening == false)
            {
                price = (float)order.ClosePrice;
            }

            if (drawOpening && _showPendingOrdersTracing && order.IsOpen)
            {// Open orders tracking line.
                PointF point1 = new PointF(updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + price);
                float sellPrice = (float)_dataProvider.Bid;
                if (order.IsBuy == false)
                {
                    sellPrice = (float)_dataProvider.Ask;
                }
                PointF point2 = new PointF(lastBarX - itemWidth / 2f, updatedImageDrawingPoint.Y + sellPrice);
                g.DrawLine(dashedPen, point1, point2);
            }

            //if (drawOpening && _showClosedOrdersTracing && order.IsOpen == false)
            //{// Closed order tracking.
            // Close order tracing is implemented in main draw function.
            //}

            if (_showOrderSpot)
            {
                PointF basePoint = new PointF(updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + price);
                float height = (yToXScaling * itemWidth);
                if (order.IsBuy == false)
                {
                    height = -height;
                }

                if (drawOpening)
                {
                    g.FillPolygon(brush, new PointF[] { basePoint, new PointF(basePoint.X + itemWidth, basePoint.Y),
                        new PointF(basePoint.X + (itemWidth / 2f), basePoint.Y + height) });
                    g.DrawPolygon(Pens.White, new PointF[] { basePoint, new PointF(basePoint.X + itemWidth, basePoint.Y),
                        new PointF(basePoint.X + (itemWidth / 2f), basePoint.Y + height) });

                    // Take profit level.
                    if (double.IsInfinity(order.SourceTakeProfit) == false
                        && double.IsNaN(order.SourceTakeProfit) == false
                        && order.SourceTakeProfit != 0)
                    {
                        g.DrawLine(pen, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit,
                            updatedImageDrawingPoint.X + itemWidth, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit);

                        g.DrawLine(pen, updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit,
                            updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit - height);
                    }

                    // Stop loss level.
                    if (double.IsInfinity(order.SourceStopLoss) == false
                        && double.IsNaN(order.SourceStopLoss) == false
                        && order.SourceStopLoss != 0)
                    {
                        g.DrawLine(pen, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss,
                            updatedImageDrawingPoint.X + itemWidth, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss);

                        g.DrawLine(pen, updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss,
                            updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss + height);
                    }
                }
                else
                {
                    g.DrawRectangle(Pens.White, basePoint.X, basePoint.Y,
                        itemWidth, yToXScaling * itemWidth);
                }

            }

            float imageHeight = 2 * (yToXScaling * itemWidth);
            if (_showOrderArrow)
            {
                // Draw up image.

                g.DrawImage(image, updatedImageDrawingPoint.X - (itemWidth / 2f), updatedImageDrawingPoint.Y +
                    (float)orderBarData.Low - (yToXScaling * itemWidth), 2 * itemWidth, -imageHeight);

                updatedImageDrawingPoint.Y -= 1.2f * imageHeight;
            }
        }