Coins: 17,637
Exchanges: 1,460
Market Cap: $2.607T 0.6%
24h Vol: $97.35B
Gas: 0.045 GWEI
Go Ad-free
API
TABLE OF CONTENTS

How to Build a Pump.fun Sniper Bot in Python

3.9
| by
Vikas Negi
|
Edited by
Brian Lee
-

Solana launchpads such as Pump.fun list new memecoins continuously, and price discovery can move quickly. For developers, that pace makes automated monitoring useful for running consistent, rules-based entry and exit logic.

A sniper bot is a tool designed to automatically buy newly launched tokens the moment liquidity becomes available on launchpads such as Pump.fun. By reacting instantly to on-chain events and market signals, such a bot aims to enter or exit positions more reliably than any human trader can. It is able to swiftly execute any kind of trading logic based on predetermined conditions.

In this article, we’ll walk through how to build a simple Pump.fun sniper bot using Python, leveraging the CoinGecko API, with its REST endpoints for token discovery and WebSocket streams for real-time monitoring.

Disclaimer: This guide is for educational purposes only and should not be considered financial advice. Always do your own research.

How to Build a Pump.fun Sniper Bot with CoinGecko API


What is the Architecture of a Pump.fun Sniper Bot?

At its core, a Pump.fun sniper bot follows a simple three-pillar architecture – Scan, Filter, and Execute. Here’s how each pillar works:

Pump.fun Sniper Bot Architectural Flow1. Scan (Discovery)

The Scan layer is responsible for finding opportunities. In practice, this means continuously querying a data source such as the CoinGecko API “New Pools” endpoint for newly created pools on a network and DEX. These pools represent tokens that have just launched or are about to receive liquidity, which is the exact moment sniper bots are designed to target.

2. Filter (Decision Logic)

The Filter layer takes market data from the previous scan step and applies decision logic to filter out pools that are not worth sniping, which may include low-quality or high-risk launches. Typical conditions analyzed here include:

  • Age: Is the pool recently created or has become stale (no activity)?

  • FDV (Fully Diluted Valuation): Is the valuation absurdly high relative to liquidity?

  • Graduation percentage: Has the bonding curve progress reached completion?

Pools meeting these predefined criteria are passed forward. This layer is the core of our strategy and risk control. These criteria are a starting point; additional checks and filters can be applied based on individual needs.

3. Execution (Trade Management)

Once a pool passes the filter, the Execution layer takes over. Here, the bot connects to a WebSocket stream to monitor real-time price movements. This allows it to:

  • Enter a position as soon as market conditions are met

  • React instantly to price movements

  • Trigger Take Profit or Stop Loss rules

Because meme coin price action can change in seconds, WebSockets are critical. Polling introduces latency because the server must query the data source for updates. This inherent delay makes data refresh slower compared to the continuous streaming of WebSockets. Therefore, polling is generally inadequate for the near-instantaneous decision-making required by a sniper bot.


Prerequisites

We will make use of a Jupyter notebook within VS Code as our primary development environment. Make sure to have installed the Jupyter extension.

Additionally, the following packages need to be installed or imported.

import pandas as pd
pd.set_option('display.max_columns', None)
import pytz
import duckdb
import time

import requests as rq
import json
from datetime import datetime

import os
from pathlib import Path

import asyncio
import json
import websockets
from urllib.parse import urlparse, parse_qs
import numpy as np
import psycopg

To start coding in a new notebook, simply create a new file with the .ipynb extension. To get a head start, you can clone this GitHub repository and open it in with VS Code.

CoinGecko API key

This guide uses the WebSocket API, which requires an Analyst plan or higher. To access the REST API endpoints, you will need at least a Demo API key. If you don't have one, read this guide on how to get your free Demo API key.

Setting Up the API Access

In order to have our environment set up for secure API access, we can save the keys locally to a .env file and read from there whenever needed. This file is excluded from the git repository by adding it to the exclusion list within the .gitignore file. 

The .env file should have entries like this: CG_ANALYST_API_KEY = “CG-XXXXX”

Request headers can be defined as shown below:

use_demo = {
          "accept": "application/json",
          "x-cg-demo-api-key" : CG_DEMO_API_KEY
}

use_pro = {
        "accept": "application/json",
        "x-cg-pro-api-key" : CG_PRO_API_KEY
}

Below function will handle the response from the REST API calls.

The base URLs for the Demo (free) API and the Pro API are assigned to the following variables:

PUB_URL = "https://api.coingecko.com/api/v3"
PRO_URL = "https://pro-api.coingecko.com/api/v3"

Setting up a PostgreSQL server

