Commit Graph

171 Commits

Author SHA1 Message Date
0428775abf Excellent! Everything builds successfully. Let me create a summary of all the changes:
## Summary of Changes

I've successfully moved the `GetBacktestStats` endpoint to the `DataController` and removed JWT authentication. Here's what was done:

### 1. **Moved GetBacktestStats Endpoint to DataController** 
- **File**: `src/Managing.Api/Controllers/DataController.cs:1064`
- **Endpoint**: `GET /Data/GetBacktestStats/{id}`
- **Authentication**: None required (DataController has `[AllowAnonymous]`)
- Returns only statistical information without positions, signals, or candles

### 2. **Added IBacktester Dependency to DataController** 
- **File**: `src/Managing.Api/Controllers/DataController.cs:45,87`
- Added `IBacktester` field and constructor parameter
- Allows DataController to retrieve backtest information

### 3. **Created New Repository Method** 
- **Interface**: `src/Managing.Application.Abstractions/Repositories/IBacktestRepository.cs:41`
- **Implementation**: `src/Managing.Infrastructure.Database/PostgreSql/PostgreSqlBacktestRepository.cs:301`
- Added `GetBacktestByIdAsync(string id)` - retrieves backtest without user filtering

### 4. **Created New Service Method** 
- **Interface**: `src/Managing.Application.Abstractions/Services/IBacktester.cs:67`
- **Implementation**: `src/Managing.Application/Backtests/Backtester.cs:221`
- Added `GetBacktestByIdAsync(string id)` in IBacktester service

### 5. **Removed Duplicate Endpoint from BacktestController** 
- **File**: `src/Managing.Api/Controllers/BacktestController.cs`
- Removed the `/Backtest/{id}/stats` endpoint to avoid duplication

### 6. **Regenerated Frontend API Client** 
- Successfully ran `dotnet build` in `src/Managing.Nswag`
- The new endpoint is now available in `ManagingApi.ts`

## API Endpoint Details

**Endpoint**: `GET /Data/GetBacktestStats/{id}`

**Authentication**: None (AllowAnonymous)

**Response Format**:
```json
{
  "id": "string",
  "name": "string",
  "ticker": "BTC",
  "timeframe": "15m",
  "tradingType": "Futures",
  "startDate": "2024-01-01T00:00:00Z",
  "endDate": "2024-12-31T23:59:59Z",
  "initialBalance": 1000,
  "finalPnl": 150.50,
  "netPnl": 145.25,
  "growthPercentage": 14.5,
  "hodlPercentage": 12.3,
  "winRate": 65,
  "sharpeRatio": 1.8,
  "maxDrawdown": -5.2,
  "maxDrawdownRecoveryTime": "2.00:00:00",
  "fees": 5.25,
  "score": 85.5,
  "scoreMessage": "Good performance",
  "positionCount": 150
}
```

All changes have been tested and the project builds successfully!
2026-01-09 19:18:52 +07:00
452c274073 Excellent! Let me create a comprehensive summary of all the changes made:
## Summary

I've successfully implemented all the requested features to add BacktestId support to the strategies/bot system:

### 1. **Added BacktestId Column to BotEntity** 
- **File**: `src/Managing.Infrastructure.Database/PostgreSql/Entities/BotEntity.cs:47`
- Added nullable `int? BacktestId` property with documentation
- This allows bots to reference the backtest they were created from

### 2. **Updated Bot Domain Model** 
- **File**: `src/Managing.Domain/Bots/Bot.cs:37`
- Added `BacktestId` property to the domain model
- Maintains consistency between entity and domain layers

### 3. **Updated TradingBotConfig and TradingBotConfigRequest** 
- **File**: `src/Managing.Domain/Bots/TradingBotConfig.cs:131`
  - Added `[Id(24)] public int? BacktestId` with Orleans serialization attribute
- **File**: `src/Managing.Domain/Bots/TradingBotConfigRequest.cs:119`
  - Added `BacktestId` property to the request model
- These changes ensure BacktestId flows through the entire bot creation pipeline

### 4. **Updated Data Mappers** 
- **File**: `src/Managing.Infrastructure.Database/PostgreSql/PostgreSqlMappers.cs`
  - Updated `Map(Bot bot)` at line 833 to include BacktestId
  - Updated `Map(BotEntity entity)` at line 799 to include BacktestId
