Thanks to visit codestin.com
Credit goes to github.com

Skip to content

iamnshrd/MeteorShower

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

81 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MeteorShower - Advanced DLMM Liquidity Bot

MeteorShower Bot Solana Node.js License

🌟 Introduction

MeteorShower is a sophisticated, open-source automated liquidity bot for Meteora's Dynamic Liquidity Market Maker (DLMM) pools on Solana. Built for professional DeFi traders and liquidity providers, it features advanced rebalancing strategies, real-time P&L tracking, and comprehensive risk management tools.

✨ Advanced Features Overview

  • πŸ—οΈ Modular Architecture - Refactored from 1500-line monolith to clean, maintainable modules
  • 🎯 Take Profit & Stop Loss - Automated exit conditions with position-specific triggers
  • πŸ”„ Smart Swapless Rebalancing - Minimize fees with intelligent single-sided rebalancing
  • πŸ’° Bin Array Fee Checking - Proactive estimation of initialization costs with user confirmation
  • πŸ’Έ Advanced Fee Management - Choose between auto-compound or claim-and-convert-to-SOL
  • πŸ”§ Selective Compounding - Compound both tokens, SOL-only, token-only, or none
  • πŸ“ˆ Dual P&L Tracking - Real-time USD and SOL-denominated profit/loss monitoring
  • πŸ›‘οΈ Dynamic SOL Management - Intelligent budget caps with adaptive retry logic
  • ⚑ RPC Compatibility - Auto-detection with fallbacks for Helius, QuickNode, Alchemy, and others
  • πŸŽ›οΈ Interactive Configuration - User-friendly prompts for all settings with 43-44 char pool support
  • ⚑ Session Fee Optimization - Cross-rebalance fee accrual for swapless efficiency
  • πŸ”§ Professional Tools - Comprehensive testing, monitoring, and emergency controls

⚠️ Important Disclaimers

No Financial Advice

This tool is for informational purposes only and does not constitute financial, investment, or trading advice. Use at your sole discretion and risk.

Risk of Financial Loss

Providing liquidity carries significant risks including impermanent loss, price volatility, and potential loss of capital. The automated nature does not eliminate these risks.

Open-Source Software

Provided "as is" without warranties. Users are responsible for reviewing and understanding the code before use.

Smart Contract Risk

Interacts with Meteora smart contracts and third-party protocols like Jupiter. Smart contracts may have vulnerabilities.


πŸš€ Quick Start Guide

1. Prerequisites

2. Get a Solana RPC URL

You need a reliable RPC endpoint. Recommended providers:

Helius (Recommended)

  1. Go to helius.xyz and create free account
  2. Create a new project and copy your API URL
  3. It will look like: https://mainnet.helius-rpc.com/?api-key=your-key-here

Other Options:

  • QuickNode: Professional RPC with free tier
  • Alchemy: Another reliable option with generous free tier
  • Public RPC: https://api.mainnet-beta.solana.com (slower, rate limited)

3. Create/Get Your Solana Wallet

Option A: Create New Wallet

# Install Solana CLI tools first, then:
solana-keygen new --outfile ~/solana-keypair.json

# Your new wallet address:
solana-keygen pubkey ~/solana-keypair.json

Option B: Import from Phantom/Solflare (Recommended)

  1. In Phantom: Settings β†’ Export Private Key β†’ Copy the private key
  2. Use the enhanced configuration script (automatically converts base58 to JSON):
# Run the interactive configuration
node configure.js

# When prompted for wallet setup, choose option 2:
# "Import existing private key (base58 format from Phantom/Solflare)"
# Then paste your private key - it will auto-convert!

Option C: Use Existing Keypair

If you already have a .json wallet file, note its path.

4. Fund Your Wallet

Send at least 0.2 SOL to your wallet address for:

  • Transaction fees (0.1+ SOL)
  • Liquidity provision (0.1+ SOL)
  • Buffer for safety

5. Installation

# Clone the repository
git clone https://github.com/fciaf420/MeteorShower.git
cd MeteorShower

# Install dependencies
npm install

# Create configuration file (optional - bot will prompt if missing)
cp .env.example .env

6. Interactive Configuration (Recommended)

Run the enhanced configuration script for easy setup:

# Interactive configuration with wallet import support
node configure.js

The script will:

  1. Guide you through all settings - RPC URL, pool selection, etc.
  2. Handle wallet setup with 3 options:
    • Create a new wallet
    • Import from Phantom/Solflare (base58 β†’ JSON conversion)
    • Use existing wallet file
  3. Auto-generate .env file with all your settings
  4. Display your wallet address for verification

Manual Configuration (Alternative)

If you prefer editing .env manually:

# Required: Your RPC endpoint
RPC_URL=https://mainnet.helius-rpc.com/?api-key=YOUR_KEY_HERE

