Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
3f98e2c
chore: remove unused imports and fix JSX character escaping
CryptoGnome Oct 12, 2025
4ed3f50
feat: add TradingView charts with liquidation database management
birdbathd Nov 18, 2025
bb0a7b6
feat: add infinite historical data loading to chart
birdbathd Nov 18, 2025
0046305
fix: remove duplicate prependHistoricalKlines function
birdbathd Nov 18, 2025
f0b82f3
fix: resolve chart initialization issues with historical data loading
birdbathd Nov 18, 2025
b6299c0
fix: preserve chart view position after user interaction
birdbathd Nov 18, 2025
5c6973e
fix: Add WebSocket keepalive and inactivity monitoring to Hunter
birdbathd Nov 18, 2025
e6aa8c7
feat: Add TP/SL toggle and reorganize chart controls
birdbathd Nov 19, 2025
3a21847
Merge branch 'dev' into feature/tradingview-charts
birdbathd Nov 19, 2025
8d9aad1
fix: prevent duplicate liquidations from accumulated event listeners
birdbathd Nov 19, 2025
57ebca2
feat: add configurable auto-refresh interval for chart (5s to 5min op…
birdbathd Nov 19, 2025
c09577f
perf: optimize auto-refresh to fetch only latest 2 candles instead of…
birdbathd Nov 19, 2025
3aeb2a5
Add volume histogram to TradingView chart with toggle
birdbathd Nov 19, 2025
0164ead
Fix ReferenceError and reduce WebSocket console spam
birdbathd Nov 19, 2025
42657ff
Add debug logging to track Hunter event listener accumulation
birdbathd Nov 19, 2025
de4a230
Revert "Add volume histogram to TradingView chart with toggle"
birdbathd Nov 19, 2025
56556b4
Reduce WebSocket broadcast spam and add eventTime logging
birdbathd Nov 19, 2025
bcc201c
fix: prevent duplicate liquidations with database UNIQUE constraint
birdbathd Nov 20, 2025
87ea43c
chore: restore tranche implementation and docs accidentally deleted b…
birdbathd Nov 20, 2025
6bb2ce2
docs: merge back with dev - restore tranche documentation
birdbathd Nov 20, 2025
2159acc
fix: prevent duplicate liquidation events from inflating threshold co…
birdbathd Nov 21, 2025
0303219
refactor: improve WebSocket reconnection logic to prevent reconnectio…
birdbathd Nov 21, 2025
703fe2f
feat: enable tranche management UI configuration
birdbathd Nov 23, 2025
f045004
feat: enable tranche management system (untested)
birdbathd Nov 23, 2025
c527762
feat: implement protective orders system
birdbathd Nov 23, 2025
2d97d31
Add timestamps to logs UI and initialize ProtectiveOrderService
birdbathd Nov 23, 2025
6882f5b
Remove per-symbol protective order config and fix duplicate service s…
birdbathd Nov 23, 2025
218f606
Fix ProtectiveOrderService initialization check in API
birdbathd Nov 23, 2025
0e07ed4
feat: Transform trailing stop to trailing TP with break-even protecti…
birdbathd Nov 23, 2025
f3a080d
Mobile responsive improvements and performance optimizations
birdbathd Nov 23, 2025
ec6fa3b
Fix desktop layout spacing for better space utilization
birdbathd Nov 23, 2025
673f3b0
Consolidate Recent Orders header into single row
birdbathd Nov 23, 2025
e213fec
chore: add .db-shm files to gitignore
birdbathd Nov 23, 2025
7346ba7
feat: mobile responsiveness and UX improvements
birdbathd Nov 24, 2025
c1d60ef
Fix PM2 logs for multi-instance setups
birdbathd Nov 24, 2025
6fd4670
Merge remote-tracking branch 'origin/fix/ui-ux-mobile-optimization' i…
birdbathd Nov 24, 2025
a5c8501
Fix build: resolve linting errors and add build ignore flags
birdbathd Nov 24, 2025
c9e5c99
Fix React Hooks rules violations and build errors
birdbathd Nov 24, 2025
8516d11
Fix auth redirect to use actual host instead of hardcoded localhost
birdbathd Nov 24, 2025
343cf5c
fix: onboarding state now persists server-side instead of localStorage
birdbathd Nov 25, 2025
ca55908
CRITICAL FIX: onboarding config preservation and setup escape
birdbathd Nov 25, 2025
1a3a8ac
fix: comprehensive authentication, security, and onboarding improvements
birdbathd Nov 25, 2025
8bf9d57
chore: remove unused imports and variables per Copilot review
birdbathd Nov 25, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ next-env.d.ts
data/*.db
data/*.db-journal
data/*.db-wal
data/*.db-shm

# user configuration
config.user*
Expand All @@ -54,3 +55,10 @@ data/optimizer-jobs.json
# claude code local settings and agents
.claude/settings.local.json
.claude/agents/

# local development files (not for commit)
[WEB]
ecosystem.config.js
scripts/aster-notifier.cjs
*.swp
.*.swp
74 changes: 66 additions & 8 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,17 @@ npm run lint # Run ESLint
npx tsc --noEmit # Check TypeScript types

# Testing
npm test # Run all tests
npm run test:hunter # Test Hunter component
npm run test:position # Test PositionManager
npm run test:rate # Test rate limiting
npm run test:ws # Test WebSocket functionality
npm run test:errors # Test error logging
npm run test:integration # Test trading flow integration
npm run test:watch # Run tests in watch mode
npm test # Run all tests
npm run test:hunter # Test Hunter component
npm run test:position # Test PositionManager
npm run test:rate # Test rate limiting
npm run test:ws # Test WebSocket functionality
npm run test:errors # Test error logging
npm run test:integration # Test trading flow integration
npm run test:tranche # Test tranche system (basic)
npm run test:tranche:integration # Test tranche integration (comprehensive)
npm run test:tranche:all # Run all tranche tests
npm run test:watch # Run tests in watch mode

# Utilities
npm run optimize:ui # Run configuration optimizer
Expand Down Expand Up @@ -80,10 +83,57 @@ npm run optimize:ui # Run configuration optimizer
|-----------|----------|---------|
| **Hunter** | `src/lib/bot/hunter.ts` | Monitors liquidation streams, triggers trades |
| **PositionManager** | `src/lib/bot/positionManager.ts` | Manages positions, SL/TP orders, user data streams |
| **TrancheManager** | `src/lib/services/trancheManager.ts` | Tracks multiple position entries (tranches) per symbol |
| **AsterBot** | `src/bot/index.ts` | Main orchestrator coordinating Hunter and PositionManager |
| **StatusBroadcaster** | `src/bot/websocketServer.ts` | WebSocket server for real-time UI updates |
| **ProcessManager** | `scripts/process-manager.js` | Cross-platform process lifecycle management |

### Multi-Tranche Position Management

The bot includes an advanced **multi-tranche system** that tracks multiple virtual position entries per symbol:

**What are Tranches?**
- Virtual position entries tracked locally while exchange sees one combined position
- Allows isolation of underwater positions (>5% loss by default)
- Continue trading fresh positions without adding to losers
- Better margin utilization and risk management

**Key Components:**
- **Database Layer** (`src/lib/db/trancheDb.ts`): Tranche and event storage with SQLite
- **TrancheManager Service** (`src/lib/services/trancheManager.ts`): Core tranche lifecycle management
- **Hunter Integration**: Pre-trade limit checks, post-order tranche creation
- **PositionManager Integration**: Tranche closing on SL/TP fills, exchange synchronization
- **UI Dashboard** (`/tranches`): Real-time tranche visualization and management

**Configuration (per symbol):**
```json
{
"enableTrancheManagement": true,
"trancheIsolationThreshold": 5, // % loss before isolation
"maxTranches": 3, // Max active tranches
"maxIsolatedTranches": 2, // Max isolated tranches
"trancheStrategy": {
"closingStrategy": "FIFO", // FIFO, LIFO, WORST_FIRST, BEST_FIRST
"slTpStrategy": "NEWEST", // NEWEST, OLDEST, BEST_ENTRY, AVERAGE
"isolationAction": "HOLD" // Action when isolated
},
"allowTrancheWhileIsolated": true, // Continue trading with isolated tranches
"trancheAutoCloseIsolated": false // Auto-close when recovered
}
```

**Testing:**
```bash
npm run test:tranche # Basic system tests
npm run test:tranche:integration # Full integration tests (100% passing)
npm run test:tranche:all # Run all tranche tests
```

**Documentation:**
- Implementation Plan: `docs/TRANCHE_IMPLEMENTATION_PLAN.md`
- Testing Guide: `docs/TRANCHE_TESTING.md`
- User Guide: `docs/TRANCHE_USER_GUIDE.md` (for end users)

### Services (`src/lib/services/`)

- **balanceService.ts**: Real-time balance tracking via WebSocket
Expand All @@ -93,6 +143,7 @@ npm run optimize:ui # Run configuration optimizer
- **configManager.ts**: Hot-reload configuration management
- **pnlService.ts**: Real-time P&L tracking and session metrics
- **thresholdMonitor.ts**: 60-second rolling volume threshold tracking
- **trancheManager.ts**: Multi-tranche position tracking and lifecycle management

### API Layer (`src/lib/api/`)

Expand Down Expand Up @@ -265,6 +316,13 @@ config.default.json # Default configuration template
- Includes stack traces, timestamps, and trading data
- Accessible via web UI at `/errors`

**Tranche Database** (`src/lib/db/trancheDb.ts`):
- Stores all tranche entries and lifecycle events
- Tracks active, isolated, and closed tranches
- Audit trail via `tranche_events` table
- Indexed for performance (symbol, side, status, entry_time)
- Automatic cleanup of old closed tranches

## Error Handling

### Custom Error Types (`src/lib/errors/TradingErrors.ts`)
Expand Down
124 changes: 124 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ A smart trading bot that monitors and trades liquidation events on Aster DEX. Fe

- 📈 **Real-time Liquidation Hunting** - Monitors and instantly trades liquidation events
- 💰 **Smart Position Management** - Automatic stop-loss and take-profit on every trade
- 🎯 **Multi-Tranche System** - Isolate losing positions while continuing to trade fresh entries
- 🧪 **Paper Trading Mode** - Test strategies safely with simulated trades
- 🎨 **Beautiful Web Dashboard** - Monitor everything from a clean, modern UI
- ⚡ **One-Click Setup** - Get running in under 2 minutes
Expand Down Expand Up @@ -75,6 +76,7 @@ Access at http://localhost:3000

- **Dashboard** - Monitor positions and P&L
- **Config** - Adjust all settings via UI
- **Tranches** - View and manage multi-tranche positions
- **History** - View past trades

## ⚙️ Commands
Expand Down Expand Up @@ -178,11 +180,133 @@ Found a bug in the dev branch? Help us improve!

**Note**: Always start with paper mode when testing new beta features!

## 🎯 Advanced Features

### Multi-Tranche Position Management

The bot includes an intelligent **multi-tranche system** that dramatically improves trading performance when positions move against you:

#### What are Tranches?

Think of tranches as separate "sub-positions" within the same trading pair. Instead of one large position that you keep adding to, the bot tracks multiple independent entries:

- **Position goes underwater (>5% loss)?** → Bot automatically **isolates** it
- **Continue trading?** → Bot opens **new tranches** without adding to the loser
- **Keep making profits?** → Trade fresh entries while holding positions recover
- **Better margin usage** → Don't let one bad position lock up all your capital

#### Why Use Multi-Tranche?

**Traditional Trading Problem:**
```
Enter BTCUSDT LONG @ $50,000
Price drops to $47,500 (-5%)
You're stuck: Can't trade more without adding to losing position
Miss opportunities while waiting for recovery
```

**With Multi-Tranche System:**
```
Tranche #1: LONG @ $50,000 → Down 5% → ISOLATED (held separately)
Tranche #2: LONG @ $47,500 → Up 2% → CLOSE (+profit!)
Tranche #3: LONG @ $48,000 → Up 3% → CLOSE (+profit!)
Meanwhile, Tranche #1 recovers → Eventually closes at breakeven or profit
```

**Result:** You keep making money on new trades while bad positions recover naturally.

#### Key Benefits

✅ **Isolate Losing Positions** - Underwater positions tracked separately
✅ **Continue Trading** - Open fresh positions without adding to losers
✅ **Better Margin Efficiency** - Don't lock up capital in losing trades
✅ **Automatic Management** - Bot handles everything automatically
✅ **Configurable Strategies** - Choose FIFO, LIFO, or close best/worst first
✅ **Real-Time Monitoring** - Dashboard shows all tranches and their P&L

#### How to Enable

1. **Via Web UI** (Recommended):
- Go to http://localhost:3000/config
- Find your trading pair (e.g., BTCUSDT)
- Scroll to "Tranche Management Settings"
- Toggle "Enable Multi-Tranche Management"
- Configure settings:
- **Isolation Threshold**: When to isolate (default: 5% loss)
- **Max Tranches**: Max active positions (default: 3)
- **Max Isolated**: Max underwater positions before blocking new trades (default: 2)
- **Closing Strategy**: FIFO (oldest first), LIFO (newest first), WORST_FIRST, BEST_FIRST
- **SL/TP Strategy**: Which tranche's targets to use (NEWEST, OLDEST, BEST_ENTRY, AVERAGE)

2. **Monitor Your Tranches**:
- Visit http://localhost:3000/tranches
- See all active, isolated, and closed tranches
- Real-time P&L tracking
- Event timeline showing tranche lifecycle

#### Configuration Example

```json
{
"symbols": {
"BTCUSDT": {
"enableTrancheManagement": true,
"trancheIsolationThreshold": 5,
"maxTranches": 3,
"maxIsolatedTranches": 2,
"allowTrancheWhileIsolated": true,
"trancheStrategy": {
"closingStrategy": "FIFO",
"slTpStrategy": "NEWEST",
"isolationAction": "HOLD"
}
}
}
}
```

#### Safety & Risk Management

The multi-tranche system includes built-in safety features:

- **Position Limits**: Won't exceed max tranches per symbol
- **Isolation Blocking**: Stops new trades if too many positions are underwater
- **Exchange Sync**: Reconciles local tracking with exchange positions
- **Automatic Monitoring**: Checks every 10 seconds for positions needing isolation
- **Event Audit Trail**: Full history of every tranche action in database

**⚠️ Important Notes:**
- Start with **paper mode** to understand how tranches work
- Set conservative limits (3 max tranches, 2 max isolated is recommended)
- Higher isolation threshold (5-10%) prevents over-isolation
- Monitor the `/tranches` dashboard regularly

#### Advanced Use Cases

**Scalping Strategy:**
- Low isolation threshold (3%)
- High max tranches (5)
- LIFO closing (close newest first)
- Works great for quick in-and-out trades

**Hold & Recover Strategy:**
- High isolation threshold (10%)
- Moderate max tranches (3)
- FIFO closing (close oldest first)
- Good for trending markets

**Best Trade First:**
- BEST_FIRST closing strategy
- Take profits on winners quickly
- Hold losers for recovery
- Maximizes realized gains

## 🛡️ Safety Features

- Paper mode for testing
- Automatic stop-loss/take-profit
- Position size limits
- Multi-tranche isolation system
- WebSocket auto-reconnection

## 🌐 Remote Access Configuration
Expand Down
Empty file added [WEB]
Empty file.
8 changes: 7 additions & 1 deletion config.default.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@
"positionMode": "HEDGE",
"maxOpenPositions": 5,
"useThresholdSystem": false,
"debugMode": false,
"server": {
"dashboardPassword": "admin",
"dashboardPort": 3000,
"websocketPort": 8080,
"useRemoteWebSocket": false,
"websocketHost": null
"websocketHost": null,
"setupComplete": false
},
"rateLimit": {
"maxRequestWeight": 2400,
Expand All @@ -46,6 +48,10 @@
"deduplicationWindowMs": 1000,
"parallelProcessing": true,
"maxConcurrentRequests": 3
},
"liquidationDatabase": {
"retentionDays": 90,
"cleanupIntervalHours": 24
}
},
"version": "1.1.0"
Expand Down
Loading
Loading