- Ensures proper mapping between entity and domain models

### 5. **Updated LiveTradingBotGrain** 
- **File**: `src/Managing.Application/Bots/Grains/LiveTradingBotGrain.cs`
  - Added BacktestId to bot creation at line 1078 (for saved bots)
  - Added BacktestId to bot creation at line 1145 (for running bots)
- The grain now properly persists BacktestId when saving bot statistics

### 6. **Created New Endpoint for Backtest Stats** 
- **File**: `src/Managing.Api/Controllers/BacktestController.cs:114`
- **New Endpoint**: `GET /Backtest/{id}/stats`
- Returns only statistical information without positions, signals, or candles:
  - Basic info: id, name, ticker, timeframe, tradingType, startDate, endDate
  - Performance: initialBalance, finalPnl, netPnl, growthPercentage, hodlPercentage, winRate
  - Risk metrics: sharpeRatio, maxDrawdown, maxDrawdownRecoveryTime
  - Other: fees, score, scoreMessage, positionCount

### 7. **Created Database Migration** 
- **Generated Migration**: `AddBacktestIdToBots`
- The migration adds a nullable integer column `BacktestId` to the `Bots` table
- Ready to be applied with `dotnet ef database update`

### 8. **Regenerated Frontend API Client** 
- Ran `dotnet build` in `src/Managing.Nswag`
- The `ManagingApi.ts` file has been regenerated with:
  - `backtestId` field in bot-related DTOs
  - New `/Backtest/{id}/stats` endpoint

## How It Works

### Starting a Bot from a Backtest:
1. Frontend sends `StartBotRequest` with `TradingBotConfigRequest` containing `backtestId`
2. `BotController` validates and prepares the request
3. `StartBotCommandHandler` creates the bot configuration with BacktestId
4. `LiveTradingBotGrain.CreateAsync()` receives the config and saves it to state
5. When the bot is saved via `SaveBotAsync()`, BacktestId is persisted to the database
6. The Bot entity now has a reference to its originating backtest

### Retrieving Backtest Stats:
1. Frontend calls `GET /Backtest/{id}/stats` with the backtest ID
2. Backend retrieves the full backtest from the database
3. Returns only the statistical summary (without heavy data like positions/signals/candles)
4. Frontend can display backtest performance metrics when viewing a bot

## Database Schema
```sql
ALTER TABLE "Bots" ADD COLUMN "BacktestId" integer NULL;
```

