示例#1
0
        public Module(string pathToModule)
        {
            ModulePath = pathToModule;
            CFGPath    = pathToModule + "\\cfg.txt";

            string[] pathSplit = ModulePath.Split('\\');
            Name = pathSplit[pathSplit.Length - 1];

            string[] executables = Directory.EnumerateFiles(ModulePath)
                                   .Where(f => f.Split('\\').Last().StartsWith(Name) && (f.EndsWith(".py") || f.EndsWith(".exe")))
                                   .ToArray();

            if (executables.Length != 1)
            {
                Console.WriteLine("Module {0} err: either couldn't find an executable ({0}.py || {0}.exe) or found too many.", Name);
                Filename       = null;
                Extension      = null;
                ExecutablePath = null;
            }
            else
            {
                ExecutablePath = executables[0];
                Filename       = ExecutablePath.Split('\\').Last();
                Extension      = '.' + Filename.Split('.').Last();
            }

            ProcessManager = new ProcessHandler(this);
        }
示例#2
0
 public void FindSuitableOffset(string symbol)
 {
     this.symbol   = symbol;
     quoteFilePath = ExecutablePath.Combine($"{symbol}.csv");
     LoadTradeSignals();
     FindTimeframeOffest();
 }
示例#3
0
        private void ReduceERatio(List <SignalStat> stat)
        {
            var eratio = new float[timeframes];

            for (var i = 0; i < eratio.Length; i++)
            {
                float sumPro = 0f, sumCons = 0f;
                foreach (var s in stat)
                {
                    sumPro  += s.proCons[i].pro;
                    sumCons += s.proCons[i].con;
                }
                eratio[i] = sumCons == 0f ? 1 : sumPro / sumCons;
            }
            // сохранить в файл
            var fileName = ExecutablePath.Combine($"report_{accountId}_{symbol}.txt");

            using (var sw = new StreamWriter(fileName, false, Encoding.ASCII))
            {
                sw.WriteLine($"Account {accountId}, symbol {symbol}");
                sw.WriteLine($"{signals.Count} trades, M{timeframe}, {timeframes} timeframes");
                sw.WriteLine();
                foreach (var e in eratio)
                {
                    sw.WriteLine(e.ToString("f4", CultureInfo.InvariantCulture));
                }
            }
        }
        private bool ValidateForm()
        {
            ResetBackgroundColors();
            var eCol = new SolidColorBrush(Colors.OrangeRed);

            if (ExecutablePath.IsNullOrEmpty())
            {
                _log.StatusError("Executable path not set.");
                executablePathTxtBox.Background = eCol;
                return(false);
            }

            if (!File.Exists(ExecutablePath))
            {
                _log.StatusError("Ececutable not found.");
                executablePathTxtBox.Background = eCol;
                return(false);
            }

            if (GameRoot.IsNullOrEmpty())
            {
                _log.StatusError("Gameroot folder not set.");
                gameRootPathTxtBox.Background = eCol;
                return(false);
            }

            if (!Directory.Exists(GameRoot))
            {
                _log.StatusMessage("Game root folder not found.");
                gameRootPathTxtBox.Background = eCol;
                return(false);
            }

            return(true);
        }
示例#5
0
 public void BuildEratio(string symbol)
 {
     this.symbol   = symbol;
     quoteFilePath = ExecutablePath.Combine($"{symbol}.csv");
     LoadTradeSignals();
     BuildEratio();
 }
示例#6
0
 public void BuildEratio(string symbol, List <TradeSignal> signals)
 {
     this.symbol   = symbol;
     quoteFilePath = ExecutablePath.Combine($"{symbol}.csv");
     this.signals  = signals;
     BuildEratio();
 }
示例#7
0
 public void TestSetup()
 {
     TradeSharpDictionary.Initialize(MoqTradeSharpDictionary.Mock);
     ExecutablePath.InitializeFake(string.Empty);
     AtomCandleStorage.Instance.LoadFromFile(ExecutablePath.ExecPath + "\\quotes", Symbol);
     candles = AtomCandleStorage.Instance.GetAllMinuteCandles(Symbol);
     quotes  = candles.Select(q => new QuoteData(q.close, DalSpot.Instance.GetAskPriceWithDefaultSpread(Symbol, q.close), q.timeOpen)).ToList();
 }
示例#8
0
        /// <summary>
        /// save settings in JSON file by default path
        /// </summary>
        public void SaveSettings()
        {
            var path = ExecutablePath.Combine("settings.txt");

            using (var sw = new StreamWriter(path, false, Encoding.UTF8))
            {
                sw.Write(JsonConvert.SerializeObject(this, Formatting.Indented));
            }
        }
