Browse Source

Enhance trading documentation and commands - Updated README and command references to include new automatic stop loss features for long and short positions. Improved clarity on command usage and added new commands for risk metrics and version information. Adjusted monitoring intervals for real-time notifications and refined project structure documentation.

Carles Sentis 4 days ago
parent
commit
dffa441997
5 changed files with 252 additions and 64 deletions
  1. 13 3
      README.md
  2. 3 1
      docs/README.md
  3. 168 26
      docs/commands.md
  4. 53 29
      docs/project-structure.md
  5. 15 5
      docs/setup.md

+ 13 - 3
README.md

@@ -118,8 +118,13 @@ ManualTrader/
 
 ### **Trading Commands**
 ```
-/buy 0.001 50000    # Buy 0.001 BTC at $50,000
-/sell 0.001 55000   # Sell 0.001 BTC at $55,000
+/long BTC 100           # Long BTC with $100 USDC (Market)
+/long BTC 100 50000     # Long BTC with $100 at $50,000 (Limit)
+/long BTC 100 sl:49000  # Long BTC with stop loss at $49,000
+/short ETH 50           # Short ETH with $50 USDC (Market)
+/short ETH 50 3500      # Short ETH with $50 at $3,500 (Limit)
+/short ETH 50 sl:3600   # Short ETH with stop loss at $3,600
+/exit BTC               # Close BTC position
 ```
 
 ### **Instant Action Buttons**
@@ -292,12 +297,17 @@ python utils/simple_chat_id.py
 ### Enhanced Trading Operations
 - **Multi-Platform Support**: Direct integration with Hyperliquid perpetuals trading
 - **Smart Order Management**: Long/short positions with market and limit orders
+- **Automatic Stop Loss**: Inline `sl:price` syntax for automatic stop loss placement
 - **Advanced Position Tracking**: Multi-entry/exit scenarios with weighted average calculations
+- **Price Alerts**: Real-time monitoring with customizable price alarms
 - **Integrated Analytics**: Single source of truth for position tracking and performance analysis
 - **Risk Management**: Automatic stop-loss functionality with customizable triggers
 
 ### System Architecture
 - **Unified Position Tracking**: Integrated TradingStats system provides consistent position management
 - **Real-Time Notifications**: Context-aware alerts for position opens, increases, reductions, and closes
+- **External Trade Detection**: Automatic monitoring and sync of trades made outside the bot
 - **Multi-Entry/Exit Support**: Advanced tracking for complex trading scenarios with accurate P&L calculations
-- **Data Consistency**: Single source of truth eliminates discrepancies between real-time and historical data 
+- **10-Second Monitoring**: Real-time order fill detection and automatic stop loss placement
+- **Data Consistency**: Single source of truth eliminates discrepancies between real-time and historical data
+- **Comprehensive Logging**: Advanced log management with cleanup and statistics 

+ 3 - 1
docs/README.md

@@ -48,12 +48,14 @@
 /exit BTC    # Close BTC position
 ```
 
-### **๐Ÿš€ Simplified Trading**
+### **๐Ÿš€ Enhanced Trading**
 ```bash
 /long BTC 100        # Long Bitcoin with $100 (Market)
 /long BTC 100 45000  # Long Bitcoin with $100 at $45k (Limit)
+/long BTC 100 sl:44000 # Long with automatic stop loss
 /short ETH 50        # Short Ethereum with $50 (Market)
 /short ETH 50 3500   # Short Ethereum with $50 at $3.5k (Limit)
+/short ETH 50 sl:3600 # Short with automatic stop loss
 /exit BTC            # Close Bitcoin position
 ```
 

+ 168 - 26
docs/commands.md

@@ -10,16 +10,19 @@ The most important commands to get started:
 /start       # Show main menu with quick action buttons
 /balance     # Check your account balance
 /long BTC 10 # Open long position with $10 USDC
+/long BTC 10 sl:9500 # Long with automatic stop loss
 /sl BTC 9000 # Set stop loss at $9,000
 /tp BTC 11000 # Set take profit at $11,000
 /monitoring  # Check order monitoring status
 /performance # Token performance ranking
 /daily       # Daily performance (last 10 days)
 /alarm BTC 50000 # Set price alert for BTC at $50,000
+/risk        # Advanced risk metrics
+/version     # Bot version and system info
 /help        # Full command reference
 ```
 
