public void Start(bool coinigyEnabled, bool bittrexEnabled, bool poloEnabled, bool bagManagementEnabled) { // Needs to be called here as if we use DI, the config has not been binded yet _bot.StartBot(_telegramConfig); var registry = new Registry(); if (bittrexEnabled || poloEnabled) { SendStartupMessage().Wait(); registry.Schedule(() => GetNewOrders().Wait()) .ToRunNow() .AndEvery(5) .Minutes(); } if (bittrexEnabled || poloEnabled || coinigyEnabled) { registry.Schedule(() => CheckBalances().Wait()).ToRunNow().AndEvery(1).Hours().At(0); } if (bagManagementEnabled) { registry.Schedule(() => CheckForBags().Wait()).ToRunEvery(6).Hours(); } if (coinigyEnabled) { _bus.SendAsync(new GetCoinigyAccountCommand()); } JobManager.Initialize(registry); }
private async void BotOnMessageReceivedAsync(object sender, MessageEventArgs e) { var message = e.Message; await _bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); if (await CheckStates(message)) { return; } if (message.Type != MessageType.TextMessage) { return; } try { await CheckMessage(message.Text); } catch (Exception ex) { _log.LogError($"Woops. {ex}"); var sb = new StringBuffer(); sb.Append(StringContants.CouldNotProcessCommand); await _bus.SendAsync(new SendMessageCommand(sb)); } }
public async Task Start() { // Needs to be called here as if we use DI, the config has not been binded yet _bot.StartBot(_telegramConfig); var registry = new Registry(); if (_bittrexConfig.Enabled || _poloniexConfig.Enabled) { SendStartupMessage().Wait(); registry.Schedule(() => GetNewOrders().Wait()) .ToRunNow() .AndEvery(1) .Minutes(); } if (_bittrexConfig.Enabled) { if (!string.IsNullOrEmpty(_bittrexConfig.DailyNotifications)) { var dailyBalance = _bittrexConfig.DailyNotifications.Split(':'); int.TryParse(dailyBalance[0], out int hour); int.TryParse(dailyBalance[1], out int min); registry.Schedule(() => DailyBalanceCheck(Constants.Bittrex).Wait()).ToRunEvery(1).Days().At(hour, min); } } if (_poloniexConfig.Enabled) { if (!string.IsNullOrEmpty(_poloniexConfig.DailyNotifications)) { var dailyBalance = _poloniexConfig.DailyNotifications.Split(':'); int.TryParse(dailyBalance[0], out int hour); int.TryParse(dailyBalance[1], out int min); registry.Schedule(() => DailyBalanceCheck(Constants.Poloniex).Wait()).ToRunEvery(1).Days().At(hour, min); } } if (_bittrexConfig.Enabled || _poloniexConfig.Enabled || _coinigyConfig.Enabled) { registry.Schedule(() => CheckBalances().Wait()).ToRunNow().AndEvery(1).Hours().At(0); registry.Schedule(() => CheckDepositAndWithdrawals().Wait()).ToRunEvery(2).Minutes(); } if (_bagConfig.Enabled || _lowBtcConfig.Enabled || _dustConfig.Enabled) { registry.Schedule(() => CheckForBags().Wait()).ToRunEvery(8).Hours(); registry.Schedule(() => CheckForBags().Wait()).ToRunOnceIn(5).Minutes(); } if (_coinigyConfig.Enabled) { await _bus.SendAsync(new GetCoinigyAccountCommand()); } JobManager.Initialize(registry); }
public async Task Handle(NewTradesCheckEvent @event) { var lastChecked = await _bus.QueryAsync(new LastCheckedQuery(Constants.Bittrex)); var orderHistory = await _bittrexService.GetOrderHistory(lastChecked.LastChecked); var newTradesResponse = await _bus.QueryAsync(new FindNewTradeQuery(orderHistory)); await _bus.SendAsync(new AddLastCheckedCommand(Constants.Bittrex)); if (@event.BittrexTradeNotifcations) { var i = 0; foreach (var newTrade in newTradesResponse.NewTrades) { if (@event.IsStartup && i > 4) { break; } await _bus.SendAsync(new TradeNotificationCommand(newTrade)); i++; } } }
public async Task Handle(NewTradesCheckEvent @event) { try { var lastChecked = await _bus.QueryAsync(new LastCheckedQuery(Constants.Poloniex)); var orderHistory = await _poloService.GetOrderHistory(lastChecked.LastChecked); var newTradesResponse = await _bus.QueryAsync(new FindNewTradeQuery(orderHistory)); await _bus.SendAsync(new AddLastCheckedCommand(Constants.Poloniex)); if (@event.PoloniexTradeNotification) { var i = 0; foreach (var newTrade in newTradesResponse.NewTrades) { if (@event.IsStartup && i > 4) { break; } await _bus.SendAsync(new TradeNotificationCommand(newTrade)); i++; } } } catch (Exception ex) { _log.LogError("Error in getting new orders from poloniex\n" + ex.Message); throw; } }
public async Task Handle(BalanceCheckEvent @event) { if (@event.Exchange == null && [email protected]) { await _coinigyBalanceService.GetAllBalances(); await _coinigyBalanceService.GetBalance(); } if (@event.UserRequested || _config.SendHourlyUpdates && @event.Exchange == Constants.CoinigyAccountBalance) { if (@event.CoinigyAccountId.HasValue) { var accountInfo = await _coinigyBalanceService.GetAccountBalance(@event.CoinigyAccountId.Value); await _bus.SendAsync(new SendBalanceInfoCommand(accountInfo)); } else { await _bus.SendAsync(new SendHelpMessageCommand()); } } if (@event.Exchange == Constants.TotalCoinigyBalance && (@event.UserRequested || _config.SendHourlyUpdates)) { await _coinigyBalanceService.GetAllBalances(); var balanceInformation = await _coinigyBalanceService.GetBalance(); await _bus.SendAsync(new SendBalanceInfoCommand(balanceInformation)); } }
private async void BotOnMessageReceivedAsync(object sender, MessageEventArgs e) { var message = e.Message; await _bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); if (await CheckStates(message)) { return; } if (message.Type != MessageType.TextMessage) { return; } try { await CheckMessage(message.Text); } catch (Exception ex) { _log.LogError($"Woops. {ex}"); await _bus.SendAsync(new SendMessageCommand("Could not process your command. Check your logs")); } }
public async Task BittrexTradeImport() { BittrexFileUploadState.Waiting = true; var mess = new StringBuffer(); mess.Append(StringContants.BittrexFileUpload); await _bus.SendAsync(new SendMessageCommand(mess)); }
public async Task Handle(SendBalanceInfoCommand requestedCommand) { var sb = new StringBuffer(); var accountName = requestedCommand.BalanceInformation.AccountName; var current = requestedCommand.BalanceInformation.CurrentBalance; var lastBalance = requestedCommand.BalanceInformation.PreviousBalance; var walletBalances = requestedCommand.BalanceInformation.WalletBalances; var currentReporting = Helpers.Helpers.FormatCurrencyAmount(current.ReportingAmount, current.ReportingCurrency); var previousReporting = Helpers.Helpers.FormatCurrencyAmount(lastBalance.ReportingAmount, lastBalance.ReportingCurrency); var timeFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Time:", $" {DateTime.Now:g}", StringContants.StrongOpen, StringContants.StrongClose); var currentFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Current:", $" {current.Balance:##0.#####} {_generalConfig.TradingCurrency} ({currentReporting})", StringContants.StrongOpen, StringContants.StrongClose); var previousFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Previous:", $" {lastBalance.Balance:##0.#####} {_generalConfig.TradingCurrency} ({previousReporting})", StringContants.StrongOpen, StringContants.StrongClose); sb.Append(string.Format("{1}24 Hour Summary{2} for {1}{0}{2}\n\n", accountName, StringContants.StrongOpen, StringContants.StrongClose)); sb.Append(timeFormat); sb.Append(currentFormat); sb.Append(previousFormat); // Only calculate difference if current/last reporting currencies are the same if (current.ReportingCurrency == lastBalance.ReportingCurrency) { var differenceReporting = Helpers.Helpers.FormatCurrencyAmount(current.ReportingAmount - lastBalance.ReportingAmount, current.ReportingCurrency); var differenceFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Difference:", $"{(current.Balance - lastBalance.Balance):##0.#####} {_generalConfig.TradingCurrency} ({differenceReporting})", StringContants.StrongOpen, StringContants.StrongClose); sb.Append(differenceFormat); } if (lastBalance.Balance == 0 || lastBalance.ReportingAmount == 0 || lastBalance.ReportingCurrency != _generalConfig.ReportingCurrency) { await No24HourOfDataNotify(); } else { var percentage = Math.Round((current.Balance - lastBalance.Balance) / lastBalance.Balance * 100, 2); var reportingPercentage = Math.Round( (current.ReportingAmount - lastBalance.ReportingAmount) / lastBalance.ReportingAmount * 100, 2); var percentageFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Change:", $" {percentage}% {_generalConfig.TradingCurrency} ({reportingPercentage}% {_generalConfig.ReportingCurrency})", StringContants.StrongOpen, StringContants.StrongClose); sb.Append(percentageFormat); } if (walletBalances != null) { sb.Append($"\n{StringContants.StrongOpen}Wallet information{StringContants.StrongClose} (with % change since last bought)\n\n"); foreach (var walletBalance in walletBalances) { if (walletBalance.BtcAmount >= _generalConfig.IgnoreDustInTradingCurrency) { sb.Append(string.Format("{3}{0,-10}{4} {1,-15} {2,10}", walletBalance.Currency, $"{walletBalance.BtcAmount:##0.0###} {_generalConfig.TradingCurrency}", $"{walletBalance.PercentageChange}%\n", StringContants.StrongOpen, StringContants.StrongClose)); } } } await _bus.SendAsync(new SendMessageCommand(sb)); }
public async Task RequestedPairProfit() { var mess = new StringBuffer(); mess.Append(StringContants.WhatPairProfits); await _bus.SendAsync(new SendMessageCommand(mess)); PairProfitState.WaitingForCurrency = true; }
public async Task Handle(DepositAndWithdrawalEvent @event) { if (_config.DepositNotification.HasValue && _config.DepositNotification.Value) { var deposits = await _bittrexService.GetNewDeposits(); var i = 0; foreach (var deposit in deposits) { if (i > 30) { var message = new StringBuffer(); message.Append(StringContants.BittrexMoreThan30Deposits); await _bus.SendAsync(new SendMessageCommand(message)); break; } var priceInBtc = await _bittrexService.GetPrice(_generalConfig.TradingCurrency, deposit.Currency); var btcAmount = priceInBtc * Convert.ToDecimal(deposit.Amount); await SendDepositNotification(deposit, btcAmount); i++; } } if (_config.WithdrawalNotification.HasValue && _config.WithdrawalNotification.Value) { var withdrawals = await _bittrexService.GetNewWithdrawals(); var i = 0; foreach (var withdrawal in withdrawals) { if (i > 30) { var message = new StringBuffer(); message.Append(StringContants.BittrexMoreThan30Deposits); await _bus.SendAsync(new SendMessageCommand(message)); break; } var priceInBtc = await _bittrexService.GetPrice(_generalConfig.TradingCurrency, withdrawal.Currency); var btcAmount = priceInBtc * Convert.ToDecimal(withdrawal.Amount); await SendWithdrawalNotification(withdrawal, btcAmount); i++; } } }
private async Task SendBagNotification(WalletBalance walletBalance, Trade lastTradeForPair, decimal currentPrice, decimal percentageDrop) { var message = $"<strong>{Constants.Bittrex}</strong>: {DateTime.Now:g}\n" + $"<strong>Bag detected for {walletBalance.Currency}</strong>\n" + $"Bought price: {lastTradeForPair.Limit:#0.#############}\n" + $"Current price: {currentPrice:#0.#############}\n" + $"Percentage: {percentageDrop}%\n" + $"Bought on: {lastTradeForPair.TimeStamp:g}\n" + $"Value: {walletBalance.Balance * currentPrice:#0.#####} BTC"; await _bus.SendAsync(new SendMessageCommand(message)); }
public async Task Handle(SendBalanceInfoCommand requestedCommand) { var sb = new StringBuffer(); var accountName = requestedCommand.BalanceInformation.AccountName; var current = requestedCommand.BalanceInformation.CurrentBalance; var lastBalance = requestedCommand.BalanceInformation.PreviousBalance; var walletBalances = requestedCommand.BalanceInformation.WalletBalances; var timeFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Time:", $" {DateTime.Now:g}", StringContants.StrongOpen, StringContants.StrongClose); var currentFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Current:", $" {current.Balance:##0.#####} {_generalConfig.TradingCurrency} (${current.DollarAmount})", StringContants.StrongOpen, StringContants.StrongClose); var previousFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Previous:", $" {lastBalance.Balance:##0.#####} {_generalConfig.TradingCurrency} (${lastBalance.DollarAmount})", StringContants.StrongOpen, StringContants.StrongClose); var differenceFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Difference:", $"{(current.Balance - lastBalance.Balance):##0.#####} {_generalConfig.TradingCurrency} (${Math.Round(current.DollarAmount - lastBalance.DollarAmount, 2)})", StringContants.StrongOpen, StringContants.StrongClose); sb.Append(string.Format("{1}24 Hour Summary{2} for {1}{0}{2}\n\n", accountName, StringContants.StrongOpen, StringContants.StrongClose)); sb.Append(timeFormat); sb.Append(currentFormat); sb.Append(previousFormat); sb.Append(differenceFormat); try { var percentage = Math.Round((current.Balance - lastBalance.Balance) / lastBalance.Balance * 100, 2); var dollarPercentage = Math.Round( (current.DollarAmount - lastBalance.DollarAmount) / lastBalance.DollarAmount * 100, 2); var percentageFormat = string.Format("{2}{0,-13}{3}{1,-25}\n", "Change:", $" {percentage}% {_generalConfig.TradingCurrency} ({dollarPercentage}% USD)", StringContants.StrongOpen, StringContants.StrongClose); sb.Append(percentageFormat); } catch (Exception) { var message = new StringBuffer(); message.Append(StringContants.No24HourOfData); await _bus.SendAsync(new SendMessageCommand(message)); } if (walletBalances != null) { sb.Append($"\n{StringContants.StrongOpen}Wallet information{StringContants.StrongClose} (with % change since last bought)\n\n"); foreach (var walletBalance in walletBalances) { if (walletBalance.BtcAmount >= _generalConfig.IgnoreDustInTradingCurrency) { sb.Append(string.Format("{3}{0,-10}{4} {1,-15} {2,10}", walletBalance.Currency, $"{walletBalance.BtcAmount:##0.0###} {_generalConfig.TradingCurrency}", $"{walletBalance.PercentageChange}%\n", StringContants.StrongOpen, StringContants.StrongClose)); } } } await _bus.SendAsync(new SendMessageCommand(sb)); }
public async Task Handle(DepositAndWithdrawalEvent @event) { if (_config.DepositNotification) { var deposits = await _poloniexService.GetNewDeposits(); var i = 0; foreach (var deposit in deposits) { if (i > 3) { var message = $"{deposits.Count - i} deposit can be sent but not going to as to avoid spamming"; await _bus.SendAsync(new SendMessageCommand(message)); break; } var priceInBtc = await _priceService.GetPriceInBtc(deposit.Currency); var btcAmount = priceInBtc * Convert.ToDecimal(deposit.Amount); await SendDepositNotification(deposit, btcAmount); i++; } } if (_config.WithdrawalNotification) { var withdrawals = await _poloniexService.GetNewWithdrawals(); var i = 0; foreach (var withdrawal in withdrawals) { if (i > 3) { var message = $"{withdrawals.Count - i} withdrawals can be sent but not going to as to avoid spamming"; await _bus.SendAsync(new SendMessageCommand(message)); break; } var priceInBtc = await _priceService.GetPriceInBtc(withdrawal.Currency); var btcAmount = priceInBtc * Convert.ToDecimal(withdrawal.Amount); await SendWithdrawalNotification(withdrawal, btcAmount); i++; } } }
public async Task Handle(BittrexTradeExportCommand command) { try { var file = await _bot.Bot.GetFileAsync(command.FileId); var trades = TradeConverter.BittrexFileToTrades(file.FileStream); _databaseService.AddTrades(trades, out List <Trade> newTrades); await _bus.SendAsync(new SendMessageCommand($"{newTrades.Count} new bittrex trades added.")); } catch (Exception) { await _bus.SendAsync(new SendMessageCommand("Could not process file.")); } }
public async Task Handle(ExcelExportCommand command) { var tradeExport = _tradeExportService.GetTradeExport(); await _bus.SendAsync(new SendFileCommand("TradeExport.xlsx", tradeExport.OpenRead())); tradeExport.Delete(); }
private async Task <HttpResponseMessage> ProcessResponse(Task <HttpResponseMessage> task, ApiLogEntry apiLogEntry) { var response = task.Result; if (!_helper.ShouldLog) { return(response); } // Update the API log entry with response info apiLogEntry.ResponseStatusCode = (int)response.StatusCode; apiLogEntry.ResponseTimestamp = DateTime.Now; if (response.Content != null) { apiLogEntry.ResponseContentBody = response.Content.ReadAsStringAsync().Result; apiLogEntry.ResponseContentType = response.Content.Headers.ContentType.MediaType; apiLogEntry.ResponseHeaders = SerializeHeaders(response.Content.Headers); } // TODO: Save the API log entry to the database _traceStepper.WriteOperation("Web API response", "response body", apiLogEntry.ResponseContentBody); _traceStepper.WriteOperation("Web API response", "response headers", apiLogEntry.ResponseHeaders); _traceStepper.Dispose(); var traceSteps = _tracer.TraceSteps; _tracer.Clear(); await _bus.SendAsync(new ApiEntryCommand(apiLogEntry, traceSteps)); return(response); }
public async Task Handle(SendHelpMessageCommand command) { var usage = "<strong>Help</strong>\n\n" + "<strong>Common commands</strong>\n" + $"{TelegramCommands.CommonExcel} - an excel export of all trades\n" + $"{TelegramCommands.CommonPairProfit} - profit information for pair\n"; if (_coinigyConfig.Enabled) { usage = usage + "\n<strong>Coinigy commands</strong>\n" + $"{TelegramCommands.CoinigyAccountList} - coinigy accounts and their balance\n" + $"{TelegramCommands.CoinigyTotalBalance} - total balance from all acounts\n"; } if (_bittrexConfig.Enabled) { usage = usage + "\n<strong>Bittrex commands</strong>\n" + $"{TelegramCommands.BittrexTradeExportUpload} - upload bittrex order export\n" + $"{TelegramCommands.BittrexBalanceInfo} - bittrex account summary\n"; } if (_poloniexConfig.Enabled) { usage = usage + "\n<strong>Poloniex commands</strong>\n" + $"{TelegramCommands.PoloniexBalanceInfo} - poloniex account summary\n" + $"{TelegramCommands.PoloniexTradeReset} - reset trades database from poloniex"; } _log.LogInformation("Sending help message"); await _bus.SendAsync(new SendMessageCommand(usage)); }
private async Task SendBagNotification(WalletBalance walletBalance, decimal averagePrice, decimal currentPrice, decimal percentageDrop) { var lastBought = await _databaseService.GetLastBoughtAsync(_generalConfig.TradingCurrency, walletBalance.Currency, Constants.Bittrex); var message = $"<strong>{Constants.Bittrex}</strong>: {DateTime.Now:g}\n" + $"<strong>Bag detected for {walletBalance.Currency}</strong>\n" + $"Average bought price: {averagePrice:#0.#############}\n" + $"Current price: {currentPrice:#0.#############}\n" + $"Percentage: {percentageDrop}%\n" + $"Bought on: {lastBought:g}\n" + $"Value: {walletBalance.Balance * currentPrice:#0.#####} {_generalConfig.TradingCurrency}"; await _bus.SendAsync(new SendMessageCommand(message)); }
private async Task SendBagNotification(WalletBalance walletBalance, decimal averagePrice, decimal currentPrice, decimal percentageDrop) { var lastBought = await _databaseService.GetLastBoughtAsync(_generalConfig.TradingCurrency, walletBalance.Currency, Constants.Binance); var sb = new StringBuffer(); sb.Append($"{StringContants.StrongOpen}{Constants.Binance}{StringContants.StrongClose}: {DateTime.Now:g}\n"); sb.Append($"{StringContants.StrongOpen}Bag detected for {walletBalance.Currency}{StringContants.StrongClose}\n"); sb.Append($"Average bought price: {averagePrice:#0.#############}\n"); sb.Append($"Current price: {currentPrice:#0.#############}\n"); sb.Append($"Percentage: {percentageDrop}%\n"); sb.Append($"Bought on: {lastBought:g}\n"); sb.Append($"Value: {walletBalance.Balance * currentPrice:#0.#####} {_generalConfig.TradingCurrency}"); await _bus.SendAsync(new SendMessageCommand(sb)); }
protected virtual async Task SendCommandAsync <TCommand>(TCommand command, Action action = null) where TCommand : CommandBase { CommandValidator.Validate(command); action?.Invoke(); await Bus.SendAsync(command); }
public async Task Handle(SendCoinigyAccountInfoCommand command) { var accountList = await _coinigyBalanceService.GetAccounts(); var message = accountList.Aggregate($"{DateTime.Now:g}\n" + "Connected accounts on Coinigy are: \n", (current, acc) => current + "/acc_" + acc.Key + " - " + acc.Value.Name + "\n"); _log.LogInformation("Sending the account list"); await _bus.SendAsync(new SendMessageCommand(message)); }
/// <inheritdoc /> public override async Task HandleAsync(DeactiveCustomerIntegrationEvent @event) { var command = new DeactiveCustomerCommand { CustomerId = @event.CustomerId }; await _bus.SendAsync(command); }
public override async Task HandleAsync(CancelOrderIntegrationEvent @event) { var command = new CancelOrderCommand { OrderId = @event.OrderId }; await _bus.SendAsync(command); }
public async Task Handle(CoinigyPnLForAccountCommand command) { var accountBalance24HoursAgo = await _coinigyBalanceService.GetAccountBalance(command.AccountId); await _bus.SendAsync(new SendBalanceInfoCommand(accountBalance24HoursAgo.CurrentBalance, accountBalance24HoursAgo.PreviousBalance, accountBalance24HoursAgo.WalletBalances, accountBalance24HoursAgo.AccountName)); }
public override async Task HandleAsync(PlaceOrderIntegrationEvent @event) { var command = new PlaceOrderCommand { CustomerId = @event.CustomerId, Price = @event.Price }; await _bus.SendAsync(command); }
// Need to do this or we end may end up with 500 + messages on first run private async Task GetNewOrdersOnStartup(bool bittrexTradeNotifcations, bool poloniexTradeNotifcation) { if (bittrexTradeNotifcations && poloniexTradeNotifcation) { const string message = "<strong>Checking new orders on startup. Will only send top 5</strong>\n"; await _bus.SendAsync(new SendMessageCommand(message)); } await _bus.PublishAsync(new NewTradesCheckEvent(true, bittrexTradeNotifcations, poloniexTradeNotifcation)); }
public async Task Handle(SendBalanceInfoCommand requestedCommand) { var accountName = requestedCommand.AccountName; var current = requestedCommand.Current; var lastBalance = requestedCommand.LastBalance; var walletBalances = requestedCommand.WalletBalances; var timeFormat = string.Format("<strong>{0,-13}</strong>{1,-25}\n", "Time:", $" {DateTime.Now:g}"); var currentFormat = string.Format("<strong>{0,-13}</strong>{1,-25}\n", "Current:", $" {current.Balance:##0.####} BTC (${current.DollarAmount})"); var previousFormat = string.Format("<strong>{0,-13}</strong>{1,-25}\n", "Previous:", $" {lastBalance.Balance:##0.####} BTC (${lastBalance.DollarAmount})"); var differenceFormat = string.Format("<strong>{0,-13}</strong>{1,-25}\n", "Difference:", $"{(current.Balance - lastBalance.Balance):##0.####} BTC (${Math.Round(current.DollarAmount - lastBalance.DollarAmount, 2)})"); var message = $"<strong>24 Hour Summary</strong> for <strong>{accountName}</strong>\n\n" + timeFormat + currentFormat + previousFormat + differenceFormat; try { var percentage = Math.Round((current.Balance - lastBalance.Balance) / lastBalance.Balance * 100, 2); var dollarPercentage = Math.Round( (current.DollarAmount - lastBalance.DollarAmount) / lastBalance.DollarAmount * 100, 2); var percentageFormat = string.Format("<strong>{0,-13}</strong>{1,-25}\n", "Change:", $" {percentage}% BTC ({dollarPercentage}% USD)"); message = message + percentageFormat; } catch (Exception ex) { await _bus.SendAsync(new SendMessageCommand($"Could not calculate percentages. Probably because we don't have 24 hours of data yet")); } if (walletBalances != null) { message = message + "\n<strong>Wallet information</strong> (with % change since last bought)\n\n"; foreach (var walletBalance in walletBalances) { message = message + string.Format("<strong>{0, -10}</strong> {1,-15} {2,10}\n", walletBalance.Currency, $"{walletBalance.BtcAmount:##0.0000} BTC", $"{walletBalance.PercentageChange}%"); } } await _bus.SendAsync(new SendMessageCommand(message)); }
public async Task Handle(ResetPoloniexTrades command) { var trades = await _poloniexService.GetOrderHistory(Constants.DateTimeUnixEpochStart); await _databaseService.DeleteAllTrades(Constants.Poloniex); await _databaseService.AddTrades(trades); await _bus.SendAsync(new SendMessageCommand($"I've reset your trades with {trades.Count} trades from polo.")); }
public async Task Handle(PairProfitCommand command) { try { var pairsArray = command.Pair.Split("-"); var profitAndLoss = await _profitAndLossService.GetPnLInfo(pairsArray[0], pairsArray[1]); var message = $"{DateTime.Now:g}\n" + $"Profit information for <strong>{command.Pair}</strong>\n" + $"<strong>Average buy price</strong>: {profitAndLoss.AverageBuyPrice:#0.###########}\n" + $"<strong>Total PnL</strong>: {profitAndLoss.Profit} BTC\n"; await _bus.SendAsync(new SendMessageCommand(message)); } catch (Exception) { await _bus.SendAsync(new SendMessageCommand("Could not work out what the pair you typed was")); } }