Update doc and todo (#4)

* Updade doc

* Updade doc
This commit is contained in:
Oda
2024-07-20 21:33:50 +07:00
committed by GitHub
parent a43e560d3a
commit 743d04e6c5
12 changed files with 483 additions and 71 deletions

View File

@@ -1,6 +1,7 @@
# Introduction
Managing App is a bot management application written using C# and Typescript. First goal was to be able to run an infinite
Managing App is a bot management application written using C# and Typescript. First goal was to be able to run an
infinite
number of Bot without any limitations (will depend on your server capabilities only)
It is designed to support multiples exchanges and be controlled via webUI or Discord.
It contains bot management, backtesting, scenario management and money management..
@@ -10,6 +11,7 @@ It contains bot management, backtesting, scenario management and money managemen
# Roadmap
## v1 - The base
- [x] Bot management
- [x] Backtesting
- [x] MoneyManagement
@@ -21,36 +23,46 @@ It contains bot management, backtesting, scenario management and money managemen
- [x] Workers (prices, backtests, volumes)
## v2 - The custody back
- [x] Web3 Authentification
- [x] Hot-wallets management
- [x] Chainlink and Subgraphs feeds
- [x] [GMX Contracts integration](https://gmx.io/)
- [ ] GMX v2 Contracts integration
### v2.1
- [x] Tools : RektFees, Spotlight
- [ ] Address tracking
- [x] Funding Rates
- [ ] Strategies optimisation
- [ ] Delta neutral positions
- [ ] Address tracking
- [ ] Trading desk
- [ ] Metrics (backtests, portofolio)
- [ ] Enhance performances
- [ ] Dockerize everything
### v2.2
- [ ] Hedging Bot with Options [HegicOption](https://www.hegic.co/)
- [ ] Market making
## v3 - The bitcoin protocol
- [ ] Integrate [LNMarkets](https://lnmarkets.com/)
## v4 - The omnipotence
- [ ] Connect to [Blockstream Satellite](https://blockstream.com/satellite/)
# Stack
## Architecture
![alt text](assets/img/Architecture.png)
## Front-end
- [Vite.JS](https://vitejs.dev/)
- [Tailwindcss](https://tailwindcss.com/)
- [Daisy UI](https://daisyui.com/)
@@ -63,6 +75,7 @@ It contains bot management, backtesting, scenario management and money managemen
- [Connectkit](https://github.com/family/connectkit)
## Back-end
- .NET 7
- [SignalR](https://dotnet.microsoft.com/en-us/apps/aspnet/signalr)
- [Discord.Net](https://github.com/discord-net/Discord.Net)
@@ -74,36 +87,42 @@ It contains bot management, backtesting, scenario management and money managemen
---
# Features
## Money Management
- Create a defined money management for a given timeframe (StopLoss, TakeProfit, Amount to risk)
- Edit a money management configuration
- Delete a configuration
## Strategies
- Build a strategy
- Delete strategy
Strategies availables :
| Strategy | Description | Recommanded values |
| ----------- | ----------- | ----------- |
| RsiDivergence | Trigger a signal when a divergence occurs on the period | Period : 4 for 6|
| RsiDivergenceConfirm | First, detect a divergence and trigger a signal when the divergence is confirmed. The confirmation happen for a LONG when the price close above the candle in divergence. The loopback period is based on the period parameter. | Period : 4 for 6|
| MACDCross | Trigger a signal when EMAs cross | FastPeriod : 12, SlowPeriods : 26, SignalPeriods : 9|
| SuperTrend | Trigger a SHORT signal when previous candle is above the super trend and the last candle close below the super trend | Period : 10, Multiplier : 3 |
| ChandelierExit | Trigger a SHORT signal when previous candle is above the ChandelierExit and the last candle close below the ChandelierExit | Period : 22, Multiplier : 3 |
| EMACross | Trigger a signal when last candle cross the EMA | Period : 200 |
| EMATrend | Return a Trend signal SHORT when last candle is below the EMA and return a Trend LONG signal when StochRSI < 20% | Period : 200 |
| StochRsiTrend | Return a Trend signal SHORT when Stoch RSI > 80% and return a Trend LONG signal when StochRSI < 20% | Period : 22 |
| STC | Return a signal SHORT when previous STC > 75% and current STC <= 75% | Period : 22 |
| Strategy | Description | Recommended values |
|----------------------|------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------|
| ChandelierExit | Triggers a SHORT signal when the previous candle is above the ChandelierExit, and the last candle closes below the ChandelierExit. | Period: 22, Multiplier: 3 |
| EMACross | Triggers a signal when the last candle crosses the EMA. | Period: 200 |
| EMATrend | Returns a Trend signal SHORT when the last candle is below the EMA, and a Trend LONG signal when StochRSI < 20%. | Period: 200 |
| MACDCross | Triggers a signal when EMAs cross. | FastPeriod: 12, SlowPeriods: 26, SignalPeriods: 9 |
| RSIDivergenceConfirm | First, detects a divergence and then triggers a signal when the divergence is confirmed. | Period: 4 for 6 |
| RSIDivergence | Triggers a signal when a divergence occurs on the period. | Period: 4 for 6 |
| STC | Returns a signal SHORT when the previous STC > 75% and the current STC <= 75%. | Period: 22 |
| StochRsiTrend | Returns a Trend signal SHORT when Stoch RSI > 80% and a Trend LONG signal when StochRSI < 20%. | Period: 22 |
| SuperTrend | Triggers a SHORT signal when the previous candle is above the super trend, and the last candle closes below the super trend. | Period: 10, Multiplier: 3 |
| ThreeWhiteSoldiers | Triggers a LONG signal when the Three White Soldiers pattern is identified. | Lookback Period: 3 |
## Scenarios
- Build a scenario with multiple strategies
- Delete a scenario
## Backtests
The backtest system works with multiple required parameters :
- Exchange (Binance, Kraken, FTX)
- Ticker (ADAUSDT, BTCUSDT, etc..)
- Days : Since when did you want to start backtest. Should be a negative value
@@ -123,7 +142,7 @@ The backtest system works with multiple required parameters :
Bot types availables :
| Type | Description |
| ----------- | ----------- |
|-------------|----------------------------------------------------------------------------------------|
| ScalpingBot | This bot will open position and wait before opening a new one |
| FlippingBot | The flipping bot flipping the position only when a strategy trigger an opposite signal |

View File

@@ -1,8 +1,12 @@
# V2
## Done
### Adaptive mode
- [x] Create a risk mode 'Adaptive' to be able to not use save moneymanagement settings
- [x] Adaptive mode will force Bot to determine SL by getting the previous highest price on the period (prevent choppy price on good entry)
- [x] Adaptive mode will force Bot to determine SL by getting the previous highest price on the period (prevent choppy
price on good entry)
- [x] Create account (type, exchange, key, secret)
- [x] Update trading bot to handle one account
- [x] Remove exchange from bot. Exchange will be set on the account
@@ -13,9 +17,12 @@
- [x] Create method in application to get best bid and best ask
- [x] Submit only limit with IOC
- [x] Implement Poly to have a retry policy for limit order ioc execution => Unsure position is open
- [x] For openOrder inject a parameter to select the ioc mode. If risk is adaptive we just place the order a the price without forcing the position opening
- [x] For openOrder inject a parameter to select the ioc mode. If risk is adaptive we just place the order a the price
without forcing the position opening
- [x] Integrate STC signals
### Web3
- [x] Integrate wallet management from backend side
- [x] Integrate wagmi/connectkit
- [x] Sign message with connectkit
@@ -48,11 +55,14 @@
- [x] Display best last backtests ran by backtester workers
- [x] Refactor GetAccounts/GetAccount to handle the user
- [x] AccountType : Binance/EvmTrador/EvmWatch/EvmPersonal
- [x] Make better abstration of the Database projects (influx, mongodb) to Remove the link between Application and Infrastructure
- [x] Make better abstration of the Database projects (influx, mongodb) to Remove the link between Application and
Infrastructure
- [x] Implement strategy pattern for exchange processors
- [x] Use cache for position and signal
- [x] Don't run update Signal and manage position if no new candle
### Workers
- [x] Add Influxdb
- [x] Create workers for scrap data (per ticker, per exchange, per timeframe)
- [x] Use candle from influxdb for backtests and bots
@@ -61,10 +71,12 @@
- [x] Create a worker that run backtest and save it in db
### Front-end
- [x] Return list of balances with tokens/chains data
- [x] On account line click, display tokens by chain available
- [x] Call Available ticker to produce the droplist
- [x] Display multipanes https://github.com/qwpto/lightweight-charts-panels / https://codesandbox.io/s/react-typescript-forked-mxek17?file=/src/App.tsx / https://github.com/Rassibassi/multipane_tradingview
- [x] Display
multipanes https://github.com/qwpto/lightweight-charts-panels / https://codesandbox.io/s/react-typescript-forked-mxek17?file=/src/App.tsx / https://github.com/Rassibassi/multipane_tradingview
- [x] Display last open position with lines (add SL and TP)
- [x] Fix double charts problem (has been fixed by removing strict mode)
- [x] Try to pass the tailwind current theme color to the chart
@@ -76,13 +88,16 @@
- [x] Add input to specify the account balance. If not set, it will use the selected account balance
# The rest
## Part 1 : Adaptive trading
- [x] From backtests list : Determine TP and Stop loss % by getting average profit and average lost for a signal
- [x] Modify bot to use MoneyManagement object instead of using the risk associated to the signal.
- [x] Bot object should return MoneyManagement object
- [ ] Strategy can return a suggested trade that will give the best orders to execute
## Part 2 : Workflows builder
- [x] Create a workflow type that will encapsulate a list of flows
- [x] Each flow will have parameters, inputs and outputs that will be used by the children flows
- [ ] Flow can handle multiple parents
@@ -91,9 +106,11 @@
- [ ] Add flows : ClosePosition, Scenario
## Part 2 : Strategies optimisation
- [ ] Optimize all strategies with more data (funding rate trend, bbwp, etc..)
- [ ] Optimize entry by getting last ask price and place an order limit to match directly with it
- [ ] Add bbwp indicator => PR example : https://github.com/DaveSkender/Stock.Indicators/pull/893/files#diff-df1cd2a99846f7328c9fc3db4d2c164380a0fa943cdcad2ece01b886cac68137
- [ ] Add bbwp indicator => PR
example : https://github.com/DaveSkender/Stock.Indicators/pull/893/files#diff-df1cd2a99846f7328c9fc3db4d2c164380a0fa943cdcad2ece01b886cac68137
- [ ] Create strategies types from signal (a divergence) / trend (stoch long or short) / context (high vol/low vol)
- [ ] Create a trend strategy on fundinrate -> long trend if negativ fr / short trend if positiv fr
- [ ] Add entry/exit price to signal for adaptive risk
@@ -101,6 +118,7 @@
- [ ] Improve strategy composability by using delegate pattern
## Part 3 : Backtests automation
- [ ] Create a worker that determine best TP and SL
- [ ] Create a page 'Analyze' to show the best TP and SL for multiple backtest result
- [ ] Implement reverseSignal to close and flip the trade
@@ -115,29 +133,44 @@
_______________________________________________________________________________________________________________
# Phase 2 - Web3
## 1 - Wallet management
- [ ] User can deposit token to and evm account with a QR code or clicking on button to copy the address
- [ ] Add account abstraction to level up security
## 2 - [Track address](https://github.com/users/CryptoOda/projects/1/views/1?pane=issue&itemId=32158941)
- [ ] Create a snapshot of the account balances with BalancesWorker
- [ ] Display balance in $ evolution per token hold on the account page
## 3 - Settings [Link](https://github.com/users/CryptoOda/projects/1/views/1?pane=issue&itemId=32159287)
- [ ] Save theme into database
- [ ] Call GET Settings/Theme to retrieve the theme used by the user
## 4 - Trading desk [Link](https://github.com/users/CryptoOda/projects/1/views/1?pane=issue&itemId=11070087)
- [x] Live data position hub
- [x] Live candles
- [x] Open position from desk
## 5 - Live liquidation map
- [ ] Create worker to aggregate binance/okx liquidation
- [ ] Render liquidation map with a hub subscription to get live update
- [ ] Live data signal
- [ ] Display massive liquidation on TradeChartWidget
## 6 - Metrics [Link](https://github.com/users/CryptoOda/projects/1/views/1?pane=issue&itemId=32159107)
- [ ] Create a worker that get top 5 cryptos by scenario
- [ ] Create worker to store portofolio evolution
- [ ] Display portofolio evolution
- [ ] Create a worker to scrap funding fees over time (per ticker, per exchange)
## 7 - Improvement [Link](https://github.com/users/CryptoOda/projects/1/views/1?pane=issue&itemId=32159127)
- [ ] Handling user on every object => Use the JWT token to inject the userName
- [ ] Extract BacktestReport from tests to a Tools projects
- [ ] Factorize amount management for GMX Service
@@ -152,36 +185,55 @@ ________________________________________________________________________________
- [ ] Implement from/to tickers array pattern
- [ ] Extract all managing trade method into a TradingBox class => Create composable trading bot type easily
- [ ] Bot backup worker: Every x, get saved bots and check if still running. If not running call api to reboot bot.
- [ ] Create worker to fetch the biggest spread between long\short funding rate and send alert when most profitable delta neutral position is found
- [ ] Create worker to fetch the biggest spread between long\short funding rate and send alert when most profitable
delta neutral position is found
# Front-end
## Improve Account page
- [ ] Display total balances (only trader account) on Settings->Accounts Page
- [ ] On Token Account details line -> Add button to withdraw money (this will open a Modal to prompt the address/amount that will receive the money)
- [ ] On Token Account details line -> Add button to withdraw money (this will open a Modal to prompt the
address/amount that will receive the money)
## Charts
- [ ] Add multi-timeframe options
- [ ] Display optionnal indicators on charts
- [ ] Display current selected position (when i click on a Position in the list)
## Trading desk
- [ ] WAIT - Create a button to open a hedge on option market
- [ ] Get global exposure ((total position / total balances *) 100)
- [ ] Display multiple tab to show different tickers
## Scenarios
- [x] Create a blocky-like editor to create scenarios https://google.github.io/blockly-samples/
## Bots
- [ ] Add button to display money management use by the bot
- [ ] On the modal, When simple bot selected, show only a select for the workflow
## Backtests
- [x] Display the money management used by the backtest
## Technical front-end :
- [ ] Implement alias to reduce 'import' lines https://github.com/subwaytime/vite-aliases
- [ ] Make Get Accounts List as a store
- [ ] Replace all html-tag Modals (ex: BacktestPlayground.tsx)
- [ ] Refactoring Components :
- organism : Put all the code related to the app (Trade charts etc). This folder should be delete when the project is forked
- organism : Put all the code related to the app (Trade charts etc). This folder should be delete when the project is
forked
- mollecules : Put aggregate of atoms to create forms/modal/table
- atoms : Put all basic html tag components (List, Select, Slider...)
## Workflow
- [x] List all workflow saved in
- [x] Use https://reactflow.dev/ to display a workflow (map flow to nodes and children to edges)
- [x] On update Nodes : https://codesandbox.io/s/dank-waterfall-8jfcf4?file=/src/App.js

View File

@@ -5,11 +5,21 @@ using static Managing.Common.Enums;
namespace Managing.Api.Workers.Workers;
/// <summary>
/// Represents a worker that watches traders and performs actions based on trading activities.
/// Inherits from <see cref="BaseWorker{TWorker}"/> where TWorker is <see cref="FeeWorker"/>.
/// </summary>
public class TraderWatcher : BaseWorker<FeeWorker>
{
private readonly ITradingService _tradingService;
private static readonly WorkerType _workerType = WorkerType.TraderWatcher;
/// <summary>
/// Initializes a new instance of the <see cref="TraderWatcher"/> class.
/// </summary>
/// <param name="logger">The logger to be used by the worker.</param>
/// <param name="tradingService">The trading service to monitor trading activities.</param>
/// <param name="workerService">The worker service to manage worker lifecycle.</param>
public TraderWatcher(
ILogger<FeeWorker> logger,
ITradingService tradingService,
@@ -23,6 +33,10 @@ public class TraderWatcher : BaseWorker<FeeWorker>
_tradingService = tradingService;
}
/// <summary>
/// Executes the worker's task to watch traders. This method is called periodically based on the worker's configured interval.
/// </summary>
/// <param name="cancellationToken">A token to observe while waiting for the task to complete.</param>
protected override async Task Run(CancellationToken cancellationToken)
{
await _tradingService.WatchTrader();

View File

@@ -5,11 +5,20 @@ using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers
{
/// <summary>
/// Provides endpoints for account management operations such as creating, retrieving, and deleting accounts.
/// Requires authorization for access.
/// </summary>
[Authorize]
public class AccountController : BaseController
{
private readonly IAccountService _AccountService;
/// <summary>
/// Initializes a new instance of the <see cref="AccountController"/> class.
/// </summary>
/// <param name="AccountService">Service for account-related operations.</param>
/// <param name="userService">Service for user-related operations.</param>
public AccountController(
IAccountService AccountService,
IUserService userService)
@@ -18,6 +27,11 @@ namespace Managing.Api.Controllers
_AccountService = AccountService;
}
/// <summary>
/// Creates a new account for the authenticated user.
/// </summary>
/// <param name="Account">The account details to create.</param>
/// <returns>The created account details.</returns>
[HttpPost]
public async Task<ActionResult<Account>> PostAccount(Account Account)
{
@@ -25,6 +39,10 @@ namespace Managing.Api.Controllers
return Ok(await _AccountService.CreateAccount(user, Account));
}
/// <summary>
/// Retrieves all accounts associated with the authenticated user.
/// </summary>
/// <returns>A list of accounts.</returns>
[HttpGet]
[Route("accounts")]
public async Task<ActionResult<IEnumerable<Account>>> GetAccounts()
@@ -33,6 +51,10 @@ namespace Managing.Api.Controllers
return Ok(_AccountService.GetAccountsByUser(user, true));
}
/// <summary>
/// Retrieves the balances of all accounts associated with the authenticated user.
/// </summary>
/// <returns>A list of accounts with their balances.</returns>
[HttpGet]
[Route("balances")]
public async Task<ActionResult<IEnumerable<Account>>> GetAccountsBalances()
@@ -41,6 +63,11 @@ namespace Managing.Api.Controllers
return Ok(_AccountService.GetAccountsBalancesByUser(user));
}
/// <summary>
/// Retrieves a specific account by name for the authenticated user.
/// </summary>
/// <param name="name">The name of the account to retrieve.</param>
/// <returns>The account details if found.</returns>
[HttpGet]
public async Task<ActionResult<Account>> GetAccount(string name)
{
@@ -48,6 +75,11 @@ namespace Managing.Api.Controllers
return Ok(await _AccountService.GetAccountByUser(user, name, true, true));
}
/// <summary>
/// Deletes a specific account by name for the authenticated user.
/// </summary>
/// <param name="name">The name of the account to delete.</param>
/// <returns>An ActionResult indicating the outcome of the operation.</returns>
[HttpDelete]
public ActionResult DeleteAccount(string name)
{

View File

@@ -10,6 +10,11 @@ using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
/// <summary>
/// Controller for managing backtest operations.
/// Provides endpoints for creating, retrieving, and deleting backtests.
/// Requires authorization for access.
/// </summary>
[ApiController]
[Authorize]
[Route("[controller]")]
@@ -22,6 +27,14 @@ public class BacktestController : ControllerBase
private readonly IAccountService _accountService;
private readonly IMoneyManagementService _moneyManagementService;
/// <summary>
/// Initializes a new instance of the <see cref="BacktestController"/> class.
/// </summary>
/// <param name="hubContext">The SignalR hub context for real-time communication.</param>
/// <param name="backtester">The service for backtesting strategies.</param>
/// <param name="scenarioService">The service for managing scenarios.</param>
/// <param name="accountService">The service for account management.</param>
/// <param name="moneyManagementService">The service for money management strategies.</param>
public BacktestController(
IHubContext<BotHub> hubContext,
IBacktester backtester,
@@ -36,18 +49,31 @@ public class BacktestController : ControllerBase
_moneyManagementService = moneyManagementService;
}
/// <summary>
/// Retrieves all backtests.
/// </summary>
/// <returns>A list of backtests.</returns>
[HttpGet]
public ActionResult<IEnumerable<Backtest>> Backtests()
{
return Ok(_backtester.GetBacktests());
}
/// <summary>
/// Deletes a specific backtest by ID.
/// </summary>
/// <param name="id">The ID of the backtest to delete.</param>
/// <returns>An ActionResult indicating the outcome of the operation.</returns>
[HttpDelete]
public ActionResult DeleteBacktest(string id)
{
return Ok(_backtester.DeleteBacktest(id));
}
/// <summary>
/// Deletes all backtests.
/// </summary>
/// <returns>An ActionResult indicating the outcome of the operation.</returns>
[HttpDelete]
[Route("deleteAll")]
public ActionResult DeleteBacktests()
@@ -55,6 +81,21 @@ public class BacktestController : ControllerBase
return Ok(_backtester.DeleteBacktests());
}
/// <summary>
/// Runs a backtest with the specified parameters.
/// </summary>
/// <param name="accountName">The name of the account to use for the backtest.</param>
/// <param name="botType">The type of bot to use for the backtest.</param>
/// <param name="ticker">The ticker symbol to backtest.</param>
/// <param name="scenarioName">The name of the scenario to use for the backtest.</param>
/// <param name="timeframe">The timeframe for the backtest.</param>
/// <param name="watchOnly">Whether to only watch the backtest without executing trades.</param>
/// <param name="days">The number of days to backtest.</param>
/// <param name="balance">The starting balance for the backtest.</param>
/// <param name="moneyManagementName">The name of the money management strategy to use.</param>
/// <param name="moneyManagement">The money management strategy details, if not using a named strategy.</param>
/// <param name="save">Whether to save the backtest results.</param>
/// <returns>The result of the backtest.</returns>
[HttpPost]
[Route("Run")]
public async Task<ActionResult<Backtest>> Run(string accountName,
@@ -124,6 +165,10 @@ public class BacktestController : ControllerBase
return Ok(backtestResult);
}
/// <summary>
/// Notifies subscribers about the backtesting results via SignalR.
/// </summary>
/// <param name="backtesting">The backtest result to notify subscribers about.</param>
private async Task NotifyBacktesingSubscriberAsync(Backtest backtesting)
{
if(backtesting != null){

View File

@@ -11,6 +11,10 @@ using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
/// <summary>
/// Controller for bot operations such as starting, stopping, deleting, and managing bots.
/// Requires authorization for access and produces JSON responses.
/// </summary>
[ApiController]
[Authorize]
[Route("[controller]")]
@@ -22,6 +26,13 @@ public class BotController : ControllerBase
private readonly IHubContext<BotHub> _hubContext;
private readonly IBacktester _backtester;
/// <summary>
/// Initializes a new instance of the <see cref="BotController"/> class.
/// </summary>
/// <param name="logger">Logger for logging information.</param>
/// <param name="mediator">Mediator for handling commands and requests.</param>
/// <param name="hubContext">SignalR hub context for real-time communication.</param>
/// <param name="backtester">Backtester for running backtests on bots.</param>
public BotController(ILogger<BotController> logger, IMediator mediator, IHubContext<BotHub> hubContext, IBacktester backtester)
{
_logger = logger;
@@ -30,6 +41,11 @@ public class BotController : ControllerBase
_backtester = backtester;
}
/// <summary>
/// Starts a bot with the specified parameters.
/// </summary>
/// <param name="request">The request containing bot start parameters.</param>
/// <returns>A string indicating the result of the start operation.</returns>
[HttpPost]
[Route("Start")]
public async Task<ActionResult<string>> Start(StartBotRequest request)
@@ -41,6 +57,12 @@ public class BotController : ControllerBase
return Ok(result);
}
/// <summary>
/// Stops a bot specified by type and name.
/// </summary>
/// <param name="botType">The type of the bot to stop.</param>
/// <param name="botName">The name of the bot to stop.</param>
/// <returns>A string indicating the result of the stop operation.</returns>
[HttpGet]
[Route("Stop")]
public async Task<ActionResult<string>> Stop(BotType botType, string botName)
@@ -53,6 +75,11 @@ public class BotController : ControllerBase
return Ok(result);
}
/// <summary>
/// Deletes a bot specified by name.
/// </summary>
/// <param name="botName">The name of the bot to delete.</param>
/// <returns>A boolean indicating the result of the delete operation.</returns>
[HttpDelete]
[Route("Delete")]
public async Task<ActionResult<bool>> Delete(string botName)
@@ -65,6 +92,10 @@ public class BotController : ControllerBase
return Ok(result);
}
/// <summary>
/// Stops all active bots.
/// </summary>
/// <returns>A string summarizing the results of the stop operations for all bots.</returns>
[HttpGet]
[Route("StopAll")]
public async Task<string> StopAll()
@@ -83,6 +114,12 @@ public class BotController : ControllerBase
return result;
}
/// <summary>
/// Restarts a bot specified by type and name.
/// </summary>
/// <param name="botType">The type of the bot to restart.</param>
/// <param name="botName">The name of the bot to restart.</param>
/// <returns>A string indicating the result of the restart operation.</returns>
[HttpGet]
[Route("Restart")]
public async Task<ActionResult<string>> Restart(BotType botType, string botName)
@@ -95,6 +132,10 @@ public class BotController : ControllerBase
return Ok(result);
}
/// <summary>
/// Restarts all active bots.
/// </summary>
/// <returns>A string summarizing the results of the restart operations for all bots.</returns>
[HttpGet]
[Route("RestartAll")]
public async Task<string> RestartAll()
@@ -113,6 +154,11 @@ public class BotController : ControllerBase
return result;
}
/// <summary>
/// Toggles the watching status of a bot specified by name.
/// </summary>
/// <param name="botName">The name of the bot to toggle watching status.</param>
/// <returns>A string indicating the new watching status of the bot.</returns>
[HttpGet]
[Route("ToggleIsForWatching")]
public async Task<ActionResult<string>> ToggleIsForWatching(string botName)
@@ -125,12 +171,20 @@ public class BotController : ControllerBase
return Ok(result);
}
/// <summary>
/// Retrieves a list of active bots.
/// </summary>
/// <returns>A list of active trading bots.</returns>
[HttpGet]
public async Task<List<TradingBot>> GetActiveBots()
{
return await GetBotList();
}
/// <summary>
/// Retrieves a list of active bots by sending a command to the mediator.
/// </summary>
/// <returns>A list of trading bots.</returns>
private async Task<List<TradingBot>> GetBotList()
{
var result = await _mediator.Send(new GetActiveBotsCommand());
@@ -160,6 +214,9 @@ public class BotController : ControllerBase
return list;
}
/// <summary>
/// Notifies subscribers about the current list of bots via SignalR.
/// </summary>
private async Task NotifyBotSubscriberAsync()
{
var botsList = await GetBotList();

View File

@@ -10,6 +10,10 @@ using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
/// <summary>
/// Controller for handling data-related operations such as retrieving tickers, spotlight data, and candles.
/// Requires authorization for access.
/// </summary>
[ApiController]
[Authorize]
[Route("[controller]")]
@@ -21,6 +25,14 @@ public class DataController : ControllerBase
private readonly IStatisticService _statisticService;
private readonly IHubContext<CandleHub> _hubContext;
/// <summary>
/// Initializes a new instance of the <see cref="DataController"/> class.
/// </summary>
/// <param name="exchangeService">Service for interacting with exchanges.</param>
/// <param name="accountService">Service for account management.</param>
/// <param name="cacheService">Service for caching data.</param>
/// <param name="statisticService">Service for statistical analysis.</param>
/// <param name="hubContext">SignalR hub context for real-time communication.</param>
public DataController(
IExchangeService exchangeService,
IAccountService accountService,
@@ -35,6 +47,12 @@ public class DataController : ControllerBase
_hubContext = hubContext;
}
/// <summary>
/// Retrieves tickers for a given account and timeframe, utilizing caching to improve performance.
/// </summary>
/// <param name="accountName">The name of the account to retrieve tickers for.</param>
/// <param name="timeframe">The timeframe for which to retrieve tickers.</param>
/// <returns>An array of tickers.</returns>
[HttpPost("GetTickers")]
public async Task<ActionResult<Ticker[]>> GetTickers(string accountName, Timeframe timeframe)
{
@@ -48,6 +66,10 @@ public class DataController : ControllerBase
return Ok(tickers);
}
/// <summary>
/// Retrieves the latest spotlight overview, using caching to enhance response times.
/// </summary>
/// <returns>A <see cref="SpotlightOverview"/> object containing spotlight data.</returns>
[HttpGet("Spotlight")]
public ActionResult<SpotlightOverview> GetSpotlight()
{
@@ -64,10 +86,17 @@ public class DataController : ControllerBase
return Ok(overview);
}
/// <summary>
/// Retrieves candle data for a given exchange, ticker, start date, and timeframe.
/// </summary>
/// <param name="exchange">The exchange to retrieve candles from.</param>
/// <param name="ticker">The ticker symbol to retrieve candles for.</param>
/// <param name="startDate">The start date for the candle data.</param>
/// <param name="timeframe">The timeframe for the candle data.</param>
/// <returns>A list of <see cref="Candle"/> objects.</returns>
[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

@@ -5,6 +5,11 @@ using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers;
/// <summary>
/// Controller for managing money management strategies.
/// Provides endpoints for creating, retrieving, updating, and deleting money management strategies.
/// Requires authorization for access and produces JSON responses.
/// </summary>
[ApiController]
[Authorize]
[Route("[controller]")]
@@ -12,17 +17,31 @@ namespace Managing.Api.Controllers;
public class MoneyManagementController : ControllerBase
{
private readonly IMoneyManagementService _moneyManagementService;
/// <summary>
/// Initializes a new instance of the <see cref="MoneyManagementController"/> class.
/// </summary>
/// <param name="moneyManagementService">The service for managing money management strategies.</param>
public MoneyManagementController(IMoneyManagementService moneyManagementService)
{
_moneyManagementService = moneyManagementService;
}
/// <summary>
/// Creates a new money management strategy or updates an existing one.
/// </summary>
/// <param name="moneyManagement">The money management strategy to create or update.</param>
/// <returns>The created or updated money management strategy.</returns>
[HttpPost]
public async Task<ActionResult<MoneyManagement>> PostMoneyManagement(MoneyManagement moneyManagement)
{
return Ok(await _moneyManagementService.CreateOrUpdateMoneyManagement(moneyManagement));
}
/// <summary>
/// Retrieves all money management strategies.
/// </summary>
/// <returns>A list of money management strategies.</returns>
[HttpGet]
[Route("moneymanagements")]
public ActionResult<IEnumerable<MoneyManagement>> GetMoneyManagements()
@@ -30,12 +49,22 @@ public class MoneyManagementController : ControllerBase
return Ok(_moneyManagementService.GetMoneyMangements());
}
/// <summary>
/// Retrieves a specific money management strategy by name.
/// </summary>
/// <param name="name">The name of the money management strategy to retrieve.</param>
/// <returns>The requested money management strategy if found.</returns>
[HttpGet]
public ActionResult<MoneyManagement> GetMoneyManagement(string name)
{
return Ok(_moneyManagementService.GetMoneyMangement(name));
}
/// <summary>
/// Deletes a specific money management strategy by name.
/// </summary>
/// <param name="name">The name of the money management strategy to delete.</param>
/// <returns>An ActionResult indicating the outcome of the operation.</returns>
[HttpDelete]
public ActionResult DeleteMoneyManagement(string name)
{

View File

@@ -7,6 +7,11 @@ using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
/// <summary>
/// Controller for managing scenarios and strategies within the application.
/// Provides endpoints for creating, retrieving, and deleting scenarios and strategies.
/// Requires authorization for access and produces JSON responses.
/// </summary>
[ApiController]
[Authorize]
[Route("[controller]")]
@@ -14,30 +19,53 @@ namespace Managing.Api.Controllers;
public class ScenarioController : ControllerBase
{
private readonly IScenarioService _scenarioService;
/// <summary>
/// Initializes a new instance of the <see cref="ScenarioController"/> class.
/// </summary>
/// <param name="scenarioService">The service for managing scenarios.</param>
public ScenarioController(IScenarioService scenarioService)
{
_scenarioService = scenarioService;
}
/// <summary>
/// Retrieves all scenarios.
/// </summary>
/// <returns>A list of scenarios.</returns>
[HttpGet]
public ActionResult<IEnumerable<Scenario>> GetScenarios()
{
return Ok(_scenarioService.GetScenarios());
}
/// <summary>
/// Creates a new scenario with the specified name and strategies.
/// </summary>
/// <param name="name">The name of the scenario.</param>
/// <param name="strategies">A list of strategy names to include in the scenario.</param>
/// <returns>The created scenario.</returns>
[HttpPost]
public ActionResult<Scenario> CreateScenario(string name, List<string> strategies)
{
return Ok(_scenarioService.CreateScenario(name, strategies));
}
/// <summary>
/// Deletes a scenario by name.
/// </summary>
/// <param name="name">The name of the scenario to delete.</param>
/// <returns>An ActionResult indicating the outcome of the operation.</returns>
[HttpDelete]
public ActionResult DeleteScenario(string name)
{
return Ok(_scenarioService.DeleteScenario(name));
}
/// <summary>
/// Retrieves all strategies.
/// </summary>
/// <returns>A list of strategies.</returns>
[HttpGet]
[Route("strategy")]
public ActionResult<IEnumerable<Strategy>> GetStrategies()
@@ -45,6 +73,21 @@ public class ScenarioController : ControllerBase
return Ok(_scenarioService.GetStrategies());
}
/// <summary>
/// Creates a new strategy with specified parameters.
/// </summary>
/// <param name="strategyType">The type of the strategy.</param>
/// <param name="timeframe">The timeframe for the strategy.</param>
/// <param name="name">The name of the strategy.</param>
/// <param name="period">The period for the strategy (optional).</param>
/// <param name="fastPeriods">The fast periods for the strategy (optional).</param>
/// <param name="slowPeriods">The slow periods for the strategy (optional).</param>
/// <param name="signalPeriods">The signal periods for the strategy (optional).</param>
/// <param name="multiplier">The multiplier for the strategy (optional).</param>
/// <param name="stochPeriods">The stochastic periods for the strategy (optional).</param>
/// <param name="smoothPeriods">The smooth periods for the strategy (optional).</param>
/// <param name="cyclePeriods">The cycle periods for the strategy (optional).</param>
/// <returns>The created strategy.</returns>
[HttpPost]
[Route("strategy")]
public ActionResult<Strategy> CreateStrategy(
@@ -74,6 +117,11 @@ public class ScenarioController : ControllerBase
cyclePeriods));
}
/// <summary>
/// Deletes a strategy by name.
/// </summary>
/// <param name="name">The name of the strategy to delete.</param>
/// <returns>An ActionResult indicating the outcome of the operation.</returns>
[HttpDelete]
[Route("strategy")]
public ActionResult DeleteStrategy(string name)

View File

@@ -10,6 +10,10 @@ using static Managing.Common.Enums;
namespace Managing.Api.Controllers;
/// <summary>
/// Controller for trading operations such as opening and closing positions, and retrieving trade information.
/// Requires authorization for access.
/// </summary>
[ApiController]
[Authorize]
[Route("[controller]")]
@@ -20,9 +24,16 @@ public class TradingController : ControllerBase
private readonly ITradingService _tradingService;
private readonly IMoneyManagementService _moneyManagementService;
private readonly IMediator _mediator;
private readonly ILogger<TradingController> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TradingController"/> class.
/// </summary>
/// <param name="logger">Logger for logging information.</param>
/// <param name="openTradeCommandHandler">Command handler for opening trades.</param>
/// <param name="closeTradeCommandHandler">Command handler for closing trades.</param>
/// <param name="tradingService">Service for trading operations.</param>
/// <param name="mediator">Mediator for handling commands and requests.</param>
public TradingController(
ILogger<TradingController> logger,
ICommandHandler<OpenPositionRequest, Position> openTradeCommandHandler,
@@ -37,6 +48,11 @@ public class TradingController : ControllerBase
_mediator = mediator;
}
/// <summary>
/// Retrieves a list of positions based on the initiator type.
/// </summary>
/// <param name="positionInitiator">The initiator of the position (e.g., User, System).</param>
/// <returns>A list of positions.</returns>
[HttpGet("GetPositions")]
public async Task<ActionResult<List<Position>>> GetPositions(PositionInitiator positionInitiator)
{
@@ -44,6 +60,13 @@ public class TradingController : ControllerBase
return Ok(result);
}
/// <summary>
/// Retrieves a specific trade by account name, ticker, and exchange order ID.
/// </summary>
/// <param name="accountName">The name of the account.</param>
/// <param name="ticker">The ticker symbol of the trade.</param>
/// <param name="exchangeOrderId">The exchange order ID of the trade.</param>
/// <returns>The requested trade.</returns>
[HttpGet("GetTrade")]
public async Task<ActionResult<Trade>> GetTrade(string accountName, Ticker ticker, string exchangeOrderId)
{
@@ -51,13 +74,24 @@ public class TradingController : ControllerBase
return Ok(result);
}
/// <summary>
/// Retrieves a list of trades for a given account and ticker.
/// </summary>
/// <param name="accountName">The name of the account.</param>
/// <param name="ticker">The ticker symbol of the trades.</param>
/// <returns>A list of trades.</returns>
[HttpGet("GetTrades")]
public async Task<ActionResult<Trade>> GetTrades(string accountName, Ticker ticker, string exchangeOrderId)
public async Task<ActionResult<Trade>> GetTrades(string accountName, Ticker ticker)
{
var result = await _mediator.Send(new GetTradesCommand(ticker, accountName));
return Ok(result);
}
/// <summary>
/// Closes a position identified by its unique identifier.
/// </summary>
/// <param name="identifier">The unique identifier of the position to close.</param>
/// <returns>The closed position.</returns>
[HttpGet("ClosePosition")]
public async Task<ActionResult<Position>> ClosePosition(string identifier)
{
@@ -66,6 +100,18 @@ public class TradingController : ControllerBase
return Ok(result);
}
/// <summary>
/// Opens a new position based on the provided parameters.
/// </summary>
/// <param name="accountName">The name of the account to open the position for.</param>
/// <param name="moneyManagementName">The name of the money management strategy to use.</param>
/// <param name="direction">The direction of the trade (Buy or Sell).</param>
/// <param name="ticker">The ticker symbol for the trade.</param>
/// <param name="riskLevel">The risk level for the trade.</param>
/// <param name="isForPaperTrading">Indicates whether the trade is for paper trading.</param>
/// <param name="moneyManagement">The money management strategy details (optional).</param>
/// <param name="openPrice">The opening price for the trade (optional).</param>
/// <returns>The opened position.</returns>
[HttpGet("OpenPosition")]
public async Task<ActionResult<Position>> Trade(
string accountName,

View File

@@ -6,6 +6,9 @@ using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers;
/// <summary>
/// Provides authentication-related actions, including token creation for user authentication.
/// </summary>
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
@@ -15,6 +18,12 @@ public class UserController : ControllerBase
private readonly IUserService _userService;
private readonly IJwtUtils _jwtUtils;
/// <summary>
/// Initializes a new instance of the <see cref="UserController"/> class.
/// </summary>
/// <param name="config">Configuration settings.</param>
/// <param name="userService">Service for user-related operations.</param>
/// <param name="jwtUtils">Utility for JWT token operations.</param>
public UserController(IConfiguration config, IUserService userService, IJwtUtils jwtUtils)
{
_config = config;
@@ -22,6 +31,11 @@ public class UserController : ControllerBase
_jwtUtils = jwtUtils;
}
/// <summary>
/// Creates a JWT token for a user based on the provided login credentials.
/// </summary>
/// <param name="login">The login request containing user credentials.</param>
/// <returns>A JWT token if authentication is successful; otherwise, an Unauthorized result.</returns>
[AllowAnonymous]
[HttpPost]
public async Task<ActionResult<string>> CreateToken([FromBody] LoginRequest login)

View File

@@ -7,28 +7,50 @@ using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers
{
/// <summary>
/// Controller for managing workflows, including creating, retrieving, and deleting workflows.
/// Requires authorization for access.
/// </summary>
[Authorize]
public class WorkflowController : BaseController
{
private readonly IWorkflowService _workflowService;
/// <summary>
/// Initializes a new instance of the <see cref="WorkflowController"/> class.
/// </summary>
/// <param name="WorkflowService">Service for managing workflows.</param>
/// <param name="userService">Service for user-related operations.</param>
public WorkflowController(IWorkflowService WorkflowService, IUserService userService) : base(userService)
{
_workflowService = WorkflowService;
}
/// <summary>
/// Creates a new workflow or updates an existing one based on the provided workflow request.
/// </summary>
/// <param name="workflowRequest">The workflow request containing the details of the workflow to be created or updated.</param>
/// <returns>The created or updated workflow.</returns>
[HttpPost]
public async Task<ActionResult<Workflow>> PostWorkflow([ModelBinder]SyntheticWorkflow workflowRequest)
{
return Ok(await _workflowService.InsertOrUpdateWorkflow(workflowRequest));
}
/// <summary>
/// Retrieves all workflows.
/// </summary>
/// <returns>A list of all workflows.</returns>
[HttpGet]
public ActionResult<IEnumerable<SyntheticWorkflow>> GetWorkflows()
{
return Ok(_workflowService.GetWorkflows());
}
/// <summary>
/// Retrieves all available flows.
/// </summary>
/// <returns>A list of all available flows.</returns>
[HttpGet]
[Route("flows")]
public async Task<ActionResult<IEnumerable<IFlow>>> GetAvailableFlows()
@@ -36,6 +58,11 @@ namespace Managing.Api.Controllers
return Ok(await _workflowService.GetAvailableFlows());
}
/// <summary>
/// Deletes a workflow by name.
/// </summary>
/// <param name="name">The name of the workflow to delete.</param>
/// <returns>An ActionResult indicating the outcome of the operation.</returns>
[HttpDelete]
public ActionResult DeleteWorkflow(string name)
{