docker files fixes from liaqat

This commit is contained in:
alirehmani
2024-05-03 16:39:25 +05:00
commit 464a8730e8
587 changed files with 44288 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
using Managing.Application.Abstractions.Services;
using Managing.Domain.Accounts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers
{
[Authorize]
public class AccountController : BaseController
{
private readonly IAccountService _AccountService;
public AccountController(
IAccountService AccountService,
IUserService userService)
: base(userService)
{
_AccountService = AccountService;
}
[HttpPost]
public async Task<ActionResult<Account>> PostAccount(Account Account)
{
var user = await GetUser();
return Ok(await _AccountService.CreateAccount(user, Account));
}
[HttpGet]
[Route("accounts")]
public async Task<ActionResult<IEnumerable<Account>>> GetAccounts()
{
var user = await GetUser();
return Ok(_AccountService.GetAccountsByUser(user, true));
}
[HttpGet]
[Route("balances")]
public async Task<ActionResult<IEnumerable<Account>>> GetAccountsBalances()
{
var user = await GetUser();
return Ok(_AccountService.GetAccountsBalancesByUser(user));
}
[HttpGet]
public async Task<ActionResult<Account>> GetAccount(string name)
{
var user = await GetUser();
return Ok(await _AccountService.GetAccountByUser(user, name, true, true));
}
[HttpDelete]
public ActionResult DeleteAccount(string name)
{
var user = GetUser().Result;
return Ok(_AccountService.DeleteAccount(user, name));
}
}
}

View File

@@ -0,0 +1,133 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.Hubs;
using Managing.Domain.Backtests;
using Managing.Domain.MoneyManagements;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
[ApiController]
[Authorize]
[Route("[controller]")]
[Produces("application/json")]
public class BacktestController : ControllerBase
{
private readonly IHubContext<BotHub> _hubContext;
private readonly IBacktester _backtester;
private readonly IScenarioService _scenarioService;
private readonly IAccountService _accountService;
private readonly IMoneyManagementService _moneyManagementService;
public BacktestController(
IHubContext<BotHub> hubContext,
IBacktester backtester,
IScenarioService scenarioService,
IAccountService accountService,
IMoneyManagementService moneyManagementService)
{
_hubContext = hubContext;
_backtester = backtester;
_scenarioService = scenarioService;
_accountService = accountService;
_moneyManagementService = moneyManagementService;
}
[HttpGet]
public ActionResult<IEnumerable<Backtest>> Backtests()
{
return Ok(_backtester.GetBacktests());
}
[HttpDelete]
public ActionResult DeleteBacktest(string id)
{
return Ok(_backtester.DeleteBacktest(id));
}
[HttpDelete]
[Route("deleteAll")]
public ActionResult DeleteBacktests()
{
return Ok(_backtester.DeleteBacktests());
}
[HttpPost]
[Route("Run")]
public async Task<ActionResult<Backtest>> Run(string accountName,
BotType botType,
Ticker ticker,
string scenarioName,
Timeframe timeframe,
bool watchOnly,
int days,
decimal balance,
string moneyManagementName,
MoneyManagement? moneyManagement = null,
bool save = false)
{
if (string.IsNullOrEmpty(accountName))
{
throw new ArgumentException($"'{nameof(accountName)}' cannot be null or empty.", nameof(accountName));
}
if (string.IsNullOrEmpty(scenarioName))
{
throw new ArgumentException($"'{nameof(scenarioName)}' cannot be null or empty.", nameof(scenarioName));
}
if (string.IsNullOrEmpty(moneyManagementName) && moneyManagement == null)
{
throw new ArgumentException($"'{nameof(moneyManagementName)}' and '{nameof(moneyManagement)}' cannot be null or empty.", nameof(moneyManagementName));
}
if (days > 0)
{
days = days * -1;
}
Backtest backtestResult = null;
var scenario = _scenarioService.GetScenario(scenarioName);
var account = await _accountService.GetAccount(accountName, true, false);
if (!string.IsNullOrEmpty(moneyManagementName) && moneyManagement is null)
{
moneyManagement = await _moneyManagementService.GetMoneyMangement(moneyManagementName);
}
else
{
moneyManagement.FormatPercentage();
}
if (scenario == null)
return BadRequest("No scenario found");
switch (botType)
{
case BotType.SimpleBot:
break;
case BotType.ScalpingBot:
backtestResult = _backtester.RunScalpingBotBacktest(account, moneyManagement, ticker, scenario,
timeframe, Convert.ToDouble(days), balance, watchOnly, save);
break;
case BotType.FlippingBot:
backtestResult = _backtester.RunFlippingBotBacktest(account, moneyManagement, ticker, scenario,
timeframe, Convert.ToDouble(days), balance, watchOnly, save);
break;
}
await NotifyBacktesingSubscriberAsync(backtestResult);
return Ok(backtestResult);
}
private async Task NotifyBacktesingSubscriberAsync(Backtest backtesting)
{
if(backtesting != null){
await _hubContext.Clients.All.SendAsync("BacktestsSubscription", backtesting);
}
}
}

