Skip to main content

Bot example source

For setup and commands, see Bot examples. These complete snapshots are included in the full docs for AI.

Source revision: c13ecdb. Each bot is one complete file: settings at the top, code below. It needs no other files.

Copytrader​

Repository file

Read copytrader_bot.py
copytrader_bot.py
"""ZeroSlip copytrader bot.

Copies the first buy that a watched wallet makes in a token, then copies its
sells in the same proportion.

How it works:
1. Reads live trades from the ZeroSlip data stream (one websocket).
2. When a wallet in WALLETS makes its first buy of a token, buys BUY_FRACTION
of that amount, capped at MAX_BUY_AMOUNT.
3. When that wallet sells 25% of its tokens, sells 25% of yours.
Only Pump.fun and Pump-created PumpSwap pools are copied (Mayhem mode skipped).

LIVE = False (default) only logs paper trades; nothing is sent.
LIVE = True sends orders with your key to the ZeroSlip Trade API, which signs them.

Run: python3 copytrader_bot.py (Python 3.9+, pip install aiohttp websockets)
"""

# ---------------------------------- SETTINGS ----------------------------------
LIVE = False # True sends real orders.
API_KEY = '' # Your ZeroSlip wallet API key. Needed only when LIVE = True.
PRIVATE_KEY = '' # Or your base58 private key. API_KEY is used if both are set.

WALLETS = [] # Wallet addresses to copy, e.g. ['address1', 'address2']
TOKEN_MINTS = [] # Only copy these tokens. Empty = any token.
BUY_FRACTION = 0.1 # Copy 10% of the watched wallet's buy...
MAX_BUY_AMOUNT = 0.01 # ...up to this many SOL. USDC pools use the same value in USDC.
MY_WALLET = '' # Optional: your own address, so you can't copy yourself by mistake.
BUY_SLIPPAGE = 20 # %
SELL_SLIPPAGE = 99 # %
PRIORITY_FEE = 0.0001 # SOL
# ------------------------------------------------------------------------------

# Lets `uv run <file>` install the packages for you. Plain python3 ignores it.
# /// script
# requires-python = ">=3.9"
# dependencies = ["aiohttp>=3.12,<4", "websockets>=15,<16"]
# ///

import asyncio
from decimal import Decimal, ROUND_DOWN, localcontext
import json
import logging
import math
import time

import aiohttp
import websockets

TRADE_URL = 'https://api.zeroslip.ai'
STREAM_URL = 'wss://stream.zeroslip.ai/'
CONFIRM_SECONDS = 3 # How long to wait for our own trade to appear on the stream.

WSOL = 'So11111111111111111111111111111111111111112'
USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
SOL_USDC_POOL = 'Gf7sXMoP8iRw4iiXmJ1nq4vxcRycbGXy5RL8a8LnTd3v'
BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

sol_price = 80.0 # USDC per SOL until the SOL/USDC pool trades on the stream.


class StopBot(Exception):
"""Bad settings, or an order outcome we can't confirm. Stop instead of retrying."""


def positive(value):
try:
value = float(value)
except (TypeError, ValueError):
return 0.0
return value if math.isfinite(value) and value > 0 else 0.0


def check_address(value, name):
# Solana addresses are 32 to 44 base58 characters. Catches pasted text that isn't an address.
if not isinstance(value, str) or not 32 <= len(value) <= 44 or any(c not in BASE58 for c in value):
raise StopBot(f'{name} must be a Solana address')


def credentials():
if API_KEY.strip():
return {'apiKey': API_KEY.strip()}
if PRIVATE_KEY.strip():
return {'privateKey': PRIVATE_KEY.strip()}
raise StopBot('LIVE = True needs API_KEY or PRIVATE_KEY in the settings')


def check_settings():
numbers = (BUY_FRACTION, MAX_BUY_AMOUNT, BUY_SLIPPAGE, SELL_SLIPPAGE, PRIORITY_FEE)
if any(isinstance(n, bool) or not isinstance(n, (int, float)) or not math.isfinite(n) for n in numbers):
raise StopBot('Number settings must be finite numbers')
if not isinstance(WALLETS, list) or not WALLETS:
raise StopBot('Add the wallets you want to copy to WALLETS')
for wallet in WALLETS:
check_address(wallet, 'WALLETS')
for mint in TOKEN_MINTS:
check_address(mint, 'TOKEN_MINTS')
if MY_WALLET:
check_address(MY_WALLET, 'MY_WALLET')
if MY_WALLET in WALLETS:
raise StopBot('Do not copy your own wallet')
try:
if not (0 < BUY_FRACTION <= 1 and MAX_BUY_AMOUNT > 0):
raise StopBot('BUY_FRACTION must be above 0 and at most 1; MAX_BUY_AMOUNT above 0')
if not (0 <= BUY_SLIPPAGE < 100 and 0 <= SELL_SLIPPAGE < 100):
raise StopBot('BUY_SLIPPAGE and SELL_SLIPPAGE must be from 0 to below 100')
if PRIORITY_FEE < 0:
raise StopBot('PRIORITY_FEE cannot be negative')
except TypeError:
raise StopBot('Number settings must be numbers') from None
if not isinstance(LIVE, bool):
raise StopBot('LIVE must be True or False')
if LIVE:
credentials()


def update_sol_price(event):
"""Track SOL's USDC price from the SOL/USDC pool. Returns True for that pool's events."""
global sol_price
if event.get('poolId') != SOL_USDC_POOL:
return False
price = positive(event.get('price'))
if price:
sol_price = 1 / price
return True


def sol_to_quote(quote, sol_amount):
return sol_amount if quote == WSOL else sol_amount * sol_price


def convert_price(price, from_quote, to_quote):
if from_quote == to_quote:
return price
return price / sol_price if from_quote == USDC else price * sol_price


def pump_pool(event):
# Pump.fun bonding curve, or a PumpSwap pool that Pump created. Mayhem mode is skipped.
return not event.get('mayhemMode') and (
event.get('pool') == 'pump' or (event.get('pool') == 'pump-amm' and event.get('poolCreatedBy') == 'pump')
)


async def post(session, payload):
# Never log the payload or response body: they can contain your key.
try:
async with session.post(TRADE_URL, json=payload, allow_redirects=False) as response:
if response.status != 200:
raise StopBot(f'API returned HTTP {response.status}; check the wallet before retrying')
data = await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as exc:
raise StopBot('No API response; the order may or may not have gone through. Check the wallet') from exc
if not isinstance(data, dict) or data.get('err') or data.get('error'):
raise StopBot('API rejected the order; check the wallet before retrying')
return data


class Trader:
"""Sends orders (LIVE) or simulates them (paper), and keeps the paper PnL."""

def __init__(self, session, live):
self.session, self.live = session, live
self.recent = {} # signature -> stream events, to confirm our own trades
self.paper = {} # mint -> {'tokens', 'cost', 'sol_price'}
self.pnl = {WSOL: 0.0, USDC: 0.0}
self.pnl_sol = 0.0
self.buys = self.sells = self.missed = 0

def remember(self, event):
signature = event.get('signature')
if signature:
self.recent.setdefault(signature, []).append(event)
if len(self.recent) > 10000:
del self.recent[next(iter(self.recent))]

