Skip to content
WaydeWanPublic

About

Nunchi: an AI execution agent for HSK Chain that times trades to HSKSwap's lag behind the exchanges. Built for the HSK Chain Horizon Hackathon (Seoul), Track 1.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

10 Commits

Folders and files

Repository files navigation

Nunchi logo

Nunchi

English · 中文 · 한국어

HSKSwap’s pools lag the exchanges by hours. Nunchi uses that lag to get better fills. In a 15-day replay of $100 WETH buy orders, immediate swaps received 0.68% less WETH per USDT than the exchange benchmark on average. By waiting, Nunchi received 0.31% more. Each fill was compared with the exchange price at that moment. Across about six months for WETH and WBTC and seven months for WHSK, timing beat an immediate swap on every asset and side by an average of 0.22–0.37 percentage points per filled order.

Nunchi is one AI trading agent on HSK Chain with two layers.

  • The execution layer trades autonomously. Every 10 seconds it quotes the pools, checks the exchange reference and looks for an edge. Once a user confirms an order or enables auto-gap, the engine can execute each qualifying trade without another click.
  • The AI layer reviews and tunes the strategy. Chat in English, Chinese or Korean, ask what the engine is waiting for, or draft an order. The AI reviews the market hourly, watches the opportunity radar and tests proposed strategy parameters on history. Optional autopilot can apply changes within fixed bounds. The AI cannot confirm orders, sign or send transactions. The contract enforces hard limits on every swap.

Nunchi (눈치) is Korean for knowing the right moment to act. Built for the HSK Chain Horizon Hackathon (Seoul), Track 1: AI Agent Trading. DoraHacks Build

Execution layer

Feature What the agent does
Market monitor Every 10 seconds the runner quotes WHSK/USDT, WBTC/USDT and WETH/USDT through HSKSwap V3 QuoterV2 and polls six exchanges in total, four per asset. It uses a median of fresh exchange quotes as the reference and refreshes APRO once a minute for an independent comparison.
Smart execution orders “Buy 50 USDT of ETH within 24 hours, paying at most 0.3% above the exchange.” Nunchi checks the quote for each clip size and fills when the price meets the required edge. That edge relaxes toward the user’s limit as the deadline approaches.
Lag-aware stop-loss A drop through the stop price on the exchange starts an urgent sell window. The engine can sell into a pool that still quotes the earlier, higher price, subject to the order’s maximum discount and the usual risk checks.
Take-profit When the exchange rises to the target, a smart sell order starts its execution window and waits for the lagging pool to offer an acceptable price.
Buy-the-dip When the exchange falls to the target, a smart buy order starts its execution window and waits for the pool price to follow.
Trailing stop The stop follows the highest exchange reference observed since you confirmed the order. A drop by the chosen distance triggers an urgent sale into the pool.
Smart DCA Each scheduled instalment opens a smart buy order with its own execution window. The default is one buy per day with 20 hours to find a qualifying quote.
Smart rebalancing Give the agent target portfolio weights. It values the holdings at exchange prices and drafts smart orders, listing sells first. Live mode can read the contract balances. In shadow mode you supply the holdings. Each confirmed leg waits for its own qualifying pool quote.
Auto-gap mode With a separate small budget, the agent buys at a discount and sells its own inventory at a premium, with stop-loss and timed exit rules. It yields to active user orders in the same asset. Each card shows the condition it is waiting for and, for an open position, estimated P&L if sold back to the pool now.
Risk controls and on-chain execution The engine checks reference freshness and agreement, pool price jumps, the daily loss limit, consecutive send failures and the kill switch. Each live swap passes an eth_call simulation before the operator sends it to AgentExecutor.
Verifiable scoreboard Each fill shows its edge against the exchange reference, the available APRO price and its age, and the evidence label. Mainnet transactions link to the explorer.