We will use a PostgreSQL database to store the price data streamed through the WebSocket. Follow the platform-specific instructions below to set it up:

Linux (Ubuntu/Debian)

sudo apt update
sudo apt install postgresql postgresql-contrib
sudo systemctl status postgresql
sudo -u postgres psql

In `psql`:

CREATE USER myuser WITH PASSWORD 'mypassword';
CREATE DATABASE mydb OWNER myuser;

macOS (Homebrew)

brew install postgresql@16
brew services start postgresql@16
psql -d postgres

In `psql`:

CREATE USER myuser WITH PASSWORD 'mypassword';
CREATE DATABASE mydb OWNER myuser;

Windows

  1. Download and install PostgreSQL from https://www.postgresql.org/download/windows/
  2. Use the Stack Builder/installer to set a password for the `postgres` user.
  3. Open SQL Shell (psql) and run:
CREATE USER myuser WITH PASSWORD 'mypassword';
CREATE DATABASE mydb OWNER myuser;

Connection string example:

postgresql://myuser:mypassword@localhost:5432/mydb

Step 1: How to Find New Pump.fun Token Launches

In order to discover new token launches on Pump.fun, we will make use of the "New Pools" endpoint ( /onchain/networks/{network}/new_pools) for the Solana network.

The API response will be parsed based on the below logic. Note that it is important to store the token address (different from the pool address) for our WebSocket subscription later on.

The function below is useful for collecting data from multiple pages of an API endpoint, as it accepts an optional max_pages argument to retrieve a large selection of pools.

Parsed API response is converted to a pandas DataFrame. We also change timestamps to a local timezone (CET in this case) for better readability. Output is filtered on "dex" == "pump-fun" since that is the launchpad we are currently focusing on.

A sample of the top 5 pools sorted based on “pool_created_at” timestamps is shown below:


Step 2: How to Filter Profitable Pools to Snipe

Once we have a list of pool IDs, the bot needs to inspect them to determine the best "targets." We should avoid pools containing tokens with low liquidity, a low market cap, or an age greater than a certain threshold. Given a pool address, we can fetch its data using the /onchain/networks/{network}/pools/{pool_address} endpoint.

The pool API response can then be parsed based on the logic below:

Once we have our list of pools, we can loop through them and gather details for each by calling the above endpoint. All this can be concatenated into a single pandas DataFrame.

Our filtering logic below looks for tokens which are not older than 10 minutes, have an FDV greater than 2,500 USD, and have a graduation percentage less than 75%.


Step 3: How to Monitor Real-Time Prices via WebSocket for Trade Entries & Exits

After identifying target tokens/pools in the previous section, we will monitor their real-time price activity by connecting to CoinGecko’s WebSocket API.

WebSockets maintain a persistent two-way connection, allowing the server to push real-time updates without repeated polling. This continuous data stream will run within our notebook and should be written to a database, such as PostgreSQL, which supports concurrent reads while being continuously updated. Accessing this data from a separate notebook will enable us to define and run our trading simulation logic.

First, we will store our list of target pools in a DuckDB database for access across multiple Jupyter notebooks.

The Analyst API key needs to be passed on within the WebSocket URL:

WS_URL = f"wss://stream.coingecko.com/v1?x_cg_pro_api_key={CG_ANALYST_API_KEY}"
NETWORK_ID = "solana"

We will now set up the connection to our PostgreSQL server and create a new table price_stream with the expected schema:

Since we have a token_list with multiple tokens, we will need to set up our WebSocket connection to receive data streams for all of them. This is not an issue since a maximum of 100 concurrent subscriptions are allowed per channel per socket.

Below function stream_token_prices_and_write_to_pg opens a new connection, subscribes to the OnchainSimpleTokenPrice channel for a list of token addresses, and then continuously reads messages. It then parses each incoming message and unwraps nested data when needed. Additionally, we also log subscription confirmation messages (code == 2000). For price updates (c == "G1"), we map the short keys using rename_map, convert the UNIX timestamp to a CET/CEST datetime, and insert the rows into the price_stream table which we created earlier.

The above function can be executed as: await stream_token_prices_and_write_to_pg(token_list)

It runs continuously and populates our database with the incoming stream of data for all the tokens. We can now switch to another notebook in order to build and execute our trading logic.

To fetch the list of tokens saved earlier to a local DuckDB database, use the following code snippet:

To verify if our PostgreSQL database actually has any data, we can run the following query:

Our trading logic will act on the data read from our PostgreSQL database. It needs to have the following conditions built-in:

  • Entry price: Price at detection

  • Take Profit: Sell if Price > Entry + 50%

  • Stop Loss: Sell if Price < Entry - 20%

