public ActionResult Post(BotModel model)
        {
            using (var db = new AppDatabase())
            {
                var bot = db.GetBot();

                if (bot == null)
                {
                    db.Bots.Upsert(new Database.Entities.Bot
                    {
                        Id             = 1,
                        IsEnabled      = false,
                        AccessToken    = model.AccessToken,
                        LastUpdatedUtc = DateTime.UtcNow
                    });
                }
                else
                {
                    // Reset all other parameters if token changes
                    //
                    if (bot.AccessToken != model.AccessToken)
                    {
                        bot.Username       = null;
                        bot.ChatId         = 0;
                        bot.IsEnabled      = false;
                        bot.LastUpdatedUtc = DateTime.UtcNow;
                        bot.AccessToken    = model.AccessToken;
                        db.Bots.Update(bot);
                    }
                }

                return(Ok());
            }
        }
        public void ReturnNullWhenAllBotsAreWorkedOrCrashed()
        {
            var botDataContext = new MemoryDataContext();
            var bot1           = new BotModel
            {
                Login = "******",
                State = EBotState.Worked,
            };

            botDataContext.AddBot(bot1);

            var bot2 = new BotModel
            {
                Login = "******",
                State = EBotState.Crashed,
            };

            botDataContext.AddBot(bot2);

            var botRepository = new BotRepository(botDataContext);

            var resultBot = botRepository.GetFreeBot();

            Assert.IsNull(resultBot, "There are free bots in this test.");
        }
 public BotConfigurationEditor(BotModel botModel)
 {
     InitializeComponent();
     this.botModel = botModel;
     LoadData();
     AddContextMenu();
 }
Exemple #4
0
            public Bot(BotModel model)
            {
                ID     = model.ID;
                userID = model.userID ?? -1;

                minWords        = model.minWords;
                maxWords        = model.maxWords;
                postProbability = model.postProbability;

                model.seed = Encoding.ASCII.GetString(
                    Encoding.Convert(Encoding.UTF8,
                                     Encoding.GetEncoding(
                                         Encoding.ASCII.EncodingName,
                                         new EncoderReplacementFallback(string.Empty),
                                         new DecoderExceptionFallback()
                                         ),
                                     Encoding.UTF8.GetBytes(model.seed)
                                     )
                    );
                model.seed = model.seed.Replace(".", " . ");
                model.seed = model.seed.Replace(",", " , ");
                model.seed = model.seed.Replace("!", " ! ");
                model.seed = model.seed.Replace("?", " ! ");
                model.seed = model.seed.Replace("\r", " ");
                model.seed = model.seed.Replace("\n", " ");
                model.seed = model.seed.ToLower();

                var tempseed = model.seed
                               .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                words = tempseed.Distinct().ToArray();
                count = words.Count();
                string[] seed = tempseed.ToArray();
                markovMatrix = new float[count, count];

                for (int i = 1; i < seed.Count(); i++)
                {
                    int currIndex = Array.IndexOf(words, seed[i]);
                    int prevIndex = Array.IndexOf(words, seed[i - 1]);
                    markovMatrix[currIndex, prevIndex] += 1.0f;
                }

                // matrix normalizataion
                for (int x = 0; x < count; x++)
                {
                    float columnCount = 0;
                    for (int y = 0; y < count; y++)
                    {
                        columnCount += markovMatrix[x, y];
                    }

                    if (columnCount != 0)
                    {
                        for (int y = 0; y < count; y++)
                        {
                            markovMatrix[x, y] /= columnCount;
                        }
                    }
                }
            }
Exemple #5
0
 // GET: WebChat/Bot
 public ActionResult Index()
 {
     #region
     //            var encryptedID = CryptoHelpers.EncryptString(System.Web.HttpContext.Current.User.Identity.GetUserId(), "1234", false);
     //            using (var context = new ConversationDataContext())
     //            {
     //                var record = (from each in context.UserKeys
     //                    where each.UserId == encryptedID
     //                    select each).FirstOrDefault();
     //
     //                if (record == null || (record.Timestamp < DateTime.UtcNow.AddSeconds(-20)))
     //                {
     //                    RedirectToAction("Register", "Account");
     //                }
     //                else
     //                {
     //                    context.UserKeys.Remove(record);
     //                    context.SaveChanges();
     //
     //                }
     //            }
     #endregion
     var model = new BotModel(System.Web.HttpContext.Current.User.Identity.GetUserId());
     return(View(model));
 }
