Files
pumpfun-bonkfun-bot_github/tests/regression/verify_tp_sl_exit_price.py
T
41b971147a refactor(cookbook): restructure learning-examples, add missing actions, fix quote decimals (#216)
* refactor(tests): move the regression verifiers into tests/regression

verify_*.py are not standalone examples: each imports src/, stubs the RPC
client, and asserts one previously fixed bug stays fixed. Their checks are
unchanged; PROJECT_ROOT, the usage lines and the bonk fixture lookup are
adjusted for the new depth. run_all.py runs the set and reports failures.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(tools): move the dev harness and listener benchmarks into tools/

simulate_*, live_*, both compare_* scripts and the account cleanup import
src/ and several spend real funds — they exercise the bot rather than teach
anything. compare_listeners.py reaches the repo root one level higher than
before; nothing else changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(cookbook): reorganise learning-examples into cookbook/

The directory is a reference collection — one runnable script per action — but
nothing said so: no index, scripts grouped by the transport they happened to
use, fixtures loose at the root.

Now grouped by platform, then by what you are doing:
pumpfun/{listen,read,trade,graduation,decode}, pumpswap, letsbonk, legacy.
Fixtures sit beside the script that reads them, manual_sell.py becomes
sell_token.py, and the legacy create example moves to legacy/ and says why.
pump_v2.py and tx_status.py stay at the cookbook root as the only two shared
helpers; subdirectories add that root to sys.path before importing them.
cookbook/README.md indexes every script and marks the ones that spend funds.

Also fixes create_v2's account list: the five mayhem accounts are mandatory
whatever is_mayhem_mode says, so mint_and_buy_v2.py could never have worked
with mayhem off. 11 accounts fails AnchorError 3005 (AccountNotEnoughKeys) on
sol_vault, 16 succeeds with the argument either way — simulateTransaction
against mainnet. Seven scripts gain a module docstring they were missing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(cookbook): add buy, create, balance and status examples

  buy_token.py <MINT>        buy_v2 against one coin; --dry-run simulates
  create_token.py            create_v2 on its own
  get_balances.py            SOL and tokens across both token programs
  check_tx_status.py <SIG>   success, reverted, or not visible yet

Buying previously meant manual_buy.py, which waits for the next coin created
anywhere before it trades — there was no way to buy a coin you already know.
Creating one meant bundling a buy with it, and the transaction-status helper
was a library with no entry point.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(cookbook): move pump_v2 next to the scripts that use it

pump_v2.py holds the buy_v2/sell_v2 account layouts, and only the pump.fun
trade scripts import it — it sat at the cookbook root because tx_status.py
does, not because anything outside pumpfun/trade/ needed it. The five callers
now pick it up as a plain sibling; legacy/ and the layout verifier reach into
that directory. tx_status.py stays at the root, where all four platforms use it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(cookbook): name every script protocol_verb_noun_variant

manual_buy.py did not just buy — it waited for the next coin created anywhere,
then bought, so the verb was wrong. Protocol was encoded three different ways:
directory, suffix, or not at all. And three scripts sat under pumpfun/ that have
nothing to do with pump.fun.

Filenames are now <protocol>_<verb>_<noun>[_<variant>].py, so a basename says
which chain, what it does and which instruction version without opening it:

  manual_buy.py            -> pumpfun_snipe_token_blocksubscribe.py
  manual_buy_geyser.py     -> pumpfun_snipe_token_geyser.py
  buy_token.py             -> pumpfun_buy_token_v2.py
  mint_and_buy_v2.py       -> pumpfun_create_and_buy_token_v2.py
  manual_buy_pumpswap.py   -> pumpswap_buy_token.py
  manual_buy_exact_in.py   -> letsbonk_buy_token_exact_in.py
  legacy/mint_and_buy.py   -> legacy/pumpfun_create_and_buy_token_v1.py

The sniper was named for logsSubscribe in an earlier draft; it sends
blockSubscribe, and the name now says so.

Balances, transaction status and the Anchor discriminator calculator are not
pump.fun-specific and move to a new cookbook/solana/. The two non-runnable
helpers take no verb — pump_v2.py becomes pumpfun_instructions_v2.py beside its
callers, tx_status.py becomes solana_transaction_status.py in solana/. Both are
imported under a short alias so the 106 call sites stay readable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): resolve a coin's quote mint before pricing it

quote_units() defaulted to 9 decimals for an unresolved mint, and every trade
script called it before resolve_quote_token_program() warmed the decimals
cache. pump.fun's QuoteControl registry admits mints at 6, 8 and 9 decimals —
79 of the 170 admitted are tokenized equities, 8 decimals for xStocks and 6 for
Backpack Securities — so those coins were sized against the wrong power of ten.

The error compounds rather than cancels: price_per_token() divides by the same
wrong unit, so the price reads low by the factor, the token amount comes out
high by it, and the inflated cap authorises the overspend instead of catching
it. 10x on an xStock pair, 1000x on a Backpack one.

This is not hypothetical. A 75s sample of live curve updates on 2026-09-22
caught 8 stock-paired curves out of 124 — IONQ across 5 of them, plus QUBT,
PLTRx and COPX.

quote_units() now raises for an unresolved mint instead of guessing, the four
trade paths resolve before they price, and pumpfun_read_price.py reads decimals
from chain rather than from a two-entry table. The geyser sniper never resolved
at all: it also passed SPL Token as the quote token program, which fails the
account constraints for any Token-2022 quote, and created no quote ATA.

verify_quote_decimals_resolved.py checks the fail-closed contract, that
resolution costs no extra RPC call, and that no function prices before it
resolves — confirmed to fail when the ordering is put back.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): read the quote-mint registry and Token-2022 mint state

Two reads that were unreachable without knowing an undocumented PDA seed.

pumpfun_read_quote_mints.py decodes QuoteControl (PDA ["quote-control"]), the
second quote-mint registry added in the 2026-09-15 upgrade. Reading only
Global.whitelisted_quote_mints under-reports: a coin can be paired with a mint
Global has never heard of. 170 admitted today, 79 of them tokenized equities,
each with the initial virtual quote reserves that set a new curve's opening
price. --stocks narrows to the equities, identified by the Token-2022 extension
set create_v2 requires of them rather than by a name lookup.

solana_read_token2022_mint.py reads the extensions that change what a balance
means: scaled UI amount, pausable, permanent delegate, transfer hook, default
account state. It exists mainly for one trap — the RPC returns both `multiplier`
and `newMultiplier` with an effective timestamp, and once that timestamp passes
the field named `multiplier` is the stale one. On AAPLx it passed on 2026-08-08,
so the obvious field has been wrong for six weeks. This compares against the
clock and says which is in force.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): add the exact-quote-in buy

buy_exact_quote_in_v2 was uncovered. It is the mirror of buy_v2 — buy_v2 fixes
the tokens received and caps the spend, this fixes the spend and floors the
tokens — and it takes the same 27 accounts in the same order, so it reuses
build_v2_accounts and differs only in discriminator and arguments.

Worth having because pinning the spend is the natural direction once a coin is
priced in something other than SOL: "spend exactly one AAPLx" is something you
can mean, where a token count is a number derived from a price that moved while
you derived it.

Verified by simulateTransaction against a live COPX-paired coin: the program
executes the full buy and stops at TransferChecked with insufficient funds,
which is as far as a wallet holding none of the quote asset can go.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): add the exact-SOL-in buy

buy_exact_sol_in was uncovered. SOL only — it pre-dates non-SOL quote assets and
carries no quote accounts, so the script checks the curve and points at the
exact-quote version for anything else rather than failing obscurely.

Its account list is the reason to have it. The IDL lists 16; the program needs
18, the extras being the bonding-curve-v2 PDA and a buyback fee recipient.
Determined by simulation rather than assumed: 16 accounts fails AnchorError 6062
(BuybackFeeRecipientMissing), 18 simulates clean at 96k CU. The v2 instructions
are complete in the IDL and this family is not, which is worth a newcomer
knowing before they trust the file.

The docstring carries the IDL's own fee arithmetic, since fees come out of the
amount you name rather than on top of it, and the printed estimate ignores that
split while min_tokens_out is what the program enforces.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): add the creator-fee and cashback payouts

Two payout paths that had no script. Both take no arguments and, per the IDL,
no signer — the funds can only reach the wallet they already belong to, so
either can be run for anyone, which --creator and --user expose.

collect_creator_fee_v2 sweeps a creator vault. The vault is per creator and per
quote asset, so a creator whose coins are priced in several assets collects each
separately; --quote picks which.