示例#9
0
        public ModelMock()
        {
            ExecutablePath.InitializeFake(string.Empty);

            Logger.Debug("Trace Init - file : " + ExecutablePath.Combine("Files", "Instruments.txt"));

            var jsonInstruments = System.IO.File.ReadAllText(ExecutablePath.Combine("Files", "Instruments.txt"));
            var jsonContracts   = System.IO.File.ReadAllText(ExecutablePath.Combine("Files", "Contracts.txt"));
        }
示例#10
0
        private void ReadConfig()
        {
            var fileName = ExecutablePath.Combine("settings.ini");
            var ini      = new IniFile(fileName);

            timeframe   = int.Parse(ini.ReadValue("Common", "Timeframe", "120"));
            timeframes  = int.Parse(ini.ReadValue("Common", "Timeframes", "240"));
            quoteOffset = int.Parse(ini.ReadValue("Common", "Offset", "0"));
        }
示例#11
0
        /// <summary>
        /// ensure the target folder and save the report's time
        /// </summary>
        public static void BuildReport(TraderPool pool)
        {
            var folder = $"{DateTime.Now:yyyy-MM-dd HHmmss}";

            EnsureFolder(folder);
            folder = ExecutablePath.Combine(RootFolder, folder);

            SaveStatisticsReport(pool, folder);
            SaveServerReport(pool, folder);
        }
示例#12
0
        public void TestSetup()
        {
            stockSeries = new StockSeriesDebug("StockSeriesDebug");

            ExecutablePath.InitializeFake(string.Empty);
            AtomCandleStorage.Instance.LoadFromFile(ExecutablePath.ExecPath + "\\quotes", Symbol);
            candles = AtomCandleStorage.Instance.GetAllMinuteCandles(Symbol);

            Localizer.ResourceResolver = new MockResourceResolver();
        }
示例#13
0
        public override string ToString()
        {
            if (IsDefault)
            {
                return("Empty process");
            }

            var path = string.IsNullOrEmpty(ExecutablePath) ? string.Empty : ExecutablePath.Replace("\\", "/");

            return(string.Format("{0}, {1}, {2}", ProcessId, Name, path));
        }
示例#14
0
        public static void InitDefault()
        {
            var fileName = ExecutablePath.Combine("settings.ini");
            var ini      = new IniFile(fileName);

            connectionString = ini.ReadValue("DB", "SharpConnection", "");
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception($"Connection string was not found, file \"{fileName}\"");
            }
        }
示例#15
0
 private static void SaveSignals(string s, int accountId, string symbol)
 {
     try
     {
         var fname = ExecutablePath.Combine(s.Substring("save ".Length));
         SharpRepo.InitDefault();
         var signals = SharpRepo.GetSignals(accountId, symbol);
         SharpRepo.SaveSignalsToFile(fname, signals);
     }
     catch (Exception e)
     {
         Console.WriteLine("Error: " + e);
     }
 }
示例#16
0
        public void FindPathByExecutable()
        {
            if (wowProcess.WarcraftProcess != null)
            {
                addonConfig.InstallPath = ExecutablePath.Get(wowProcess.WarcraftProcess);
                if (!string.IsNullOrEmpty(addonConfig.InstallPath))
                {
                    logger.LogInformation($"{GetType().Name}.InstallPath - found running instance: '{addonConfig.InstallPath}'");
                    return;
                }
            }

            logger.LogError($"{GetType().Name}.InstallPath - game not running");
        }
示例#17
0
        public static AppSets ReadSettingsFromFile()
        {
            var path = ExecutablePath.Combine("settings.txt");

            if (!File.Exists(path))
            {
                return(null);
            }

            string json;

            using (var sr = new StreamReader(ExecutablePath.Combine("settings.txt"), Encoding.UTF8))
                json = sr.ReadToEnd();
            return(JsonConvert.DeserializeObject <AppSets>(json));
        }
示例#18
0
        /// <summary>
        /// create the folder passed if it not exists
        /// </summary>
        private static void EnsureFolder(string subFolder)
        {
            var folder = ExecutablePath.Combine(RootFolder);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            folder = ExecutablePath.Combine(RootFolder, subFolder);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
        }
示例#19
0
        public void InitContext()
        {
            TradeSharpDictionary.Initialize(MoqTradeSharpDictionary.Mock);
            context = TestRobotUtil.GetRobotContextBacktest(new DateTime(2013, 9, 30), new DateTime(2014, 1, 30), currency: "IND");

            bot = new IchimokuRobot();
            bot.Graphics.Clear();
            bot.Graphics.Add(new Cortege2 <string, BarSettings>("INDUSD", new BarSettings
            {
                StartMinute = 0,
                Intervals   = new List <int> {
                    30
                }
            }));
            bot.Initialize(context, CurrentProtectedContext.Instance);

            ExecutablePath.InitializeFake(string.Empty);
        }
示例#20
0
        /// <summary>
        /// read the settings from JSON file by its default path
        /// </summary>
        public static TradersSettings ReadSettings()
        {
            TradersSettings settings;
            var             path = ExecutablePath.Combine("settings.txt");

            if (File.Exists(path))
            {
                string json;
                using (var sr = new StreamReader(path, Encoding.UTF8))
                    json = sr.ReadToEnd();
                settings = JsonConvert.DeserializeObject <TradersSettings>(json);
                return(settings);
            }

            settings = MakeDefaultSettings();
            settings.SaveSettings();

            return(settings);
        }
示例#21
0
        /// <summary>
        /// save the report (included in the pool parameter) in a file
        /// </summary>
        private static void SaveStatisticsReport(TraderPool pool, string folder)
        {
            var stat     = pool.statistics;
            var jsonPath = Path.Combine(folder, "rawdata.js");
            var json     = stat.Stringify(false);

            using (var sw = new StreamWriter(jsonPath, false, Encoding.UTF8))
                sw.Write("window.rawdata = " + json);

            // copy report file
            var newPath = ExecutablePath.Combine(folder, "report.html");
            var srcPath = ExecutablePath.Combine("report.html");

            if (File.Exists(newPath))
            {
                File.Delete(newPath);
            }
            File.Copy(srcPath, newPath);
        }
示例#22
0
 private static void BuildEratio(string s, TradeSignalAnalysis analz, string symbol)
 {
     try
     {
         if (s.StartsWith("load "))
         {
             var fname   = ExecutablePath.Combine(s.Substring("load ".Length));
             var signals = SharpRepo.LoadSignalsFromFile(fname);
             analz.BuildEratio(symbol, signals);
         }
         else
         {
             analz.BuildEratio(symbol);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("Error: " + e);
     }
 }
示例#23
0
        public void TestSetup()
        {
            TradeSharpDictionary.Initialize(MoqTradeSharpDictionary.Mock);
            context = TestRobotUtil.GetRobotContextBacktest(new DateTime(2013, 12, 25), new DateTime(2013, 12, 25).AddDays(30));

            bot = new VoidRobot();
            bot.Graphics.Add(new Cortege2 <string, BarSettings>("EURUSD", new BarSettings
            {
                StartMinute = 0,
                Intervals   = new List <int> {
                    30
                }
            }));
            bot.Initialize(context, CurrentProtectedContext.Instance);

            ExecutablePath.InitializeFake(string.Empty);
            context.SubscribeRobot(bot);
            context.InitiateTest();

            // Инициализация дополнительных объектом, MOCK-и
            QuoteMaker.FillQuoteStorageWithDefaultValues();
        }
示例#24
0
        static void Main()
        {
            var          localPath = ExecutablePath.Combine("instance.temp");
            StreamWriter sw        = null;

            try
            {
                sw = new StreamWriter(localPath, false);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new LoadTestForm());
            }
            catch
            {
                MessageBox.Show("Instance is already running or the folder is read-only");
                return;
            }
            finally
            {
                sw?.Close();
            }
        }
示例#25
0
        /// <summary>
        /// get the reports' times from the "reports" folder
        /// report's time is a part of its filename
        /// </summary>
        public static List <DateTime> ReadReportsTimes()
        {
            var dates = new List <DateTime>();
            var root  = ExecutablePath.Combine(RootFolder);

            if (!Directory.Exists(root))
            {
                return(dates);
            }

            foreach (var dir in Directory.GetDirectories(root))
            {
                var name = Path.GetFileName(dir);
                if (DateTime.TryParseExact(name, "yyyy-MM-dd HHmmss", CultureInfo.InvariantCulture,
                                           DateTimeStyles.None, out var date))
                {
                    dates.Add(date);
                }
            }

            return(dates.OrderByDescending(d => d).ToList());
        }
示例#26
0
        public void InitContext()
        {
            TradeSharpDictionary.Initialize(MoqTradeSharpDictionary.Mock);
            context = TestRobotUtil.GetRobotContextBacktest(new DateTime(2013, 12, 25), new DateTime(2013, 12, 25).AddDays(30));

            bot = new RobotMA
            {
                RangeFastMA           = 5,
                RangeSlowMA           = 15,
                DeriveSiteFromHistory = true
            };
            bot.Graphics.Add(new Cortege2 <string, BarSettings>("EURUSD", new BarSettings
            {
                StartMinute = 0,
                Intervals   = new List <int> {
                    30
                }
            }));
            bot.Initialize(context, CurrentProtectedContext.Instance);

            ExecutablePath.InitializeFake(string.Empty);
            context.SubscribeRobot(bot);
            context.InitiateTest();
        }
