Skip to content

MayhemStrategy/Mayhem-Strategy

Repository files navigation

Mayhem Strategy - Trading Bot for Solana

https://x.com/mayhemstrategy

image

Overview

Mayhem Strategy is a sophisticated trading system that exploits the Mayhem bot mechanics on PumpFun to create sustainable tokenomics with long-term viability through automated buyback mechanisms, liquidity management, and price stabilization strategies.

Key Features

  • Mayhem Bot Exploitation: Advanced detection and exploitation of pump-and-dump patterns on PumpFun
  • Automated Buyback Engine: Sophisticated token buyback mechanism to stabilize prices and sustain tokenomics
  • Liquidity Management: Automatic liquidity rebalancing and market-making
  • Risk Management: Comprehensive position sizing, stop-loss, and take-profit management
  • Real-time Monitoring: Dashboard monitoring, alerting, and performance analytics
  • Production-Ready: Error handling, logging, retry mechanisms, and graceful shutdown

Architecture

Core Components

src/
├── bot.ts                 # Main trading bot orchestrator
├── index.ts               # Entry point
├── monitor.ts             # Monitoring dashboard
├── buyback.ts             # Buyback daemon
├── config/
│   └── index.ts           # Configuration management
├── services/
│   ├── solana.ts          # Solana blockchain interactions
│   ├── pumpfun.ts         # PumpFun API integration
│   ├── dex.ts             # DEX/AMM interactions
│   └── buyback.ts         # Buyback engine
├── strategies/
│   └── mayhem.ts          # Mayhem exploitation strategy
├── types/
│   └── index.ts           # Type definitions
├── utils/
│   └── logger.ts          # Structured logging
└── monitor/
    └── service.ts         # Monitoring and alerting

Getting Started

Prerequisites

  • Node.js >= 18.0.0
  • npm >= 9.0.0
  • Solana wallet with SOL balance
  • PumpFun API credentials (optional)

Installation

# Clone repository
git clone https://github.com/mayhem-strategy/bot.git
cd bot

# Install dependencies
npm install

# Build TypeScript
npm run build

Configuration

  1. Create .env file from template:
cp .env.example .env
  1. Update .env with your settings:
# Solana Configuration
SOLANA_RPC_ENDPOINT=https://api.mainnet-beta.solana.com
PRIVATE_KEY=<your_base58_encoded_private_key>
WALLET_ADDRESS=<your_wallet_address>

# Trading Configuration
TRADING_ENABLED=true
MAX_SLIPPAGE=0.02
MIN_LIQUIDITY=1000

# Buyback Configuration
BUYBACK_ENABLED=true
BUYBACK_THRESHOLD=0.15
BUYBACK_AMOUNT=50
BUYBACK_INTERVAL=60000

# Monitoring
ALERT_WEBHOOK_URL=<discord_webhook_url>
LOG_LEVEL=info

Running the Bot

Start the main trading bot:

npm start
# or
npm run dev  # Development with auto-reload

Start the monitoring dashboard:

npm run monitor

Start the buyback daemon (separate process):

npm run buyback

Strategy Details

Mayhem Exploitation Strategy

The bot analyzes PumpFun tokens for "Mayhem" opportunities - periods of intense buying pressure or sentiment manipulation.

Detection Criteria

  1. Hype Phase Analysis: Tracks token lifecycle (1-5 phases)
  2. Buy Pressure: Percentage of buy volume vs. total volume
  3. Volatility: Uses log returns to measure price volatility
  4. Trade Frequency: Number of trades in monitoring window

Signal Generation

  • Strong Buy: Hype ≥ 3, Buy pressure > 70%, Low volatility
  • Buy: Hype ≥ 2, Buy pressure > 60%
  • Sell: Buy pressure < 30%, Hype ≤ 2
  • Hold: Mixed signals

Buyback Engine

The buyback engine stabilizes token price by automatically purchasing tokens when price falls below the configured threshold.

Mechanism

  1. Threshold Detection: Monitors price decline percentage
  2. Signal Generation: Evaluates buyback need based on market conditions
  3. Position Sizing: Calculates optimal buyback amount
  4. Execution: Executes buyback transaction on DEX
  5. Impact Tracking: Measures price impact of buyback

Configuration

buybackParameters: {
  enabled: true,
  threshold: 0.15,           // 15% price decline triggers buyback
  amount: 50,                // Buy 50 SOL worth each time
  interval: 60000,           // Check every 60 seconds
  targetPriceFloor: 0.00005, // Don't buy below this price
  maxBuybacksPerDay: 10      // Limit buybacks per day
}

Risk Management

Position Management

  • Maximum position size: Configured in riskParameters
  • Maximum open positions: 10 concurrent positions
  • Stop-loss: Automatically close positions on 10% loss
  • Take-profit: Automatically close positions on 25% gain

Daily Risk Limits

  • Daily loss limit: $100 per day (configurable)
  • Max position allocation: 30% of portfolio
  • Slippage tolerance: 2% (configurable)

Risk Assessment

The system continuously assesses risk on four dimensions:

  1. Portfolio Risk: Current daily loss vs. daily limit
  2. Day Trading Risk: Leveraged exposure
  3. System Risk: Error rate and reliability
  4. Single Token Risk: Concentration risk

Risk levels:

  • Safe: Overall score < 0.4
  • Caution: Overall score 0.4-0.6
  • Danger: Overall score 0.6-0.8
  • Critical: Overall score > 0.8

Monitoring & Alerting

Dashboard

Start the monitoring dashboard:

npm run monitor

Displays real-time:

  • Portfolio value and P&L
  • Open positions
  • Performance metrics (24h)
  • Active alerts

Alerts

