# Introduction

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..

---

# Roadmap

## v1 - The base

- [x] Bot management
- [x] Backtesting
- [x] MoneyManagement
- [x] Strategies systems
- [x] WebUI
- [x] Robust trading management
- [x] Adaptive trading
- [x] Account management
- [x] Workers (prices, backtests, volumes)
- [x] Bot backup

## 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
- [x] Funding Rates
- [ ] Strategies optimisation
- [ ] Delta neutral positions
- [ ] Address tracking
- [ ] Trading desk
- [ ] Metrics (backtests, portofolio)
- [ ] Account Abstraction Layer
- [ ] 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/)
- [HeroIcon](https://heroicons.com/)
- [Toastify](https://fkhadra.github.io/react-toastify/introduction)
- [Tradingview Lightweight-charts](https://github.com/tradingview/lightweight-charts)
- [Ploty](https://github.com/plotly/react-plotly.js)
- [SignalR](https://github.com/dotnet/aspnetcore/tree/main/src/SignalR#readme)
- [Wagmi](https://wagmi.sh/)
- [Connectkit](https://github.com/family/connectkit)

## Back-end

- .NET 8
- [SignalR](https://dotnet.microsoft.com/en-us/apps/aspnet/signalr)
- [Discord.Net](https://github.com/discord-net/Discord.Net)
- [CryptoExchange.Net](https://github.com/JKorf/CryptoExchange.Net)
- [Stock Indicators](https://daveskender.github.io/Stock.Indicators/)
- [InfluxDb](https://github.com/influxdata/influxdb-client-csharp)
- [Nethereum](https://github.com/Nethereum/Nethereum)

---

# API Features

## User Management (`UserController`)

- **JWT Authentication**: Secure user authentication using Web3 signatures
- **Profile Management**: Update agent name, avatar URL, and Telegram channel
- **Current User Information**: Retrieve authenticated user details

### Authentication Flow
1. Sign message with Web3 wallet
2. Submit signed message to receive JWT token
3. Use JWT token for all subsequent API calls

### Endpoints
- `POST /User` - Create JWT token with Web3 signature
- `GET /User` - Get current user information
- `PUT /User/agent-name` - Update agent name
- `PUT /User/avatar` - Update avatar URL
- `PUT /User/telegram-channel` - Update Telegram channel

## Account Management (`AccountController`)

- **Account Creation**: Create trading accounts linked to user profiles
- **Account Retrieval**: Get all accounts or specific account by name
- **Balance Monitoring**: Retrieve real-time account balances
- **GMX Integration**: Get claimable fees summary from GMX contracts
- **Account Deletion**: Remove accounts from user profile

### Endpoints
- `POST /Account` - Create new account
- `GET /Account/accounts` - Get all user accounts
- `GET /Account/balances` - Get account balances
- `GET /Account` - Get specific account by name
- `GET /Account/{name}/gmx-claimable-summary` - Get GMX claimable fees
- `DELETE /Account` - Delete account by name

## Money Management (`MoneyManagementController`)

- **Strategy Creation**: Define risk management parameters (StopLoss, TakeProfit, position sizing)
- **Strategy Updates**: Modify existing money management configurations
- **Strategy Retrieval**: Access all strategies or specific strategy by name
- **Strategy Deletion**: Remove unused money management configurations

### Endpoints
- `POST /MoneyManagement` - Create or update money management strategy
- `GET /MoneyManagement/moneymanagements` - Get all money management strategies
- `GET /MoneyManagement` - Get specific money management by name
- `DELETE /MoneyManagement` - Delete money management strategy

## Scenarios & Indicators (`ScenarioController`)

### Scenarios
- **Build Scenarios**: Combine multiple indicators into trading strategies
- **Update Scenarios**: Modify existing scenario configurations
- **Scenario Management**: Create, retrieve, update, and delete scenarios
- **Loopback Period**: Configure historical data lookback for scenario evaluation

### Indicators
- **Indicator Creation**: Build custom technical indicators with specific parameters
- **Indicator Updates**: Modify existing indicator configurations
- **Comprehensive Parameters**: Support for period, multiplier, fast/slow periods, signal periods, etc.
- **Indicator Types**: Support for various technical indicators (MACD, RSI, EMA, SuperTrend, etc.)

### Scenario Endpoints
- `GET /Scenario` - Get all scenarios for user
- `POST /Scenario` - Create new scenario
- `PUT /Scenario` - Update existing scenario
- `DELETE /Scenario` - Delete scenario by name

### Indicator Endpoints
- `GET /Scenario/indicator` - Get all indicators for user
- `POST /Scenario/indicator` - Create new indicator
- `PUT /Scenario/indicator` - Update existing indicator
- `DELETE /Scenario/indicator` - Delete indicator by name

### Available Indicators

| Indicator             | Type | Description                                                                                                                        | Parameters                                |
|----------------------|------|------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------|
| RsiDivergence        | Signal | Detects RSI divergence patterns where price and RSI move in opposite directions | Period (recommended: 4-6)               |
| RsiDivergenceConfirm | Signal | Enhanced RSI divergence that waits for confirmation before triggering signals | Period (recommended: 4-6)               |
| MacdCross            | Signal | Triggers signals when MACD histogram crosses zero line | FastPeriods: 12, SlowPeriods: 26, SignalPeriods: 9 |
| EmaCross             | Signal | Triggers signals when price crosses EMA line | Period (recommended: 200)               |
| EmaTrend             | Trend | Returns trend signals based on price position relative to EMA | Period (recommended: 200)               |
| SuperTrend           | Signal | Triggers signals when price crosses SuperTrend indicator | Period: 10, Multiplier: 3               |
| ChandelierExit       | Signal | Exit strategy based on highest/lowest values over a period with ATR multiplier | Period: 22, Multiplier: 3               |
| StochRsiTrend        | Trend | Trend signals based on Stochastic RSI levels (>80% = Short, <20% = Long) | Period (recommended: 22)                |
| Stc                  | Signal | Schaff Trend Cycle - signals when crossing 75% (Short) or 25% (Long) levels | CyclePeriods, FastPeriods, SlowPeriods  |
| ThreeWhiteSoldiers   | Signal | Candlestick pattern recognition for bullish reversal signals | Lookback Period: 3                      |
| LaggingStc           | Signal | Enhanced STC with lagging mechanism for reduced false signals | CyclePeriods, FastPeriods, SlowPeriods  |
| SuperTrendCrossEma   | Signal | Combined indicator using both SuperTrend and EMA crossovers | SuperTrend Period/Multiplier + EMA Period |
| DualEmaCross         | Signal | Dual EMA crossover system using fast and slow EMAs | FastPeriods, SlowPeriods                |

#### Signal Types
- **Signal**: Generates entry/exit signals for specific trading actions
- **Trend**: Provides directional trend information for position bias
- **Context**: Offers additional market context for decision making

#### Parameter Guidelines
- **Period**: Number of candles for calculation (higher = smoother, lower = more responsive)
- **Multiplier**: ATR multiplier for volatility-based indicators (higher = wider bands)
- **Fast/Slow Periods**: For dual-line indicators, fast reacts quickly, slow provides stability
- **Cycle Periods**: For oscillators, defines the cycle length for calculations

## Bot Management (`BotController`)

### Core Bot Operations
- **Start Bots**: Deploy bots with comprehensive configuration
- **Stop/Restart Bots**: Individual or bulk bot control
- **Delete Bots**: Remove bots and their associated data
- **Configuration Updates**: Real-time bot parameter updates without restart

### Advanced Bot Features
- **Manual Trading**: Open/close positions manually
- **Watch Mode**: Signal-only mode without actual trading
- **User Ownership**: Security validation ensuring users only control their own bots
- **Real-time Updates**: Live bot status and performance monitoring

### Flexible Configuration Options

**Scenario Configuration:**
- **Saved Scenarios**: Use `ScenarioName` to reference scenarios saved in database
- **Dynamic Scenarios**: Pass complete `Scenario` object directly without saving to database
- Dynamic scenarios are useful for testing custom configurations or one-time strategies

**Money Management Configuration:**
- **Saved Strategies**: Use `MoneyManagementName` to reference saved money management strategies
- **Dynamic Strategies**: Pass complete `MoneyManagement` object directly without saving
- Allows for custom risk parameters without cluttering the saved strategies list

### Endpoints
- `POST /Bot/Start` - Start a new bot
- `GET /Bot/Stop` - Stop specific bot
- `GET /Bot/Restart` - Restart specific bot
- `DELETE /Bot/Delete` - Delete bot
- `POST /Bot/stop-all` - Stop all user bots
- `POST /Bot/restart-all` - Restart all user bots
- `GET /Bot/ToggleIsForWatching` - Toggle watch mode
- `GET /Bot` - Get all active bots
- `POST /Bot/OpenPosition` - Manually open position
- `POST /Bot/ClosePosition` - Manually close position
- `PUT /Bot/UpdateConfig` - Update bot configuration

### TradingBotConfig Documentation

The `TradingBotConfig` class defines all configuration parameters for trading bots. Below are the available properties:

#### Required Properties

| Property | Type | Description |
|----------|------|-------------|
| `AccountName` | `string` | Name of the trading account to use |
| `MoneyManagement` | `MoneyManagement` | Risk management strategy configuration |
| `Ticker` | `Ticker` | Trading pair symbol (e.g., BTCUSDT) |
| `Timeframe` | `Timeframe` | Candle timeframe for analysis |
| `IsForWatchingOnly` | `bool` | If true, bot only sends signals without trading |
| `BotTradingBalance` | `decimal` | Initial trading balance for the bot |
| `BotType` | `BotType` | Type of trading bot behavior |
| `IsForBacktest` | `bool` | Whether this config is for backtesting |
| `CooldownPeriod` | `int` | Number of candles to wait before opening new position in same direction |
| `MaxLossStreak` | `int` | Maximum consecutive losses before requiring opposite direction signal (0 = no limit) |
| `FlipPosition` | `bool` | Whether the bot can flip positions |
| `Name` | `string` | Unique identifier/name for the bot |
| `FlipOnlyWhenInProfit` | `bool` | Only flip positions when current position is profitable (default: true) |

#### Optional Properties

| Property | Type | Description | Default |
|----------|------|-------------|---------|
| `Scenario` | `Scenario` | Scenario object with strategies (takes precedence over ScenarioName) | null |
| `ScenarioName` | `string` | Name of scenario to load from database | null |
| `MaxPositionTimeHours` | `decimal?` | Maximum hours a position can stay open before auto-close | null |
| `CloseEarlyWhenProfitable` | `bool` | Close position early when profitable (requires MaxPositionTimeHours) | false |
| `UseSynthApi` | `bool` | Enable Synth API for probabilistic price forecasts | false |
| `UseForPositionSizing` | `bool` | Use Synth predictions for position sizing adjustments | true |
| `UseForSignalFiltering` | `bool` | Use Synth predictions for signal filtering | true |
| `UseForDynamicStopLoss` | `bool` | Use Synth predictions for dynamic stop-loss/take-profit | true |

#### Advanced Configuration Details

**Time-Based Position Management:**
- When `MaxPositionTimeHours` is set, positions are automatically closed after the specified time
- Only closes when position is in profit or at breakeven (never closes at a loss due to time)
- `CloseEarlyWhenProfitable` allows immediate closure when profitable instead of waiting full duration

**Profit-Controlled Flipping:**
- `FlipOnlyWhenInProfit` ensures safer trading by only flipping profitable positions
- Helps prevent cascading losses in volatile markets

**Synth API Integration:**
- `UseSynthApi` enables probabilistic price forecasting and risk assessment
- Sub-properties control specific Synth features (position sizing, signal filtering, dynamic stops)
- Provides AI-enhanced trading decisions when enabled

**Scenario Configuration:**
- Either provide a `Scenario` object directly or use `ScenarioName` to load from database
- Direct `Scenario` objects are useful for testing custom configurations without saving
- `ScenarioName` is typically used for live trading with saved scenarios

**Money Management Configuration:**
- Either provide a `MoneyManagement` object directly or use `MoneyManagementName` in the request
- Direct objects allow for one-time custom risk parameters
- Saved strategies via name reference are ideal for reusable configurations

### Bot Configuration Parameters

| Parameter                | Description                                                                                           | Default |
|--------------------------|-------------------------------------------------------------------------------------------------------|---------|
| MaxPositionTimeHours     | Maximum time (in hours) a position can stay open. Closes only when in profit/breakeven. Null = disabled | null    |
| FlipOnlyWhenInProfit     | Only flip positions when current position is profitable                                               | true    |
| CooldownPeriod           | Number of candles to wait before opening new position in same direction                               | 10      |
| MaxLossStreak            | Maximum consecutive losses before requiring opposite direction signal. 0 = no limit                   | 0       |
| CloseEarlyWhenProfitable | Close positions early when profitable (requires MaxPositionTimeHours)                                | false   |
| BotTradingBalance        | Initial trading balance for the bot                                                                   | Required |

### Bot Types

The `BotType` enum in `TradingBotConfig` defines the following trading bot behaviors:

| Type        | Description                                                                            |
|-------------|----------------------------------------------------------------------------------------|
| SimpleBot   | Basic bot implementation for simple trading strategies                                 |
| ScalpingBot | Opens positions and waits for cooldown period before opening new ones in same direction |
| FlippingBot | Advanced bot that can flip positions when opposite signals are triggered              |

#### Flipping Mode Configuration

The flipping behavior is controlled by several `TradingBotConfig` properties:

- **`BotType`**: Set to `FlippingBot` to enable position flipping capabilities
- **`FlipPosition`**: Boolean flag that enables/disables position flipping (automatically set based on BotType)
- **`FlipOnlyWhenInProfit`**: Safety feature that only allows flipping when current position is profitable (default: true)

#### How Flipping Works

**FlippingBot Behavior:**
1. Opens initial position based on scenario signals
2. Monitors for opposite direction signals from the same scenario
3. When opposite signal occurs:
   - If `FlipOnlyWhenInProfit` is true: Only flips if current position is profitable
   - If `FlipOnlyWhenInProfit` is false: Flips regardless of profit status
4. Closes current position and immediately opens new position in opposite direction
5. Continues this cycle for the duration of the bot's operation

**ScalpingBot vs FlippingBot:**
- **ScalpingBot**: Opens position → Waits for exit signal → Closes → Cooldown → Opens new position
- **FlippingBot**: Opens position → Monitors for opposite signals → Flips immediately (no cooldown between flips)

This configuration allows for more aggressive trading strategies while maintaining risk management through the profit-controlled flipping mechanism.

## Backtesting (`BacktestController`)

### Backtest Operations
- **Run Backtests**: Execute historical strategy testing with comprehensive parameters
- **Retrieve Results**: Access backtest results with complete configuration details
- **Delete Backtests**: Remove old backtest data
- **Save/Load**: Optional saving of backtest results for future reference

### Enhanced Backtest Features
- **Complete Configuration**: Backtests include full `TradingBotConfig` for easy bot deployment
- **Advanced Parameters**: Support for all bot configuration parameters in backtests
- **Date Range Testing**: Flexible start/end date selection
- **Money Management Integration**: Test with specific money management strategies
- **Watch Mode**: Run backtests without executing trades (signal analysis only)

### Flexible Configuration Options

**Scenario Configuration for Backtests:**
- **Saved Scenarios**: Use `ScenarioName` to reference scenarios saved in database
- **Dynamic Scenarios**: Pass complete `Scenario` object directly in the backtest request
- Dynamic scenarios are perfect for testing custom indicator combinations without saving them
- Allows rapid experimentation with different strategy configurations

**Money Management Configuration for Backtests:**
- **Saved Strategies**: Use `MoneyManagementName` to reference saved money management strategies  
- **Dynamic Strategies**: Pass complete `MoneyManagement` object directly in the request
- Enables testing various risk parameters without cluttering saved strategies
- Ideal for optimization testing with different stop-loss/take-profit configurations

### Endpoints
- `GET /Backtest` - Get all backtests for user
- `GET /Backtest/{id}` - Get specific backtest by ID
- `DELETE /Backtest` - Delete backtest by ID
- `POST /Backtest/Run` - Run new backtest

### Backtest Parameters
- **Exchange**: Target exchange for historical data
- **Ticker**: Trading pair symbol
- **Timeframe**: Candle timeframe (1m, 5m, 15m, 1h, 4h, 1d, etc.)
- **Date Range**: Historical period for testing
- **Initial Balance**: Starting capital for backtest
- **Advanced Config**: All bot parameters (time limits, profit control, etc.)

### Backtest Scoring System

The backtest scoring system evaluates strategy performance using a comprehensive multi-factor approach with weighted components and dynamic penalties. The final score ranges from 0-100, where 100 represents optimal performance.

#### Scoring Components (Weighted Distribution)

| Component | Weight | Description |
|-----------|--------|-------------|
| **Growth Percentage** | 20% | Primary performance metric based on total return |
| **Sharpe Ratio** | 15% | Risk-adjusted return measure (multiplied by 100 for accuracy) |
| **Hodl Comparison** | 10% | Performance vs buy-and-hold strategy |
| **Win Rate** | 12% | Percentage of profitable trades (weighted by trade count) |
| **Profitability Bonus** | 8% | Additional reward for positive returns |
| **Trade Count** | 5% | Sufficient trading activity validation |
| **Recovery Time** | 2% | Time to recover from maximum drawdown |
| **Test Duration** | 3% | Adequate testing period validation |
| **Fees Impact** | 2% | Trading cost efficiency (based on PnL ratio) |
| **Risk Adjusted Return** | 23% | PnL vs MaxDD ratio based on trading balance |

#### Component Scoring Details

**Growth Percentage (20%)**
- **Negative Returns**: 0 points (no partial credit for losses)
- **0-5%**: Linear scale (0-20 points)
- **5-10%**: Accelerated scale (20-50 points)
- **10-20%**: Linear scale (50-100 points)
- **20%+**: Full score (100 points)

**Sharpe Ratio (15%)**
- **Input**: Sharpe ratio is multiplied by 100 for more accurate scoring
- **Negative**: 0 points
- **0-4**: Linear scale (0-100 points)
- **4+**: Full score (100 points)

**Hodl Comparison (10%)**
- **+5%+ better than HODL**: 100 points
- **+2-5% better**: 80-100 points
- **+0-2% better**: 40-80 points
- **-1-0% worse**: 20-40 points
- **-2 to -1% worse**: 0-20 points
- **-2%+ worse**: 0 points (handled by early exit)

**Win Rate (12%)**
- **Input**: Win rate as percentage (e.g., 23.45 for 23.45%)
- **Base Score**: Win rate converted to decimal (23.45% → 0.2345)
- **Trade Count Factor**: Full significance at 55+ trades, reduced for fewer trades
- **Minimum Trade Penalty**: 50% penalty for <10 trades

**Profitability Bonus (8%)**
- **Positive Returns**: Logarithmic bonus (max 50 points)
- **Negative Returns**: 0 points

**Trade Count (5%)**
- **<5 trades**: 0 points
- **5-10 trades**: Linear scale (0-50 points)
- **10-50 trades**: Linear scale (50-100 points)
- **50+ trades**: 100 points

**Recovery Time (2%)**
- **Timeframe-adjusted expectations**:
  - 5m: 3 days max recovery
  - 15m: 5 days max recovery
  - 30m: 10 days max recovery
  - 1h: 15 days max recovery
  - 4h: 30 days max recovery
  - 1d: 90 days max recovery

**Test Duration (3%)**
- **Timeframe-adjusted minimums**:
  - 5m: 14 days minimum
  - 15m: 28 days minimum
  - 30m: 56 days minimum
  - 1h: 84 days minimum
  - 4h: 120 days minimum
  - 1d: 90 days minimum
- **Optimal duration**: 3× minimum duration

**Fees Impact (2%)**
- **Based on**: Fees as percentage of PnL (not initial balance)
- **0-10% fees**: Linear scale (100-50 points)
- **10-20% fees**: Linear scale (50-0 points)
- **20%+ fees**: 0 points
- **Fees > PnL**: 0 points

**Risk Adjusted Return (23%)**
- **Based on**: Trading balance (not initial balance)
- **Calculation**: PnL percentage vs MaxDD percentage ratio
- **>3:1 ratio**: 100 points
- **2-3:1 ratio**: 80-100 points
- **1.5-2:1 ratio**: 60-80 points
- **1-1.5:1 ratio**: 40-60 points
- **0.5-1:1 ratio**: 20-40 points
- **<0.5:1 ratio**: 0-20 points

#### Dynamic Penalty System

The scoring system applies dynamic penalties based on performance thresholds:

**Early Exit Conditions**
- **No Trades**: Automatic 0 score
- **Negative PnL**: Automatic 0 score
- **HODL Underperformance**: Automatic 0 score if >2% worse than HODL

**Profitability Rules**
- **Negative Growth**: 10% penalty per 1% loss
- **Low Win Rate**: 50% penalty per 10% below 30% (for 10+ trades)
- **Low Profit**: 10% penalty per 1% below 2% (for 5+ trades)
- **High Drawdown**: 2% penalty per 1% above 20% of trading balance
- **Poor Risk/Reward**: 20% penalty per 0.5 ratio above 1.5:1 (MaxDD/PnL)
- **Short Test Duration**: 2% penalty per day below 30 days
- **HODL Underperformance**: 30% penalty per 1% underperformance

**Special Rules**
- **Score Clamping**: Final score clamped between 0-100
- **Error Handling**: Returns 0 for any calculation errors

#### Scoring Philosophy

The system prioritizes:
1. **Consistent profitability** over high-risk gains
2. **Risk management** through drawdown control based on trading balance
3. **Statistical significance** through adequate trade counts
4. **Timeframe-appropriate** expectations for recovery and duration
5. **Cost efficiency** through fee management relative to PnL
6. **Realistic performance** through dynamic penalties
7. **HODL outperformance** as a baseline requirement

This comprehensive approach ensures that high-scoring strategies demonstrate robust, sustainable performance across multiple dimensions rather than relying on single metrics or short-term luck.

### RunBacktestRequest Structure

The backtest request supports both saved and dynamic configurations:

```json
{
  "Config": {
    "ScenarioName": "MySavedScenario",  // OR pass Scenario object directly
    "Scenario": { /* full scenario object */ },
    "AccountName": "TestAccount",
    "Ticker": "BTCUSDT",
    "Timeframe": "OneHour",
    // ... other TradingBotConfig properties
  },
  "MoneyManagementName": "Conservative", // OR pass MoneyManagement object
  "MoneyManagement": { /* full money management object */ },
  "StartDate": "2024-01-01T00:00:00Z",
  "EndDate": "2024-02-01T00:00:00Z",
  "Balance": 10000,
  "Save": true
}
```

This flexibility allows for comprehensive strategy testing without requiring database saves for experimental configurations.

## Market Data & Analytics (`DataController`)

### Market Data
- **Ticker Information**: Available trading pairs with logos and metadata
- **Candle Data**: Historical OHLCV data for any timeframe
- **Real-time Updates**: Live price feeds via SignalR

### Platform Analytics
- **Strategies Statistics**: Platform-wide bot performance metrics
- **Top Strategies**: Best performing strategies by ROI
- **User Analytics**: Individual user strategy performance
- **Platform Summary**: Comprehensive platform statistics with time filters
- **Agent Balances**: Historical balance tracking for users
- **Best Agents**: Leaderboard of top performing users

### Endpoints
- `POST /Data/GetTickers` - Get available trading pairs with metadata
- `GET /Data/Spotlight` - Get market spotlight overview
- `GET /Data/GetCandles` - Get historical candle data
- `GET /Data/GetStrategiesStatistics` - Get platform-wide strategy statistics
- `GET /Data/GetTopStrategies` - Get top performing strategies
- `GET /Data/GetUserStrategies` - Get user's strategy details
- `GET /Data/GetUserStrategy` - Get specific user strategy
- `GET /Data/GetPlatformSummary` - Get comprehensive platform summary
- `GET /Data/GetAgentBalances` - Get agent balance history
- `GET /Data/GetBestAgents` - Get best performing agents leaderboard

### Analytics Features
- **Time Filters**: 24H, 3D, 1W, 1M, 1Y, Total
- **Performance Metrics**: ROI, PnL, win rates, volume traded
- **Caching**: Optimized response times with intelligent caching
- **Real-time Updates**: Live performance tracking

### Spotlight Data
- **Market Overview**: Comprehensive market analysis
- **Strategy Performance**: Cross-strategy performance comparison
- **Volume Analysis**: Trading volume statistics

## Privy Integration

This project uses [Privy](https://privy.io/) for wallet authentication and management. Privy provides a seamless authentication experience with support for both embedded wallets and external wallet connections.

### Supported Networks

- Ethereum Mainnet
- Arbitrum One

### Configuration

To use Privy in this project, you need to:

1. Create a Privy account at [https://console.privy.io/](https://console.privy.io/)
2. Create a new app in the Privy dashboard
3. Copy your Privy App ID to the `.env` file:

```
VITE_PRIVY_APP_ID=your-privy-app-id
```

### Features

- **Multi-chain support**: Connect to Ethereum and Arbitrum networks
- **Embedded wallets**: Create and manage wallets directly in the browser
- **Social login**: Authenticate with email, Google, and other providers
- **Seamless integration**: Works with wagmi for blockchain interactions

### Usage

The Privy provider is configured in `src/main.tsx` and can be used throughout the application with the `usePrivy` hook:

```tsx
import { usePrivy } from '@privy-io/react-auth';

function MyComponent() {
  const { user, login, logout, authenticated } = usePrivy();
  
  if (!authenticated) {
    return <button onClick={login}>Login</button>;
  }
  
  return (
    <div>
      <p>Welcome, {user.email}</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
}
```

For more information, see the [Privy documentation](https://docs.privy.io/).

# Development

## Utilities

The project includes several utility scripts to help with development:

### ESM Import Fixer

When working with ES Modules in Node.js:
- Local module imports require `.js` file extensions
- JSON imports require proper type assertions

We provide utility scripts that automatically handle these requirements:

```bash
# Fix imports in the src directory (add .js extensions and JSON assertions)
npm run fix-imports

# Update JSON imports to use modern "with { type: "json" }" syntax
npm run update-json-imports

# Run both scripts in sequence (fix imports then update JSON import syntax)
npm run prepare-code
```

For more details, see the [scripts documentation](scripts/README.md).

# Entity Framework Core Migrations

To manage database schema changes for the backend, use the following EF Core commands from the project root:

## Add a Migration

```
dotnet ef migrations add <MigrationName> --project src/Managing.Infrastructure.Database/Managing.Infrastructure.Databases.csproj --context ManagingDbContext
```

## Update the Database

```
dotnet ef database update --project src/Managing.Infrastructure.Database/Managing.Infrastructure.Databases.csproj --context ManagingDbContext
```

- Replace `<MigrationName>` with your desired migration name.
- These commands will build the project and apply migrations to the configured database.
- If you drop a table or reset the schema, you may need to remove old migrations and create a new one.

