On-Chain Token Live Rolling Grid · Dual-Timeframe 1inch Orderbook Grid
Risk warning: This is a live on-chain strategy with no paper-trading mode; once started, it executes real transactions and posts real limit orders using wallet funds. First-time startup immediately performs a market buy for the initial lot, and subsequent entries use downward limit orders with no automated stop-loss or panic-exit logic. High-volatility on-chain tokens carry risks of liquidity withdrawal, total loss, transfer taxes, blacklists, severe slippage, gas spikes, and prolonged unfilled orders. Displayed net P&L includes inventory valued at small-size quotes rather than realized cash. Verify the token address, chain and RPC endpoint, 1inch API permissions, and wallet balances before running.
Strategy Concept
The strategy targets volatile EVM on-chain tokens using FMZ's OneInch exchange object and the 1inch Orderbook v4.1 protocol. It runs a spot-only rolling grid that accumulates on pullbacks, prices take-profit exits from actual fill costs and holding-period volatility, and locks in a portion of realized profits above a high-water mark.
Three mechanisms separate market sizing, execution spacing, and capital compounding:
- The long timeframe defines the trading band with multi-tier fallbacks. By default, a 120-minute window computes the 10th–90th percentile band. For new or thinly traded tokens, data sources degrade gracefully from
1m/5m/15mtoken bars to syntheticToken/WrappedNative * Native/Quotebars, and finally to a simulated band derived from current price and effective spacing. Breakouts above the upper bound shift the grid band upward conditionally. - The short timeframe and holding-period movement set grid spacing. A default 15-minute window measures baseline volatility, bounded below by the minimum spacing and the cost-and-profit exit floor. When placing a take-profit sell order, the strategy also incorporates recency-weighted 1-minute return swings observed since that lot's entry (
pRecencydecay) to widen targets during upward momentum. - Profit locking and rolling round settlement. The initial trading budget starts at one lot (
pUnitU, default10 U) and compounds as rounds complete. Once cumulative realized net P&L exceeds the protection threshold (default10 U), a configured percentage (default30%) of any new high-water excess is permanently locked and excluded from future buy orders.
The strategy only trades long spot inventory in rolling rounds. It never shorts, has no fixed stop-loss, and does not guarantee fills within order lifetimes.
On-Chain Interface and Execution Architecture
The strategy operates through FMZ's OneInch exchange object, an HTTPS JSON-RPC endpoint, and the 1inch Orderbook v4.1 API, persisting all round and ledger state via _G:
- Quotes and tiered market fallbacks: Reference prices come from
exchange.GetTicker, while executable prices come from small-size sell quotes viaexchange.IO("route", PAIR, "sell", ...). Insufficient bars trigger automatic timeframe/synthetic/simulated fallbacks; the loop waits and retries only when no valid quote can be obtained. - Initial market buy and one-at-a-time limit buys: On first startup without saved state,
exchange.CreateOrdermarket-buys the first lot. In subsequent rounds, only the next pending buy slot is posted at a time. Before posting,reprice()lowers (never raises) the planned entry price if current market prices and buy spacing justify a deeper entry. - 1inch v6 EIP-712 signing and
FeeTakerextensions: The strategy queries/fee-infofor resolver and integrator fees, constructs the 1inch Aggregation Router v6 (0x111111125421ca6dc452d289314280a0f8842a65)FeeTakerextension andsalt, signs viaexchange.IO("signTypedData", ...), verifies the digest against the on-chain router hash, and submits to the Orderbook API with a1.1sminimum request interval. - Exact allowances and separate native gas accounting: Before posting orders or buying, the strategy checks wallet balances and Router allowances (including active order reservations), checking
pMinBnband broadcasting an exactapprovetransaction when needed. Native gas costs are converted viapGasPairand recorded into lot costs and cumulative net P&L without deducting from the quote-currency cash budgetS.cash. - Finality confirmation and halted-state protection: Settlement only trusts blocks at
tip - pConfirmBlocks + 1(with node clock drift< 120s), cross-checking RouterremainingInvalidatorForOrder,/eventsfill indices, and confirmedTransfer/OrderFilledlogs. Missing hashes, failed transactions, transfer-flow mismatches,MAKER_BLACKLISTEDrejections, or unmatched external cancellations triggerstopTradingto halt new orders while preserving state for manual reconciliation.
Run on an FMZ node with a configured OneInch exchange object, a matching HTTPS RPC node, and a valid 1inch Orderbook API Key.
Trading Workflow
text
Configure OneInch exchange object, matching HTTPS RPC, 1inch API Key, and dedicated wallet
↓
Verify quote/base token decimals, Orderbook auth, initial balances, and saved state
↓
First startup (no saved state) → market-buy initial lot → confirm on-chain → post sell order
↓
Fetch 1inch route quote and long/short market history (with multi-tier fallbacks)
↓
Size downward buy grid from available cash, long band, and cost-and-profit exit floor
↓
Prioritize posting sells for filled lots; otherwise reprice and post the next buy slot
↓
Verify finalized on-chain remaining amounts and fill receipts → update inventory, cash, and gas
↓
All inventory sold and zero open orders after fills → settle round and lock excess profits
↓
Release capital → wait poll interval and plan the next round
Initial Entry and Round Planning
On a fresh start with no saved state, the wallet must hold 0 target tokens and at least pUnitU in the quote token. The strategy immediately executes a market buy for one lot (pUnitU, default slippage tolerance 150 bps) and posts its take-profit sell once confirmed on-chain.
For subsequent rounds, available capital equals S.cash - S.locked - openBuyRemaining, allowing up to floor(available / pUnitU) lots. By default, the 120-minute window's 10th–90th percentile sets the grid band; fewer than 8 bars fall back to a simulated band, narrow bands extend downward to fit at least the first buy level, and 3 consecutive short-window closes above the upper bound shift the band upward.
Buy prices step down geometrically via first / (1 + gap)^i, where gap is the greater of the volatility buy gap and the cost-and-profit exit threshold, filtering out levels whose take-profit target would exceed the upper band.
Dynamic Grid and Take-Profit Execution
Rather than placing the entire buy ladder simultaneously, only the earliest unattempted buy slot is posted. If no filled lot is waiting for a sell order, reprice() recalculates the next buy price downward using the latest quote and buyGap before signing and posting. Enabling "Pause new buys" stops new buy placements while allowing existing sells and settlements to finish.
Once a buy lot confirms on-chain, the strategy prioritizes posting its sell order:
- Compute baseline sell spacing
sellGap = max(pMinGapBps / 10000, amp * pSellK). - Scan 1-minute bars after
lot.entryAtwith exponential decaypRecency(0.85default), summing positive and negative returns; if net movement is positive,swing = max(sellGap, vol * pSellK). - Calculate
sellFloor = (cost + gas + pFutureCostU + pMinProfitU) / (1 - pCostBufferBps / 10000)and takemax(cost * (1 + swing), sellFloor), scaled proportionally for any remaining unsold quantity, then submit a 1inch limit sell valid forpSellTtl.
Expired buy orders with partial fills convert the acquired tokens directly into a sellable lot; expired sell orders are recalculated and reposted on the next cycle.
Round Completion and Risk Handling
A round ends immediately when at least one fill occurred, total base inventory across all lots reaches zero, and all open orders are cleared (or if no fills occurred, no orders remain, and slots were attempted).
Upon settlement, realized round P&L is added to S.realized. If the new cumulative realized P&L exceeds max(S.highWater, pProtectAfterU), pLockPct (default 30%) of the excess is permanently added to S.locked.
Any on-chain transaction failure, missing tx hash, mismatched wallet/transfer log, API rejection, or unexplained external cancellation halts new order submission (stopTrading) until manually reviewed.
Fees and Cost Conditions
Each lot's take-profit quote target is the greater of its cost-and-profit floor and its volatility-adjusted target:
Cost-and-profit floor = (actual entry cost + gas in quote + future cost reserve + min net profit) ÷ (1 − cost buffer)
Volatility target = actual entry cost × (1 + dynamic sell spacing)
Gross exit target = max(cost-and-profit floor, volatility target)
The effective entry step also enforces this floor so that pUnitU entries are spaced widely enough to clear the minimum profitable exit threshold. Default settings:
- Lot size
pUnitU:10 U; - Target net profit per lot
pMinProfitU:0.5 U; - Future cost reserve
pFutureCostU:0.08 U; - Extra cost buffer
pCostBufferBps:80 bps(0.8%); - Minimum spacing
pMinGapBps:40 bps(0.4%).
With a default 10 U lot and zero initial gas, the floor evaluates to (10 + 0 + 0.08 + 0.5) ÷ (1 - 0.008) ≈ 10.6653 U (roughly +6.65%). Fixed U-denominated profit and reserve targets therefore dominate spacing on small lot sizes; increasing pUnitU or lowering profit/reserve targets narrows the effective step.
1inch Orderbook resolver and integrator fees retrieved from /fee-info are deducted directly from fill outputs on-chain (displayed separately in the status panel alongside confirmed gas), while actual cash accounting follows confirmed ERC-20 Transfer logs.
Live Configuration
Prepare the following before starting:
- Add one FMZ
OneInchexchange object configured for the target EVM chain (built-in chain labels cover Ethereum, OP Mainnet, BSC, Gnosis, Unichain, Polygon, Sonic, Base, and Arbitrum; the Router is verified as0x111111125421ca6dc452d289314280a0f8842a65); - Provide an HTTPS JSON-RPC URL matching the exchange's
chainIdand a valid 1inch Orderbook API Key; - Set the target token contract
pBaseToken, quote symbolpQuote(defaultUSDT, orUSDC/USDT0/ another token present in the exchange token table), and native-token pricing pairpGasPair(e.g.,BNB_USDTon BSC orETH_USDTon Ethereum).
Use a dedicated wallet per bot. Without saved state, startup requires 0 balance of the target token, at least pUnitU in the quote token, and at least pMinBnb in native gas coins before approvals or the initial market buy. Saved state is keyed by chainId + wallet + token, and resuming an existing archive requires matching pUnitU.
Main Live Parameters
| Parameter | Group | Default | Purpose |
|---|---|---|---|
| 1inch Orderbook API Key | Live Connection | Empty | Authenticates 1inch Orderbook v4.1 quote, fee, order, and event requests. |
| RPC endpoint | Live Connection | https://bsc-dataseed.binance.org | HTTPS JSON-RPC URL; must match the exchange object's chain ID. |
| Token address | Live Connection | 0x9665f094... | Target ERC-20 contract address; decimals and symbol are read on-chain. |
| Quote token | Live Connection | USDT | Quote symbol resolved from the exchange token table (USDT/USDC/USDT0, etc.). |
| Native token USD pair | Live Connection | BNB_USDT | Ticker pair used to convert native gas spend into quote units. |
| Pause new buys | Live Connection | Off | Stops posting new buy orders while continuing active sell orders and settlements. |
| Lot size (U) | Position & Profit | 10 | Quote amount per grid lot and initial cash budget; immutable while resuming saved state. |
| Target net profit per lot (U) | Position & Profit | 0.5 | Minimum net profit target included in the take-profit floor and buy step. |
| Future cost reserve per lot (U) | Position & Profit | 0.08 | Reserves quote headroom for follow-up gas and execution costs. |
| Extra cost buffer (bps) | Position & Profit | 80 | Scales the exit floor via 1 / (1 - buffer) to absorb fees and rounding. |
| Profit lock threshold (U) | Position & Profit | 10 | Cumulative realized net P&L level above which profit locking activates. |
| Profit lock percentage (%) | Position & Profit | 30 | Share of new high-water realized profits permanently locked out of buy capacity. |
| Long window (minutes) | Dual Timeframe | 120 | Computes the 10th–90th percentile grid band (10–600). |
| Short window (minutes) | Dual Timeframe | 15 | Computes baseline volatility spacing; must be shorter than the long window (8–300). |
| Buy spacing multiplier | Dual Timeframe | 0.5 | Multiplier applied to short-window volatility for buy intervals. |
| Sell spacing multiplier | Dual Timeframe | 0.5 | Multiplier applied to short-window volatility and holding-period swings. |
| Volatility recency decay | Dual Timeframe | 0.85 | Exponential decay for 1m returns during holding; lower values favor recent bars (0.5–1). |
| Minimum spacing (bps) | Dual Timeframe | 40 | Floor for buy/sell volatility spacing and fallback when range data is unavailable. |
| Initial market-buy slippage (bps) | Execution | 150 | Slippage limit for the first-run market buy. |
| Buy order TTL (seconds) | Execution | 180 | Expiry duration for 1inch limit buy orders (minimum 75). |
| Sell order TTL (seconds) | Execution | 900 | Expiry duration for 1inch limit sell orders (minimum 180). |
| Main poll interval (seconds) | Execution | 12 | Loop interval for block finality, order checks, and settlement (3–600). |
| Price refresh (seconds) | Execution | 60 | Interval for refreshing 1inch route quotes and dashboard pricing (10–600). |
| On-chain confirmation blocks | Execution | 4 | Required block depth (tip - pConfirmBlocks + 1) before finalizing receipts and fills. |
| Wallet native gas reserve | Execution | 0.003 | Minimum native coin balance checked before approve or initial market buys. |
All 25 live parameters across the four groups (Live Connection, Position & Profit, Dual Timeframe, and Execution) are listed above; execution is additionally constrained by node clock checks, token precision, and API throttling.
Operating Notes
- Smart-contract token hazards: The strategy does not audit token contracts. Fee-on-transfer taxes, honeypots, cooldowns, blacklists, or liquidity rug pulls can prevent sells, trigger transfer-mismatch halts, or result in total loss.
- No stop-loss and inventory lockup risk: If price drops below the long band, new buys pause, but existing inventory remains held with limit sells placed above cost. Prolonged downtrends can tie up capital indefinitely.
- Fixed-cost floor vs. lot size: Small lot sizes (such as the default
10 U) combined with fixed profit and reserve targets (0.5 U+0.08 U) substantially widen the effective grid step (~6.65%), and frequent on-chain approvals/fills consume native gas. SizepUnitUappropriately for each chain's gas fees. - Dedicated wallet requirement: Accounting relies on wallet balances and ERC-20
Transferlogs. Trading the same tokens manually in the same wallet or cancelling orders externally can break ledger consistency and halt the bot. - Native gas exhaustion blocks approvals: Even though gas is excluded from the quote-currency budget, running below
pMinBnbblocks token approvals and initial market buys, which can stall take-profit listing if a newly acquired token has not yet been approved. - Manual reconciliation on halts: When
stopTradingtriggers, the bot stops submitting new orders but does not automatically cancel already posted 1inch orders or market-dump inventory. Inspect on-chain state and active orders before restarting. - Floating inventory valuation: Displayed net P&L adds realized quote cash to current token inventory valued at a small 1inch sell quote. In thin pools, actual liquidation value for larger positions may be significantly lower.
- Infrastructure reliability: Public RPC rate limits, block timestamps lagging more than
120seconds behind local time, or 1inch API key throttling can delay price updates, order submissions, and fill reconciliation.
/* 1inch Orderbook 实盘滚仓。每个机器人使用独立钱包,保留原生币支付链上费用。
链取自 OneInch 交易所对象的配置,代币地址、计价币与原生币计价对取自参数,可换任意链上的任意币。 */
var V6ROUTER = "0x111111125421ca6dc452d289314280a0f8842a65";
var ZERO = "0x0000000000000000000000000000000000000000";
var FILLED = "0xfec331350fce78ba658e082a71da20ac9f8d798a99b3c79681c8440cbfe77e07";
var TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
var MAX = (BigInt(1) << BigInt(256)) - BigInt(1);
var Z = BigInt(0), QD = 18, BD, WALLET, KEY, S;
var BASE = "", QUOTE = "", ROUTER = V6ROUTER, PAIR = "", NATIVEPAIR = "", QS = "USDT", WS = "WBNB", DN = "";
var BOOK = "", CHAIN = 0, CHAIN_NAME = "";
var marketCache, gasRate, gasAt = 0, bookAt = 0, lastMessage = "", wakeAt = 0, feeCache = {}, marketLogAt = 0;
var marketTries = 0, marketFailAt = 0;- 1