# Required: Path to your wallet JSON file  
WALLET_PATH=/home/user/solana-keypair.json
# Windows: WALLET_PATH=C:\Users\username\solana-keypair.json

# Optional: Monitoring interval (seconds)
MONITOR_INTERVAL_SECONDS=60

# Optional: Transaction settings
PRIORITY_FEE_FALLBACK_MICROS=50000
SLIPPAGE=10
PRICE_IMPACT=0.5

7. First Time Setup & Verification

Check Wallet Balance

# Verify your wallet has sufficient SOL
node balance-prompt.js

Test Your Configuration

# Start the bot - it will validate RPC, wallet, and walk you through setup
node cli.js run

Expected First-Run Flow:

  1. Bot validates RPC connection βœ…
  2. Bot validates wallet access βœ…
  3. Interactive pool selection (choose from popular pools or paste custom)
  4. SOL amount selection with balance checking
  5. Position configuration (token ratio, bin span, etc.)
  6. Fee handling setup (compound vs claim-to-SOL)
  7. Take profit/stop loss configuration
  8. Position creation and monitoring begins

Emergency Stop

# Stop the bot anytime with Ctrl+C
# Bot will complete current operation safely

8. Basic Usage

# Start the bot with interactive setup
node cli.js run

# Start with custom monitoring interval (60 seconds)
node cli.js run --interval 60

# Close all positions and swap to SOL
node cli.js close

# Get help
node cli.js --help

πŸ“‹ Available Commands

Core Commands

Command Description Example
node cli.js run Start the liquidity bot with interactive setup node cli.js run --interval 30
node cli.js close Close all positions and swap to SOL node cli.js close

Utility Commands

Command Description Use Case
node balance-prompt.js Check wallet balance and get funding address Balance verification
node close-position.js Manual position closing (emergency use) Emergency position closure
node configure.js Enhanced interactive configuration setup with wallet import Initial setup, wallet import
node wallet-info.js Display wallet information (public key, location) Wallet verification
node wallet-info.js --show-private Show private key with security warnings Private key access (secure environment only)
node scroll.js Animated position display monitor Visual monitoring

CLI Options

Option Short Description Default
--interval -i Monitor interval in seconds 5
--help -h Show help information -

βš™οΈ Configuration

Environment Variables (.env)

Create a .env file in the project directory:

# Required Settings
RPC_URL=https://mainnet.helius-rpc.com/?api-key=YOUR_KEY_HERE
WALLET_PATH=~/id.json

# Monitoring Settings
MONITOR_INTERVAL_SECONDS=60           # Default monitoring interval
PNL_CHECK_INTERVAL_SECONDS=60         # Comprehensive P&L analysis interval (used for TP/SL)

# Fee & Trading Settings
# Priority fee fallback in micro‑lamports per CU. Medium uses this base; High/VeryHigh use 3x/10x when dynamic fees are unavailable.
PRIORITY_FEE_FALLBACK_MICROS=50000
SLIPPAGE=10                           # Slippage tolerance in basis points (0.1%)
PRICE_IMPACT=0.5                      # Max price impact for swaps (0.5%)

# Advanced Settings
MANUAL=true                           # Use manual configuration mode
LOG_LEVEL=info                        # Logging level: error, warn, info, debug

# Helius Sender (optional, ultra-low latency submission)
# Enable to route transactions via Helius Sender instead of standard RPC
USE_SENDER=false
# Sender endpoint: use global HTTPS for frontends, or regional HTTP for backends
# SENDER_ENDPOINT=https://sender.helius-rpc.com/fast
# SENDER_ENDPOINT=http://slc-sender.helius-rpc.com/fast
# SWQoS-only routing (lower tip, cost-optimized)
SENDER_SWQOS_ONLY=false
# Minimum Jito tip (SOL). Use 0.001 (dual routing) or 0.0005 (SWQoS-only)
SENDER_TIP_SOL_MIN=0.001
# Compute unit limit set when using Sender (CU)
SENDER_COMPUTE_UNIT_LIMIT=200000

Priority Fee Behavior

  • Dynamic priority fees: Queries Helius Priority Fee API per transaction.
  • Progressive escalation: 3 attempts at Medium, 3 at High, then VeryHigh.
  • Fallbacks: When dynamic fees are unavailable, uses PRIORITY_FEE_FALLBACK_MICROS for Medium, with 3x (High) and 10x (VeryHigh).

Helius Sender (Optional)

Helius Sender provides ultra-low-latency submission with dual routing to validators and Jito. Our integration is opt‑in and enforces Sender’s requirements automatically.

  • Enable: set USE_SENDER=true (see env vars above).
  • Routing modes:
    • Dual routing (default): best inclusion probability; tip >= 0.001 SOL.
    • SWQoS-only: cost-optimized path; set SENDER_SWQOS_ONLY=true; tip >= 0.0005 SOL.
  • What we add automatically when enabled:
    • Jito tip transfer to a designated tip account (SENDER_TIP_SOL_MIN).
    • Compute budget limit (SENDER_COMPUTE_UNIT_LIMIT).
    • Priority fee price using dynamic API β†’ env fallback.
    • Sender submission with skipPreflight: true and maxRetries: 0.

