Pump.fun WebSocket Guide: Build a Crypto Trading Bot for Popular Coins
Hello, Crypto Warriors!
Welcome back to the Pump.Fun Trading Bot series! Are you ready to take your crypto trading game to the next level? In this guide, we’ll dive deep into advanced trading bot strategies designed to maximize your profits while minimizing risks.
Whether you're a seasoned trader or just starting your journey, mastering automation is the key to staying ahead in the fast-paced crypto market.
If you're new here or missed our earlier lessons—like setting up WebSocket connections or creating your account—don’t worry! Start with our comprehensive guide, Mastering Pump.Fun Trading with WebSocket: Series 1, to build a solid foundation for success.
So, What’s Being Built Today?
We’re building a cutting-edge Popular coin trading bot for the Pump.Fun platform that leverages WebSocket technology to monitor live market transactions and token prices in real time.
Here’s how it works:
- The bot identifies coins trading above a predefined threshold price.
- It tracks unique wallets interacting with the coin, gauging its popularity.
- Once the number of wallets surpasses a certain limit, the bot flags the token as "popular" and executes a buy order.
- After buying, the bot continuously monitors the trade price. Based on the profit or loss margin, it decides the optimal time to sell, securing gains or mitigating losses effectively.
This intelligent trading bot is designed to streamline your trading process, allowing you to capitalize on market trends without constant manual effort. It’s your ultimate tool for staying ahead in the dynamic and competitive world of cryptocurrency trading!
Example:
Tracking Price:
The price of Token X rises above $0.0001. The bot starts monitoring transactions.
Wallet Count Validation:
Unique wallets begin interacting with Token X:
- Transaction 1: Wallet A interacts with Token X. Wallet count: 1.
- Transaction 15: Wallet P interacts with Token X. Wallet count: 15.
- Transaction 35: Wallet Z interacts with Token X. Wallet count exceeds 30.
Buy Triggered:
The bot identifies Token X as "popular" because the wallet count has surpassed 30 and the price is still above $0.0001.
- Buy executed: The bot buys Token X at $0.00012.
Profit or Stop-Loss:
The bot continues tracking the price of Token X:
- If the price rises:
- The price reaches $0.000132 (profit threshold).
- Sell executed: The bot sells Token X for a profit.
- Profit logged: Gain = $0.000012 per token.
- If the price falls:
- The price drops to $0.000114 (stop-loss threshold).
- Sell executed: The bot sells Token X to minimize loss.
- Loss logged: Loss = $0.000006 per token.
The bot automates the process, ensuring precise and timely execution of trades in response to market trends.
Time to Create a Bot
Preconditions
Before diving in, make sure you have the following ready:
- Python: Ensure you have Python installed (version 3.x or higher is recommended).
- API Key: Register for a free account at nolimitnodes.com to obtain your API key.
- IDE: Open your favorite IDE and create a new script. Name the script:
popularCoinTradingBot.py
.
Getting Started
To kick things off, we'll import the essential libraries that will power our trading bot:
import websocket
import json
import threading
from threading import Lock
Global Variables
Every trading bot relies on key variables to define its behavior, and our bot is no exception. These variables ensure that the bot operates according to predefined trading strategies:
- TRACKING_PRICE: The base price used as the threshold to start monitoring tokens.
- PROFIT_PERCENT: Defines the profit percentage at which the bot will sell the token.
- STOP_LOSS_PERCENT: The percentage loss that triggers the bot to sell to minimize risk.
- min_wallet_number: Additional parameters to validate trading conditions.
These global variables give the bot flexibility to adapt to various trading scenarios and strategies.
Data Structures
The bot uses simple yet effective data structures to manage trading data:
- buy_dict: Tracks tokens the bot has purchased.
- sell_dict: Keeps a record of tokens sold.
- lock: A threading lock to ensure safe, simultaneous access to shared resources.
Additionally, statistical variables like buy_trade
, profit_trade
, loss_trade
, and TOTAL_PROFIT_PRICE
help monitor the bot’s performance in real-time.
# Constants
TRACKING_PRICE = 0.0000001000
PROFIT_PERCENT = 10.0 # % of profit to trigger Sell
STOP_LOSS_PERCENT = 5.0 # % of loss to trigger Sell
min_wallet_number = 10
min_price =0
# Shared Resources
buy_dict = {}
sell_dict = {}
lock = Lock()
# Statistics
buy_trade = 0
profit_trade = 0
loss_trade = 0
TOTAL_PROFIT_PRICE = 0
# WebSocket URL and subscription message
URL = "wss://api.nolimitnodes.com/pump-fun?api_key=YOUR_API_KEY"
To proceed, we send a request to the server to retrieve the necessary cryptocurrency information.
SUBSCRIBE_PUMP_FUN_TRADE = {
"method": "pumpFunTradeSubscribe",
"params": {"referenceId": "hello", "coinAddress": "all"}
}
These powerful functions will elevate your bot to the next level, making it a powerhouse capable of outsmarting the top crypto analysts.
How the Bot Processes Trade Events
Discover how the bot efficiently handles each trade event with this step-by-step breakdown:
- Track Tokens for Buy Signals: Monitor tokens whose prices exceed
TRACKING_PRICE
and track their associated wallets. - Trigger Buys: If the number of wallets exceeds the threshold (
min_wallet_number
), initiate a buy and move the token tosell_dict
. - Monitor Sell Opportunities: Tokens in
sell_dict
are sold when they hit either thePROFIT_PERCENT
target or fall below theSTOP_LOSS_PERCENT
. - Update Metrics: Maintain and log statistics for buy trades, profitable sells, and stop-loss hits.
def handle_transaction_message(ws, message):
global buy_trade, profit_trade, loss_trade, TOTAL_PROFIT_PRICE, min_wallet_number
try:
data = json.loads(message)
except json.JSONDecodeError:
print("Received invalid JSON data")
return
if data.get("method") == "tradeEventNotification":
trade_details = data["result"]
trade_price = float(trade_details["price"]["sol"])
trade_wallet = trade_details["wallet"]["address"]
trade_token_out = trade_details["token_out"]["token"]
with lock: # Ensure thread safety
# Start tracking if price is above TRACKING_PRICE
if trade_price > TRACKING_PRICE:
if ((trade_token_out not in buy_dict) and (trade_token_out not in sell_dict)):
buy_dict[trade_token_out] = {"wallets": [trade_wallet], "count": 1}
if( trade_token_out in buy_dict):
if (trade_wallet not in buy_dict[trade_token_out]["wallets"]):
buy_dict[trade_token_out]["wallets"].append(trade_wallet)
buy_dict[trade_token_out]["count"] += 1
if (buy_dict[trade_token_out]["count"] > min_wallet_number):
buy_price = trade_price
buy_dict[trade_token_out]["buyPrice"] = buy_price
coin = buy_dict.pop(trade_token_out)
sell_dict[trade_token_out] = coin
buy_trade += 1
print(f"#Bought:{buy_trade}#Profit:{profit_trade}#Loss:{loss_trade}# BUY - Condition met : Trade_price [{trade_price:.10f}], Buy_price [{buy_price:.10f}], Total_price profit/loss [{TOTAL_PROFIT_PRICE:.10f}], (Address: {trade_token_out})"
)
elif (trade_token_out in sell_dict):
buy_price = sell_dict[trade_token_out]["buyPrice"]
if trade_price >= buy_price * (1 + PROFIT_PERCENT / 100.0):
profit_trade += 1
# TOTAL_PROFIT_PERCENT += (((trade_price / buy_price) - 1) * 100)
TOTAL_PROFIT_PRICE += ((trade_price - buy_price) * (10.0 / buy_price))
# print(f"TOTAL_PROFIT_PRICE {TOTAL_PROFIT_PRICE}");
print(f"#Bought:{buy_trade}#Profit:{profit_trade}#Loss:{loss_trade}# SELL - Target Achieved : Trade_price [{trade_price:.10f}], Buy_price [{buy_price:.10f}], Total_price profit/loss [{TOTAL_PROFIT_PRICE:.10f}], (Address: {trade_token_out})"
)
sell_dict.pop(trade_token_out, None)
elif trade_price <= buy_price * (1 - STOP_LOSS_PERCENT / 100.0):
loss_trade += 1
# TOTAL_LOSS_PERCENT += ((1 - (trade_price / buy_price)) * 100)
TOTAL_PROFIT_PRICE += ((trade_price - buy_price) * (10.0 / buy_price))
# print(f"TOTAL_PROFIT_PRICE {TOTAL_PROFIT_PRICE}");
print(f"#Bought:{buy_trade}#Profit:{profit_trade}#Loss:{loss_trade}# SELL - Stop loss : Trade_price [{trade_price:.10f}], Buy_price [{buy_price:.10f}], Total_price profit/loss [{TOTAL_PROFIT_PRICE:.10f}], (Address: {trade_token_out})"
)
sell_dict.pop(trade_token_out, None)
def on_error(ws, error):
print(f"Error: {error}")
def on_close(ws, close_status_code, close_msg):
print("WebSocket closed")
def on_open(ws):
print("WebSocket connection opened")
ws.send(json.dumps(SUBSCRIBE_PUMP_FUN_TRADE))
print(f"Subscription message sent: {SUBSCRIBE_PUMP_FUN_TRADE}")
Managing WebSocket Connections
Build a function that efficiently manages WebSocket connections using threading to handle multiple connections simultaneously—it's like having a team of crypto experts working tirelessly for you, 24/7!
def run_websocket(url):
ws = websocket.WebSocketApp(
url,
on_message=lambda ws, msg: handle_transaction_message(ws, msg),
on_error=on_error,
on_close=on_close
)
ws.on_open = on_open
ws.run_forever()
# Start WebSocket in a separate thread
thread_transaction = threading.Thread(target=run_websocket, args=(URL,))
thread_transaction.start()
thread_transaction.join()
Ready to Launch the Bot? Here's How to Start on Replit
- Tap the "Open on Replit" button below to get started.
- You'll arrive at the Replit dashboard with the project titled "Trading Bot with NolimitNodes."
- Log in to your Replit account, or create one if you’re new to Replit.
- Click the "Remix this app" button located below the project name to create your own copy.
- Adjust the project settings to suit your preferences.
- The editor will load, displaying the main.py file.
- Hit the Run button and follow the on-screen instructions provided by the bot.
- Check the right panel to find the file where the code resides.
- Replace "YOUR_API_KEY" with your actual API key to enable functionality.
That's it! are you impressed after seeing how the bot is performing? Now, sit back, relax, and start trading to maximize your gains!
Congratulations on Building Your Popular Coin Trading Bot!
You’ve successfully created a powerful trading bot to monitor live market prices, track popular tokens, and execute strategic buy and sell decisions. With this bot, you can:
- Seize profitable buying opportunities.
- Maximize your earnings with precision.
- Protect investments using smart stop-loss techniques.
Take charge of your crypto trading journey and watch your profits soar in the dynamic market!
Did You Miss Series 3?
Discover the powerful bot that tracks pullbacks, monitors trends, and makes calculated buy and sell decisions. Click on "Mastering Pump.Fun Drawdown with WebSocket: Series 3" to dive in and enhance your trading strategy today!
Need Help? Contact Us!
Got questions or need advice on crypto trading? Don’t hesitate to reach out.
📩 Email: robert.king@nolimitnodes.com
(Emails are checked daily for your convenience.)
Happy Trading and Profitable Adventures Ahead! 🚀