AI layer

  • Chat and order drafts. OpenAI tool calling lets you ask in English, Chinese or Korean about positions, P&L, why the engine is waiting and how often a target edge has appeared in history. The wait estimate includes a probability and a median wait. Chat drafts all user order types, including each leg of a rebalance.
  • Settings and what-if backtests. Ask to change position size, trade frequency, risk appetite or target assets. Before showing a numeric auto-gap proposal, the agent requests a replay of both settings on the same history through the live decision code. When results are available, the card compares current and proposed P&L before gas and sell counts. You can ask for the comparison alone or apply the proposal with one click. Asset on/off switches skip replay. On-chain limit proposals go to the owner panel for a MetaMask signature.
  • AI review. Every hour, and after a sharp exchange move, a large gap, a new fill or a position held for 24 hours, the AI reviews a snapshot of markets, opportunities, positions and the engine’s decisions. Each review gives a risk level, observations and up to three suggestions in all three languages. Numeric suggestions carry the same backtest or show that it was unavailable. The log records a SHA-256 hash of the input.
  • Autopilot within limits. Off by default. When enabled, it may apply review suggestions within fixed ranges, such as 60–300 bps for entry and 20–50 USDT per clip. All suggestions for one asset are replayed together against the current settings, and a combined loss of more than 0.5 USDT blocks all of them. A single in-range suggestion still applies if the replay is unavailable. Autopilot can switch an asset off but cannot turn it on. Switching off stops new entries; open positions keep their stop-loss and exit rules.
  • Opportunity radar. It ranks executable buy and sell edges on the three main pools. Every 10 minutes it also quotes WHSK/USDT on HSKSwap, DODO, WoofSwap and HyperIndex and checks each quoted cross-DEX round trip after fees and estimated gas. Those routes are watch-only because one contract call trades one whitelisted HSKSwap pool. The radar maps HSKSwap V3 pools by estimated depth and flags pools created in the last 24 hours.
  • MCP for other agents. Claude Desktop, Cursor and other stdio MCP clients can read markets, estimate waits, draft orders and rebalances, run what-if backtests and inspect opportunities. A human confirms drafts under Orders → Pending drafts. The server does not expose cancel_order. MCP setup and tool list

The dashboard speaks all three languages. It brings together markets, the 24-hour gap chart, orders and pending drafts, auto-gap, the fill scoreboard, AI review, opportunity radar, chat, wallet and owner controls.

How Nunchi meets Track 1

Track 1 asks for Where to see it
Monitor markets and analyze on-chain data QuoterV2 pool quotes every 10 seconds, six exchange feeds across the assets, APRO comparisons and a depth-ranked pool directory.
Identify signals and spread opportunities in real time The radar ranks executable main-pool edges and reports watch-only cross-DEX routes after fees and estimated gas.
Execute orders autonomously Smart orders, conditional orders, DCA and confirmed rebalance legs wait for qualifying quotes. Enabled auto-gap trades its own inventory.
Strict risk controls and stop-loss rules Exchange-triggered and trailing stops, reference and loss checks, kill switch, simulation before send and on-chain caps, minimum output and TWAP guard.
Conversational interface for real-time positions and P&L Trilingual chat reads positions, P&L, wait reasons, historical wait estimates and the fill scoreboard.
Adjust position size, trade frequency, risk appetite and target assets Chat proposes clip sizes and caps, cooldowns, entry/exit thresholds and asset switches. The review can suggest changes, backed by replay when available, and optional autopilot can apply them within bounds.

Evidence

15-day intensive study (2026-11-11 → 2026-11-26, 10-minute samples)

Measured pool lag. We compared 2,132 on-chain samples with Binance for WETH and WBTC and Gate for WHSK. At the time, the three HSKSwap V3 pools held about $828k (WHSK), $90k (WBTC) and $83k (WETH). Pool prices changed only a few times a day.

Pool Median absolute gap vs exchange Share of time gap > 1% Typical gap when another trader corrected it
WBTC/USDT 1.34% 62% ~3.5%
WETH/USDT 0.76% 36% ~2.4%
WHSK/USDT 0.50% 8.5% ~1.9%

Smart orders · replay. We started $100 orders every 4 hours with a 24-hour horizon and enabled a final attempt at the deadline. Every order had a fill. A positive edge means the fill beat the exchange price at that moment. The improvement column compares mean edges for Nunchi and an immediate swap.