Alerts are published with severity levels:

  • Info: General information
  • Warning: Non-critical issues
  • Error: Trading errors, connection issues
  • Critical: Risk management triggers, system failures

Webhook Integration

Configure Discord or other webhook for alert notifications:

ALERT_WEBHOOK_URL=https://discordapp.com/api/webhooks/...

Performance Metrics

Tracked Metrics

  • Win Rate: Percentage of profitable trades
  • Profit Factor: Gross profit / gross loss
  • Sharpe Ratio: Risk-adjusted returns
  • Max Drawdown: Largest decline from peak
  • Average Win/Loss: Mean profit/loss per trade

System Metrics

  • RPC Latency: Blockchain connectivity
  • Memory Usage: Process memory consumption
  • CPU Usage: Processor utilization
  • Error Rate: Percentage of failed operations

API Reference

TradingBot

// Initialize bot
await tradingBot.initialize();

// Start trading
await tradingBot.start();

// Stop trading
await tradingBot.stop();

// Get portfolio
tradingBot.getPortfolio();

// Get positions
tradingBot.getPositions();

// Get status
tradingBot.getStatus();

Strategies

// Analyze Mayhem opportunity
const signal = await mayhemStrategy.analyzeMayhemOpportunity(mint);

// Monitor for entry
await mayhemStrategy.monitorForEntry(mint, durationMs);

// Check exit condition
mayhemStrategy.shouldExit(position);

Buyback Engine

// Analyze buyback need
const signal = buybackEngine.analyzeBuybackNeed(
  mint,
  currentPrice,
  previousPrice,
  volume24h,
  holders
);

// Execute buyback
const result = await buybackEngine.executeBuyback(mint, amount);

// Get statistics
buybackEngine.getBuybackStats();

Deployment

Development

npm run dev

Production

# Build
npm run build

# Start
npm start

Docker Deployment

Create Dockerfile:

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY dist ./dist

CMD ["node", "dist/index.js"]

Build and run:

docker build -t mayhem-strategy .
docker run -d --env-file .env mayhem-strategy

Process Management (PM2)

Install PM2:

npm install -g pm2

Create ecosystem.config.js:

module.exports = {
  apps: [
    {
      name: 'trading-bot',
      script: './dist/index.js',
      instances: 1,
      exec_mode: 'fork',
      watch: false,
      env_file: '.env',
    },
    {
      name: 'buyback-daemon',
      script: './dist/buyback.js',
      instances: 1,
      exec_mode: 'fork',
      watch: false,
      env_file: '.env',
    },
    {
      name: 'monitor',
      script: './dist/monitor.js',
      instances: 1,
      exec_mode: 'fork',
      watch: false,
      env_file: '.env',
    },
  ],
};

Start with PM2:

pm2 start ecosystem.config.js
pm2 logs
pm2 stop all

Security Considerations

Wallet Security

  1. Never commit .env file to version control
  2. Use hardware wallet for large balances
  3. Rotate private keys periodically
  4. Restrict IP access to RPC endpoints
  5. Use environment variables for sensitive data

API Security

  1. Rate limiting for PumpFun API calls
  2. Timeout handling for network requests
  3. Retry with exponential backoff
  4. Circuit breakers for failing services

Smart Contract Interaction

  1. Approval scoping: Only approve necessary amounts
  2. Reentrancy protection: Built into Solana programs
  3. Slippage protection: Configurable limits
  4. Amount validation: Check before execution

Troubleshooting

Common Issues

Bot won't start:

# Check configuration
npm run type-check

# Check connection
curl https://api.mainnet-beta.solana.com

Insufficient balance:

# Check wallet balance
solana balance <wallet_address>

# Fund wallet from exchange or faucet

RPC timeout errors:

# Try different RPC endpoint in .env
SOLANA_RPC_ENDPOINT=https://api.mainnet-beta.solana.com
# Alternative: https://solana-api.projectserum.com

Transactions failing:

# Check transaction signature
solana confirm <signature>

# Check account info
solana account <account_address>

Monitoring Logs

Logs are organized by context (service):

[bot.ts] Trading loop error
[SolanaService] Transaction sent
[MayhemStrategy] Entry opportunity found
[BuybackEngine] Buyback executed
[MonitoringService] Alert published

Set log level:

LOG_LEVEL=debug    # Most verbose
LOG_LEVEL=info     # Standard
LOG_LEVEL=warn     # Important warnings only
LOG_LEVEL=error    # Only errors

Performance Optimization

Configuration Tuning

  1. Poll Interval: Adjust for responsiveness vs. RPC load
  2. Monitoring Interval: Balance between data freshness and network usage
  3. Position Limits: Higher limits = more trading but more risk
  4. Slippage Tolerance: Lower = better prices but higher failure rate

Network Optimization

  1. Use RPC node close to your location
  2. Implement connection pooling
  3. Cache market data locally
  4. Batch RPC calls where possible

Contributing

  1. Fork repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

License

MIT License - see LICENSE file for details

Support & Community

  • Issues: GitHub Issues
  • Discussions: GitHub Discussions
  • Discord: [Join Discord Server]
  • Documentation: Full Docs

Disclaimer

⚠️ WARNING: This is trading software for use on Solana blockchain. Trading involves risk of loss. Past performance does not guarantee future results. Use at your own risk and only with capital you can afford to lose.

Roadmap

  • Raydium LP management
  • Multi-wallet coordination
  • Advanced risk models (VaR, Expected Shortfall)
  • Machine learning price prediction
  • Option strategies
  • Cross-chain arbitrage
  • Community signal sharing
  • Web dashboard

Version: 1.0.0 Last Updated: 2026-04-08 Maintainer: Mayhem Strategy Team

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors