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
- Bot management
- Backtesting
- MoneyManagement
- Strategies systems
- WebUI
- Robust trading management
- Adaptive trading
- Account management
- Workers (prices, backtests, volumes)
- Bot backup
v2 - The custody back
- Web3 Authentification
- Hot-wallets management
- Chainlink and Subgraphs feeds
- GMX Contracts integration
- GMX v2 Contracts integration
v2.1
- Tools : RektFees, Spotlight
- 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
- Market making
v3 - The bitcoin protocol
- Integrate LNMarkets
v4 - The omnipotence
- Connect to Blockstream Satellite
Stack
Architecture
Front-end
- Vite.JS
- Tailwindcss
- Daisy UI
- HeroIcon
- Toastify
- Tradingview Lightweight-charts
- Ploty
- SignalR
- Wagmi
- Connectkit
Back-end
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
- Sign message with Web3 wallet
- Submit signed message to receive JWT token
- Use JWT token for all subsequent API calls
Endpoints
POST /User- Create JWT token with Web3 signatureGET /User- Get current user informationPUT /User/agent-name- Update agent namePUT /User/avatar- Update avatar URLPUT /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 accountGET /Account/accounts- Get all user accountsGET /Account/balances- Get account balancesGET /Account- Get specific account by nameGET /Account/{name}/gmx-claimable-summary- Get GMX claimable feesDELETE /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 strategyGET /MoneyManagement/moneymanagements- Get all money management strategiesGET /MoneyManagement- Get specific money management by nameDELETE /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 userPOST /Scenario- Create new scenarioPUT /Scenario- Update existing scenarioDELETE /Scenario- Delete scenario by name
Indicator Endpoints
GET /Scenario/indicator- Get all indicators for userPOST /Scenario/indicator- Create new indicatorPUT /Scenario/indicator- Update existing indicatorDELETE /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
ScenarioNameto reference scenarios saved in database - Dynamic Scenarios: Pass complete
Scenarioobject directly without saving to database - Dynamic scenarios are useful for testing custom configurations or one-time strategies
Money Management Configuration:
- Saved Strategies: Use
MoneyManagementNameto reference saved money management strategies - Dynamic Strategies: Pass complete
MoneyManagementobject directly without saving - Allows for custom risk parameters without cluttering the saved strategies list
Endpoints
POST /Bot/Start- Start a new botGET /Bot/Stop- Stop specific botGET /Bot/Restart- Restart specific botDELETE /Bot/Delete- Delete botPOST /Bot/stop-all- Stop all user botsPOST /Bot/restart-all- Restart all user botsGET /Bot/ToggleIsForWatching- Toggle watch modeGET /Bot- Get all active botsPOST /Bot/OpenPosition- Manually open positionPOST /Bot/ClosePosition- Manually close positionPUT /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
MaxPositionTimeHoursis 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)
CloseEarlyWhenProfitableallows immediate closure when profitable instead of waiting full duration
Profit-Controlled Flipping:
FlipOnlyWhenInProfitensures safer trading by only flipping profitable positions- Helps prevent cascading losses in volatile markets
Synth API Integration:
UseSynthApienables 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
Scenarioobject directly or useScenarioNameto load from database - Direct
Scenarioobjects are useful for testing custom configurations without saving ScenarioNameis typically used for live trading with saved scenarios
Money Management Configuration:
- Either provide a
MoneyManagementobject directly or useMoneyManagementNamein 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 toFlippingBotto enable position flipping capabilitiesFlipPosition: 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:
- Opens initial position based on scenario signals
- Monitors for opposite direction signals from the same scenario
- When opposite signal occurs:
- If
FlipOnlyWhenInProfitis true: Only flips if current position is profitable - If
FlipOnlyWhenInProfitis false: Flips regardless of profit status
- If
- Closes current position and immediately opens new position in opposite direction
- 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
TradingBotConfigfor 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
ScenarioNameto reference scenarios saved in database - Dynamic Scenarios: Pass complete
Scenarioobject 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
MoneyManagementNameto reference saved money management strategies - Dynamic Strategies: Pass complete
MoneyManagementobject 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 userGET /Backtest/{id}- Get specific backtest by IDDELETE /Backtest- Delete backtest by IDPOST /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:
- Consistent profitability over high-risk gains
- Risk management through drawdown control based on trading balance
- Statistical significance through adequate trade counts
- Timeframe-appropriate expectations for recovery and duration
- Cost efficiency through fee management relative to PnL
- Realistic performance through dynamic penalties
- 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:
{
"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 metadataGET /Data/Spotlight- Get market spotlight overviewGET /Data/GetCandles- Get historical candle dataGET /Data/GetStrategiesStatistics- Get platform-wide strategy statisticsGET /Data/GetTopStrategies- Get top performing strategiesGET /Data/GetUserStrategies- Get user's strategy detailsGET /Data/GetUserStrategy- Get specific user strategyGET /Data/GetPlatformSummary- Get comprehensive platform summaryGET /Data/GetAgentBalances- Get agent balance historyGET /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 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:
- Create a Privy account at https://console.privy.io/
- Create a new app in the Privy dashboard
- Copy your Privy App ID to the
.envfile:
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:
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.
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
.jsfile extensions - JSON imports require proper type assertions
We provide utility scripts that automatically handle these requirements:
# 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.
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.