Asset / side Agent edge Immediate swap edge Improvement
WETH buy +0.31% −0.68% ~+0.99%
WETH sell +0.60% −0.37% ~+0.97%
WBTC buy +0.09% −0.40% ~+0.49%
WBTC sell +0.09% −0.60% ~+0.69%
WHSK buy +0.01% −0.43% ~+0.44%
WHSK sell +0.34% −0.21% ~+0.55%

Lag-aware stop-loss · replay. The exchange fell more than 1.5% in an hour. Both sell prices below are measured against the exchange price at the trigger. The comparison uses the pool’s first catch-up quote or the six-hour observation if it stayed behind.

Asset Events Sell on the lagging pool at trigger Wait for the pool
WETH 18 +0.98% −0.54%
WBTC 13 +1.25% −0.32%

Auto-gap mode · replay. Each asset started with a $100 budget. The 15-day totals are before about $0.60 of estimated gas. Open inventory is marked at the final exchange reference.

Assets Total P&L From capturing gaps From price moves while holding
WETH + WBTC + WHSK +$17.64 +$27.80 −$10.16

Lowering the take-profit threshold from +0.8% to 0 or −0.3% moved WETH sells from 20 to 22–28 in 15 days. Combined P&L stayed in the +$17 to +$20 range in that comparison. Study methods and results

Extended replay (WHSK 2026-04-20 → 2026-11-27; WETH and WBTC 2026-06-05 → 2026-11-27; 10-minute samples)

The history starts at pool creation on 2026-01-30 for WHSK and 2026-04-21 for WETH and WBTC. Before the replay start dates above, a $100 swap often cost more than 1% of the pool mid in fees and price impact. Smart orders and stops also exclude the week of 2026-10-10 to 2026-10-16, when all three pools lost most of their liquidity.

Pool Median gap vs exchange Median absolute gap Samples with absolute gap > 1% Pool-mid changes per day
WETH −0.09% 0.28% 23.5% 16.3
WBTC −1.57% 2.16% 68.5% 1.8
WHSK (MEXC) +0.04% 0.31% 3.9% 17.0

We count pool-mid changes between consecutive samples within each usable segment and divide by the elapsed days from the first usable sample to the last, including the October outage.

Smart orders

We started a $100 order every four hours within each usable segment, with a 24-hour horizon and a final attempt at the deadline. Edges are compared only for orders with a fill.

Asset / side Orders (with a fill) Nunchi edge Immediate swap edge Improvement Months positive
WHSK buy 1,279 (1,279) −0.17% −0.47% +0.30 pp 8/8
WHSK sell 1,279 (1,278) −0.08% −0.45% +0.37 pp 8/8
WETH buy 1,004 (1,004) +0.69% +0.32% +0.37 pp 6/6
WETH sell 1,004 (969) −0.53% −0.85% +0.32 pp 6/6
WBTC buy 1,004 (1,004) +3.32% +3.10% +0.22 pp 5/6
WBTC sell 1,004 (921) −1.86% −2.14% +0.28 pp 5/6

Comparing the same orders, timing beat an immediate swap on average for every asset and side, and in 38 of 40 asset-side-months.

WBTC traded at a persistent discount to Binance (median 1.6%), and its pool mid changed about twice a day. Most WBTC buys filled immediately at the same price as the immediate swap (54% ties), so the buy edges mostly reflect that discount.

Lag-aware stop-loss

Asset Events Sell on the lagging pool at trigger Wait for the pool
WHSK 84 +0.23% −0.35%
WETH 71 −0.46% −1.14%
WBTC 42 −1.24% −1.97%

When the exchange fell 1.5% in an hour, a sale quoted on the lagging pool at the trigger beat waiting for the pool by 0.6–0.7 percentage points on all three assets. Both edges use the exchange price at the trigger. These are quotes, not simulated stop orders: a live stop sells only while the pool's bid is within its price limit (by default no more than 1% below the exchange) and expires after a 15-minute window.

