Esempio n. 1
0
        public string Play(object request)
        {
            try
            {
                var gameSettings = JsonConvert.DeserializeObject <GameSettings>(request.ToString());
                var gameManager  = new GameManager(gameSettings.MapSettings,
                                                   gameSettings.Bots.Select(bot => BotFactory.CreateBot((BotTypes)bot.Type, bot.Id, bot.Code)));
                var game = gameSettings.DebugMode ? gameManager.DebugPlay() : gameManager.Play();

                return(JsonConvert.SerializeObject(new GameResult
                {
                    Game = game,
                    IsError = false
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(JsonConvert.SerializeObject(new GameResult
                {
                    IsError = true,
                    Message = ex.Message
                }));
            }
        }
Esempio n. 2
0
        private CellSign RunSingle(CellSign firstPlayerSign)
        {
            var firstPlayerKind  = firstPlayerSign == CellSign.X ? _firstBotKind : _secondBotKind;
            var secondPlayerKind = firstPlayerSign == CellSign.X ? _secondBotKind : _firstBotKind;

            try
            {
                var config = new GameConfiguration
                {
                    BotTurnLength = _botTurnLength,
                    FirstPlayer   = BotFactory.BuildBot(firstPlayerKind),
                    SecondPlayer  = BotFactory.BuildBot(secondPlayerKind),
                    Height        = _height,
                    Width         = _width
                };

                var game = Game.CreateNewGame(config);
                if (game == null)
                {
                    SetFailedToCreate();
                    return(CellSign.Empty);
                }

                var gameEndedEventArgs = game.RunSilently();
                return(GameStateToSign(gameEndedEventArgs.State));
            }
            catch (Exception ex)
            {
                LogException(LogLevel.Warning, ex);
                SetFailedToCreate();
                return(CellSign.Empty);
            }
        }
Esempio n. 3
0
        public void TestInitialize()
        {
            var botFactory   = new BotFactory();
            var humanFactory = new HumanFactory();

            this.database = new Database(botFactory, humanFactory);
        }
Esempio n. 4
0
 public BotHost(
     BotCommander <T> botCommander,
     BotLogger botLogger,
     SettingsService settingsService,
     KahlaLocation kahlaLocation,
     FriendshipService friendshipService,
     HomeService homeService,
     VersionService versionService,
     AuthService authService,
     EventSyncer <T> eventSyncer,
     ProfileContainer profileContainer,
     BotFactory <T> botFactory)
 {
     _botCommander      = botCommander.InjectHost(this);
     _botLogger         = botLogger;
     _settingsService   = settingsService;
     _kahlaLocation     = kahlaLocation;
     _friendshipService = friendshipService;
     _homeService       = homeService;
     _versionService    = versionService;
     _authService       = authService;
     _eventSyncer       = eventSyncer;
     _profileContainer  = profileContainer;
     _botFactory        = botFactory;
 }
Esempio n. 5
0
 public BotStarter(
     ILogger <TimedCleaner> logger,
     IServiceScopeFactory scopeFactory)
 {
     _logger         = logger;
     using var scope = scopeFactory.CreateScope();
     _bot            = scope.ServiceProvider.GetService <SecurityBot>();
     _botFactory     = scope.ServiceProvider.GetService <BotFactory>();
 }
Esempio n. 6
0
        public static async Task Main(string[] args)
        {
            await AppDbContext.InitAsync();

            using (AppDbContext context = new AppDbContext())
            {
                var lastLog = await context.Logs.OrderByDescending(x => x.Id).FirstOrDefaultAsync();

                //Ensure there's a single instance being executed.
                if (lastLog != null &&
                    lastLog.State == GeoLogState.Pending &&
                    ((DateTime.UtcNow - lastLog.StartDate).TotalMinutes) < 10)    // Pending state might be fake, ignore it after 10 minutes
                {
                    return;
                }

                var last_execution_date = lastLog?.EndDate ?? lastLog?.StartDate ?? DateTime.MinValue;

                var log = new Log {
                    StartDate = DateTime.UtcNow
                };
                context.Logs.Add(log);
                await context.SaveChangesAsync();

                try
                {
                    IConfigurationRoot configuration = new ConfigurationBuilder()
                                                       .SetBasePath(Directory.GetCurrentDirectory())
                                                       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                                       .Build();

                    var credentials = configuration.GetSection("Credentials").Get <Credentials>();
                    var botSettings = configuration.GetSection("BotSettings").Get <BotSettings>();

                    //    credentials = new Credentials { Address = "http://127.0.0.1:8080/mediawiki", Username = "******", Password = "******" };

                    KabLatinizerBot bot = await BotFactory.CreateInstanceAsync <KabLatinizerBot>(credentials.Address, credentials.Username, credentials.Password);

                    if (botSettings != null)
                    {
                        bot.SaveDelay            = botSettings.SaveDelay;
                        bot.MaxLag               = botSettings.MaxLag;
                        bot.RetryCountPerRequest = botSettings.RetryCountPerRequest;
                    }

                    log.NumberOfModifiedPages = await bot.DoJobAsync(last_execution_date);
                }
                catch (Exception e)
                {
                    log.Error = e.ToString();
                }

                log.EndDate = DateTime.UtcNow;

                await context.SaveChangesAsync();
            }
        }
Esempio n. 7
0
        public string GetAnswerA(bool animate = false)
        {
            var botFactory = new BotFactory(210, 200);

            botFactory.AddInstructions(File.ReadAllLines("Day10_input.txt").OrderBy(l => l));

            return("" + botFactory.Bots
                   .First(b => b.ComparedValues.Contains(new Tuple <int, int>(17, 61))).BotId);
        }
Esempio n. 8
0
        public static void Main()
        {
            IHumanFactory humanFactory = new HumanFactory();
            IBotFactory   botFactory   = new BotFactory();
            IDatabase     database     = new Database(botFactory, humanFactory);
            IEngine       engine       = new Engine(database);

            engine.Run();
        }
Esempio n. 9
0
        public string GetAnswerB(bool animate = false)
        {
            var botFactory = new BotFactory(210, 200);

            botFactory.AddInstructions(File.ReadAllLines("Day10_input.txt").OrderBy(l => l));

            return("" + botFactory.OutputBins.Take(3)
                   .Select(o => o.Value).Aggregate(1, (x, y) => x * y));
        }
Esempio n. 10
0
        public static Bot SpawnBot(
            BotType botType,
            BotFaction faction     = BotFaction.None,
            IPlayer player         = null,
            PlayerTeam team        = BotTeam,
            bool ignoreFullSpawner = false,
            bool triggerOnSpawn    = true)
        {
            if (player == null)
            {
                player = SpawnPlayer(ignoreFullSpawner);
            }
            if (player == null)
            {
                return(null);
            }

            player.SetTeam(team);

            var bot       = BotFactory.Create(player, botType, faction);
            var info      = bot.Info;
            var weaponSet = WeaponSet.Empty;

            if (RandomHelper.Percentage(info.EquipWeaponChance))
            {
                weaponSet = RandomHelper.GetItem(GetWeapons(botType));
            }
            BotHelper.Equip(player, weaponSet);

            var profile = RandomHelper.GetItem(GetProfiles(botType));

            player.SetProfile(profile);
            if (player.Name == "COM")
            {
                player.SetBotName(profile.Name);
            }

            var behaviorSet = GetBehaviorSet(info.AIType);

            behaviorSet.SearchItems     = info.SearchItems;
            behaviorSet.SearchItemRange = info.SearchRange;

            bot.SetBotBehaviorSet(behaviorSet, true);
            player.SetModifiers(info.Modifiers);
            player.SetBotBehaviorActive(true);

            m_bots[player.UniqueID] = bot; // This may be updated if using setplayer command

            if (triggerOnSpawn)
            {
                TriggerOnSpawn(bot);
            }

            return(bot);
        }
Esempio n. 11
0
        public static void RunQuickMatch()
        {
            var game = new SabberStoneState(new SabberStoneCore.Model.Game(new GameConfig {
                StartPlayer      = 1,
                Player1Name      = Constants.SABBERSTONE_GAMECONFIG_PLAYER1_NAME,
                Player1HeroClass = CardClass.HUNTER,
                Player1Deck      = Decks.GetRandomTournamentDeck(),
                Player2Name      = Constants.SABBERSTONE_GAMECONFIG_PLAYER2_NAME,
                Player2HeroClass = CardClass.HUNTER,
                Player2Deck      = Decks.GetRandomTournamentDeck(),
                FillDecks        = false,
                Shuffle          = true,
                SkipMulligan     = false,
                History          = false
            }));

            // Create two bots to play
            var bot1 = BotFactory.CreateSabberStoneBot(BotSetupType.RandomBot, game.Player1);
            var bot2 = BotFactory.CreateSabberStoneBot(BotSetupType.RandomBot, game.Player2);

            game.Game.StartGame();

            game.Game.Process(MulliganStrategySabberStone.DefaultMulligan(game.Game.Player1));
            game.Game.Process(MulliganStrategySabberStone.DefaultMulligan(game.Game.Player2));

            game.Game.MainReady();

            while (game.Game.State != State.COMPLETE)
            {
                Console.WriteLine("");
                Console.WriteLine($"TURN {(game.Game.Turn + 1) / 2} - {game.Game.CurrentPlayer.Name}");
                Console.WriteLine($"Hero[P1] {game.Player1.Hero} HP: {game.Player1.Hero.Health} / Hero[P2] {game.Player2.Hero} HP: {game.Player2.Hero.Health}");
                Console.WriteLine($"- {game.Game.CurrentPlayer.Name} Action ----------------------------");

                // Ask the bot to act.
                var action = game.Game.CurrentPlayer.Id == game.Player1.Id ? bot1.Act(game) : bot2.Act(game);

                // Check if the action is valid
                if (action == null || !action.IsComplete())
                {
                    continue;
                }

                // Process the tasks in the action
                foreach (var item in action.Tasks)
                {
                    // Process the task
                    Console.WriteLine(item.Task.FullPrint());
                    game.Game.Process(item.Task);
                }
            }

            Console.WriteLine($"Game: {game.Game.State}, Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState}");
        }
 /// <summary>
 /// Constructs a new instance of a TournamentMatch with a specific GameConfig between two bots.
 /// Note: the order of the bots does not reflect the playing order in the match's games. (starting player is alternated)
 /// </summary>
 /// <param name="bot1Setup">The setup for the first bot.</param>
 /// <param name="bot2Setup">The setup for the second bot.</param>
 /// <param name="numberOfGames">The amount of games that should be played in this match.</param>
 /// <param name="budgetType">The type of budget that this match will be limited on.</param>
 /// <param name="budgetLimit">The amount of budget that is available to the players, relative to the <see cref="BudgetType"/>.</param>
 /// <param name="printToConsole">[Optional] Whether or not to print game information to the Console.</param>
 public TournamentMatch(BotSetupType bot1Setup, BotSetupType bot2Setup, int numberOfGames, BudgetType budgetType, long budgetLimit, bool printToConsole = false)
 {
     Bots = new List <ISabberStoneBot> {
         BotFactory.CreateSabberStoneBot(bot1Setup), BotFactory.CreateSabberStoneBot(bot2Setup)
     };
     NumberOfGames   = numberOfGames;
     BudgetType      = budgetType;
     BudgetLimit     = (long)(budgetLimit * 1.02); // I'll allow a 2% margin on the budget limitation.
     MatchStatistics = new MatchStatistics($"{bot1Setup.ToString()}[{Constants.SABBERSTONE_GAMECONFIG_PLAYER1_NAME}]", $"{bot2Setup.ToString()}[{Constants.SABBERSTONE_GAMECONFIG_PLAYER2_NAME}]", numberOfGames, BudgetType, BudgetLimit);
     _printToConsole = printToConsole;
 }
Esempio n. 13
0
    public override void SetData(PlayerInfo data, int initBodyLength)
    {
        _BevTree                   = BotFactory.GetBehaviourTree();
        _BevWorkingData            = new BotWorkingData();
        _BevWorkingData._Character = this;
        base.SetData(data, initBodyLength);

        _PathUtil = this.gameObject.AddComponent <BotAStar>();
        _PathUtil.SetData(this);
        _PlayerCamera.SetData(_Head.transform);
    }
Esempio n. 14
0
 private void Load(List <string> names)
 {
     while (names.Count != 0)
     {
         BotPanel bot = BotFactory.GetStrategyForName(_botType, names[0], _startProgramm, _isScript);
         names.RemoveAt(0);
         lock (_botLocker)
         {
             _bots.Add(bot);
         }
     }
 }
Esempio n. 15
0
    // Update is called once per frame
    void Update()
    {
        float dt = Time.deltaTime;

        updateDeserts(dt);

        botFactory = GetComponent <BotFactory> ();
        botFactory.updateBots(bots, speed, dt);

        roadFactory = GetComponent <RoadFactory>();
        roadFactory.updateBorders(borders, speed, dt);
    }
Esempio n. 16
0
 public EventSyncer(
     ConversationService conversationService,
     FriendshipService friendshipService,
     BotLogger botLogger,
     BotFactory <T> botFactory,
     AES aes)
 {
     _conversationService = conversationService;
     _friendshipService   = friendshipService;
     _botLogger           = botLogger;
     _botFactory          = botFactory;
     _aes = aes;
 }
        private void FillBotDict()
        {
            var botEnumValues = Enum.GetValues(typeof(BotKind)).Cast <BotKind>().ToList();

            foreach (var botEnumValue in botEnumValues)
            {
                var bot  = BotFactory.BuildBot(botEnumValue);
                var name = bot.Name ?? botEnumValue.ToString();
                if (name != HumanPlayerName)
                {
                    _botKindToNameDict.Add(botEnumValue, name);
                }
            }
        }
Esempio n. 18
0
    public void startGame()
    {
        print("---------- { Game started } ----------");
        dialogGameStart = GameObject.FindGameObjectWithTag("DialogStart");
        dialogGameStart.SetActive(false);

        cameraMain = GameObject.FindGameObjectWithTag("MainCamera");
        player.GetComponent <PlayerCore>().transform.position = new Vector3(0f, 0f, 0f);

        bots.Clear();

        botFactory = GetComponent <BotFactory>();
        botFactory.initBots(bots, 4);
    }
Esempio n. 19
0
 public Round(
     int number,
     IBotFactory botFactory,
     ISettings settings,
     ITurnFactory turnFactory,
     IBattlefieldFactory battlefieldFactory)
 {
     Number             = number;
     BotFactory         = botFactory ?? throw new ArgumentNullException(nameof(botFactory));
     Settings           = settings ?? throw new ArgumentNullException(nameof(settings));
     TurnFactory        = turnFactory ?? throw new ArgumentNullException(nameof(turnFactory));
     BattlefieldFactory = battlefieldFactory ?? throw new ArgumentNullException(nameof(battlefieldFactory));
     Battlefield        = BattlefieldFactory.Create();
     Bots = BotFactory.Create(Battlefield);
     Battlefield.SetRandomly(Bots);
 }
Esempio n. 20
0
 public Game(MonsterFactory monsterFactory,
             HealerFactory healerFactory,
             WeaponDealerFactory weaponDealerFactory,
             ClothesDealerFactory clothesDealerFactory,
             BotFactory botFactory,
             Gamer gamer)
 {
     _gamer   = gamer;
     _actions = new Dictionary <ConsoleKey, Func <Personage> >
     {
         { ConsoleKey.W, monsterFactory.GetPersonage },
         { ConsoleKey.S, healerFactory.GetPersonage },
         { ConsoleKey.A, weaponDealerFactory.GetPersonage },
         { ConsoleKey.D, clothesDealerFactory.GetPersonage },
         { ConsoleKey.E, botFactory.GetPersonage }
     };
 }
Esempio n. 21
0
        public JsonResult SendMessage()
        {
            DataManagement dm = new DataManagement();

            if (Session["user"] == null)
            {
                return(Json(new { status = "error", message = "User is not logged in" }));
            }
            var    currentUser = (User)Session["user"];
            var    contact     = Convert.ToInt32(Request.Form["contact"]);
            string socket_id   = Request.Form["socket_id"];
            string userMessage = String.Empty;
            int    userId      = currentUser.id;

            if (!Global.GetCommandList().Contains(Request.Form["message"].Split('=')[0]))
            {
                userMessage = Request.Form["message"];
            }
            else
            {
                //Llamar bot
                IBot MyBot = BotFactory.GiveResponse();
                userMessage = MyBot.ResponseBot(Request.Form["message"].Split('=')[1].ToString());
                userId      = dm.GetUser("BOT").id;
            }
            Conversation convo = new Conversation
            {
                sender_id   = userId,
                message     = userMessage,
                receiver_id = contact
            };

            dm.SaveConversation(convo);
            var conversationChannel = getConvoChannel(currentUser.id, contact);

            pusher.TriggerAsync(
                conversationChannel,
                "new_message",
                convo,
                new TriggerOptions()
            {
                SocketId = socket_id
            });
            return(Json(convo));
        }
Esempio n. 22
0
 static void Main(string[] args)
 {
     Task.Run(() =>
     {
         BotFactory.FabricarBot(BotEnum.Twitch).Start();
     });
     Task.Run(() =>
     {
         string url = "http://localhost:8080";
         using (WebApp.Start(url))
         {
             Console.WriteLine("Server running on {0}", url);
             Console.ReadLine();
         }
     });
     //Console.ReadKey();
     Process.GetCurrentProcess().WaitForExit();
 }
Esempio n. 23
0
        private void WorkerArea()
        {
            while (true)
            {
                if (MainWindow.ProccesIsWorked == false)
                {
                    return;
                }

                if (_botNames == null ||
                    _botNames.Count == 0)
                {
                    Thread.Sleep(500);
                    continue;
                }

                for (int i = 0; i < _botNames.Count; i++)
                {
                    lock (_lockStr)
                    {
                        if (_targetChange == true)
                        {
                            Thread.Sleep(500);
                            _targetChange = false;
                            break;
                        }
                        BotPanel bot = BotFactory.GetStrategyForName(_botType, _botNames[i], StartProgram.IsOsOptimizer, _isScript);

                        lock (_botLocker)
                        {
                            _bots.Add(bot);
                        }
                        if (i + 1 == _botNames.Count)
                        {
                            _botNames.Clear();
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 24
0
        static async Task Main(string[] args)
        {
            var fac = new BotFactory();

            fac.AddProvider("TwitchBot", () => new TwitchProvider(false));
            fac.RegisterPlugin(
                "https://bot.tika.to/plugins/counter",
                () => new CounterPlugin()
                );

            using (var file = File.OpenRead("local.bot"))
            {
                var opts = new LoadOptions();
                var xml  = await XElement.LoadAsync(file, opts, CancellationToken.None);

                fac.LoadConfig(xml);
            }

            var bot = await fac.LoadBot();

            await bot.Run();
        }
Esempio n. 25
0
 public BotHost(
     BotCommander <T> botCommander,
     BotLogger botLogger,
     SettingsService settingsService,
     KahlaLocation kahlaLocation,
     FriendshipService friendshipService,
     AuthService authService,
     EventSyncer <T> eventSyncer,
     ProfileContainer profileContainer,
     BotFactory <T> botFactory,
     IEnumerable <IHostedService> backgroundJobs)
 {
     _botCommander      = botCommander.InjectHost(this);
     _botLogger         = botLogger;
     _settingsService   = settingsService;
     _kahlaLocation     = kahlaLocation;
     _friendshipService = friendshipService;
     _authService       = authService;
     _eventSyncer       = eventSyncer;
     _profileContainer  = profileContainer;
     _botFactory        = botFactory;
     _backgroundJobs    = backgroundJobs;
 }
        private void SecondPlayerComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SecondPlayerComboBox.SelectedItem == null)
            {
                return;
            }

            _secondPlayerString = (string)SecondPlayerComboBox.SelectedItem;
            if (_secondPlayerString != HumanPlayerName)
            {
                var botKind = _botKindToNameDict.First(kv => kv.Value == _secondPlayerString).Key;
                var bot     = BotFactory.BuildBot(botKind);
                SecondPlayerNameTextBox.IsEnabled = false;
                _secondPlayerCachedName           = SecondPlayerNameTextBox.Text;
                _secondPlayer = bot;
                SecondPlayerNameTextBox.Text = bot.Name;
            }
            else
            {
                SecondPlayerNameTextBox.Text = _secondPlayerCachedName;
                _secondPlayer = new HumanPlayer(_secondPlayerCachedName);
                SecondPlayerNameTextBox.IsEnabled = true;
            }
        }
Esempio n. 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            /*MessageController.ControllerBot = new TelegramBot("1158660778:AAEi0BoYtLIRBbfrNh6LmDbv7Lko3SIjppg")
             * {
             *  Name = "TestTelegramShop"
             * };
             * MessageController.ControllerBot.SetWebhook("https://shoptelegrambot.azurewebsites.net/api/message/Update").Wait();*/

            TelegramBot telegramBot = new TelegramBot("1158660778:AAEi0BoYtLIRBbfrNh6LmDbv7Lko3SIjppg",
                                                      "MainTelegramBot",
                                                      "https://shoptelegrambot.azurewebsites.net/TelegramBot/Update");

            telegramBot.SetCommands(new List <ICommand>()
            {
                new StartCommand(),
                new HelpCommand(),
                new HelloCommand(),
                new OrderCommand(telegramBot.StepPool),
                new CatalogueCommand(telegramBot.StepPool)
            });
            BotFactory.AddBot(telegramBot);

            services.AddControllers();
        }
Esempio n. 28
0
        /// <summary>
        /// create bot
        /// создать бота
        /// </summary>
        public void CreateNewBot()
        {
            try
            {
                BotCreateUi ui = new BotCreateUi(BotFactory.GetNamesStrategy(),
                                                 BotFactory.GetScriptsNamesStrategy(), StartProgram.IsOsTrader);

                ui.ShowDialog();

                if (ui.IsAccepted == false)
                {
                    return;
                }

                if (ui.NameStrategy == "Martingale")
                {
                    if (ui.NameBot.Split('h').Length != 1)
                    {
                        MessageBox.Show(OsLocalization.Trader.Label6);
                        return;
                    }
                    if (ui.NameBot.Split('l').Length != 1)
                    {
                        MessageBox.Show(OsLocalization.Trader.Label7);
                        return;
                    }
                }

                if (File.Exists(@"Engine\" + @"SettingsRealKeeper.txt"))
                {
                    using (StreamReader reader = new StreamReader(@"Engine\" + @"SettingsRealKeeper.txt"))
                    {
                        while (!reader.EndOfStream)
                        {
                            string[] str = reader.ReadLine().Split('@');

                            if (str[0] == ui.NameBot)
                            {
                                MessageBox.Show(OsLocalization.Trader.Label8);
                                return;
                            }
                        }
                    }
                }

                if (File.Exists(@"Engine\" + @"SettingsTesterKeeper.txt"))
                {
                    using (StreamReader reader = new StreamReader(@"Engine\" + @"SettingsTesterKeeper.txt"))
                    {
                        while (!reader.EndOfStream)
                        {
                            string[] str = reader.ReadLine().Split('@');

                            if (str[0] == ui.NameBot)
                            {
                                MessageBox.Show(OsLocalization.Trader.Label8);
                                return;
                            }
                        }
                    }
                }

                BotPanel newRobot = BotFactory.GetStrategyForName(ui.NameStrategy, ui.NameBot, _startProgram, ui.IsScript);

                if (PanelsArray == null)
                {
                    PanelsArray = new List <BotPanel>();
                }
                PanelsArray.Add(newRobot);

                if (BotCreateEvent != null)
                {
                    BotCreateEvent(newRobot);
                }

                SendNewLogMessage(OsLocalization.Trader.Label9 + newRobot.NameStrategyUniq, LogMessageType.System);

                ReloadActivBot(newRobot);
                Save();

                ReloadRiskJournals();
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// load robots with saved names
        /// загрузить роботов по сохранённым именам
        /// </summary>
        private void Load()
        {
            if (!File.Exists(@"Engine\Settings" + _typeWorkKeeper + "Keeper.txt"))
            { // if there is no file we need. Just go out
              // если нет нужного нам файла. Просто выходим
                return;
            }


            int botCount = 0;

            using (StreamReader reader = new StreamReader(@"Engine\Settings" + _typeWorkKeeper + "Keeper.txt"))
            {
                while (!reader.EndOfStream)
                {
                    if (!string.IsNullOrWhiteSpace(reader.ReadLine()))
                    {
                        botCount++;
                    }
                }
            }

            if (botCount == 0)
            {
                return;
            }

            PanelsArray = new List <BotPanel>();

            int botIterator = 0;

            using (StreamReader reader = new StreamReader(@"Engine\Settings" + _typeWorkKeeper + "Keeper.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string[] names = reader.ReadLine().Split('@');

                    BotPanel bot = null;

                    if (names.Length > 2)
                    {
                        try
                        {
                            bot = BotFactory.GetStrategyForName(names[1], names[0], _startProgram, Convert.ToBoolean(names[2]));
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(" Error on bot creation. Bot Name: " + names[1] + " \n" + e.ToString());
                            continue;
                        }
                    }
                    else
                    {
                        bot = BotFactory.GetStrategyForName(names[1], names[0], _startProgram, false);
                    }

                    if (bot != null)
                    {
                        PanelsArray.Add(bot);

                        if (BotCreateEvent != null)
                        {
                            BotCreateEvent(bot);
                        }

                        if (_tabBotNames != null)
                        {
                            _tabBotNames.Items.Add(" " + PanelsArray[botIterator].NameStrategyUniq + " ");
                            SendNewLogMessage(OsLocalization.Trader.Label2 + PanelsArray[botIterator].NameStrategyUniq,
                                              LogMessageType.System);
                        }

                        botIterator++;

                        bot.NewTabCreateEvent += () =>
                        {
                            ReloadRiskJournals();
                        };
                    }
                }
            }
            if (PanelsArray.Count != 0)
            {
                ReloadActivBot(PanelsArray[0]);
            }
        }
Esempio n. 30
0
 public BotHandler(BotFactory botFactory, DataSource dataSource)
 {
     this.botFactory = botFactory;
     this.dataSource = dataSource;
 }
Esempio n. 31
0
        /// <summary>
        /// launch another robot as part of optimization
        /// запустить ещё одного робота, в рамках оптимизации
        /// </summary>
        /// <param name="parametrs">list of all parameters/список всех параметров</param>
        /// <param name="paramOptimized">brute force options/параметры по которым осуществляется перебор</param>
        /// <param name="faze">current optimization phase/текущая фаза оптимизации</param>
        /// <param name="botsInFaze">list of bots already running in the current phase/список ботов уже запущенный в текущей фазе</param>
        /// <param name="botName">the name of the created robot/имя создаваемого робота</param>
        private async void StartNewBot(List <IIStrategyParameter> parametrs, List <IIStrategyParameter> paramOptimized,
                                       OptimizerFaze faze, List <BotPanel> botsInFaze, string botName)
        {
            if (!MainWindow.GetDispatcher.CheckAccess())
            {
                MainWindow.GetDispatcher.Invoke(
                    new Action
                    <List <IIStrategyParameter>, List <IIStrategyParameter>,
                     OptimizerFaze, List <BotPanel>, string>(StartNewBot),
                    parametrs, paramOptimized, faze, botsInFaze, botName);
                await Task.Delay(1000);

                return;
            }

            // 1. Create a new server for optimization. And one thread respectively
            // 1. создаём новый сервер для оптимизации. И один поток соответственно
            OptimizerServer server = ServerMaster.CreateNextOptimizerServer(_master.Storage, _serverNum,
                                                                            _master.StartDepozit);

            _serverNum++;
            _servers.Add(server);

            server.TestingEndEvent            += server_TestingEndEvent;
            server.TypeTesterData              = _master.Storage.TypeTesterData;
            server.TestintProgressChangeEvent += server_TestintProgressChangeEvent;

            for (int i = 0; i < _master.TabsSimpleNamesAndTimeFrames.Count; i++)
            {
                Security secToStart =
                    _master.Storage.Securities.Find(s => s.Name == _master.TabsSimpleNamesAndTimeFrames[i].NameSecurity);

                server.GetDataToSecurity(secToStart, _master.TabsSimpleNamesAndTimeFrames[i].TimeFrame, faze.TimeStart,
                                         faze.TimeEnd);
            }

            // 2. create a new robot and upload it with the appropriate settings and parameters
            // 2. создаём нового робота и прогружаем его соответствующими настройками и параметрами

            BotPanel bot = BotFactory.GetStrategyForName(_master.StrategyName, botName, StartProgram.IsOsOptimizer, _master.IsScript);

            for (int i = 0; i < parametrs.Count; i++)
            {
                IIStrategyParameter par = paramOptimized.Find(p => p.Name == parametrs[i].Name);

                if (par == null)
                {
                    par = parametrs[i];
                }

                if (bot.Parameters[i].Type == StrategyParameterType.Bool)
                {
                    ((StrategyParameterBool)bot.Parameters[i]).ValueBool = ((StrategyParameterBool)par).ValueBool;
                }
                else if (bot.Parameters[i].Type == StrategyParameterType.String)
                {
                    ((StrategyParameterString)bot.Parameters[i]).ValueString = ((StrategyParameterString)par).ValueString;
                }
                else if (bot.Parameters[i].Type == StrategyParameterType.Int)
                {
                    ((StrategyParameterInt)bot.Parameters[i]).ValueInt = ((StrategyParameterInt)par).ValueInt;
                }
                else if (bot.Parameters[i].Type == StrategyParameterType.Decimal)
                {
                    ((StrategyParameterDecimal)bot.Parameters[i]).ValueDecimal = ((StrategyParameterDecimal)par).ValueDecimal;
                }
            }

            // custom tabs
            // настраиваем вкладки
            for (int i = 0; i < _master.TabsSimpleNamesAndTimeFrames.Count; i++)
            {
                bot.TabsSimple[i].Connector.ServerType    = ServerType.Optimizer;
                bot.TabsSimple[i].Connector.PortfolioName = server.Portfolios[0].Number;
                bot.TabsSimple[i].Connector.NamePaper     = _master.TabsSimpleNamesAndTimeFrames[i].NameSecurity;
                bot.TabsSimple[i].Connector.TimeFrame     =
                    _master.TabsSimpleNamesAndTimeFrames[i].TimeFrame;

                if (server.TypeTesterData == TesterDataType.Candle)
                {
                    bot.TabsSimple[i].Connector.CandleMarketDataType = CandleMarketDataType.Tick;
                }
                else if (server.TypeTesterData == TesterDataType.MarketDepthAllCandleState ||
                         server.TypeTesterData == TesterDataType.MarketDepthOnlyReadyCandle)
                {
                    bot.TabsSimple[i].Connector.CandleMarketDataType =
                        CandleMarketDataType.MarketDepth;
                }
            }

            for (int i = 0; i < _master.TabsIndexNamesAndTimeFrames.Count; i++)
            {
                bot.TabsIndex[i].Tabs.Clear();
                for (int i2 = 0; i2 < _master.TabsIndexNamesAndTimeFrames[i].NamesSecurity.Count; i2++)
                {
                    if (i2 >= bot.TabsIndex[i].Tabs.Count)
                    {
                        bot.TabsIndex[i].CreateNewSecurityConnector();
                    }

                    bot.TabsIndex[i].Tabs[i2].ServerType    = ServerType.Optimizer;
                    bot.TabsIndex[i].Tabs[i2].PortfolioName = server.Portfolios[0].Number;
                    bot.TabsIndex[i].Tabs[i2].NamePaper     = _master.TabsIndexNamesAndTimeFrames[i].NamesSecurity[i2];
                    bot.TabsIndex[i].Tabs[i2].TimeFrame     =
                        _master.TabsIndexNamesAndTimeFrames[i].TimeFrame;

                    if (server.TypeTesterData == TesterDataType.Candle)
                    {
                        bot.TabsIndex[i].Tabs[i2].CandleMarketDataType = CandleMarketDataType.Tick;
                    }
                    else if (server.TypeTesterData == TesterDataType.MarketDepthAllCandleState ||
                             server.TypeTesterData == TesterDataType.MarketDepthOnlyReadyCandle)
                    {
                        bot.TabsIndex[i].Tabs[i2].CandleMarketDataType =
                            CandleMarketDataType.MarketDepth;
                    }
                }
                bot.TabsIndex[i].UserFormula = _master.TabsIndexNamesAndTimeFrames[i].Formula;
            }

            // wait for the robot to connect to its data server
            // ждём пока робот подключиться к своему серверу данных

            DateTime timeStartWaiting = DateTime.Now;

            while (bot.IsConnected == false)
            {
                await Task.Delay(1000);

                if (timeStartWaiting.AddSeconds(20) < DateTime.Now)
                {
                    SendLogMessage(
                        OsLocalization.Optimizer.Message10,
                        LogMessageType.Error);
                    return;
                }
            }

            server.TestingStart();

            botsInFaze.Add(bot);
        }