-**๐Ÿ’ก Auto-Notifications:** The bot automatically monitors your orders every 30 seconds and sends notifications when orders are filled!
+**๐Ÿ’ก Auto-Notifications:** The bot automatically monitors your orders every 10 seconds and sends notifications when orders are filled!
 
 ## ๐Ÿ’ผ Account Management
 
@@ -430,28 +433,40 @@ Show monthly performance breakdown for the last 10 months.
 
 ## ๐Ÿš€ Perps Trading
 
-### `/long [token] [USDC amount] [price (optional)]`
-Open a long position using market order or limit order.
+### `/long [token] [USDC amount] [price (optional)] [sl:price (optional)]`
+Open a long position using market order or limit order, with optional automatic stop loss.
 
 **Usage:**
 ```
-/long <TOKEN> <USDC_AMOUNT>           # Market order
-/long <TOKEN> <USDC_AMOUNT> <PRICE>   # Limit order
+/long <TOKEN> <USDC_AMOUNT>                    # Market order
+/long <TOKEN> <USDC_AMOUNT> <PRICE>            # Limit order
+/long <TOKEN> <USDC_AMOUNT> sl:<STOP_PRICE>    # Market order with stop loss
+/long <TOKEN> <USDC_AMOUNT> <PRICE> sl:<STOP_PRICE> # Limit order with stop loss
 ```
 
 **Examples:**
 ```
-/long BTC 100       # Long Bitcoin with $100 USDC (Market Order)
-/long BTC 100 45000 # Long Bitcoin with $100 USDC at $45,000 (Limit Order)
-/long ETH 50        # Long Ethereum with $50 USDC (Market Order)
-/long ETH 50 3200   # Long Ethereum with $50 USDC at $3,200 (Limit Order)
+/long BTC 100              # Long Bitcoin with $100 USDC (Market Order)
+/long BTC 100 45000        # Long Bitcoin with $100 USDC at $45,000 (Limit Order)
+/long BTC 100 sl:44000     # Market order with automatic stop loss at $44,000
+/long BTC 100 45000 sl:44000 # Limit order at $45,000 with stop loss at $44,000
+/long ETH 50               # Long Ethereum with $50 USDC (Market Order)
+/long ETH 50 3200          # Long Ethereum with $50 USDC at $3,200 (Limit Order)
+/long ETH 50 sl:3100       # Market order with stop loss at $3,100
+/long ETH 50 3200 sl:3100  # Limit order with stop loss at $3,100
 ```
 
+**Stop Loss Validation:**
+- For LONG positions: Stop loss price must be BELOW entry price
+- Stop loss is placed automatically when the original order fills
+- Uses `sl:price` format to distinguish from limit price
+
 **How it works:**
 1. **Market Order** (2 parameters): Fetches current market price and places market buy order
 2. **Limit Order** (3 parameters): Places limit buy order at specified price
-3. Calculates token amount: `token_amount = usdc_amount / price`
-4. Records trade in statistics
+3. **With Stop Loss**: Saves stop loss for automatic placement when order fills
+4. Calculates token amount: `token_amount = usdc_amount / price`
+5. Records trade in statistics
 
 **Market Order Confirmation:**
 ```
@@ -491,28 +506,40 @@ Open a long position using market order or limit order.
 โš ๏ธ Are you sure you want to open this long position?
 ```
 
