* Start building with orlean

* Add missing file

* Serialize grain state

* Remove grain and proxies

* update and add plan

* Update a bit

* Fix backtest grain

* Fix backtest grain

* Clean a bit
This commit is contained in:
Oda
2025-07-30 11:03:30 +02:00
committed by GitHub
parent d281d7cd02
commit 3de8b5e00e
59 changed files with 2626 additions and 677 deletions

329
CLAUDE.md
View File

@@ -1,165 +1,204 @@
# CLAUDE.md
# Managing Apps - Claude Code Guidelines
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
This is a quantitative finance application with .NET backend and React TypeScript frontend, focusing on algorithmic trading, market indicators, and financial mathematics.
## Common Development Commands
## Core Architecture Principles
### Backend (.NET)
### Quantitative Finance Requirements
- **IMPORTANT**: Use `decimal` for all monetary calculations (never `double` or `float`)
- Implement proven financial mathematics (Black-Scholes, Monte Carlo, etc.)
- Optimize time-series processing for tick data/OHLCV series
- Validate models with historical backtesting frameworks
- Maintain audit trails for all financial calculations
- Prioritize numerical precision in all calculations
### Backend (.NET/C#) Guidelines
#### Code Style and Structure
- Write concise, idiomatic C# code following .NET conventions
- Use object-oriented and functional programming patterns appropriately
- Prefer LINQ and lambda expressions for collection operations
- Use descriptive variable and method names (e.g., `IsUserSignedIn`, `CalculateTotal`)
- Structure files according to .NET conventions (Controllers, Models, Services, etc.)
#### Naming Conventions
- **PascalCase**: Class names, method names, public members
- **camelCase**: Local variables, private fields
- **UPPERCASE**: Constants
- **Prefix interfaces with "I"**: `IUserService`, `IAccountRepository`
#### C# and .NET Usage
- Use C# 10+ features (record types, pattern matching, null-coalescing assignment)
- Leverage built-in ASP.NET Core features and middleware
- Use `var` for implicit typing when type is obvious
- Use MongoDb and Influxdb for database operations
#### Architecture Layers (YOU MUST FOLLOW)
1. **Controller****Application****Repository** (NEVER inject repository in controllers)
2. Always implement methods you create
3. Check existing code before creating new objects/methods
4. Update all layers when necessary (database to frontend)
#### Error Handling and Validation
- Use exceptions for exceptional cases, not control flow
- Implement proper error logging with .NET logging
- Use Data Annotations or Fluent Validation for model validation
- Return appropriate HTTP status codes and consistent error responses
- Services in `services/` directory must throw user-friendly errors for tanStackQuery
#### API Design
- Follow RESTful API design principles
- Use attribute routing in controllers
- Implement versioning for APIs
- Use Swagger/OpenAPI for documentation
#### Performance Optimization
- Use `async/await` for I/O-bound operations
- Implement caching strategies (IMemoryCache or distributed caching)
- Use efficient LINQ queries, avoid N+1 query problems
- Implement pagination for large datasets
### Frontend (React/TypeScript) Guidelines
#### Component Structure
- Use functional components with TypeScript interfaces
- Use declarative JSX
- Use `function`, not `const` for components
- Use DaisyUI Tailwind Aria for components and styling
- Implement responsive design with Tailwind CSS (mobile-first approach)
#### File Organization
- Use lowercase with dashes for directories: `components/auth-wizard`
- Place static content and interfaces at file end
- Use content variables for static content outside render functions
- Favor named exports for components
#### State Management
- Minimize `use client`, `useEffect`, and `setState`
- Favor React Server Components (RSC)
- Wrap client components in Suspense with fallback
- Use dynamic loading for non-critical components
- Use `useActionState` with react-hook-form for form validation
#### Error Handling
- Model expected errors as return values (avoid try/catch for expected errors)
- Use error boundaries for unexpected errors (`error.tsx`, `global-error.tsx`)
- Use `useActionState` to manage errors and return them to client
#### Component Library
- **DO NOT** reference new React libraries if components exist in `mollecules` or `atoms`
- Check existing components before creating new ones
## Development Workflow
### Build and Run Commands
```bash
# Build entire solution
dotnet build src/Managing.sln
# Backend
dotnet build
dotnet run --project src/Managing.Api
# Run main API (port 80/443)
dotnet run --project src/Managing.Api/Managing.Api.csproj
# Frontend
npm run build
npm run dev
# Run worker API (port 81/444)
dotnet run --project src/Managing.Api.Workers/Managing.Api.Workers.csproj
# Run tests
dotnet test src/Managing.Application.Tests/
dotnet test src/Managing.Infrastructure.Tests/
# Run specific test
dotnet test --filter "TestMethodName"
# Database migrations
dotnet ef database update --project src/Managing.Infrastructure.Database/Managing.Infrastructure.Databases.csproj --context ManagingDbContext
dotnet ef migrations add <MigrationName> --project src/Managing.Infrastructure.Database/Managing.Infrastructure.Databases.csproj --context ManagingDbContext
# Regenerate API client (after API changes)
# Regenerate API client (after backend changes)
cd src/Managing.Nswag && dotnet build
```
### Frontend (React/TypeScript)
```bash
cd src/Managing.WebApp
### API Client Generation
1. **NEVER** update `ManagingApi.ts` manually
2. After backend endpoint changes:
- Run the Managing.Api project
- Execute: `cd src/Managing.Nswag && dotnet build`
- This regenerates `ManagingApi.ts` automatically
# Install dependencies
npm install
### Testing
- Write unit tests using xUnit for backend
- Use Mock or NSubstitute for mocking dependencies
- Implement integration tests for API endpoints
# Development server
npm run dev
## Security Guidelines
- **IMPORTANT**: Handle sensitive data carefully (API keys, private keys, etc.)
- Implement proper authentication and authorization
- Use secure communication protocols
- Validate all user inputs
# Build for production
npm run build
## Database Guidelines
- Use PostgreSQL for relational data
- Use InfluxDB for time-series data (candles, metrics)
- Use MongoDB for document storage
- Implement proper migrations
# Linting and type checking
npm run lint
npm run typecheck
## Orleans Integration (Co-Hosting)
- Use `IGrainFactory` instead of `IClusterClient` for co-hosting scenarios
- Orleans automatically provides `IGrainFactory` when using `UseOrleans()`
- Avoid circular dependency issues by not manually registering `IClusterClient`
- Use Orleans grains for high-availability trading bots
# Tests
npm run test
## Common Patterns
### Backend Service Pattern
```csharp
public class ExampleService : IExampleService
{
private readonly IExampleRepository _repository;
private readonly ILogger<ExampleService> _logger;
public ExampleService(IExampleRepository repository, ILogger<ExampleService> logger)
{
_repository = repository;
_logger = logger;
}
public async Task<Example> CreateExampleAsync(ExampleRequest request)
{
// Implementation
}
}
```
### Full Stack Development
```bash
# Quick start with Docker
./scripts/build_and_run.sh
### Frontend Component Pattern
```typescript
interface ComponentProps {
isLoading: boolean;
data: SomeType[];
}
# Alternative using Aspire
cd src && ./run-aspire.sh
function Component({ isLoading, data }: ComponentProps): JSX.Element {
if (isLoading) return <Loader />;
return (
<div className="container mx-auto">
{/* Component content */}
</div>
);
}
export default Component;
```
## Architecture Overview
## File Structure Conventions
```
src/
├── Managing.Api/ # API Controllers
├── Managing.Application/ # Business Logic
├── Managing.Domain/ # Domain Models
├── Managing.Infrastructure/ # Data Access
└── Managing.WebApp/ # React Frontend
└── src/
├── components/
│ ├── atoms/ # Basic components
│ ├── mollecules/ # Composite components
│ └── organism/ # Complex components
└── services/ # API calls
```
### Clean Architecture Pattern
The codebase follows Clean Architecture with clear layer separation:
- **Domain** (`Managing.Domain`): Business entities and core rules
- **Application** (`Managing.Application*`): Use cases, commands, and business orchestration
- **Infrastructure** (`Managing.Infrastructure.*`): External integrations (databases, Web3, messaging)
- **Presentation** (`Managing.Api*`): REST APIs and controllers
### Service Architecture
Multiple coordinated services handle different concerns:
- **Managing.Api**: Main trading operations, bot management, backtesting
- **Managing.Api.Workers**: Background workers for price data, genetic algorithms, statistics
- **Managing.Web3Proxy**: Node.js service for Web3/GMX blockchain interactions
- **Managing.WebApp**: React frontend with real-time SignalR updates
### Data Storage Strategy (Polyglot Persistence)
- **PostgreSQL**: Transactional data (users, bots, positions, scenarios, backtests)
- **InfluxDB**: Time-series data (OHLCV candles, agent balances, performance metrics)
- **MongoDB**: Document storage for certain data types
### Key Domain Concepts
- **Bot**: Abstract base with lifecycle management for trading automation
- **Position**: Trading positions with PnL tracking and trade history
- **Scenario**: Collections of technical indicators defining trading strategies
- **Indicator**: Technical analysis tools (RSI, MACD, EMA, SuperTrend, etc.)
- **MoneyManagement**: Risk parameters (stop loss, take profit, position sizing)
- **Account**: Multi-exchange trading accounts (CEX, GMX V2, Privy wallets)
## Development Patterns
### Adding New Features
1. **Domain First**: Create entities in `Managing.Domain`
2. **Application Layer**: Add services/command handlers in `Managing.Application`
3. **Infrastructure**: Implement repositories and external integrations
4. **API Layer**: Add controllers and endpoints
5. **Frontend**: Update React components and API client
### Bot Development
- Inherit from `Bot` base class in `Managing.Domain/Bots/`
- Implement `SaveBackup()` and `LoadBackup()` for persistence
- Use dependency injection pattern for services
- Follow worker pattern for background execution
### Adding Technical Indicators
1. Create indicator class implementing `IIndicator`
2. Add to `IndicatorType` enum in `Managing.Common`
3. Register in DI container via `ApiBootstrap`
4. Implement calculation logic in `TradingService`
### Database Changes
1. Update entities in domain layer
2. Modify `ManagingDbContext` with new DbSets
3. Generate EF Core migration
4. Update repository interfaces and implementations
5. Consider InfluxDB for time-series data
### Web3 Integration
- GMX V2 interactions go through `Managing.Web3Proxy` Node.js service
- Use `Managing.Infrastructure.Web3` for .NET integration
- Privy handles wallet management and authentication
## Configuration & Environment
### Key Configuration Files
- `src/Managing.Api/appsettings.*.json`: Main API configuration
- `src/Managing.Api.Workers/appsettings.*.json`: Worker configuration
- `src/Managing.WebApp/.env`: Frontend environment variables
### Environment-Specific Deployments
- Development: `appsettings.Development.json`
- Sandbox: `appsettings.Sandbox.json`
- Production: `appsettings.Production.json`
- Docker: `appsettings.Oda-docker.json`
## Important Development Guidelines
### Quantitative Finance Principles
- Use `decimal` for all monetary calculations (never `float` or `double`)
- Implement proper audit trails for financial operations
- Validate trading strategies with historical backtesting
- Optimize time-series processing for performance
### Code Architecture Rules
- Follow Controller → Application → Repository pattern (never inject repositories directly into controllers)
- Use CQRS pattern with command handlers for complex operations
- Implement proper error handling with user-friendly messages
- Maintain separation between domain logic and infrastructure concerns
### API Development
- Follow RESTful conventions
- Use attribute routing in controllers
- Return appropriate HTTP status codes
- Implement proper validation using Data Annotations
### Testing Strategy
- Unit tests focus on domain logic and indicators
- Integration tests for external service interactions
- Use data-driven testing with JSON fixtures for backtesting scenarios
## Real-time Features
- SignalR hubs provide live updates for trading data, bot status, and market information
- Frontend uses reactive patterns with real-time price feeds and position updates
## Important Reminders
- Always implement methods you create
- Check existing code before creating new functionality
- Update multiple layers when necessary
- Build project after finishing edits
- Follow the controller → application → repository pattern
- Use existing components in mollecules/atoms before adding new libraries
- Use `IGrainFactory` for Orleans co-hosting (not `IClusterClient`)