Auto-gap mode

Each asset started flat with 100 USDT, a 50 USDT clip and 80 bps entry and take-profit thresholds. Auto-gap ran continuously through the October outage. Amounts are in USDT.

Asset Period (2026) Buys / sells Total P&L From capturing gaps From price moves while holding Max drawdown
WHSK 04-20 → 11-27 55 / 62 +$14.26 +$32.03 −$17.77 $15.45
WETH 06-05 → 11-27 72 / 70 +$47.61 +$35.72 +$11.89 $9.32
WBTC 06-05 → 11-27 48 / 51 +$29.67 +$14.78 +$14.89 $9.08
Combined — 175 / 183 +$91.54 +$82.53 +$9.01 —

Gap capture was positive on every asset. WHSK made +$14.26 while HSK fell 51%. The totals are before about $2.90 in estimated gas for 358 fills at about $0.008 each, the rate used in the 15-day study.

Coverage and replay assumptions

  • We used five-minute Binance closes for ETH and BTC and five-minute MEXC closes for HSK. Gate’s archived HSK bars were hourly until 2026-10-24 11:00 UTC. A reference up to an hour old made the WHSK pool look cheap during HSK’s decline, and auto-gap lost $45.11 with Gate. With Gate, smart-order improvements rose to 0.58 pp on both sides. A sale quoted at the stop trigger still beat waiting (+0.31% vs −0.02%). The live engine requires exchange quotes no older than 15 seconds.
  • The replay uses the engine’s decision code and the active liquidity recorded at each block. Quotes include the 0.3% fee and price impact. Simulated fills leave the historical pool price path unchanged. Results are before gas.
  • The default settings came from the 15-day November study, which falls within this window. The results show the historical direction of the effect and have limited value as a forecast.
  • The 15-day November study showed larger timing gains, with larger median absolute gaps for WETH and WHSK. Gains varied by month, which is why AI review and chat backtests recheck settings through the latest sample in the selected history. Monthly results and methods

Run from engine/. To repeat either comparison with Gate, append --whsk-reference gate.

node src/replay/run.ts --asset all --side both --data-dir ../research/data/extended --usable-only --worst-bps -1000 --force-at-deadline --lag-stats
node src/autogap/replay.ts --asset all --data-dir ../research/data/extended --usable-only

Mainnet live, read-only (shadow)

Simulated fills. Auto-gap completed one round trip each on WBTC and WETH, 80 USDT per asset. WBTC bought on 2026-11-26 at +2.36% and +2.44% edge against the exchange and, after the 24-hour hold, sold on 2026-11-27 at −0.11% and −0.27%. WETH bought on 2026-11-27 at +1.14% and +1.00%. When ETH fell later that day, its stop-loss fired and sold into the lagging pool at +1.49% and +1.35%, above the exchange price. The eight fills captured +3.76 USDT of edge, but ETH fell about 4.5% and BTC about 3% while held, so realized P&L was −2.41 USDT before gas. This is why the scoreboard reports edge and inventory drift separately.

Opportunity radar, 2026-11-27. The read-only scan found 18 HSKSwap V3 pools. Only three had substantial priced depth (WHSK ~$835k, WBTC ~$91k and WETH ~$85k). The smaller WHSK venues held only ~$70–$490 each. At the tested sizes of 1, 5 and 20 USDT, no quoted cross-DEX round trip was profitable after fees and estimated gas. That is why Nunchi trades the main pools against the exchange lag. Recorded pool balances · Read-only scan script

Mainnet fork

On local forks at HSK blocks 30,679,016 and 30,687,702, the rehearsal deployed AgentExecutor, funded it with 100 USDT and confirmed a 20 USDT WETH buy through the API. The engine sent the swap and received 0.011761 WETH (about 1,700 USDT/ETH). The script checked the receipt, gas, fee, Executed event and decision hash against the scoreboard. Fork rehearsal

On the second fork the owner paused trading from the dashboard, observed CONTRACT_PAUSED, resumed, deposited 10 USDT and withdrew 5 USDT back to the owner.

