Type/to search

股票除息合理价差与动态回归网格 v4.0

Common strategy
Created: 2026-11-27 13:24:41
Last modified: 20 hours ago
2
Follow
559
Followers

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 Special funding payment from shorts to longs, keeping long equity neutral; Hyperliquid xyz perpetuals pay no dividend and drop directly with spot. The strategy deducts expected holding-period funding F, round-trip fees and slippage C, and minimum safety margin pMinEdgeBps from the dividend yield Y to compute a Fair Ceiling and real-time Net 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 band W, and Z-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 (default 1000 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 xyz position, 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 hits pMaxHoldAfterHours.

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'):

  1. Global dividend discovery and market-wide scanning: Polls Binance exchangeInfo/premiumIndex and Hyperliquid metaAndAssetCtxs (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 as 000660 -> SKHY), and Yahoo Finance dividend cadence hints.
  2. 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.
  3. Standard FMZ pair binding and precision sync: bindPair(ticker) follows the standard FMZ sequence—calling SetCurrency (TICKER_USDT on BN, xyz:TICKER_USDC on HL) followed by SetContractType("swap"), reading PricePrecision and AmountPrecision, and applying SetPrecision—making the code identically compatible with FMZ sandbox and live trading.
  4. HL-first, BN-hedge two-leg execution: Posts a slightly aggressive limit order on Hyperliquid xyz (avgPx * 0.997 for shorts, avgPx * 1.004 to close), polls GetOrder for up to 2.4s, cancels any remainder via CancelOrder, and immediately hedges the exact filledQty on Binance via market order (-1). Any BN hedge failure logs a single-leg risk alert and aborts.
  5. Interactive UI and status dashboard: Renders a 4-tab LogStatus dashboard (Overview & Grid Plan, Spread Monitoring, Positions & Ledger, Controls & Logs) alongside AppKit live subscriptions, and reports settled equity via LogProfit.

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 > 1 lot 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.75 below the lowest held lot, a dip-add increases the cross-dividend buffer; if >= 6h remain before ex-dividend with netEdgeBps >= 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 from fairCeilingBps and netEdgeBps.

Live Configuration

Complete the following before starting:

  • Add 2 FMZ exchange objects: exchanges[0] bound to Futures_Binance and exchanges[1] bound to Futures_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, and query1.finance.yahoo.com;
  • Maintain adequate USDT / USDC margin on both venues to prevent single-leg hedge failures during concurrent grid additions.

Main Live Parameters

ParameterIdentifierDefaultPurpose
Enable auto open / gridpAutoTradeOnAutomatically opens qualified dividend events and manages grid adds/exits.
Budget per ticker (USDT)pNotional1000Maximum hedged notional per stock/ETF (40–500000).
Max concurrent tickerspMaxOpen3Maximum number of simultaneous open ticker positions (1–20).
Enable regression gridpGridEnabledOnSplits budget into dynamic grid lots before ex-dividend while keeping a base lot.
Max grid lots (0=auto)pGridLots00 for dynamic planning based on edge and volatility; >0 caps lot count (0–20).
Min lot size (USDT)pMinLotUsd50Minimum notional per grid lot to stay above exchange minimums (10–10000).
Fallback grid step (bps)pGridStepBps30Baseline grid spacing fallback (5–500).
Min grid net profit (bps)pMinGridNetBps8Minimum L2 VWAP net profit after fees required for auto grid exits (1–200).
Min dividend yield (bps)pMinDivBps35Minimum dividend yield threshold to qualify (5–2000).
Min net edge (bps)pMinEdgeBps25Minimum net arbitrage edge after discount, funding, fees, and slippage (1–1000).
Min xyz 24h volume (USD)pMinXyzVolUsd100000Filters out illiquid Hyperliquid xyz contracts (0–100000000).
Post-div target spread (bps)pExitSpreadBps15Target convergence spread to close all lots after ex-dividend (0–200).
Max post-div hold (hours)pMaxHoldAfterHours3Forces full exit after this many hours post-dividend (0.5–48).
Round-trip open fee (bps)pFeeBps9.5Combined BN + xyz fee per open or close leg pair (0–100).
Estimated extra slippage (bps)pSlipBps5Conservative slippage buffer included in costBps (0–100).
Scan interval (seconds)pScanSec15Main loop interval for scanning, evaluation, and position management (5–300).
Ex-div settlement UTC hourpDstUtcHour1UTC 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

  1. Strict exchange order: exchanges[0] must be Futures_Binance and exchanges[1] must be Futures_Hyperliquid; swapping them causes contract-binding errors or inverted fills.
  2. Single-leg execution exposure: Orders execute on Hyperliquid xyz first 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.
  3. Non-US settlement timing: Non-US equities discovered via TradingView (such as Korean SKHY) may have ex-dividend cutoff times or DST rules differing from pDstUtcHour; verify event countdowns before entry.
  4. Thin orderbook spreads: Lower-volume xyz stock perpetuals can have 8–10 bp bid-ask spreads; raise pMinXyzVolUsd and pMinGridNetBps appropriately for larger capital sizes.
  5. Pre-dividend funding spikes: Hourly negative funding on xyz can exceed -1 bp/h in the final hours before ex-dividend; monitor accrued funding and estimated net P&L on the dashboard.
  6. 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 via close:TICKER or closeAll to prevent stale funding accrual or duplicate closes.
Source
JavaScript
// 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))) {
Strategy parameters
Strategy parameters
启用自动开仓/网格
单标的总预算(USDT)
最大同时持仓标的数
启用价差回归滚动网格
网格份数上限(0=自动动态规划)
单格最低名义金额(USDT)
备用基础格距(bps)
每格减仓最低净利(bps)
最低股息率门槛(bps)
最低净套利空间(bps)
xyz最低24h成交额(USD)
除息后目标收敛价差(bps)
除息后最长持仓(小时)
双边单次开仓手续费(bps)
预估额外滑点(bps)
行情扫描间隔(秒)
除息结算UTC小时
Comment
All comments (0)
No data
No data
  • 1
Forums
PINE Language
Get the app
iPhone Download
© 2015 - ∞ INVENTOR PTE LTD (SG)