股票除息合理价差与动态回归网格 v4.0
Fair-Spread Dividend Arbitrage & Dynamic Mean-Reversion Grid v4.0 · Cross-Exchange Stock Perpetual Arbitrage
Risk warning: This is a cross-exchange hedging strategy that supports both FMZ native sandbox trading (live market-data simulation) and live execution, with no hard percentage stop-loss. Trading cross-exchange stock perpetuals carries risks including thin orderbooks and wide bid-ask spreads, severe negative Hyperliquid funding rates eroding returns, single-leg execution exposure if the hedge leg fails, extreme price dislocations at ex-dividend timestamps, external calendar feed delays, and exchange rule changes or halts. Estimated net P&L displayed on the dashboard includes unrealized mark-to-market spread and does not represent settled profit. Before running live, verify that exchanges[0] (Binance Futures) and exchanges[1] (Hyperliquid) are bound in the exact order, ensure sufficient margin on both venues, and test the full flow in FMZ sandbox mode first.
Strategy Concept
The strategy exploits ex-dividend settlement asymmetries between Binance TradFi stock perpetuals and Hyperliquid HIP-3 (xyz) stock perpetuals, automatically scanning overlapping tickers and executing a "Long Binance + Short Hyperliquid xyz" hedged grid:
- Dividend-anchored fair discount ceiling prevents chasing. At the ex-dividend timestamp, Binance TradFi perpetuals settle a
Specialfunding payment from shorts to longs, keeping long equity neutral; Hyperliquidxyzperpetuals pay no dividend and drop directly with spot. The strategy deducts expected holding-period fundingF, round-trip fees and slippageC, and minimum safety marginpMinEdgeBpsfrom the dividend yieldYto compute aFair Ceilingand real-timeNet Edge, blocking entries when discounts or negative funding are excessive. - 5-minute K-line regression timing and dynamic lot splitting. Before opening, the strategy backfills 6 hours of 5-minute K-lines across both venues to compute the historical discount median
μ, standard deviationσ, 10th–90th percentile bandW, andZ-Score. Initial base lots only open when statistical samples are ready and the discount sits in a favorable entry zone, splitting the per-ticker budget (default1000 U) into multiple lots aligned to both exchanges' joint quantity step. - Dual-track grid before ex-dividend and convergence exit afterward. With a Long BN + Short
xyzposition, narrower discounts trigger dip-adding to widen the cross-dividend buffer, while sudden discount widening triggers profit-taking on the lowest-discount lot after L2 VWAP net-profit verification—always retaining at least one base lot across the ex-dividend event. Post-dividend, all remaining lots close once the spread converges into[-3 bp, pExitSpreadBps]or hitspMaxHoldAfterHours.
The strategy operates strictly as a directional cross-exchange hedge (Long Binance + Short Hyperliquid xyz); it never reverses direction and does not guarantee grid exits prior to ex-dividend.
Cross-Exchange Interface and Execution Architecture
Built exclusively on standard FMZ trading/precision APIs and public REST endpoints—avoiding non-standard exchange.IO("api", ...) calls—the strategy persists all positions, grid ledgers, and settlement history under _G('fmz-div-arb-grid-v4'):
- Global dividend discovery and market-wide scanning: Polls Binance
exchangeInfo/premiumIndexand HyperliquidmetaAndAssetCtxs(dex: "xyz") to map 100+ overlapping stock/ETF perpetuals. Every 4 hours it syncs 10-day Nasdaq calendars (merging same-day Regular + Special payouts), TradingView Global/Korea Scanners (mapping Korean equities such as000660 -> SKHY), and Yahoo Finance dividend cadence hints. - 5m K-line backfill and L2 VWAP depth verification: Backfills 5m candles from public endpoints to build regression bands. Every open, grid add, and automatic take-profit fetches 20-level orderbooks (
depth/l2Book) to compute exact-quantity VWAP fills, preventing mark-price phantom triggers from executing at a loss. - Standard FMZ pair binding and precision sync:
bindPair(ticker)follows the standard FMZ sequence—callingSetCurrency(TICKER_USDTon BN,xyz:TICKER_USDCon HL) followed bySetContractType("swap"), readingPricePrecisionandAmountPrecision, and applyingSetPrecision—making the code identically compatible with FMZ sandbox and live trading. - HL-first, BN-hedge two-leg execution: Posts a slightly aggressive limit order on Hyperliquid
xyz(avgPx * 0.997for shorts,avgPx * 1.004to close), pollsGetOrderfor up to2.4s, cancels any remainder viaCancelOrder, and immediately hedges the exactfilledQtyon Binance via market order (-1). Any BN hedge failure logs a single-leg risk alert and aborts. - Interactive UI and status dashboard: Renders a 4-tab
LogStatusdashboard (Overview & Grid Plan, Spread Monitoring, Positions & Ledger, Controls & Logs) alongsideAppKitlive subscriptions, and reports settled equity viaLogProfit.
Configure two FMZ exchange objects: exchanges[0] = Futures_Binance and exchanges[1] = Futures_Hyperliquid (select FMZ simulated exchanges for live-data sandbox testing, or real accounts for live trading).
Trading Workflow
text
Configure exchanges[0]=Futures_Binance and exchanges[1]=Futures_Hyperliquid with budget & risk parameters
↓
Verify 2 exchanges → Scan overlapping BN × HL xyz contracts → Sync Nasdaq / TradingView / Yahoo calendars
↓
Backfill 5m spread K-lines for event pool → Compute Fair Ceiling, median μ, dynamic step, and lot sizes
↓
Net Edge & regression entry criteria met → Check L2 orderbook VWAP → Execute base lot (1/N) on HL + BN
↓
Monitor open positions: accrue hourly HL/BN funding → Check discount-widening TP & dip/mean-reversion adds
↓
Reach ex-dividend timestamp → Query BN Special funding rate (fallback to dividend ratio) → Credit payout
↓
Post-dividend spread converges into [-3bp, pExitSpreadBps] (after 5m cooldown) or times out → Close all lots
↓
Update cumulative net P&L and call LogProfit → Release slot for next opportunity
Initial Entry and Lot Sizing
When an event has hoursToEx > 0.05, divBps >= pMinDivBps, netEdgeBps >= pMinEdgeBps, xyz 24h volume >= pMinXyzVolUsd, and at least 12 5m samples, the strategy computes:
dynStepBps = max(costFloor, baseCost + carry4hBps + pMinGridNetBps, ampBps * 0.35, stdBps * 1.1)
where baseCost = 2 * pFeeBps + pSlipBps and costFloor = baseCost + pMinGridNetBps. Budget allocation dynLots scales with edge headroom and volatility amplitude (bounded by pMinLotUsd and pGridLots), and alignContractQty aligns quantities to the coarser step size of the two venues. Once the discount enters the regression buy zone and open tickers are below pMaxOpen, the base lot opens automatically.
Pre-Dividend Dynamic Grid and VWAP Take-Profit
Between entry and ex-dividend settlement, the Long BN + Short xyz position follows two exact rules:
- Discount-widening take-profit: When holding
> 1lot and the spread widens by>= max(step * 0.85, baseCost)above the lowest-discount lot, the strategy previews closing that lowest-discount lot against live L2 orderbooks and executes only if net profit after fees>= notional * pMinGridNetBps / 10000, always preserving at least one base lot for the dividend. - Controlled two-way grid additions: If the discount narrows by
>= step * 0.75below the lowest held lot, a dip-add increases the cross-dividend buffer; if>= 6hremain before ex-dividend withnetEdgeBps >= max(pMinEdgeBps * 1.6, step)and widening>= step, a mean-reversion add is allowed.
Dividend Settlement and Post-Dividend Exit
At the UTC ex-dividend hour (pDstUtcHour, default 1 for US winter time / 09:00 UTC+8), the strategy checks Binance fundingRate for the Special settlement and credits the payout. To avoid selling into the initial negative-discount dump caused by BN longs closing at market, exits require the spread to settle into <= pExitSpreadBps (default 15 bp) and >= -3 bp (or after a 5-minute cooldown), with a hard timeout exit at pMaxHoldAfterHours (default 3h) followed by LogProfit.
Fees and Cost Conditions
Both entry qualification and grid take-profit floors enforce round-trip fees, slippage, and holding funding costs:
Round-trip base cost costBps = 2 × pFeeBps + pSlipBps
Grid take-profit step floor costFloor = costBps + pMinGridNetBps
Fair discount ceiling fairCeilingBps = Dividend Y - Est. Funding F - costBps - pMinEdgeBps
Current net edge netEdgeBps = Dividend Y - Current Discount S - Est. Funding F - costBps
With default parameters (pFeeBps = 9.5, pSlipBps = 5, pMinGridNetBps = 8, pMinEdgeBps = 25):
- Round-trip base cost is
9.5 × 2 + 5 = 24 bps; - Minimum grid take-profit step is
24 + 8 = 32 bps, subject to live L2 VWAP net profit>= 8 bps; - Expected negative Hyperliquid funding or positive Binance funding over remaining hours (capped at
72h) is automatically deducted fromfairCeilingBpsandnetEdgeBps.
Live Configuration
Complete the following before starting:
- Add 2 FMZ exchange objects:
exchanges[0]bound toFutures_Binanceandexchanges[1]bound toFutures_Hyperliquid; - Sandbox vs. live execution: The strategy contains no internal paper-trading toggle—select FMZ's built-in simulated exchanges under Add Robot -> Trading Configuration to run with live market data (each robot acts as an isolated account, and on-chain venues support custom RPCs), or bind real exchange accounts for live trading;
- Ensure the FMZ node can reach
fapi.binance.com,api.hyperliquid.xyz,api.nasdaq.com,scanner.tradingview.com, andquery1.finance.yahoo.com; - Maintain adequate USDT / USDC margin on both venues to prevent single-leg hedge failures during concurrent grid additions.
Main Live Parameters
| Parameter | Identifier | Default | Purpose |
|---|---|---|---|
| Enable auto open / grid | pAutoTrade | On | Automatically opens qualified dividend events and manages grid adds/exits. |
| Budget per ticker (USDT) | pNotional | 1000 | Maximum hedged notional per stock/ETF (40–500000). |
| Max concurrent tickers | pMaxOpen | 3 | Maximum number of simultaneous open ticker positions (1–20). |
| Enable regression grid | pGridEnabled | On | Splits budget into dynamic grid lots before ex-dividend while keeping a base lot. |
| Max grid lots (0=auto) | pGridLots | 0 | 0 for dynamic planning based on edge and volatility; >0 caps lot count (0–20). |
| Min lot size (USDT) | pMinLotUsd | 50 | Minimum notional per grid lot to stay above exchange minimums (10–10000). |
| Fallback grid step (bps) | pGridStepBps | 30 | Baseline grid spacing fallback (5–500). |
| Min grid net profit (bps) | pMinGridNetBps | 8 | Minimum L2 VWAP net profit after fees required for auto grid exits (1–200). |
| Min dividend yield (bps) | pMinDivBps | 35 | Minimum dividend yield threshold to qualify (5–2000). |
| Min net edge (bps) | pMinEdgeBps | 25 | Minimum net arbitrage edge after discount, funding, fees, and slippage (1–1000). |
| Min xyz 24h volume (USD) | pMinXyzVolUsd | 100000 | Filters out illiquid Hyperliquid xyz contracts (0–100000000). |
| Post-div target spread (bps) | pExitSpreadBps | 15 | Target convergence spread to close all lots after ex-dividend (0–200). |
| Max post-div hold (hours) | pMaxHoldAfterHours | 3 | Forces full exit after this many hours post-dividend (0.5–48). |
| Round-trip open fee (bps) | pFeeBps | 9.5 | Combined BN + xyz fee per open or close leg pair (0–100). |
| Estimated extra slippage (bps) | pSlipBps | 5 | Conservative slippage buffer included in costBps (0–100). |
| Scan interval (seconds) | pScanSec | 15 | Main loop interval for scanning, evaluation, and position management (5–300). |
| Ex-div settlement UTC hour | pDstUtcHour | 1 | UTC settlement hour: 1 for US winter time (09:00 UTC+8), 0 for summer (08:00). |
All 17 parameters are listed above; interactive controls in the status panel and AppKit frontend also support pausing/resuming entries, manual rescans, calendar syncs, per-ticker open/reduce/close, and close-all commands.
Operating Notes
- Strict exchange order:
exchanges[0]must beFutures_Binanceandexchanges[1]must beFutures_Hyperliquid; swapping them causes contract-binding errors or inverted fills. - Single-leg execution exposure: Orders execute on Hyperliquid
xyzfirst and hedge filled quantities on Binance at market. Unfilled HL orders are cancelled cleanly, but if HL fills and the BN hedge fails due to margin or rate limits, the strategy logs a single-leg alert and halts that action for manual intervention. - Non-US settlement timing: Non-US equities discovered via TradingView (such as Korean
SKHY) may have ex-dividend cutoff times or DST rules differing frompDstUtcHour; verify event countdowns before entry. - Thin orderbook spreads: Lower-volume
xyzstock perpetuals can have8–10 bpbid-ask spreads; raisepMinXyzVolUsdandpMinGridNetBpsappropriately for larger capital sizes. - Pre-dividend funding spikes: Hourly negative funding on
xyzcan exceed-1 bp/hin the final hours before ex-dividend; monitor accrued funding and estimated net P&L on the dashboard. - Saved state reconciliation: Positions persist under
_G('fmz-div-arb-grid-v4'). If you manually close positions on the exchange, clear the bot's state viaclose:TICKERorcloseAllto prevent stale funding accrual or duplicate closes.
// FMZ JavaScript: Binance × Hyperliquid xyz · 股票除息套利与动态价差网格 v4.0(FMZ 原生模拟盘 / 实盘统一版)
// 说明:已移除内置纸面模拟逻辑,统一通过 FMZ 标准交易接口 (SetCurrency / SetContractType / SetPrecision / Buy / Sell / GetOrder) 下单,
// 可直接在 FMZ 创建机器人时勾选【模拟盘】使用实盘行情撮合,或直接运行实盘,不使用底层 IO('api', ...) 接口。
// 核心逻辑:
// 1) 股息锚定合理价差:以每股股息率 Y 扣除预期持有期双所资金费 F 与双边摩擦成本 C,计算【理论合理贴水上限 (Fair Ceiling)】与【统计回归中枢 (Regression Center μ)】;
// 2) K线回补统计价差回归:自动回补两所 5m K 线,统计历史价差中位数 μ、标准差 σ、10%~90% 波动带宽 W 及当前 Z-Score 偏离度,杜绝零样本盲目抢跑;
// 3) 严格的合约与每格金额分配:按双所最小下单步长(stepSize/szDecimals)、最小名义金额及股息安全垫,将单标的预算拆分为【跨除息底仓 + 多层回归网格仓】,对齐双腿完全等量合约张数,杜绝 1/1 份一把打满;
// 4) 价差偏离建仓 & 回归止盈:贴水达到回归入场轨才建首份底仓,贴水按轨道继续走阔逐级加仓,贴水向中枢回归收窄逐格止盈落袋,始终保留底仓跨除息收取 Special 分红。
function setting(raw, label, min, max, integer) {
let value = Number(raw);
if (raw === null || String(raw).trim() === '' || !Number.isFinite(value) || value < min || value > max || (integer && !Number.isInteger(value))) {- 1