claim_cashback_v2 pays out an accrued cashback balance. create_v2 has rejected
new cashback coins since 2026-09-15 (error 6082), but coins minted before that
keep accruing and stay claimable, which is why the cashback handling elsewhere
in this repo is not dead code.

Both verified by simulateTransaction against mainnet: 10 accounts each, 8 data
bytes, no error.

Also repairs two cookbook README rows that the earlier rename mangled —
pumpswap_buy_token.py had been rewritten to pumpswap_pumpfun_buy_token_v2.py
because its name contains the string that rename matched on.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* refactor(cookbook): take every script's input on the command line

A reference collection only works if you can run a script against your own coin
without editing it. Several carried the coin as a module-level constant instead:

    TOKEN_MINT = Pubkey.from_string(sys.argv[1] if len(sys.argv) > 1 else "...")

which reads as optional but raises at import, so running the script the way its
own usage line described it died on ValueError: Invalid Base58 string before
printing anything. Nine scripts did this. Four more took their amount and
slippage from environment variables that no usage line mentioned.

Every script now builds an ArgumentParser in main(): required values are
positionals, tunables are --options, and the literals live in DEFAULT_* constants
that supply the defaults. --help works on all 32 that take input; the seven
listeners take none and are exempt. The decode scripts keep defaulting to the
fixture beside them, so they still run bare.

Behaviour is unchanged. create_and_buy's mayhem flag defaulted to on, so it takes
--mayhem/--no-mayhem via BooleanOptionalAction rather than a store_true that
would have silently flipped it off.

Two fixes found while threading the values through: the wallet listener read a
global `wallet` from four functions that no longer had one, and find_pool raised
IndexError on a coin that has not graduated instead of saying so.

verify_cookbook_arguments.py enforces the shape — no module-level sys.argv, no
placeholder values, argparse wherever there is input, and every default a usable
value. Confirmed to fail when the old pattern is put back.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* fix(docs): replace three dead links and check the rest

The Anchor discriminator citation in anchor_calculate_discriminator.py pointed
at book.anchor-lang.com/anchor_bts/discriminator.html, which Anchor removed when
it restructured its docs. Two links in the README had also moved:
docs.chainstack.com/quickstart/ and docs.chainstack.com/docs/trader-nodes.

  book.anchor-lang.com/anchor_bts/discriminator.html
    -> www.anchor-lang.com/docs/basics/idl          (has a Discriminators section)
  docs.chainstack.com/quickstart/
    -> docs.chainstack.com/reference/blockchain-apis
  docs.chainstack.com/docs/trader-nodes
    -> docs.chainstack.com/docs/solana-trader-nodes

All 28 real URLs in the repo now return 200, checked by fetching each one.

verify_documentation_links.py keeps them honest: offline it asserts every URL is
https and that none of the four dead endpoints has come back, and --live fetches
each and fails on 4xx/5xx. It skips the unroutable hosts the offline verifiers
point stub clients at, and example.com, which RFC 2606 reserves for exactly the
placeholder metadata URI a test coin is created with.

The discriminator script also still asked you to edit a constant, which the
argument rule had just outlawed, so it takes the name on the command line and
prints the u64, the byte list and the hex. Cross-checks against the constants in
pumpfun_instructions_v2.py: global:buy_v2 gives [184, 23, 238, 97, 103, 197,
211, 61], which is BUY_V2_DISCRIMINATOR.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* fix(cookbook,tools): detect coins via logs so v1 transactions are not skipped

Solana transaction v1 has been live since 2026-09-15 and solders cannot
deserialize one until 0.29. Three scripts detected coins by deserializing the
transaction envelope, so each went blind to v1:

  cookbook/pumpfun/listen/pumpfun_listen_tokens_blocksubscribe.py
      30,080 "skipping a v1 transaction" lines in 150s
  tools/compare_listeners.py
      601 "Failed to process transaction: io error: unexpected end of file"
      in 100s, which its own comment read as a transport difference
  cookbook/pumpfun/trade/pumpfun_snipe_token_blocksubscribe.py
      skipped v1 silently, so a coin created in one was never sniped

All three now route on meta.logMessages, which the RPC has already decoded and
which reads the same for every version. The blocks example keeps the envelope
decode as a genuine fallback for providers that return blocks without logs; the
sniper derives the associated bonding curve from the mint and curve instead of
reading the instruction's account list, verified against
pumpfun_derive_curve_addresses.py on a live coin.

Measured live after the change: the blocks example decoded 88 v0, 6 v1 and 4
legacy creates with zero skips and zero errors, and compare_listeners' block
lane now appears alongside logs and geyser for the same coins.

Upgrading solders was tried first and reverted. 0.29 does decode v1 — 0.26,
0.27.1 and 0.28 all raise "io error: unexpected end of file" on the committed
fixture — but it requires solana>=0.40, which moved TxOpts, MemcmpOpts and
TokenAccountOpts out of solana.rpc.types. 22 files import them and 16 of 19
verifiers failed on the import alone, so that is a migration of its own.

verify_transaction_v1.py gains a check that no cookbook or tools listener
detects by opening the envelope. It found the sniper, which this had missed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* fix(cookbook): label the transaction version and restore the lost fields

The blocks listener printed "Found CreateEvent in a 0 transaction", which reads
as a count rather than what it is — Solana's transaction version. It now prints
v0, v1 or legacy.

Routing detection through the CreateEvent also dropped two fields the
instruction path used to fill, so every detection showed "Token Standard: N/A"
and no Associated BC. Both come from the event's token_program: the standard is
that program, and the associated bonding curve is an ordinary ATA of the curve
under it. Verified against pumpfun_derive_curve_addresses.py on a live coin —
curve E94izXvHd7dd... derives to He94dArnuprt..., matching what the listener
now prints.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 09:34:40 +02:00

448 lines
16 KiB
Python

"""Verify the tp/sl exit sells against the fresh price and retries a failed sell.
Two bugs in `UniversalTrader._monitor_position_until_exit` (issue #189):
1. The sell was handed `position.entry_price` while the `current_price` that
had just triggered the exit sat in the same scope, fetched one RPC call
earlier. The seller turns that price into the slippage floor
(`min_quote_output`), so on a stop-loss the floor was computed from the
higher entry price and demanded more quote asset than the curve could pay
— the sell reverts with pump.fun 6003 TooLittleSolReceived exactly during
the drop the stop-loss exists to escape. On a take-profit the error runs
the other way: the floor lands far below market and protects nothing.
2. `break` 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 right above it. The
seller's own `max_retries` covers transaction *submission* only, so an
on-chain revert was never retried: the position was abandoned mid-crash.
Offline machine checks, no network and no funds moved. The real monitor loop is
driven with a stub curve manager serving a scripted price series and a stub
seller that records the price it is handed:
1. A stop-loss exit passes the triggering price, not the entry price.
2. A take-profit exit passes the triggering price too.
3. The floor built from the entry price is unpayable on a stop-loss, while
the floor from the triggering price is payable (why check 1 matters).
4. A failed sell is retried, and a retry that succeeds closes the position.
5. Retries are bounded, so a token that keeps reverting cannot pin the bot.
6. A price that recovers before the retry resets the attempt counter.
7. A successful sell still closes the position on the first attempt.
8. The cap comes from trade.max_exit_sell_attempts and is wired end to end.
Usage:
uv run tests/regression/verify_tp_sl_exit_price.py
"""
import asyncio
import sys
from dataclasses import dataclass, field
from pathlib import Path
from types import SimpleNamespace
PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT / "src"))
from solders.pubkey import Pubkey # noqa: E402
from core.pubkeys import WSOL_MINT, quote_units_per_token # noqa: E402
from interfaces.core import ( # noqa: E402
Platform,
TokenInfo,
TradeFailureReason,
)
from trading.base import TradeResult # noqa: E402
from trading.position import Position # noqa: E402
from trading.universal_trader import ( # noqa: E402
DEFAULT_MAX_EXIT_SELL_ATTEMPTS,
UniversalTrader,
)
ENTRY_PRICE = 1.0e-6 # SOL per token
QUANTITY = 1_000_000.0 # tokens, so entry notional is 1.0 SOL
SELL_SLIPPAGE = 0.3 # bots/*.yaml default
STOP_LOSS_PCT = 0.4
TAKE_PROFIT_PCT = 0.4
SL_TRIGGER_PRICE = ENTRY_PRICE * 0.55 # 45% down, past the stop loss
TP_TRIGGER_PRICE = ENTRY_PRICE * 1.5 # 50% up, past the take profit
REVERT_6003 = "custom program error: 0x1773 (6003 TooLittleSolReceived)"
@dataclass
class StubCurveManager:
"""Serves a scripted price series; the last value repeats forever."""
prices: list[float]
calls: int = 0
async def calculate_price(self, _pool_address: Pubkey) -> float:
price = self.prices[min(self.calls, len(self.prices) - 1)]
self.calls += 1
return price
@dataclass
class StubSeller:
"""Records the price it is handed. Fails the first `fail_first` calls."""
fail_first: int = 0
prices_seen: list[float] = field(default_factory=list)
async def execute(
self, token_info: TokenInfo, token_amount: float, token_price: float
) -> TradeResult:
self.prices_seen.append(token_price)
if len(self.prices_seen) <= self.fail_first:
return TradeResult(
success=False,
platform=token_info.platform,
# A revert is what this stub simulates, so it has to say so:
# an exit sell is only retried when retrying is provably safe,
# and a failure with no reason is treated as unresolved.
tx_signature="stub-reverted-signature",
error_message=REVERT_6003,
failure_reason=TradeFailureReason.REVERTED,
)
return TradeResult(
success=True,
platform=token_info.platform,
tx_signature="stub-signature",
amount=token_amount,
price=token_price,
)
def _make_trader(
curve_manager: StubCurveManager,
seller: StubSeller,
max_exit_sell_attempts: int = DEFAULT_MAX_EXIT_SELL_ATTEMPTS,
) -> UniversalTrader:
"""Build a trader carrying only what the monitor loop touches."""
trader = object.__new__(UniversalTrader)
trader.price_check_interval = 0 # no real waiting between iterations
trader.max_exit_sell_attempts = max_exit_sell_attempts
trader.platform_implementations = SimpleNamespace(
curve_manager=curve_manager, address_provider=None
)
trader.seller = seller
trader.solana_client = None
trader.wallet = None
trader.priority_fee_manager = None
trader.cleanup_mode = "disabled" # keeps handle_cleanup_after_sell a no-op
trader.cleanup_with_priority_fee = False
trader.cleanup_force_close_with_burn = False
# Keep a verification run from writing to ./trades.
trader._log_trade = lambda *_args, **_kwargs: None # noqa: SLF001
return trader
def _make_token_info() -> TokenInfo:
return TokenInfo(
name="Verify189",
symbol="V189",
uri="",
mint=Pubkey.default(),
platform=Platform.PUMP_FUN,
bonding_curve=Pubkey.default(),
)
def _make_position() -> Position:
return Position.create_from_buy_result(
mint=Pubkey.default(),
symbol="V189",
entry_price=ENTRY_PRICE,
quantity=QUANTITY,
take_profit_percentage=TAKE_PROFIT_PCT,
stop_loss_percentage=STOP_LOSS_PCT,
max_hold_time=None,
)
def _slippage_floor(reference_price: float) -> int:
"""Reproduce the seller's min_quote_output for the fixture position.
Mirrors PlatformAwareSeller.execute: expected output is amount * price,
then the slippage tolerance comes off it, in the quote mint's raw units.
"""
expected_quote_output = QUANTITY * reference_price
return max(
1,
int(
(expected_quote_output * (1 - SELL_SLIPPAGE))
* quote_units_per_token(WSOL_MINT)
),
)
def _payable(price: float) -> int:
"""Raw quote units the pool would return at `price`, ignoring curve impact.
Optimistic on purpose: a real sell moves the curve down and pays a fee, so
anything unpayable against this number is unpayable on chain too.
"""
return int(QUANTITY * price * quote_units_per_token(WSOL_MINT))
MONITOR_TIMEOUT = 10 # a bounded loop finishes in milliseconds here
async def _run_monitor(
prices: list[float],
fail_first: int = 0,
max_exit_sell_attempts: int = DEFAULT_MAX_EXIT_SELL_ATTEMPTS,
) -> tuple[Position, StubSeller, StubCurveManager]:
"""Drive the real monitor loop to completion over a scripted price series.
Raises:
TimeoutError: If the loop never exits, i.e. retries are unbounded.
"""
curve_manager = StubCurveManager(prices=list(prices))
seller = StubSeller(fail_first=fail_first)
position = _make_position()
trader = _make_trader(curve_manager, seller, max_exit_sell_attempts)
await asyncio.wait_for(
trader._monitor_position_until_exit(_make_token_info(), position), # noqa: SLF001
timeout=MONITOR_TIMEOUT,
)
return position, seller, curve_manager
def _check(label: str, passed: bool, detail: str) -> bool: # noqa: FBT001
print(f" [{'PASS' if passed else 'FAIL'}] {label}: {detail}")
return passed
async def check_stop_loss_uses_trigger_price() -> bool:
print("\n1. Stop-loss exit sells against the triggering price")
_, seller, _ = await _run_monitor([ENTRY_PRICE, SL_TRIGGER_PRICE])
price = seller.prices_seen[0]
return _check(
"price handed to seller",
price == SL_TRIGGER_PRICE,
f"{price:.8f} SOL (trigger {SL_TRIGGER_PRICE:.8f}, entry {ENTRY_PRICE:.8f})",
)
async def check_take_profit_uses_trigger_price() -> bool:
print("\n2. Take-profit exit sells against the triggering price")
_, seller, _ = await _run_monitor([ENTRY_PRICE, TP_TRIGGER_PRICE])
price = seller.prices_seen[0]
return _check(
"price handed to seller",
price == TP_TRIGGER_PRICE,
f"{price:.8f} SOL (trigger {TP_TRIGGER_PRICE:.8f}, entry {ENTRY_PRICE:.8f})",
)
def check_stale_floor_is_unpayable() -> bool:
print("\n3. Why it matters: the entry-price floor is unpayable on a drop")
from_entry = _slippage_floor(ENTRY_PRICE)
from_trigger = _slippage_floor(SL_TRIGGER_PRICE)
payable = _payable(SL_TRIGGER_PRICE)
print(
f" floor from entry price : {from_entry:>14,} raw quote units\n"
f" floor from trigger price : {from_trigger:>14,}\n"
f" pool can pay (optimistic): {payable:>14,}"
)
ok = _check(
"entry-price floor exceeds what the pool can pay",
from_entry > payable,
f"{from_entry:,} > {payable:,}, so the sell reverts 6003",
)
return ok and _check(
"trigger-price floor is payable",
from_trigger <= payable,
f"{from_trigger:,} <= {payable:,}",
)
async def check_failed_sell_is_retried() -> bool:
print("\n4. A failed sell is retried on the next price check")
fail_first = 1
position, seller, _ = await _run_monitor(
[ENTRY_PRICE, SL_TRIGGER_PRICE], fail_first=fail_first
)
expected = fail_first + 1 # the failure, then the retry that lands
ok = _check(
"seller called again after the failure",
len(seller.prices_seen) == expected,
f"{len(seller.prices_seen)} attempts, expected {expected}",
)
ok = (
_check(
"position closed after the retry landed",
not position.is_active,
f"is_active={position.is_active}, "
f"exit_reason={position.exit_reason.value if position.exit_reason else None}",
)
and ok
)
return ok
async def check_retries_are_bounded() -> bool:
print("\n5. Retries are bounded, so a reverting token cannot pin the bot")
# fail_first far above the cap: the loop must give up on its own, so the
# timeout firing is itself a failure - it means the retry never terminates
# and the bot would sit on this position forever.
try:
position, seller, _ = await _run_monitor(
[ENTRY_PRICE, SL_TRIGGER_PRICE], fail_first=99
)
except TimeoutError:
return _check(
"monitor loop terminates on repeated failures",
False, # noqa: FBT003
f"still retrying after {MONITOR_TIMEOUT}s - retries are unbounded",
)
ok = _check(
"attempts capped at the configured maximum",
len(seller.prices_seen) == DEFAULT_MAX_EXIT_SELL_ATTEMPTS,
f"{len(seller.prices_seen)} attempts, cap {DEFAULT_MAX_EXIT_SELL_ATTEMPTS}",
)
ok = (
_check(
"position not falsely marked closed",
position.is_active and position.exit_price is None,
f"is_active={position.is_active}, exit_price={position.exit_price}",
)
and ok
)
# Every retry must re-read the price rather than reuse the first one.
ok = (
_check(
"every attempt used the freshly read price",
all(p == SL_TRIGGER_PRICE for p in seller.prices_seen),
f"prices seen: {[f'{p:.8f}' for p in seller.prices_seen]}",
)
and ok
)
return ok
async def check_recovery_resets_attempts() -> bool:
print("\n6. A price recovery between attempts resets the attempt counter")
# Fail every sell. The price dips below the stop loss, recovers to flat,
# then dips again. With the counter reset on recovery, the cap applies to
# each burst separately, so the total is one full cap plus the earlier dip.
prices = [ENTRY_PRICE, SL_TRIGGER_PRICE, ENTRY_PRICE, SL_TRIGGER_PRICE]
_, seller, _ = await _run_monitor(prices, fail_first=99)
expected = 1 + DEFAULT_MAX_EXIT_SELL_ATTEMPTS
return _check(
"attempts counted per burst, not per position",
len(seller.prices_seen) == expected,
f"{len(seller.prices_seen)} attempts (1 before recovery + "
f"{DEFAULT_MAX_EXIT_SELL_ATTEMPTS} after), expected {expected}",
)
async def check_successful_sell_closes_once() -> bool:
print("\n7. A successful sell still closes the position on the first attempt")
position, seller, _ = await _run_monitor([ENTRY_PRICE, TP_TRIGGER_PRICE])
ok = _check(
"single sell attempt",
len(seller.prices_seen) == 1,
f"{len(seller.prices_seen)} attempt",
)
return (
_check(
"position closed with the exit recorded",
not position.is_active
and position.exit_reason is not None
and position.exit_price == TP_TRIGGER_PRICE,
f"is_active={position.is_active}, "
f"reason={position.exit_reason.value if position.exit_reason else None}, "
f"exit_price={position.exit_price}",
)
and ok
)
async def check_config_knob_is_honoured() -> bool:
"""The cap comes from trade.max_exit_sell_attempts, not a hardcoded value."""
print("\n8. trade.max_exit_sell_attempts drives the cap")
configured = 2 # deliberately different from the default
_, seller, _ = await _run_monitor(
[ENTRY_PRICE, SL_TRIGGER_PRICE],
fail_first=99,
max_exit_sell_attempts=configured,
)
ok = _check(
"configured value overrides the default",
len(seller.prices_seen) == configured != DEFAULT_MAX_EXIT_SELL_ATTEMPTS,
f"{len(seller.prices_seen)} attempts with the knob set to {configured} "
f"(default {DEFAULT_MAX_EXIT_SELL_ATTEMPTS})",
)
# Static wiring: a knob the runner never reads is a knob that does nothing.
runner = (PROJECT_ROOT / "src" / "bot_runner.py").read_text()
ok = (
_check(
"bot_runner reads it from the trade config",
'cfg["trade"].get(' in runner
and "max_exit_sell_attempts" in runner
and "DEFAULT_MAX_EXIT_SELL_ATTEMPTS" in runner,
"passed to UniversalTrader with the module default as fallback",
)
and ok
)
loader = (PROJECT_ROOT / "src" / "config_loader.py").read_text()
ok = (
_check(
"config_loader validates its range",
"trade.max_exit_sell_attempts" in loader,
"a 0 or a string in the YAML is rejected at startup",
)
and ok
)
documented = sorted(
path.name
for path in (PROJECT_ROOT / "bots").glob("*.yaml")
if "max_exit_sell_attempts" in path.read_text()
)
bots = sorted(path.name for path in (PROJECT_ROOT / "bots").glob("*.yaml"))
return (
_check(
"every bot config documents it",
documented == bots,
f"{len(documented)}/{len(bots)} configs mention it",
)
and ok
)
async def main() -> int:
print("Verifying tp/sl exit pricing and retry behaviour (issue #189)")
print(
f"fixture: entry {ENTRY_PRICE:.8f} SOL, {QUANTITY:,.0f} tokens, "
f"SL -{STOP_LOSS_PCT:.0%}, TP +{TAKE_PROFIT_PCT:.0%}, "
f"sell slippage {SELL_SLIPPAGE:.0%}"
)
results = [
await check_stop_loss_uses_trigger_price(),
await check_take_profit_uses_trigger_price(),
check_stale_floor_is_unpayable(),
await check_failed_sell_is_retried(),
await check_retries_are_bounded(),
await check_recovery_resets_attempts(),
await check_successful_sell_closes_once(),
await check_config_knob_is_honoured(),
]
passed = sum(results)
print(f"\n{passed}/{len(results)} checks passed")
if passed != len(results):
print("FAILED")
return 1
print("OK")
return 0
if __name__ == "__main__":
raise SystemExit(asyncio.run(main()))