View File

@@ -0,0 +1,35 @@
using Managing.Application.Abstractions.Services;
using Managing.Domain.Users;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Managing.Api.Controllers;
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public abstract class BaseController : ControllerBase
{
private readonly IUserService _userService;
public BaseController(IUserService userService)
{
_userService = userService;
}
protected async Task<User> GetUser()
{
var identity = HttpContext?.User.Identity as ClaimsIdentity;
if (identity != null)
{
var address = identity.Claims.FirstOrDefault(c => c.Type == "address").Value;
var user = await _userService.GetUserByAddressAsync(address);
if (user != null)
return user;
throw new Exception("User not found for this token");
}
throw new Exception("Not identity assigned to this token");
}
}

View File

@@ -0,0 +1,168 @@
using Managing.Api.Models.Requests;
using Managing.Api.Models.Responses;
using Managing.Application.Abstractions;
using Managing.Application.Hubs;
using Managing.Application.ManageBot.Commands;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
[ApiController]
[Authorize]
[Route("[controller]")]
[Produces("application/json")]
public class BotController : ControllerBase
{
private readonly IMediator _mediator;
private readonly ILogger<BotController> _logger;
private readonly IHubContext<BotHub> _hubContext;
private readonly IBacktester _backtester;
public BotController(ILogger<BotController> logger, IMediator mediator, IHubContext<BotHub> hubContext, IBacktester backtester)
{
_logger = logger;
_mediator = mediator;
_hubContext = hubContext;
_backtester = backtester;
}
[HttpPost]
[Route("Start")]
public async Task<ActionResult<string>> Start(StartBotRequest request)
{
var result = await _mediator.Send(new StartBotCommand(request.BotType, request.BotName, request.Ticker,
request.Scenario, request.Timeframe, request.AccountName, request.MoneyManagementName, request.IsForWatchOnly));
await NotifyBotSubscriberAsync();
return Ok(result);
}
[HttpGet]
[Route("Stop")]
public async Task<ActionResult<string>> Stop(BotType botType, string botName)
{
var result = await _mediator.Send(new StopBotCommand(botType, botName));
_logger.LogInformation($"{botType} type called {botName} is now {result}");
await NotifyBotSubscriberAsync();
return Ok(result);
}
[HttpDelete]
[Route("Delete")]
public async Task<ActionResult<bool>> Delete(string botName)
{
var result = await _mediator.Send(new DeleteBotCommand(botName));
_logger.LogInformation($"{botName} is now deleted");
await NotifyBotSubscriberAsync();
return Ok(result);
}
[HttpGet]
[Route("StopAll")]
public async Task<string> StopAll()
{
var bots = await GetBotList();
var result = "";
foreach (var bot in bots)
{
result += $"{bot.Name} : ";
result = await _mediator.Send(new StopBotCommand(bot.BotType, bot.Name));
result += $" |";
}
await NotifyBotSubscriberAsync();
return result;
}
[HttpGet]
[Route("Restart")]
public async Task<ActionResult<string>> Restart(BotType botType, string botName)
{
var result = await _mediator.Send(new RestartBotCommand(botType, botName));
_logger.LogInformation($"{botType} type called {botName} is now {result}");
await NotifyBotSubscriberAsync();
return Ok(result);
}
[HttpGet]
[Route("RestartAll")]
public async Task<string> RestartAll()
{
var bots = await GetBotList();
var result = "";
foreach (var bot in bots)
{
result += $"{bot.Name} : ";
result = await _mediator.Send(new RestartBotCommand(bot.BotType, bot.Name));
result += $" |";
}
await NotifyBotSubscriberAsync();
return result;
}
[HttpGet]
[Route("ToggleIsForWatching")]
public async Task<ActionResult<string>> ToggleIsForWatching(string botName)
{
var result = await _mediator.Send(new ToggleIsForWatchingCommand(botName));
_logger.LogInformation($"{botName} bot is now {result}");
await NotifyBotSubscriberAsync();
return Ok(result);
}
[HttpGet]
public async Task<List<TradingBot>> GetActiveBots()
{
return await GetBotList();
}
private async Task<List<TradingBot>> GetBotList()
{
var result = await _mediator.Send(new GetActiveBotsCommand());
var list = new List<TradingBot>();
foreach (var item in result)
{
list.Add(new TradingBot
{
Status = item.GetStatus(),
Name = item.GetName(),
Candles = item.Candles.ToList(),
Positions = item.Positions,
Signals = item.Signals.ToList(),
WinRate = item.GetWinRate(),
ProfitAndLoss = item.GetProfitAndLoss(),
Timeframe = item.Timeframe,
Ticker = item.Ticker,
AccountName = item.AccountName,
Scenario = item.Scenario,
IsForWatchingOnly = item.IsForWatchingOnly,
BotType = item.BotType,
MoneyManagement = item.MoneyManagement
});
}
return list;
}
private async Task NotifyBotSubscriberAsync()
{
var botsList = await GetBotList();
await _hubContext.Clients.All.SendAsync("BotsSubscription", botsList);
}
}

View File

@@ -0,0 +1,73 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.Hubs;
using Managing.Application.Workers.Abstractions;
using Managing.Domain.Candles;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
[ApiController]
[Authorize]
[Route("[controller]")]
public class DataController : ControllerBase
{
private readonly IExchangeService _exchangeService;
private readonly IAccountService _accountService;
private readonly ICacheService _cacheService;
private readonly IStatisticService _statisticService;
private readonly IHubContext<CandleHub> _hubContext;
public DataController(
IExchangeService exchangeService,
IAccountService accountService,
ICacheService cacheService,
IStatisticService statisticService,
IHubContext<CandleHub> hubContext)
{
_exchangeService = exchangeService;
_accountService = accountService;
_cacheService = cacheService;
_statisticService = statisticService;
_hubContext = hubContext;
}
[HttpPost("GetTickers")]
public async Task<ActionResult<Ticker[]>> GetTickers(string accountName, Timeframe timeframe)
{
var account = await _accountService.GetAccount(accountName, true, false);
var cacheKey = string.Concat(accountName, timeframe.ToString());
var tickers = _cacheService.GetOrSave(cacheKey, () =>
{
return _exchangeService.GetTickers(account, timeframe).Result;
}, TimeSpan.FromHours(2));
return Ok(tickers);
}
[HttpGet("Spotlight")]
public ActionResult<SpotlightOverview> GetSpotlight()
{
var overview = _cacheService.GetOrSave(nameof(SpotlightOverview), () =>
{
return _statisticService.GetLastSpotlight(DateTime.Now.AddHours(-3));
}, TimeSpan.FromMinutes(2));
if (overview?.Spotlights.Count < overview?.ScenarioCount)
{
overview = _statisticService.GetLastSpotlight(DateTime.Now.AddHours(-3));
}
return Ok(overview);
}
[HttpGet("GetCandles")]
public async Task<ActionResult<List<Candle>>> GetCandles(TradingExchanges exchange, Ticker ticker, DateTime startDate, Timeframe timeframe)
{
return Ok(await _exchangeService.GetCandlesInflux(exchange, ticker, startDate, timeframe));
}
}

View File

@@ -0,0 +1,44 @@
using Managing.Application.Abstractions;
using Managing.Domain.MoneyManagements;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers;
[ApiController]
[Authorize]
[Route("[controller]")]
[Produces("application/json")]
public class MoneyManagementController : ControllerBase
{
private readonly IMoneyManagementService _moneyManagementService;
public MoneyManagementController(IMoneyManagementService moneyManagementService)
{
_moneyManagementService = moneyManagementService;
}
[HttpPost]
public async Task<ActionResult<MoneyManagement>> PostMoneyManagement(MoneyManagement moneyManagement)
{
return Ok(await _moneyManagementService.CreateOrUpdateMoneyManagement(moneyManagement));
}
[HttpGet]
[Route("moneymanagements")]
public ActionResult<IEnumerable<MoneyManagement>> GetMoneyManagements()
{
return Ok(_moneyManagementService.GetMoneyMangements());
}
[HttpGet]
public ActionResult<MoneyManagement> GetMoneyManagement(string name)
{
return Ok(_moneyManagementService.GetMoneyMangement(name));
}
[HttpDelete]
public ActionResult DeleteMoneyManagement(string name)
{
return Ok(_moneyManagementService.DeleteMoneyManagement(name));
}
}

View File

@@ -0,0 +1,83 @@
using Managing.Application.Abstractions;
using Managing.Domain.Scenarios;
using Managing.Domain.Strategies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
[ApiController]
[Authorize]
[Route("[controller]")]
[Produces("application/json")]
public class ScenarioController : ControllerBase
{
private readonly IScenarioService _scenarioService;
public ScenarioController(IScenarioService scenarioService)
{
_scenarioService = scenarioService;
}
[HttpGet]
public ActionResult<IEnumerable<Scenario>> GetScenarios()
{
return Ok(_scenarioService.GetScenarios());
}
[HttpPost]
public ActionResult<Scenario> CreateScenario(string name, List<string> strategies)
{
return Ok(_scenarioService.CreateScenario(name, strategies));
}
[HttpDelete]
public ActionResult DeleteScenario(string name)
{
return Ok(_scenarioService.DeleteScenario(name));
}
[HttpGet]
[Route("strategy")]
public ActionResult<IEnumerable<Strategy>> GetStrategies()
{
return Ok(_scenarioService.GetStrategies());
}
[HttpPost]
[Route("strategy")]
public ActionResult<Strategy> CreateStrategy(
StrategyType strategyType,
Timeframe timeframe,
string name,
int? period = null,
int? fastPeriods = null,
int? slowPeriods = null,
int? signalPeriods = null,
double? multiplier = null,
int? stochPeriods = null,
int? smoothPeriods = null,
int? cyclePeriods = null)
{
return Ok(_scenarioService.CreateStrategy(
strategyType,
timeframe,
name,
period,
fastPeriods,
slowPeriods,
signalPeriods,
multiplier,
stochPeriods,
smoothPeriods,
cyclePeriods));
}
[HttpDelete]
[Route("strategy")]
public ActionResult DeleteStrategy(string name)
{
return Ok(_scenarioService.DeleteStrategy(name));
}
}

View File

@@ -0,0 +1,30 @@
using Managing.Application.Abstractions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers;
[ApiController]
[Authorize]
[Route("[controller]")]
[Produces("application/json")]
public class SettingsController : ControllerBase
{
private readonly ISettingsService _settingsService;
public SettingsController(ISettingsService settingsService)
{
_settingsService = settingsService;
}
[HttpPost]
public ActionResult SetupSettings()
{
return Ok(_settingsService.SetupSettings());
}
[HttpDelete]
public async Task<ActionResult<bool>> ResetSettings()
{
return Ok(await _settingsService.ResetSettings());
}
}

View File