Use the global HTTPS endpoint for frontends, or a regional HTTP endpoint nearest your servers for backends.

Interactive Configuration

The bot provides step-by-step interactive prompts for:

  1. Pool Selection - Choose from popular pools or enter custom address (43-44 characters)
  2. Capital Amount - Specify SOL amount with automatic balance checking
  3. Token Allocation - Select ratio (100% SOL, 50/50, 100% Token, or custom)
  4. Position Range - Configure bin span with price coverage visualization
  5. Liquidity Strategy - Choose distribution pattern (Spot, Curve, BidAsk)
  6. Rebalancing Mode - Enable swapless rebalancing with custom bin spans
  7. Initial Phase Gate - Configure re-entry depth for controlled swapless activation
  8. Fee Management - Choose between auto-compound or claim-and-convert-to-SOL
  9. Compounding Mode - Select which fees to compound (both, SOL-only, token-only, none)
  10. Take Profit/Stop Loss - Set automated exit conditions with trailing stops

🎯 Advanced Features

Take Profit & Stop Loss

Position-Specific Risk Management with Comprehensive Analysis

  • Configurable profit targets (0.1% - 200%)
  • Configurable loss limits (0.1% - 100%)
  • Triggers based on comprehensive P&L data updated every PNL_CHECK_INTERVAL_SECONDS
  • Bin-level precision for accurate position valuation and fee attribution
  • Only closes the monitored position (not all wallet positions)
  • Only swaps tokens from that specific pool to SOL
  • Real-time P&L monitoring with TP/SL status display
πŸ“Š Time      β”‚ πŸ’° Value   β”‚ πŸ“ˆ P&L     β”‚ πŸ“Š P&L%   β”‚ πŸ’Ž Fees   β”‚ πŸ”„ Rebal β”‚ 🎯 Exit
⏰ 7:05:47   β”‚ $   21.77  β”‚ βœ…+$  2.15 β”‚   +10.9%  β”‚ $   0.48  β”‚     3    β”‚ πŸ”₯+15% πŸ›‘οΈ-10%

Swapless Rebalancing Strategy

Intelligent Direction-Based Rebalancing

  • Price moves UP β†’ Stay in SOL, create position BELOW new price
  • Price moves DOWN β†’ Switch to TOKEN, create position ABOVE new price
  • Minimizes swap fees and slippage
  • Configurable bin spans independent of initial position
  • Always starts at current active bin (0 distance from price)

Initial Phase Gate System

Smart Rebalancing Activation for Stability

The bot includes an intelligent "initial phase gate" that provides better control over when swapless rebalancing becomes active:

  • Purpose: Prevents premature swapless switching during initial position establishment
  • How it works:
    • Blocks swapless rebalancing until price re-enters the position by a specified depth
    • Maintains the initial wide template during the gate-active phase
    • Enables swapless mode only after price demonstrates sufficient inside movement
  • Configuration: Configurable re-entry depth (default: 2 bins from nearest edge)
  • Benefits:
    • Reduces unnecessary early rebalancing noise
    • Ensures swapless strategy activates at optimal timing
    • Maintains position stability during initial volatile periods
    • Provides cleaner strategy transitions

Example Flow:

  1. Position created with 20-bin span around current price
  2. Price moves outside range β†’ Normal rebalancing (maintains wide template)
  3. Price re-enters by 2+ bins from edge β†’ Gate deactivates
  4. Future out-of-range moves β†’ Swapless rebalancing activated
πŸ’‘ Configuration prompt:
πŸ”§ Initial re-entry threshold:
    Blocks the first swapless rebalancing until price re-enters by X bins from the nearest edge.

Enter inside re-entry depth in bins (default 2): 

Advanced Fee Management

Choose Your Fee Strategy

The bot now offers two distinct fee handling modes:

Auto-Compound Mode

  • Purpose: Reinvest fees to grow position size over time
  • How it works: Earned fees are automatically added to new positions during rebalancing
  • Selective Compounding Options:
    • both - Compound SOL and token fees (default)
    • sol_only - Compound only SOL-side fees, claim token fees
    • token_only - Compound only token-side fees, claim SOL fees
    • none - No compounding (same as claim-and-convert mode)

Claim-and-Convert Mode

  • Purpose: Convert all fees to SOL for steady SOL accumulation
  • How it works: On each rebalance, non-SOL fees are swapped to SOL via Jupiter Ultra
  • Benefits: Simplifies portfolio management, reduces token exposure
  • Use case: When you prefer pure SOL accumulation over position growth