Mainnet live

Public deployment and transaction evidence is pending. The Contracts table below reserves space for the verified address and explorer link.

Tests

  • The contract suite includes 34 unit and fuzz tests plus 8 mainnet-fork tests against HSKSwap pools and QuoterV2.
  • The engine suite includes 322 offline tests covering decisions, chat and review, autopilot bounds, rebalancing, radar and MCP.

Architecture and safety

Live user order · Draft → human confirmation → qualifying pool quote → eth_call → operator signature → AgentExecutor → fill scoreboard.

The Node 24 / TypeScript engine selects clips and the operator signs live swaps. The AI has no tool to confirm an order, sign or send. The engine validates changes from chat or autopilot with the same checks as the dashboard. Architecture and order flow

  • Contract limits. The non-upgradeable AgentExecutor accepts only whitelisted pools, caps each trade and daily activity, checks the minimum output and enforces a time-weighted average price (TWAP) guard. It supports pausing and restricts withdrawals to the owner.
  • Owner controls. The owner reviews and signs pause/resume, limit changes, deposits and withdrawals in MetaMask. The operator key can trade within those limits and pause trading. It cannot withdraw funds.
  • Oracle access. APRO rejects contract reads from addresses outside its allowlist (No access). The contract’s oracle guard is off by default. The engine records APRO prices off-chain alongside the exchange comparison when readings are available.

Contracts

Network AgentExecutor Verification
HSK Chain mainnet (177) [deployed 2026-11-28] [Blockscout link]

HSK testnet has no HSKSwap pools. Trading rehearsals use a local mainnet fork.

Run it (Windows PowerShell)

Use Node 24 and, for the contracts, Foundry 1.10+. To enable chat and AI review, copy .env.example to .env at the repository root and set OPENAI_API_KEY. The execution engine and MCP server can run without this key.

cd engine
npm.cmd install
node --test "test/**/*.test.ts"
node src/runner/run.ts --mode shadow     # http://127.0.0.1:8787/

For a multi-day shadow run, use the restart script below in place of the runner command. Run the replays separately from the same directory to reproduce the 15-day comparison.

powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\run-forever.ps1
node src/replay/run.ts --asset all --side both --data-dir ../research/data --worst-bps -1000 --force-at-deadline
node src/autogap/replay.ts --asset all --data-dir ../research/data

AI review defaults to 60 minutes. Set AI_REVIEW_MINUTES to change the interval or AI_REVIEW=off to disable reviews. Shadow reviews are stored in engine/data/state/reviews.jsonl. Run the contract tests from a fresh shell at the repository root.

cd contracts
forge test --no-match-path "test/fork/*"
$env:HSK_RPC_URL="https://mainnet.hsk.xyz"
forge test --match-path "test/fork/*"

For live setup, operator key generation and deployment, see the engine runbook and contract runbook.

Limitations

  • The 15-day replay uses 10-minute samples, assumes healthy external risk checks and leaves the subsequent pool price path unchanged after a simulated fill. Gas is excluded. Stop-loss event counts are small.
  • Other traders can close the gap first. Waiting can lead to a partial fill, expiry or a worse outcome. WETH and WBTC pool depth was around $40k per side in the study, so the $50–100 clip sizes matter.
  • The configured TWAP guard can delay even an urgent stop when the pool moves more than 300 ticks (about 3%) from its 10-minute average. If simulation catches the rejection, the engine spends no gas on that swap.
  • AI suggestions can misread market conditions. Backtests reflect the selected history. Human review, engine checks, autopilot bounds and contract caps each limit different parts of the process.

Roadmap

  • Seek APRO allowlisting so the contract can check the oracle on-chain.
  • Research internal crossing between user orders and auto-gap inventory, and hedging for open inventory.

Team

Wayde (@WaydeWan), yigel124 and Yiping-Yin. DoraHacks team

License

MIT

About

Nunchi: an AI execution agent for HSK Chain that times trades to HSKSwap's lag behind the exchanges. Built for the HSK Chain Horizon Hackathon (Seoul), Track 1.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages