Bot API
Check a token, scan a wallet and get a quote with no sign-in and no wallet: a key is only needed to trade.
- 7
- open endpoints
- 7
- keyed endpoints
- 0.25%
- fee
- 0
- sign-in to read
Try it
curl https://trnch.fun/api/bot/v1/statsEndpoints
Buy and sell through TRNCH from your own bot. You get the live race as opaque token ids, a webhook when a token enters it, and swap transactions that are ready to sign, in one call. Your bot signs with its own key and sends the transaction. TRNCH never holds your funds and never sees your keys. Snipers, trading bots and AI agents welcome.
Every token is screened by Trnch before it reaches the feed: rugs, honeypots, scam contracts, heavy sell taxes and copycats are kept out, and the API refuses to buy them (selling one stays possible). Every official Stock Token is covered, and copies are flagged. Live numbers, no key: GET /stats.
Get a key
Connect your wallet, open Profile and create a key in the API section. You can have 3 active keys. A key is shown once: copy it then. We only keep a fingerprint, so a lost key cannot be recovered, only revoked and replaced. A key works for the wallet that created it and for no other: swaps built with it always pay that wallet.
No browser? GET /register?wallet=0x... returns a message; sign it with that wallet (personal_sign) and POST /register { wallet, message, signature } to get the key. Building an agent for others? Add ref (your referral code) and earn your referral share of the fees of every swap it makes, for life.
Authorization: Bearer trnch_bot_YOUR_KEYMCP server for AI agents: https://trnch.fun/api/mcp (streamable HTTP, JSON). Tools: check, scan_wallet, top_24h, stats, register, heat, quote, buy, sell, confirm, alerts_subscribe, alerts_list, alerts_unsubscribe. Install lines and tool list. Agent guide: skill.md.
Agent quickstart
Key, quote, swap, signed by the agent wallet itself. Use a dedicated wallet with a small balance; its private key stays on your machine.
# 1. Key: get the message, sign it with the agent wallet (personal_sign), post it
curl "https://trnch.fun/api/bot/v1/register?wallet=0xAGENT_WALLET"
curl -X POST https://trnch.fun/api/bot/v1/register -H "Content-Type: application/json" \
-d '{ "wallet": "0xAGENT_WALLET", "message": "MESSAGE", "signature": "0xSIGNATURE" }' # -> { "key": "trnch_bot_..." }
# 2. Quote: best of the routers, fee included. Keep best.router
curl -X POST https://trnch.fun/api/bot/v1/quote -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
-d '{ "tokenIn": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", "tokenOut": "0xTOKEN", "amountIn": "5000000", "decimalsIn": 6, "decimalsOut": 18, "slippageBps": 100 }'
# 3. Build: the answer holds approval (or null) and tx, to sign with the agent wallet and send
curl -X POST https://trnch.fun/api/bot/v1/build -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
-d '{ "router": "BEST_ROUTER", "tokenIn": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", "tokenOut": "0xTOKEN", "amountIn": "5000000", "decimalsIn": 6, "decimalsOut": 18, "slippageBps": 100 }'import os, requests
from eth_account import Account
from eth_account.messages import encode_defunct
from web3 import Web3
API, USDG, TOKEN = "https://trnch.fun/api/bot/v1", "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", "0xTOKEN"
acct = Account.from_key(os.environ["AGENT_PRIVATE_KEY"]) # dedicated wallet, signs here only
w3 = Web3(Web3.HTTPProvider("https://rpc.mainnet.chain.robinhood.com"))
msg = requests.get(f"{API}/register", params={"wallet": acct.address}).json()["message"]
sig = acct.sign_message(encode_defunct(text=msg)).signature.to_0x_hex() # 0x-prefixed (web3.py v7: .hex() has no 0x)
key = requests.post(f"{API}/register", json={"wallet": acct.address, "message": msg, "signature": sig}).json()["key"]
H = {"Authorization": f"Bearer {key}"}
body = {"tokenIn": USDG, "tokenOut": TOKEN, "amountIn": "5000000", "decimalsIn": 6, "decimalsOut": 18, "slippageBps": 100}
best = requests.post(f"{API}/quote", json=body, headers=H).json()["best"]["router"]
r = requests.post(f"{API}/build", json={**body, "router": best}, headers=H).json()
assert r["from"].lower() == acct.address.lower()
for t in filter(None, [r["approval"], r["tx"]]):
tx = {"to": t["to"], "data": t["data"], "value": int(t.get("value", 0)), "chainId": r["chainId"],
"nonce": w3.eth.get_transaction_count(acct.address), "gasPrice": w3.eth.gas_price}
# tx.gas can be null: estimate it then
tx["gas"] = int(t["gas"]) if t.get("gas") else w3.eth.estimate_gas({**tx, "from": acct.address})
h = w3.eth.send_raw_transaction(acct.sign_transaction(tx).raw_transaction)
w3.eth.wait_for_transaction_receipt(h)
requests.post(f"{API}/confirm", json={"txHash": h.to_0x_hex()}, headers=H) # web3.py v7: .hex() has no 0x prefiximport { createWalletClient, createPublicClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
const API = "https://trnch.fun/api/bot/v1", USDG = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", TOKEN = "0xTOKEN";
const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY as `0x${string}`); // dedicated wallet, signs here only
const wallet = createWalletClient({ account, transport: http("https://rpc.mainnet.chain.robinhood.com") });
const rpc = createPublicClient({ transport: http("https://rpc.mainnet.chain.robinhood.com") });
const post = (path: string, body: unknown, key?: string) =>
fetch(API + path, { method: "POST", headers: { "Content-Type": "application/json", ...(key ? { Authorization: "Bearer " + key } : {}) }, body: JSON.stringify(body) }).then((r) => r.json());
const { message } = await fetch(`${API}/register?wallet=${account.address}`).then((r) => r.json());
const { key } = await post("/register", { wallet: account.address, message, signature: await account.signMessage({ message }) });
const body = { tokenIn: USDG, tokenOut: TOKEN, amountIn: "5000000", decimalsIn: 6, decimalsOut: 18, slippageBps: 100 };
const { best } = await post("/quote", body, key);
const r = await post("/build", { ...body, router: best.router }, key);
if (r.from.toLowerCase() !== account.address.toLowerCase()) throw new Error("wrong signer");
let hash;
for (const t of [r.approval, r.tx].filter(Boolean)) {
hash = await wallet.sendTransaction({ chain: null, to: t.to, data: t.data, value: BigInt(t.value ?? 0) });
await rpc.waitForTransactionReceipt({ hash });
}
await post("/confirm", { txHash: hash }, key);GET /heat
The current Heat, as three parts. heat: the tokens of the Heat. new: newly spotted tokens (status: "unverified"), higher risk. stats: counts for the last 24 hours, spotted, inHeat, flagged (removed by Trnch) and rugged (liquidity pulled). Each token is an opaque id with market numbers (rank, Heat score, price, liquidity, volume, price changes, entry time). The price is rounded to 2 significant digits, liquidity and volumes to 2, times to the minute. The Bot API gives no token names or addresses: the id only works with TRNCH /quote, /build, /buy and /sell. With since (epoch milliseconds or an ISO date) you only receive tokens that entered the Heat, or were spotted, after it. Pass the nextSince of each response to your next call; a token of the same minute can come back, dedupe by id. Every valid key gets the same feed.
curl -H "Authorization: Bearer trnch_bot_YOUR_KEY" \
"https://trnch.fun/api/bot/v1/heat"
# Only what entered the Heat after the last call (pass back nextSince):
curl -H "Authorization: Bearer trnch_bot_YOUR_KEY" \
"https://trnch.fun/api/bot/v1/heat?since=1760000000000"POST /buy and POST /sell
One call to trade. We ask every active router, as the site does, keep the best route and build the transaction for the wallet of your key. /buy takes tokenId (from /heat) or a token token address, and either amountUsd (paid in USDG) or amountIn in the smallest unit of tokenIn (USDG by default). /sell takes tokenId or token and either percent (a share of the balance your wallet holds, read on-chain) or amount in token units, and pays you in USDG. slippageBps is optional (default 100, from 10 to 5000). If the best route cannot be built any more, the next router is tried once. The answer is { router, quote, approval, tx, chainId, from }: send approval first when it is not null, then tx, both signed by your bot. Same guards as /build: no receiver field, tokens TRNCH cannot trade for a bot refused (409), and the same limits. When swaps are paused on TRNCH, it answers 503.
curl -X POST "https://trnch.fun/api/bot/v1/buy" \
-H "Authorization: Bearer trnch_bot_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "tokenId": "ID_FROM_HEAT", "amountUsd": 25, "slippageBps": 150 }'
# Or pay with another token: "amountIn" in its smallest unit, plus "tokenIn" (USDG by default)
# { "tokenId": "ID_FROM_HEAT", "tokenIn": "0xTOKEN_YOU_PAY_WITH", "amountIn": "1000000000000000" }
# Response: { router, quote, approval, tx, chainId, from }
# quote: { amountOut, inUsd, outUsd, gasUsd, unjudged, feeTaken, routesAsked }; feeBps (fee rate in basis points) sits next to router
# tx.gas: the router estimate + 30%, send it as iscurl -X POST "https://trnch.fun/api/bot/v1/sell" \
-H "Authorization: Bearer trnch_bot_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "tokenId": "ID_FROM_HEAT", "percent": 100, "slippageBps": 150 }'
# Or an exact amount, in token units: { "tokenId": "ID_FROM_HEAT", "amount": "1234.5" }POST /quote
The best route for a swap, every router asked: input and output token, amountIn in the smallest unit of the input token, andslippageBps (100 is 1%, default 100; slippage as a fraction is still accepted). The answer lists each route with its output amount; keep the router of the one you want. Routes that need an intermediate signature are not offered. tokenIn and tokenOut take an address or a token id from /heat. Optional fast: true returns the first clean quote after about 250 ms and may return a slightly worse price; partial: true in the answer says a slower router was cut. timing gives the server time of the quote, in total and per router (ms).
curl -X POST "https://trnch.fun/api/bot/v1/quote" \
-H "Authorization: Bearer trnch_bot_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"tokenIn": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
"tokenOut": "ID_FROM_HEAT",
"amountIn": "25000000",
"decimalsIn": 6,
"decimalsOut": 18,
"slippageBps": 100
}'POST /build
A transaction ready to sign, for the wallet of your key and nobody else. The body is the quote body plus the router. There is no receiver or taker field: any extra field is refused. The route is quoted again and checked against our prices when you build, so sign it soon after. If the input token is an ERC-20, approval holds an approve for the exact amount, to send first unless your allowance already covers it; it is null for native ETH.
curl -X POST "https://trnch.fun/api/bot/v1/build" \
-H "Authorization: Bearer trnch_bot_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"router": "0x",
"tokenIn": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
"tokenOut": "ID_FROM_HEAT",
"amountIn": "25000000",
"decimalsIn": 6,
"decimalsOut": 18,
"slippageBps": 100
}'
# Response: { router, amountOut, tx, chainId, from, approval }
# 1. if approval is not null and your allowance is lower, sign and send approval
# 2. sign and send tx with YOUR keyPOST /confirm
After you send the transaction, tell us its hash. The swap is checked on-chain and its volume counts for your TRNCH account like a swap made on the site. Nothing is counted for a hash that is not a swap built by your key for your wallet.
curl -X POST "https://trnch.fun/api/bot/v1/confirm" \
-H "Authorization: Bearer trnch_bot_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "txHash": "0xYOUR_SWAP_TRANSACTION_HASH" }'GET /scan
No key. Every ERC-20 a wallet holds on Robinhood Chain: address, symbol, balance (raw and decimals), valueUsd when known, the same Trnch verdict as /check (status, category, rugged, dumped), flagged and canSell (false only for a confirmed honeypot). A flagged token that can be sold carries a sell hint: the POST /sell call to make and a trnch.fun/trade link. Flagged tokens come first. ETH, WETH, USDG and official assets are listed as official, without a check. At most 100 other tokens are returned, flagged first, then tokens with no known price, then the most valuable: truncated: true when more are held. Cached 60 seconds per wallet; 20 calls per minute per IP. A signal, never a guarantee.
curl "https://trnch.fun/api/bot/v1/scan?wallet=0xYOUR_WALLET"Check any CA
curl "https://trnch.fun/api/bot/v1/check?token=0xTOKEN"curl -X POST https://trnch.fun/api/bot/v1/check/batch \
-H "content-type: application/json" \
-d '{"tokens":["0xTOKEN_1","0xTOKEN_2"]}'summary: one line to post as is.verified: true for tokens verified by Trnch and official assets.status,category,rugged,dumped: the verdict.tokenUrl: the token page.cardUrl: the share image.license: free to display and relay with a link totokenUrl.- Batch:
{ results }in input order, duplicates removed. A token that cannot be checked returns{ token, error }. - No key.
/check: 120 calls per minute per IP./check/batch: 20 addresses per call, 10 calls per minute per IP.
Badge
<a href="https://trnch.fun/token/0x...">
<img src="https://trnch.fun/api/badge/token/0x....svg" alt="trnch scan verdict" height="28">
</a>[](https://trnch.fun/token/0x...)GET /api/badge/token/0x...(with or without.svg): an SVG pill, the same verdict as/check.?theme=light|dark, default dark.- Verified, No red flag, Flagged: category, Rugged, Dumped, Not seen yet. A signal, never a guarantee.
- No key. Free to display with the link to the token page. Cached 5 minutes, 120 calls per minute per IP.
Partner integration
- Header
X-Trnch-Partner-Key: trnch_ptn_...on/check,/check/batchand/api/badge/token/0x.... - The key replaces the per-IP limit: 1,200 calls per minute by default, plus a daily cap, counted in tokens across the three routes (a batch of 20 counts 20). A 429 carries
Retry-After. - Missing, unknown or revoked key: the anonymous limit applies, nothing else changes. Key lookups are limited per IP (30 per minute).
- Deployer clusters (
GET /api/partner/v1/deployer?token=0x...) need a key with the clusters right, granted under a written agreement. - Self-serve:
GET /partner/key?wallet=, sign with the payout wallet,POST /partner/key. One active key per payout wallet. Keep it server side. Contact: hello@trnch.fun.
Integrator fee
curl "https://trnch.fun/api/bot/v1/partner/key?wallet=0xPAYOUT_WALLET"
# sign the returned message with that wallet (personal_sign), then:
curl -X POST https://trnch.fun/api/bot/v1/partner/key -H "Content-Type: application/json" \
-d '{ "wallet": "0xPAYOUT_WALLET", "message": "MESSAGE", "signature": "0xSIGNATURE" }' # -> { "key": "trnch_ptn_..." }integratorFeeBps0 to 100 on/quote,/build,/buy,/sell, withX-Trnch-Partner-Key.- Default fee:
PUT /partner/fee { bps }, MCPtrnch_partner_fee_set. - On top of the Trnch fee, on all eight routers. Paid by the partner program at its payout period. Earn
Wallet alerts
Key required. POST /alerts { wallet, webhookUrl } subscribes a webhook to the Trnch flags on a wallet (any address); GET /alerts lists your subscriptions; DELETE /alerts?id= removes one. 3 per key, 5 active per wallet, 20 per destination host. Every 5 minutes, a token the wallet holds that Trnch newly flagged is sent as one JSON POST; the first time, each token it already holds that Trnch keeps out is sent once with initial: true: { event: "wallet.flag", id, initial, wallet, token, verdict, canSell, sell }, signed like the Heat webhook (X-TRNCH-Signature, secret shown once when you subscribe).
- The URL must be https on port 443, with a public domain name: IP addresses, localhost, private and internal names are refused, and the name is resolved at each send, the connection pinned to the checked address. Redirects are not followed.
- Answer with a 2xx within 3 seconds; a failed delivery is retried on the next run, 3 attempts at most. The list shows
lastDelivery(delivered or failed) only. After 10 failed deliveries in a row the subscription is switched off; subscribe again to restart it. A revoked key loses its subscriptions.
curl -X POST "https://trnch.fun/api/bot/v1/alerts" \
-H "Authorization: Bearer trnch_bot_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "wallet": "0xWALLET_TO_WATCH", "webhookUrl": "https://example.com/trnch-alerts" }'New Stock Tokens
Key required. POST /events { event: "stock.listed", webhookUrl } subscribes a webhook to new verified Stock Tokens on Robinhood Chain; GET /events lists it; DELETE /events?id= removes it. 1 per key, 5 active per wallet, 20 per destination host. Within the hour a token joins the official list, one JSON POST: { event: "stock.listed", id, createdAt, chainId: 4663, token: { address, symbol, company }, url, listedAt }, signed like the Heat webhook (X-TRNCH-Signature, secret shown once).
- Only tokens listed after you subscribe. Same URL rules as wallet alerts. Dedupe on
id: a retry carries the same one. - Answer with a 2xx within 3 seconds; a failed delivery is retried on the next run, 3 attempts at most. After 10 failed deliveries in a row the subscription is switched off. A revoked key loses it.
curl -X POST "https://trnch.fun/api/bot/v1/events" \
-H "Authorization: Bearer trnch_bot_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "event": "stock.listed", "webhookUrl": "https://example.com/trnch-events" }'Webhook: the Heat comes to you
Instead of polling, give a https URL to each key in Profile (API section). When a token enters the Heat, the same event as the New in the Heat alert, TRNCH sends a JSON POST to it, within about a minute, with the same token fields as /heat (an opaque id and market numbers). Nothing about you is sent. The signing secret (whsec_...) is shown once when you save the URL.
- Check
X-TRNCH-Signature: t=<unix seconds>,v1=<hex>:v1is the HMAC-SHA256 of<t>.<raw body>with your secret. Reject a signature that does not match, or atmore than 5 minutes old. - Answer with a 2xx within 3 seconds. A network error, a 5xx or a 429 is retried at most 2 more times; other answers are not retried. Redirects are not followed.
- After 5 failed deliveries in a row the webhook is switched off; save the URL again in your Profile to restart it. A revoked key loses its webhook.
- The URL must be https on port 443, with a public domain name (no IP address). One token is sent once per webhook, and only tokens that entered the Heat after the webhook was saved.
POST https://your-bot.example.com/trnch
Content-Type: application/json
X-TRNCH-Signature: t=1760000000,v1=9f2c...e1
{
"event": "heat.entry",
"id": "OPAQUE_TOKEN_ID:1760000000000",
"createdAt": 1760000003000,
"token": {
"id": "OPAQUE_TOKEN_ID", "rank": 4,
"heatScore": 74, "momentum": 1.8, "priceUsd": 0.00042, "liquidityUsd": 31000,
"volume1hUsd": 5400, "volume24hUsd": 5400, "priceChange5mPct": 3.1, "priceChange1hPct": null,
"traders24h": 38, "status": "active",
"enteredHeatAt": 1760000000000
}
}Starter scripts
- This is a starting point, not a strategy. New pools are the riskiest tokens there are: many are rugs, honeypots or illiquid, and the Heat filters only remove the ones we can detect.
- A bot that signs by itself can lose all the funds in its wallet in minutes. Use a dedicated wallet with a small balance, never your main wallet. Start with tiny amounts.
- The private key stays on your machine: read it from an environment variable, never write it in the code, never commit it, never send it to anyone. TRNCH never asks for it.
- Nothing here is financial advice. You are responsible for what your bot buys and sells.
Agent strategy (dry run by default)
One script per language, modules chosen by environment variables. ENTRY: heat (default, polls /heat with since / nextSince), trending (/top), dip (a drop from the window high on DIP_TOKENS). EXIT: tp_sl (default), trailing, ladder, time. A guard (new, like REENTRY_HOURS) re-checks every held token by address with /check and sells if Trnch now keeps it out or its quoted value collapses; with neither tp_sl nor trailing in EXIT a STOP_LOSS_PCT stop is added. The script stays under the 30 per minute quote limit of the key (QUOTE_BUDGET_PER_MIN, 25), open positions first. Every action is logged. A reverted transaction is an error, never a position; it sells exactly what it bought. An invalid setting stops the program. Nothing is signed until you set DRY_RUN=0; the dry run quotes with /quote and builds nothing. Settings are environment variables: BUY_USD, MAX_TOTAL_USD (optional total spend cap, 0 = none), MIN_SCORE, MIN_LIQUIDITY_USD, TAKE_PROFIT_PCT, STOP_LOSS_PCT, TRAILING_STOP_PCT, LADDER, MAX_HOLD_MINUTES, DIP_PCT, DIP_MAX_PCT, REENTRY_HOURS, MAX_OPEN, SLIPPAGE_BPS, POLL_SECONDS. An example rule set, not a recommendation. Download: curl -s "https://trnch.fun/api/bot/v1/strategy?lang=ts" -o agent.ts (or lang=py).
TypeScript (viem)
// Trnch agent strategy pack (example). Node 20+ : npm i viem tsx && npx tsx agent.ts
// DRY RUN BY DEFAULT: it logs what it would do and signs nothing. Set DRY_RUN=0 to trade for real.
// Env: TRNCH_API_KEY (required) | BOT_PRIVATE_KEY (only for DRY_RUN=0, a DEDICATED wallet; signs here, never sent)
// Pick modules (comma lists, defaults = the classic Heat strategy):
// ENTRY=heat | trending | dip e.g. ENTRY=heat,trending
// EXIT=tp_sl | trailing | ladder | time e.g. EXIT=tp_sl,time (first rule that fires wins)
// Common: BUY_USD=5 MAX_TOTAL_USD=0 (optional total spend cap, 0 = no cap) MAX_OPEN=3 SLIPPAGE_BPS=150 POLL_SECONDS=5
// REENTRY_HOURS=6 (no re-buy of a token just sold, 0 = off)
// heat: MIN_SCORE=70 MIN_LIQUIDITY_USD=20000
// trending: TREND_MIN_X=1.1 TREND_MAX_X=5 TREND_MAX_PULLBACK_PCT=25 TREND_LIMIT=10 TOP_POLL_SECONDS=300 (source: GET /top)
// dip: DIP_TOKENS=0xabc...,0xdef... (your list; empty = the /top list) DIP_PCT=10 DIP_WINDOW_MINUTES=60
// DIP_SAMPLE_SECONDS=60 DIP_PROBE_USD=10 DIP_MAX_TOKENS=10 (price = /quote of a probe amount, nothing is bought to sample)
// DIP_MAX_PCT=40 (a drop deeper than this is skipped: likely a rug, not a dip); a quotable SELL route is required before a buy
// tp_sl: TAKE_PROFIT_PCT=50 STOP_LOSS_PCT=25
// trailing: TRAILING_STOP_PCT=15 (sell when the value falls this much from its peak since entry)
// ladder: LADDER=50:30,100:30,200:40 (gain %:share of the buy sold at that gain; shares add up to at most 100)
// time: MAX_HOLD_MINUTES=240
// Safety stop: if EXIT has neither tp_sl nor trailing (ladder and/or time alone), a STOP_LOSS_PCT stop (25) is added, so a
// position never rides on the guards alone. A ladder whose shares add up to less than 100 leaves the rest on that
// stop, on time (if listed) and on the guards.
// guard (always on): every held token is re-checked by address with /check and sold if Trnch now keeps it out, flags it
// or it is rugged/dumped; sold if the /quote value falls GUARD_LIQUIDITY_DROP_PCT=60 in one cycle or from entry,
// or if no route can be quoted 3 times in a row.
// Quote budget: /quote, /buy and /sell share the 30 per minute limit of your key. The script keeps its own count of the last 60 s
// and stays under QUOTE_BUDGET_PER_MIN=25; open positions come first, dip sampling and new entries use what is left.
// On a 429 it waits for Retry-After once (never per token) and skips the rest of that scan.
// New in this version: the always-on guard and REENTRY_HOURS. A token Trnch refuses to quote or sell (409, Trnch keeps it out) keeps
// its position and logs alert_not_tradable: sell it elsewhere with your own wallet.
// WATCH_TOKENS=0xabc...,0xdef... (optional, logged with /check at start)
// A setting that is not valid stops the program with an error. Dry run and live keep separate state files.
// Every action is logged. An example of an automated rule set, not a recommendation: prices can fall to zero.
import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { createPublicClient, createWalletClient, defineChain, formatUnits, http, parseAbi, type Hex, type TransactionReceipt } from "viem";
import { privateKeyToAccount } from "viem/accounts";
const API = "https://trnch.fun/api/bot/v1";
const USDG = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168";
function num(key: string, fallback: number, min: number, max = Infinity): number {
const raw = process.env[key];
if (raw === undefined || raw === "") return fallback;
const value = Number(raw);
if (!Number.isFinite(value) || value < min || value > max) {
console.error("Invalid " + key + "=" + raw + ": expected a number from " + min + " to " + max);
process.exit(1);
}
return value;
}
function modules(key: string, fallback: string, allowed: readonly string[]): string[] {
const raw = process.env[key] || fallback;
const list = parseModules(raw, allowed);
if (!list) {
console.error("Invalid " + key + "=" + raw + ": expected a comma list of " + allowed.join(", "));
process.exit(1);
}
return list;
}
function addresses(key: string): string[] {
const list = (process.env[key] ?? "").split(",").map((a) => a.trim().toLowerCase()).filter(Boolean);
for (const a of list) {
if (!/^0x[0-9a-f]{40}$/.test(a)) {
console.error("Invalid " + key + ": " + a + " is not a 0x address");
process.exit(1);
}
}
return list;
}
const LADDER_RAW = process.env.LADDER || "50:30,100:30,200:40";
const LADDER = parseLadder(LADDER_RAW);
if (!LADDER) {
console.error("Invalid LADDER=" + LADDER_RAW + ": expected gain:share pairs like 50:30,100:30,200:40 (gains increasing, shares adding up to at most 100)");
process.exit(1);
}
const DIP_TOKENS = addresses("DIP_TOKENS");
const CFG = {
dryRun: process.env.DRY_RUN !== "0",
entries: modules("ENTRY", "heat", ["heat", "trending", "dip"]),
exits: withSafetyStop(modules("EXIT", "tp_sl", ["tp_sl", "trailing", "ladder", "time"])),
buyUsd: num("BUY_USD", 5, 0.01),
maxTotalUsd: num("MAX_TOTAL_USD", 0, 0),
minScore: num("MIN_SCORE", 70, 0, 100),
minLiquidityUsd: num("MIN_LIQUIDITY_USD", 20000, 0),
takeProfitPct: num("TAKE_PROFIT_PCT", 50, 0.1),
stopLossPct: num("STOP_LOSS_PCT", 25, 0.1, 99.9),
trailingStopPct: num("TRAILING_STOP_PCT", 15, 0.1, 99.9),
ladder: LADDER,
maxHoldMinutes: num("MAX_HOLD_MINUTES", 240, 1),
trendMinX: num("TREND_MIN_X", 1.1, 0.01),
trendMaxX: num("TREND_MAX_X", 5, 0.01),
trendMaxPullbackPct: num("TREND_MAX_PULLBACK_PCT", 25, 0, 99.9),
trendLimit: Math.floor(num("TREND_LIMIT", 10, 1, 20)),
topPollSeconds: Math.max(60, num("TOP_POLL_SECONDS", 300, 1)),
dipPct: num("DIP_PCT", 10, 0.1, 99.9),
dipMaxPct: num("DIP_MAX_PCT", 40, 1, 99.9),
dipWindowMinutes: num("DIP_WINDOW_MINUTES", 60, 2),
dipSampleSeconds: Math.max(30, num("DIP_SAMPLE_SECONDS", 60, 1)),
dipProbeUsd: num("DIP_PROBE_USD", 10, 0.5),
dipMaxTokens: Math.floor(num("DIP_MAX_TOKENS", 10, 1, 20)),
liquidityDropPct: num("GUARD_LIQUIDITY_DROP_PCT", 60, 1, 99.9),
quoteBudget: Math.floor(num("QUOTE_BUDGET_PER_MIN", 25, 5, 30)),
reentryHours: num("REENTRY_HOURS", 6, 0),
maxOpen: Math.floor(num("MAX_OPEN", 3, 1, 50)),
slippageBps: Math.floor(num("SLIPPAGE_BPS", 150, 10, 5000)),
pollSeconds: Math.max(3, num("POLL_SECONDS", 5, 1)),
};
if (CFG.dipMaxPct < CFG.dipPct) {
console.error("Invalid DIP_MAX_PCT=" + CFG.dipMaxPct + ": it must be at least DIP_PCT=" + CFG.dipPct);
process.exit(1);
}
if (!process.env.TRNCH_API_KEY || (!CFG.dryRun && !process.env.BOT_PRIVATE_KEY)) {
console.error("TRNCH_API_KEY is required, and BOT_PRIVATE_KEY too when DRY_RUN=0");
process.exit(1);
}
const WATCH = (process.env.WATCH_TOKENS ?? "").split(",").map((a) => a.trim()).filter(Boolean);
const STATE_FILE = process.env.STATE_FILE ?? (CFG.dryRun ? "trnch-state-dry.json" : "trnch-state-live.json");
const LOG_FILE = process.env.LOG_FILE ?? "trnch-actions.jsonl";
// --- decision logic (pure, no network) ---
interface Tranche { gainPct: number; sharePct: number }
interface Cfg {
minScore: number; minLiquidityUsd: number; takeProfitPct: number; stopLossPct: number; maxOpen: number;
exits: string[]; trailingStopPct: number; ladder: Tranche[]; maxHoldMinutes: number;
trendMinX: number; trendMaxX: number; trendMaxPullbackPct: number;
dipPct: number; dipMaxPct: number; dipWindowMinutes: number; liquidityDropPct: number; reentryHours: number;
}
interface HeatToken { id: string; heatScore: number; liquidityUsd: number; status: string; risk?: string }
interface TopToken { token: string; latestSinceEntry: string | null; peakSinceEntry: string | null }
interface Check { status: string; category: string | null; rugged: boolean; dumped: boolean }
interface PosView { costUsd: number; peakUsd: number; openedAtMs: number; soldShare: number; ladderStep: number }
interface Exit { reason: string; share: number }
interface Pos {
costUsd: number; peakUsd: number; prevUsd: number | null; amount: string; initialAmount: string;
soldShare: number; ladderStep: number; misses: number; openedAtMs: number;
}
// A clean trnch_check verdict: seen by Trnch, no risk category, not rugged, not dumped. "unknown" and "kept_out" are not clean.
function isClean(c: Check): boolean {
return (c.status === "in_heat" || c.status === "seen") && c.category === null && !c.rugged && !c.dumped;
}
// Entry gate for a token found by address: never kept out, flagged, rugged or dumped; "unknown" only if you chose the token yourself.
function entryOk(c: Check | null, allowUnknown: boolean): boolean {
if (!c || c.status === "kept_out" || c.rugged || c.dumped || (c.category ?? null) !== null) return false;
return allowUnknown || isClean(c);
}
// /heat -> heat holds tokens already screened by Trnch ("new" is not screened and is ignored). Then your own filter.
function wanted(t: HeatToken, cfg: Cfg, openCount: number, held: ReadonlySet<string>): boolean {
if (openCount >= cfg.maxOpen || held.has(t.id)) return false;
if (t.status !== "active" || t.risk !== undefined) return false;
return t.heatScore >= cfg.minScore && t.liquidityUsd >= cfg.minLiquidityUsd;
}
// Optional total spend cap: 0 = no cap; otherwise the next buy must fit under MAX_TOTAL_USD (spent counts every buy).
function withinBudget(spentUsd: number, buyUsd: number, maxTotalUsd: number): boolean {
return maxTotalUsd <= 0 || spentUsd + buyUsd <= maxTotalUsd + 1e-9;
}
function pnlPct(entryUsd: number, nowUsd: number): number {
return (nowUsd / entryUsd - 1) * 100;
}
function exitReason(pct: number, cfg: Cfg): "take_profit" | "stop_loss" | null {
if (pct >= cfg.takeProfitPct) return "take_profit";
if (pct <= -cfg.stopLossPct) return "stop_loss";
return null;
}
// A comma list of module names, each one allowed, no duplicates; null if empty or unknown.
function parseModules(raw: string, allowed: readonly string[]): string[] | null {
const items = raw.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
if (items.length === 0 || items.some((i) => !allowed.includes(i))) return null;
return items.filter((item, index) => items.indexOf(item) === index);
}
// "50:30,100:30,200:40": gain % : share % of the buy. Gains strictly increasing, shares positive and adding up to at most 100.
function parseLadder(raw: string): Tranche[] | null {
const out: Tranche[] = [];
let total = 0;
let last = 0;
for (const part of raw.split(",")) {
const m = /^\s*(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)\s*$/.exec(part);
if (!m) return null;
const gainPct = Number(m[1]);
const sharePct = Number(m[2]);
if (gainPct <= last || sharePct <= 0 || sharePct > 100) return null;
total += sharePct;
last = gainPct;
out.push({ gainPct, sharePct });
}
return out.length > 0 && total <= 100 + 1e-9 ? out : null;
}
// /top says "x1.5": the multiple since the Heat entry.
function parseX(s: string | null): number | null {
const m = typeof s === "string" ? /^x(\d+(?:\.\d+)?)$/.exec(s) : null;
return m ? Number(m[1]) : null;
}
// trending: still up, not already too far gone, and still close to its peak (momentum, not a token already falling back).
function trendingWanted(t: TopToken, cfg: Cfg, openCount: number, held: ReadonlySet<string>): boolean {
if (openCount >= cfg.maxOpen || held.has(t.token.toLowerCase())) return false;
const latest = parseX(t.latestSinceEntry);
const peak = parseX(t.peakSinceEntry);
if (latest === null || peak === null || latest < cfg.trendMinX || latest > cfg.trendMaxX) return false;
return latest >= peak * (1 - cfg.trendMaxPullbackPct / 100) - 1e-9;
}
// dip: history = [timeMs, price index] samples taken before now; buy when the price is DIP_PCT under the high of the window,
// and only once the samples cover at least half the window.
function dipWanted(history: [number, number][], nowMs: number, price: number, cfg: Cfg): boolean {
const windowMs = cfg.dipWindowMinutes * 60000;
const recent = history.filter(([t]) => t >= nowMs - windowMs);
if (recent.length < 2 || nowMs - recent[0][0] < windowMs / 2) return false;
const high = Math.max(...recent.map(([, p]) => p));
const drop = ((high - price) / high) * 100;
return high > 0 && drop >= cfg.dipPct - 1e-9 && drop <= cfg.dipMaxPct + 1e-9;
}
// A dip is only bought when the probe amount can be sold back for a decent part of its value.
function sellRouteOk(probeUsd: number, outUsd: number | null): boolean {
return outUsd !== null && outUsd >= probeUsd * 0.7;
}
// Quotes, buys and sells made in the last 60 s count against the key's 30 per minute swap limit; this is what is left of our own budget.
function quoteRoom(calls: number[], nowMs: number, budget: number): number {
return budget - calls.filter((t) => t > nowMs - 60000).length;
}
// With neither tp_sl nor trailing in EXIT, a stop-loss is added: a position never rides on the guards alone.
function withSafetyStop(exits: string[]): string[] {
return exits.includes("tp_sl") || exits.includes("trailing") ? exits : [...exits, "stop"];
}
// The amount a buy delivered when the receipt names no single token: the balance delta, else the quoted amount only if the wallet really holds that much.
function fallbackAmount(delta: bigint | null, quoted: bigint | null, balance: bigint): bigint | null {
if (delta !== null && delta > 0n) return delta;
return quoted !== null && quoted > 0n && quoted <= balance ? quoted : null;
}
// No re-buy of a token this bot just sold, for REENTRY_HOURS.
function cooledDown(exitedAtMs: number | undefined, nowMs: number, hours: number): boolean {
return hours <= 0 || exitedAtMs === undefined || nowMs - exitedAtMs >= hours * 3600000;
}
// Exit rules in the order of EXIT; the first that fires wins. share = part of the ORIGINAL buy to sell now (1 - soldShare = all that is left).
function exitDecision(p: PosView, nowUsd: number, nowMs: number, cfg: Cfg): Exit | null {
const left = 1 - p.soldShare;
const pct = pnlPct(p.costUsd, nowUsd);
for (const rule of cfg.exits) {
if (rule === "tp_sl") {
const reason = exitReason(pct, cfg);
if (reason) return { reason, share: left };
} else if (rule === "stop") {
if (pct <= -cfg.stopLossPct) return { reason: "stop_loss", share: left };
} else if (rule === "trailing") {
if (nowUsd <= Math.max(p.peakUsd, nowUsd) * (1 - cfg.trailingStopPct / 100)) return { reason: "trailing_stop", share: left };
} else if (rule === "ladder") {
const step = cfg.ladder[p.ladderStep];
if (step && pct >= step.gainPct) {
const full = p.ladderStep === cfg.ladder.length - 1 && cfg.ladder.reduce((sum, s) => sum + s.sharePct, 0) >= 100 - 1e-9;
return { reason: "ladder_" + (p.ladderStep + 1), share: full ? left : Math.min(step.sharePct / 100, left) };
}
} else if (rule === "time") {
if (nowMs - p.openedAtMs >= cfg.maxHoldMinutes * 60000) return { reason: "max_hold", share: left };
}
}
return null;
}
function closes(share: number, soldShare: number): boolean {
return share >= 1 - soldShare - 1e-9;
}
// The exact raw amount to sell: all that is left when the position closes, else the share of the original buy (never more than is left).
function sellRaw(initial: bigint, remaining: bigint, share: number, closing: boolean): bigint {
if (closing) return remaining;
const part = (initial * BigInt(Math.round(share * 1000000))) / 1000000n;
return part > remaining ? remaining : part;
}
// GUARD 1: Trnch now keeps the token out, flags it, or it is rugged / dumped. Unknown or a failed check is not an exit.
function guardExit(c: Check | null): string | null {
if (!c) return null;
return c.status === "kept_out" || c.rugged || c.dumped || (c.category ?? null) !== null ? "guard_tia" : null;
}
// GUARD 2: the quoted value of what we hold fell dropPct since the last cycle or since entry.
function liquidityCollapsed(prevUsd: number | null, costUsd: number, nowUsd: number, dropPct: number): boolean {
const keep = 1 - dropPct / 100;
return [prevUsd, costUsd].some((ref) => ref !== null && ref > 0 && nowUsd <= ref * keep);
}
// GUARD 3: no route quoted three cycles in a row.
function noRouteExit(misses: number): boolean {
return misses >= 3;
}
// One management cycle for one position, pure: peak, previous value, no-route count, then the guards, then the EXIT rules.
function evaluate(p: Pos, nowUsd: number | null, verdict: Check | null, nowMs: number, cfg: Cfg): { p: Pos; exit: Exit | null } {
const next = { ...p };
const left = 1 - p.soldShare;
let exit: Exit | null = null;
const tia = guardExit(verdict);
if (tia) exit = { reason: tia, share: left };
if (nowUsd === null) {
next.misses = p.misses + 1;
if (!exit && noRouteExit(next.misses)) exit = { reason: "guard_no_route", share: left };
} else {
next.misses = 0;
if (!exit && liquidityCollapsed(p.prevUsd, p.costUsd, nowUsd, cfg.liquidityDropPct)) exit = { reason: "guard_liquidity", share: left };
next.peakUsd = Math.max(p.peakUsd, nowUsd);
if (!exit) exit = exitDecision(next, nowUsd, nowMs, cfg);
next.prevUsd = nowUsd;
}
return { p: next, exit };
}
// After selling raw of the position: null when it is closed, else the rest, with cost, peak and last value scaled to what is left
// (otherwise a tranche would look like a crash to the trailing stop and the liquidity guard).
function applySale(p: Pos, raw: bigint, exit: Exit): Pos | null {
const before = BigInt(p.amount);
if (closes(exit.share, p.soldShare) || raw >= before) return null;
const rest = before - raw;
const f = Number(rest) / Number(before);
return {
...p,
amount: rest.toString(),
costUsd: p.costUsd * f,
peakUsd: p.peakUsd * f,
prevUsd: p.prevUsd === null ? null : p.prevUsd * f,
soldShare: p.soldShare + exit.share,
ladderStep: p.ladderStep + (exit.reason.startsWith("ladder_") ? 1 : 0),
misses: 0,
};
}
// --- end decision logic ---
interface Position extends Pos {
decimals: number | null; openedAt: string; address: string | null; alias: string | null;
lastCheckMs: number; alertedMs: number; source: string;
}
interface State {
positions: Record<string, Position>; spentUsd: number; pendingConfirms: string[];
pendingBuys: { key: string; txHash: string; at: string }[];
exited: Record<string, number>; prices: Record<string, [number, number][]>;
}
interface Candidate { key: string; ref: { tokenId: string } | { token: string }; address: string | null; source: string; allowUnknown: boolean; fields: Record<string, unknown> }
const loaded: Partial<State> = existsSync(STATE_FILE) ? JSON.parse(readFileSync(STATE_FILE, "utf8")) : {};
const state: State = { positions: {}, spentUsd: 0, pendingConfirms: [], pendingBuys: [], exited: {}, prices: {}, ...loaded };
// A state file written by the previous version: fill the new fields.
for (const p of Object.values(state.positions) as (Position & { entryUsd?: number })[]) {
p.costUsd ??= p.entryUsd ?? 0;
p.initialAmount ??= p.amount;
p.peakUsd ??= p.costUsd;
p.soldShare ??= 0;
p.ladderStep ??= 0;
p.prevUsd ??= null;
p.misses ??= 0;
p.address ??= null;
p.alias ??= null;
p.lastCheckMs ??= 0;
p.alertedMs ??= 0;
p.source ??= "heat";
p.openedAtMs ??= Date.parse(p.openedAt);
}
// Atomic: write a temp file, then rename it over the state file (a crash never leaves half a file).
const save = () => {
writeFileSync(STATE_FILE + ".tmp", JSON.stringify(state, null, 2));
renameSync(STATE_FILE + ".tmp", STATE_FILE);
};
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function log(action: string, fields: Record<string, unknown> = {}) {
const line = JSON.stringify({ at: new Date().toISOString(), action, dryRun: CFG.dryRun, ...fields });
console.log(line);
appendFileSync(LOG_FILE, line + "\n");
}
// Quotes, buys and sells count against the key's 30 per minute swap limit: we keep our own count (quoteRoom).
const swapCalls: number[] = [];
// A rate limit pauses the main loop once; loops never sleep per token.
let pausedUntil = 0;
const paused = () => Date.now() < pausedUntil;
function pauseFrom(res: Response) {
const wait = res.status === 429 ? Number(res.headers.get("retry-after") ?? res.headers.get("ratelimit-reset") ?? 30) : Number(res.headers.get("ratelimit-remaining") ?? 99) < 3 ? Number(res.headers.get("ratelimit-reset") ?? 5) : 0;
if (wait > 0) pausedUntil = Math.max(pausedUntil, Date.now() + Math.min(wait, 120) * 1000);
}
async function api(path: string, body?: unknown) {
if (["/quote", "/buy", "/sell", "/build"].includes(path)) {
swapCalls.push(Date.now());
if (swapCalls.length > 200) swapCalls.splice(0, swapCalls.length - 100);
}
const res = await fetch(API + path, {
method: body ? "POST" : "GET",
headers: { Authorization: "Bearer " + process.env.TRNCH_API_KEY, "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
// RateLimit-Remaining / RateLimit-Reset on every authenticated response: pause before the 429 (the loops check paused()).
pauseFrom(res);
const json = await res.json();
if (!res.ok) throw Object.assign(new Error(path + " " + res.status + " " + JSON.stringify(json)), { status: res.status });
return json;
}
const notTradable = (e: unknown) => (e as { status?: number }).status === 409;
const rateLimited = (e: unknown) => (e as { status?: number }).status === 429;
// /check and /top need no key (limits per IP).
async function pub(path: string) {
const res = await fetch(API + path);
if (res.status === 429) pauseFrom(res);
if (!res.ok) throw Object.assign(new Error(path + " " + res.status), { status: res.status });
return res.json();
}
async function checkToken(address: string): Promise<Check | null> {
try {
return (await pub("/check?token=" + address)) as Check;
} catch (e) {
log("check_failed", { token: address, message: (e as Error).message });
return null;
}
}
// Signing only in live mode, on this machine.
const chain = defineChain({
id: 4663,
name: "Robinhood Chain",
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.mainnet.chain.robinhood.com"] } },
});
const account = CFG.dryRun ? null : privateKeyToAccount(process.env.BOT_PRIVATE_KEY as Hex);
const rpc = createPublicClient({ chain, transport: http() });
const wallet = account ? createWalletClient({ account, chain, transport: http() }) : null;
const TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
const decimalsCache = new Map<string, number>();
// Only a value really read from the token is kept: on an RPC failure this throws (the caller refuses or retries), never assumes 18.
async function decimalsOf(address: string): Promise<number> {
const known = decimalsCache.get(address);
if (known !== undefined) return known;
const d = Number(await rpc.readContract({ address: address as Hex, abi: parseAbi(["function decimals() view returns (uint8)"]), functionName: "decimals" }));
if (!Number.isInteger(d) || d < 0 || d > 36) throw new Error("unreadable decimals for " + address);
decimalsCache.set(address, d);
return d;
}
async function balanceOf(token: string, owner: string): Promise<bigint> {
return (await rpc.readContract({ address: token as Hex, abi: parseAbi(["function balanceOf(address) view returns (uint256)"]), functionName: "balanceOf", args: [owner as Hex] })) as bigint;
}
// A reverted transaction is an error: nothing is confirmed or recorded for it.
async function send(tx: { to: string; data: string; value?: string; gas?: string | null }) {
if (!wallet) throw new Error("dry run");
const hash = await wallet.sendTransaction({ to: tx.to as Hex, data: tx.data as Hex, value: BigInt(tx.value ?? "0"), gas: tx.gas ? BigInt(tx.gas) : undefined });
const receipt = await rpc.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("transaction reverted: " + hash);
return { hash, receipt };
}
// The token the wallet received in this transaction (everything but USDG): { token, amount } or null if not exactly one token.
function received(receipt: TransactionReceipt): { token: string; amount: bigint } | null {
const mine = (account?.address ?? "").toLowerCase().slice(2);
const sums = new Map<string, bigint>();
for (const l of receipt.logs) {
if (l.topics[0] !== TRANSFER || l.topics.length !== 3 || !l.topics[2] || l.topics[2].toLowerCase().slice(-40) !== mine) continue;
if (l.address.toLowerCase() === USDG.toLowerCase()) continue;
sums.set(l.address, (sums.get(l.address) ?? 0n) + BigInt(l.data));
}
if (sums.size !== 1) return null;
const [token, amount] = [...sums.entries()][0];
return { token, amount };
}
// /confirm only credits volume: best effort. A failure is queued and retried, never lost and never blocks the position.
async function confirm(hash: string) {
try {
await api("/confirm", { txHash: hash });
} catch (e) {
state.pendingConfirms.push(hash);
save();
log("confirm_failed", { txHash: hash, message: (e as Error).message });
}
}
async function retryConfirms() {
for (const hash of state.pendingConfirms.splice(0)) await confirm(hash);
}
// /buy and /sell return { router, quote, approval, tx, from }: approval first, then tx; both must succeed on chain.
async function execute(r: { from: string; approval: { to: string; data: string } | null; tx: { to: string; data: string; value: string; gas?: string | null } }) {
if (!account || r.from.toLowerCase() !== account.address.toLowerCase()) throw new Error("API key wallet is not the signer");
if (r.approval) await send(r.approval);
const done = await send(r.tx);
await confirm(done.hash);
return done;
}
function heldSet(): Set<string> {
const held = new Set<string>();
for (const [key, p] of Object.entries(state.positions)) {
held.add(key);
if (p.address) held.add(p.address);
if (p.alias) held.add(p.alias);
}
return held;
}
// A position is keyed by the token address as soon as it is known (a Heat id is kept as its alias), so trending and dip see it as held.
function openPosition(c: Candidate, costUsd: number, amount: string, decimals: number | null, address: string | null): string {
const addr = address ? address.toLowerCase() : null;
const key = addr ?? c.key;
state.positions[key] = {
costUsd, amount, initialAmount: amount, decimals, openedAt: new Date().toISOString(), openedAtMs: Date.now(),
peakUsd: costUsd, soldShare: 0, ladderStep: 0, prevUsd: null, misses: 0,
address: addr, alias: key !== c.key ? c.key : null, lastCheckMs: 0, alertedMs: 0, source: c.source,
};
return key;
}
async function enter(c: Candidate) {
try {
// The token's decimals first, read from the token itself: no read, no buy.
const known = c.address ? await decimalsOf(c.address) : null;
if (CFG.dryRun) {
// /quote builds nothing and signs nothing: the dry run never touches the build limit. A Heat id has no address: 18 is assumed (simulated).
const q = await api("/quote", { tokenIn: USDG, tokenOut: c.key, amountIn: String(Math.round(CFG.buyUsd * 1e6)), decimalsIn: 6, decimalsOut: known ?? 18, slippage: CFG.slippageBps / 10000 });
if (!q.best || !q.best.amountOut) return log("skip", { id: c.key, reason: "no route or no amount" });
openPosition(c, q.best.inUsd ?? CFG.buyUsd, String(q.best.amountOut), known ?? 18, c.address);
state.spentUsd += CFG.buyUsd;
log("buy", { id: c.key, source: c.source, usd: CFG.buyUsd, ...c.fields, router: q.best.router, simulated: true });
save();
return;
}
const before = c.address && account ? await balanceOf(c.address, account.address) : null;
const r = await api("/buy", { ...c.ref, amountUsd: CFG.buyUsd, slippageBps: CFG.slippageBps });
const done = await execute(r);
// The money is spent once the transaction is mined: saved right away, before anything else can fail.
state.spentUsd += CFG.buyUsd;
state.pendingBuys.push({ key: c.key, txHash: done.hash, at: new Date().toISOString() });
save();
try {
const got = received(done.receipt);
let amount: bigint | null = got ? got.amount : null;
const address = got ? got.token : c.address;
if (amount === null && address && account) {
const balance = await balanceOf(address, account.address);
amount = fallbackAmount(before === null ? null : balance - before, r.quote.amountOut ? BigInt(r.quote.amountOut) : null, balance);
}
if (amount === null || !address) {
return log("error", { id: c.key, txHash: done.hash, message: "bought, but the received amount is unknown: position NOT tracked, check the wallet" });
}
let decimals: number | null = null;
try {
decimals = await decimalsOf(address.toLowerCase());
} catch (e) {
log("error", { id: c.key, txHash: done.hash, message: "decimals unreadable, the position is tracked and retried each cycle: " + (e as Error).message });
}
openPosition(c, r.quote.inUsd ?? CFG.buyUsd, amount.toString(), decimals, address);
state.pendingBuys = state.pendingBuys.filter((b) => b.txHash !== done.hash);
log("buy", { id: c.key, source: c.source, usd: CFG.buyUsd, ...c.fields, router: r.router, txHash: done.hash });
save();
} catch (e) {
log("error", { id: c.key, txHash: done.hash, message: "bought, but the position could not be recorded: check the wallet. " + (e as Error).message });
}
} catch (e) {
// 409 = Trnch does not trade this token: skipped, not an error. A reverted buy lands here too: nothing is recorded.
log("skip", { id: c.key, reason: (e as Error).message });
}
}
// One candidate through the shared gates. Returns false when the optional spend cap stops all buying.
async function consider(c: Candidate): Promise<boolean> {
const now = Date.now();
const held = heldSet();
if (Object.keys(state.positions).length >= CFG.maxOpen || held.has(c.key) || (c.address !== null && held.has(c.address))) return true;
if (!cooledDown(state.exited[c.key], now, CFG.reentryHours) || (c.address !== null && !cooledDown(state.exited[c.address], now, CFG.reentryHours))) return true;
if (!withinBudget(state.spentUsd, CFG.buyUsd, CFG.maxTotalUsd)) {
log("cap_reached", { spentUsd: state.spentUsd, maxTotalUsd: CFG.maxTotalUsd });
return false;
}
if (quoteRoom(swapCalls, now, CFG.quoteBudget) < 2) {
log("skip", { id: c.key, reason: "quote budget: positions come first" });
return true;
}
if (c.address) {
const verdict = await checkToken(c.address);
if (!entryOk(verdict, c.allowUnknown)) {
log("skip", { id: c.key, reason: "check: " + (verdict ? verdict.status + " " + (verdict.category ?? "") : "unavailable") });
return true;
}
}
await enter(c);
return true;
}
// Trnch no longer quotes or sells this token (409: Trnch keeps it out). The position stays in the state file; logged loudly, every 5 minutes.
function alertNotTradable(key: string, p: Position, verdict: Check | null) {
const now = Date.now();
if (now - p.alertedMs < 300000) return;
p.alertedMs = now;
log("alert_not_tradable", {
id: key, token: p.address, amount: p.decimals === null ? p.amount + " (raw)" : formatUnits(BigInt(p.amount), p.decimals), verdict: verdict?.status ?? null,
message: "Trnch will not quote or sell this token any more (kept out). Position kept, nothing was sold. Sell elsewhere with your own wallet.",
});
save();
}
async function managePositions() {
await retryConfirms();
for (const [key, p] of Object.entries(state.positions)) {
if (paused()) return;
try {
const now = Date.now();
// GUARD first: the Trnch verdict by address (every minute) is read and logged before any quote, so a token Trnch refuses to quote still has its verdict on record.
let verdict: Check | null = null;
if (p.address && now - p.lastCheckMs >= 60000) {
p.lastCheckMs = now;
verdict = await checkToken(p.address);
if (verdict) log("guard_check", { id: key, token: p.address, status: verdict.status, category: verdict.category });
}
if (p.decimals === null) {
try {
p.decimals = p.address ? await decimalsOf(p.address) : null;
} catch (e) {
log("error", { id: key, message: "decimals still unreadable, position not valued this cycle: " + (e as Error).message });
}
if (p.decimals === null) continue;
}
const decimals = p.decimals;
let nowUsd: number | null = null;
try {
// Value = what the amount this bot still holds would sell for now.
const q = await api("/quote", { tokenIn: key, tokenOut: USDG, amountIn: p.amount, decimalsIn: decimals, decimalsOut: 6, slippage: CFG.slippageBps / 10000 });
nowUsd = q.best?.outUsd ?? null;
} catch (e) {
if (!notTradable(e)) throw e;
alertNotTradable(key, p, verdict);
continue;
}
const ev = evaluate(p, nowUsd, verdict, now, CFG);
Object.assign(p, ev.p);
const pct = nowUsd === null ? null : Math.round(pnlPct(p.costUsd, nowUsd) * 10) / 10;
log("hold", { id: key, entryUsd: p.costUsd, nowUsd, pnlPct: pct, misses: p.misses });
const d = ev.exit;
if (!d) {
save();
continue;
}
const raw = sellRaw(BigInt(p.initialAmount), BigInt(p.amount), d.share, closes(d.share, p.soldShare));
if (raw <= 0n) {
save();
continue;
}
if (CFG.dryRun) {
log("sell", { id: key, reason: d.reason, share: d.share, pnlPct: pct, simulated: true });
} else {
try {
// Exactly what was bought (or a share of it), never a percent of the whole wallet balance. A reverted sell throws: the position stays, retried next cycle.
const r = await api("/sell", { ...(key.startsWith("0x") ? { token: key } : { tokenId: key }), amount: formatUnits(raw, decimals), slippageBps: CFG.slippageBps });
const done = await execute(r);
log("sell", { id: key, reason: d.reason, share: d.share, pnlPct: pct, txHash: done.hash });
} catch (e) {
if (!notTradable(e)) throw e;
alertNotTradable(key, p, verdict);
continue;
}
}
const rest = applySale(p, raw, d);
if (rest) {
Object.assign(p, rest);
} else {
for (const id of [key, p.address, p.alias]) if (id) state.exited[id] = now;
delete state.positions[key];
}
save();
} catch (e) {
log("error", { id: key, message: (e as Error).message });
}
}
}
async function watchlist() {
for (const token of WATCH) {
const c = (await pub("/check?token=" + token)) as Check;
log("check", { token, status: c.status, category: c.category, clean: isClean(c) });
}
}
// ENTRY=trending: the best tokens of the last 24 hours from GET /top, still near their peak.
let top: TopToken[] = [];
async function trendingScan() {
top = (await pub("/top?limit=" + CFG.trendLimit)).tokens as TopToken[];
if (!CFG.entries.includes("trending")) return;
for (const t of top) {
if (paused()) return;
if (!trendingWanted(t, CFG, Object.keys(state.positions).length, heldSet())) continue;
const address = t.token.toLowerCase();
if (!(await consider({ key: address, ref: { token: address }, address, source: "trending", allowUnknown: false, fields: { latest: t.latestSinceEntry, peak: t.peakSinceEntry } }))) return;
}
}
// ENTRY=dip: sample the price of each watched token (a /quote of a probe amount, nothing is bought), buy a drop from the window high.
async function dipScan() {
const universe = (DIP_TOKENS.length > 0 ? DIP_TOKENS : top.map((t) => t.token.toLowerCase())).slice(0, CFG.dipMaxTokens);
// Histories of tokens that are no longer sampled are dropped.
for (const address of Object.keys(state.prices)) if (!universe.includes(address)) delete state.prices[address];
const windowMs = CFG.dipWindowMinutes * 60000;
for (const address of universe) {
if (paused()) break;
// Positions come first (about 4 quotes a minute each); a sample costs 1, the sell-route check 1 more.
if (quoteRoom(swapCalls, Date.now(), CFG.quoteBudget) < 2 + 4 * Object.keys(state.positions).length) {
log("skip", { id: address, reason: "quote budget: dip sampling skipped this scan" });
break;
}
if (heldSet().has(address)) continue;
try {
const now = Date.now();
const decimals = await decimalsOf(address);
const q = await api("/quote", { tokenIn: USDG, tokenOut: address, amountIn: String(Math.round(CFG.dipProbeUsd * 1e6)), decimalsIn: 6, decimalsOut: decimals, slippage: CFG.slippageBps / 10000 });
const out = Number(q.best?.amountOut ?? 0);
if (!(out > 0)) continue;
const price = CFG.dipProbeUsd / out;
const history = (state.prices[address] ?? []).filter(([t]) => t >= now - windowMs);
const dip = dipWanted(history, now, price, CFG);
state.prices[address] = [...history, [now, price]];
if (!dip) continue;
// A quotable SELL route is required before buying: the probe amount must sell back for most of its value.
const back = await api("/quote", { tokenIn: address, tokenOut: USDG, amountIn: String(q.best.amountOut), decimalsIn: decimals, decimalsOut: 6, slippage: CFG.slippageBps / 10000 });
if (!sellRouteOk(CFG.dipProbeUsd, back.best?.outUsd ?? null)) {
log("skip", { id: address, reason: "dip, but no sell route for the probe amount" });
continue;
}
const high = Math.max(...history.map(([, p]) => p));
const go = await consider({ key: address, ref: { token: address }, address, source: "dip", allowUnknown: DIP_TOKENS.length > 0, fields: { dropPct: Math.round(((high - price) / high) * 1000) / 10 } });
// The history is cleared only once the token is really held; a skipped buy keeps it.
if (heldSet().has(address)) delete state.prices[address];
if (!go) break;
} catch (e) {
log("skip", { id: address, reason: (e as Error).message });
if (rateLimited(e)) break;
}
}
save();
}
async function main() {
log("start", { entry: CFG.entries, exit: CFG.exits, buyUsd: CFG.buyUsd, maxTotalUsd: CFG.maxTotalUsd, spentUsd: state.spentUsd, maxOpen: CFG.maxOpen, quoteBudget: CFG.quoteBudget });
for (const b of state.pendingBuys) log("error", { id: b.key, txHash: b.txHash, at: b.at, message: "bought earlier but never tracked: check the wallet" });
let since = Date.now();
let lastManaged = 0;
let lastTop = 0;
let lastDip = 0;
const seen = new Set<string>();
await watchlist().catch((e) => log("error", { message: (e as Error).message }));
for (;;) {
try {
// A rate limit is honoured once, here (Retry-After), never inside the loops.
if (paused()) await sleep(pausedUntil - Date.now());
// Open positions come first, then entries and dip sampling with what is left of the quote budget.
if (Date.now() - lastManaged >= 15000) {
lastManaged = Date.now();
await managePositions();
}
if (CFG.entries.includes("heat") && !paused()) {
const feed = await api("/heat?since=" + since);
since = feed.nextSince;
for (const t of feed.heat as HeatToken[]) {
if (seen.has(t.id)) continue;
seen.add(t.id);
if (paused()) break;
if (!wanted(t, CFG, Object.keys(state.positions).length, heldSet())) continue;
if (!(await consider({ key: t.id, ref: { tokenId: t.id }, address: null, source: "heat", allowUnknown: false, fields: { heatScore: t.heatScore } }))) break;
}
}
if ((CFG.entries.includes("trending") || CFG.entries.includes("dip")) && !paused() && Date.now() - lastTop >= CFG.topPollSeconds * 1000) {
lastTop = Date.now();
await trendingScan().catch((e) => log("error", { message: (e as Error).message }));
}
if (CFG.entries.includes("dip") && !paused() && Date.now() - lastDip >= CFG.dipSampleSeconds * 1000) {
lastDip = Date.now();
await dipScan();
}
} catch (e) {
log("error", { message: (e as Error).message });
}
await sleep(CFG.pollSeconds * 1000);
}
}
main().catch((e) => {
console.error((e as Error).message);
process.exit(1);
});
Python (web3.py)
# Trnch agent strategy pack (example). Python 3.10+ : pip install web3 requests && python agent.py
# DRY RUN BY DEFAULT: it logs what it would do and signs nothing. Set DRY_RUN=0 to trade for real.
# Env: TRNCH_API_KEY (required) | BOT_PRIVATE_KEY (only for DRY_RUN=0, a DEDICATED wallet; signs here, never sent)
# Pick modules (comma lists, defaults = the classic Heat strategy):
# ENTRY=heat | trending | dip e.g. ENTRY=heat,trending
# EXIT=tp_sl | trailing | ladder | time e.g. EXIT=tp_sl,time (first rule that fires wins)
# Common: BUY_USD=5 MAX_TOTAL_USD=0 (optional total spend cap, 0 = no cap) MAX_OPEN=3 SLIPPAGE_BPS=150 POLL_SECONDS=5
# REENTRY_HOURS=6 (no re-buy of a token just sold, 0 = off)
# heat: MIN_SCORE=70 MIN_LIQUIDITY_USD=20000
# trending: TREND_MIN_X=1.1 TREND_MAX_X=5 TREND_MAX_PULLBACK_PCT=25 TREND_LIMIT=10 TOP_POLL_SECONDS=300 (source: GET /top)
# dip: DIP_TOKENS=0xabc...,0xdef... (your list; empty = the /top list) DIP_PCT=10 DIP_WINDOW_MINUTES=60
# DIP_SAMPLE_SECONDS=60 DIP_PROBE_USD=10 DIP_MAX_TOKENS=10 (price = /quote of a probe amount, nothing is bought to sample)
# DIP_MAX_PCT=40 (a drop deeper than this is skipped: likely a rug, not a dip); a quotable SELL route is required before a buy
# tp_sl: TAKE_PROFIT_PCT=50 STOP_LOSS_PCT=25
# trailing: TRAILING_STOP_PCT=15 (sell when the value falls this much from its peak since entry)
# ladder: LADDER=50:30,100:30,200:40 (gain %:share of the buy sold at that gain; shares add up to at most 100)
# time: MAX_HOLD_MINUTES=240
# Safety stop: if EXIT has neither tp_sl nor trailing (ladder and/or time alone), a STOP_LOSS_PCT stop (25) is added, so a
# position never rides on the guards alone. A ladder whose shares add up to less than 100 leaves the rest on that
# stop, on time (if listed) and on the guards.
# guard (always on): every held token is re-checked by address with /check and sold if Trnch now keeps it out, flags it
# or it is rugged/dumped; sold if the /quote value falls GUARD_LIQUIDITY_DROP_PCT=60 in one cycle or from entry,
# or if no route can be quoted 3 times in a row.
# Quote budget: /quote, /buy and /sell share the 30 per minute limit of your key. The script keeps its own count of the last 60 s
# and stays under QUOTE_BUDGET_PER_MIN=25; open positions come first, dip sampling and new entries use what is left.
# On a 429 it waits for Retry-After once (never per token) and skips the rest of that scan.
# New in this version: the always-on guard and REENTRY_HOURS. A token Trnch refuses to quote or sell (409, Trnch keeps it out) keeps
# its position and logs alert_not_tradable: sell it elsewhere with your own wallet.
# WATCH_TOKENS=0xabc...,0xdef... (optional, logged with /check at start)
# A setting that is not valid stops the program with an error. Dry run and live keep separate state files.
# Every action is logged. An example of an automated rule set, not a recommendation: prices can fall to zero.
import json, math, os, re, sys, time
from datetime import datetime, timezone
import requests
from web3 import Web3
API = "https://trnch.fun/api/bot/v1"
USDG = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"
CHAIN_ID = 4663 # Robinhood Chain
RPC_URL = "https://rpc.mainnet.chain.robinhood.com"
def env_num(key, default, lo, hi=math.inf):
raw = os.environ.get(key)
if raw is None or raw == "":
return default
try:
value = float(raw)
except ValueError:
value = math.nan
if not math.isfinite(value) or value < lo or value > hi:
sys.exit(f"Invalid {key}={raw}: expected a number from {lo} to {hi}")
return value
# --- decision logic (pure, no network) ---
def is_clean(c):
"""A clean trnch_check verdict: seen by Trnch, no risk category, not rugged, not dumped. 'unknown' and 'kept_out' are not clean."""
return c["status"] in ("in_heat", "seen") and c["category"] is None and not c["rugged"] and not c["dumped"]
def entry_ok(c, allow_unknown):
"""Entry gate for a token found by address: never kept out, flagged, rugged or dumped; 'unknown' only if you chose the token yourself."""
if not c or c["status"] == "kept_out" or c["rugged"] or c["dumped"] or c.get("category") is not None:
return False
return allow_unknown or is_clean(c)
def wanted(t, cfg, open_count, held):
"""/heat -> 'heat' holds tokens already screened by Trnch ('new' is not screened and is ignored). Then your own filter."""
if open_count >= cfg["max_open"] or t["id"] in held:
return False
if t["status"] != "active" or "risk" in t:
return False
return t["heatScore"] >= cfg["min_score"] and t["liquidityUsd"] >= cfg["min_liquidity_usd"]
def within_budget(spent_usd, buy_usd, max_total_usd):
"""Optional total spend cap: 0 = no cap; otherwise the next buy must fit under MAX_TOTAL_USD."""
return max_total_usd <= 0 or spent_usd + buy_usd <= max_total_usd + 1e-9
def pnl_pct(entry_usd, now_usd):
return (now_usd / entry_usd - 1) * 100
def exit_reason(pct, cfg):
if pct >= cfg["take_profit_pct"]:
return "take_profit"
if pct <= -cfg["stop_loss_pct"]:
return "stop_loss"
return None
def parse_modules(raw, allowed):
"""A comma list of module names, each one allowed, no duplicates; None if empty or unknown."""
items = [s.strip().lower() for s in raw.split(",") if s.strip()]
if not items or any(i not in allowed for i in items):
return None
return [item for index, item in enumerate(items) if items.index(item) == index]
def parse_ladder(raw):
"""'50:30,100:30,200:40': gain % : share % of the buy. Gains strictly increasing, shares positive and adding up to at most 100."""
out, total, last = [], 0.0, 0.0
for part in raw.split(","):
m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)\s*", part)
if not m:
return None
gain, share = float(m.group(1)), float(m.group(2))
if gain <= last or share <= 0 or share > 100:
return None
total += share
last = gain
out.append({"gain_pct": gain, "share_pct": share})
return out if out and total <= 100 + 1e-9 else None
def parse_x(s):
"""/top says 'x1.5': the multiple since the Heat entry."""
m = re.fullmatch(r"x(\d+(?:\.\d+)?)", s) if isinstance(s, str) else None
return float(m.group(1)) if m else None
def trending_wanted(t, cfg, open_count, held):
"""trending: still up, not already too far gone, and still close to its peak (momentum, not a token already falling back)."""
if open_count >= cfg["max_open"] or t["token"].lower() in held:
return False
latest, peak = parse_x(t.get("latestSinceEntry")), parse_x(t.get("peakSinceEntry"))
if latest is None or peak is None or latest < cfg["trend_min_x"] or latest > cfg["trend_max_x"]:
return False
return latest >= peak * (1 - cfg["trend_max_pullback_pct"] / 100) - 1e-9
def dip_wanted(history, now_ms, price, cfg):
"""dip: history = [time_ms, price index] samples taken before now; buy when the price is DIP_PCT under the high of the window,
and only once the samples cover at least half the window."""
window_ms = cfg["dip_window_minutes"] * 60000
recent = [h for h in history if h[0] >= now_ms - window_ms]
if len(recent) < 2 or now_ms - recent[0][0] < window_ms / 2:
return False
high = max(h[1] for h in recent)
drop = (high - price) / high * 100 if high > 0 else 0
return high > 0 and cfg["dip_pct"] - 1e-9 <= drop <= cfg["dip_max_pct"] + 1e-9
def sell_route_ok(probe_usd, out_usd):
"""A dip is only bought when the probe amount can be sold back for a decent part of its value."""
return out_usd is not None and out_usd >= probe_usd * 0.7
def quote_room(calls, now_ms, budget):
"""Quotes, buys and sells made in the last 60 s count against the key's 30 per minute swap limit; this is what is left of our own budget."""
return budget - len([t for t in calls if t > now_ms - 60000])
def with_safety_stop(exits):
"""With neither tp_sl nor trailing in EXIT, a stop-loss is added: a position never rides on the guards alone."""
return exits if "tp_sl" in exits or "trailing" in exits else exits + ["stop"]
def fallback_amount(delta, quoted, balance):
"""The amount a buy delivered when the receipt names no single token: the balance delta, else the quoted amount only if the wallet really holds that much."""
if delta is not None and delta > 0:
return delta
return quoted if quoted is not None and 0 < quoted <= balance else None
def cooled_down(exited_at_ms, now_ms, hours):
"""No re-buy of a token this bot just sold, for REENTRY_HOURS."""
return hours <= 0 or exited_at_ms is None or now_ms - exited_at_ms >= hours * 3600000
def exit_decision(p, now_usd, now_ms, cfg):
"""Exit rules in the order of EXIT; the first that fires wins. share = part of the ORIGINAL buy to sell now (1 - soldShare = all that is left)."""
left = 1 - p["soldShare"]
pct = pnl_pct(p["costUsd"], now_usd)
for rule in cfg["exits"]:
if rule == "tp_sl":
reason = exit_reason(pct, cfg)
if reason:
return {"reason": reason, "share": left}
elif rule == "stop":
if pct <= -cfg["stop_loss_pct"]:
return {"reason": "stop_loss", "share": left}
elif rule == "trailing":
if now_usd <= max(p["peakUsd"], now_usd) * (1 - cfg["trailing_stop_pct"] / 100):
return {"reason": "trailing_stop", "share": left}
elif rule == "ladder":
step = cfg["ladder"][p["ladderStep"]] if p["ladderStep"] < len(cfg["ladder"]) else None
if step and pct >= step["gain_pct"]:
full = p["ladderStep"] == len(cfg["ladder"]) - 1 and sum(s["share_pct"] for s in cfg["ladder"]) >= 100 - 1e-9
return {"reason": f"ladder_{p['ladderStep'] + 1}", "share": left if full else min(step["share_pct"] / 100, left)}
elif rule == "time":
if now_ms - p["openedAtMs"] >= cfg["max_hold_minutes"] * 60000:
return {"reason": "max_hold", "share": left}
return None
def closes(share, sold_share):
return share >= 1 - sold_share - 1e-9
def sell_raw(initial, remaining, share, closing):
"""The exact raw amount to sell: all that is left when the position closes, else the share of the original buy (never more than is left)."""
if closing:
return remaining
return min(remaining, initial * round(share * 1000000) // 1000000)
def guard_exit(c):
"""GUARD 1: Trnch now keeps the token out, flags it, or it is rugged / dumped. Unknown or a failed check is not an exit."""
if not c:
return None
return "guard_tia" if c["status"] == "kept_out" or c["rugged"] or c["dumped"] or c.get("category") is not None else None
def liquidity_collapsed(prev_usd, cost_usd, now_usd, drop_pct):
"""GUARD 2: the quoted value of what we hold fell drop_pct since the last cycle or since entry."""
keep = 1 - drop_pct / 100
return any(ref is not None and ref > 0 and now_usd <= ref * keep for ref in (prev_usd, cost_usd))
def no_route_exit(misses):
"""GUARD 3: no route quoted three cycles in a row."""
return misses >= 3
def evaluate(p, now_usd, verdict, now_ms, cfg):
"""One management cycle for one position, pure: peak, previous value, no-route count, then the guards, then the EXIT rules."""
nxt = dict(p)
left = 1 - p["soldShare"]
exit_ = None
tia = guard_exit(verdict)
if tia:
exit_ = {"reason": tia, "share": left}
if now_usd is None:
nxt["misses"] = p["misses"] + 1
if not exit_ and no_route_exit(nxt["misses"]):
exit_ = {"reason": "guard_no_route", "share": left}
else:
nxt["misses"] = 0
if not exit_ and liquidity_collapsed(p["prevUsd"], p["costUsd"], now_usd, cfg["liquidity_drop_pct"]):
exit_ = {"reason": "guard_liquidity", "share": left}
nxt["peakUsd"] = max(p["peakUsd"], now_usd)
if not exit_:
exit_ = exit_decision(nxt, now_usd, now_ms, cfg)
nxt["prevUsd"] = now_usd
return nxt, exit_
def apply_sale(p, raw, exit_):
"""After selling raw of the position: None when it is closed, else the rest, with cost, peak and last value scaled to what is left
(otherwise a tranche would look like a crash to the trailing stop and the liquidity guard)."""
before = int(p["amount"])
if closes(exit_["share"], p["soldShare"]) or raw >= before:
return None
rest = before - raw
f = rest / before
return {**p, "amount": str(rest), "costUsd": p["costUsd"] * f, "peakUsd": p["peakUsd"] * f,
"prevUsd": None if p["prevUsd"] is None else p["prevUsd"] * f,
"soldShare": p["soldShare"] + exit_["share"], "ladderStep": p["ladderStep"] + (1 if exit_["reason"].startswith("ladder_") else 0), "misses": 0}
# --- end decision logic ---
def env_modules(key, default, allowed):
raw = os.environ.get(key) or default
items = parse_modules(raw, allowed)
if items is None:
sys.exit(f"Invalid {key}={raw}: expected a comma list of {', '.join(allowed)}")
return items
def env_addresses(key):
items = [a.strip().lower() for a in os.environ.get(key, "").split(",") if a.strip()]
for a in items:
if not re.fullmatch(r"0x[0-9a-f]{40}", a):
sys.exit(f"Invalid {key}: {a} is not a 0x address")
return items
LADDER_RAW = os.environ.get("LADDER") or "50:30,100:30,200:40"
LADDER = parse_ladder(LADDER_RAW)
if LADDER is None:
sys.exit(f"Invalid LADDER={LADDER_RAW}: expected gain:share pairs like 50:30,100:30,200:40 (gains increasing, shares adding up to at most 100)")
DIP_TOKENS = env_addresses("DIP_TOKENS")
DRY_RUN = os.environ.get("DRY_RUN") != "0"
CFG = {
"entries": env_modules("ENTRY", "heat", ["heat", "trending", "dip"]),
"exits": with_safety_stop(env_modules("EXIT", "tp_sl", ["tp_sl", "trailing", "ladder", "time"])),
"buy_usd": env_num("BUY_USD", 5, 0.01),
"max_total_usd": env_num("MAX_TOTAL_USD", 0, 0),
"min_score": env_num("MIN_SCORE", 70, 0, 100),
"min_liquidity_usd": env_num("MIN_LIQUIDITY_USD", 20000, 0),
"take_profit_pct": env_num("TAKE_PROFIT_PCT", 50, 0.1),
"stop_loss_pct": env_num("STOP_LOSS_PCT", 25, 0.1, 99.9),
"trailing_stop_pct": env_num("TRAILING_STOP_PCT", 15, 0.1, 99.9),
"ladder": LADDER,
"max_hold_minutes": env_num("MAX_HOLD_MINUTES", 240, 1),
"trend_min_x": env_num("TREND_MIN_X", 1.1, 0.01),
"trend_max_x": env_num("TREND_MAX_X", 5, 0.01),
"trend_max_pullback_pct": env_num("TREND_MAX_PULLBACK_PCT", 25, 0, 99.9),
"trend_limit": int(env_num("TREND_LIMIT", 10, 1, 20)),
"top_poll_seconds": max(60, env_num("TOP_POLL_SECONDS", 300, 1)),
"dip_pct": env_num("DIP_PCT", 10, 0.1, 99.9),
"dip_max_pct": env_num("DIP_MAX_PCT", 40, 1, 99.9),
"dip_window_minutes": env_num("DIP_WINDOW_MINUTES", 60, 2),
"dip_sample_seconds": max(30, env_num("DIP_SAMPLE_SECONDS", 60, 1)),
"dip_probe_usd": env_num("DIP_PROBE_USD", 10, 0.5),
"dip_max_tokens": int(env_num("DIP_MAX_TOKENS", 10, 1, 20)),
"liquidity_drop_pct": env_num("GUARD_LIQUIDITY_DROP_PCT", 60, 1, 99.9),
"quote_budget": int(env_num("QUOTE_BUDGET_PER_MIN", 25, 5, 30)),
"reentry_hours": env_num("REENTRY_HOURS", 6, 0),
"max_open": int(env_num("MAX_OPEN", 3, 1, 50)),
"slippage_bps": int(env_num("SLIPPAGE_BPS", 150, 10, 5000)),
"poll_seconds": max(3, env_num("POLL_SECONDS", 5, 1)),
}
if CFG["dip_max_pct"] < CFG["dip_pct"]:
sys.exit(f"Invalid DIP_MAX_PCT={CFG['dip_max_pct']}: it must be at least DIP_PCT={CFG['dip_pct']}")
if not os.environ.get("TRNCH_API_KEY") or (not DRY_RUN and not os.environ.get("BOT_PRIVATE_KEY")):
sys.exit("TRNCH_API_KEY is required, and BOT_PRIVATE_KEY too when DRY_RUN=0")
WATCH = [a.strip() for a in os.environ.get("WATCH_TOKENS", "").split(",") if a.strip()]
STATE_FILE = os.environ.get("STATE_FILE", "trnch-state-dry.json" if DRY_RUN else "trnch-state-live.json")
LOG_FILE = os.environ.get("LOG_FILE", "trnch-actions.jsonl")
state = {"positions": {}, "spentUsd": 0, "pendingConfirms": [], "pendingBuys": [], "exited": {}, "prices": {}}
if os.path.exists(STATE_FILE):
state.update(json.load(open(STATE_FILE)))
# A state file written by the previous version: fill the new fields.
for _p in state["positions"].values():
_p.setdefault("costUsd", _p.get("entryUsd", 0))
_p.setdefault("initialAmount", _p["amount"])
_p.setdefault("peakUsd", _p["costUsd"])
_p.setdefault("soldShare", 0)
_p.setdefault("ladderStep", 0)
_p.setdefault("prevUsd", None)
_p.setdefault("misses", 0)
_p.setdefault("address", None)
_p.setdefault("alias", None)
_p.setdefault("lastCheckMs", 0)
_p.setdefault("alertedMs", 0)
_p.setdefault("source", "heat")
_p.setdefault("openedAtMs", int(datetime.fromisoformat(_p["openedAt"]).timestamp() * 1000))
def save():
"""Atomic: write a temp file, then rename it over the state file (a crash never leaves half a file)."""
with open(STATE_FILE + ".tmp", "w") as f:
json.dump(state, f, indent=2)
os.replace(STATE_FILE + ".tmp", STATE_FILE)
def log(action, **fields):
line = json.dumps({"at": datetime.now(timezone.utc).isoformat(), "action": action, "dryRun": DRY_RUN, **fields})
print(line, flush=True)
with open(LOG_FILE, "a") as f:
f.write(line + "\n")
def now_ms():
return int(time.time() * 1000)
headers = {"Authorization": "Bearer " + os.environ["TRNCH_API_KEY"]}
swap_calls = [] # quotes, buys and sells count against the key's 30 per minute swap limit: we keep our own count (quote_room)
paused_until = 0.0 # a rate limit pauses the main loop once; loops never sleep per token
def paused():
return time.time() < paused_until
def pause_from(res):
global paused_until
if res.status_code == 429:
wait = float(res.headers.get("retry-after") or res.headers.get("ratelimit-reset") or 30)
elif int(res.headers.get("ratelimit-remaining", 99)) < 3:
wait = float(res.headers.get("ratelimit-reset") or 5)
else:
wait = 0
if wait > 0:
paused_until = max(paused_until, time.time() + min(wait, 120))
def api_error(message, status):
err = RuntimeError(message)
err.status = status
return err
def api(path, body=None):
if path in ("/quote", "/buy", "/sell", "/build"):
swap_calls.append(now_ms())
del swap_calls[:-100]
res = requests.request("POST" if body else "GET", API + path, json=body, headers=headers, timeout=30)
# RateLimit-Remaining / RateLimit-Reset on every authenticated response: pause before the 429 (the loops check paused()).
pause_from(res)
if not res.ok:
raise api_error(f"{path} {res.status_code} {res.text}", res.status_code)
return res.json()
def not_tradable(e):
return getattr(e, "status", None) == 409
def rate_limited(e):
return getattr(e, "status", None) == 429
def pub(path):
"""/check and /top need no key (limits per IP)."""
res = requests.get(API + path, timeout=30)
if res.status_code == 429:
pause_from(res)
if not res.ok:
raise api_error(f"{path} {res.status_code}", res.status_code)
return res.json()
def check_token(address):
try:
return pub("/check?token=" + address)
except Exception as e:
log("check_failed", token=address, message=str(e))
return None
# Signing only in live mode, on this machine.
w3 = Web3(Web3.HTTPProvider(RPC_URL))
account = None if DRY_RUN else w3.eth.account.from_key(os.environ["BOT_PRIVATE_KEY"])
TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
DECIMALS_ABI = [{"name": "decimals", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"name": "", "type": "uint8"}]}]
BALANCE_ABI = [{"name": "balanceOf", "type": "function", "stateMutability": "view", "inputs": [{"name": "", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}]}]
_decimals = {}
def decimals_of(address):
"""Only a value really read from the token is kept: on an RPC failure this raises (the caller refuses or retries), never assumes 18."""
if address not in _decimals:
d = int(w3.eth.contract(address=Web3.to_checksum_address(address), abi=DECIMALS_ABI).functions.decimals().call())
if d < 0 or d > 36:
raise RuntimeError("unreadable decimals for " + address)
_decimals[address] = d
return _decimals[address]
def balance_of(token, owner):
return int(w3.eth.contract(address=Web3.to_checksum_address(token), abi=BALANCE_ABI).functions.balanceOf(Web3.to_checksum_address(owner)).call())
def send(tx):
"""Sign locally and send. The private key never leaves this process. A reverted transaction raises: nothing is confirmed or recorded for it."""
call = {"from": account.address, "to": Web3.to_checksum_address(tx["to"]), "data": tx["data"], "value": int(tx.get("value", "0"))}
call["gas"] = int(tx["gas"]) if tx.get("gas") else int(w3.eth.estimate_gas(call) * 1.3)
call["nonce"] = w3.eth.get_transaction_count(account.address, "pending")
call["gasPrice"] = w3.eth.gas_price
call["chainId"] = CHAIN_ID
signed = account.sign_transaction(call)
raw = getattr(signed, "raw_transaction", None) or signed.rawTransaction # web3.py 7 / 6
tx_hash = w3.eth.send_raw_transaction(raw)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
h = tx_hash.hex()
h = h if h.startswith("0x") else "0x" + h
if receipt["status"] != 1:
raise RuntimeError("transaction reverted: " + h)
return h, receipt
def received(receipt):
"""The token the wallet received in this transaction (everything but USDG): (token, amount) or None if not exactly one token."""
mine = account.address.lower()[2:]
sums = {}
for entry in receipt["logs"]:
topics = ["0x" + bytes(t).hex() for t in entry["topics"]]
if len(topics) != 3 or topics[0] != TRANSFER or topics[2][-40:] != mine:
continue
if entry["address"].lower() == USDG.lower():
continue
sums[entry["address"]] = sums.get(entry["address"], 0) + int.from_bytes(bytes(entry["data"]), "big")
return next(iter(sums.items())) if len(sums) == 1 else None
def confirm(tx_hash):
"""/confirm only credits volume: best effort. A failure is queued and retried, never lost and never blocks the position."""
try:
api("/confirm", {"txHash": tx_hash})
except Exception as e:
state["pendingConfirms"].append(tx_hash)
save()
log("confirm_failed", txHash=tx_hash, message=str(e))
def retry_confirms():
pending, state["pendingConfirms"] = state["pendingConfirms"], []
for tx_hash in pending:
confirm(tx_hash)
def execute(r):
"""/buy and /sell return { router, quote, approval, tx, from }: approval first, then tx; both must succeed on chain."""
if account is None or r["from"].lower() != account.address.lower():
raise RuntimeError("API key wallet is not the signer")
if r["approval"]:
send(r["approval"])
tx_hash, receipt = send(r["tx"])
confirm(tx_hash)
return tx_hash, receipt
def format_units(raw, decimals):
s = str(raw).rjust(decimals + 1, "0")
whole, frac = (s[:-decimals], s[-decimals:].rstrip("0")) if decimals else (s, "")
return whole + ("." + frac if frac else "")
def held_set():
held = set()
for key, p in state["positions"].items():
held.add(key)
if p["address"]:
held.add(p["address"])
if p["alias"]:
held.add(p["alias"])
return held
def open_position(c, cost_usd, amount, decimals, address):
"""A position is keyed by the token address as soon as it is known (a Heat id is kept as its alias), so trending and dip see it as held."""
addr = address.lower() if address else None
key = addr or c["key"]
state["positions"][key] = {
"costUsd": cost_usd, "amount": amount, "initialAmount": amount, "decimals": decimals,
"openedAt": datetime.now(timezone.utc).isoformat(), "openedAtMs": now_ms(),
"peakUsd": cost_usd, "soldShare": 0, "ladderStep": 0, "prevUsd": None, "misses": 0,
"address": addr, "alias": c["key"] if key != c["key"] else None, "lastCheckMs": 0, "alertedMs": 0, "source": c["source"],
}
return key
def enter(c):
try:
# The token's decimals first, read from the token itself: no read, no buy.
known = decimals_of(c["address"]) if c["address"] else None
if DRY_RUN:
# /quote builds nothing and signs nothing: the dry run never touches the build limit. A Heat id has no address: 18 is assumed (simulated).
q = api("/quote", {"tokenIn": USDG, "tokenOut": c["key"], "amountIn": str(round(CFG["buy_usd"] * 1e6)), "decimalsIn": 6, "decimalsOut": known if known is not None else 18, "slippage": CFG["slippage_bps"] / 10000})
if not q.get("best") or not q["best"].get("amountOut"):
return log("skip", id=c["key"], reason="no route or no amount")
open_position(c, q["best"].get("inUsd") or CFG["buy_usd"], str(q["best"]["amountOut"]), known if known is not None else 18, c["address"])
state["spentUsd"] += CFG["buy_usd"]
log("buy", id=c["key"], source=c["source"], usd=CFG["buy_usd"], **c["fields"], router=q["best"]["router"], simulated=True)
save()
return
before = balance_of(c["address"], account.address) if c["address"] else None
r = api("/buy", {**c["ref"], "amountUsd": CFG["buy_usd"], "slippageBps": CFG["slippage_bps"]})
tx_hash, receipt = execute(r)
# The money is spent once the transaction is mined: saved right away, before anything else can fail.
state["spentUsd"] += CFG["buy_usd"]
state["pendingBuys"].append({"key": c["key"], "txHash": tx_hash, "at": datetime.now(timezone.utc).isoformat()})
save()
try:
got = received(receipt)
amount = got[1] if got else None
address = got[0] if got else c["address"]
if amount is None and address:
balance = balance_of(address, account.address)
quoted = int(r["quote"]["amountOut"]) if r["quote"].get("amountOut") else None
amount = fallback_amount(None if before is None else balance - before, quoted, balance)
if amount is None or not address:
return log("error", id=c["key"], txHash=tx_hash, message="bought, but the received amount is unknown: position NOT tracked, check the wallet")
decimals = None
try:
decimals = decimals_of(address.lower())
except Exception as e:
log("error", id=c["key"], txHash=tx_hash, message="decimals unreadable, the position is tracked and retried each cycle: " + str(e))
open_position(c, r["quote"].get("inUsd") or CFG["buy_usd"], str(amount), decimals, address)
state["pendingBuys"] = [b for b in state["pendingBuys"] if b["txHash"] != tx_hash]
log("buy", id=c["key"], source=c["source"], usd=CFG["buy_usd"], **c["fields"], router=r["router"], txHash=tx_hash)
save()
except Exception as e:
log("error", id=c["key"], txHash=tx_hash, message="bought, but the position could not be recorded: check the wallet. " + str(e))
except Exception as e:
# 409 = Trnch does not trade this token: skipped, not an error. A reverted buy lands here too: nothing is recorded.
log("skip", id=c["key"], reason=str(e))
def consider(c):
"""One candidate through the shared gates. Returns False when the optional spend cap stops all buying."""
now = now_ms()
held = held_set()
if len(state["positions"]) >= CFG["max_open"] or c["key"] in held or (c["address"] is not None and c["address"] in held):
return True
if not cooled_down(state["exited"].get(c["key"]), now, CFG["reentry_hours"]) or (c["address"] is not None and not cooled_down(state["exited"].get(c["address"]), now, CFG["reentry_hours"])):
return True
if not within_budget(state["spentUsd"], CFG["buy_usd"], CFG["max_total_usd"]):
log("cap_reached", spentUsd=state["spentUsd"], maxTotalUsd=CFG["max_total_usd"])
return False
if quote_room(swap_calls, now, CFG["quote_budget"]) < 2:
log("skip", id=c["key"], reason="quote budget: positions come first")
return True
if c["address"]:
verdict = check_token(c["address"])
if not entry_ok(verdict, c["allow_unknown"]):
log("skip", id=c["key"], reason="check: " + (f"{verdict['status']} {verdict.get('category') or ''}" if verdict else "unavailable"))
return True
enter(c)
return True
def alert_not_tradable(key, p, verdict):
"""Trnch no longer quotes or sells this token (409: Trnch keeps it out). The position stays in the state file; logged loudly, every 5 minutes."""
now = now_ms()
if now - p["alertedMs"] < 300000:
return
p["alertedMs"] = now
amount = p["amount"] + " (raw)" if p["decimals"] is None else format_units(p["amount"], p["decimals"])
log("alert_not_tradable", id=key, token=p["address"], amount=amount, verdict=(verdict or {}).get("status"),
message="Trnch will not quote or sell this token any more (kept out). Position kept, nothing was sold. Sell elsewhere with your own wallet.")
save()
def manage_positions():
retry_confirms()
for key, p in list(state["positions"].items()):
if paused():
return
try:
now = now_ms()
# GUARD first: the Trnch verdict by address (every minute) is read and logged before any quote, so a token Trnch refuses to quote still has its verdict on record.
verdict = None
if p["address"] and now - p["lastCheckMs"] >= 60000:
p["lastCheckMs"] = now
verdict = check_token(p["address"])
if verdict:
log("guard_check", id=key, token=p["address"], status=verdict["status"], category=verdict.get("category"))
if p["decimals"] is None:
try:
p["decimals"] = decimals_of(p["address"]) if p["address"] else None
except Exception as e:
log("error", id=key, message="decimals still unreadable, position not valued this cycle: " + str(e))
if p["decimals"] is None:
continue
decimals = p["decimals"]
now_usd = None
try:
# Value = what the amount this bot still holds would sell for now.
q = api("/quote", {"tokenIn": key, "tokenOut": USDG, "amountIn": p["amount"], "decimalsIn": decimals, "decimalsOut": 6, "slippage": CFG["slippage_bps"] / 10000})
now_usd = (q.get("best") or {}).get("outUsd")
except Exception as e:
if not not_tradable(e):
raise
alert_not_tradable(key, p, verdict)
continue
nxt, d = evaluate(p, now_usd, verdict, now, CFG)
p.update(nxt)
pct = None if now_usd is None else round(pnl_pct(p["costUsd"], now_usd), 1)
log("hold", id=key, entryUsd=p["costUsd"], nowUsd=now_usd, pnlPct=pct, misses=p["misses"])
if d is None:
save()
continue
raw = sell_raw(int(p["initialAmount"]), int(p["amount"]), d["share"], closes(d["share"], p["soldShare"]))
if raw <= 0:
save()
continue
if DRY_RUN:
log("sell", id=key, reason=d["reason"], share=d["share"], pnlPct=pct, simulated=True)
else:
try:
# Exactly what was bought (or a share of it), never a percent of the whole wallet balance. A reverted sell raises: the position stays, retried next cycle.
ref = {"token": key} if key.startswith("0x") else {"tokenId": key}
r = api("/sell", {**ref, "amount": format_units(raw, decimals), "slippageBps": CFG["slippage_bps"]})
tx_hash, _ = execute(r)
log("sell", id=key, reason=d["reason"], share=d["share"], pnlPct=pct, txHash=tx_hash)
except Exception as e:
if not not_tradable(e):
raise
alert_not_tradable(key, p, verdict)
continue
rest = apply_sale(p, raw, d)
if rest:
p.update(rest)
else:
for ident in (key, p["address"], p["alias"]):
if ident:
state["exited"][ident] = now
del state["positions"][key]
save()
except Exception as e:
log("error", id=key, message=str(e))
top = []
def trending_scan():
"""ENTRY=trending: the best tokens of the last 24 hours from GET /top, still near their peak."""
global top
top = pub(f"/top?limit={CFG['trend_limit']}")["tokens"]
if "trending" not in CFG["entries"]:
return
for t in top:
if paused():
return
if not trending_wanted(t, CFG, len(state["positions"]), held_set()):
continue
address = t["token"].lower()
if not consider({"key": address, "ref": {"token": address}, "address": address, "source": "trending", "allow_unknown": False, "fields": {"latest": t.get("latestSinceEntry"), "peak": t.get("peakSinceEntry")}}):
return
def dip_scan():
"""ENTRY=dip: sample the price of each watched token (a /quote of a probe amount, nothing is bought), buy a drop from the window high."""
universe = (DIP_TOKENS if DIP_TOKENS else [t["token"].lower() for t in top])[: CFG["dip_max_tokens"]]
# Histories of tokens that are no longer sampled are dropped.
for address in list(state["prices"]):
if address not in universe:
del state["prices"][address]
window_ms = CFG["dip_window_minutes"] * 60000
for address in universe:
if paused():
break
# Positions come first (about 4 quotes a minute each); a sample costs 1, the sell-route check 1 more.
if quote_room(swap_calls, now_ms(), CFG["quote_budget"]) < 2 + 4 * len(state["positions"]):
log("skip", id=address, reason="quote budget: dip sampling skipped this scan")
break
if address in held_set():
continue
try:
now = now_ms()
decimals = decimals_of(address)
q = api("/quote", {"tokenIn": USDG, "tokenOut": address, "amountIn": str(round(CFG["dip_probe_usd"] * 1e6)), "decimalsIn": 6, "decimalsOut": decimals, "slippage": CFG["slippage_bps"] / 10000})
out = float((q.get("best") or {}).get("amountOut") or 0)
if not out > 0:
continue
price = CFG["dip_probe_usd"] / out
history = [h for h in state["prices"].get(address, []) if h[0] >= now - window_ms]
dip = dip_wanted(history, now, price, CFG)
state["prices"][address] = history + [[now, price]]
if not dip:
continue
# A quotable SELL route is required before buying: the probe amount must sell back for most of its value.
back = api("/quote", {"tokenIn": address, "tokenOut": USDG, "amountIn": str(q["best"]["amountOut"]), "decimalsIn": decimals, "decimalsOut": 6, "slippage": CFG["slippage_bps"] / 10000})
if not sell_route_ok(CFG["dip_probe_usd"], (back.get("best") or {}).get("outUsd")):
log("skip", id=address, reason="dip, but no sell route for the probe amount")
continue
high = max(h[1] for h in history)
go = consider({"key": address, "ref": {"token": address}, "address": address, "source": "dip", "allow_unknown": bool(DIP_TOKENS), "fields": {"dropPct": round((high - price) / high * 100, 1)}})
# The history is cleared only once the token is really held; a skipped buy keeps it.
if address in held_set():
state["prices"].pop(address, None)
if not go:
break
except Exception as e:
log("skip", id=address, reason=str(e))
if rate_limited(e):
break
save()
log("start", entry=CFG["entries"], exit=CFG["exits"], buyUsd=CFG["buy_usd"], maxTotalUsd=CFG["max_total_usd"], spentUsd=state["spentUsd"], maxOpen=CFG["max_open"], quoteBudget=CFG["quote_budget"])
for b in state["pendingBuys"]:
log("error", id=b["key"], txHash=b["txHash"], at=b["at"], message="bought earlier but never tracked: check the wallet")
for token in WATCH:
try:
c = pub("/check?token=" + token)
log("check", token=token, status=c["status"], category=c["category"], clean=is_clean(c))
except Exception as e:
log("error", message=str(e))
since = now_ms()
last_managed = last_top = last_dip = 0.0
seen = set()
while True:
try:
# A rate limit is honoured once, here (Retry-After), never inside the loops.
if paused():
time.sleep(max(0.0, paused_until - time.time()))
# Open positions come first, then entries and dip sampling with what is left of the quote budget.
if time.time() - last_managed >= 15:
last_managed = time.time()
manage_positions()
if "heat" in CFG["entries"] and not paused():
feed = api(f"/heat?since={since}")
since = feed["nextSince"]
for t in feed["heat"]:
if t["id"] in seen:
continue
seen.add(t["id"])
if paused():
break
if not wanted(t, CFG, len(state["positions"]), held_set()):
continue
if not consider({"key": t["id"], "ref": {"tokenId": t["id"]}, "address": None, "source": "heat", "allow_unknown": False, "fields": {"heatScore": t["heatScore"]}}):
break
if ("trending" in CFG["entries"] or "dip" in CFG["entries"]) and not paused() and time.time() - last_top >= CFG["top_poll_seconds"]:
last_top = time.time()
try:
trending_scan()
except Exception as e:
log("error", message=str(e))
if "dip" in CFG["entries"] and not paused() and time.time() - last_dip >= CFG["dip_sample_seconds"]:
last_dip = time.time()
dip_scan()
except Exception as e:
log("error", message=str(e))
time.sleep(CFG["poll_seconds"])
Minimal sniper
The shorter starting point: poll /heat, keep the tokens that pass a simple filter (minimum Heat score and liquidity, edit the constants), call /buy, sign the transaction locally with the private key read from BOT_PRIVATE_KEY, send it to the public RPC of Robinhood Chain (chain id 4663), then call /confirm. They send the approval first when there is one, and refuse a transaction built for another wallet.
// Heat sniper, starter. Node 20+ : npm i viem tsx && npx tsx bot.ts
// TRNCH_API_KEY = your API key (Profile > API). BOT_PRIVATE_KEY = the key of a DEDICATED wallet.
// The private key signs on this machine only. It is never sent anywhere.
import { createPublicClient, createWalletClient, defineChain, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
const API = "https://trnch.fun/api/bot/v1";
const MIN_SCORE = 70; // minimum Heat score
const MIN_LIQUIDITY_USD = 20000;
const BUY_USD = 5; // dollars of USDG per buy: keep it small
const SLIPPAGE_BPS = 150; // 1.5%
const POLL_MS = 5000; // 12 calls a minute, the limit is 60
const chain = defineChain({
id: 4663,
name: "Robinhood Chain",
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.mainnet.chain.robinhood.com"] } },
});
const account = privateKeyToAccount(process.env.BOT_PRIVATE_KEY as `0x${string}`);
const rpc = createPublicClient({ chain, transport: http() });
const wallet = createWalletClient({ account, chain, transport: http() });
async function api(path: string, body?: unknown) {
const res = await fetch(API + path, {
method: body ? "POST" : "GET",
headers: { Authorization: "Bearer " + process.env.TRNCH_API_KEY, "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
const json = await res.json();
if (!res.ok) throw new Error(path + " " + res.status + " " + JSON.stringify(json));
return json;
}
// Your filter. Return true to buy.
function wanted(t: { heatScore: number; liquidityUsd: number; status: string }) {
return t.status === "active" && t.heatScore >= MIN_SCORE && t.liquidityUsd >= MIN_LIQUIDITY_USD;
}
async function buy(tokenId: string) {
const r = await api("/buy", { tokenId, amountUsd: BUY_USD, slippageBps: SLIPPAGE_BPS });
// The transaction is built for the wallet of your API key. Refuse anything else.
if (r.from.toLowerCase() !== account.address.toLowerCase()) throw new Error("API key wallet is not the signer");
if (r.approval) {
const approveHash = await wallet.sendTransaction({ to: r.approval.to, data: r.approval.data, value: 0n });
await rpc.waitForTransactionReceipt({ hash: approveHash });
}
const hash = await wallet.sendTransaction({ to: r.tx.to, data: r.tx.data, value: BigInt(r.tx.value), gas: r.tx.gas ? BigInt(r.tx.gas) : undefined }); // signed locally, gas with 30% margin
console.log("buy", tokenId, "via", r.router, hash);
await api("/confirm", { txHash: hash });
}
let since = Date.now();
for (;;) {
try {
const feed = await api("/heat?since=" + since);
since = feed.nextSince;
for (const t of feed.heat) if (wanted(t)) await buy(t.id).catch((e) => console.error(t.id, e.message));
} catch (e) {
console.error((e as Error).message);
}
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
}
# Heat sniper, starter. Python 3.10+ : pip install web3 requests && python bot.py
# TRNCH_API_KEY = your API key (Profile > API). BOT_PRIVATE_KEY = the key of a DEDICATED wallet.
# The private key signs on this machine only. It is never sent anywhere.
import os, time, requests
from web3 import Web3
API = "https://trnch.fun/api/bot/v1"
MIN_SCORE = 70 # minimum Heat score
MIN_LIQUIDITY_USD = 20000
BUY_USD = 5 # dollars of USDG per buy: keep it small
SLIPPAGE_BPS = 150 # 1.5%
POLL_S = 5 # 12 calls a minute, the limit is 60
CHAIN_ID = 4663 # Robinhood Chain
RPC_URL = "https://rpc.mainnet.chain.robinhood.com"
w3 = Web3(Web3.HTTPProvider(RPC_URL))
account = w3.eth.account.from_key(os.environ["BOT_PRIVATE_KEY"])
headers = {"Authorization": "Bearer " + os.environ["TRNCH_API_KEY"]}
def api(path, body=None):
res = requests.request("POST" if body else "GET", API + path, json=body, headers=headers, timeout=30)
if not res.ok:
raise RuntimeError(f"{path} {res.status_code} {res.text}")
return res.json()
def send(tx):
"""Sign locally and send. The private key never leaves this process."""
call = {"from": account.address, "to": Web3.to_checksum_address(tx["to"]), "data": tx["data"], "value": int(tx.get("value", "0"))}
call["gas"] = int(tx["gas"]) if tx.get("gas") else int(w3.eth.estimate_gas(call) * 1.3) # tx["gas"]: router estimate + 30%
call["nonce"] = w3.eth.get_transaction_count(account.address, "pending")
call["gasPrice"] = w3.eth.gas_price
call["chainId"] = CHAIN_ID
signed = account.sign_transaction(call)
raw = getattr(signed, "raw_transaction", None) or signed.rawTransaction # web3.py 7 / 6
tx_hash = w3.eth.send_raw_transaction(raw)
w3.eth.wait_for_transaction_receipt(tx_hash)
return tx_hash.hex()
# Your filter. Return True to buy.
def wanted(t):
return t["status"] == "active" and t["heatScore"] >= MIN_SCORE and t["liquidityUsd"] >= MIN_LIQUIDITY_USD
def buy(token_id):
r = api("/buy", {"tokenId": token_id, "amountUsd": BUY_USD, "slippageBps": SLIPPAGE_BPS})
# The transaction is built for the wallet of your API key. Refuse anything else.
if r["from"].lower() != account.address.lower():
raise RuntimeError("API key wallet is not the signer")
if r["approval"]:
send(r["approval"])
tx_hash = send(r["tx"])
print("buy", token_id, "via", r["router"], tx_hash)
api("/confirm", {"txHash": tx_hash if tx_hash.startswith("0x") else "0x" + tx_hash})
since = int(time.time() * 1000)
while True:
try:
feed = api(f"/heat?since={since}")
since = feed["nextSince"]
for t in feed["heat"]:
if wanted(t):
try:
buy(t["id"])
except Exception as e:
print(t["id"], e)
except Exception as e:
print(e)
time.sleep(POLL_S)
Receive the webhook instead of polling
Same bot, fed by the webhook: verify the signature, then run your filter and buy on the token you receive.
// Webhook receiver, starter. Node 20+ : npx tsx hook.ts
// TRNCH_WEBHOOK_SECRET = the whsec_... secret shown once when you saved the URL (Profile > API).
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
const SECRET = process.env.TRNCH_WEBHOOK_SECRET!;
// Header: X-TRNCH-Signature: t=<unix seconds>,v1=<hex hmac sha256 of "<t>.<raw body>">
function verify(header: string | undefined, body: string): boolean {
const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? "");
if (!m || Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return false;
const expected = createHmac("sha256", SECRET).update(m[1] + "." + body).digest();
return timingSafeEqual(expected, Buffer.from(m[2], "hex"));
}
createServer((req, res) => {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
if (!verify(req.headers["x-trnch-signature"] as string | undefined, body)) return void res.writeHead(401).end();
res.writeHead(200).end(); // answer fast (within 3 s), work after
const { token } = JSON.parse(body); // { event: "heat.entry", id, createdAt, token: { id, rank, heatScore, liquidityUsd, ... } }
console.log("entered the Heat:", token.id, token.heatScore, token.liquidityUsd);
// call your wanted(token) filter and buy(token.id) from bot.ts here
});
}).listen(8080);
# Webhook receiver, starter. Python 3.10+ : python hook.py (standard library only)
# TRNCH_WEBHOOK_SECRET = the whsec_... secret shown once when you saved the URL (Profile > API).
import hashlib, hmac, json, os, re, time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["TRNCH_WEBHOOK_SECRET"].encode()
# Header: X-TRNCH-Signature: t=<unix seconds>,v1=<hex hmac sha256 of "<t>.<raw body>">
def verify(header, body: bytes) -> bool:
m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
if not m or abs(time.time() - int(m.group(1))) > 300:
return False
expected = hmac.new(SECRET, m.group(1).encode() + b"." + body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, m.group(2))
class Hook(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("content-length", 0)))
if not verify(self.headers.get("x-trnch-signature"), body):
self.send_response(401); self.end_headers(); return
self.send_response(200); self.end_headers() # answer fast (within 3 s), work after
token = json.loads(body)["token"] # { id, rank, heatScore, liquidityUsd, ... }
print("entered the Heat:", token["id"], token["heatScore"], token["liquidityUsd"])
# call your wanted(token) filter and buy(token["id"]) from bot.py here
HTTPServer(("0.0.0.0", 8080), Hook).serve_forever()
Packages and marketplaces
- npm:
@trnchfun/agent-tools, a typed client for this API with adapters for Coinbase AgentKit, ElizaOS and the Vercel AI SDK. It never signs. - Virtuals ACP: trnch sells two jobs,
token_check(the/checkverdict) andswap_quote_build(a quote and an unsigned swap for the buyer's wallet).
Limits and fee
- 60 calls per minute per key, all routes together; 30 of them can be quotes, builds, buys or sells. Above that you get 429 with a retry-after header.
- 120 calls per minute per IP across keys.
- Up to 10 new keys per IP per day.
- Responses that need an API key carry the rate limit headers (IETF draft):
RateLimit-Limit,RateLimit-RemainingandRateLimit-Reset(seconds to the next minute), plusRateLimit-Policy(60;w=60). They follow the counter closest to its limit: the 60 calls, or the 30 quotes, builds, buys and sells. A 429 also sendsRetry-After(seconds)./registercounts per IP and carries the same headers. The public routes (/stats,/check,/scan,/top, and/quotewithout a key) count per IP and carry none; a request refused before any counter (401, 503) carries none either. - When swaps are paused on TRNCH, quote, build, buy and sell answer 503. The feed stays open.
- A swap into a token TRNCH cannot trade for a bot is refused with 409 and the same message for every case,
token not tradable through TRNCH, never a reason. Selling a token Trnch keeps out is allowed. A token with no route gets a 404 at build time. - Building more than 8 swaps without sending any transaction stops building for that wallet for up to 24 hours (429 with retry-after). Quotes stay open.
- Trnch takes a fee on swaps built through the API: 0.25% per swap, 0.10% between major assets such as ETH and USDG, 0.05% between a Stock Token and a major asset, 0.50% for tokens under 24 h old or with no known launch time. It is taken inside the route you sign, so the amounts we return are net of it.
- Errors are JSON: an
errorfield and the matching HTTP status (400, 401, 404, 409, 429, 503).
Fees go to the TRNCH treasury, a multisig Safe on Robinhood Chain, the only address that collects them: 0xe1F2aBa69cfD0C6973d037426D4391FE64b2Fc2e
Versioning
- The version is in the URL:
/api/bot/v1. Within a version we add fields and endpoints, never remove or rename them. - A breaking change ships as
/api/bot/v2, announced at least 90 days before anything inv1stops answering. - A deprecated endpoint sends
DeprecationandSunsetheaders (RFC 9745, RFC 8594) on every response, with aLinkto its successor. Nothing is deprecated today.
Your bot signs
TRNCH never signs for you, never holds your funds and never sees a private key. The API gives you data and transactions; your bot signs them with its own key and sends them to the chain. Never share a wallet key or a seed phrase with anyone, TRNCH included. If an API key leaks, revoke it in your Profile: it stops working at once.
Quotes and swaps may be used automatically. Raw TRNCH data are licensed only for trading through TRNCH. Any other use, including partial reproduction, is prohibited. Terms of Use