Session Fee Optimization

  • Smart Reuse: During swapless UP cycles, token fees are accrued for reuse in DOWN cycles
  • Efficiency: Reduces swap costs by reusing previously earned tokens
  • Tracking: Real-time session fee accrual monitoring and consumption

Comprehensive P&L Tracking

Dual-Layer P&L Analysis with Comprehensive Bin-Level Precision

Live P&L Grid (Real-Time Updates)

  • Quick wallet-based P&L calculations for immediate feedback
  • Updates every MONITOR_INTERVAL_SECONDS (default: 60s)
  • Shows current position value, basic P&L, and rebalance count
  • Fast response for continuous monitoring

Comprehensive P&L Analysis (Detailed Reports)

  • Bin-level position analysis with precise fee attribution
  • Updates every PNL_CHECK_INTERVAL_SECONDS (default: 60s)
  • Used for Take Profit & Stop Loss triggers for maximum accuracy
  • Detailed breakdown of:
    • Position Value: Current liquidity value across all bins
    • Fee Analysis: Earned fees from each rebalance cycle
    • P&L Attribution: Sources of gains/losses with bin-level precision
    • Performance Metrics: ROI, fee efficiency, rebalance effectiveness

Session-Based Logging System

  • Date-Organized Logs: logs/YYYY-MM-DD/ms-timestamp.log and .jsonl
  • Debug Toggle: Press D to toggle live debug output visibility
  • Clean Console: Production-ready UI with comprehensive background logging
  • Session Tracking: Each bot session gets unique identifier for log correlation

USD & SOL Denominated Tracking

  • USD P&L: Tracks profit/loss from initial deposit in USD terms
  • SOL P&L: Independent SOL-denominated performance tracking
  • Baseline Protection: Locks in SOL price at monitoring start
  • Reserve Tracking: Monitors SOL reserves and includes in P&L calculations
πŸ“ˆ Enhanced P&L Display with Debug Toggle:
πŸ“Š Time      β”‚ πŸ’° Value   β”‚ πŸ“ˆ P&L     β”‚ πŸ“Š P&L%   β”‚ πŸ’Ž Fees   β”‚ πŸ”„ Rebal β”‚ 🎯 Exit
⏰ 7:05:47   β”‚ $   21.77  β”‚ βœ…+$  2.15 β”‚   +10.9%  β”‚ $   0.48  β”‚     3    β”‚ πŸ”₯+15% πŸ›‘οΈ-10%
πŸͺ™ P&L(SOL): +0.0134 SOL (+8.2%)
πŸ”§ Reserve counted: +$0.12
πŸ’‘ Press 'D' to toggle debug output | Session: ms-2024-01-15T10:30:45.123Z

πŸ” Wallet Management Utilities

Enhanced Wallet Configuration

The configure.js script provides an enhanced wallet setup experience:

node configure.js

Features:

  • πŸ”‘ Three wallet options:
    1. Create new wallet - Generate fresh keypair
    2. Import from Phantom/Solflare - Paste base58 private key (auto-converts to JSON)
    3. Use existing wallet file - Point to existing JSON wallet
  • βœ… Automatic conversion from base58 to JSON array format
  • πŸ›‘οΈ Input validation with clear error messages and retry prompts
  • πŸ“‹ Complete configuration - All environment variables in one flow

Wallet Information Utility

The wallet-info.js script helps you view and manage wallet information:

Basic Usage (Safe)

# Show wallet location and public key only
node wallet-info.js

Output:

πŸ”‘ Wallet Information
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
πŸ“ Wallet Location: /path/to/your/wallet.json
πŸ”“ Public Key:      6yP4...JWkq

πŸ’‘ To display private key, run: node wallet-info.js --show-private

Private Key Access (Secure Environment Only)

# Show all wallet information including private key
node wallet-info.js --show-private

⚠️ Security Features:

  • Multiple security warnings before displaying private key
  • Confirmation prompt to ensure user consent
  • Strong disclaimers about fund loss risks
  • Reminders to clear terminal after use

Private Key Formats Shown:

  • Base58 format (for importing to Phantom/Solflare)
  • JSON array format (for bot configuration)

Command Options

node wallet-info.js --help          # Show help information
node wallet-info.js --show-private  # Show private key (with warnings)
node wallet-info.js -p              # Short form of --show-private

πŸ”§ Core Functionality

Position Management

Automated Position Lifecycle

  • Open Position: Creates DLMM liquidity position centered around active bin
  • Monitor Position: Continuously tracks position health and price movements
  • Smart Rebalancing: Only triggers when price moves completely outside position range
  • Emergency Close: Manual position closure with token swapping

Rebalancing Trigger Logic

  • Monitors active bin ID vs position range (lower bin to upper bin)
  • Triggers rebalancing only when price moves outside the range, not at edges
  • Uses activeBinId < lowerBin or activeBinId > upperBin logic
  • Prevents premature rebalancing at position boundaries