示例#27
0
 public ServerStatPicker(TradersSettings settings, Logger logMessage)
 {
     this.settings   = settings;
     this.logMessage = logMessage;
     filePath        = ExecutablePath.Combine("serverlog.json");
 }
示例#28
0
 private static readonly Lazy <StartupManager> _currentStartupManager = new(() => new StartupManager(
                                                                                ExecutablePath,
                                                                                LibraryInformation.Name,
示例#29
0
        public static async Task InstallExtension()
        {
            var allowAutoClose = true;

            Console.WriteLine();
            Console.WriteLine($"Viramate Installer v{MyAssembly.GetName().Version}");
            if (Environment.GetCommandLineArgs().Contains("--version"))
            {
                return;
            }

            if (Environment.GetCommandLineArgs().Contains("--update"))
            {
                await AutoUpdateInstaller();
            }

            Console.WriteLine("Installing extension. This'll take a moment...");

            if (await InstallExtensionFiles(false, null) != InstallResult.Failed)
            {
                Console.WriteLine($"Extension id: {ExtensionId}");

                string manifestText;
                using (var s = new StreamReader(OpenResource("nmh.json"), Encoding.UTF8))
                    manifestText = s.ReadToEnd();

                manifestText = manifestText
                               .Replace(
                    "$executable_path$",
                    ExecutablePath.Replace("\\", "\\\\").Replace("\"", "\\\"")
                    ).Replace(
                    "$extension_id$", ExtensionId
                    );

                var manifestPath = Path.Combine(MiscPath, "nmh.json");
                Directory.CreateDirectory(MiscPath);
                File.WriteAllText(manifestPath, manifestText);

                Directory.CreateDirectory(Path.Combine(DataPath, "Help"));
                foreach (var n in MyAssembly.GetManifestResourceNames())
                {
                    if (!n.EndsWith(".gif") && !n.EndsWith(".png"))
                    {
                        continue;
                    }

                    var destinationPath = Path.Combine(DataPath, n.Replace("Viramate.", "").Replace("Help.", "Help\\"));
                    using (var src = MyAssembly.GetManifestResourceStream(n))
                        using (var dst = File.Open(destinationPath, FileMode.Create))
                            await src.CopyToAsync(dst);
                }

                const string keyName = @"Software\Google\Chrome\NativeMessagingHosts\com.viramate.installer";
                using (var key = Registry.CurrentUser.CreateSubKey(keyName)) {
                    Console.WriteLine($"{keyName}\\@ = {manifestPath}");
                    key.SetValue(null, manifestPath);
                }

                try {
                    WebSocketServer.SetupFirewallRule();
                } catch (Exception exc) {
                    Console.WriteLine("Failed to install firewall rule: {0}", exc);
                    allowAutoClose = false;
                }

                string helpFileText;
                using (var s = new StreamReader(OpenResource("Help/index.html"), Encoding.UTF8))
                    helpFileText = s.ReadToEnd();

                helpFileText = Regex.Replace(
                    helpFileText,
                    @"\<pre\ id='install_path'>[^<]*\</pre\>",
                    @"<pre id='install_path'>" + DataPath + "</pre>"
                    );

                var helpFilePath = Path.Combine(DataPath, "Help", "index.html");
                File.WriteAllText(helpFilePath, helpFileText);

                Console.WriteLine($"Viramate v{ReadManifestVersion(null)} has been installed.");
                if (!Environment.GetCommandLineArgs().Contains("--nohelp"))
                {
                    Console.WriteLine("Opening install instructions...");
                    Process.Start(helpFilePath);
                }
                else if (!Debugger.IsAttached && !IsRunningInsideCmd)
                {
                    Console.WriteLine("Press enter to exit.");
                    return;
                }

                if (!Environment.GetCommandLineArgs().Contains("--nodir"))
                {
                    Console.WriteLine("Waiting, then opening install directory...");
                    await Task.Delay(2000);

                    Process.Start(DataPath);
                }
            }
            else
            {
                await AutoUpdateInstaller();

                if (!Debugger.IsAttached && !IsRunningInsideCmd)
                {
                    Console.WriteLine("Failed to install extension. Press enter to exit.");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Failed to install extension.");
                }
            }
        }
示例#30
0
 public override string GetSummary() => $"Runs {ExecutablePath.Split('\\').Last()}";