We start with an empty state (defined as “None”), run the simulation logic every 2 seconds and then save the state for every token. A log line is printed only when the state changes. Additionally, the line color is configured for easy visibility of profit (green) and loss (red) trades.

The following is an example of the sniper bot's operational logs and results:


Further Enhancements

Once our logic is profitable in simulation, we can consider these enhancements for production.

At this stage, we are hardening it for real-world conditions where latency, volatility, and execution risk matter.

Wallet Integration

To move beyond paper trading, the bot needs direct wallet and transaction support on Solana.

In Python, this is typically done using libraries such as solana.py or Solders, which allow us to:

  • Load and manage a Solana wallet

  • Sign and submit transactions

  • Interact with on-chain programs and DEXes

Alternatively, we can integrate directly with a Solana DEX trading API, letting the bot submit swaps without manually crafting instructions.

Slippage Protection (Surviving Meme Coin Volatility)

Meme coins are extremely volatile, so price can move several percent between transaction creation and confirmation. To protect against bad entries or failed transactions, adding slippage tolerance logic is recommended and is outlined below:

  • Estimate price impact before submitting a trade

  • Only execute buys if expected slippage < 5 %

  • Abort trades if liquidity suddenly drops or spreads widen

This can prevent scenarios where the bot technically “wins the race” but enters at a terrible price due to sudden demand spikes.

Universal Launchpad Integration (Beyond Pump.fun)

One of the biggest advantages of this architecture is that it’s plug-and-play. Our bot isn’t hardcoded to a single launchpad.

That means the same architecture can be adapted to other launchpads by changing network and launchpad filters, for example Raydium on Solana and non-Solana launchpads such as Four.meme.

Altogether, these enhancements turn a prototype sniper bot into a production-ready system. It  connects to a real wallet, protected against volatility, and flexible enough to operate across multiple launchpads thanks to the wide coverage of onchain market data powered by GeckoTerminal.

Subscribe to CoinGecko API


Conclusion

In this guide, we walked through how to build a Pump.fun sniper bot that can discover, qualify, and track newly launched tokens using the CoinGecko API. From scanning new Solana pools to filtering out obvious risks and monitoring price action in real time using WebSockets, you now have a clear blueprint for building an event-driven Pump.fun sniper bot in Python.

One of the biggest advantages of this approach is speed with simplicity. By relying on high-quality, indexed market data, we avoid the operational overhead of running and maintaining a full Solana node, while still getting fast, reliable signals suitable for launchpad trading on platforms like Pump.fun.

If you plan to take this further, or make this production-ready, consider upgrading to a paid API plan. This grants you access to the WebSocket API, exclusive endpoints, higher rate limits, and more call credits, all of which are essential for this strategy. These enhanced features make a meaningful difference, allowing you to concurrently monitor and snipe more tokens simultaneously.

Disclaimer: This guide is for educational and informational purposes only and does not constitute financial advice. Meme coin trading is highly speculative and carries significant risk. Always do your own research and experiment responsibly.

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Want to be the first to know about upcoming airdrops?
Subscribe to the CoinGecko Daily Newsletter!
Join 600,000+ crypto enthusiasts, traders, and degens in getting the latest crypto news, articles, videos, and reports by subscribing to our FREE newsletter.
Tell us how much you like this article!
Vote count: 8
Vikas Negi
Vikas Negi
Vikas holds a PhD in Applied Physics. He loves to write code for applications centered around crypto data. When not tinkering with a Raspberry Pi or his home lab, he spends his time slaying demons in Diablo.

Related Articles

New Portfolio
Icon & name
Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
SOL
Solana
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT-BR
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Welcome to CoinGecko
Welcome back!
Login or Sign up in seconds
or
Sign in with . Not you?
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
Get Price Alerts with CoinGecko App
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores
Add NFT
Track wallet address
Paste
We only display assets from supported networks.
Ethereum Mainnet
Base Mainnet
BNB Smart Chain
Arbitrum
Avalanche
Fantom
Flare
Gnosis
Linea
Optimism
Polygon
Polygon zkEVM
Scroll
Stellar
Story
Syscoin
Telos
X Layer
Xai
Read-only access
We only fetch public data. No private keys, no signing, and we can't make any changes to your wallet.
Create Portfolio
Select icon
💎
🔥
👀
🚀
💰
🦍
🌱
💩
🌙
🪂
💚
CoinGecko
Better on the app
Real-time price alerts and a faster, smoother experience.
You’ve reached the limit.
Guest portfolios are limited to 10 coins. Sign up or log in to keep the coins listed below.