Token Balancing & Swapping

  • Jupiter DEX integration for optimal token swaps
  • Slippage protection on all swaps
  • Support for any token ratio (100% SOL, 50/50, 80/20, 100% Token, custom)
  • Automatic token identification (SOL vs alt-token)

Safety & Reliability Features

SOL Buffer Management

  • Reserves 0.07 SOL automatically for transaction fees
  • Prevents account closure due to insufficient SOL
  • Balance validation before all operations

Advanced Error Handling

  • Retry logic with exponential backoff for failed transactions
  • Graceful handling of network issues and RPC failures
  • Continues monitoring despite temporary failures
  • Comprehensive error logging and recovery

Position Protection

  • Uses exact balances from closed positions during rebalancing
  • Prevents double-counting or balance inflation issues
  • Accurate capital usage calculations

πŸ“Š Testing & Validation

Comprehensive Test Suite

The bot includes extensive testing capabilities with real blockchain operations:

# Available test scripts (real mainnet transactions)
npm run test:ultra-swap                  # Test Jupiter Ultra swap functionality
npm run test:regular-swap               # Test regular Jupiter swap functionality  
npm run test:swap-comparison            # Compare swap methods performance

# Direct script execution
node scripts/test-ultra-swap.js         # Jupiter Ultra API testing
node scripts/test-regular-swap.js       # Regular Jupiter swap testing
node scripts/swap-tester.js             # Performance comparison suite

⚠️ Important Test Notes:

  • Real Transactions: All test scripts execute actual blockchain transactions on Solana mainnet
  • Use Small Amounts: Start with 0.01-0.05 SOL for safety
  • Monitor Costs: Each test consumes SOL for transaction fees
  • Network Dependent: Results vary with network conditions and slippage

Manual Testing Recommendations

  • Start with small amounts (0.01-0.05 SOL) to test functionality
  • Use the visual monitor: node scroll.js to observe position changes
  • Test different configurations through node configure.js
  • Monitor console output for errors and performance metrics

πŸ› οΈ Architecture

Project Structure

MeteorShower/
β”œβ”€β”€ cli.js                 # Command line interface with yargs
β”œβ”€β”€ main.js                # Core bot logic, monitoring loop, TP/SL
β”œβ”€β”€ balance-prompt.js      # Interactive configuration prompts
β”œβ”€β”€ close-position.js      # Position closing and emergency functions
β”œβ”€β”€ configure.js           # Enhanced setup with wallet import support
β”œβ”€β”€ wallet-info.js         # Wallet information utility with security features
β”œβ”€β”€ scroll.js              # Animated monitoring display
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ dlmm.js           # Main DLMM entry point (refactored architecture)
β”‚   β”œβ”€β”€ dlmm/             # Modular DLMM architecture
β”‚   β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”‚   β”œβ”€β”€ index.js              # Core module exports
β”‚   β”‚   β”‚   └── position-creation.js  # Position creation and management
β”‚   β”‚   β”œβ”€β”€ strategies/
β”‚   β”‚   β”‚   β”œβ”€β”€ index.js              # Strategy module exports
β”‚   β”‚   β”‚   β”œβ”€β”€ swap-logic.js         # Token balancing and swapping logic
β”‚   β”‚   β”‚   └── rebalance.js          # Position rebalancing strategies
β”‚   β”‚   β”œβ”€β”€ handlers/
β”‚   β”‚   β”‚   β”œβ”€β”€ index.js              # Handler module exports
β”‚   β”‚   β”‚   β”œβ”€β”€ error-handler.js      # Comprehensive error handling
β”‚   β”‚   β”‚   └── fee-handler.js        # Fee management and processing
β”‚   β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”‚   β”œβ”€β”€ index.js              # Utility module exports
β”‚   β”‚   β”‚   β”œβ”€β”€ token-verification.js # Token assignment verification
β”‚   β”‚   β”‚   β”œβ”€β”€ sol-position-mapper.js# SOL position detection and mapping
β”‚   β”‚   β”‚   β”œβ”€β”€ bin-distribution.js   # Bin calculation and distribution
β”‚   β”‚   β”‚   β”œβ”€β”€ validation.js         # Parameter validation utilities
β”‚   β”‚   β”‚   └── wallet-scanner.js     # Wallet scanning utilities
β”‚   β”‚   └── test-integration.js       # Integration testing suite
β”‚   β”œβ”€β”€ dlmm-backup.js    # Original working implementation (reference)
β”‚   β”œβ”€β”€ bin-array-checker.js # Bin array initialization fee checking
β”‚   β”œβ”€β”€ solana.js         # Solana blockchain utilities
β”‚   β”œβ”€β”€ jupiter.js        # Jupiter DEX integration
β”‚   β”œβ”€β”€ price.js          # CoinGecko price feed integration
β”‚   β”œβ”€β”€ retry.js          # Retry logic for failed operations
β”‚   β”œβ”€β”€ math.js           # Mathematical utilities and calculations
β”‚   β”œβ”€β”€ logger.js         # Session-based logging with date organization
β”‚   β”œβ”€β”€ pnl-tracker.js    # Comprehensive P&L tracking and analysis
β”‚   β”œβ”€β”€ priority-fee.js   # Dynamic priority fees with RPC detection
β”‚   β”œβ”€β”€ sender.js         # Helius Sender integration for ultra-low latency
β”‚   β”œβ”€β”€ balance-utils.js  # Wallet balance utilities and SOL management
β”‚   β”œβ”€β”€ fee-utils.js      # Fee calculation and handling utilities
β”‚   β”œβ”€β”€ position-manager.js # Position management utilities
β”‚   └── constants.js      # Application constants and configurations
β”œβ”€β”€ package.json          # Dependencies and npm scripts
└── .env                  # Environment configuration

