# 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 |
| `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 (default: false) |
| `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

**Bot Behavior Control:**
- `IsForWatchingOnly` controls whether the bot executes actual trades or only analyzes and generates signals
- `FlipPosition` controls whether the bot can flip positions when opposite signals occur (default: false)
- `FlipOnlyWhenInProfit` ensures safer trading by only flipping profitable positions when flipping is enabled
- 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 Behavior Configuration

Trading bots support flexible behavior configuration through boolean flags rather than predefined types:

#### Watch-Only Mode
- **`IsForWatchingOnly`**: When `true`, the bot analyzes market conditions and generates signals but does not execute actual trades
- Perfect for strategy testing, signal validation, or paper trading
- Useful for developing confidence in a strategy before committing real capital

#### Position Flipping
- **`FlipPosition`**: When `true`, enables the bot to flip positions when opposite signals are triggered
- **`FlipOnlyWhenInProfit`**: Safety feature that only allows flipping when current position is profitable (default: true)

#### How Position Flipping Works

**When Flipping is Enabled (`FlipPosition = true`):**
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

**When Flipping is Disabled (`FlipPosition = false`):**
- Opens position → Waits for exit signal → Closes → Cooldown → Opens new position in same direction
- More conservative approach with cooldown periods between trades
- Reduces frequency of trades and potential whipsaw losses

This simplified configuration provides clear control over bot behavior 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.)

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