async def order(self, action, mint, quote, amount, price, tokens=0):
"""Buy `amount` of quote, or sell `amount` tokens ('100%' sells all). Returns the fill."""
if not self.live:
return self.paper_order(action, mint, quote, amount, price, tokens)
payload = {
**credentials(),
'action': action,
'mint': mint,
'quoteMint': quote,
'amount': amount,
'denominatedInQuote': 'true' if action == 'buy' else 'false',
'slippage': BUY_SLIPPAGE if action == 'buy' else SELL_SLIPPAGE,
'priorityFee': PRIORITY_FEE,
}
signature = (await post(self.session, payload)).get('signature')
if not isinstance(signature, str) or not signature:
raise StopBot('API did not return a signature; check the wallet before retrying')
logging.info('Sent %s mint=%s signature=%s', action, mint, signature)
# Our own trade shows up on the stream with the real price and token amount.
deadline = time.monotonic() + CONFIRM_SECONDS
while time.monotonic() < deadline:
for event in self.recent.get(signature, []):
if (
event.get('action') == action
and event.get('mint') == mint
and positive(event.get('price'))
and positive(event.get('tokenAmount'))
):
logging.info('Confirmed %s mint=%s', action, mint)
return event
await asyncio.sleep(0.1)
raise StopBot(f'{signature} not seen on the stream; not retried. Check the wallet before restarting')

def paper_order(self, action, mint, quote, amount, price, tokens):
quote_name = 'SOL' if quote == WSOL else 'USDC'
logging.info('PAPER %s mint=%s amount=%s quote=%s', action.upper(), mint, amount, quote_name)
if action == 'buy':
quantity = amount / price
self.paper[mint] = {'tokens': quantity, 'cost': amount, 'sol_price': sol_price}
self.buys += 1
else:
quantity = tokens * float(amount[:-1]) / 100 if str(amount).endswith('%') else float(amount)
quantity = min(tokens, quantity)
position = self.paper[mint]
cost = position['cost'] * quantity / position['tokens']
pnl = quantity * price - cost
self.pnl[quote] += pnl
self.pnl_sol += pnl if quote == WSOL else pnl / position['sol_price']
self.sells += 1
move = (quantity * price / cost - 1) * 100
logging.info('PAPER RESULT mint=%s move=%+.2f%% pnl=%+.8f %s', mint, move, pnl, quote_name)
position['tokens'] -= quantity
position['cost'] -= cost
if position['tokens'] <= 0:
del self.paper[mint]
return {'price': price, 'tokenAmount': quantity, 'quoteAmount': quantity * price}

def report(self):
if self.live:
return
counts = self.buys, self.sells, self.missed, len(self.paper)
logging.info('Paper trades: %s buys, %s sells, %s missed, %s open', *counts)
logging.info('Paper PnL: %+.8f SOL (WSOL %+.8f, USDC %+.8f), fees excluded', self.pnl_sol, *self.pnl.values())


class Copytrader:
def __init__(self, trader):
self.trader = trader
# mint -> {'wallet', 'quote', 'tokens' (ours), 'copied_remaining' (theirs), 'decimals'}
self.positions = {}

def watched_wallet(self, event):
"""The watched wallet that traded in this event, if any."""
signer = event.get('txSigner')
involved = event.get('tradersInvolved')
if isinstance(involved, dict):
# The wallet that opened a position comes first, so its exits are found.
owner = self.positions.get(event.get('mint'), {}).get('wallet')
if owner in involved:
return owner
if signer in WALLETS and signer in involved:
return signer
return next((wallet for wallet in WALLETS if wallet in involved), None)
if signer in WALLETS:
return signer
balances = event.get('postBalances') or {}
return next((wallet for wallet in WALLETS if wallet in balances), None)

@staticmethod
def wallet_quantity(event, wallet):
"""Tokens this wallet traded. None when a bundled trade doesn't say."""
breakdown = event.get('breakdown')
if isinstance(breakdown, list):
return sum(
positive(trade.get('tokenAmount'))
for trade in breakdown
if isinstance(trade, dict) and trade.get('trader') == wallet and trade.get('action') == event['action']
)
if len(event.get('tradersInvolved') or {}) > 1:
return None
return positive(event.get('tokenAmount'))

def wants(self, event):
"""Which stream events need a worker: trades by watched wallets in Pump pools."""
if update_sol_price(event):
return False
return event.get('action') in ('buy', 'sell') and pump_pool(event) and bool(self.watched_wallet(event))

async def on_event(self, event):
if event.get('action') not in ('buy', 'sell') or not pump_pool(event):
return
wallet = self.watched_wallet(event)
mint, quote = event.get('mint'), event.get('quoteMint')
price, quantity = positive(event.get('price')), positive(event.get('tokenAmount'))
if not wallet or not mint or not price or not quantity or quote not in (WSOL, USDC):
return
if TOKEN_MINTS and mint not in TOKEN_MINTS:
return
if event['action'] == 'buy':
await self.copy_buy(event, wallet, mint, quote, price, quantity)
elif mint in self.positions:
await self.copy_sell(event, wallet, mint, quote, price)

async def copy_buy(self, event, wallet, mint, quote, price, quantity):
if mint in self.positions:
# More buys by the same wallet raise the amount its later sells are measured against.
if wallet == self.positions[mint]['wallet']:
bought = self.wallet_quantity(event, wallet)
if bought is not None:
self.positions[mint]['copied_remaining'] += bought
return
# First buy only: nobody in the transaction held the token before it.
balances = event.get('postBalances') or {}
held_after = sum(positive(values.get(mint)) for values in balances.values())
if abs(held_after - quantity) > max(0.000001, quantity * 0.000001):
return
amount = min(positive(event.get('quoteAmount')) * BUY_FRACTION, sol_to_quote(quote, MAX_BUY_AMOUNT))
if amount <= 0:
return
fill = await self.trader.order('buy', mint, quote, amount, price)
self.positions[mint] = {
'wallet': wallet,
'quote': quote,
'tokens': positive(fill['tokenAmount']),
'copied_remaining': positive(balances.get(wallet, {}).get(mint)) or quantity,
'decimals': event.get('decimals'),
}

async def copy_sell(self, event, wallet, mint, quote, price):
position = self.positions[mint]
if wallet != position['wallet']:
return # Only the wallet that opened the position closes it.
sold = self.wallet_quantity(event, wallet)
if sold is None:
logging.warning('Skipped a bundled sell mint=%s; it does not say how much this wallet sold', mint)
return
if sold <= 0:
return
fraction = min(1.0, sold / position['copied_remaining'])
amount = '100%' if fraction >= 1 else position['tokens'] * fraction
if self.trader.live and fraction < 1:
# Live partial sells send an exact token amount, rounded down to the token's decimals.
decimals = position['decimals']
if not isinstance(decimals, int) or isinstance(decimals, bool) or not 0 <= decimals <= 255:
raise StopBot('Token decimals unknown; cannot size a partial sell. Check the wallet')
with localcontext() as context:
context.prec = max(28, decimals + 20)
ours, theirs = Decimal(str(position['tokens'])), Decimal(str(position['copied_remaining']))
exact = ours * Decimal(str(sold)) / theirs
amount = float(exact.quantize(Decimal(1).scaleb(-decimals), rounding=ROUND_DOWN))
if amount == 0:
position['copied_remaining'] = max(0, position['copied_remaining'] - sold)
logging.info('Skipped a sell smaller than one token unit mint=%s', mint)
return
price = convert_price(price, quote, position['quote'])
fill = await self.trader.order('sell', mint, position['quote'], amount, price, position['tokens'])
position['tokens'] = max(0, position['tokens'] - positive(fill['tokenAmount']))
position['copied_remaining'] = max(0, position['copied_remaining'] - sold)
if fraction >= 1 or position['tokens'] == 0:
del self.positions[mint]
logging.info('Copied sell by %s mint=%s fraction=%.2f%%', wallet, mint, fraction * 100)