-### `/short [token] [USDC amount] [price (optional)]`
-Open a short position using market order or limit order.
+### `/short [token] [USDC amount] [price (optional)] [sl:price (optional)]`
+Open a short position using market order or limit order, with optional automatic stop loss.
 
 **Usage:**
 ```
-/short <TOKEN> <USDC_AMOUNT>           # Market order
-/short <TOKEN> <USDC_AMOUNT> <PRICE>   # Limit order
+/short <TOKEN> <USDC_AMOUNT>                    # Market order
+/short <TOKEN> <USDC_AMOUNT> <PRICE>            # Limit order
+/short <TOKEN> <USDC_AMOUNT> sl:<STOP_PRICE>    # Market order with stop loss
+/short <TOKEN> <USDC_AMOUNT> <PRICE> sl:<STOP_PRICE> # Limit order with stop loss
 ```
 
 **Examples:**
 ```
-/short BTC 100       # Short Bitcoin with $100 USDC (Market Order)
-/short BTC 100 46000 # Short Bitcoin with $100 USDC at $46,000 (Limit Order)
-/short ETH 50        # Short Ethereum with $50 USDC (Market Order)
-/short ETH 50 3400   # Short Ethereum with $50 USDC at $3,400 (Limit Order)
+/short BTC 100              # Short Bitcoin with $100 USDC (Market Order)
+/short BTC 100 46000        # Short Bitcoin with $100 USDC at $46,000 (Limit Order)
+/short BTC 100 sl:47000     # Market order with automatic stop loss at $47,000
+/short BTC 100 46000 sl:47000 # Limit order at $46,000 with stop loss at $47,000
+/short ETH 50               # Short Ethereum with $50 USDC (Market Order)
+/short ETH 50 3400          # Short Ethereum with $50 USDC at $3,400 (Limit Order)
+/short ETH 50 sl:3500       # Market order with stop loss at $3,500
+/short ETH 50 3400 sl:3500  # Limit order with stop loss at $3,500
 ```
 
+**Stop Loss Validation:**
+- For SHORT positions: Stop loss price must be ABOVE entry price
+- Stop loss is placed automatically when the original order fills
+- Uses `sl:price` format to distinguish from limit price
+
 **How it works:**
 1. **Market Order** (2 parameters): Fetches current market price and places market sell order
 2. **Limit Order** (3 parameters): Places limit sell order at specified price
-3. Calculates token amount: `token_amount = usdc_amount / price`
-4. Records trade in statistics
+3. **With Stop Loss**: Saves stop loss for automatic placement when order fills
+4. Calculates token amount: `token_amount = usdc_amount / price`
+5. Records trade in statistics
 
 **Market Order Confirmation:**
 ```
@@ -819,7 +846,7 @@ Will trigger when BTC price moves above $50,000.00
 
 โฐ Created: 14:25:30
 
-๐Ÿ’ก The alarm will be checked every 30 seconds and you'll receive a notification when triggered.
+๐Ÿ’ก The alarm will be checked every 10 seconds and you'll receive a notification when triggered.
 ```
 
 **List All Alarms:**
@@ -904,7 +931,7 @@ Will trigger when BTC price moves above $50,000.00
 
 ## ๐Ÿ”„ Order Monitoring & Notifications
 
-The bot automatically monitors your orders and positions every 30 seconds and sends real-time notifications when orders are filled.
+The bot automatically monitors your orders and positions every 10 seconds and sends real-time notifications when orders are filled.
 
 ### Automatic Notifications
 
@@ -999,7 +1026,7 @@ Check the status of all monitoring systems.
 
 ๐Ÿ“Š Order Monitoring:
 โ€ข Active: โœ… Yes
-โ€ข Check Interval: 30 seconds
+โ€ข Check Interval: 10 seconds
 โ€ข Orders Tracked: 3
 โ€ข Positions Tracked: 2
 
@@ -1111,6 +1138,121 @@ View log file statistics and manage log cleanup.
 โœ… Log cleanup completed!
 ```
 
+### `/risk`
+Show advanced risk metrics and portfolio analysis.
+
+**Example:**
+```
+/risk
+```
+
+**Response:**
+```
+๐Ÿ“Š Risk Analysis & Advanced Metrics
+
+๐ŸŽฏ Risk-Adjusted Performance:
+โ€ข Sharpe Ratio: 1.850
+โ€ข Sortino Ratio: 2.410
+โ€ข Annual Volatility: 12.30%
+
+๐Ÿ“‰ Drawdown Analysis:
+โ€ข Maximum Drawdown: 8.50%
+โ€ข Value at Risk (95%): 3.20%
+
+๐Ÿ’ฐ Portfolio Context:
+โ€ข Current Balance: $1,150.00
+โ€ข Initial Balance: $1,000.00
+โ€ข Total P&L: $150.00
+โ€ข Days Active: 30
+
+๐Ÿ“Š Risk Interpretation:
+โ€ข ๐ŸŸข Good risk-adjusted returns (Sharpe > 1.0)
+โ€ข ๐ŸŸข Low maximum drawdown (< 15%)
+โ€ข ๐ŸŸก Moderate portfolio volatility (< 25%)
+
+๐Ÿ’ก Risk Definitions:
+โ€ข Sharpe Ratio: Risk-adjusted return (excess return / volatility)
+โ€ข Sortino Ratio: Return / downside volatility (focuses on bad volatility)
+โ€ข Max Drawdown: Largest peak-to-trough decline
+โ€ข VaR 95%: Maximum expected loss 95% of the time
+โ€ข Volatility: Annualized standard deviation of returns
+
+๐Ÿ“ˆ Data Based On:
+โ€ข Completed Trades: 25
+โ€ข Daily Balance Records: 30
+โ€ข Trading Period: 30 days
+```
+
+### `/version`
+Show bot version and system information.
+
+**Example:**
+```
+/version
+```
+
+**Response:**
+```
+๐Ÿค– Trading Bot Version & System Info
+
+๐Ÿ“ฑ Bot Information:
+โ€ข Version: v2.0.0
+โ€ข Network: Mainnet
+โ€ข Uptime: 2d 5h 30m
+โ€ข Default Token: BTC
+
+๐Ÿ’ป System Information:
+โ€ข Python: 3.11.5
+โ€ข Platform: Darwin arm64
+โ€ข Architecture: arm64
+
+๐Ÿ“Š Trading Stats:
+โ€ข Total Orders: 45
+โ€ข Completed Trades: 25
+โ€ข Days Active: 30
+โ€ข Start Date: 2024-01-15
+
+๐Ÿ”„ Monitoring Status:
+โ€ข Order Monitoring: โœ… Active
+โ€ข External Trades: โœ… Active
+โ€ข Price Alarms: โœ… Active (5 active)
+โ€ข Risk Management: โŒ Disabled
+
+โฐ Current Time: 2024-12-15 14:25:30
+```
+
+### `/balance_adjustments`
+Show deposit and withdrawal history for accurate P&L tracking.
+
+**Example:**
+```
+/balance_adjustments
+```
+
+**Response:**
+```
+๐Ÿ’ฐ Balance Adjustments History
+
+๐Ÿ“Š Summary:
+โ€ข Total Deposits: $500.00
+โ€ข Total Withdrawals: $200.00
+โ€ข Net Adjustment: $300.00
+โ€ข Total Transactions: 3
+
+๐Ÿ“… Recent Adjustments:
+โ€ข ๐Ÿ’ฐ 12/15 09:30: +$200.00
+โ€ข ๐Ÿ’ธ 12/10 16:45: -$150.00
+โ€ข ๐Ÿ’ฐ 12/05 11:20: +$300.00
+
+๐Ÿ’ก How it Works:
+โ€ข Bot checks for deposits/withdrawals every hour
+โ€ข Adjustments maintain accurate P&L calculations
+โ€ข Non-trading balance changes don't affect performance metrics
+โ€ข Trading statistics remain pure and accurate
+
+โฐ Last Check: 12/15 14:00
+```
+
 ## ๐Ÿ’ก Pro Tips
 
 ### **๐ŸŽฏ Best Practices**
@@ -1172,13 +1314,13 @@ View log file statistics and manage log cleanup.
 ### **๐Ÿ›ก๏ธ Safety Features**
 - **Confirmation dialogs** for all trades
 - **Auto-notifications** for order fills
-- **Real-time monitoring** every 30 seconds
+- **Real-time monitoring** every 10 seconds
 - **Comprehensive logging** of all activities
 - **Price alerts** for key levels
 - **External trade detection** and sync
 
 ### **๐Ÿ”„ Order Monitoring**
-- **30-second intervals** for order fill detection
+- **10-second intervals** for order fill detection
 - **Automatic P&L calculation** for closed positions
 - **Position change tracking** (opens, closes, increases)
 - **Instant Telegram notifications** for all fills

+ 53 - 29
docs/project-structure.md

@@ -10,7 +10,9 @@ trader_hyperliquid/
 โ”‚   โ”œโ”€โ”€ ๐Ÿ telegram_bot.py     # Main Telegram bot
 โ”‚   โ”œโ”€โ”€ ๐Ÿ”— hyperliquid_client.py # Hyperliquid API client
 โ”‚   โ”œโ”€โ”€ โš™๏ธ config.py           # Configuration management
-โ”‚   โ””โ”€โ”€ ๐Ÿ“Š trading_stats.py    # Statistics tracking
+โ”‚   โ”œโ”€โ”€ ๐Ÿ“Š trading_stats.py    # Statistics tracking
+โ”‚   โ”œโ”€โ”€ ๐Ÿ”” alarm_manager.py    # Price alarm management
+โ”‚   โ””โ”€โ”€ ๐Ÿ“ logging_config.py   # Logging configuration
 โ”œโ”€โ”€ ๐Ÿ“‚ tests/                   # Test suite
 โ”‚   โ”œโ”€โ”€ ๐Ÿ“‹ README.md           # Test documentation
 โ”‚   โ”œโ”€โ”€ ๐Ÿƒ run_all_tests.py    # Test runner
@@ -24,19 +26,23 @@ trader_hyperliquid/
 โ”‚   โ”œโ”€โ”€ ๐Ÿ“ commands.md         # Command reference
 โ”‚   โ”œโ”€โ”€ ๐Ÿš€ setup.md            # Setup guide
 โ”‚   โ”œโ”€โ”€ ๐Ÿ—๏ธ project-structure.md # This file
-โ”‚   โ””โ”€โ”€ ๐Ÿš€ deployment.md       # Deployment guide
+โ”‚   โ”œโ”€โ”€ ๐Ÿš€ deployment.md       # Deployment guide
+โ”‚   โ””โ”€โ”€ ๐Ÿ”ง SYSTEM_INTEGRATION.md # System integration
 โ”œโ”€โ”€ ๐Ÿ“‚ config/                  # Configuration files
 โ”‚   โ””โ”€โ”€ ๐Ÿ“„ .env.example        # Environment template
-โ”œโ”€โ”€ ๐Ÿ“‚ logs/                    # Log files
+โ”œโ”€โ”€ ๐Ÿ“‚ logs/                    # Log files (auto-created)
 โ”œโ”€โ”€ ๐Ÿ“‚ utils/                   # Utility scripts
-โ”œโ”€โ”€ ๐Ÿ“‚ __pycache__/            # Python cache
+โ”‚   โ”œโ”€โ”€ ๐Ÿ” get_telegram_chat_id.py # Chat ID finder
+โ”‚   โ”œโ”€โ”€ ๐Ÿ” simple_chat_id.py   # Alternative chat ID finder
+โ”‚   โ””โ”€โ”€ ๐Ÿ“Š demo_stats.py       # Demo statistics
+โ”œโ”€โ”€ ๐Ÿ“‚ __pycache__/            # Python cache (auto-created)
 โ”œโ”€โ”€ ๐Ÿ“‚ venv/                   # Virtual environment
 โ”œโ”€โ”€ ๐Ÿ“„ README.md               # Main project README
 โ”œโ”€โ”€ ๐Ÿ“„ requirements.txt        # Python dependencies
 โ”œโ”€โ”€ ๐Ÿ“„ .gitignore             # Git ignore rules
-โ”œโ”€โ”€ ๐Ÿ telegram_bot.py         # Bot entry point (legacy)
-โ”œโ”€โ”€ ๐Ÿ trading_bot.py          # Trading bot (legacy)
-โ””โ”€โ”€ ๐Ÿ“Š demo_stats.py           # Demo statistics
+โ”œโ”€โ”€ ๐Ÿ“„ .env                    # Environment configuration
+โ”œโ”€โ”€ ๐Ÿ“Š trading_stats.json      # Persistent statistics data
+โ””โ”€โ”€ ๐Ÿš€ trading_bot.py          # Main entry point
 ```
 
 ## ๐Ÿ“ Core Source Files
@@ -55,11 +61,20 @@ trader_hyperliquid/
 
 **Key Methods:**
 - `start_command()` - Bot startup
-- `long_command()` - Long position
-- `short_command()` - Short position
+- `long_command()` - Long position with stop loss support
+- `short_command()` - Short position with stop loss support
 - `exit_command()` - Close positions
 - `orders_command()` - Order management
 - `coo_command()` - Cancel orders
+- `sl_command()` - Manual stop loss
+- `tp_command()` - Take profit orders
+- `alarm_command()` - Price alerts
+- `monitoring_command()` - System status
+- `performance_command()` - Token performance
+- `risk_command()` - Risk metrics
+- `version_command()` - System info
+- `logs_command()` - Log management
+- `balance_adjustments_command()` - Deposit/withdrawal history
 
 ### **๐Ÿ”— src/hyperliquid_client.py**
 **Hyperliquid API client using CCXT**
@@ -110,6 +125,34 @@ trader_hyperliquid/
 - `get_basic_stats()` - Basic metrics
 - `format_stats_message()` - Telegram formatting
 
+### **๐Ÿ”” src/alarm_manager.py**
+**Price alarm management system**
+- Price alert creation and monitoring
+- Trigger detection
+- Alarm persistence
+- Multi-token support
+
+**Key Classes:**
+- `AlarmManager` - Alarm management
+
+**Key Methods:**
+- `create_alarm()` - Create price alert
+- `check_alarms()` - Monitor prices
+- `remove_alarm()` - Delete alarm
+- `get_statistics()` - Alarm stats
+
+### **๐Ÿ“ src/logging_config.py**
+**Centralized logging configuration**
+- Log level management
+- File rotation
+- Format standardization
+- Cleanup utilities
+
+**Key Functions:**
+- `setup_logging()` - Initialize logging
+- `cleanup_logs()` - Remove old logs
+- `format_log_stats()` - Log statistics
+
 ## ๐Ÿงช Test Suite
 
 ### **๐Ÿƒ tests/run_all_tests.py**