Exemple #6
0
 private string CheckAmount(BotModel bot, int index)
 {
     if (bot.Money <= 0)
     {
         _bots.RemoveAt(index);
         return(String.Format("\t{0} Left the game", bot.Name));
     }
     return(Constants.EmptyString);
 }
Exemple #7
0
        internal static BotModel Process(BotModel botModel)
        {
            var time   = botModel.Request.Parameters.FirstOrDefault(p => p.Key == "time");
            var date   = botModel.Request.Parameters.FirstOrDefault(p => p.Key == "date");
            var number = botModel.Request.Parameters.FirstOrDefault(p => p.Key == "number");

            botModel.Response.Text = "Awesome! Your table for " + number + " is booked for " + date + " at " + time + "Have a nice day!";
            return(botModel);
        }
Exemple #8
0
        public void AddBotWith(string login, EBotState state)
        {
            var bot = new BotModel
            {
                Login = login,
                State = state,
            };

            AddBot(bot);
        }
Exemple #9
0
        internal static GoogleCloudDialogflowV2WebhookResponse ModelToDialogFlow(BotModel botModel)
        {
            var response = new GoogleCloudDialogflowV2WebhookResponse()
            {
                FulfillmentText = botModel.Response.Text,
                Source          = "BookAtableBot",
            };

            return(response);
        }
Exemple #10
0
 private void BotLogic(BotModel bot)
 {
     bot.Bid = 50;
     if (Constants.ScoreLimitForBots >= bot.Score)
     {
         bot.Cards.Add(_getCardFromDeck());
         BotLogic(bot);
         return;
     }
 }
        public async static Task <List <string> > GetChatProfiles()
        {
            var config = await DbBotCollection.FindOneById(BotAlphaName);

            if (config == null)
            {
                var botModel = new BotModel();
                botModel._id = BotAlphaName;
                config       = await DbBotCollection.InsertNewOrUpdate(botModel);
            }
            return(config?.Configuration?.ChatProfiles?.Select(item => item.Name).ToList());
        }
Exemple #12
0
        internal static BotModel DialogFlowToModel(GoogleCloudDialogflowV2WebhookRequest dFlowResponse)
        {
            var botModel = new BotModel()
            {
                Id = dFlowResponse.ResponseId
            };

            botModel.Session.Id         = dFlowResponse.Session;
            botModel.Request.Intent     = dFlowResponse.QueryResult.Intent.DisplayName;
            botModel.Request.Parameters = dFlowResponse.QueryResult.Parameters.ToList()
                                          .ConvertAll(p => new KeyValuePair <string, string>(p.Key, p.Value.ToString()));
            return(botModel);
        }
        public static BotModel Process(BotModel botModel)
        {
            var intentsList = WebApiConfig.IntentHandlers;
            var intent      = intentsList.FirstOrDefault(i => i.Key.ToLower() == botModel.Request.Intent.ToLower());

            if (!string.IsNullOrWhiteSpace(intent.Key))
            {
                return(intent.Value(botModel));
            }
            if (string.IsNullOrWhiteSpace(botModel.Response.Text))
            {
                botModel.Response.Text = "Sorry, I do not understand. please try again.";
            }
            return(botModel);
        }
        public void LoginIsCorrectWhenFreeBotIsExisted()
        {
            var          botDataContext = new MemoryDataContext();
            const string botLogin       = "******";
            var          bot            = new BotModel
            {
                Login = botLogin,
                State = EBotState.Free,
            };

            botDataContext.AddBot(bot);
            var botRepository = new BotRepository(botDataContext);

            var resultBot = botRepository.GetFreeBot();

            Assert.AreEqual(botLogin, resultBot.Login, "Not correct bot's login.");
        }
        public void UpdateBotStateFromWorkedToCrashed()
        {
            var botDataContext = new MemoryDataContext();
            var bot            = new BotModel
            {
                Id    = new ObjectId("597dd372ab6fc118d85cc08d"),
                Login = "******",
                State = EBotState.Worked,
            };

            botDataContext.AddBot(bot);
            var botsHandler = new BotRepository(botDataContext);

            botsHandler.UpdateStateBot(bot.Id, EBotState.Crashed);

            var updatedBot = botDataContext.GetBotByLogin("plaprobot");

            Assert.AreEqual(EBotState.Crashed, updatedBot.State, "Bot's state is not updated.");
        }
        public void EditBot([FromBody] BotModel botData)
        {
            using (var db = new ApplicationContext())
            {
                BotModel bot    = new BotModel();
                string   userId = User.Identity.GetUserId();

                bot = db.BotModels.FirstOrDefault(b => b.UserId == userId);

                bot.TradePairs    = botData.TradePairs;
                bot.MinPriceTrade = botData.MinPriceTrade;
                bot.MinOrder      = botData.MinOrder;
                bot.MinProfit     = botData.MinProfit;
                bot.TimeLose      = botData.TimeLose;
                bot.IsOn          = botData.IsOn;

                db.Entry(bot).State = EntityState.Modified;

                db.SaveChanges();
            }
        }
        public async Task <IActionResult> Bot(int id)
        {
            try
            {
                appsettingsModel appsettings = JsonConvert.DeserializeAnonymousType(ServerFileManager.FileReader(GetPathes.Get_SolutionMainPath() + "/Alduin.Web/appsettings.json"), new appsettingsModel());
                var query = new GetBotByIdQuery
                {
                    Id = id
                };
                GetImgJsonModel ImagesJsonModel = JsonConvert.DeserializeAnonymousType(await _getBotImagesJsonServices.GetAllImg(id), new GetImgJsonModel());
                var             bot             = await _mediator.Send(query);

                DateTime DateNowUTC = DateTime.UtcNow.AddMinutes(-5);
                var      status     = _localizer["Offline"];
                if (bot.LastLoggedInUTC >= DateNowUTC)
                {
                    status = _localizer["Online"];
                }
                var botInquiryDeatils = new BotDeatilsInquiryModel
                {
                    Name            = bot.UserName,
                    Domain          = bot.Domain,
                    LastIPAddress   = bot.LastIPAddress,
                    LastLoggedInUTC = bot.LastLoggedInUTC,
                    Status          = status,
                    KeyCertified    = bot.KeyCertified,
                    KeyUnique       = appsettings.Stump.KeyCertified
                };
                var botmodel = new BotModel
                {
                    newImagesJsonModel        = ImagesJsonModel,
                    newBotDeatilsInquiryModel = botInquiryDeatils
                };
                return(View(botmodel));
            }
            catch
            {
                return(RedirectToAction(nameof(List)));
            };
        }
        public HttpResponseMessage GetOrCreateBot()
        {
            using (var db = new ApplicationContext())
            {
                BotModel bot    = new BotModel();
                string   userId = User.Identity.GetUserId();

                bot = db.BotModels.FirstOrDefault(b => b.UserId == userId);

                // Если в базе данных не был найден бот
                // прикрепленный к активному пользовотелю,
                // заполняем  бота значениями по умолчанию
                // и записываем его в
                if (bot == null)
                {
                    bot = new BotModel();
                    // Id пользователя к которому мы прикрепляем бота.
                    bot.UserId = userId;
                    // Максимальное количество одновременно торгуемых пар
                    bot.TradePairs = 10;
                    // Минимальная цена криптовалюты для торговли (в рублях за одну монету ).
                    bot.MinPriceTrade = 1;
                    // Минимальный размер одного ордера в рублях
                    bot.MinOrder = 10;
                    // Минимальный размер выгоды в процентах
                    bot.MinProfit = 4;
                    // Время ожидания перед продажей, даже если нет выгоды (в часах)
                    bot.TimeLose = 8;
                    // Включен ли бот
                    bot.IsOn = false;

                    db.BotModels.Add(bot);

                    db.SaveChanges();
                }
                return(Request.CreateResponse(HttpStatusCode.OK, bot));
            }
        }
Exemple #19
0
        public List <BotModel> CreateBotModels(int numberOdBots)
        {
            List <BotModel> bots = new List <BotModel>();

            for (int i = 0; i < numberOdBots; i++)
            {
                int randomIndex = Random.Next(warshipNames.Count);
                Console.WriteLine(randomIndex);
                Console.WriteLine(warshipNames.Count);
                string   warshipName = warshipNames[randomIndex];
                ushort   id          = BotTemporaryIdFactory.Create();
                BotModel botModel    = new BotModel
                {
                    BotName           = GenerateNickname(id, warshipName),
                    WarshipName       = warshipName,
                    TemporaryId       = id,
                    WarshipPowerLevel = 1
                };
                bots.Add(botModel);
            }

            return(bots);
        }
        public async Task <IActionResult> Bot(int id)
        {
            try
            {
                var getImagesStatus = "";
#if (!DEBUG)
                // Release
                appsettingsModel appsettings = JsonConvert.DeserializeAnonymousType(ServerFileManager.FileReader(GetPathes.Get_SolutionMainPath() + "/appsettings.json"), new appsettingsModel());
#else
                // Debug
                appsettingsModel appsettings = JsonConvert.DeserializeAnonymousType(ServerFileManager.FileReader(GetPathes.Get_SolutionMainPath() + "/Alduin.Web/appsettings.json"), new appsettingsModel());
#endif
                GetImgJsonModel ImagesJsonModel;
                var             query = new GetBotByIdQuery
                {
                    Id = id
                };
                var bot = await _mediator.Send(query);

                if (_env.WebRootFileProvider.GetDirectoryContents("img/Bots/" + bot.UserName + "_" + id).Exists)
                {
                    var           fullpath = _env.WebRootFileProvider.GetFileInfo("img/Bots")?.PhysicalPath + "/" + bot.UserName + "_" + id;
                    var           files    = Directory.GetFiles(fullpath);//Wait to test
                    List <string> images   = new List <string>(files);
                    ImagesJsonModel = new GetImgJsonModel()
                    {
                        Images = images
                    };
                    getImagesStatus = "local";
                }
                else
                {
                    try
                    {
                        ImagesJsonModel = JsonConvert.DeserializeAnonymousType(await _getBotImagesJsonServices.GetAllImg(id), new GetImgJsonModel());
                        if (ImagesJsonModel.Images.Count == 0)
                        {
                            getImagesStatus = "nothing";
                        }
                        else
                        {
                            getImagesStatus = "network";
                        }
                    }
                    catch
                    {
                        ImagesJsonModel = JsonConvert.DeserializeAnonymousType("{'Images':[]}", new GetImgJsonModel());
                        getImagesStatus = "nothing";
                    };
                }
                DateTime DateNowUTC = DateTime.UtcNow.AddMinutes(-5);
                var      status     = _localizer["Offline"];
                if (bot.LastLoggedInUTC >= DateNowUTC)
                {
                    status = _localizer["Online"];
                }
                var botInquiryDeatils = new BotDeatilsInquiryModel
                {
                    Name            = bot.UserName,
                    Domain          = bot.Domain,
                    LastIPAddress   = bot.LastIPAddress,
                    LastLoggedInUTC = bot.LastLoggedInUTC,
                    Status          = status,
                    KeyCertified    = bot.KeyCertified,
                    KeyUnique       = appsettings.Stump.KeyCertified
                };
                var botmodel = new BotModel
                {
                    newImagesJsonModel        = ImagesJsonModel,
                    newBotDeatilsInquiryModel = botInquiryDeatils,
                    getImagesStatus           = getImagesStatus
                };
                ViewData["ID"] = id;
                return(View(botmodel));
            }
            catch (Exception e)
            {
                return(Content(e.ToString()));
            };
        }
Exemple #21
0
 public void AddBot(BotModel bot)
 {
     bots.Add(bot);
 }
        public async Task <BotModel> Simulate(BotModel bot)
        {
            bot.TradeBook = new TradeBook()
            {
                Id           = 10,
                TradeEntries = new List <TradeEntry>(1000),
                Series       = new List <SeriesItem>(1000)
            };
            // gather needed data to execute trades against
            var tickerDetails = await IntrinioService.GetTickerDetails(bot.TargetTicker.TickerSymbol);

            var prices = await IntrinioService.GetTickerPrices(bot.TargetTicker.TickerSymbol, bot.StartDate.AddDays(-1), DateTime.UtcNow.Date);

            var priceLookup = prices.ToDictionary(k => k.Date.ToString("yyyyMMddHHmmss"), m => new NormalizedPriceItem()
            {
                High  = (int)(m.High * 100),
                Low   = (int)(m.Low * 100),
                Open  = (int)(m.Open * 100),
                Close = (int)(m.Close * 100),
                Date  = DateTime.SpecifyKind(m.Date, DateTimeKind.Utc)
            });

            // register data with the model so it can perform its analysis

            bot.Model.RegisterInputSources(IntrinioService.GetTickerPrices, bot.StartDate, DateTime.UtcNow);

            // run get signal over a time series of the target equity
            var idxDate       = bot.StartDate;
            var stopDate      = DateTime.UtcNow;
            var idxDateString = idxDate.ToString("yyyyMMddHHmmss");
            // Take the first time step and use it to setup initial portfolio

            NormalizedPriceItem currPrice;

            while (!priceLookup.ContainsKey(idxDateString))
            {
                idxDate       = idxDate.AddDays(1);
                idxDateString = idxDate.ToString("yyyyMMddHHmmss");
            }
            currPrice = priceLookup[idxDateString];
            var prevItem = new SeriesItem()
            {
                Signal         = Signal.Hold,
                Date           = idxDate,
                Open           = currPrice.Open,
                High           = currPrice.High,
                Low            = currPrice.Low,
                Close          = currPrice.Close,
                PortfolioValue = currPrice.Close,
                Position       = 0
            };

            bot.TradeBook.Series.Add(prevItem);
            idxDate       = idxDate.AddDays(1);
            idxDateString = idxDate.ToString("yyyyMMddHHmmss");
            while (idxDate < stopDate)
            {
                // make sure the date is included in our data set coming from the data provider (ie intrinio)
                // (ie skip weekends)
                if (priceLookup.ContainsKey(idxDateString))
                {
                    // set up calculations for this time-step
                    var(newSignal, multiplier) = await bot.Model.GetSignal(idxDate);

                    var tradeEntry = new TradeEntry()
                    {
                        Type          = "pin",
                        RollOverColor = blue
                    };
                    currPrice = priceLookup[idxDateString];

                    var seriesItem = new SeriesItem()
                    {
                        Date   = idxDate,
                        Open   = currPrice.Open,
                        High   = currPrice.High,
                        Low    = currPrice.Low,
                        Close  = currPrice.Close,
                        Signal = newSignal,
                    };

                    ///
                    /// ====================================================================
                    /// Determine if we want to alter our position based on the model signal
                    /// ====================================================================
                    ///
                    var positionChange = 0;
                    if (prevItem.Signal != newSignal)
                    {
                        switch (newSignal)
                        {
                        case Signal.Buy:

                            // if prev position is a short we want to reverse it
                            positionChange = (int)Math.Round(bot.OrderAmount * multiplier) - prevItem.Position;

                            tradeEntry.Position        = TradeType.Buy;
                            tradeEntry.Text            = "B";
                            tradeEntry.Date            = idxDate;
                            tradeEntry.Price           = seriesItem.Close;
                            seriesItem.Position        = positionChange + prevItem.Position;
                            tradeEntry.Description     = Math.Abs(positionChange) + " share(s) purchased @ $" + seriesItem.Close / 100.0;
                            tradeEntry.BackgroundColor = buyColor;
                            break;

                        case Signal.Sell:
                            // if long the prev position we want to reverse it
                            positionChange             = -1 * (int)Math.Round(bot.OrderAmount * multiplier) - prevItem.Position;
                            tradeEntry.Position        = TradeType.Sell;
                            tradeEntry.Text            = "S";
                            tradeEntry.Date            = idxDate;
                            tradeEntry.Price           = seriesItem.Close;
                            seriesItem.Position        = positionChange + prevItem.Position;
                            tradeEntry.Description     = Math.Abs(positionChange) + " share(s) sold @ $" + seriesItem.Close / 100.0;
                            tradeEntry.BackgroundColor = sellColor;
                            break;

                        case Signal.Hold:
                            // if long the prev position we want to reverse it
                            positionChange = -1 * prevItem.Position;

                            tradeEntry.Text     = "H";
                            tradeEntry.Date     = idxDate;
                            tradeEntry.Price    = seriesItem.Close;
                            seriesItem.Position = positionChange + prevItem.Position;
                            if (positionChange > 0)
                            {
                                tradeEntry.Description = Math.Abs(positionChange) + " share(s) bought @ $" + seriesItem.Close / 100.0 + " to flatten position.";
                                tradeEntry.Position    = TradeType.Buy;
                            }
                            else
                            {
                                tradeEntry.Description = Math.Abs(positionChange) + " share(s) sold @ $" + seriesItem.Close / 100.0 + " to flatten position.";
                                tradeEntry.Position    = TradeType.Sell;
                            }
                            tradeEntry.BackgroundColor = "#0075be";
                            break;

                        default:
                            throw new Exception("Unhandled signal '" + newSignal.ToString() + "'!!!");
                        }
                        bot.TradeBook.TradeEntries.Add(tradeEntry);
                    }
                    else
                    {
                        seriesItem.Position = prevItem.Position;
                    }
                    ///
                    /// ====================================================================
                    ///

                    ///
                    /// ====================================================================
                    /// Calculate portfolio value
                    ///     Use the previous indexes signal value / position and the current closed value
                    ///     to determine how the porfolio changed
                    /// ====================================================================
                    ///
                    if (prevItem.Position != 0)
                    {
                        seriesItem.PortfolioValue = prevItem.Position * (seriesItem.Close - prevItem.Close) + prevItem.PortfolioValue;
                    }
                    else if (prevItem.Position < 0)
                    {
                        seriesItem.PortfolioValue = prevItem.Position * (seriesItem.Close - prevItem.Close) + prevItem.PortfolioValue;
                    }
                    else
                    {
                        seriesItem.PortfolioValue = prevItem.PortfolioValue;
                    }

                    ///
                    /// ====================================================================
                    ///

                    prevItem = seriesItem;
                    bot.TradeBook.Series.Add(seriesItem);
                }
                idxDate       = idxDate.AddDays(1);
                idxDateString = idxDate.ToString("yyyyMMddHHmmss");
            }

            ///
            /// If we have an open position then lets go ahead and close it out
            ///

            if (prevItem.Position != 0)
            {
                var closeOutTradeEntry = new TradeEntry();
                var positionChange     = -1 * prevItem.Position;

                closeOutTradeEntry.Text  = "H";
                closeOutTradeEntry.Date  = prevItem.Date;
                closeOutTradeEntry.Price = prevItem.Close;
                prevItem.Position        = positionChange + prevItem.Position;
                if (positionChange > 0)
                {
                    closeOutTradeEntry.Description = Math.Abs(positionChange) + " share(s) bought @ $" + prevItem.Close / 100.0 + " to flatten position.";
                }
                else
                {
                    closeOutTradeEntry.Description = Math.Abs(positionChange) + " share(s) sold @ $" + prevItem.Close / 100.0 + " to flatten position.";
                }
                closeOutTradeEntry.BackgroundColor = "#0075be";
                bot.TradeBook.TradeEntries.Add(closeOutTradeEntry);
            }


            ///
            /// ====================================================================
            /// Calculate stats
            /// ====================================================================
            ///

            var stats = new TradingStats();

            var startingValue = bot.TradeBook.Series.First().PortfolioValue;
            var endingValue   = bot.TradeBook.Series.Last().PortfolioValue;

            stats.TotalPnL = endingValue - startingValue;
            var tradeProfits = new List <int>();

            for (int idx = 0; idx < bot.TradeBook.TradeEntries.Count - 1; idx += 2)
            {
                var entryTrade = bot.TradeBook.TradeEntries[idx];
                var exitTrade  = bot.TradeBook.TradeEntries[idx + 1];


                //think more about this need to get true profit
                if (entryTrade.Position == TradeType.Buy)
                {
                    tradeProfits.Add(exitTrade.Price - entryTrade.Price);
                }
                else
                {
                    tradeProfits.Add(entryTrade.Price - exitTrade.Price);
                }
            }
            stats.WinPct = 100 * tradeProfits.Count(k => k > 0) / tradeProfits.Count();

            bot.TradeBook.TradingStats = stats;
            bot.Model.Reset();
            return(bot);
        }
 public BotManager(BotRepository botRepository, BotModel botModel)
 {
     this.botRepository = botRepository;
     this.bot           = botModel;
 }
 internal static BotModel Process(BotModel botModel)
 {
     botModel.Response.Text = "Hi! Would you like to book a table? If yes, simply type 'Book a table'";
     return(botModel);
 }