async def on_tick(self, mint):
"""Returns False when the token's worker can stop."""
return mint in self.positions


async def run_stream(trader, strategy):
"""Read the stream and give each token its own worker.

Tokens are handled in parallel, so a slow order on one token doesn't delay
the others. Each token's events stay in order.
"""
queues, workers = {}, set()
failure = asyncio.get_running_loop().create_future()

def worker_done(task):
workers.discard(task)
if not task.cancelled() and task.exception() and not failure.done():
failure.set_exception(task.exception())

async def token_worker(mint, queue):
while True:
try:
await strategy.on_event(await asyncio.wait_for(queue.get(), timeout=1))
except asyncio.TimeoutError:
pass
if not await strategy.on_tick(mint) and queue.empty():
del queues[mint] # No await since the check, so nothing can be queued in between.
return

async def reader():
delay = 0.4
while True:
connected_at = None
try:
async with websockets.connect(STREAM_URL, max_size=8 << 20) as socket:
connected_at = time.monotonic()
logging.info('Connected to the stream (%s)', 'LIVE' if trader.live else 'PAPER')
async for message in socket:
try:
event = json.loads(message)
except ValueError:
continue
if not isinstance(event, dict):
continue
trader.remember(event)
mint = event.get('mint') or 'market'
if not strategy.wants(event) and mint not in queues:
continue
if mint not in queues:
queues[mint] = asyncio.Queue(maxsize=10000)
task = asyncio.create_task(token_worker(mint, queues[mint]))
workers.add(task)
task.add_done_callback(worker_done)
try:
queues[mint].put_nowait(event)
except asyncio.QueueFull:
raise StopBot('Too many queued events for one token; check your positions') from None
reason = f'closed {socket.close_code} {socket.close_reason}'
except (OSError, websockets.exceptions.WebSocketException) as exc:
reason = f'{type(exc).__name__}: {exc}'
if connected_at is not None and time.monotonic() - connected_at >= 30:
delay = 0.4
logging.warning('Stream disconnected (%s); reconnecting in %.1f s', reason, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, 30)

stream = asyncio.create_task(reader())
try:
done, _ = await asyncio.wait([stream, failure], return_when=asyncio.FIRST_COMPLETED)
for task in done:
task.result()
finally:
for task in [stream, *workers]:
task.cancel()
await asyncio.gather(stream, *workers, return_exceptions=True)
failure.cancel()
trader.report()


async def main():
check_settings()
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session:
trader = Trader(session, LIVE)
await run_stream(trader, Copytrader(trader))


if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info('Stopped. Open positions stay in your wallet; restarting does not restore them.')
except StopBot as exc:
logging.error('%s', exc)
raise SystemExit(1) from None

Sniper​

Repository file

Read live_sniper_bot.py
live_sniper_bot.py
"""ZeroSlip sniper bot.

Buys one token you choose, or snipes new Pump.fun launches, then sells at
take profit, stop loss, or after a quiet period.

How it works:
1. Reads live trades from the ZeroSlip data stream (one websocket).
2. Buys when your entry rule matches.
3. Sells 100% when price hits TAKE_PROFIT or STOP_LOSS, or the token goes quiet.

LIVE = False (default) only logs paper trades; nothing is sent.
LIVE = True sends orders with your key to the ZeroSlip Trade API, which signs them.

Run: python3 live_sniper_bot.py (Python 3.9+, pip install aiohttp websockets)
"""

# ---------------------------------- SETTINGS ----------------------------------
LIVE = False # True sends real orders.
API_KEY = '' # Your ZeroSlip wallet API key. Needed only when LIVE = True.
PRIVATE_KEY = '' # Or your base58 private key. API_KEY is used if both are set.

TOKEN_MINT = '' # Token to buy once. Empty = snipe new Pump.fun launches.
MIN_INITIAL_BUY = 20 # Launch mode: the creator's first buy must exceed this many SOL.
BUY_AMOUNT = 0.001 # SOL per buy. USDC pools buy the same value in USDC.
TAKE_PROFIT = 50 # Sell when the price is up this many % from entry.
STOP_LOSS = 20 # Sell when the price is down this many % from entry.
IDLE_SECONDS = 300 # Sell when the token has no activity for this long.
BUY_SLIPPAGE = 20 # %
SELL_SLIPPAGE = 99 # %
PRIORITY_FEE = 0.0001 # SOL
# ------------------------------------------------------------------------------

# Lets `uv run <file>` install the packages for you. Plain python3 ignores it.
# /// script
# requires-python = ">=3.9"
# dependencies = ["aiohttp>=3.12,<4", "websockets>=15,<16"]
# ///

import asyncio
import json
import logging
import math
import time

import aiohttp
import websockets

TRADE_URL = 'https://api.zeroslip.ai'
STREAM_URL = 'wss://stream.zeroslip.ai/'
CONFIRM_SECONDS = 3 # How long to wait for our own trade to appear on the stream.

WSOL = 'So11111111111111111111111111111111111111112'
USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
SOL_USDC_POOL = 'Gf7sXMoP8iRw4iiXmJ1nq4vxcRycbGXy5RL8a8LnTd3v'
BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

sol_price = 80.0 # USDC per SOL until the SOL/USDC pool trades on the stream.


class StopBot(Exception):
"""Bad settings, or an order outcome we can't confirm. Stop instead of retrying."""


def positive(value):
try:
value = float(value)
except (TypeError, ValueError):
return 0.0
return value if math.isfinite(value) and value > 0 else 0.0


def check_address(value, name):
# Solana addresses are 32 to 44 base58 characters. Catches pasted text that isn't an address.
if not isinstance(value, str) or not 32 <= len(value) <= 44 or any(c not in BASE58 for c in value):
raise StopBot(f'{name} must be a Solana address')


def credentials():
if API_KEY.strip():
return {'apiKey': API_KEY.strip()}
if PRIVATE_KEY.strip():
return {'privateKey': PRIVATE_KEY.strip()}
raise StopBot('LIVE = True needs API_KEY or PRIVATE_KEY in the settings')


