Skip to content
The Chat Archive
qwen-max-2025-01-25· Alibaba (Qwen) LMArena Human Preference 140K

Create compact, concurrent Solana memecoin bot (Python/asyncio). Goal: $100/day via many…

  1. User

    Create compact, concurrent Solana memecoin bot (Python/asyncio).

    Goal: 100/dayviamany100/day via many 1 -> $10 flips.

    Action: Auto-buy 1(SOL/USDC),auto−sell∗exactly∗at1 (SOL/USDC), auto-sell *exactly* at 10 (10x) or stop-loss (~-25% from $1).

    Tech: Use solana-py (placeholder wallet/RPC), DEX API (e.g., Jupiter).

    Features: Must find tokens (new pools OR high momentum), handle concurrent trades+monitoring, track positions, basic error handling, configurable vars (amounts, SL%).

  2. Assistant

    Below is a compact, concurrent Solana memecoin trading bot written in Python using asyncio and solana-py. The bot aims to achieve the goal of flipping 1investmentsinto1 investments into 10 gains while implementing stop-loss protection. It uses a placeholder RPC and assumes integration with a DEX API like Jupiter for swaps.


    Code Implementation

    import asyncio
    import logging
    from solana.rpc.async_api import AsyncClient
    from solana.publickey import PublicKey
    from solana.transaction import Transaction
    from solana.system_program import TransferParams, transfer
    from typing import Dict, List
    
    # Configure logging
    logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
    
    # Configurable variables
    RPC_URL = "https://api.mainnet-beta.solana.com"  # Placeholder RPC URL
    WALLET_PRIVATE_KEY = b"your_private_key_here"  # Replace with your private key
    TRADE_AMOUNT_SOL = 1.0  # Amount to trade in SOL
    STOP_LOSS_PERCENT = 25  # Stop-loss percentage (e.g., 25%)
    TARGET_PROFIT_MULTIPLIER = 10  # Target profit multiplier (e.g., 10x)
    POLL_INTERVAL = 5  # Polling interval in seconds
    
    # Global state
    active_trades: Dict[str, Dict] = {}  # Tracks active trades: {token_mint: {"buy_price": float, "amount": float}}
    
    # Initialize Solana client
    solana_client = AsyncClient(RPC_URL)
    
    async def find_tokens() -> List[str]:
        """
        Simulates finding new or high-momentum tokens.
        Replace this with actual logic to scan pools or track momentum.
        """
        logging.info("Scanning for new tokens...")
        # Placeholder: Return mock token mints
        return ["TokenMint1", "TokenMint2"]
    
    async def buy_token(token_mint: str, amount: float):
        """
        Buys a token using the DEX API (e.g., Jupiter).
        """
        logging.info(f"Buying {amount} SOL worth of token {token_mint}")
        # Placeholder: Simulate buying logic
        active_trades[token_mint] = {"buy_price": 1.0, "amount": amount}
        logging.info(f"Bought token {token_mint} at $1.0")
    
    async def sell_token(token_mint: str, sell_price: float):
        """
        Sells a token using the DEX API (e.g., Jupiter).
        """
        if token_mint not in active_trades:
            logging.warning(f"No active trade found for token {token_mint}")
            return
    
        trade = active_trades[token_mint]
        buy_price = trade["buy_price"]
        amount = trade["amount"]
    
        logging.info(f"Selling token {token_mint} at ${sell_price}")
        profit = (sell_price - buy_price) * amount
        logging.info(f"Sold token {token_mint} for ${sell_price}. Profit: ${profit:.2f}")
    
        # Remove trade from active trades
        del active_trades[token_mint]
    
    async def monitor_trades():
        """
        Monitors active trades for target profit or stop-loss conditions.
        """
        while True:
            for token_mint, trade in list(active_trades.items()):
                buy_price = trade["buy_price"]
                current_price = await get_token_price(token_mint)  # Fetch current price
                if current_price >= buy_price * TARGET_PROFIT_MULTIPLIER:
                    await sell_token(token_mint, current_price)
                elif current_price <= buy_price * (1 - STOP_LOSS_PERCENT / 100):
                    await sell_token(token_mint, current_price)
            await asyncio.sleep(POLL_INTERVAL)
    
    async def get_token_price(token_mint: str) -> float:
        """
        Fetches the current price of a token.
        Replace with actual API call to fetch price.
        """
        # Placeholder: Simulate price fetching
        return 1.0 + (hash(token_mint) % 10) / 10  # Random price between $1.0 and $2.0
    
    async def main():
        """
        Main function to run the bot.
        """
        logging.info("Starting Solana memecoin bot...")
    
        # Start monitoring trades concurrently
        asyncio.create_task(monitor_trades())
    
        while True:
            try:
                # Find new tokens to trade
                tokens = await find_tokens()
                for token_mint in tokens:
                    if token_mint not in active_trades:
                        await buy_token(token_mint, TRADE_AMOUNT_SOL)
            except Exception as e:
                logging.error(f"Error in main loop: {e}")
    
            await asyncio.sleep(POLL_INTERVAL)
    
    if __name__ == "__main__":
        asyncio.run(main())
    

    Explanation of Key Components

    1. Token Discovery (find_tokens):

      • Simulates scanning for new or high-momentum tokens.
      • Replace with actual logic to query pools or track token momentum.
    2. Buying Logic (buy_token):

      • Simulates buying tokens using a DEX API (e.g., Jupiter).
      • Tracks the buy price and amount in active_trades.
    3. Selling Logic (sell_token):

      • Executes a sell order when the target profit or stop-loss condition is met.
      • Calculates and logs the profit/loss.
    4. Trade Monitoring (monitor_trades):

      • Continuously checks active trades for target profit or stop-loss conditions.
      • Uses asyncio for non-blocking monitoring.
    5. Price Fetching (get_token_price):

      • Simulates fetching the current price of a token.
      • Replace with an actual API call to fetch real-time prices.
    6. Concurrency:

      • Uses asyncio to handle concurrent tasks (e.g., token discovery, trade monitoring).
    7. Error Handling:

      • Basic error handling ensures the bot continues running even if an error occurs.
    8. Configurability:

      • Trade amount, stop-loss percentage, and polling interval are configurable.

    Next Steps

    1. Integrate with DEX API:

      • Replace placeholder buy/sell logic with actual API calls to a DEX like Jupiter.
    2. Enhance Token Discovery:

      • Implement logic to scan new pools or track high-momentum tokens using on-chain data.
    3. Optimize Performance:

      • Use a dedicated RPC provider (e.g., QuickNode) for faster responses.
    4. Add Risk Management:

      • Implement additional safeguards, such as maximum trade size or cooldown periods.
    5. Deploy Securely:

      • Store private keys securely using environment variables or a secrets manager.

    This implementation provides a solid foundation for a Solana memecoin bot. Customize and expand it based on your specific requirements and risk tolerance.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.