diff --git a/Core/DataObjects/ProfitTrailerData.cs b/Core/DataObjects/ProfitTrailerData.cs index 9e04667..dae645f 100644 --- a/Core/DataObjects/ProfitTrailerData.cs +++ b/Core/DataObjects/ProfitTrailerData.cs @@ -136,7 +136,7 @@ namespace Core.Main.DataObjects public double GetCurrentBalance() { - return this.GetSnapshotBalance(DateTime.Now.ToUniversalTime()); + return this.GetSnapshotBalance(DateTime.UtcNow); } public double GetSnapshotBalance(DateTime snapshotDateTime) diff --git a/Core/Helper/FileHelper.cs b/Core/Helper/FileHelper.cs index f2bb1c9..e262561 100644 --- a/Core/Helper/FileHelper.cs +++ b/Core/Helper/FileHelper.cs @@ -64,9 +64,9 @@ namespace Core.Helper DirectoryInfo folder = new DirectoryInfo(folderPath); foreach (FileInfo file in folder.GetFiles()) { - DateTime maxAge = DateTime.Now.AddMinutes(-maxMinutes); + DateTime maxAge = DateTime.UtcNow.AddMinutes(-maxMinutes); - if (file.LastWriteTime < maxAge) + if (file.LastWriteTimeUtc < maxAge) { File.Delete(file.FullName); } @@ -83,9 +83,9 @@ namespace Core.Helper DirectoryInfo folder = new DirectoryInfo(folderPath); foreach (FileInfo file in folder.GetFiles()) { - DateTime maxAge = DateTime.Now.AddHours(-(maxHours + 1)); + DateTime maxAge = DateTime.UtcNow.AddHours(-(maxHours + 1)); - if (file.LastWriteTime < maxAge) + if (file.LastWriteTimeUtc < maxAge) { File.Delete(file.FullName); } diff --git a/Core/Main/PTMagic.cs b/Core/Main/PTMagic.cs index f66faad..de3e60b 100644 --- a/Core/Main/PTMagic.cs +++ b/Core/Main/PTMagic.cs @@ -31,8 +31,6 @@ namespace Core.Main private int _state = 0; private int _runCount = 0; private int _totalElapsedSeconds = 0; - private int _configCheckRetryCount = 0; - private bool _configCheckResult = true; private bool _globalSettingWritten = false; private bool _singleMarketSettingWritten = false; private bool _enforceSettingsReapply = false; @@ -510,6 +508,30 @@ namespace Core.Main #endregion #region PTMagic Startup Methods + + private static int ExponentialDelay(int failedAttempts, + int maxDelayInSeconds = 900) + { + //Attempt 1 0s 0s + //Attempt 2 2s 2s + //Attempt 3 4s 4s + //Attempt 4 8s 8s + //Attempt 5 16s 16s + //Attempt 6 32s 32s + + //Attempt 7 64s 1m 4s + //Attempt 8 128s 2m 8s + //Attempt 9 256s 4m 16s + //Attempt 10 512 8m 32s + //Attempt 11 1024 17m 4s + + var delayInSeconds = ((1d / 2d) * (Math.Pow(2d, failedAttempts) - 1d)); + + return maxDelayInSeconds < delayInSeconds + ? maxDelayInSeconds + : (int)delayInSeconds; + } + public bool StartProcess() { bool result = true; @@ -535,27 +557,28 @@ namespace Core.Main return false; } - _configCheckResult = this.RunConfigurationChecks(); - if (!_configCheckResult) - { - this.Log.DoLogInfo("Starting configuration check retry in 10 seconds..."); - System.Timers.Timer configCheckTimer = new System.Timers.Timer(10000); - configCheckTimer.Enabled = true; - configCheckTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.ConfigCheckTimer_Elapsed); + bool configCheckResult = this.RunConfigurationChecks(); - while (!_configCheckResult && _configCheckRetryCount < 20) + if (!configCheckResult) + { + // Config check failed so retry using an exponential back off until it passes; max retry time 15 mins. + int configRetryCount = 1; + int delaySeconds; + + while (!configCheckResult) { - Thread.Sleep(100); + delaySeconds = ExponentialDelay(configRetryCount); + this.Log.DoLogError("Configuration check retry " + configRetryCount + " failed, starting next retry in " + delaySeconds + " seconds..."); + Thread.Sleep(delaySeconds * 1000); + + // Reinit config in case the user changed something + this.InitializeConfiguration(); + configCheckResult = this.RunConfigurationChecks(); + configRetryCount++; } - configCheckTimer.Stop(); } - if (!_configCheckResult) - { - return false; - } - - this.LastSettingFileCheck = DateTime.Now; + this.LastSettingFileCheck = DateTime.UtcNow; SettingsFiles.CheckPresets(this.PTMagicConfiguration, this.Log, true); @@ -662,7 +685,7 @@ namespace Core.Main } // Check for CoinMarketCap API Key - if (!this.PTMagicConfiguration.GeneralSettings.Application.CoinMarketCapAPIKey.Equals("")) + if (!String.IsNullOrEmpty(this.PTMagicConfiguration.GeneralSettings.Application.CoinMarketCapAPIKey)) { this.Log.DoLogInfo("CoinMarketCap API KEY found"); } @@ -678,7 +701,7 @@ namespace Core.Main } else { - this.Log.DoLogInfo("No FreeCurrencyConverterApi KEY specified! You can't use non USD Currencies!"); + this.Log.DoLogInfo("No FreeCurrencyConverterApi KEY specified, you can only use USD; apply for a key at: https://freecurrencyrates.com/en"); } } @@ -698,7 +721,7 @@ namespace Core.Main this.Log.DoLogInfo("========== STARTING CHECKS FOR Profit Trailer =========="); // Check for PT license key - if (!this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerLicense.Equals("")) + if (!String.IsNullOrEmpty(this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerLicense)) { this.Log.DoLogInfo("Profit Trailer check: Profit Trailer license found"); } @@ -709,18 +732,18 @@ namespace Core.Main } //Check for ptServerAPIToken - if (!this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerServerAPIToken.Equals("")) + if (!String.IsNullOrEmpty(this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerServerAPIToken)) { this.Log.DoLogInfo("Profit Trailer check: Profit Trailer Server API Token Specified"); } else { - this.Log.DoLogError("Profit Trailer check: No Server API Token specified. It has to be the same Token as in the Profit Trailer Config File"); + this.Log.DoLogError("Profit Trailer check: No Server API Token specified. Please configure ProfitTrailerServerAPIToken in settings.general.json , ensuring it has to be the same Token as in the Profit Trailer Config File!"); result = false; } // Check for PT default setting key - if (!this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerDefaultSettingName.Equals("")) + if (!String.IsNullOrEmpty(this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerDefaultSettingName)) { this.Log.DoLogInfo("Profit Trailer check: Profit Trailer default setting name specified"); } @@ -731,7 +754,7 @@ namespace Core.Main } // Check for PT monitor - if (!this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerMonitorURL.Equals("")) + if (!String.IsNullOrEmpty(this.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerMonitorURL)) { this.Log.DoLogInfo("Profit Trailer check: Profit Trailer monitor URL found"); } @@ -778,17 +801,6 @@ namespace Core.Main #endregion #region PTMagic Interval Methods - public void ConfigCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) - { - // Reinit config in case the user changed something - this.InitializeConfiguration(); - _configCheckResult = this.RunConfigurationChecks(); - _configCheckRetryCount++; - if (!_configCheckResult) - { - this.Log.DoLogError("Configuration check retry " + _configCheckRetryCount + "/10 failed, starting next retry in 5 seconds..."); - } - } public void PTMagicIntervalTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { @@ -815,7 +827,7 @@ namespace Core.Main // Change state to "Running" this.State = Constants.PTMagicBotState_Running; - this.LastRuntime = DateTime.Now; + this.LastRuntime = DateTime.UtcNow; this.LastRuntimeSummary = new Summary(); this.LastRuntimeSummary.LastRuntime = this.LastRuntime; @@ -891,7 +903,7 @@ namespace Core.Main if (File.Exists(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + "LastRuntimeSummary.json")) { FileInfo fiLastSummary = new FileInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + "LastRuntimeSummary.json"); - if (fiLastSummary.LastWriteTime < DateTime.Now.AddMinutes(-(this.PTMagicConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes * 2))) + if (fiLastSummary.LastWriteTimeUtc < DateTime.UtcNow.AddMinutes(-(this.PTMagicConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes * 2))) { Log.DoLogWarn("PTMagic seems to have frozen after raid " + this.RunCount.ToString() + ", but don't worry I will sacrifice some Magicbots to get this running again..."); this.State = Constants.PTMagicBotState_Idle; @@ -914,7 +926,7 @@ namespace Core.Main FileInfo generalSettingsFile = new FileInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "settings.general.json"); FileInfo analyzerSettingsFile = new FileInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "settings.analyzer.json"); - if (generalSettingsFile.LastWriteTime > this.LastSettingFileCheck || analyzerSettingsFile.LastWriteTime > this.LastSettingFileCheck || EnforceSettingsReapply) + if (generalSettingsFile.LastWriteTimeUtc > this.LastSettingFileCheck || analyzerSettingsFile.LastWriteTimeUtc > this.LastSettingFileCheck || EnforceSettingsReapply) { Log.DoLogInfo("Detected configuration changes. Reloading settings..."); @@ -945,7 +957,7 @@ namespace Core.Main } Log.DoLogInfo("New configuration reloaded."); - this.LastSettingFileCheck = DateTime.Now; + this.LastSettingFileCheck = DateTime.UtcNow; result = true; if (this.Timer.Interval != this.PTMagicConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes * 60 * 1000) @@ -987,7 +999,7 @@ namespace Core.Main } else { - if (this.PTMagicConfiguration.GeneralSettings.Application.Exchange.Equals("")) + if (String.IsNullOrEmpty(this.PTMagicConfiguration.GeneralSettings.Application.Exchange)) { Log.DoLogError("Your setting for Application.Exchange in settings.general.json is invalid (empty)! Terminating process."); this.Timer.Stop(); @@ -1010,10 +1022,10 @@ namespace Core.Main private void CheckLatestGitHubVersion(string currentVersion) { // Get latest version number - if (this.LastVersionCheck < DateTime.Now.AddMinutes(-30)) + if (this.LastVersionCheck < DateTime.UtcNow.AddMinutes(-30)) { this.LatestVersion = BaseAnalyzer.GetLatestGitHubRelease(this.Log, currentVersion); - this.LastVersionCheck = DateTime.Now; + this.LastVersionCheck = DateTime.UtcNow; if (!SystemHelper.IsRecentVersion(currentVersion, this.LatestVersion)) { this.Log.DoLogWarn("Your bot is out of date! The most recent version of PTMagic is " + this.LatestVersion); @@ -1026,7 +1038,7 @@ namespace Core.Main this.LastRuntimeSummary.MainFiatCurrency = this.LastMainFiatCurrency; this.LastRuntimeSummary.MainFiatCurrencyExchangeRate = this.LastMainFiatCurrencyExchangeRate; - if (this.LastFiatCurrencyCheck < DateTime.Now.AddHours(-12) && !this.PTMagicConfiguration.GeneralSettings.Application.MainFiatCurrency.Equals("USD", StringComparison.InvariantCultureIgnoreCase)) + if (this.LastFiatCurrencyCheck < DateTime.UtcNow.AddHours(-12) && !this.PTMagicConfiguration.GeneralSettings.Application.MainFiatCurrency.Equals("USD", StringComparison.InvariantCultureIgnoreCase)) { try { @@ -1035,7 +1047,7 @@ namespace Core.Main this.LastMainFiatCurrency = this.LastRuntimeSummary.MainFiatCurrency; this.LastMainFiatCurrencyExchangeRate = this.LastRuntimeSummary.MainFiatCurrencyExchangeRate; - this.LastFiatCurrencyCheck = DateTime.Now; + this.LastFiatCurrencyCheck = DateTime.UtcNow; } catch (Exception ex) { @@ -1122,7 +1134,7 @@ namespace Core.Main private void BuildMarketData() { - if (!this.PTMagicConfiguration.GeneralSettings.Application.CoinMarketCapAPIKey.Equals("")) + if (!String.IsNullOrEmpty(this.PTMagicConfiguration.GeneralSettings.Application.CoinMarketCapAPIKey)) { // Get most recent market data from CMC string cmcMarketDataResult = CoinMarketCap.GetMarketData(this.PTMagicConfiguration, this.Log); @@ -1164,7 +1176,7 @@ namespace Core.Main private void BuildMarketList() { string marketPairs = SettingsHandler.GetMarketPairs(this.PTMagicConfiguration, this.PairsLines, this.Log); - if (marketPairs.ToLower().Equals("all") || marketPairs.ToLower().Equals("false") || marketPairs.ToLower().Equals("true") || marketPairs.Equals("")) + if (marketPairs.ToLower().Equals("all") || marketPairs.ToLower().Equals("false") || marketPairs.ToLower().Equals("true") || String.IsNullOrEmpty(marketPairs)) { this.MarketList = this.ExchangeMarketList; } @@ -1309,7 +1321,7 @@ namespace Core.Main private void ActivateSetting(ref bool headerLinesAdded, ref GlobalSetting triggeredSetting, ref List matchedTriggers) { string activeSettingName = SettingsHandler.GetActiveSetting(this, ref headerLinesAdded); - if (activeSettingName.Equals("") && this.PTMagicConfiguration.GeneralSettings.Application.TestMode) + if (String.IsNullOrEmpty(activeSettingName) && this.PTMagicConfiguration.GeneralSettings.Application.TestMode) { activeSettingName = this.ActiveSetting; } @@ -1667,7 +1679,7 @@ namespace Core.Main if (marketInfo != null) { - int marketAge = (int)Math.Floor(DateTime.Now.ToUniversalTime().Subtract(marketInfo.FirstSeen).TotalDays); + int marketAge = (int)Math.Floor(DateTime.UtcNow.Subtract(marketInfo.FirstSeen).TotalDays); if (marketAge < trigger.AgeDaysLowerThan) { matchedSingleMarketTriggers.Add(marketSetting.SettingName + ": '" + marketPair + "' is only " + marketAge.ToString() + " days old on this exchange. Trigger matched!"); @@ -1989,7 +2001,7 @@ namespace Core.Main private void SaveRuntimeSummary(bool headerLinesAdded) { - DateTime endTime = DateTime.Now; + DateTime endTime = DateTime.UtcNow; int elapsedSeconds = (int)Math.Round(endTime.Subtract(this.LastRuntime).TotalSeconds, 0); this.LastRuntimeSummary.LastRuntimeSeconds = elapsedSeconds; @@ -2014,11 +2026,11 @@ namespace Core.Main // Market trend changes history for graph data foreach (string key in summary.MarketTrendChanges.Keys) { - this.LastRuntimeSummary.MarketTrendChanges.Add(key, summary.MarketTrendChanges[key].FindAll(mtc => mtc.TrendDateTime >= DateTime.Now.AddHours(-PTMagicConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours))); + this.LastRuntimeSummary.MarketTrendChanges.Add(key, summary.MarketTrendChanges[key].FindAll(mtc => mtc.TrendDateTime >= DateTime.UtcNow.AddHours(-PTMagicConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours))); } // Global setting summary to be kept - this.LastRuntimeSummary.GlobalSettingSummary.AddRange(summary.GlobalSettingSummary.FindAll(gss => gss.SwitchDateTime >= DateTime.Now.AddHours(-96))); + this.LastRuntimeSummary.GlobalSettingSummary.AddRange(summary.GlobalSettingSummary.FindAll(gss => gss.SwitchDateTime >= DateTime.UtcNow.AddHours(-96))); this.Log.DoLogInfo("Summary: Loaded old LastRuntimeSummary.json to keep data."); } @@ -2044,7 +2056,7 @@ namespace Core.Main if (this.LastRuntimeSummary.GlobalSettingSummary.Count > 0) { lastSettingSummary = this.LastRuntimeSummary.GlobalSettingSummary.OrderByDescending(lss => lss.SwitchDateTime).First(); - lastSettingSummary.ActiveSeconds = (int)Math.Ceiling(DateTime.Now.ToUniversalTime().Subtract(lastSettingSummary.SwitchDateTime).TotalSeconds); + lastSettingSummary.ActiveSeconds = (int)Math.Ceiling(DateTime.UtcNow.Subtract(lastSettingSummary.SwitchDateTime).TotalSeconds); } this.LastRuntimeSummary.GlobalSettingSummary.Add(gss); @@ -2058,7 +2070,7 @@ namespace Core.Main if (this.LastRuntimeSummary.GlobalSettingSummary.Count > 0) { lastSettingSummary = this.LastRuntimeSummary.GlobalSettingSummary.OrderByDescending(lss => lss.SwitchDateTime).First(); - lastSettingSummary.ActiveSeconds = (int)Math.Ceiling(DateTime.Now.ToUniversalTime().Subtract(lastSettingSummary.SwitchDateTime).TotalSeconds); + lastSettingSummary.ActiveSeconds = (int)Math.Ceiling(DateTime.UtcNow.Subtract(lastSettingSummary.SwitchDateTime).TotalSeconds); } } @@ -2170,7 +2182,7 @@ namespace Core.Main for (int dca = 1; dca <= maxDCALevel; dca++) { string dcaTriggerString = SettingsHandler.GetCurrentPropertyValue(dcaProperties, "buy_trigger_" + dca.ToString(), "DEFAULT_DCA_buy_trigger_" + dca.ToString()); - if (!dcaTriggerString.Equals("")) + if (!String.IsNullOrEmpty(dcaTriggerString)) { double dcaTrigger = SystemHelper.TextToDouble(dcaTriggerString, 0, "en-US"); @@ -2193,7 +2205,7 @@ namespace Core.Main for (int dca = 1; dca <= maxDCALevel; dca++) { string dcaPercentageString = SettingsHandler.GetCurrentPropertyValue(dcaProperties, "DEFAULT_DCA_buy_percentage_" + dca.ToString(), ""); - if (!dcaPercentageString.Equals("")) + if (!String.IsNullOrEmpty(dcaPercentageString)) { double dcaPercentage = SystemHelper.TextToDouble(dcaPercentageString, 0, "en-US"); @@ -2210,7 +2222,7 @@ namespace Core.Main for (char c = 'A'; c <= 'Z'; c++) { string buyStrategyName = SettingsHandler.GetCurrentPropertyValue(pairsProperties, "DEFAULT_" + c + "_buy_strategy", ""); - if (!buyStrategyName.Equals("")) + if (!String.IsNullOrEmpty(buyStrategyName)) { StrategySummary buyStrategy = new StrategySummary(); buyStrategy.Name = buyStrategyName; @@ -2228,7 +2240,7 @@ namespace Core.Main for (char c = 'A'; c <= 'Z'; c++) { string sellStrategyName = SettingsHandler.GetCurrentPropertyValue(pairsProperties, "DEFAULT_" + c + "_sell_strategy", ""); - if (!sellStrategyName.Equals("")) + if (!String.IsNullOrEmpty(sellStrategyName)) { StrategySummary sellStrategy = new StrategySummary(); sellStrategy.Name = sellStrategyName; @@ -2246,7 +2258,7 @@ namespace Core.Main for (char c = 'A'; c <= 'Z'; c++) { string buyStrategyName = SettingsHandler.GetCurrentPropertyValue(dcaProperties, "DEFAULT_DCA_" + c + "_buy_strategy", ""); - if (!buyStrategyName.Equals("")) + if (!String.IsNullOrEmpty(buyStrategyName)) { StrategySummary buyStrategy = new StrategySummary(); buyStrategy.Name = buyStrategyName; @@ -2264,7 +2276,7 @@ namespace Core.Main for (char c = 'A'; c <= 'Z'; c++) { string sellStrategyName = SettingsHandler.GetCurrentPropertyValue(dcaProperties, "DEFAULT_DCA_" + c + "_sell_strategy", ""); - if (!sellStrategyName.Equals("")) + if (!String.IsNullOrEmpty(sellStrategyName)) { StrategySummary sellStrategy = new StrategySummary(); sellStrategy.Name = sellStrategyName; @@ -2325,7 +2337,7 @@ namespace Core.Main for (char c = 'A'; c <= 'Z'; c++) { string buyStrategyName = SettingsHandler.GetCurrentPropertyValue(pairsProperties, marketPairSimple + "_" + c + "_buy_strategy", ""); - if (!buyStrategyName.Equals("")) + if (!String.IsNullOrEmpty(buyStrategyName)) { StrategySummary buyStrategy = new StrategySummary(); buyStrategy.Name = buyStrategyName; @@ -2344,7 +2356,7 @@ namespace Core.Main for (char c = 'A'; c <= 'Z'; c++) { string sellStrategyName = SettingsHandler.GetCurrentPropertyValue(pairsProperties, marketPairSimple + "_" + c + "_sell_strategy", ""); - if (!sellStrategyName.Equals("")) + if (!String.IsNullOrEmpty(sellStrategyName)) { StrategySummary sellStrategy = new StrategySummary(); sellStrategy.Name = sellStrategyName; diff --git a/Core/MarketAnalyzer/BaseAnalyzer.cs b/Core/MarketAnalyzer/BaseAnalyzer.cs index 520150d..ca38f1b 100644 --- a/Core/MarketAnalyzer/BaseAnalyzer.cs +++ b/Core/MarketAnalyzer/BaseAnalyzer.cs @@ -27,9 +27,11 @@ namespace Core.MarketAnalyzer request.UserAgent = "PTMagic.Import"; request.KeepAlive = true; + HttpWebResponse httpResponse = null; + try { - HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse(); + httpResponse = (HttpWebResponse)request.GetResponse(); StreamReader jsonReader = new StreamReader(httpResponse.GetResponseStream()); string jsonString = jsonReader.ReadToEnd(); @@ -41,7 +43,18 @@ namespace Core.MarketAnalyzer } catch (WebException ex) { - log.DoLogCritical(ex.Message, ex); + // Error calling the service but we got a response so dump it. + string responseString = string.Empty; + var encoding = httpResponse.CharacterSet == "" ? Encoding.UTF8 : Encoding.GetEncoding(httpResponse.CharacterSet); + + using (var stream = httpResponse.GetResponseStream()) + { + var reader = new StreamReader(stream, encoding); + responseString = reader.ReadToEnd(); + } + + log.DoLogCritical(String.Format("{0} - Response: ({1}) {2} : {3}", ex.Message, httpResponse.StatusCode, httpResponse.StatusDescription, responseString), ex); + throw ex; } catch (Exception ex) @@ -199,7 +212,7 @@ namespace Core.MarketAnalyzer { double result = 1; - string baseUrl = "http://free.currencyconverterapi.com/api/v5/convert?q=USD_" + currency + "&compact=y&apiKey="+FreeCurrencyAPI; + string baseUrl = "http://free.currencyconverterapi.com/api/v5/convert?q=USD_" + currency + "&compact=y&apiKey=" + FreeCurrencyAPI; log.DoLogDebug("http://free.currencyconverterapi.com - Getting latest exchange rates..."); Newtonsoft.Json.Linq.JObject jsonObject = GetSimpleJsonObjectFromURL(baseUrl, log, false); @@ -300,7 +313,7 @@ namespace Core.MarketAnalyzer List marketTrends = systemConfiguration.AnalyzerSettings.MarketAnalyzer.MarketTrends.FindAll(mt => mt.Platform.Equals(platform, StringComparison.InvariantCultureIgnoreCase)); if (marketTrends.Count > 0) { - Dictionary recentMarkets = BaseAnalyzer.GetMarketDataFromFile(systemConfiguration, log, platform, DateTime.Now.ToUniversalTime(), "Recent"); + Dictionary recentMarkets = BaseAnalyzer.GetMarketDataFromFile(systemConfiguration, log, platform, DateTime.UtcNow, "Recent"); foreach (MarketTrend marketTrend in marketTrends) { @@ -313,7 +326,7 @@ namespace Core.MarketAnalyzer log.DoLogInfo(platform + " - Building market trend changes for '" + marketTrend.Name + "'..."); } - Dictionary trendMarkets = BaseAnalyzer.GetMarketDataFromFile(systemConfiguration, log, platform, DateTime.Now.ToUniversalTime().AddMinutes(-marketTrend.TrendMinutes), marketTrend.Name); + Dictionary trendMarkets = BaseAnalyzer.GetMarketDataFromFile(systemConfiguration, log, platform, DateTime.UtcNow.AddMinutes(-marketTrend.TrendMinutes), marketTrend.Name); List marketTrendChanges = BaseAnalyzer.GetMarketTrendChanges(platform, mainMarket, marketTrend, marketList, recentMarkets, trendMarkets, sortBy, isGlobal, systemConfiguration, log); @@ -407,7 +420,7 @@ namespace Core.MarketAnalyzer mtc.Market = recentMarket.Name; mtc.LastPrice = recentMarket.Price; mtc.Volume24h = recentMarket.Volume24h; - mtc.TrendDateTime = DateTime.Now; + mtc.TrendDateTime = DateTime.UtcNow; result.Add(mtc); diff --git a/Core/MarketAnalyzer/Binance.cs b/Core/MarketAnalyzer/Binance.cs index 1b31c0d..083911f 100644 --- a/Core/MarketAnalyzer/Binance.cs +++ b/Core/MarketAnalyzer/Binance.cs @@ -106,7 +106,7 @@ namespace Core.MarketAnalyzer Binance.CheckForMarketDataRecreation(mainMarket, markets, systemConfiguration, log); - DateTime fileDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0).ToUniversalTime(); + DateTime fileDateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, 0).ToUniversalTime(); FileHelper.WriteTextToFile(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathExchange + Path.DirectorySeparatorChar, "MarketData_" + fileDateTime.ToString("yyyy-MM-dd_HH.mm") + ".json", JsonConvert.SerializeObject(markets), fileDateTime, fileDateTime); @@ -188,7 +188,7 @@ namespace Core.MarketAnalyzer marketInfo.FirstSeen = Binance.GetFirstSeenDate(key, systemConfiguration, log); } } - marketInfo.LastSeen = DateTime.Now.ToUniversalTime(); + marketInfo.LastSeen = DateTime.UtcNow; marketsChecked++; @@ -223,7 +223,7 @@ namespace Core.MarketAnalyzer try { - Int64 endTime = (Int64)Math.Ceiling(DateTime.Now.ToUniversalTime().Subtract(Constants.Epoch).TotalMilliseconds); + Int64 endTime = (Int64)Math.Ceiling(DateTime.UtcNow.Subtract(Constants.Epoch).TotalMilliseconds); int ticksLimit = 500; string baseUrl = ""; int ticksFetched = 0; @@ -327,13 +327,13 @@ namespace Core.MarketAnalyzer latestMarketDataFileDateTime = latestMarketDataFile.LastWriteTimeUtc; } - if (latestMarketDataFileDateTime < DateTime.Now.ToUniversalTime().AddMinutes(-20)) + if (latestMarketDataFileDateTime < DateTime.UtcNow.AddMinutes(-20)) { - int lastMarketDataAgeInSeconds = (int)Math.Ceiling(DateTime.Now.ToUniversalTime().Subtract(latestMarketDataFileDateTime).TotalSeconds); + int lastMarketDataAgeInSeconds = (int)Math.Ceiling(DateTime.UtcNow.Subtract(latestMarketDataFileDateTime).TotalSeconds); // Go back in time and create market data - DateTime startDateTime = DateTime.Now.ToUniversalTime(); - DateTime endDateTime = DateTime.Now.ToUniversalTime().AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours); + DateTime startDateTime = DateTime.UtcNow; + DateTime endDateTime = DateTime.UtcNow.AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours); if (latestMarketDataFileDateTime != Constants.confMinDate && latestMarketDataFileDateTime > endDateTime) { // Existing market files too old => Recreate market data for configured timeframe diff --git a/Core/MarketAnalyzer/Bittrex.cs b/Core/MarketAnalyzer/Bittrex.cs index ef9a624..f747947 100644 --- a/Core/MarketAnalyzer/Bittrex.cs +++ b/Core/MarketAnalyzer/Bittrex.cs @@ -105,7 +105,7 @@ namespace Core.MarketAnalyzer marketInfos.Add(marketName, marketInfo); } if (currencyTicker["Summary"]["Created"].Type == Newtonsoft.Json.Linq.JTokenType.Date) marketInfo.FirstSeen = (DateTime)currencyTicker["Summary"]["Created"]; - marketInfo.LastSeen = DateTime.Now.ToUniversalTime(); + marketInfo.LastSeen = DateTime.UtcNow; } } @@ -113,7 +113,7 @@ namespace Core.MarketAnalyzer Bittrex.CheckForMarketDataRecreation(mainMarket, markets, systemConfiguration, log); - DateTime fileDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0).ToUniversalTime(); + DateTime fileDateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, 0).ToUniversalTime(); FileHelper.WriteTextToFile(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathExchange + Path.DirectorySeparatorChar, "MarketData_" + fileDateTime.ToString("yyyy-MM-dd_HH.mm") + ".json", JsonConvert.SerializeObject(markets), fileDateTime, fileDateTime); @@ -203,13 +203,13 @@ namespace Core.MarketAnalyzer latestMarketDataFileDateTime = latestMarketDataFile.LastWriteTimeUtc; } - if (latestMarketDataFileDateTime < DateTime.Now.ToUniversalTime().AddMinutes(-20)) + if (latestMarketDataFileDateTime < DateTime.UtcNow.AddMinutes(-20)) { - int lastMarketDataAgeInSeconds = (int)Math.Ceiling(DateTime.Now.ToUniversalTime().Subtract(latestMarketDataFileDateTime).TotalSeconds); + int lastMarketDataAgeInSeconds = (int)Math.Ceiling(DateTime.UtcNow.Subtract(latestMarketDataFileDateTime).TotalSeconds); // Go back in time and create market data - DateTime startDateTime = DateTime.Now.ToUniversalTime(); - DateTime endDateTime = DateTime.Now.ToUniversalTime().AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours); + DateTime startDateTime = DateTime.UtcNow; + DateTime endDateTime = DateTime.UtcNow.AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours); if (latestMarketDataFileDateTime != Constants.confMinDate && latestMarketDataFileDateTime > endDateTime) { // Existing market files too old => Recreate market data for configured timeframe diff --git a/Core/MarketAnalyzer/CoinMarketCap.cs b/Core/MarketAnalyzer/CoinMarketCap.cs index 93ce88a..3bd9d61 100644 --- a/Core/MarketAnalyzer/CoinMarketCap.cs +++ b/Core/MarketAnalyzer/CoinMarketCap.cs @@ -53,7 +53,7 @@ namespace Core.MarketAnalyzer CoinMarketCap.CheckForMarketDataRecreation(markets, systemConfiguration, log); - DateTime fileDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0).ToUniversalTime(); + DateTime fileDateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, 0).ToUniversalTime(); FileHelper.WriteTextToFile(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathCoinMarketCap + Path.DirectorySeparatorChar, "MarketData_" + fileDateTime.ToString("yyyy-MM-dd_HH.mm") + ".json", JsonConvert.SerializeObject(markets), fileDateTime, fileDateTime); @@ -87,7 +87,7 @@ namespace Core.MarketAnalyzer List marketFiles = dataDirectory.EnumerateFiles("MarketData*") .Select(x => { x.Refresh(); return x; }) - .Where(x => x.LastWriteTimeUtc <= DateTime.Now.AddHours(-24)) + .Where(x => x.LastWriteTimeUtc <= DateTime.UtcNow.AddHours(-24)) .ToArray().OrderByDescending(f => f.LastWriteTimeUtc).ToList(); bool build24hMarketDataFile = false; @@ -95,7 +95,7 @@ namespace Core.MarketAnalyzer if (marketFiles.Count > 0) { marketFile = marketFiles.First(); - if (marketFile.LastWriteTimeUtc <= DateTime.Now.AddHours(-24).AddMinutes(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes).AddSeconds(-10)) + if (marketFile.LastWriteTimeUtc <= DateTime.UtcNow.AddHours(-24).AddMinutes(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes).AddSeconds(-10)) { log.DoLogDebug("CoinMarketCap - 24h market data file too old (" + marketFile.LastWriteTimeUtc.ToString() + "). Rebuilding data..."); build24hMarketDataFile = true; @@ -105,13 +105,13 @@ namespace Core.MarketAnalyzer { marketFiles = dataDirectory.EnumerateFiles("MarketData*") .Select(x => { x.Refresh(); return x; }) - .Where(x => x.LastWriteTimeUtc >= DateTime.Now.AddHours(-24)) + .Where(x => x.LastWriteTimeUtc >= DateTime.UtcNow.AddHours(-24)) .ToArray().OrderBy(f => f.LastWriteTimeUtc).ToList(); if (marketFiles.Count > 0) { marketFile = marketFiles.First(); - if (marketFile.LastWriteTimeUtc >= DateTime.Now.AddHours(-24).AddMinutes(systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes).AddSeconds(10)) + if (marketFile.LastWriteTimeUtc >= DateTime.UtcNow.AddHours(-24).AddMinutes(systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes).AddSeconds(10)) { log.DoLogDebug("CoinMarketCap - 24h market data file too young (" + marketFile.LastWriteTimeUtc.ToString() + "). Rebuilding data..."); build24hMarketDataFile = true; @@ -139,7 +139,7 @@ namespace Core.MarketAnalyzer markets24h.Add(markets[key].Name, market24h); } - DateTime fileDateTime = new DateTime(DateTime.Now.ToLocalTime().AddHours(-24).Year, DateTime.Now.ToLocalTime().AddHours(-24).Month, DateTime.Now.ToLocalTime().AddHours(-24).Day, DateTime.Now.ToLocalTime().AddHours(-24).Hour, DateTime.Now.ToLocalTime().AddHours(-24).Minute, 0).ToUniversalTime(); + DateTime fileDateTime = new DateTime(DateTime.UtcNow.ToLocalTime().AddHours(-24).Year, DateTime.UtcNow.ToLocalTime().AddHours(-24).Month, DateTime.UtcNow.ToLocalTime().AddHours(-24).Day, DateTime.UtcNow.ToLocalTime().AddHours(-24).Hour, DateTime.UtcNow.ToLocalTime().AddHours(-24).Minute, 0).ToUniversalTime(); FileHelper.WriteTextToFile(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathCoinMarketCap + Path.DirectorySeparatorChar, "MarketData_" + fileDateTime.ToString("yyyy-MM-dd_HH.mm") + ".json", JsonConvert.SerializeObject(markets24h), fileDateTime, fileDateTime); diff --git a/Core/MarketAnalyzer/Poloniex.cs b/Core/MarketAnalyzer/Poloniex.cs index 091fef1..69ea1f8 100644 --- a/Core/MarketAnalyzer/Poloniex.cs +++ b/Core/MarketAnalyzer/Poloniex.cs @@ -97,7 +97,7 @@ namespace Core.MarketAnalyzer Poloniex.CheckForMarketDataRecreation(mainMarket, markets, systemConfiguration, log); - DateTime fileDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0).ToUniversalTime(); + DateTime fileDateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, 0).ToUniversalTime(); FileHelper.WriteTextToFile(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathExchange + Path.DirectorySeparatorChar, "MarketData_" + fileDateTime.ToString("yyyy-MM-dd_HH.mm") + ".json", JsonConvert.SerializeObject(markets), fileDateTime, fileDateTime); @@ -150,7 +150,7 @@ namespace Core.MarketAnalyzer marketInfo.FirstSeen = Poloniex.GetFirstSeenDate(key, systemConfiguration, log); } } - marketInfo.LastSeen = DateTime.Now.ToUniversalTime(); + marketInfo.LastSeen = DateTime.UtcNow; marketsChecked++; @@ -165,7 +165,7 @@ namespace Core.MarketAnalyzer { DateTime result = Constants.confMinDate; - Int64 startTime = (Int64)Math.Ceiling(DateTime.Now.ToUniversalTime().AddDays(-100).Subtract(Constants.Epoch).TotalSeconds); + Int64 startTime = (Int64)Math.Ceiling(DateTime.UtcNow.AddDays(-100).Subtract(Constants.Epoch).TotalSeconds); string baseUrl = "https://poloniex.com/public?command=returnChartData&period=14400&start=" + startTime.ToString() + "&end=9999999999¤cyPair=" + marketName; log.DoLogDebug("Poloniex - Getting first seen date for '" + marketName + "'..."); @@ -188,7 +188,7 @@ namespace Core.MarketAnalyzer try { - Int64 startTime = (Int64)Math.Ceiling(DateTime.Now.ToUniversalTime().AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours).Subtract(Constants.Epoch).TotalSeconds); + Int64 startTime = (Int64)Math.Ceiling(DateTime.UtcNow.AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours).Subtract(Constants.Epoch).TotalSeconds); string baseUrl = "https://poloniex.com/public?command=returnChartData&period=300&start=" + startTime.ToString() + "&end=9999999999¤cyPair=" + marketName; log.DoLogDebug("Poloniex - Getting ticks for '" + marketName + "'..."); @@ -237,13 +237,13 @@ namespace Core.MarketAnalyzer latestMarketDataFileDateTime = latestMarketDataFile.LastWriteTimeUtc; } - if (latestMarketDataFileDateTime < DateTime.Now.ToUniversalTime().AddMinutes(-(systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes * 3))) + if (latestMarketDataFileDateTime < DateTime.UtcNow.AddMinutes(-(systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes * 3))) { - int lastMarketDataAgeInSeconds = (int)Math.Ceiling(DateTime.Now.ToUniversalTime().Subtract(latestMarketDataFileDateTime).TotalSeconds); + int lastMarketDataAgeInSeconds = (int)Math.Ceiling(DateTime.UtcNow.Subtract(latestMarketDataFileDateTime).TotalSeconds); // Go back in time and create market data - DateTime startDateTime = DateTime.Now.ToUniversalTime(); - DateTime endDateTime = DateTime.Now.ToUniversalTime().AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours); + DateTime startDateTime = DateTime.UtcNow; + DateTime endDateTime = DateTime.UtcNow.AddHours(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours); if (latestMarketDataFileDateTime != Constants.confMinDate && latestMarketDataFileDateTime > endDateTime) { // Existing market files too old => Recreate market data for configured timeframe diff --git a/Core/ProfitTrailer/SettingsFiles.cs b/Core/ProfitTrailer/SettingsFiles.cs index b3b579a..483dcd5 100644 --- a/Core/ProfitTrailer/SettingsFiles.cs +++ b/Core/ProfitTrailer/SettingsFiles.cs @@ -44,7 +44,7 @@ namespace Core.ProfitTrailer List lines = File.ReadAllLines(filePath).ToList(); lines.Insert(0, ""); lines.Insert(0, "# ####################################"); - lines.Insert(0, "# PTMagic_LastChanged = " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); + lines.Insert(0, "# PTMagic_LastChanged = " + DateTime.UtcNow.ToShortDateString() + " " + DateTime.UtcNow.ToShortTimeString()); lines.Insert(0, "# PTMagic_ActiveSetting = " + SystemHelper.StripBadCode(settingName, Constants.WhiteListProperties)); lines.Insert(0, "# ####### PTMagic Current Setting ########"); lines.Insert(0, "# ####################################"); @@ -117,7 +117,7 @@ namespace Core.ProfitTrailer if (presetFilePath.IndexOf(".properties", StringComparison.InvariantCultureIgnoreCase) > -1) { FileInfo presetFile = new FileInfo(presetFilePath); - if (presetFile.LastWriteTime > DateTime.Now.AddMinutes(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes).AddSeconds(2)) + if (presetFile.LastWriteTime > DateTime.UtcNow.AddMinutes(-systemConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes).AddSeconds(2)) { // File has changed recently, force preparation check diff --git a/Core/ProfitTrailer/SettingsHandler.cs b/Core/ProfitTrailer/SettingsHandler.cs index 37481c2..9c7906c 100644 --- a/Core/ProfitTrailer/SettingsHandler.cs +++ b/Core/ProfitTrailer/SettingsHandler.cs @@ -88,7 +88,7 @@ namespace Core.ProfitTrailer // Writing Header lines fileLines.Insert(0, ""); fileLines.Insert(0, "# ####################################"); - fileLines.Insert(0, "# PTMagic_LastChanged = " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); + fileLines.Insert(0, "# PTMagic_LastChanged = " + DateTime.UtcNow.ToShortDateString() + " " + DateTime.UtcNow.ToShortTimeString()); fileLines.Insert(0, "# PTMagic_ActiveSetting = " + SystemHelper.StripBadCode(ptmagicInstance.DefaultSettingName, Constants.WhiteListProperties)); fileLines.Insert(0, "# ####################################"); @@ -206,7 +206,7 @@ namespace Core.ProfitTrailer { // Setting last change datetime - result.Add("# PTMagic_LastChanged = " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); + result.Add("# PTMagic_LastChanged = " + DateTime.UtcNow.ToShortDateString() + " " + DateTime.UtcNow.ToShortTimeString()); } else if (line.IndexOf("PTMagic_SingleMarketSettings", StringComparison.InvariantCultureIgnoreCase) > -1) @@ -293,14 +293,14 @@ namespace Core.ProfitTrailer string previousLine = result.Last(); if (previousLine.IndexOf("PTMagic Changed Line", StringComparison.InvariantCultureIgnoreCase) > -1) { - previousLine = "# PTMagic changed line for setting '" + settingName + "' on " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); + previousLine = "# PTMagic changed line for setting '" + settingName + "' on " + DateTime.UtcNow.ToShortDateString() + " " + DateTime.UtcNow.ToShortTimeString(); result.RemoveAt(result.Count - 1); result.Add(previousLine); } else { - string editLine = "# PTMagic changed line for setting '" + settingName + "' on " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); + string editLine = "# PTMagic changed line for setting '" + settingName + "' on " + DateTime.UtcNow.ToShortDateString() + " " + DateTime.UtcNow.ToShortTimeString(); result.Add(editLine); } result.Add(line); @@ -337,7 +337,7 @@ namespace Core.ProfitTrailer } } - newPairsLines.Add("# PTMagic_SingleMarketSettings - Written on " + DateTime.Now.ToString()); + newPairsLines.Add("# PTMagic_SingleMarketSettings - Written on " + DateTime.UtcNow.ToString()); newPairsLines.Add("# ########################################################################"); newPairsLines.Add(""); @@ -357,7 +357,7 @@ namespace Core.ProfitTrailer } } - newDCALines.Add("# PTMagic_SingleMarketSettings - Written on " + DateTime.Now.ToString()); + newDCALines.Add("# PTMagic_SingleMarketSettings - Written on " + DateTime.UtcNow.ToString()); newDCALines.Add("# ########################################################################"); newDCALines.Add(""); @@ -381,7 +381,7 @@ namespace Core.ProfitTrailer Dictionary globalDCAProperties = SettingsHandler.GetPropertiesAsDictionary(globalDCALines); Dictionary globalIndicatorsProperties = SettingsHandler.GetPropertiesAsDictionary(globalIndicatorsLines); - newIndicatorsLines.Add("# PTMagic_SingleMarketSettings - Written on " + DateTime.Now.ToString()); + newIndicatorsLines.Add("# PTMagic_SingleMarketSettings - Written on " + DateTime.UtcNow.ToString()); newIndicatorsLines.Add("# ########################################################################"); newIndicatorsLines.Add(""); diff --git a/Monitor/Pages/Login.cshtml.cs b/Monitor/Pages/Login.cshtml.cs index 1c1f972..6958d1a 100644 --- a/Monitor/Pages/Login.cshtml.cs +++ b/Monitor/Pages/Login.cshtml.cs @@ -29,14 +29,14 @@ namespace Monitor.Pages if (encryptedPassword.Equals(PTMagicConfiguration.SecureSettings.MonitorPassword)) { - HttpContext.Session.SetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString(), DateTime.Now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")); + HttpContext.Session.SetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString(), DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")); if (cbRememberMe != null) { if (cbRememberMe.Equals("on", StringComparison.InvariantCultureIgnoreCase)) { CookieOptions cookieOption = new CookieOptions(); - cookieOption.Expires = DateTime.Now.AddYears(1); + cookieOption.Expires = DateTime.UtcNow.AddYears(1); string cookieValue = EncryptionHelper.Encrypt(encryptedPassword); diff --git a/Monitor/Pages/MarketAnalyzer.cshtml.cs b/Monitor/Pages/MarketAnalyzer.cshtml.cs index f495c46..85ef6f7 100644 --- a/Monitor/Pages/MarketAnalyzer.cshtml.cs +++ b/Monitor/Pages/MarketAnalyzer.cshtml.cs @@ -62,7 +62,7 @@ namespace Monitor.Pages TrendChartDataJSON += "values: ["; // Get trend ticks for chart - DateTime currentDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0); + DateTime currentDateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, 0, 0); DateTime startDateTime = currentDateTime.AddHours(-PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours); DateTime endDateTime = currentDateTime; int trendChartTicks = 0; diff --git a/Monitor/Pages/StatusSummary.cshtml b/Monitor/Pages/StatusSummary.cshtml index 904bf84..3ab5b73 100644 --- a/Monitor/Pages/StatusSummary.cshtml +++ b/Monitor/Pages/StatusSummary.cshtml @@ -15,7 +15,7 @@

PTMagic Status

@{ DateTime lastRuntime = Model.Summary.LastRuntime; - double elapsedSecondsSinceRuntime = DateTime.Now.Subtract(lastRuntime).TotalSeconds; + double elapsedSecondsSinceRuntime = DateTime.UtcNow.Subtract(lastRuntime).TotalSeconds; double intervalSeconds = Model.PTMagicConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes * 60.0; string ptMagicHealthIcon = ""; @@ -28,7 +28,7 @@ floodProtectionIcon = ""; } - string lastGlobalSettingSwitch = Core.Helper.SystemHelper.GetProperDurationTime((int)Math.Ceiling(DateTime.Now.Subtract(Model.Summary.LastGlobalSettingSwitch).TotalSeconds)) + " ago"; + string lastGlobalSettingSwitch = Core.Helper.SystemHelper.GetProperDurationTime((int)Math.Ceiling(DateTime.UtcNow.Subtract(Model.Summary.LastGlobalSettingSwitch).TotalSeconds)) + " ago"; if (Model.Summary.LastGlobalSettingSwitch == Core.Main.Constants.confMinDate) { lastGlobalSettingSwitch = "-"; } diff --git a/Monitor/Pages/StatusSummary.cshtml.cs b/Monitor/Pages/StatusSummary.cshtml.cs index 9b47c10..8532f09 100644 --- a/Monitor/Pages/StatusSummary.cshtml.cs +++ b/Monitor/Pages/StatusSummary.cshtml.cs @@ -71,7 +71,7 @@ namespace Monitor.Pages { if (Summary.GlobalSettingSummary.Count > 0) { - DateTime dateTime24hAgo = DateTime.Now.AddHours(-24); + DateTime dateTime24hAgo = DateTime.UtcNow.AddHours(-24); List gsSummaries24h = Summary.GlobalSettingSummary.FindAll(gss => gss.SwitchDateTime >= dateTime24hAgo); IEnumerable gsNames24h = gsSummaries24h.GroupBy(gss => gss.SettingName).Select(group => group.First()); @@ -141,7 +141,7 @@ namespace Monitor.Pages { if (Summary.GlobalSettingSummary.Count > 0) { - DateTime dateTime3dAgo = DateTime.Now.AddHours(-72); + DateTime dateTime3dAgo = DateTime.UtcNow.AddHours(-72); List gsSummaries3d = Summary.GlobalSettingSummary.FindAll(gss => gss.SwitchDateTime >= dateTime3dAgo); IEnumerable gsNames3d = gsSummaries3d.GroupBy(gss => gss.SettingName).Select(group => group.First()); diff --git a/Monitor/Pages/_get/DashboardBottom.cshtml.cs b/Monitor/Pages/_get/DashboardBottom.cshtml.cs index f60ae71..c2153a9 100644 --- a/Monitor/Pages/_get/DashboardBottom.cshtml.cs +++ b/Monitor/Pages/_get/DashboardBottom.cshtml.cs @@ -72,7 +72,7 @@ namespace Monitor.Pages { TrendChartDataJSON += "values: ["; // Get trend ticks for chart - DateTime currentDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0); + DateTime currentDateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, 0, 0); DateTime startDateTime = currentDateTime.AddHours(-PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours); DateTime endDateTime = currentDateTime; int trendChartTicks = 0; @@ -115,9 +115,9 @@ namespace Monitor.Pages { string profitPerDayJSON = ""; if (PTData.SellLog.Count > 0) { DateTime minSellLogDate = PTData.SellLog.OrderBy(sl => sl.SoldDate).First().SoldDate.Date; - DateTime graphStartDate = DateTime.Now.Date.AddDays(-30); + DateTime graphStartDate = DateTime.UtcNow.Date.AddDays(-30); if (minSellLogDate > graphStartDate) graphStartDate = minSellLogDate; - for (DateTime salesDate = graphStartDate; salesDate <= DateTime.Now.Date; salesDate = salesDate.AddDays(1)) { + for (DateTime salesDate = graphStartDate; salesDate <= DateTime.UtcNow.Date; salesDate = salesDate.AddDays(1)) { if (tradeDayIndex > 0) { profitPerDayJSON += ",\n"; } diff --git a/Monitor/Pages/_get/TickerWidgets.cshtml b/Monitor/Pages/_get/TickerWidgets.cshtml index 7bfc730..99aeed4 100644 --- a/Monitor/Pages/_get/TickerWidgets.cshtml +++ b/Monitor/Pages/_get/TickerWidgets.cshtml @@ -16,7 +16,7 @@ } DateTime lastRuntime = Model.Summary.LastRuntime; - double elapsedSecondsSinceRuntime = DateTime.Now.Subtract(lastRuntime).TotalSeconds; + double elapsedSecondsSinceRuntime = DateTime.UtcNow.Subtract(lastRuntime).TotalSeconds; double intervalSeconds = Model.PTMagicConfiguration.AnalyzerSettings.MarketAnalyzer.IntervalMinutes * 60.0; string iconColor = "text-success"; diff --git a/Monitor/Program.cs b/Monitor/Program.cs index 7fda2ec..6e6768f 100644 --- a/Monitor/Program.cs +++ b/Monitor/Program.cs @@ -27,7 +27,7 @@ namespace Monitor { string appsettingsJson = monitorBasePath + Path.DirectorySeparatorChar + "appsettings.json"; if (!File.Exists(appsettingsJson)) { Console.WriteLine("ERROR: appsettings.json not found: '" + appsettingsJson + "'. Please check if the file exists. If not, review the PT Magic setup steps listed on the wiki!"); - if (Console.KeyAvailable) Console.ReadKey(); + if (!Console.IsInputRedirected) Console.ReadKey(); } else { Console.WriteLine("INFO: appsettings.json found in " + monitorBasePath); @@ -46,7 +46,7 @@ namespace Monitor { // Check if PT Magic directoy is correctly configured if (!Directory.Exists(ptMagicBasePath)) { Console.WriteLine("ERROR: PT Magic directory not found: '" + ptMagicBasePath + "'. Please check your setting for 'PTMagicBasePath' in 'Monitor/appsettings.json'"); - if (Console.KeyAvailable) Console.ReadKey(); + if (!Console.IsInputRedirected) Console.ReadKey(); } else { Console.WriteLine("INFO: PT Magic directory found at " + ptMagicBasePath); @@ -54,7 +54,7 @@ namespace Monitor { string settingsGeneralJson = ptMagicBasePath + "settings.general.json"; if (!File.Exists(settingsGeneralJson)) { Console.WriteLine("ERROR: PT Magic settings not found: '" + settingsGeneralJson + "'. Please check if you setup PT Magic correctly!"); - if (Console.KeyAvailable) Console.ReadKey(); + if (!Console.IsInputRedirected) Console.ReadKey(); } else { Console.WriteLine("INFO: settings.general.json found at " + settingsGeneralJson); @@ -62,7 +62,7 @@ namespace Monitor { string lastRuntimeSummaryJson = ptMagicBasePath + Constants.PTMagicPathData + Path.DirectorySeparatorChar + "LastRuntimeSummary.json"; if (!File.Exists(lastRuntimeSummaryJson)) { Console.WriteLine("ERROR: PT Magic runtime summary not found: '" + lastRuntimeSummaryJson + "'. Please wait for PT Magic to complete its first run!"); - if (Console.KeyAvailable) Console.ReadKey(); + if (!Console.IsInputRedirected) Console.ReadKey(); } else { Console.WriteLine("INFO: LastRuntimeSummary.json found at " + lastRuntimeSummaryJson); @@ -76,14 +76,14 @@ namespace Monitor { string wwwrootPath = monitorBasePath + Path.DirectorySeparatorChar + "wwwroot"; if (!Directory.Exists(wwwrootPath)) { Console.WriteLine("ERROR: wwwroot directory not found: '" + wwwrootPath + "'. Did you copy all files as instructed on the wiki?"); - if (Console.KeyAvailable) Console.ReadKey(); + if (!Console.IsInputRedirected) Console.ReadKey(); } else { Console.WriteLine("INFO: wwwroot directory found at " + wwwrootPath); string assetsPath = wwwrootPath + Path.DirectorySeparatorChar + "assets"; if (!Directory.Exists(assetsPath)) { Console.WriteLine("ERROR: assets directory not found: '" + assetsPath + "'. Did you copy all files as instructed on the wiki?"); - if (Console.KeyAvailable) Console.ReadKey(); + if (!Console.IsInputRedirected) Console.ReadKey(); } else { Console.WriteLine("INFO: assets directory found at " + assetsPath); Console.WriteLine("INFO: ALL CHECKS COMPLETED - ATTEMPTING TO START WEBSERVER..."); diff --git a/Monitor/_Internal/BasePageModelSecure.cs b/Monitor/_Internal/BasePageModelSecure.cs index 5ea9620..a1fc1c4 100644 --- a/Monitor/_Internal/BasePageModelSecure.cs +++ b/Monitor/_Internal/BasePageModelSecure.cs @@ -33,7 +33,7 @@ namespace Monitor._Internal string encryptedPassword = EncryptionHelper.Decrypt(Request.Cookies["PTMRememberMeKey"]); if (encryptedPassword.Equals(PTMagicConfiguration.SecureSettings.MonitorPassword)) { - HttpContext.Session.SetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString(), DateTime.Now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")); + HttpContext.Session.SetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString(), DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")); redirectToLogin = false; } } diff --git a/Monitor/_Internal/BasePageModelSecureAJAX.cs b/Monitor/_Internal/BasePageModelSecureAJAX.cs index 21d2117..c1c7c6a 100644 --- a/Monitor/_Internal/BasePageModelSecureAJAX.cs +++ b/Monitor/_Internal/BasePageModelSecureAJAX.cs @@ -33,7 +33,7 @@ namespace Monitor._Internal string encryptedPassword = EncryptionHelper.Decrypt(Request.Cookies["PTMRememberMeKey"]); if (encryptedPassword.Equals(PTMagicConfiguration.SecureSettings.MonitorPassword)) { - HttpContext.Session.SetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString(), DateTime.Now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")); + HttpContext.Session.SetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString(), DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")); redirectToLogin = false; } } diff --git a/PTMagic/Program.cs b/PTMagic/Program.cs index ddb21c8..4edac9b 100644 --- a/PTMagic/Program.cs +++ b/PTMagic/Program.cs @@ -7,7 +7,7 @@ using Core.Helper; using Core.Main.DataObjects.PTMagicData; using Microsoft.Extensions.DependencyInjection; -[assembly: AssemblyVersion("2.1.2")] +[assembly: AssemblyVersion("2.1.3")] [assembly: AssemblyProduct("PT Magic")] namespace PTMagic @@ -26,7 +26,7 @@ namespace PTMagic // Keep the app running for (; ; ) { - Thread.Sleep(100); + Thread.Sleep(10000); } } }