def check_settings():
numbers = (MIN_INITIAL_BUY, BUY_AMOUNT, TAKE_PROFIT, STOP_LOSS, IDLE_SECONDS,
BUY_SLIPPAGE, SELL_SLIPPAGE, PRIORITY_FEE)
if any(isinstance(n, bool) or not isinstance(n, (int, float)) or not math.isfinite(n) for n in numbers):
raise StopBot('Number settings must be finite numbers')
try:
if not (BUY_AMOUNT > 0 and TAKE_PROFIT > 0 and IDLE_SECONDS > 0 and 0 < STOP_LOSS < 100):
raise StopBot('BUY_AMOUNT, TAKE_PROFIT and IDLE_SECONDS must be above 0; STOP_LOSS between 0 and 100')
if not (0 <= BUY_SLIPPAGE < 100 and 0 <= SELL_SLIPPAGE < 100):
raise StopBot('BUY_SLIPPAGE and SELL_SLIPPAGE must be from 0 to below 100')
if MIN_INITIAL_BUY < 0 or PRIORITY_FEE < 0:
raise StopBot('MIN_INITIAL_BUY and PRIORITY_FEE cannot be negative')
except TypeError:
raise StopBot('Number settings must be numbers') from None
if not isinstance(LIVE, bool):
raise StopBot('LIVE must be True or False')
if TOKEN_MINT:
check_address(TOKEN_MINT, 'TOKEN_MINT')
if LIVE:
credentials()


def update_sol_price(event):
"""Track SOL's USDC price from the SOL/USDC pool. Returns True for that pool's events."""
global sol_price
if event.get('poolId') != SOL_USDC_POOL:
return False
price = positive(event.get('price'))
if price:
sol_price = 1 / price
return True


def sol_to_quote(quote, sol_amount):
return sol_amount if quote == WSOL else sol_amount * sol_price


def convert_price(price, from_quote, to_quote):
if from_quote == to_quote:
return price
return price / sol_price if from_quote == USDC else price * sol_price


def pump_pool(event):
# Pump.fun bonding curve, or a PumpSwap pool that Pump created. Mayhem mode is skipped.
return not event.get('mayhemMode') and (
event.get('pool') == 'pump' or (event.get('pool') == 'pump-amm' and event.get('poolCreatedBy') == 'pump')
)


async def post(session, payload):
# Never log the payload or response body: they can contain your key.
try:
async with session.post(TRADE_URL, json=payload, allow_redirects=False) as response:
if response.status != 200:
raise StopBot(f'API returned HTTP {response.status}; check the wallet before retrying')
data = await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as exc:
raise StopBot('No API response; the order may or may not have gone through. Check the wallet') from exc
if not isinstance(data, dict) or data.get('err') or data.get('error'):
raise StopBot('API rejected the order; check the wallet before retrying')
return data


class Trader:
"""Sends orders (LIVE) or simulates them (paper), and keeps the paper PnL."""

def __init__(self, session, live):
self.session, self.live = session, live
self.recent = {} # signature -> stream events, to confirm our own trades
self.paper = {} # mint -> {'tokens', 'cost', 'sol_price'}
self.pnl = {WSOL: 0.0, USDC: 0.0}
self.pnl_sol = 0.0
self.buys = self.sells = self.missed = 0

def remember(self, event):
signature = event.get('signature')
if signature:
self.recent.setdefault(signature, []).append(event)
if len(self.recent) > 10000:
del self.recent[next(iter(self.recent))]

async def order(self, action, mint, quote, amount, price, tokens=0):
"""Buy `amount` of quote, or sell `amount` tokens ('100%' sells all). Returns the fill."""
if not self.live:
return self.paper_order(action, mint, quote, amount, price, tokens)
payload = {
**credentials(),
'action': action,
'mint': mint,
'quoteMint': quote,
'amount': amount,
'denominatedInQuote': 'true' if action == 'buy' else 'false',
'slippage': BUY_SLIPPAGE if action == 'buy' else SELL_SLIPPAGE,
'priorityFee': PRIORITY_FEE,
}
signature = (await post(self.session, payload)).get('signature')
if not isinstance(signature, str) or not signature:
raise StopBot('API did not return a signature; check the wallet before retrying')
logging.info('Sent %s mint=%s signature=%s', action, mint, signature)
# Our own trade shows up on the stream with the real price and token amount.
deadline = time.monotonic() + CONFIRM_SECONDS
while time.monotonic() < deadline:
for event in self.recent.get(signature, []):
if (
event.get('action') == action
and event.get('mint') == mint
and positive(event.get('price'))
and positive(event.get('tokenAmount'))
):
logging.info('Confirmed %s mint=%s', action, mint)
return event
await asyncio.sleep(0.1)
raise StopBot(f'{signature} not seen on the stream; not retried. Check the wallet before restarting')

def paper_order(self, action, mint, quote, amount, price, tokens):
quote_name = 'SOL' if quote == WSOL else 'USDC'
logging.info('PAPER %s mint=%s amount=%s quote=%s', action.upper(), mint, amount, quote_name)
if action == 'buy':
quantity = amount / price
self.paper[mint] = {'tokens': quantity, 'cost': amount, 'sol_price': sol_price}
self.buys += 1
else:
quantity = tokens * float(amount[:-1]) / 100 if str(amount).endswith('%') else float(amount)
quantity = min(tokens, quantity)
position = self.paper[mint]
cost = position['cost'] * quantity / position['tokens']
pnl = quantity * price - cost
self.pnl[quote] += pnl
self.pnl_sol += pnl if quote == WSOL else pnl / position['sol_price']
self.sells += 1
move = (quantity * price / cost - 1) * 100
logging.info('PAPER RESULT mint=%s move=%+.2f%% pnl=%+.8f %s', mint, move, pnl, quote_name)
position['tokens'] -= quantity
position['cost'] -= cost
if position['tokens'] <= 0:
del self.paper[mint]
return {'price': price, 'tokenAmount': quantity, 'quoteAmount': quantity * price}

def report(self):
if self.live:
return
counts = self.buys, self.sells, self.missed, len(self.paper)
logging.info('Paper trades: %s buys, %s sells, %s missed, %s open', *counts)
logging.info('Paper PnL: %+.8f SOL (WSOL %+.8f, USDC %+.8f), fees excluded', self.pnl_sol, *self.pnl.values())


class Sniper:
def __init__(self, trader, clock=time.monotonic):
self.trader, self.clock = trader, clock
self.positions = {} # mint -> {'entry', 'price', 'tokens', 'last', 'quote'}
self.pending = {} # paper buys waiting for the next trade price
self.finished = set() # TOKEN_MINT mode buys once

def is_launch(self, event):
return event.get('action') == 'create' and event.get('pool') == 'pump' and pump_pool(event)

def wants(self, event):
"""Which stream events need a worker: launches, TOKEN_MINT, and tokens we hold."""
if update_sol_price(event):
return False
mint = event.get('mint')
return bool(mint) and (
mint in self.positions or mint in self.pending or mint == TOKEN_MINT or self.is_launch(event)
)

async def on_event(self, event):
mint, quote = event.get('mint'), event.get('quoteMint')
price = positive(event.get('price'))
if not mint:
return
if TOKEN_MINT:
eligible = mint == TOKEN_MINT and event.get('action') in ('buy', 'sell')
else:
big_enough = positive(event.get('quoteAmount')) > sol_to_quote(quote, MIN_INITIAL_BUY)
eligible = self.is_launch(event) and big_enough

if mint in self.pending:
# Paper buys fill at the next trade price, like a real order that lands a moment later.
pending = self.pending[mint]
if event.get('action') not in ('buy', 'sell') or not price or quote not in (WSOL, USDC):
return
if not TOKEN_MINT and not pump_pool(event):
return
price = convert_price(price, quote, pending['quote'])
del self.pending[mint]
ceiling = pending['decision'] / (1 - BUY_SLIPPAGE / 100)
if price > ceiling:
self.trader.missed += 1
logging.info('PAPER MISS mint=%s price=%s above slippage limit %s', mint, price, ceiling)
if TOKEN_MINT:
self.finished.add(mint)
return
await self.buy(mint, pending['quote'], price)
return # The fill event can't also trigger take profit.

if mint not in self.positions:
if not eligible or mint in self.finished or quote not in (WSOL, USDC) or not price:
return
if self.trader.live:
await self.buy(mint, quote, price)
else:
self.pending[mint] = {'decision': price, 'quote': quote, 'last': self.clock()}
logging.info('PAPER PENDING BUY mint=%s; waiting for the next trade price', mint)
return

# Any event for a held token resets the idle timer; only trades and liquidity moves set the price.
position = self.positions[mint]
position['last'] = self.clock()
if event.get('action') not in ('buy', 'sell', 'add', 'remove') or not price or quote not in (WSOL, USDC):
return
if not TOKEN_MINT and not pump_pool(event):
return
position['price'] = convert_price(price, quote, position['quote'])
change = (position['price'] - position['entry']) / position['entry'] * 100
if change > TAKE_PROFIT:
await self.sell(mint, 'take profit')
elif change < -STOP_LOSS:
await self.sell(mint, 'stop loss')

async def buy(self, mint, quote, price):
fill = await self.trader.order('buy', mint, quote, sol_to_quote(quote, BUY_AMOUNT), price)
entry = positive(fill['price'])
self.positions[mint] = {
'entry': entry,
'price': entry,
'tokens': positive(fill['tokenAmount']),
'last': self.clock(),
'quote': quote,
}
logging.info('Opened %s; TP=%s%% SL=%s%%', mint, TAKE_PROFIT, STOP_LOSS)

async def sell(self, mint, reason):
position = self.positions[mint]
await self.trader.order('sell', mint, position['quote'], '100%', position['price'], position['tokens'])
del self.positions[mint]
if TOKEN_MINT:
self.finished.add(mint)
logging.info('Closed %s (%s)', mint, reason)

async def on_tick(self, mint):
"""Runs about once a second per token. Returns False when the token's worker can stop."""
now = self.clock()
if mint in self.pending and now - self.pending[mint]['last'] > IDLE_SECONDS:
del self.pending[mint]
self.trader.missed += 1
if TOKEN_MINT:
self.finished.add(mint)
logging.info('PAPER MISS mint=%s; no trade before the idle timeout', mint)
if mint in self.positions and now - self.positions[mint]['last'] > IDLE_SECONDS:
await self.sell(mint, 'idle timeout')
return mint in self.positions or mint in self.pending


async def run_stream(trader, strategy):
"""Read the stream and give each token its own worker.

Tokens are handled in parallel, so a slow order on one token doesn't delay
the others. Each token's events stay in order.
"""
queues, workers = {}, set()
failure = asyncio.get_running_loop().create_future()

def worker_done(task):
workers.discard(task)
if not task.cancelled() and task.exception() and not failure.done():
failure.set_exception(task.exception())

async def token_worker(mint, queue):
while True:
try:
await strategy.on_event(await asyncio.wait_for(queue.get(), timeout=1))
except asyncio.TimeoutError:
pass
if not await strategy.on_tick(mint) and queue.empty():
del queues[mint] # No await since the check, so nothing can be queued in between.
return

async def reader():
delay = 0.4
while True:
connected_at = None
try:
async with websockets.connect(STREAM_URL, max_size=8 << 20) as socket:
connected_at = time.monotonic()
logging.info('Connected to the stream (%s)', 'LIVE' if trader.live else 'PAPER')
async for message in socket:
try:
event = json.loads(message)
except ValueError:
continue
if not isinstance(event, dict):
continue
trader.remember(event)
mint = event.get('mint') or 'market'
if not strategy.wants(event) and mint not in queues:
continue
if mint not in queues:
queues[mint] = asyncio.Queue(maxsize=10000)
task = asyncio.create_task(token_worker(mint, queues[mint]))
workers.add(task)
task.add_done_callback(worker_done)
try:
queues[mint].put_nowait(event)
except asyncio.QueueFull:
raise StopBot('Too many queued events for one token; check your positions') from None
reason = f'closed {socket.close_code} {socket.close_reason}'
except (OSError, websockets.exceptions.WebSocketException) as exc:
reason = f'{type(exc).__name__}: {exc}'
if connected_at is not None and time.monotonic() - connected_at >= 30:
delay = 0.4
logging.warning('Stream disconnected (%s); reconnecting in %.1f s', reason, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, 30)

stream = asyncio.create_task(reader())
try:
done, _ = await asyncio.wait([stream, failure], return_when=asyncio.FIRST_COMPLETED)
for task in done:
task.result()
finally:
for task in [stream, *workers]:
task.cancel()
await asyncio.gather(stream, *workers, return_exceptions=True)
failure.cancel()
trader.report()


async def main():
check_settings()
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session:
trader = Trader(session, LIVE)
await run_stream(trader, Sniper(trader))


if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info('Stopped. Open positions stay in your wallet; restarting does not restore them.')
except StopBot as exc:
logging.error('%s', exc)
raise SystemExit(1) from None

Backtester​

Repository file

Read backtest_sniper_strategy.py
backtest_sniper_strategy.py
"""ZeroSlip sniper backtester.

Replays past hours of market data through the launch-sniper rules from
live_sniper_bot.py and reports what would have happened. It never trades.

How it works:
1. Downloads the last HOURS completed UTC hours from the ZeroSlip replay
archive (or reads REPLAY_FILE), one event at a time.
2. Buys new Pump.fun launches whose first buy exceeds MIN_INITIAL_BUY, after
BUY_LATENCY_MS, unless the price moved more than BUY_SLIPPAGE.
3. Sells at TAKE_PROFIT, STOP_LOSS, or after IDLE_SECONDS, after SELL_LATENCY_MS.
4. Reports PnL after modeled fees, win rate, exit reasons, and missed entries.
Fills use the last known price, so results are an estimate, not a promise.

Run: python3 backtest_sniper_strategy.py (Python 3.9+, pip install aiohttp zstandard orjson)
"""

# ---------------------------------- SETTINGS ----------------------------------
HOURS = 1 # Completed UTC hours to replay. Each hour is a ~600 MB download (about 2 minutes).
REPLAY_FILE = '' # Or a downloaded .jsonl / .jsonl.zst archive to replay instead.
ALLOW_GAPS = False # True skips hours missing from the archive instead of stopping.

MIN_INITIAL_BUY = 20 # The creator's first buy must exceed this many SOL.
BUY_AMOUNT = 0.001 # SOL per buy. USDC pools buy the same value in USDC.
TAKE_PROFIT = 50 # Sell when the price is up this many % from entry.
STOP_LOSS = 20 # Sell when the price is down this many % from entry.
IDLE_SECONDS = 300 # Sell when the token has no activity for this long.
BUY_SLIPPAGE = 20 # %. A buy is missed if the price rises more than this before it fills.

BUY_LATENCY_MS = 400 # Delay between deciding to buy and the buy filling.
SELL_LATENCY_MS = 400
SERVICE_FEE = 0.0025 # ZeroSlip fee per trade, as a fraction (0.25%).
EXTRA_FEE = 0.0005 # Extra cost per trade you want to assume, as a fraction.
# ------------------------------------------------------------------------------