@@ -202,26 +245,7 @@ DEFAULT_TRADE_AMOUNT=100
 LOG_LEVEL=INFO
 ```
 
-## ๐Ÿ“Š Data Files
-
-### **๐Ÿ“Š demo_stats.py**
-Demo statistics generator for testing
-
-### **๐Ÿ“Š demo_stats.json**
-Sample statistics data
-
-### **๐Ÿ“‚ logs/**
-Application log files (created at runtime)
-
-## ๐Ÿ”„ Legacy Files
-
-### **๐Ÿ telegram_bot.py** (root)
-Legacy bot entry point - use `src/telegram_bot.py` instead
-
-### **๐Ÿ trading_bot.py** (root)
-Legacy trading bot - functionality moved to `src/`
-
-## ๐Ÿš€ Running the Project
+## ๐Ÿ”„ Running the Project
 
 ### **From Source Directory**
 ```bash

+ 15 - 5
docs/setup.md

@@ -43,8 +43,8 @@ nano .env  # Or use your preferred editor
 
 **Required settings:**
 ```env
-# Get from Hyperliquid account settings
-HYPERLIQUID_PRIVATE_KEY=your_private_key_here
+# Use API Generator Key from https://app.hyperliquid.xyz/API (NOT your wallet private key)
+HYPERLIQUID_PRIVATE_KEY=your_api_generator_key_here
 HYPERLIQUID_SECRET_KEY=your_secret_key_here
 HYPERLIQUID_TESTNET=true
 
@@ -63,17 +63,27 @@ python trading_bot.py
 
 ## ๐Ÿ”‘ Getting Hyperliquid Keys
 
+### API Keys (Recommended - SECURE)
+1. Go to [Hyperliquid API Panel](https://app.hyperliquid.xyz/API)
+2. Generate a dedicated API key for trading
+3. **NEVER use your wallet's private key directly**
+4. Use the generated API key in your `.env` file
+
 ### Testnet (Recommended First)
 1. Go to [Hyperliquid Testnet](https://app.hyperliquid-testnet.xyz/)
 2. Connect/create wallet
-3. Export private key from wallet settings
+3. Generate API key from API panel
 
 ### Mainnet (Real Money)
 1. Go to [Hyperliquid](https://app.hyperliquid.xyz/)
 2. Connect wallet
-3. Export private key from wallet settings
+3. Generate API key from API panel
 
-โš ๏ธ **Never share your private keys!**
+โš ๏ธ **Security Best Practices:**
+- Use API generator keys, NOT wallet private keys
+- Keep API keys secure and never share them
+- Use limited permissions when available
+- Test on testnet first
 
 ## โœ… Verify Setup