@@ -0,0 +1,107 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.Trading.Commands;
using Managing.Domain.MoneyManagements;
using Managing.Domain.Trades;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
[ApiController]
[Authorize]
[Route("[controller]")]
public class TradingController : ControllerBase
{
private readonly ICommandHandler<OpenPositionRequest, Position> _openTradeCommandHandler;
private readonly ICommandHandler<ClosePositionCommand, Position> _closeTradeCommandHandler;
private readonly ITradingService _tradingService;
private readonly IMoneyManagementService _moneyManagementService;
private readonly IMediator _mediator;
private readonly ILogger<TradingController> _logger;
public TradingController(
ILogger<TradingController> logger,
ICommandHandler<OpenPositionRequest, Position> openTradeCommandHandler,
ICommandHandler<ClosePositionCommand, Position> closeTradeCommandHandler,
ITradingService tradingService,
IMediator mediator)
{
_logger = logger;
_openTradeCommandHandler = openTradeCommandHandler;
_closeTradeCommandHandler = closeTradeCommandHandler;
_tradingService = tradingService;
_mediator = mediator;
}
[HttpGet("GetPositions")]
public async Task<ActionResult<List<Position>>> GetPositions(PositionInitiator positionInitiator)
{
var result = await _mediator.Send(new GetPositionsCommand(positionInitiator));
return Ok(result);
}
[HttpGet("GetTrade")]
public async Task<ActionResult<Trade>> GetTrade(string accountName, Ticker ticker, string exchangeOrderId)
{
var result = await _mediator.Send(new GetTradeCommand(accountName, exchangeOrderId, ticker));
return Ok(result);
}
[HttpGet("GetTrades")]
public async Task<ActionResult<Trade>> GetTrades(string accountName, Ticker ticker, string exchangeOrderId)
{
var result = await _mediator.Send(new GetTradesCommand(ticker, accountName));
return Ok(result);
}
[HttpGet("ClosePosition")]
public async Task<ActionResult<Position>> ClosePosition(string identifier)
{
var position = _tradingService.GetPositionByIdentifier(identifier);
var result = await _closeTradeCommandHandler.Handle(new ClosePositionCommand(position));
return Ok(result);
}
[HttpGet("OpenPosition")]
public async Task<ActionResult<Position>> Trade(
string accountName,
string moneyManagementName,
TradeDirection direction,
Ticker ticker,
RiskLevel riskLevel,
bool isForPaperTrading,
MoneyManagement? moneyManagement = null,
decimal? openPrice = null)
{
if (string.IsNullOrEmpty(accountName))
{
throw new ArgumentException($"'{nameof(accountName)}' cannot be null or empty.", nameof(accountName));
}
if (string.IsNullOrEmpty(moneyManagementName) && moneyManagement == null)
{
throw new ArgumentException($"'{nameof(moneyManagementName)}' cannot be null or empty.", nameof(moneyManagementName));
}
if (moneyManagement == null)
{
moneyManagement = await _moneyManagementService.GetMoneyMangement(moneyManagementName);
}
var command = new OpenPositionRequest(
accountName,
moneyManagement,
direction,
ticker,
PositionInitiator.User,
DateTime.UtcNow,
isForPaperTrading: isForPaperTrading,
price: openPrice);
var result = await _openTradeCommandHandler.Handle(command);
return Ok(result);
}
}

View File

@@ -0,0 +1,39 @@
using Managing.Api.Authorization;
using Managing.Api.Models.Requests;
using Managing.Application.Abstractions.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers;
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class UserController : ControllerBase
{
private IConfiguration _config;
private readonly IUserService _userService;
private readonly IJwtUtils _jwtUtils;
public UserController(IConfiguration config, IUserService userService, IJwtUtils jwtUtils)
{
_config = config;
_userService = userService;
_jwtUtils = jwtUtils;
}
[AllowAnonymous]
[HttpPost]
public async Task<ActionResult<string>> CreateToken([FromBody] LoginRequest login)
{
var user = await _userService.Authenticate(login.Name, login.Address, login.Message, login.Signature);
if (user != null)
{
var tokenString = _jwtUtils.GenerateJwtToken(user, login.Address);
return Ok(tokenString);
}
return Unauthorized();
}
}

View File

@@ -0,0 +1,45 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Domain.Workflows;
using Managing.Domain.Workflows.Synthetics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers
{
[Authorize]
public class WorkflowController : BaseController
{
private readonly IWorkflowService _workflowService;
public WorkflowController(IWorkflowService WorkflowService, IUserService userService) : base(userService)
{
_workflowService = WorkflowService;
}
[HttpPost]
public async Task<ActionResult<Workflow>> PostWorkflow([ModelBinder]SyntheticWorkflow workflowRequest)
{
return Ok(await _workflowService.InsertOrUpdateWorkflow(workflowRequest));
}
[HttpGet]
public ActionResult<IEnumerable<SyntheticWorkflow>> GetWorkflows()
{
return Ok(_workflowService.GetWorkflows());
}
[HttpGet]
[Route("flows")]
public async Task<ActionResult<IEnumerable<IFlow>>> GetAvailableFlows()
{
return Ok(await _workflowService.GetAvailableFlows());
}
[HttpDelete]
public ActionResult DeleteWorkflow(string name)
{
return Ok(_workflowService.DeleteWorkflow(name));
}
}
}