// Specify what you want to happen when the Elapsed event is raised.
        private  void OnHeartBeat(object source, ElapsedEventArgs e)
        {
            try
            {


                // è scattato un heartbeat
                //var stop = false;
                CUtility.Log("*** heartbeat");

                // verifico lo stato del mercato
                _market.GetTicker();

                // aggiorno la mia situazione
                _market.GetWallet();

                /*
                // trend
                _trend = _market.Trend.CalculateTrend();

                // ema
                _ema = _market.Trend.Ema;

                // il trend deve essere affidabile altrimenti esce
                if (!_market.Trend.TrendIsValid)
                {
                    return;
                }
                */
                if (!_market.CandleMaker.Analyze.IsValid())
                {
                    return;
                }
                

                // elimina le bolle (ad ogni tick.. prima si fa e meglio è)
                var hasExplodedBubbles = CheckBubbles();

                // check wishlist
                var hasResolvedWishList = CheckWishList();

                if (!hasExplodedBubbles && !hasResolvedWishList)
                {
                    // strategia per il tick
                    if (_configuration.TickDynamic)
                    {
                        _ticksPerHearthBeat = NextTick(_ticksPerHearthBeat);
                    }

                    // verifico se deve scattare un tick
                    _tickCounter++;
                    if (_tickCounter >= _ticksPerHearthBeat)
                    {
                        // non uso il mod perchè potrei dover usare un 
                        // cambio dinamico al tickcounter
                        _tickCounter = 0;
                        OnTick();

                    }
                }
                // al termine dei task decido se fermare il processo oppure no

                if (_market.Stop)
                {
                    _stopwatch.Stop();
                    _heartBeatTimer.Enabled = false;
                    CUtility.Log("Time Elapsed : " + _stopwatch.Elapsed);
                }

                // secondo me questo è il momento in cui vanno salvate le persistenze
            }
            catch (Exception)
            {
                CUtility.Log("Error in hearthbeat : ");
                //throw;
            }
            finally
            {
                CUtility.Log("Created  : " + this._bubblesCreated);
                CUtility.Log("Exploded : " + this._bubblesExploded);
                CUtility.Log("Canceled : " + this._bubblesCanceled);
                CUtility.Log("Whish    : " + this.WishList.Count);
            }
        }
        // Specify what you want to happen when the Elapsed event is raised.
        private void OnHeartBeat(object source, ElapsedEventArgs e)
        {
            try
            {
                // verifico lo stato del mercato
                // aziono il candlemaker
                if (!Market.GetTicker())
                {
                    // c'è stato un errore
                    Log("** ticker error");
                    return;
                }


                if (!Market.CandleMaker.Analyze.IsValid())
                {
                    // il candlemaker non puo' fare previsioni
                    Log("** Analyzer not yet ready");
                    return;
                }

                // gestendo la creazione delle candele occorre ripensare l'heartbeat
                //
                if (_lastCandleId != Market.CandleMaker.CurrentCandleId)
                {
                    LogTrade.Init();

                    // aggiorno la mia situazione
                    Market.GetWallet();

                    var candlemaker = Market.CandleMaker;
                    this.SuggestedAction      = candlemaker.Analyze.SuggestedAction(this.Market);
                    this.CurrentTrend         = candlemaker.Analyze.CurrentTrend;
                    this.CurrentLongTermTrend = candlemaker.LongTermTrend();

                    OnHeartBeat();

                    var eval = Evaluations.EvaluationManager.Instance;
                    eval.Evaluate(Market.CandleMaker.CurrentCandleDate, Market.Buy);

                    if (this.Statistics.StartValue == decimal.MinValue && this.Market.TotValue > 0)
                    {
                        this.Statistics.StartValue = this.Market.TotValue;
                    }
                    this.Statistics.EndValue = this.Market.TotValue;

                    if (MainConfiguration.Configuration.GenerateOutputTradeHistory)
                    {
                        using (var fileStreamOut = new StreamWriter(string.Format(@"data\output\output{0}.csv", MainConfiguration.Configuration.SessionId), true)
                        {
                            AutoFlush = true
                        })
                        {
                            LogTrade.CandleDate = candlemaker.CurrentCandleDate;
                            LogTrade.Bid        = this.Market.Buy;

                            LogTrade.EmaDiff      = candlemaker.Analyze.CurrentEmaDiff;
                            LogTrade.Macd         = candlemaker.Analyze.CurrentMacdValue;
                            LogTrade.MacdStandard = candlemaker.Analyze.Values.Derivative.CurrentSpeed;
                            //this.Market.CandleMaker.Analyze.EmaDiff.Derivative.CurrentSpeed;
                            LogTrade.Roc = candlemaker.Analyze.Rocdiff; //this.Statistics.Gain;
                            //this.Market.CandleMaker.Analyze.MacdList[0].Macd.Derivative.CurrentSpeed;

                            LogTrade.SuggestedAction      = this.SuggestedAction;
                            LogTrade.CurrentTrend         = this.CurrentTrend;
                            LogTrade.CurrentLongTermTrend = this.CurrentLongTermTrend;

                            LogTrade.TotMoney = this.Market.TotMoney;
                            LogTrade.TotCoins = this.Market.TotCoins;
                            LogTrade.TotValue = this.Market.TotValue;

                            fileStreamOut.WriteLine(LogTrade.CsvRow());

                            Cloud.CloudManager.Push(MainConfiguration.Configuration.SessionId.ToString(), "output", LogTrade.ToObjectInstance());
                        }
                    }
                    //}

                    // loggo i valori parziali
                    if (candlemaker.CurrentCandleDate.Day == 1 &&
                        candlemaker.CurrentCandleDate.Hour == 0 &&
                        candlemaker.CurrentCandleDate.Minute == 0)
                    {
                        AnalyticsTools.ProgressList.List.Add(new Progress()
                        {
                            Coins = Market.TotCoins,
                            Money = Market.TotMoney,
                            Value = Market.TotValue,
                            Month = candlemaker.CurrentCandleDate.Month,
                            Year  = candlemaker.CurrentCandleDate.Year
                        });
                    }


                    _averageDailyPriceTmpSum += (candlemaker.GetLastCandles()[0].High + candlemaker.GetLastCandles()[0].Low) / 2;
                    _averageDailyPriceTmpNum++;
                    // prezzo medio giornaliero
                    if (candlemaker.CurrentCandleDate.Hour == 0 &&
                        candlemaker.CurrentCandleDate.Minute == 0)
                    {
                        this.Statistics.AverageDailyPrice = _averageDailyPriceTmpNum != 0 ? _averageDailyPriceTmpSum / _averageDailyPriceTmpNum : 0;
                        _averageDailyPriceTmpSum          = 0;
                        _averageDailyPriceTmpNum          = 0;
                    }

                    Log(string.Format("{0} ", Market.UniqueName));
                    Log("Date  : " + candlemaker.CurrentCandleDate.ToString(CultureInfo.InvariantCulture));
                    Log("Money : " + Math.Round(this.Market.TotMoney, 4).ToString(CultureInfo.InvariantCulture));
                    Log("SMoney: " + Math.Round(this.SavedMoney, 4).ToString(CultureInfo.InvariantCulture));
                    Log("Coins : " + Math.Round(this.Market.TotCoins, 4).ToString(CultureInfo.InvariantCulture));
                    Log("SMCoin: " + Math.Round(this.SavedCoins, 4).ToString(CultureInfo.InvariantCulture));
                    Log("Value : " + Math.Round(this.Market.TotValue, 4).ToString(CultureInfo.InvariantCulture));
                    Log("Gain% : " + Math.Round(this.Statistics.Gain, 2).ToString(CultureInfo.InvariantCulture));
                    Log("Bid   : " + Math.Round(this.Market.Buy, 4).ToString(CultureInfo.InvariantCulture));
                    Log("Bid ad: " + Math.Round(this.Statistics.AverageDailyPrice, 4).ToString(CultureInfo.InvariantCulture));
                    Log("EMA   : " + Math.Round(candlemaker.Analyze.CurrentEmaDiff, 4).ToString(CultureInfo.InvariantCulture));
                    Log("MACD  : " + Math.Round(candlemaker.Analyze.CurrentMacdValue, 4).ToString(CultureInfo.InvariantCulture));
                    //Log("ROC   : " + Math.Round(this.Market.CandleMaker.Analyze.CurrentMacdValue, 4).ToString(CultureInfo.InvariantCulture));

                    Log("Trend : " + this.CurrentTrend.ToString());
                    Log("LTrend: " + CurrentLongTermTrend.ToString());
                    Log("Sugg  : " + this.SuggestedAction.ToString());
                    Log("Action: " + LogTrade.Action);
                    Log("Messag: " + LogTrade.Motivation);
                    Log("Note  : " + LogTrade.Note);
                    Log("");
                }

                /*
                 * // verifico se deve scattare un tick
                 * TickCounter++;
                 * if (TickCounter >= MainConfiguration.Configuration.RealTimeTickEveryHeartBeats)
                 * {
                 *  // non uso il mod perchè potrei dover usare un
                 *  // cambio dinamico al tickcounter
                 *  TickCounter = 0;
                 *  //Log("*** heartbeat");
                 *  OnTick();
                 *
                 * }
                 */

                _lastCandleId = Market.CandleMaker.CurrentCandleId;

                // al termine dei task decido se fermare il processo oppure no

                if (Market.Stop)
                {
                    _stopwatch.Stop();
                    HeartBeatTimer.Enabled = false;

                    AnalyticsTools.ProgressList.List.Add(new Progress()
                    {
                        Coins = Market.TotCoins,
                        Money = Market.TotMoney,
                        Value = Market.TotValue,
                        Month = Market.CandleMaker.CurrentCandleDate.Month,
                        Year  = Market.CandleMaker.CurrentCandleDate.Year
                    });

                    using (var stream = new StreamWriter(@"data\output\timing.csv", true)
                    {
                        AutoFlush = true
                    })
                    {
                        AnalyticsTools.ProgressList.Print(stream);
                        stream.WriteLine(",,,,");
                        AnalyticsTools.ProgressList.List.Clear();
                    }

                    /*
                     * if (_fileStreamOut != null)
                     * {
                     *  _fileStreamOut.Close();
                     *  _fileStreamOut.Dispose();
                     *  _fileStreamOut = null;
                     * }
                     */
                    Log("Time Elapsed : " + _stopwatch.Elapsed);
                }

                // secondo me questo è il momento in cui vanno salvate le persistenze
            }
            catch (Exception ex)
            {
                Log("Error in hearthbeat : " + ex.Message);
                //throw;
            }
            finally
            {
            }
        }