Copying a Strategy on BNB Smart Chain
This guide shows how to follow a Treasures strategy from a wallet on BNB Smart Chain: ask for a plan, then quote, sign and submit each order, one at a time. Treasures never holds the key and never signs for you. It is the worked example for Strategy Signals: On BNB Smart Chain, which lists every rule.
The flow
- Plan.
POST /signals-orders/rebalance/planwithchain: "bnb"compares what your wallet holds with the strategy's book and returns the orders that close the gap. Nothing is quoted and nothing expires. - Execute each order. For every order in the plan: quote it, sign the quote within about 14 seconds, submit it, and poll it until it settles. Then move to the next order.
- Plan again. Buys spend only the
amount_usdcyou sent, never the proceeds of sells in the same plan. Once your sells have settled, call the plan again with the USDC now committed to the strategy (funding.next_amount_usdcwhen every order filled) to place the buys that were deferred. Repeat until the plan returns no orders.
To leave a strategy, use POST /signals-orders/exit/plan the same way: it returns one full sell per name you hold.
Before your first order
- A general integrator API key, sent as
X-API-Keyon every call. - Binance-Peg USDC on BNB Smart Chain in the wallet. It is an 18-decimal token and is not the same asset as USDC on other chains.
- Token approvals. A buy needs the wallet's Binance-Peg USDC approved to the router; a sell needs the stock token approved. The plan tells you which are missing in
approvals(see below). Sending an approval is an ordinary transaction, so keep a small amount of BNB for gas. Trades themselves cost no gas.
What the plan returns
{
"strategy_id": "cst_...",
"book_hash": "9f2c...", // send back as expected_book_hash to detect a changed book
"signal_id": "...",
"as_of": 1794900000,
"nav_usdc": "512.40", // what you hold in the strategy's names, plus amount_usdc
"usdc_available": "140.250000", // Binance-Peg USDC in the wallet
"funding": {
"usdc_spendable": "100",
"buys_required_usdc": "180",
"buys_scaled": true, // buys were scaled down to fit amount_usdc
"buys_deferred_usdc": "80",
"buys_deferred_until_sells_settle": true,
"next_amount_usdc": "161.20" // the next call's amount_usdc, if every order here fills
},
"orders": [
{ "ticker": "NVDA", "side": "sell", "shares": "0.412", "notional_usdc": "61.20" },
{ "ticker": "AAPL", "side": "buy", "shares": null, "notional_usdc": "42.500000" }
],
"skipped": [
{ "ticker": "TSLA", "side": "buy", "reason": "below_min_notional", "detail": null }
],
"approvals": [
{ "token": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d", "spender": "0x...", "approval_required": true }
]
}
- A sell is exact in shares. Send
sharesasamount_sharesonPOST /quote/sell. Itsnotional_usdcis an estimate of the position's value. - A buy is exact in USDC. Send
notional_usdcasamount_usdconPOST /quote/buy.sharesisnullbecause the share count depends on the price when you quote. skippedlists every name that was not ordered, and why: for examplebelow_min_notional(under the venue minimum),not_tradable(no BNB listing),awaiting_sell_proceedsorinsufficient_balance(not enoughamount_usdcthis round).approvals:spenderis the router contract that settles your orders (0x111111125421cA6dc452d289314280a0f8842A65).truemeans approve that token tospenderbefore you trade it, or the order is refused at submit.falsemeans the allowance is enough.nullmeans it could not be read: check the allowance yourself before signing.
Minimums: an order for a name that only lists as xStocks on BNB Smart Chain must be at least $10; other names $1. When amount_usdc is short, every buy is scaled down in proportion, and a buy that falls under its minimum is skipped, so a small amount spread over many names can place no buys at all. The shortfall stays in funding.buys_deferred_usdc.
Sample: plan, then execute one order at a time
TypeScript with viem. The sample is sequential on purpose: each quote must be signed within about 14 seconds, so quote an order only when you are ready to sign it.
import { privateKeyToAccount } from "viem/accounts";
const API = "https://api.treasures.io/public/v1";
const account = privateKeyToAccount(process.env.ETH_PRIVATE_KEY as `0x${string}`);
const headers = {
"content-type": "application/json",
"x-api-key": process.env.TREASURES_API_KEY ?? "",
};
// The only contract an order from this guide is signed for: the router your approvals name as `spender`.
const ROUTER = "0x111111125421ca6dc452d289314280a0f8842a65";
const POLL_LIMIT_MS = 5 * 60_000;
type Json = Record<string, any>;
type Order = { ticker: string; side: "buy" | "sell"; shares: string | null; notional_usdc: string | null };
// usdcDelta: USDC this order added to (a sell) or took from (a buy) the wallet, in micro-units.
type Outcome = { ticker: string; side: string; result: string; usdcDelta: bigint; detail?: unknown };
async function call(method: "GET" | "POST", path: string, body?: unknown): Promise<{ status: number; body: Json }> {
const res = await fetch(`${API}${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
return { status: res.status, body: (await res.json()) as Json };
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// USDC amounts are decimal strings: handle them as integer micro-units, never as floats.
const toMicro = (usdc: string) => {
const [whole, fraction = ""] = usdc.split(".");
return BigInt(whole) * 1_000_000n + BigInt(`${fraction}000000`.slice(0, 6)); // rounds down
};
const fromMicro = (micro: bigint) => `${micro / 1_000_000n}.${String(micro % 1_000_000n).padStart(6, "0")}`;
// A fresh proof per call: it is valid for about five minutes.
async function ownershipProof() {
const issuedAt = Math.floor(Date.now() / 1000);
const challenge = ["treasures-finance-quote-v1", String(issuedAt), "", account.address.toLowerCase()].join("\n");
return { issued_at: issuedAt, eth_signature: await account.signMessage({ message: challenge }) };
}
// 1. Plan. Omit amountUsdc to only reshuffle what the wallet already holds.
async function plan(strategyId: string, amountUsdc?: string, expectedBookHash?: string) {
const res = await call("POST", "/signals-orders/rebalance/plan", {
strategy_id: strategyId,
chain: "bnb",
eth_wallet: account.address,
ownership_proof: await ownershipProof(),
amount_usdc: amountUsdc,
expected_book_hash: expectedBookHash,
});
// 409 book_changed carries the new book_hash: read the book again, then re-plan.
if (res.status !== 200) throw new Error(`plan refused: ${res.status} ${res.body.error}`);
return res.body;
}
// Sign only the gasless order payload. Never sign anything else from this loop: a token permit is
// typed data too, so check the type, the chain and the contract, not just the payload kind.
async function signPayload(payload: Json) {
if (payload.type !== "evm_eip712_typed_data") throw new Error(`unexpected payload ${payload.type}`);
const { domain, types, primaryType, message } = payload.typed_data;
if (primaryType !== "Order") throw new Error(`unexpected typed data ${primaryType}`);
if (domain.chainId !== 56) throw new Error(`unexpected chain ${domain.chainId}`);
if (String(domain.verifyingContract).toLowerCase() !== ROUTER) {
throw new Error(`unexpected contract ${domain.verifyingContract}`);
}
const { EIP712Domain: _omit, ...typesNoDomain } = types; // viem adds the domain type itself
const signature = await account.signTypedData({ domain, types: typesNoDomain, primaryType, message });
return { type: "evm_eip712_signature" as const, signature };
}
// 2. One order: quote, sign, submit, poll to a final status.
async function executeOrder(order: Order, maxSlippageBps: number): Promise<Outcome> {
const nothing = { ticker: order.ticker, side: order.side, usdcDelta: 0n };
const common = {
ticker: order.ticker,
chain: "bnb",
protocol: ["ondo", "xstocks"], // the venues the plan read; do not leave this unpinned
eth_wallet: account.address,
ownership_proof: await ownershipProof(),
max_slippage_bps: maxSlippageBps,
};
const quote =
order.side === "sell"
? await call("POST", "/quote/sell", { ...common, amount_shares: order.shares })
: await call("POST", "/quote/buy", { ...common, amount_usdc: order.notional_usdc });
// Typical refusals: no_routes, slippage_exceeded, amount_too_small, market_closed.
if (quote.status !== 200) return { ...nothing, result: "quote_refused", detail: quote.body };
// Sign every leg of this quote straight away. A sell can return more than one leg.
const signed = [];
for (const leg of quote.body.quotes as Json[]) {
const signedPayloads = [];
for (const payload of leg.signable_payloads as Json[]) signedPayloads.push(await signPayload(payload));
signed.push({ quote_index: leg.quote_index, signed_payloads: signedPayloads });
}
const submit = await call("POST", "/trade/submit", { quote_id: quote.body.quote_id, signed });
if (submit.status !== 200) return { ...nothing, result: "submit_refused", detail: submit.body };
const results = submit.body.results as Json[];
// not_enough_balance_or_allowance here means a missing approval or too little balance.
if (results.every((leg) => leg.status === "broadcast_failed")) {
return { ...nothing, result: "broadcast_failed", detail: results };
}
// `broadcast` and `broadcast_unknown` both mean: poll, never re-submit.
const deadline = Date.now() + POLL_LIMIT_MS;
while (Date.now() < deadline) {
const status = await call("GET", `/quote/${quote.body.quote_id}/status`);
if (status.status === 200 && status.body.aggregate_status !== "in_progress") {
const filled = (status.body.legs as Json[]).filter((leg) => leg.status === "completed");
const usdcDelta =
order.side === "sell"
? filled.reduce((sum, leg) => sum + toMicro(leg.filled_usdc), 0n) // proceeds received
: filled.length > 0
? -toMicro(order.notional_usdc ?? "0") // a filled buy spent what it was quoted for
: 0n;
return { ...nothing, usdcDelta, result: status.body.aggregate_status, detail: status.body.legs };
}
await sleep(status.body.poll_after_ms ?? 3250);
}
// Still open: the order may yet fill. Stop the whole run rather than open a second order or
// size the next round without it; check the status by hand before running again.
throw new Error(`${order.side} ${order.ticker}: quote ${quote.body.quote_id} not final after ${POLL_LIMIT_MS / 1000}s`);
}
// 3. One round: plan, stop on a missing approval, then run the orders in the order given.
async function runRound(strategyId: string, amountUsdc: string | undefined, maxSlippageBps: number) {
const planned = await plan(strategyId, amountUsdc);
const blocked = (planned.approvals as Json[]).filter((row) => row.approval_required !== false);
if (blocked.length > 0) {
throw new Error(`approve or check these tokens first: ${blocked.map((row) => row.token).join(", ")}`);
}
const outcomes: Outcome[] = [];
for (const order of planned.orders as Order[]) {
outcomes.push(await executeOrder(order, maxSlippageBps)); // one at a time, sells first
}
return { planned, outcomes };
}
// Never above what the wallet holds: an amount_usdc over the balance is refused.
async function capAtWalletCash(budget: bigint): Promise<bigint> {
const wallet = await call("GET", `/portfolio?eth_wallet=${account.address}`);
if (wallet.status !== 200) throw new Error(`portfolio refused: ${wallet.status}`);
const cash = toMicro(wallet.body.usdc.bnb);
return cash < budget ? cash : budget;
}
// Round 1 places the sells and the buys the budget covers. Later rounds place the deferred buys.
// The budget is what you committed, plus what sells actually paid, minus what buys actually spent.
// funding.next_amount_usdc is the same sum assuming every planned order fills, so it is only right
// when they all do.
async function copyStrategy(strategyId: string, amountUsdc: string | undefined, maxSlippageBps = 300) {
let budget = amountUsdc === undefined ? 0n : toMicro(amountUsdc);
for (let round = 1; round <= 4; round += 1) {
// "0" is refused: omit amount_usdc instead.
const amount = budget === 0n ? undefined : fromMicro(budget);
const { planned, outcomes } = await runRound(strategyId, amount, maxSlippageBps);
console.log(`round ${round}`, outcomes.map((o) => `${o.side} ${o.ticker}: ${o.result}`));
if (planned.orders.length === 0) return;
// Nothing filled this round: stop instead of repeating the same refusals.
if (outcomes.every((o) => o.usdcDelta === 0n)) return;
budget = await capAtWalletCash(outcomes.reduce((sum, o) => sum + o.usdcDelta, budget));
}
}
await copyStrategy("example-13f", "100");
Things to get right
- Sign fast. A quote on BNB Smart Chain must be signed and submitted within about 14 seconds. If you miss it, quote the order again; never re-submit an old quote.
- Check what you sign. Sign a payload only when its
primaryTypeisOrder, itsdomain.chainIdis 56 and itsdomain.verifyingContractis the router above. Compare against an address you hold in your own code, not one read from a response. - Always pin
protocolto["ondo","xstocks"]on the per-order quotes. The plan only reads those venues, so an unpinned quote could trade a token the plan did not count. - bStocks holdings are not counted. The plan reads only the Ondo and xStocks tokens in the wallet. A strategy name you hold as bStocks reads as not held: a rebalance buys its full target again, an exit leaves it in the wallet, and it is not part of
nav_usdc. Sell it yourself first if you do not want both. - The quote is the firm price, not the plan. Prices move between the two. If a quote is refused, skip that name for this round and let the next plan pick it up.
- Slippage. During the US session a
max_slippage_bpsof 100 is enough for most names; outside it, xStocks often need about 300. broadcast_unknownis not a failure. The order may be live. Poll its status; do not quote the same order again until the status is final. If it is still not final after a few minutes, stop, as the sample does: do not start the next order or plan again while one may still fill.- Size the next round from what actually filled.
funding.next_amount_usdcassumes every planned order fills. If a sell failed or a buy was refused, it is wrong: compute the nextamount_usdcas what you sent, plus the USDC your sells paid (filled_usdcon their completed status legs), minus what your filled buys spent, as the sample does. Never send more than the wallet's Binance-Peg USDC (usdc.bnbonGET /portfolio): an amount above the balance is refused with422 insufficient_balance."0"is refused too, so omitamount_usdcinstead. - Rate limits. The rebalance plan route allows 12 calls a minute per wallet. Wait for a round to settle before planning the next.
Where to go next
- Strategy Signals: the books, the plan routes, every skip reason and refusal.
- Chains and Venues: BNB Smart Chain's stablecoin, approvals and signing window.
- Ownership Proof: the signature each plan and quote call carries.
- API Reference: every field on the signals routes.