# Lets `uv run <file>` install the packages for you. Plain python3 ignores it.
# /// script
# requires-python = ">=3.9"
# dependencies = ["aiohttp>=3.12,<4", "zstandard>=0.23,<1", "orjson>=3.10,<4"]
# ///

import asyncio
from collections import Counter
from datetime import datetime, timedelta, timezone
import io
import logging
import math
from pathlib import Path
import tempfile

import aiohttp
import zstandard

try:
import orjson as json # Optional: pip install orjson makes replays about 2x faster.
except ImportError:
import json

REPLAY_URL = 'https://replay.pumpapi.io' # Hourly archives: /YYYY/MM/DD/HH.jsonl.zst

WSOL = 'So11111111111111111111111111111111111111112'
USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
SOL_USDC_POOL = 'Gf7sXMoP8iRw4iiXmJ1nq4vxcRycbGXy5RL8a8LnTd3v'


class StopBot(Exception):
"""Bad settings or an archive problem. Stop with a clear message."""


def check_settings():
numbers = (MIN_INITIAL_BUY, BUY_AMOUNT, TAKE_PROFIT, STOP_LOSS, IDLE_SECONDS,
BUY_SLIPPAGE, BUY_LATENCY_MS, SELL_LATENCY_MS, SERVICE_FEE, EXTRA_FEE)
if any(isinstance(n, bool) or not isinstance(n, (int, float)) or not math.isfinite(n) for n in numbers):
raise StopBot('Number settings must be finite numbers')
try:
if not (BUY_AMOUNT > 0 and TAKE_PROFIT > 0 and IDLE_SECONDS > 0 and 0 < STOP_LOSS < 100):
raise StopBot('BUY_AMOUNT, TAKE_PROFIT and IDLE_SECONDS must be above 0; STOP_LOSS between 0 and 100')
if not 0 <= BUY_SLIPPAGE < 100:
raise StopBot('BUY_SLIPPAGE must be from 0 to below 100')
if min(MIN_INITIAL_BUY, BUY_LATENCY_MS, SELL_LATENCY_MS, SERVICE_FEE, EXTRA_FEE) < 0:
raise StopBot('MIN_INITIAL_BUY, latencies and fees cannot be negative')
if SERVICE_FEE + EXTRA_FEE >= 1:
raise StopBot('SERVICE_FEE and EXTRA_FEE are fractions; together they must be below 1')
except TypeError:
raise StopBot('Number settings must be numbers') from None
if not REPLAY_FILE and (not isinstance(HOURS, int) or isinstance(HOURS, bool) or HOURS < 1):
raise StopBot('HOURS must be a whole number of at least 1')
if not isinstance(ALLOW_GAPS, bool):
raise StopBot('ALLOW_GAPS must be True or False')


def finite(value):
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def pump_pool(event):
return event.get('pool') == 'pump' or (event.get('pool') == 'pump-amm' and event.get('poolCreatedBy') == 'pump')


class Backtest:
def __init__(self):
self.sol_price = 80.0 # USDC per SOL until the SOL/USDC pool trades.
self.positions = {} # mint -> position; 'state' is pending_buy, held or pending_sell
self.trades = []
self.last_ts = 0
self.first_ts = self.end_ts = None
self.seen = self.skipped = self.missed = self.buys = self.creates = 0

def sol_to_quote(self, quote, sol_amount):
return sol_amount if quote == WSOL else sol_amount * self.sol_price

def fill_buy(self, mint, pos):
decision, fill = pos['decision_price'], pos['cur_price']
if fill > decision / (1 - min(BUY_SLIPPAGE, 99.9) / 100):
self.missed += 1
del self.positions[mint]
move = (fill / decision - 1) * 100
logging.info('MISS %s: price rose %+.1f%% in %s ms, past BUY_SLIPPAGE', mint, move, BUY_LATENCY_MS)
return
amount = pos['amount']
pos.update(
state='held',
entry_price=fill,
quote_spent=amount,
tokens=amount * (1 - SERVICE_FEE - EXTRA_FEE - pos['entry_pool_fee']) / fill,
sol_price=self.sol_price,
spent_sol=amount if pos['quote_mint'] == WSOL else amount / self.sol_price,
buy_slip=(fill / decision - 1) * 100,
last_ts=pos['buy_fill_ts'],
)
self.buys += 1
logging.info('BUY %s: entry slippage %+.1f%%', mint, pos['buy_slip'])

def trigger_sell(self, pos, ts, reason):
pos.update(state='pending_sell', sell_reason=reason, sell_fill_ts=ts + SELL_LATENCY_MS)

def close(self, mint, pos, exit_price, reason):
fee = SERVICE_FEE + EXTRA_FEE
gross = pos['tokens'] * exit_price
pnl = gross * (1 - fee - pos['last_pool_fee']) - pos['quote_spent']
fees = pos['quote_spent'] * (fee + pos['entry_pool_fee']) + gross * (fee + pos['last_pool_fee'])
is_sol = pos['quote_mint'] == WSOL
self.trades.append(
{
'mint': mint,
'quote_mint': pos['quote_mint'],
'reason': reason,
'pct': (exit_price - pos['entry_price']) / pos['entry_price'] * 100,
'pnl': pnl,
'pnl_sol': pnl if is_sol else pnl / pos['sol_price'],
'spent_sol': pos['spent_sol'],
'fee_sol': fees if is_sol else fees / pos['sol_price'],
'buy_slip': pos['buy_slip'],
}
)
del self.positions[mint]
trade = self.trades[-1]
logging.info('SELL %s: %s, move %+.1f%%, pnl %+.8f SOL', mint, reason, trade['pct'], trade['pnl_sol'])

def resolve(self, ts):
"""Fill buys and sells whose latency has passed, and start idle sells."""
for mint, pos in list(self.positions.items()):
if pos['state'] == 'pending_buy' and pos['buy_fill_ts'] <= ts:
self.fill_buy(mint, pos)
elif pos['state'] == 'pending_sell' and pos['sell_fill_ts'] <= ts:
self.close(mint, pos, pos['cur_price'], pos['sell_reason'])
elif pos['state'] == 'held' and ts - pos['last_ts'] > IDLE_SECONDS * 1000:
self.trigger_sell(pos, pos['last_ts'] + IDLE_SECONDS * 1000, 'idle')

def handle_event(self, event):
self.seen += 1
ts = event['timestamp']
self.last_ts = ts
self.first_ts = ts if self.first_ts is None else min(self.first_ts, ts)
self.end_ts = ts if self.end_ts is None else max(self.end_ts, ts)
# Pending fills resolve at the last known price, before this event's price applies.
self.resolve(ts)
if event['action'] not in ('buy', 'sell', 'add', 'remove', 'create', 'migrate', 'createPool'):
return
mint = event['mint']
if event.get('poolId') == SOL_USDC_POOL:
if finite(event.get('price')) and event['price'] > 0:
self.sol_price = 1 / event['price']
return
if event['action'] == 'create' and event['pool'] == 'pump' and not event.get('mayhemMode'):
self.creates += 1
quote = event['quoteMint']
big_enough = event['quoteAmount'] > self.sol_to_quote(quote, MIN_INITIAL_BUY)
if quote in (WSOL, USDC) and big_enough and mint not in self.positions:
self.positions[mint] = {
'state': 'pending_buy',
'quote_mint': quote,
'amount': self.sol_to_quote(quote, BUY_AMOUNT),
'decision_price': event['price'],
'cur_price': event['price'],
'entry_pool_fee': event['poolFeeRate'],
'last_pool_fee': event['poolFeeRate'],
'buy_fill_ts': ts + BUY_LATENCY_MS,
'buy_slip': 0.0,
}
elif mint in self.positions:
pos = self.positions[mint]
quote = event.get('quoteMint')
if (event['action'] in ('buy', 'sell', 'add', 'remove', 'migrate')
and pump_pool(event) and quote in (WSOL, USDC)):
price = event['price']
# Keep every price in the entry quote, as the live sniper does.
if quote != pos['quote_mint']:
price = price / self.sol_price if quote == USDC else price * self.sol_price
pos.update(cur_price=price, last_pool_fee=event['poolFeeRate'])
if pos['state'] == 'held':
change = (price - pos['entry_price']) / pos['entry_price'] * 100
if change > TAKE_PROFIT:
self.trigger_sell(pos, ts, 'tp')
elif change < -STOP_LOSS:
self.trigger_sell(pos, ts, 'sl')
if pos['state'] == 'held':
pos['last_ts'] = ts

def read(self, lines):
for line in lines:
if not line.strip():
continue
try:
event = json.loads(line)
if not isinstance(event, dict):
raise ValueError('Not an event')
# Check the fields that set time or open/update a position; skip bad lines.
ts = event.get('timestamp')
if not finite(ts) or ts < 0:
raise ValueError('Invalid timestamp')
quote, amount = event.get('quoteMint'), event.get('quoteAmount')
entry = (
event.get('action') == 'create'
and event.get('pool') == 'pump'
and not event.get('mayhemMode')
and quote in (WSOL, USDC)
and finite(amount)
and amount > self.sol_to_quote(quote, MIN_INITIAL_BUY)
)
update = (
event.get('mint') in self.positions
and event.get('action') in ('buy', 'sell', 'add', 'remove', 'migrate')
and pump_pool(event)
)
if entry or update:
price, fee = event.get('price'), event.get('poolFeeRate')
if not finite(price) or price <= 0 or not finite(fee) or not 0 <= fee < 1:
raise ValueError('Invalid price or pool fee')
self.handle_event(event)
except (KeyError, TypeError, ValueError, ZeroDivisionError):
self.skipped += 1

def read_file(self, path):
with open(path, 'rb') as file:
if str(path).endswith('.zst'):
with zstandard.ZstdDecompressor().stream_reader(file) as reader:
self.read(io.BufferedReader(reader))
else:
self.read(file)

def finish(self):
# Buys still in flight fill; open positions close at their last price.
for mint, pos in list(self.positions.items()):
if pos['state'] == 'pending_buy':
self.fill_buy(mint, pos)
for mint, pos in list(self.positions.items()):
if pos['state'] == 'pending_sell':
reason = pos['sell_reason']
else:
reason = 'idle' if self.last_ts - pos['last_ts'] > IDLE_SECONDS * 1000 else 'end'
self.close(mint, pos, pos['cur_price'], reason)
self.report()

def report(self):
trades, count = self.trades, len(self.trades)
pnl_sol = sum(t['pnl_sol'] for t in trades)
volume = sum(t['spent_sol'] for t in trades)
wins = sum(t['pnl_sol'] > 0 for t in trades)
logging.info('Events=%s creates=%s buys=%s closed=%s', self.seen, self.creates, self.buys, count)
logging.info('Missed entries (price moved past BUY_SLIPPAGE)=%s; bad lines=%s', self.missed, self.skipped)
pnl_wsol = sum(t['pnl'] for t in trades if t['quote_mint'] == WSOL)
pnl_usdc = sum(t['pnl'] for t in trades if t['quote_mint'] == USDC)
logging.info('PnL=%+.8f SOL (WSOL %+.8f, USDC %+.8f); wins=%s/%s', pnl_sol, pnl_wsol, pnl_usdc, wins, count)
roi = pnl_sol / volume * 100 if volume else 0
logging.info('Volume=%.6f SOL; ROI=%+.2f%%; fees=%.8f SOL', volume, roi, sum(t['fee_sol'] for t in trades))
if count:
reasons = Counter(t['reason'] for t in trades)
exits = reasons['tp'], reasons['sl'], reasons['idle'], reasons['end'], wins / count * 100
logging.info('Exits: tp=%s sl=%s idle=%s end=%s; win rate=%.2f%%', *exits)
average_move = sum(t['pct'] for t in trades) / count
average_slip = sum(t['buy_slip'] for t in trades) / count
logging.info('Average move=%+.2f%%; average entry slippage=%+.2f%%', average_move, average_slip)
for label, pick in [('Best', max), ('Worst', min)]:
t = pick(trades, key=lambda t: t['pnl_sol'])
details = t['mint'], t['pnl_sol'], t['pct'], t['reason']
logging.info('%s trade: %s pnl=%+.8f SOL move=%+.2f%% exit=%s', label, *details)
else:
logging.info('No trades filled. For more trades, raise HOURS, lower MIN_INITIAL_BUY, or raise BUY_SLIPPAGE.')
if self.first_ts is not None:
start = datetime.fromtimestamp(self.first_ts / 1000, timezone.utc)
end = datetime.fromtimestamp(self.end_ts / 1000, timezone.utc)
logging.info('Replay window: %s to %s UTC', start.isoformat(), end.isoformat())


async def download_hour(session, hour, path):
"""Save one archive hour to `path`. Returns False if ALLOW_GAPS skipped it."""
url = f'{REPLAY_URL}/{hour:%Y/%m/%d/%H}.jsonl.zst'
logging.info('Downloading %s UTC', hour.strftime('%Y-%m-%d %H:00'))
try:
async with session.get(url) as response:
if response.status == 404 and ALLOW_GAPS:
logging.warning('Skipping a missing archive hour')
return False
if response.status == 404:
raise StopBot('Archive hour not found. The newest hour can take 90 seconds to upload; retry after that')
if response.status != 200:
raise StopBot(f'Archive download returned HTTP {response.status}')
with open(path, 'wb') as file:
async for chunk in response.content.iter_chunked(1 << 20):
file.write(chunk)
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
raise StopBot(f'Archive download failed ({type(exc).__name__}: {exc}); retry or set REPLAY_FILE') from exc
except OSError as exc:
raise StopBot('Cannot save the archive. Free disk space, set TMPDIR, or use REPLAY_FILE') from exc
return True


async def main():
check_settings()
backtest = Backtest()
if REPLAY_FILE:
try:
backtest.read_file(REPLAY_FILE)
except OSError as exc:
raise StopBot(f'Cannot read REPLAY_FILE: {exc}') from exc
else:
now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
timeout = aiohttp.ClientTimeout(total=None, sock_connect=30, sock_read=120)
async with aiohttp.ClientSession(timeout=timeout) as session:
with tempfile.TemporaryDirectory(prefix='zeroslip-replay-') as folder:
path = Path(folder) / 'hour.jsonl.zst'
for hours_ago in range(HOURS, 0, -1):
if await download_hour(session, now - timedelta(hours=hours_ago), path):
await asyncio.to_thread(backtest.read_file, path)
backtest.finish()


if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info('Stopped.')
except StopBot as exc:
logging.error('%s', exc)
raise SystemExit(1) from None

Sell balances​

Repository file

Read sell_all_tokens.py
sell_all_tokens.py
"""ZeroSlip sell-all-tokens script.

Sells every token in a wallet (or only the ones you list), keeping SOL and USDC.

How it works:
1. LIVE = False (default): reads WALLET's token balances from Solana RPC and
logs what it would sell. Nothing is sent.
2. LIVE = True: asks the ZeroSlip Trade API for your key's wallet balances,
then sells 100% of each selected token and waits for confirmation.
Frozen balances are skipped.

Run: python3 sell_all_tokens.py (Python 3.9+, pip install aiohttp)
"""

# ---------------------------------- SETTINGS ----------------------------------
LIVE = False # True sends real sell orders.
API_KEY = '' # Your ZeroSlip wallet API key. Needed only when LIVE = True.
PRIVATE_KEY = '' # Or your base58 private key. API_KEY is used if both are set.

WALLET = '' # Wallet address to preview. LIVE sells from your key's wallet instead.
SELL_ALL = True # True = every token. False = only TOKEN_MINTS.
TOKEN_MINTS = [] # Tokens to sell when SELL_ALL = False.
SLIPPAGE = 100 # %. 100 accepts any price.
PRIORITY_FEE = 0.0001 # SOL
# ------------------------------------------------------------------------------

# Lets `uv run <file>` install the packages for you. Plain python3 ignores it.
# /// script
# requires-python = ">=3.9"
# dependencies = ["aiohttp>=3.12,<4"]
# ///

import asyncio
import logging
import math

import aiohttp

TRADE_URL = 'https://api.zeroslip.ai'
RPC_URL = 'https://api.mainnet-beta.solana.com' # Public Solana RPC. Use your own if rate limited.

WSOL = 'So11111111111111111111111111111111111111112'
USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
TOKEN_PROGRAMS = ('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb')
BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'


class StopBot(Exception):
"""Bad settings, or a sale we can't confirm. Stop instead of retrying."""


def positive(value):
try:
value = float(value)
except (TypeError, ValueError):
return 0.0
return value if math.isfinite(value) and value > 0 else 0.0


def check_address(value, name):
# Solana addresses are 32 to 44 base58 characters. Catches pasted text that isn't an address.
if not isinstance(value, str) or not 32 <= len(value) <= 44 or any(c not in BASE58 for c in value):
raise StopBot(f'{name} must be a Solana address')


def credentials():
if API_KEY.strip():
return {'apiKey': API_KEY.strip()}
if PRIVATE_KEY.strip():
return {'privateKey': PRIVATE_KEY.strip()}
raise StopBot('LIVE = True needs API_KEY or PRIVATE_KEY in the settings')


def check_settings():
numbers = (SLIPPAGE, PRIORITY_FEE)
if any(isinstance(n, bool) or not isinstance(n, (int, float)) or not math.isfinite(n) for n in numbers):
raise StopBot('Number settings must be finite numbers')
if not isinstance(LIVE, bool) or not isinstance(SELL_ALL, bool):
raise StopBot('LIVE and SELL_ALL must be True or False')
if WALLET:
check_address(WALLET, 'WALLET')
elif not LIVE:
raise StopBot('Set WALLET to the wallet address you want to preview')
for mint in TOKEN_MINTS:
check_address(mint, 'TOKEN_MINTS')
if SELL_ALL and TOKEN_MINTS:
raise StopBot('Use SELL_ALL = True or list TOKEN_MINTS, not both')
if not SELL_ALL and not TOKEN_MINTS:
raise StopBot('List TOKEN_MINTS, or set SELL_ALL = True')
try:
if not 0 <= SLIPPAGE <= 100 or PRIORITY_FEE < 0:
raise StopBot('SLIPPAGE must be from 0 to 100; PRIORITY_FEE cannot be negative')
except TypeError:
raise StopBot('Number settings must be numbers') from None
if LIVE:
credentials()


async def post(session, url, payload, service='API'):
# Never log the payload or response body: they can contain your key.
try:
async with session.post(url, json=payload, allow_redirects=False) as response:
if response.status != 200:
raise StopBot(f'{service} returned HTTP {response.status}; check the wallet before retrying')
data = await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as exc:
raise StopBot(f'No {service} response ({type(exc).__name__}); check the wallet before retrying') from exc
if not isinstance(data, dict) or data.get('err') or data.get('error'):
detail = data.get('error') if service == 'RPC' and isinstance(data, dict) else 'request rejected'
raise StopBot(f'{service} error: {detail}; check the wallet before retrying')
return data


async def balances(session):
"""mint -> {'balance', 'frozen'}"""
if LIVE:
# The balances of the wallet that will sell. The API charges a small fee for this call.
data = await post(session, TRADE_URL, {**credentials(), 'action': 'getBalances'})
if not isinstance(data.get('tokenBalances'), dict):
raise StopBot('API did not return token balances')
return data['tokenBalances']
result = {}
for program in TOKEN_PROGRAMS:
params = [WALLET, {'programId': program}, {'encoding': 'jsonParsed', 'commitment': 'confirmed'}]
request = {'jsonrpc': '2.0', 'id': 1, 'method': 'getTokenAccountsByOwner', 'params': params}
data = await post(session, RPC_URL, request, 'RPC')
accounts = data.get('result', {}).get('value')
if not isinstance(accounts, list):
raise StopBot('RPC did not return token accounts')
for account in accounts:
info = account['account']['data']['parsed']['info']
entry = result.setdefault(info['mint'], {'balance': 0, 'frozen': False})
entry['balance'] += positive(info['tokenAmount'].get('uiAmountString'))
entry['frozen'] = entry['frozen'] or info.get('state') == 'frozen'
return result


def select(holdings):
# SOL and USDC are what you sell into, so they are always kept.
return {
mint: info
for mint, info in holdings.items()
if mint not in (WSOL, USDC) and (SELL_ALL or mint in TOKEN_MINTS) and positive(info.get('balance'))
}


async def main():
check_settings()
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session:
selected = select(await balances(session))
if not selected:
logging.info('No matching token balances to sell.')
return
for mint, info in selected.items():
if info.get('frozen'):
logging.warning('Skipping frozen balance mint=%s', mint)
continue
logging.info('%s SELL 100%% mint=%s balance=%s', 'LIVE' if LIVE else 'PREVIEW', mint, info['balance'])
if not LIVE:
continue
order = {
**credentials(),
'action': 'sell',
'mint': mint,
'amount': '100%',
'denominatedInQuote': 'false',
'slippage': SLIPPAGE,
'priorityFee': PRIORITY_FEE,
'guaranteedDelivery': 'true',
}
data = await post(session, TRADE_URL, order)
if data.get('confirmed') is not True or not data.get('signature'):
raise StopBot('Sale not confirmed; check the wallet before retrying')
trades = [trade for trade in data.get('trades', []) if isinstance(trade, dict)]
quote = trades[0].get('quoteMint') if trades else 'auto-selected'
logging.info('Sold mint=%s for %s signature=%s', mint, quote, data['signature'])


if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info('Stopped.')
except StopBot as exc:
logging.error('%s', exc)
raise SystemExit(1) from None