Operation Flow

  1. Interactive Setup β†’ User-friendly prompts for all configuration
  2. Position Creation β†’ Open DLMM position with specified parameters
  3. Monitoring Loop β†’ Continuously track price, position health, and P&L
  4. Smart Rebalancing β†’ Close and reopen position when price exits range
  5. Fee Compounding β†’ Automatically reinvest earned fees (if enabled)
  6. Risk Management β†’ Monitor TP/SL conditions and auto-close if triggered

Key Components

  • Main Loop: Real-time monitoring with configurable intervals
  • Position Manager: DLMM SDK integration for position operations
  • Rebalancing Engine: Swapless and traditional rebalancing strategies
  • Risk Manager: Take profit, stop loss, and safety systems
  • Price Oracle: CoinGecko integration for USD valuations
  • Swap Engine: Jupiter integration for token exchanges

Modular Architecture Benefits

  • πŸ”§ Maintainability: Clean separation of concerns across focused modules
  • πŸ›‘οΈ Reliability: Isolated error handling and robust retry mechanisms
  • ⚑ Performance: Optimized code paths and efficient resource usage
  • 🎯 Testability: Comprehensive integration testing with modular components
  • πŸ“ˆ Scalability: Easy extension and modification of individual components

πŸ” Monitoring & Logs

Real-Time Console Output with Clean UI

πŸš€ Welcome to MeteorShower DLMM Bot!

🎯 Position Monitor Active
═══════════════════════════════════════════════════════════════════════════════════════
πŸ“Š Time      β”‚ πŸ’° Value   β”‚ πŸ“ˆ P&L     β”‚ πŸ“Š P&L%   β”‚ πŸ’Ž Fees   β”‚ πŸ”„ Rebal β”‚ 🎯 Exit
─────────────────────────────────────────────────────────────────────────────────────
⏰ 7:05:47   β”‚ $   21.77  β”‚ βœ…+$  1.32 β”‚    +6.4%  β”‚ $   0.48  β”‚     1    β”‚ πŸ“ˆ+15% πŸ›‘οΈ-10%
πŸ“Š Position: Bin 8193 β”‚ Range 8180-8210 β”‚ Status: 🟒 IN-RANGE
   🟒 Position healthy (13↕17 bins from edges)
πŸ’‘ Press 'D' to toggle debug output | Session: ms-2024-01-15T10:30:45.123Z

Session-Based Logging System

Clean Console with Comprehensive Background Logging

  • Production UI: Clean, focused console output for monitoring
  • Debug Toggle: Press D key to show/hide detailed debug messages in real-time
  • Session Logs: All debug detail saved to logs/YYYY-MM-DD/ms-timestamp.log
  • Structured Data: Machine-readable logs in .jsonl format for analysis
  • Date Organization: Logs automatically organized by date for easy navigation

Monitoring Features

  • Position Health: Active bin tracking vs position range
  • P&L Metrics: Real-time profit/loss, percentage, and fees
  • Rebalancing Events: Detailed logs with transaction signatures
  • TP/SL Status: Current take profit and stop loss settings
  • Price Movement Analysis: Bins from edges, price coverage

Enhanced Logging Features

Console Logging:

  • Clean Production Mode: Focused output with essential information
  • Interactive Debug Toggle: Press D to show/hide debug messages
  • Real-Time Switching: Toggle debug visibility without restarting bot

File Logging (Always Active):

  • Session-Based: Each run gets unique timestamped log files
  • Date Organization: Logs stored in logs/YYYY-MM-DD/ directories
  • Dual Format: Text logs (.log) and structured data (.jsonl)
  • Complete Detail: All debug information captured regardless of console setting

Log Levels in .env:

  • error - Only critical errors
  • warn - Warnings and errors
  • info - Standard operation info (recommended)
  • debug - Detailed debugging information (affects file logging verbosity)

🚨 Safety Guidelines & Best Practices

Before Running

  1. Start with small amounts to test strategy
  2. Understand liquidity provision risks (impermanent loss, volatility)
  3. Backup your wallet keypair securely
  4. Test on devnet first if available
  5. Review all configuration settings carefully

During Operation

  1. Monitor console output for errors or unusual activity
  2. Keep sufficient SOL for transaction fees (>0.1 SOL recommended)
  3. Check position performance regularly through P&L display
  4. Be aware of high volatility periods that may trigger frequent rebalancing
  5. Use Ctrl+C to stop the bot gracefully

Risk Management Recommendations

  1. Set appropriate TP/SL levels based on your risk tolerance
  2. Use wider bin spans for less frequent rebalancing
  3. Monitor during high volatility periods more closely
  4. Have exit strategies prepared for different market conditions
  5. Don't invest more than you can afford to lose

πŸ†˜ Troubleshooting

Common Issues & Solutions

"RPC_URL is not set" Error

```bash

Solution: Check .env file

echo "RPC_URL=https://your-rpc-endpoint" >> .env


#### **"Transfer: insufficient lamports" Error**
- **Cause**: Insufficient SOL for transaction fees
- **Solution**: Add more SOL to wallet (minimum 0.1 SOL recommended)
- **Check**: Verify `PRIORITY_FEE_FALLBACK_MICROS` setting

#### **"No positions found" in close-position.js**
- **Cause**: Position detection issue or no active positions
- **Solution**: Verify positions exist with wallet explorer
- **Check**: Ensure correct RPC endpoint and wallet path

#### **Position Not Rebalancing**
- **Cause**: Price hasn't moved outside position range
- **Solution**: Check position range vs current active bin
- **Verify**: Monitor interval and rebalancing trigger logic

#### **TP/SL Not Triggering**
- **Cause**: P&L hasn't reached threshold or calculation error
- **Solution**: Verify P&L calculation and threshold settings
- **Check**: Monitor TP/SL status in console output

#### **High Gas Fees**
- **Cause**: Network congestion or high priority fees
- **Solution**: Adjust `PRIORITY_FEE_FALLBACK_MICROS` in .env
- **Consider**: Using lower priority during off-peak hours

#### **Bin Array Initialization Fees**
- **Cause**: Position range extends into uninitialized bin arrays
- **Solution**: Wide positions (>100 bins) may require 0.2-0.4 SOL initialization fees
- **Prevention**: Use `checkBinArrayInitializationFees()` for advance cost estimation
- **Note**: One-time fees are permanent (not recoverable)

#### **Module Import Errors**
- **Cause**: Issues with the new modular architecture
- **Solution**: Ensure all dependencies are installed with `npm install`
- **Check**: Node.js version 16+ required for ES module support
- **Verify**: `.env` file has `"type": "module"` in package.json

#### **RPC Compatibility Issues**
- **Cause**: Helius-specific functions on non-Helius RPCs
- **Solution**: Bot automatically detects RPC provider and uses fallbacks
- **Enhancement**: Consider Helius RPC for full feature compatibility
- **Fallbacks**: Dynamic priority fees fall back to static values on other RPCs

### Emergency Procedures

#### **Stop the Bot Immediately**
```bash
# Press Ctrl+C in the terminal
^C
# Bot will complete current operation and stop safely

Emergency Position Closure

# Close all positions and swap to SOL
node cli.js close

# Manual closure if CLI fails
node close-position.js

Check Current Status

# View wallet balances and position status
node balance-prompt.js

# View wallet information and public key
node wallet-info.js

# Check recent transactions on Solana explorer
# Use your wallet address: https://solscan.io/account/YOUR_WALLET_ADDRESS

Reset Configuration

# Backup current settings
cp .env .env.backup

# Reconfigure from scratch with enhanced wallet setup
node configure.js

πŸ”— Additional Resources

Documentation Links

Community & Support

  • GitHub Issues: Report bugs and request features
  • Meteora Discord: Join for DLMM strategy discussions
  • Solana Discord: General Solana development support

Development Information

  • Language: JavaScript (ES modules)
  • Runtime: Node.js 16+
  • Testing: Comprehensive integration test suite
  • Contributing: Community contributions welcome

πŸ“„ License

This project is open-source software provided under the MIT License. See LICENSE file for details.


⚑ Recent Updates & Version History

Latest Version (v4.0) - Major Architecture Overhaul

πŸ—οΈ Complete Modular Refactoring

  • Restructured from 1500-line monolithic file to clean, modular architecture
  • Separated concerns across focused modules (core, strategies, handlers, utils)
  • Improved maintainability with clear separation of responsibilities
  • Enhanced testability with isolated, testable components
  • Better error isolation and recovery mechanisms

πŸ”§ Critical Bug Fixes & Improvements

  • Fixed BN.js TypeError: Resolved Cannot create property 'negative' on number errors
  • NaN Value Handling: Fixed price calculation failures and undefined decimal issues
  • Budget Enforcement: Comprehensive SOL budget validation and clamping logic
  • Position Validation: Improved position creation validation with retry mechanisms
  • Bin Span Limits: Corrected validation to allow up to 1400 bins (was incorrectly 150)

πŸ’° New Bin Array Fee Management

  • Proactive Fee Checking: Estimates bin array initialization fees before position creation
  • User Confirmation: Interactive prompts for expensive initialization operations
  • RPC Compatibility: Helius-optimized with graceful fallbacks for other providers
  • Cost Transparency: Clear breakdown of one-time initialization costs

⚑ Enhanced RPC Compatibility

  • Provider Detection: Automatic detection of Helius, QuickNode, Alchemy, and other RPCs
  • Fallback Systems: Robust fallbacks for Helius-specific functions on other RPCs
  • Better Error Messages: Informative messages about RPC-specific limitations
  • Dynamic Priority Fees: Enhanced fee estimation with provider-specific optimizations

πŸ” Professional Logging & Monitoring System

  • Session-Based Logging: Date-organized logs (logs/YYYY-MM-DD/) with unique session identifiers
  • Clean Console UI: Production-ready interface with interactive debug toggle (D key)
  • Comprehensive P&L Analysis: Bin-level precision for accurate TP/SL triggers
  • Dual-Format Logging: Text (.log) and structured data (.jsonl) for analysis
  • Real-Time Debug Control: Toggle debug visibility without restarting bot

🎯 Enhanced Take Profit & Stop Loss

  • Comprehensive P&L Integration: TP/SL triggers now use bin-level analysis data
  • Timing Alignment: Respects PNL_CHECK_INTERVAL_SECONDS for accurate trigger timing
  • Precision Improvements: Uses detailed position analysis instead of basic wallet calculations

πŸ” Enhanced Wallet Management

  • Interactive wallet setup with 3 options (create new, import base58, use existing)
  • Phantom/Solflare Import: Direct base58 private key import with automatic JSON conversion
  • Wallet Info Utility: Safe wallet information display with optional private key access
  • Enhanced security warnings and validation for all wallet operations
  • Auto-detection of existing wallets with fallback handling

Previous Version (v3.0) Features

🎯 Take Profit & Stop Loss System

  • Position-specific TP/SL triggers (not wallet-wide)
  • Configurable profit/loss thresholds
  • Automatic position closure and token swapping
  • Real-time TP/SL status monitoring

πŸ”„ Enhanced Swapless Rebalancing

  • Direction-based strategy implementation
  • Configurable bin spans for swapless positions
  • Proper active bin positioning (0 distance from current price)
  • Minimized swap fees and slippage

πŸ’° Advanced Auto-Compounding

  • Fee-only compounding to prevent wallet drainage
  • Proportional Token X and Token Y fee reinvestment
  • Accurate fee tracking and P&L calculation

πŸ“ˆ Comprehensive P&L Tracking

  • Real-time profit/loss monitoring from initial deposit
  • Total fees earned tracking across rebalances
  • Rebalance counter and performance metrics
  • USD-denominated position valuation

πŸ›‘οΈ Improved Safety & Reliability

  • Fixed "insufficient lamports" errors during rebalancing
  • Proper SOL buffer management
  • Enhanced error handling and retry logic
  • Position-specific balance usage (no double-counting)

πŸŽ›οΈ Interactive Configuration System

  • User-friendly step-by-step prompts
  • Visual bin coverage and price range displays
  • Comprehensive configuration validation
  • Graceful cancellation handling

Key Technical Improvements

  • Exact Balance Usage: Uses precise amounts from closed positions
  • Position Detection: Robust SDK data structure handling
  • Module Import Handling: Fixed Windows path compatibility issues
  • Swapless Logic: Proper token allocation based on rebalance direction
  • Error Recovery: Enhanced retry mechanisms for network issues

πŸ”„ Recent Reliability Fixes

  • Progressive Slippage Retry: Fixed "ExceededBinSlippageTolerance" errors during volatile rebalancing with 1%, 2%, 3% progressive slippage
  • Balance Caching Fix: Retry attempts now respect original SOL limits instead of using unclamped wallet totals
  • Jupiter Ultra API Improvements: Fresh order requests on each retry with dynamic slippage recalculation instead of reusing stale orders
  • Position-Only Operation: Bot never exceeds initial deposit + earned gains/losses, wallet reserves remain untouched

Built with ❀️ for the Solana DeFi ecosystem

Disclaimer: This software is experimental. Always test with small amounts and understand the risks involved in liquidity provision and automated trading.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 93.2%
  • HTML 3.9%
  • CSS 2.9%