* fix(trading): price tp/sl exits off the trigger price and retry a reverted sell
`_monitor_position_until_exit` handed `position.entry_price` to the sell while
the `current_price` that had just triggered the exit sat in the same scope, one
line up. `PlatformAwareSeller.execute` does not read a price - the `token_price`
it receives *is* the slippage floor - so a stop-loss priced off the entry demands
more quote asset than the curve can pay and reverts with 6003
`TooLittleSolReceived`, during the very drop the stop-loss exists to escape. On
a take-profit the same mistake runs the other way and the floor protects
nothing. `current_price` costs no extra RPC call; `_handle_time_based_exit` has
nothing fresher and keeps passing the buy price.
The `break` also sat outside both branches of `if sell_result.success:`, so the
loop exited whether the sell landed or not - contradicting the "Keep monitoring
in case sell can be retried" comment directly above it. The seller's
`max_retries` covers transaction submission only, so an on-chain revert was
never retried and the position was abandoned mid-crash with `is_active=True`.
A failed exit sell now retries on the next price check, re-reading the price so
the floor tracks the market, bounded by `trade.max_exit_sell_attempts`
(default 3, validated to 1..100) so a permanently reverting token cannot pin the
bot on one position. The counter resets if the price recovers out of the exit
band, and giving up is logged loudly since the tokens are still held.
Fixes#189
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test(learning-examples): machine-check the tp/sl exit price and retry path
Drives the real `_monitor_position_until_exit` with a stub curve manager
serving a scripted price series and a stub seller that records the price it is
handed. Offline, no network and no funds moved, per the `verify_*` convention.
Eight checks: both exit kinds sell at the triggering price, the entry-price
floor is arithmetically unpayable on a drop while the trigger-price floor is
payable, a reverted sell is retried and a landing retry closes the position,
retries stay bounded, a price recovery resets the counter, a successful sell
still closes on the first attempt, and the cap comes from
`trade.max_exit_sell_attempts` wired through bot_runner and config_loader.
Mutation-tested rather than trusted on a green run - reintroducing the stale
entry price drops it to 4/8, giving up after one failure to 4/8, and ignoring
the config knob to 7/8.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* docs: document the tp/sl exit path and its verifier
The caller owns the sell's slippage floor, which is not obvious from
`PlatformAwareSeller.execute` - it never reads a price, it just turns
`token_price` into `min_quote_output`. Records that, why an exit must price off
the triggering price, and that the seller's `max_retries` covers submission
only so an on-chain revert has to be retried in the monitor loop.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Extreme-fast mode submits with no RPC calls between detection and buy
when the listener parsed the on-chain CreateEvent (geyser/logs/blocks):
TokenInfo.state_from_event carries the canonical creator, mayhem/cashback
flags and quote_mint, so the pre-buy curve refresh is skipped. The geyser
listener now delegates to the event-first parser instead of inlining
instruction decoding, which also catches create_v2 transactions that omit
the trailing is_cashback_enabled byte.
Listeners without event data (pumpportal) keep the refresh, hardened per
issue #170: bonding curve derived from the mint instead of the payload's
bondingCurveKey, curve and mint read in one slot-consistent
getMultipleAccounts (correcting the guessed token program), and an
unreadable curve now skips the token within trade.curve_refresh_budget
instead of submitting a buy built from guessed accounts.
Machine-checked by verify_extreme_fast_zero_rpc.py and
verify_pumpportal_buy_path.py; validated live via simulate_bot_buy_path
on both geyser and pumpportal paths.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Refresh the vendored IDLs from pump-fun/pump-public-docs @ 9c82f61 and move all
pump.fun trading onto the v2 instruction interface. This is required, not
optional: legacy buy/sell cannot trade coins paired against a quote asset other
than SOL, and USDC is already whitelisted in the on-chain Global account.
Protocol changes absorbed:
- buy_v2 (27 accounts) / sell_v2 (26 accounts) replace the legacy instructions.
Every account is mandatory and the order is identical for all coins, so the
conditional cashback/mayhem account lists are gone. Legacy remains available
via PumpFunInstructionBuilder(use_legacy_instructions=True).
- BondingCurve is 151 bytes: virtual_sol_reserves -> virtual_quote_reserves,
real_sol_reserves -> real_quote_reserves, plus quote_mint at offset 83. Old
field names are kept as aliases so existing callers keep working.
- v2 instruction data drops the track_volume OptionBool; amounts are in the
quote mint's raw units rather than always lamports.
- create_v2 carries a non-SOL quote mint as optional remaining accounts 17-19,
and CreateEvent gained quote_mint, so extreme_fast_mode can resolve the quote
asset without an extra fetch.
USDC support: new trade.quote_amounts and filters.allowed_quote_mints config,
accepting "sol"/"usdc" aliases or raw mints. Amounts are per-quote-mint because
1 USDC and 1 SOL are not interchangeable. A coin whose quote mint has no
configured amount is skipped rather than traded at the wrong size, so SOL-only
configs are unaffected.
Bug fixes found while verifying:
- The logs and blocks listeners set no websocket max_size, so any frame over
1 MiB closed the connection with 1009 and the token in it was lost. Raised
to 32 MiB.
- PumpSwap priced against the raw quote vault balance, ignoring the new
Pool.virtual_quote_reserves (i128 at offset 245; live pools are 301 bytes).
Upstream's note that this field is 0 everywhere is out of date: a live pool
carries 17.58 SOL against a 148 SOL vault, a 10.15% price error.
- The seller read curve state once at confirmed commitment and silently fell
back to create-time values, risking a stale creator_vault and ConstraintSeeds.
It now retries at processed, matching the buyer.
- Account cleanup would burn wrapped SOL when force_burn was set, destroying
value that closing the account returns. WSOL is now closed without burning.
- The mint scripts treated a landed transaction as a successful one, so a
reverted buy printed as success. They now assert the on-chain result.
Compute unit limits retuned from mainnet measurements: buy 100k -> 180k,
sell 60k -> 120k. Mint-and-buy is no longer atomic, because create_v2 plus
buy_v2 exceeds the 1232-byte transaction limit; both mint scripts send two
transactions.
Adds learning-examples/pump_v2.py as one shared, standalone v2 toolkit for the
example scripts, and three verification scripts: an offline layout check
against the IDL, a no-funds mainnet simulation, and a live listener matrix that
buys, sells and closes the ATA per listener.
Verified on mainnet: all four listeners (geyser, logs, blocks, pumpportal) and
all eight example scripts completed a real buy, sell and ATA close, each
confirmed by reading the transaction result back rather than trusting
confirmation alone. The USDC path is verified structurally only; no USDC-paired
coin could be found on-chain to exercise it.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Before: BC fetch in extreme_fast_mode used default (confirmed) commitment
and retried up to 10 times with growing backoff (~10s total). Geyser/logs
fire on processed, so the BC isn't yet at confirmed commitment when the
bot reads it — most fetches failed and burned the full retry budget,
adding ~10s to detect→confirmed.
After: read at processed commitment to match the listener event horizon,
and cap retries at 4 with 150ms gaps (~600ms ceiling). Most reads succeed
on the first attempt.
Mainnet benchmark (n=4 successful buys, geyser listener):
buy_slot − create_slot: min=2 median=3 max=9 (~0.8s — 3.6s on chain)
wall detect→confirmed: median 2-3s (1s resolution)
Best case 2 slots = next slot after creation + tx propagation.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two related fixes from mainnet validation of geyser/logs/blocks/pumpportal:
1. extreme_fast_mode buys previously skipped the BC fetch entirely. After
the 2026-04-28 cutover, fee_recipient (mayhem mode) and creator_vault
(PFEE-delegated BC.creator) cannot be derived from listener-side data
alone — the program rejects with NotAuthorized (0x1770) /
ConstraintSeeds (0x7d6). Add a short retry loop that fetches the curve
state once before submitting the buy, so the instruction builder picks
the correct fee_recipient and creator_vault. The ~150ms cost is small
relative to a failed tx and 5s sell wait.
2. LetsBonkPumpPortalProcessor returned TokenInfo without token_program_id.
The universal builder then defaulted to Token-2022 and the buy failed
with IncorrectProgramId at GetAccountDataSize on the user-ATA create
ix. LetsBonk tokens are predominantly regular SPL Token, so default to
TOKEN_PROGRAM in the processor.
Note: the pumpportal listener still has unrelated data-race issues (the
PumpPortal stream sometimes fires before the on-chain BC is RPC-readable,
and bondingCurveKey occasionally references a different mint than the
detected token). These predate the 2026-04-28 cutover and need a separate
fix (e.g., verifying mint+BC consistency on the tx side before submit).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Post-2026-04-28, BC.creator can be delegated to a PFEE-program-owned PDA
after the initial creator buy. The create-time creator_vault cached on
TokenInfo goes stale before the sell lands, producing ConstraintSeeds
(0x7d6) on the Sell instruction.
The sell flow already re-fetches pool_state to refresh is_mayhem_mode and
is_cashback_coin; extend it to also refresh token_info.creator and re-derive
creator_vault from the current BC.creator.
Mainnet validation: geyser listener buy+sell on BEE — buy 2TSqZHZh…k7uN,
sell 3TevcP5g…f8nQ, err=None on both.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mirrors the four learning-examples commits (9b48418, c25e2ed, 57ffe8b,
ad6d2cc) into the production code paths under src/. Affects only pump_fun;
lets_bonk untouched. PumpSwap is not implemented under src/ so the
pool-v2 + breaking-fee-recipient pumpswap accounts are out of scope here.
Changes
-------
src/platforms/pumpfun/address_provider.py
- Adds BREAKING_FEE_RECIPIENTS: ClassVar[list[Pubkey]] with the 8
addresses pump.fun published for the 2026-04-28 upgrade.
- Adds pick_breaking_fee_recipient() (random.choice across the 8 to
spread program-tx throughput per pump.fun's recommendation).
- get_buy_instruction_accounts and get_sell_instruction_accounts now
expose "breaking_fee_recipient" alongside the existing keys.
src/platforms/pumpfun/instruction_builder.py
- BC buy ix: appends breaking_fee_recipient (mutable) AFTER
bonding_curve_v2 → 18 accounts total (was 17).
- BC sell ix: appends breaking_fee_recipient (mutable) AFTER
bonding_curve_v2 for both cashback and non-cashback paths
→ 16 accounts non-cashback / 17 cashback (was 15 / 16).
- get_required_accounts_for_{buy,sell} updated to include the new
account so priority-fee scraping covers it.
src/platforms/pumpfun/event_parser.py
- is_mayhem_mode now extracted into TokenInfo on both paths
(CreateEvent logs path and create / create_v2 instruction path);
previously only is_cashback_coin was carried forward, leaving
extreme_fast_mode buys to use the wrong fee_recipient on
Mayhem-Mode tokens.
src/trading/platform_aware.py
- Buy non-extreme path now also refreshes is_cashback_coin from
pool_state (was only refreshing is_mayhem_mode).
- Sell path now refreshes both flags from curve state before building
the sell ix, so a coin that flips cashback after buy still gets the
correct 16-vs-17-account layout. Wrapped in try/except so a transient
RPC failure logs a warning and falls back to token_info defaults
rather than failing the sell outright.
Live-validation (mainnet, all four bots/*.yaml configs)
-------------------------------------------------------
bot-sniper-2-logs.yaml buy 4GVJJwYtGixSPAQimgUhNYjEUBG6TB9XeQjKxs9EWpw2QfWuq7LHmUivPrsjhESgaPsPJQ9N6CCxECqxm9csqrH9 (18 accts) → sell 2ijgoPgxPmcSX4mFqz1PVkZ3yAvu36vj3Jy1yWZofxrK7jR92j2DWP3tRNy9PmUd1kiTaoYzVsrpGr6286KCnTp7 (16 accts) ✓
bot-sniper-3-blocks.yaml buy 4siRLG7tYk9iHyXAvnp3DH54vQXVEDHmCqZRmFgYhnRB9mVGjhh43ywohKjg8CpWctt5TyCtDkLRTRWT6VDwVyZi → sell 46jShWJ3sfuCP4YgTcpXWZdyqVmw4ULQSTC3Kwvbc9hE2y4yDosBww8Un8anXZpR1Xf96rN9QusV1G92oNcbp1o3 ✓
bot-sniper-1-geyser.yaml buy 4UEZy7LPm7Rxgw22d1bduQHTWHHHYJSpuaoq2iCyPFpnBPGt4C3QUCu9x77vwWugXnyGv4pQQeTbEZEjvyxxiDH2 → sell 21hSHVPKtqse25XybxhdGrpqK1fSxKKeNZGDCD5j568mzRPfyYR1TQs6mAc2moHKT7kaAAfdMC8DPt8VXmu2rviF ✓
bot-sniper-4-pp.yaml buy 4P91y4iPK6y1gPjz65VL6XAcVkT4DbqjHE5vHfX8PLnzqViCy1qZQ44eWiNDUPzoWCejibB7UJPKYAEj4K3Z3c3S ✓ ; sell hit slippage protection (Custom 6003 — program-side, the ix passed deserialization)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(core): disable account_data_size limit and add meta.err checking
The 12.5MB setLoadedAccountsDataSizeLimit was causing all buy transactions
to fail with MaxLoadedAccountsDataSizeExceeded since pump.fun migrated to
Token-2022. Transactions landed on-chain (fees paid) but inner instructions
were rejected — the bot paid gas for nothing.
Changes:
- Disable account_data_size in all bot configs (Token-2022 needs >12.5MB)
- Add meta.err check in get_buy_transaction_details() for clear error
reporting when transactions fail on-chain
- Include tx signature in platform_aware.py error messages for debugging
Tested: full buy→sell→cleanup cycle works on pump_fun with geyser listener.
* fix(core): check meta.err in confirm_transaction to detect failed txs
Solana transactions can be "confirmed" (included in a block) but still
fail execution if inner program instructions are rejected. Previously,
confirm_transaction only checked that the tx landed on-chain, causing
silent failures in buy, sell, and cleanup operations.
Now fetches the transaction result after confirmation and checks
meta.err, returning False when the transaction failed. This fixes
the ATA cleanup issue where sells were silently failing with
Custom: 6003 errors, leaving non-zero token balances.
* fix(core): treat failed tx fetch as unconfirmed in confirm_transaction
When _get_transaction_result returns None (RPC failure, timeout, etc.),
the function was falling through to return True — silently treating an
unknown state as success. Now returns False with a warning log.
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat(trading): enhance sell execution with token amount and price parameters to reduce RPC delays
* feat(trading): add method to fetch actual token balance after transaction to improve accuracy
* feat(trading): update account data size limit and enhance price calculations