/candle:candle-trade-executionfrom candle
Guides building and debugging automated trading on the Candle agent SDK, covering position accounting, sell failures, retry loops, and error handling that cost real money in production.
Ships in candle. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
For detailed per-token signals and wallet intelligence, call GET https://api.hacc.fun/v1/signals?asset=<mint>&chain=solana&limit=50 with Authorization: Bearer <your cndl_live_ key> (production only, rows filtered to your plan); see Data and strategy API.
This is a field guide for agents wiring Candle's SDK into an automated strategy. Every rule below is here because it failed in production on a live wallet, not because it seemed prudent. Where a number appears, it is measured.
The failures cluster into three families, in order of how much they cost:
ExecutedTradeResult.amounts looks like this:
amounts: {
amountRaw: string // what you asked to spend or sell
minOutRaw: string // the enforced floor, guaranteed by the swap
expectedOutRaw: string // THE QUOTE. Not what you received.
quoteAsset: string
actualOutRaw?: string // what arrived, on Solana only
}
expectedOutRaw is the pre-trade expectation. It is not the delivered amount. On Solana,
amounts.actualOutRaw is what actually arrived, decoded from the payer's own balance change when the
server confirmed the trade; book from it. It is absent on Hood (and on a server that predates it),
where you still read the chain as below.
If you book a position's quantity from expectedOutRaw, your ledger drifts from the wallet by exactly
the buy's realised slippage, in whichever direction the fill went:
Both happened in one production run, from one line of code. The failing direction jammed three
positions for nine hours. The winning direction quietly stranded tokens across four trades starting
with the very first live order, every one marked executed / success: true.
Book from physical reality. On Solana, actualOutRaw is that reality. Where it is absent, fetch the transaction and diff the owner's pre
and post token balances for that mint. Read it with the highest transaction version your RPC and
client library document. Treat an unsupported-version error as an error, never as a reason to book
from the quote:
// MAX_TX_VERSION: the highest transaction version your RPC and client library document
const tx = await rpc.getTransaction(signature, { maxSupportedTransactionVersion: MAX_TX_VERSION })
const pre = tx.meta.preTokenBalances.find(b => b.owner === owner && b.mint === mint)
const post = tx.meta.postTokenBalances.find(b => b.owner === owner && b.mint === mint)
const delivered = BigInt(post?.uiTokenAmount.amount ?? '0') - BigInt(pre?.uiTokenAmount.amount ?? '0')
That is one extra RPC call per buy. It is the cheapest insurance in the system.
Record which source you used. Store a qty_source: 'onchain' | 'quote' beside the quantity, and
alert when it falls back. A fallback that nothing reports is the original bug wearing a hat.
If you will not do the on-chain read, book minOutRaw, not expectedOutRaw. It is the floor the
swap guarantees, so the ledger can only ever under-state what you hold. Under-stating strands dust;
over-stating jams the exit. Prefer the failure that does not block your exits.
Even with correct booking, clamp at the moment of the sell:
amountRaw = min(bookedQtyRaw, onChainBalanceRaw)
Three properties this must have, all learned the hard way:
The same bug has a twin on the way out. If you book exit_usd and realised PnL from the sell's
expectedOutRaw, every closed trade's PnL carries the same quote-versus-fill gap, and those numbers
feed drawdown limits and promotion gates. Read the quote-asset delta from the transaction. On a native
SOL leg, separate swap proceeds from the network fee and any rent, or the numbers move by the wrong
amount.
Every retry loop needs an attempt cap, a backoff, and a terminal state before it is allowed near real
money. In production a while pending: try again loop with none of the three ran 8,755 attempts
over 9 hours 45 minutes against orders that were arithmetically incapable of succeeding, at roughly
8 seconds per attempt, each attempt spending a quote, a build, a signing call and a broadcast.
If the retry gate is created_at < now() - someInterval, the timestamp never advances and the gate
only ever delays the first retry. Every subsequent cycle re-fires immediately. Give each attempt its
own scheduled time:
next_attempt_at = now() + backoff(attempts) -- exponential, jittered, capped
and select on next_attempt_at <= now().
Capping attempts on the order is not enough. When the order stops being pending, the layer above sees a position with no pending exit and mints a fresh order, and the loop resumes under a new id. This is not hypothetical: it produced order 19 (1,437 attempts), then order 21 (2,765 attempts) for the same position. Give abandonment a state the position-level logic also respects.
The subtlest version of this bug hid inside the fix for it. A per-order try/catch was added so one
failing order could not abort the whole cycle. It swallowed the throw without incrementing attempts,
so an order that threw before its status was written was re-claimed and re-executed forever, exempt
from the cap. A throw must cost an attempt exactly like a failure does.
A bare select ... for update skip locked on a connection pool releases its lock at statement end and
does not protect anything. Claim with a single statement:
update orders set next_attempt_at = now() + lease, last_attempt_at = now()
where id in (select id from orders where status='pending' and next_attempt_at <= now()
order by next_attempt_at limit $n for update skip locked)
returning *
Make the lease longer than one attempt's worst case, which is the sum of every HTTP timeout in the attempt, not one of them.
API errors (CandleApiError) carry .code, .status, .retryable and, where present, .field
and .routing; RPC errors (JsonRpcError) carry .code and .data. The SDK's own docs say to branch on code and never on
message. Do that. Three specific consequences:
-32002 is a preflight rejection, and it is definiteThe node simulated your exact signed transaction, refused it, and never forwarded it to a leader. If no earlier attempt's transaction could still be in flight, treat it as a definite rejection, not as "uncertain, retry". Classifying it as uncertain is what turned one deterministic failure into 2,026 identical attempts.
But AlreadyProcessed is a -32002 too, and it means the transaction landed. Marking it failed
books a loss on a swap that actually executed, leaving your ledger and the chain disagreeing about real
money. Blockhash expiry likewise stays uncertain, because a rebuild fixes it.
The rule that survived review: definite requires that you can already rule out an earlier attempt's transaction being alive.
err.data.logs has the full program logs; the message does notThe SDK's error formatter truncates the log array to three lines. On a Solana failure the first three frames are ComputeBudget instructions, so the truncated message shows you nothing but compute budget setup and hides the program that actually failed.
That single truncation is why a production incident took six hours to diagnose instead of ten minutes.
Store err.data.logs in full. When you need to know which program rejected a transaction, the logs are
the only thing that tells you, and a decoded error number without the program is meaningless (see
below).
The SDK interpolates the caller-supplied RPC URL verbatim into thrown error messages, at four sites, for both Solana and EVM. Most providers authenticate by API key in the query string. So the thrown message contains a live credential.
In production this reached a Discord channel in four alerts and forced a key rotation. Nothing in the integrator's own code ever wrote the key into a string; it was interpolated by a library and forwarded by an alerting path that had no idea what it was carrying.
Redact at every outbound boundary, not at the call site. Two passes:
KEY|TOKEN|SECRET|PASSPHRASE|PASSWORD|WEBHOOK|CREDENTIAL|AUTH). This is the pass that does
not rot as new variables appear, and it catches the secret in any shape.Redact before truncating, or a cut leaves the head of a key behind as ordinary text. Guard the value pass with a minimum length and skip URL-valued variables, or you will scrub ordinary words.
custom program error: 0x1788 is decimal 6024. Anchor numbers custom errors from 6000, so this is
the 25th error in some program's enum, and which program is the entire question.
Do not trust a blog post. The same number means different things in each program:
| program | 6024 |
|---|---|
Jupiter v6 (JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4) | InsufficientFunds |
PumpSwap AMM (pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA) | Truncation |
pump.fun bonding curve (6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P) | Overflow |
To settle it properly:
invoke [2] means the aggregator rejected it before entering any AMM.base = findProgramAddress([], programId), then
createWithSeed(base, "anchor:idl", programId), fetch that account, and zlib-decode it. This is
authoritative in a way that documentation is not.simulateTransaction before concluding anything. A bisect on the input
amount that shows balance clean and balance + 1 failing tells you more than any error table.Two you will meet often on this path:
InsufficientFunds: your input amount exceeds the wallet's balance. Raised by Jupiter's own
Route frame before any AMM is touched. This is the quote-versus-fill bug.SlippageToleranceExceeded: the transaction landed, reverted, and paid fees. Your
ledger should record it as a real cost, and a confirm step that refuses to book it (correctly) still
leaves you having spent money.A stable clientTradeId makes the vendor's ledger at-most-once. Through 8,755 attempts it held
perfectly, with no double-spend.
It does not limit how many signed transactions your process puts on the wire. On a linked-payer path you sign and broadcast yourself, so the idempotency key is a property of their records, not a lock on the network. If you rebuild and re-sign on each retry, you are generating a fresh signature every time. Guard against two live transactions yourself:
An alert dedupe key must carry the dimension that is getting worse. A key like
order:<id>:stuck announces a condition once and then guarantees silence while it deteriorates. In
production, four alerts covered 8,755 attempts: 99.95% of the deterioration was absorbed silently, and
the one alert an operator saw said "3 attempts".
Put the attempt bucket in the key, give the terminal state its own alert, and re-announce anything unreconciled once a day until a human clears it.
A liveness check must measure the work, not the loop. A heartbeat stayed green through all 8,755 failed attempts, because the process was looping perfectly. Publish the queue's own health (pending count, oldest attempt count, oldest age) onto the heartbeat that is already monitored, rather than only behind a new endpoint nobody polls.
Slippage tolerance is phantom quantity if you book from quotes. Widening buy slippage from 100 bps to 300 bps widened the gap between quote and fill, and therefore the size of the unsellable phantom position. The three jammed positions were short 2.165%, 1.256% and 0.103%, all inside the 300 bps tolerance. Fix the booking; do not paper over it by tightening slippage, especially since the same knob usually governs exits and tightening it makes real exits fail.
Check whether a "disable" value actually disables. A guard reading
Number.isFinite(raw) && raw > 0 ? raw : fallback silently falls back to its default when you set the
variable to 0. Setting a spend cap to 0 to stop trading can leave the default cap in force. Use a
value the guard accepts, and verify inside the running process, not in the config file.
In Docker Compose, VAR: ${VAR:-} sets an empty string rather than leaving the variable unset, so
?? defaults never fire. Use || or an explicit trim-or-default.
Verify env changes reached the process. A stopped container restarted rather than recreated keeps
its original environment. docker exec <container> printenv VAR is the check; the config file is not.
minOutRaw, never expectedOutRaw.code and .data, never on .message-32002 is definite only when an earlier send can be ruled out; AlreadyProcessed is not a rejectionerr.data.logs is stored, not the truncated messagegetSignatureStatuses with searchTransactionHistory: true. If null, nothing
landed and no amount of retrying will change that.getTokenAccountsByOwner, summing every account for that mint. A shortfall of a few tenths of a
percent is the quote-versus-fill bug.simulateTransaction before changing production state. Bisect the
amount: the threshold is usually the answer.Stop the loop before you investigate. A stuck order is spending provider quota and, if it is an exit, leaving a position exposed with no working stop.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
npx claudepluginhub candledottv/agentic --plugin candle23 skills in this plugin
/candle-agent-operations[OPERATIONS] Run long-lived trading workers and data collectors so they recover from crashes without losing state, never extend their own run, report health truthfully, and hand over cleanly to the next agent session. Use when deploying a trading worker or collector that runs for hours or days, when a worker has crashed, hung or restarted, and when ending a session that leaves workers running./candle-book-limits[RISK CONTROL] Size and audit the lifetime caps, slot counts and wallet reserves of an autonomous trading book so they bound risk without silently stopping the book or blocking its exits. Use when designing a book's limits, when a running book has gone quiet, when an order is stuck unresolved, and when two books share one wallet./candle-drained-pool-writeoff[RISK CONTROL] Recognize a held position whose pool was emptied after entry, and account for it as a loss instead of marking it at a stale price or retrying sells forever. Use when a held token's price has stopped updating, when sell quotes keep failing, when a mark looks healthy but no trades arrive, and when deciding whether an unsellable position can be closed out./candle-first-live-trade[OPERATIONS] The plumbing test a trading bot needs before and during its first live trades: a supervised minimum-size round trip through the real code, a sell proven before buys scale, a control exercised on a live position, and the ledger reconciled against the wallet. Use when a bot is about to trade real money for the first time, after any change of key, signer, wallet, venue or quote asset, when an operator says to kill a newly live bot, when the first live fills look different from paper, and when a newly live book goes quiet./candle-kill-switches[RISK CONTROL] The operator controls an autonomous trading book needs so a human can stop new risk, cut one position or cut everything without editing code or killing a process mid-order, and how those controls differ from the rail's own profile stops. Use when building a trading worker, before running one with real money, and when an operator asks to pause, cut, stop or restart a running book./candle-launch[TOKEN LAUNCH] Launch a new token on Candle, on Solana or Hood, optionally seeded with a dev buy (same transaction on Solana; best-effort follow-up on Hood). Use when the user asks to launch, create, deploy, or seed a token.