All changes follow the project's architecture patterns (Controller → Application → Repository) and maintain backward compatibility through nullable BacktestId fields.
2026-01-09 18:24:08 +07:00
1d33c6c2ee Update AgentSummaryRepository to clarify BacktestCount management
- Added comments to indicate that BacktestCount is not updated directly in the entity, as it is managed independently via IncrementBacktestCountAsync. This change prevents other update operations from overwriting the BacktestCount, ensuring data integrity.
2026-01-09 04:27:58 +07:00
ae353aa0d5 Implement balance update callback in TradingBotBase for immediate sync
- Removed the private _currentBalance field and replaced it with direct access to Config.BotTradingBalance.
- Added OnBalanceUpdatedCallback to TradingBotBase for immediate synchronization and database saving when the balance is updated.
- Updated LiveTradingBotGrain to set the callback for balance updates, ensuring accurate state management.
- Modified PostgreSqlBotRepository to save the updated bot trading balance during entity updates.
2026-01-09 03:34:35 +07:00
6f55566db3 Implement LLM provider configuration and update user settings
- Added functionality to update the default LLM provider for users via a new endpoint in UserController.
- Introduced LlmProvider enum to manage available LLM options: Auto, Gemini, OpenAI, and Claude.
- Updated User and UserEntity models to include DefaultLlmProvider property.
- Enhanced database context and migrations to support the new LLM provider configuration.
- Integrated LLM services into the application bootstrap for dependency injection.
- Updated TypeScript API client to include methods for managing LLM providers and chat requests.
2026-01-03 21:55:55 +07:00
18373b657a Add min and max balance filters to bot management
- Introduced optional parameters for minimum and maximum BotTradingBalance in BotController, DataController, and related services.
- Updated interfaces and repository methods to support filtering by BotTradingBalance.
- Enhanced TradingBotResponse and BotEntity models to include BotTradingBalance property.
- Adjusted database schema to accommodate new BotTradingBalance field.
- Ensured proper mapping and handling of BotTradingBalance in PostgreSQL repository and mappers.
2026-01-01 21:32:05 +07:00
a37b59f29a Add vibe-kanban 2025-12-31 01:31:54 +07:00
21d87efeee Refactor user settings management to remove IsGmxEnabled and DefaultExchange from updatable fields, introducing GmxSlippage instead. Update UserController, UserService, and related DTOs to reflect these changes, ensuring proper handling of user settings. Adjust database schema and migrations to accommodate the new GmxSlippage property, enhancing user customization options for trading configurations. 2025-12-30 07:19:08 +07:00
aa3b06bbe4 Enhance user settings management by adding new properties and updating related functionality
This commit introduces additional user settings properties, including TrendStrongAgreementThreshold, SignalAgreementThreshold, AllowSignalTrendOverride, and DefaultExchange, to the User entity and associated DTOs. The UserController and UserService are updated to handle these new settings, allowing users to customize their trading configurations more effectively. Database migrations are also included to ensure proper schema updates for the new fields.
2025-12-30 06:48:08 +07:00
79d8a381d9 Add user settings update functionality in UserController and UserService
Implement a new endpoint in UserController to allow users to update their settings. The UserService is updated to handle the logic for updating user settings, including partial updates for various fields. Additionally, the User entity and database schema are modified to accommodate new user settings properties, ensuring persistence and retrieval of user preferences.
2025-12-30 05:54:15 +07:00
bcb00b9a86 Refactor pagination sorting parameters across multiple controllers and services to use the new SortDirection enum; update related API models and TypeScript definitions for consistency. Fix minor documentation and naming inconsistencies in the Bot and Data controllers. 2025-12-14 20:23:26 +07:00
c4e444347c Fix bot update with the tradingtype 2025-12-13 14:46:30 +07:00
87bc2e9dce Enhance PostgreSqlBacktestRepository to include PositionCount in backtest mappings
- Updated the mapping logic in multiple methods to include PositionCount alongside existing fields such as NetPnl, Score, and InitialBalance.
2025-12-12 01:44:34 +07:00
a254db6d24 Update bot market type 2025-12-11 23:32:06 +07:00
Oda
9d536ea49e Refactoring TradingBotBase.cs + clean architecture (#38)
* Refactoring TradingBotBase.cs + clean architecture

* Fix basic tests

* Fix tests

* Fix workers

* Fix open positions

* Fix closing position stucking the grain

* Fix comments

* Refactor candle handling to use IReadOnlyList for chronological order preservation across various components
2025-12-01 19:32:06 +07:00
fef66f6d7b Update configuration settings and logging behavior for SQL monitoring
- Increased thresholds for maximum query and method executions per window to 500 and 250, respectively, to reduce false positives in loop detection.
- Enabled logging of slow queries only, improving performance by reducing log volume.
- Adjusted SQL query logging to capture only warnings and errors, further optimizing logging efficiency.
- Updated various settings across appsettings files to reflect these changes, ensuring consistency in configuration.
2025-11-24 01:02:53 +07:00
411fc41bef Refactor BotController and BotService for improved bot management
- Cleaned up constructor parameters in BotController for better readability.
- Enhanced StartCopyTradingCommand handling with improved formatting.
- Updated bot deletion logic in BotService to delete associated positions and trigger agent summary updates.
- Added new method in TradingService for deleting positions by initiator identifier.
- Implemented error handling in StopBotCommandHandler to ensure agent summary updates do not disrupt bot stop operations.
2025-11-23 15:30:11 +07:00
9c8ab71736 Do not update the masterBotUserId if update change it to null 2025-11-22 16:32:00 +07:00
2a354bd7d2 Implement profitable bots filtering in BotController and DataController
- Added IConfiguration dependency to BotController for accessing environment variables.
- Updated GetBotsPaginatedAsync method in BotService and IBotService to include a flag for filtering profitable bots.
- Modified DataController to utilize the new filtering option for agent summaries and bot retrieval.
- Enhanced PostgreSqlBotRepository to apply filtering based on profitability when querying bots.
2025-11-22 14:02:29 +07:00
e69dd43ace Enhance DataController and BotService with new configuration and bot name checks
- Added IConfiguration dependency to DataController for environment variable access.
- Updated GetPaginatedAgentSummariesCommand to include a flag for filtering profitable agents.
- Implemented HasUserBotWithNameAsync method in IBotService and BotService to check for existing bots by name.
- Modified StartBotCommandHandler and StartCopyTradingCommandHandler to prevent duplicate bot names during strategy creation.
2025-11-22 13:34:26 +07:00
269bbfaab0 Add GetBotByUserIdAndNameAsync method to IBotService and BotService
- Implemented GetBotByUserIdAndNameAsync in IBotService and BotService to retrieve a bot by user ID and name.
- Updated GetUserStrategyCommandHandler to utilize the new method for fetching strategies based on user ID.
- Added corresponding method in IBotRepository and PostgreSqlBotRepository for database access.
2025-11-22 10:46:07 +07:00
55f70add44 Include master bot for all query on Botentity 2025-11-20 14:52:55 +07:00
190a9cf12d Finish copy trading 2025-11-20 14:46:54 +07:00
ff2df2d9ac Add MasterBotUserId and MasterAgentName for copy trading support
- Introduced MasterBotUserId and MasterAgentName properties to facilitate copy trading functionality.
- Updated relevant models, controllers, and database entities to accommodate these new properties.
- Enhanced validation logic in StartCopyTradingCommandHandler to ensure proper ownership checks for master strategies.
2025-11-20 00:33:31 +07:00
61f95981a7 Fix position count 2025-11-19 17:58:04 +07:00
096fb500e4 Add position count property map 2025-11-19 14:16:30 +07:00
68e9b2348c Add PositionCount property to Backtest models and responses
- Introduced PositionCount to Backtest, LightBacktest, and their respective response models.
- Updated BacktestController and BacktestExecutor to include PositionCount in responses.
- Modified database schema to accommodate new PositionCount field in relevant entities.
2025-11-18 22:23:20 +07:00
02e46e8d0d Add paginated user retrieval functionality in AdminController and related services. Implemented UsersFilter for filtering user queries and added LastConnectionDate property to User model. Updated database schema and frontend API to support new user management features. 2025-11-17 20:04:17 +07:00
06ef33b7ab Enhance user authentication by adding optional OwnerWalletAddress parameter in LoginRequest and UserService. Update UserController and related components to support the new wallet address functionality, ensuring better user profile management and validation in trading operations. 2025-11-17 13:48:05 +07:00
0cfc30598b Fix managing with good backtest return 2025-11-14 14:28:13 +07:00
4a8c22e52a Update and fix worker 2025-11-11 03:02:24 +07:00
e8e2ec5a43 Add test for executor 2025-11-11 02:15:57 +07:00
d02a07f86b Fix initial balance on the backtest + n8n webhook 2025-11-10 18:37:44 +07:00
91c766de86 Add admin endpoint to delete bundle backtest requests and implement related UI functionality + Add job resilient 2025-11-10 12:28:07 +07:00
0861e9a8d2 Add admin page for bundle 2025-11-10 11:50:20 +07:00
7e52b7a734 Improve workers for backtests 2025-11-10 01:44:33 +07:00
747bda2700 Update jobs 2025-11-09 04:48:15 +07:00
7e08e63dd1 Add genetic backtest to worker 2025-11-09 03:32:08 +07:00
7dba29c66f Add jobs 2025-11-09 02:08:31 +07:00
f16e4e0d48 fix isAdmin 2025-11-08 02:37:31 +07:00
e0795677e4 Add whitelisting and admin 2025-11-07 23:46:48 +07:00
21110cd771 Add whitelisting service + update the jwt valid audience 2025-11-07 19:38:33 +07:00
5afddb895e Add async for saving backtests 2025-11-05 16:58:46 +07:00
28f2daeb05 Update the keep for influx request 2025-10-28 19:06:33 +07:00
7676a9f1ac Fix influxdb candle fetch 2025-10-28 18:27:56 +07:00
92c28367cf Add Versionning for bundle backtest request 2025-10-23 13:37:53 +07:00
f49f75ede0 Add migrations 2025-10-16 17:19:47 +07:00
472c507801 Add netpnl and initialBalance to backtests 2025-10-16 17:19:22 +07:00
b3f3bccd72 Add delete backtests by filters 2025-10-15 00:28:25 +07:00
48c2d20d70 Add sort by name 2025-10-14 20:03:20 +07:00