//TO DO check. dangerous
        public CTimeFrameInfo GetPrevLastTimeFrameInfo(EnmTF TF)
        {
            CTimeFrameInfo tfi = null;

            try
            {
                DateTime dtMax = new DateTime(0);
                foreach (KeyValuePair <DateTime, CTimeFrameArray> kvp in this[TF.ToString()])
                {
                    if (kvp.Key > dtMax && kvp.Value.ListTimeFrameInfo.Count > 0)
                    {
                        dtMax = kvp.Key;
                    }
                }

                int cnt = this[TF.ToString()][dtMax].ListTimeFrameInfo.Count;
                if (cnt >= 2)
                {
                    tfi = this[TF.ToString()][dtMax].ListTimeFrameInfo[cnt - 2];
                }
                else
                {
                    tfi = this[TF.ToString()][dtMax].ListTimeFrameInfo.Last();
                }
                return(tfi);
            }
            catch (Exception e)
            {
                Error("GetLastTimeFrameInfo", e);
                return(tfi);
            }
        }
        private void Analyze_D1(DateTime dt)
        {
            try
            {
                CTimeFrameInfo ntfi = m_dictTFArray.GetNewTimeFrameInfo(m_isin, EnmTF.D1, dt);


                CTimeFrameArray M_low_TF_Array = m_dictTFArray[EnmTF.H1.ToString()][dt];


                for (int i = 1; i < M_low_TF_Array.ListTimeFrameInfo.Count; i++) //each TF array
                {
                    ntfi.OpenedPos = M_low_TF_Array.ListTimeFrameInfo[i].OpenedPos;

                    CTimeFrameInfo currtfi = M_low_TF_Array.ListTimeFrameInfo[i];
                    ntfi.numOfDeals += currtfi.numOfDeals;
                    ntfi.Volume     += currtfi.Volume;

                    if (ntfi.HighPrice < currtfi.HighPrice)
                    {
                        ntfi.HighPrice = currtfi.HighPrice;
                    }
                    if (ntfi.LowPrice > currtfi.LowPrice)
                    {
                        ntfi.LowPrice = currtfi.LowPrice;
                    }
                }
            }
            catch (Exception e)
            {
                string st = e.Message;
            }
        }
 public CStructTF(string isin, string tf, string dt, CTimeFrameInfo tfinfo)
 {
     Isin   = isin;
     TF     = tf;
     Dt     = dt;
     TFinfo = tfinfo;
 }
 private void CheckTFIConsistent(CTimeFrameInfo ntfi)
 {
     //  Plaza2Connector.GUIBox.GUICandleBox.UpdateCandle(this.m_isin, TF_high.ToString(), dtcnd.ToString(), ntfi);
     if (ntfi.HighPrice < ntfi.LowPrice)
     {
         Error("Not consistent data.ntfi.HighPrice < ntfi.LowPrice");
     }
 }
        public void AnalyzeOnlineData(CRawDeal rd)
        {
            try
            {
                if (m_timerWriteFiles == null)
                {
                    m_timerWriteFiles = new CTimer(5000, new Action(m_dictTFArray.WriteAllDataToDisk), true);
                }

                CheckTFAnalyzerOnline(rd);

                if (m_prevDeal == null && m_currDeal == null)
                {
                    m_currDeal = rd;

                    CTimeFrameInfo tfi = m_dictTFArray.GetLatestTFI();
                    if (tfi != null)
                    {
                        m_prevDeal = new CRawDeal(tfi);
                    }
                    else
                    {
                        m_prevDeal = rd;
                        return;
                    }
                }

                m_prevDeal = m_currDeal;
                m_currDeal = rd;

                //if data old do not analyze it
                if (!m_dictTFArray.IsNewData(rd))
                {
                    return;
                }


                AnalyzeOnlineM1((CRawDeal)rd.Copy(), m_prevDeal);


                /*
                 * if (m_dictTFArray.IsTimeToWrite(EnmTF.M1))
                 * {
                 *
                 *  (new System.Threading.Tasks.Task(() => m_dictTFArray.WriteAllDataToDisk())).Start();
                 * }
                 *
                 */
            }

            catch (Exception e)
            {
                Error("Error AnalyzeData", e);
            }
        }
        public void QueueTFinfo(string isin, string tf, string dt, CTimeFrameInfo tfi)
        {
            //after this time all data will (or already where) loaded
            //so it is possible to update


            if (m_plaza2Connector.IsTimeToInitCandles)
            {
                _dictCandleProc[isin].Add(isin, tf, dt, tfi);
            }
        }
        private void InsertToValidPlace(CTimeFrameInfo tfi, int ind, CTimeFrameArray arr)
        {
            int i = 0;

            for (i = 0; i < arr.ListTimeFrameInfo.Count - 1; i++)
            {
                if (arr.ListTimeFrameInfo[i].Dt > tfi.Dt)
                {
                    break;
                }
            }

            arr.ListTimeFrameInfo.Insert(i, tfi);
            arr.ListTimeFrameInfo.RemoveAt(ind);
        }
        private void TriggerRecalcAllBotsChangedTF(EnmTF TF, CTimeFrameInfo tfi)
        {
            if (!Plaza2Connector.IsDealsOnline || !IsOnlineData)
            {
                return;
            }

            BotEventTF mess = new BotEventTF()
            {
                TFUpdate = TF,
                TFI      = tfi
            };

            Plaza2Connector.TriggerRecalcAllBotsWithInstrument(m_isin, EnmBotEventCode.OnTFChanged, mess);
        }
        private void AnalyzeDiskTFDays()
        {
            try
            {
                if (!m_dictTFArray.ContainsKey(EnmTF.H1.ToString()))
                {
                    return;
                }



                foreach (KeyValuePair <DateTime, CTimeFrameArray> kvp in m_dictTFArray[EnmTF.H1.ToString()]) //all dates of low TF array
                {
                    try
                    {
                        CTimeFrameArray M_low_TF_Array = kvp.Value;

                        DateTime dt = CUtilTime.NormalizeDay(M_low_TF_Array.ListTimeFrameInfo[0].Dt.Date);
                        if (m_dictTFArray.IsContainTimeFrameInfo(EnmTF.D1, dt))
                        {
                            continue;
                        }


                        CTimeFrameInfo ntfi = m_dictTFArray.GetNewTimeFrameInfo(m_isin, EnmTF.D1, dt);

                        Analyze_D1(dt);
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            catch (Exception e)
            {
                Error("AnalyzeDiskTFDays", e);
            }
        }
        public void UpdateCandle(string isin, string tf, string dt, CTimeFrameInfo tfinfo)
        {
            CreateIfNeedAll(isin, tf, dt);

            //TO DO normal
            //TO DO remove delay from deals thread
            sw.Start();
            m_dictTFMx[isin][tf].WaitOne();
            sw1.Start();
            this[isin][tf][dt].Update(tfinfo);
            sw1.Stop();
            m_dictTFMx[isin][tf].ReleaseMutex();
            sw.Stop();

            int tmp = 1;

            /*
             *  if (m_GUIBox != null && CandleBoxUpdated!=null)
             *  m_GUIBox.ExecuteCandlesUpdate(new Action (()=>  CandleBoxUpdated()));
             * else
             *  CandleBoxUpdated();
             */
        }
        public void Update(CTimeFrameInfo tfinfo)
        {
            //  mx.WaitOne();

            /*if (EvntUpdateGUI == null)
             *  UpdateCandle(tfinfo);
             *
             * else
             *  EvntUpdateGUI(new Action(()=> UpdateCandle(tfinfo)));
             */
            sw.Start();
            if (m_subScribedDispatcher != null)
            {
                m_subScribedDispatcher.BeginInvoke(new Action(() => UpdateCandle(tfinfo, true)));
            }
            else
            {
                UpdateCandle(tfinfo, false);
            }

            sw.Stop();
            int tmp = 0;
            // mx.ReleaseMutex();
        }
        private void AnalyzeOnlineTF(ChangedTF changedTF, List <int> lstScale, EnmTF TF_high, EnmTF TF_low, CRawDeal prevDeal, CRawDeal currDeal)
        {
            DateTime dtPrev = prevDeal.Moment;
            DateTime dtCurr = currDeal.Moment;


            //Get  last high TF
            CTimeFrameInfo TFinfo_low = m_dictTFArray.GetLastTimeFrameInfo(TF_low);

            /*  if (!TFinfo_low.bNotProcessedData)
             *    return;
             */


            DateTime dtFrom = new DateTime(0);
            DateTime dtTo   = new DateTime(0);



            bool b_wasChangedTF = changedTF(prevDeal.Moment, currDeal.Moment, lstScale, ref dtFrom, ref dtTo);



            if (!m_dictTFArray.IsContainTimeFrameInfo(TF_high, /*dtFrom*/ dtTo))
            {
                m_dictTFArray.AddNewTimeFrameInfo(m_isin, TF_high, /*dtFrom*/ dtTo, this);
            }

            CTimeFrameInfo TFinfo_low_prev  = m_dictTFArray.GetPrevLastTimeFrameInfo(TF_low);
            CTimeFrameInfo TFinfo_high_prev = m_dictTFArray.GetPrevLastTimeFrameInfo(TF_high);


            CTimeFrameInfo TFinfo_high = m_dictTFArray.GetLastTimeFrameInfo(TF_high);


            bool bChangedExtr = false;


            if (currDeal.ReplID > TFinfo_high.LastReplId)
            {
                TFinfo_high.numOfDeals++;
                TFinfo_high.Volume   += currDeal.Amount;
                TFinfo_high.OpenedPos = currDeal.Pos;

                //changed 2016/08/01
                //only if changed extremum do recalc
                if (TFinfo_high.HighPrice < TFinfo_low.HighPrice)
                {
                    TFinfo_high.HighPrice = currDeal.Price;
                    bChangedExtr          = true;
                }
                if (TFinfo_high.LowPrice > TFinfo_low.LowPrice)
                {
                    TFinfo_high.LowPrice = currDeal.Price;
                    bChangedExtr         = true;
                }

                TFinfo_high.LastReplId = currDeal.ReplID;

                TFinfo_high.LastUpdate = DateTime.Now;

                if (!TFinfo_high.bProcessedData)
                {
                    TFinfo_high.OpenPrice      = TFinfo_low.OpenPrice;
                    TFinfo_high.bProcessedData = true;
                }
                //KAA 2015-12-23
                //because low TF was already updated
                // if (!b_wasChangedTF)
                TFinfo_high.ClosePrice = TFinfo_low.ClosePrice;
                // else
                // TFinfo_high.ClosePrice = TFinfo_low_prev.ClosePrice; //TFinfo_low.ClosePrice;


                DateTime dtcnd = CUtilTime.NormalizeDay(dtFrom);
                //  Plaza2Connector.GUIBox.GUICandleBox.UpdateCandle(this.m_isin, TF_high.ToString(), dtcnd.ToString(), TFinfo_high);

                Plaza2Connector.GUIBox.GUICandleBox.QueueTFinfo(this.m_isin, TF_high.ToString(), dtcnd.ToString(), TFinfo_high);


                //changed 2016/08/01
                //only if changed extremum do recalc
                if (bChangedExtr)
                {
                    TriggerRecalcAllBotsUpdateTF(TF_high, TFinfo_high);
                }

                if (b_wasChangedTF)
                {
                    Log(TF_high.ToString() + " TFinfo_high.Dt=" + TFinfo_high.Dt.ToString() + " was closed prevDeal.Moment=" + prevDeal.Moment + " currDeal.Moment=" + currDeal.Moment + " TFinfo_high.ClosePrice=" + TFinfo_high.ClosePrice +
                        " TFinfo_low_prev.ClosePrice=" + TFinfo_low_prev.ClosePrice + " TFinfo_low_prev.Dt =" + TFinfo_low_prev.Dt);

                    if (Plaza2Connector.IsDealsOnline && Plaza2Connector.IsAnalyzerTFOnline)
                    {
                        TriggerRecalcAllBotsChangedTF(TF_high, TFinfo_high_prev);
                    }
                }
            }
            else
            {
            }


            //  TrapError(m_dictTFArray[TF_high.ToString()][CUtil.NormalizeDay(dtFrom)]);


            int tmp = 1;
        }
        public void UpdateCandle(CTimeFrameInfo tfinfo, bool bNeedGUIUpd)
        {
            int ind = NOT_FOUND;

            try
            {
                sw1.Start();
                sw11.Start();

                sw2.Start();
                sw3.Start();
                sw4.Start();
                sw5.Start();
                sw6.Start();


                mx.WaitOne();
                sw11.Stop();


                // TrapError();

                ind = this.ContainsDate(tfinfo.Dt);
                sw6.Stop();
                if (ind == NOT_FOUND)
                {
                    //if (this.Count > 0 && tfinfo.Dt < this.Last().Date)
                    //  System.Threading.Thread.Sleep(0);


                    this.Add(new GUICandleObject
                    {
                        Date   = tfinfo.Dt,
                        Open   = (double)tfinfo.OpenPrice,
                        Close  = (double)tfinfo.ClosePrice,
                        High   = (double)tfinfo.HighPrice,
                        Low    = (double)tfinfo.LowPrice,
                        Volume = (int)tfinfo.Volume
                    }, bNeedGUIUpd);

                    sw5.Stop();
                    this.Last().UpdateCandle(bNeedGUIUpd);
                    sw4.Stop();
                }
                else
                {
                    GUICandleObject curr = this[ind];

                    /*
                     * this[ind] = new GUICandleObject {
                     * Date = tfinfo.Dt,
                     * Open = (double)tfinfo.OpenPrice,
                     * Close = (double)tfinfo.ClosePrice,
                     * High = (double)tfinfo.HighPrice,
                     * Low = (double)tfinfo.LowPrice,
                     * Volume = (int)tfinfo.Volume,
                     * };
                     */

                    this[ind].Date   = tfinfo.Dt;
                    this[ind].Open   = (double)tfinfo.OpenPrice;
                    this[ind].Close  = (double)tfinfo.ClosePrice;
                    this[ind].High   = (double)tfinfo.HighPrice;
                    this[ind].Low    = (double)tfinfo.LowPrice;
                    this[ind].Volume = (int)tfinfo.Volume;
                    sw5.Stop();
                    this[ind].UpdateCandle(bNeedGUIUpd);
                    DebugPrint(ind);
                    sw4.Stop();
                }

                sw3.Stop();

                //  TrapError();


                //tempo uncomment
                //  NotifyCollectionChanged();
                if (CandleCollectionUpdate != null)
                {
                    CandleCollectionUpdate();
                }
            }
            catch (Exception e)
            {
                Error("CGUICandleCollecion.UpdateCandle", e);
            }
            finally
            {
                sw2.Stop();
                mx.ReleaseMutex();
            }

            sw1.Stop();
            int tmp = 1;
        }
 public void Add(string isin, string tf, string dt, CTimeFrameInfo tfi)
 {
     _q.Add(new CStructTF(isin, tf, dt, (CTimeFrameInfo)tfi.Copy()));
 }
 private void IfNotLastInsert(CTimeFrameInfo tfi)
 {
 }
        private void AnalyzeDiskTF(ChangedTF changedTF, List <int> lstScale, EnmTF TF_high, EnmTF TF_low)
        {
            try
            {
                foreach (KeyValuePair <DateTime, CTimeFrameArray> kvp in m_dictTFArray[TF_low.ToString()]) //all dates of low TF array
                {
                    if (CUtilTime.OlderThanTwoWorkDays(kvp.Key))
                    {
                        continue;
                    }

                    CTimeFrameArray M_low_TF_Array = kvp.Value;
                    for (int i = 1; i < M_low_TF_Array.ListTimeFrameInfo.Count; i++) //each TF array
                    {
                        DateTime dtPrev = M_low_TF_Array.ListTimeFrameInfo[i - 1].Dt;
                        DateTime dtCurr = M_low_TF_Array.ListTimeFrameInfo[i].Dt;



                        DateTime dtFrom = new DateTime(0);
                        DateTime dtTo   = new DateTime(0);

                        if (changedTF(dtPrev, dtCurr, lstScale, ref dtFrom, ref dtTo))
                        {
                            //TO DO chek prev day etc

                            if (m_dictTFArray.IsContainTimeFrameInfo(TF_high, dtFrom))
                            {
                                continue; //if  already exists in high TF array than nothing to do and  continue
                            }
                            //exp logics
                            CTimeFrameInfo ntfi = null;
                            if (m_dictTFArray.GetLatestTFI(TF_high.ToString()) != null)
                            {
                                DateTime dtLast = (m_dictTFArray.GetLatestTFI(TF_high.ToString())).Dt;
                                if (dtLast > dtFrom)
                                {
                                    ntfi = m_dictTFArray.GetNewTFIPuttingtoWritePlace(m_isin, TF_high, dtFrom);
                                    //Error("Inserting data. TO DO check and remove");
                                }
                                else
                                {
                                    ntfi = m_dictTFArray.GetNewTimeFrameInfo(m_isin, TF_high, dtFrom);
                                }
                            }
                            else
                            {
                                ntfi = m_dictTFArray.GetNewTimeFrameInfo(m_isin, TF_high, dtFrom);
                            }



                            int j = i - 1;

                            //note: the last pos
                            ntfi.OpenedPos  = M_low_TF_Array.ListTimeFrameInfo[j].OpenedPos;
                            ntfi.ClosePrice = M_low_TF_Array.ListTimeFrameInfo[j].ClosePrice;


                            while (j >= 0 && M_low_TF_Array.ListTimeFrameInfo[j].Dt >= dtFrom)
                            {
                                CTimeFrameInfo currtfi = M_low_TF_Array.ListTimeFrameInfo[j];
                                ntfi.numOfDeals += currtfi.numOfDeals;
                                ntfi.Volume     += currtfi.Volume;

                                if (ntfi.HighPrice < currtfi.HighPrice)
                                {
                                    ntfi.HighPrice = currtfi.HighPrice;
                                }
                                if (ntfi.LowPrice > currtfi.LowPrice)
                                {
                                    ntfi.LowPrice = currtfi.LowPrice;
                                }

                                ntfi.OpenPrice = M_low_TF_Array.ListTimeFrameInfo[j].OpenPrice;

                                j--; //backward
                            }

                            DateTime dtcnd = CUtilTime.NormalizeDay(dtFrom);

                            //no need ? check !
                            CheckTFIConsistent(ntfi);
                        }
                    }
                    //TrapError(kvp.Value);
                }
            }
            catch (Exception e)
            {
                Error("AnalyzeDiskTF", e);
            }
        }
        private void AnalyzeOnlineM1(CRawDeal rd, CRawDeal prevDeal)
        {
            DateTime dtTill = rd.Moment.AddSeconds(-rd.Moment.Second);

            dtTill = dtTill.AddMilliseconds(-dtTill.Millisecond);


            if (!m_dictTFArray.IsContainTimeFrameInfo(EnmTF.M1, dtTill))
            {
                m_dictTFArray.AddNewTimeFrameInfo(m_isin, EnmTF.M1, dtTill, this);
            }



            CTimeFrameInfo tfi = m_dictTFArray.GetLastTimeFrameInfo(EnmTF.M1);



            DateTime currMoment = rd.Moment;
            CRawDeal currRd     = rd;

            //changed 2016/08/01
            //only if changed extremum do recalc
            bool bChangedExtr = false;

            if (rd.ReplID > tfi.LastReplId)
            {
                tfi.LastReplId = rd.ReplID;
                tfi.OpenedPos  = rd.Pos;
                tfi.Volume    += rd.Amount;
                tfi.numOfDeals++;
                if (currRd.Price > tfi.HighPrice)
                {
                    bChangedExtr  = true;;
                    tfi.HighPrice = currRd.Price;
                }
                if (currRd.Price < tfi.LowPrice)
                {
                    bChangedExtr = true;
                    tfi.LowPrice = currRd.Price;
                }

                tfi.LastUpdate = rd.Moment;

                if (!tfi.bProcessedData)
                {
                    tfi.OpenPrice      = rd.Price;
                    tfi.bProcessedData = true;
                }
                tfi.ClosePrice = rd.Price;

                DateTime dtcnd = CUtilTime.NormalizeDay(dtTill);
                CheckTFIConsistent(tfi);

                //    sw5.Stop();

                //Plaza2Connector.GUIBox.GUICandleBox.UpdateCandle(this.m_isin, EnmTF.M1.ToString(), dtcnd.ToString(), tfi);
                Plaza2Connector.GUIBox.GUICandleBox.QueueTFinfo(this.m_isin, EnmTF.M1.ToString(), dtcnd.ToString(), tfi);
            }

            // TrapError(m_dictTFArray["M1"][CUtil.NormalizeDay(tfi.Dt)]);



            CheckDataOnline(rd);



            if (Plaza2Connector.IsDealsOnline)
            {
                //changed 2016/08/01
                //only if changed extremum do recalc
                if (bChangedExtr)
                {
                    TriggerRecalcAllBotsUpdateTF(EnmTF.M1, tfi);
                }

                DateTime dtTmp  = Plaza2Connector.ServerTime;
                DateTime dtFrom = new DateTime(0);
                DateTime dtTo   = new DateTime(0);

                CTimeFrameInfo tfiPrev = m_dictTFArray.GetPrevLastTimeFrameInfo(EnmTF.M1);


                if (CUtilTF.WasClose_M1_TF(prevDeal.Moment, rd.Moment))
                {
                    Log("M1 was closed prevDeal.Moment=" + prevDeal.Moment + " rd.Moment=" + rd.Moment);
                    if (Plaza2Connector.IsAnalyzerTFOnline)
                    {
                        TriggerRecalcAllBotsChangedTF(EnmTF.M1, tfiPrev);
                    }
                }
            }



            AnalyzeOnlineTF(CUtilTF./*(IsClosed_M5_M15_M30_TF*/ WasClosed_M5_M15_M30_TF, m_M5_scale, EnmTF.M5, EnmTF.M1, prevDeal, rd);


            AnalyzeOnlineTF(CUtilTF./*IsClosed_M5_M15_M30_TF*/ WasClosed_M5_M15_M30_TF, m_M15_scale, EnmTF.M15, EnmTF.M5, prevDeal, rd);



            AnalyzeOnlineTF(CUtilTF./*IsClosed_M5_M15_M30_TF*/ WasClosed_M5_M15_M30_TF, m_M30_scale, EnmTF.M30, EnmTF.M15, prevDeal, rd);



            AnalyzeOnlineTF(CUtilTF./*IsClosed_H1*/ WasClosed_H1, m_M30_scale, EnmTF.H1, EnmTF.M30, prevDeal, rd);


            AnalyzeOnlineTF(CUtilTF./*IsClosed_D1*/ WasClosed_D1, m_M30_scale, EnmTF.D1, EnmTF.H1, prevDeal, rd);


            CTimeFrameInfo TFinfo_D1 = m_dictTFArray.GetLastTimeFrameInfo(EnmTF.D1);

            LowDayPrice  = TFinfo_D1.LowPrice;
            HighDayPrice = TFinfo_D1.HighPrice;
        }