Forecasting Funding Rates for Crypto Perpetual Futures
A funding-rate forecasting system estimates whether the next perpetual-futures funding payment is likely to persist, flip, or become too crowded to trade. The practical goal is not to chase yield mechanically. It is to forecast funding and basis risk, subtract execution costs, then decide whether a hedged spot-perp carry trade should be paper-tested, skipped, reduced, or eventually executed under strict controls.
Article Status
This article is engineering research and implementation guidance, not financial, investment, legal, tax, or compliance advice. Funding carry is not risk-free: basis can widen, funding can flip, margin can deteriorate, and exchange rules can change.
Quick Read
- The theory: Perpetual futures stay near an index through recurring funding payments, but the expected payment is only one part of the trade. Pricing bounds also depend on transaction costs, funding formulas, clamps, and margin risk. Sources: [HMRV2022] [AHJ2024] [DLY2025]
- The forecast: The research question is whether next funding, funding sign persistence, and post-funding markout can be forecast better than no-change and EWMA baselines using premium, open interest, taker flow, liquidations, and order flow. Sources: [INAN2025] [BEHAVIOR2023] [RUAN2022]
- The path: Start with public funding snapshots, mark/index prices, order books, and positioning data. Add a paper carry simulator before private state, and use tiny live pilots only after actual funding payments and hedge drift reconcile correctly. Sources: [BINANCE_MARK] [BINANCE_FUNDING] [BINANCE_OPEN_INTEREST] [BINANCE_ORDER]
Theory And Hypothesis
- Funding is a cash flow, not free yield: Positive funding usually means longs pay shorts, while negative funding usually means shorts pay longs. A hedged carry trade can still lose if basis widens, fees dominate, margin is stressed, or the mark price moves against the futures leg. Sources: [HMRV2022] [AHJ2024] [YANG2025]
- A forecast is separate from a trade: The model should forecast market variables: next funding, sign probability, persistence, basis widening risk, and post-funding adverse markout. The strategy then decides whether those forecasts survive executable costs and risk gates. Sources: [INAN2025] [RUAN2022]
- Funding-cycle windows can be adverse: A trade can receive funding and still lose through bad entry timing or adverse selection around the settlement window. The system should test entry windows separately rather than always entering just before funding. Sources: [RUAN2022] [AHJ2024]
- Positioning context matters: Open interest, long/short ratios, taker buy/sell volume, and liquidation flow help distinguish persistent demand from crowded trades that may unwind before or after funding. Sources: [BEHAVIOR2023] [BINANCE_OPEN_INTEREST_STATS] [BINANCE_LONG_SHORT]
- Exchange methodology is part of the model: Funding intervals, caps, clamps, premium-index formulas, mark prices, settlement timing, and account modes differ by venue and symbol. The article uses Binance USD-M as a concrete example, but the system should keep exchange rules behind adapters. Sources: [BINANCE_MARK] [BINANCE_FUNDING] [AHJ2024]
For liquid perpetuals such as Binance BTCUSDT, the next funding payment and its persistence may be forecast better than no-change baselines using current funding, perp-index basis, spot-perp basis, open-interest change, taker buy/sell volume, long/short ratios, liquidation flow, and order-book state. A carry candidate is only useful if expected net funding and basis convergence exceed spot and futures costs, hedge drift, margin buffers, and post-funding markout risk.
- Forecast: Predict next funding bps, sign, persistence, and magnitude bucket at 4 h, 2 h, 1 h, 30 min, and 10 min before funding.
- Carry: Evaluate long spot plus short perp markout through funding, separating funding PnL, basis PnL, fees, slippage, and hedge drift.
- Robustness: Walk forward by symbol and regime, compare against no-change, rolling mean, and EWMA baselines, and reject models that decay quickly.
- Safety: Block on stale funding snapshots, funding flips, basis stress, private-state mismatch, margin pressure, or unsettled leg state.
Research Evidence
- Perpetual futures create recurring funding cash flows that can generate implied carry, but the trade remains exposed to basis and margin risk. Model funding PnL, basis PnL, and liquidation distance separately rather than treating the quoted funding rate as yield. Sources: [HMRV2022] [YANG2025]
- No-arbitrage bounds for perpetuals depend on funding formulas, clamps, and transaction costs. Read exchange methodology before building a generalized signal; a forecast from one venue or symbol may not transfer. Sources: [AHJ2024] [DLY2025] [BINANCE_MARK]
- Recent funding-rate research reports out-of-sample predictability but emphasizes time-varying stability. Use rolling validation, baselines, confidence decay, and forecast-error monitors as first-class system components. Sources: [INAN2025]
- Funding cycles can interact with liquidity and adverse selection. Test entry and exit windows around funding settlement. A funding receipt is not enough if post-funding markout is consistently adverse. Sources: [RUAN2022]
- Positioning and trading-behavior data can add context to derivatives predictability. Include open interest, long/short ratios, taker buy/sell volume, and liquidations as feature families. Sources: [BEHAVIOR2023] [BINANCE_OPEN_INTEREST_STATS] [BINANCE_TAKER_VOLUME]
- Binance USD-M exposes the required public market-data surfaces for a concrete worked example. Use mark price and funding streams, funding history, open interest, long/short ratios, taker volume, liquidation streams, depth, and spot hedge data. Sources: [BINANCE_MARK] [BINANCE_FUNDING] [BINANCE_OPEN_INTEREST] [BINANCE_LONG_SHORT] [BINANCE_LIQUIDATIONS]
Worked Example: Binance Funding And Hedge Data
- Mark price and funding snapshot:
GET /fapi/v1/premiumIndex via USDMClient.getMarkPrice()markPrice, indexPrice, lastFundingRate, interestRate, nextFundingTime Core live forecast input. Store snapshots with receive time instead of using only the final settled rate after the fact. Sources: [BINANCE_MARK] [SDK_ENDPOINTS] - Funding history:
GET /fapi/v1/fundingRate via USDMClient.getFundingRateHistory()symbol, fundingRate, fundingTime, markPrice Builds labels, no-change and rolling baselines, persistence features, and funding-calendar checks. Sources: [BINANCE_FUNDING] [SDK_ENDPOINTS] - Mark-price WebSocket:
symbol@markPrice or symbol@markPrice@1smark price, index price, estimated funding rate, next funding time Provides intraperiod funding updates that the live model can actually know before settlement. Sources: [BINANCE_MARK_WS] [SDK_README] - Perpetual order book and trades:
symbol@depth@100ms, symbol@aggTrade, symbol@bookTickerdepth update IDs, best bid/ask, public trades, event time Models executable futures entry/exit cost, slippage, book freshness, and order-flow timing. Sources: [BINANCE_DEPTH] [SDK_README] - Spot hedge order book:
Spot depth, trade, bookTicker, REST depth snapshotspot bid/ask, depth, update IDs, trades, symbol filters The hedge leg needs its own executable-depth and precision model before the carry result is meaningful. Sources: [BINANCE_SPOT_WS] [BINANCE_SPOT_MARKET] [BINANCE_FILTERS] - Open interest and positioning:
USDMClient.getOpenInterest(), getOpenInterestStatistics(), getGlobalLongShortAccountRatio(), getTakerBuySellVolume()open interest, OI history, account ratios, taker buy/sell volume Helps identify whether high funding reflects persistent demand or unstable crowding. Sources: [BINANCE_OPEN_INTEREST] [BINANCE_OPEN_INTEREST_STATS] [BINANCE_LONG_SHORT] [BINANCE_TAKER_VOLUME] - Liquidation stream:
!forceOrder@arrsymbol, side, order type, quantity, price, event time Liquidation bursts can destabilize funding forecasts, basis, and post-funding markout. Sources: [BINANCE_LIQUIDATIONS] - Private ledger and positions:
Futures account, positions, income history, order/fill streamsbalances, positions, margin ratio, fills, actual funding payments Verifies that paper assumptions match account reality before any live carry workflow is considered. Sources: [BINANCE_ORDER] [SDK_ENDPOINTS]
Research Findings
- Predict funding, then trade selectively: The useful forecast is not just next funding. It is next funding after confidence adjustment, basis stress, and expected post-funding markout. Sources: [INAN2025] [RUAN2022]
- Separate the PnL sources: A carry trade should report funding PnL, basis PnL, fee PnL, slippage, hedge drift, and margin capital cost separately. Sources: [HMRV2022] [YANG2025]
- Open interest changes the interpretation: Positive funding with rising open interest can mean crowded longs; positive funding with falling open interest can mean demand is decaying. Sources: [BEHAVIOR2023] [BINANCE_OPEN_INTEREST_STATS]
- Settlement timing is a test dimension: Backtest 4 h, 2 h, 1 h, 30 min, and 10 min entry windows separately because the right forecast can still be entered badly. Sources: [RUAN2022] [BINANCE_MARK]
- Spot hedging is operational, not trivial: The spot leg needs its own order-book data, precision checks, fees, balances, and reconciliation before futures funding can be evaluated safely. Sources: [BINANCE_SPOT_MARKET] [BINANCE_FILTERS] [BINANCE_ORDER]
- Live mode is a later phase: The first build should record public data, replay feature rows, and paper trade. Private state and tiny live pilots come only after funding ledger and hedge reconciliation pass. Sources: [SDK_README] [BINANCE_ORDER]
Market Surface: Carry, Reversal, And Basket Workflows
- Positive funding carry is the default worked case: The simplest hedged trade is long spot and short perpetual when funding paid to shorts is expected to persist after all costs. The spot leg hedges directional exposure but does not remove basis or margin risk. Sources: [HMRV2022] [BINANCE_MARK] [BINANCE_ORDER]
- Reverse carry needs borrow support: If funding is negative, the theoretical reverse is long perp and short or borrow spot. Skip this in v1 unless spot margin borrow availability, borrow cost, and liquidation mechanics are explicitly modeled. Sources: [YANG2025] [BINANCE_FILTERS]
- Perp-only reversal is not arbitrage: Extreme funding can be a crowding signal, but a directional squeeze or reversal monitor should be kept separate from the hedged carry workflow. Sources: [BEHAVIOR2023] [RUAN2022]
- Funding dispersion is an advanced basket: Ranking symbols by predicted net funding may support a same-exchange long/short basket later, but it adds beta, liquidity, altcoin, and margin-correlation risk. Sources: [YANG2025] [BEHAVIOR2023]
Carry Candidate And Skip Conditions
- Carry candidate: Predicted next funding is positive after confidence adjustment. Perp trades rich but basis stress is below the approved threshold. Open interest and taker flow support persistence rather than an exhausted crowd. Spot and perp depth can fill the hedge within slippage limits. Expected net carry clears fees, spread, exit cost, hedge drift, and margin buffers. Sources: [HMRV2022] [INAN2025] [BINANCE_MARK] [BINANCE_OPEN_INTEREST]
- Skip or reduce candidate: Funding is near cap or has started to roll over before settlement. Open interest is extreme and liquidation flow is elevated. Spot and perp books differ in freshness or available depth. Basis is widening faster than the expected funding payment. Private position state, margin ratio, or funding ledger reconciliation is uncertain. Sources: [AHJ2024] [RUAN2022] [BINANCE_LIQUIDATIONS] [BINANCE_ORDER]
Minimum Forecast Feature Set
- Funding APR:
fundingApr = nativeFundingRate * (365 * 24 / fundingIntervalHours)Normalizes funding across symbols and funding intervals, but should not be treated as guaranteed yield. Sources: [BINANCE_MARK] [HMRV2022] - Funding z-score:
fundingZ = (currentFunding - rollingMean) / rollingStdMeasures whether the current funding rate is extreme relative to symbol history. Sources: [INAN2025] - Perp-index basis:
basisBps = 10000 * (perpMid - indexPrice) / indexPriceLinks funding pressure to the premium or discount of the perpetual versus its reference. Sources: [HMRV2022] [BINANCE_MARK] - Spot-perp basis:
spotPerpBasisBps = 10000 * (perpMid - spotMid) / spotMidMeasures hedge-entry spread and basis risk for a spot-perp carry trade. Sources: [HMRV2022] [BINANCE_SPOT_MARKET] - Time to funding:
timeToFundingMs = nextFundingTimeMs - nowMsAllows separate models and backtests for 4 h, 2 h, 1 h, 30 min, and 10 min entry windows. Sources: [BINANCE_MARK] [RUAN2022] - Open-interest pressure:
oiPressure = z(openInterestChange) * sign(currentFunding)Helps distinguish high funding with fresh position growth from high funding with position decay. Sources: [BEHAVIOR2023] [BINANCE_OPEN_INTEREST_STATS] - Taker buy/sell imbalance:
takerImbalance = (buyVol - sellVol) / max(buyVol + sellVol, epsilon)Adds flow context to funding persistence and squeeze-risk estimates. Sources: [BINANCE_TAKER_VOLUME] [BEHAVIOR2023] - Net carry gate:
expectedNet = predictedFunding - entryCosts - exitCosts - hedgeDrift - marginBuffer - markoutBufferPrevents paper or live carry decisions unless funding survives all modeled costs and risks. Sources: [YANG2025] [AHJ2024]
Manual Research Workflow
- 1. Pick one liquid perpetual: Start with BTCUSDT or ETHUSDT. Record the funding interval, fee tier, spot and futures tick sizes, lot sizes, notional rules, and account margin mode. Sources: [BINANCE_MARK] [BINANCE_FILTERS]
- 2. Watch funding and basis together: Track current funding, next funding time, mark-index basis, spot-perp basis, and how those values evolve during the hours before settlement. Sources: [BINANCE_MARK] [BINANCE_MARK_WS]
- 3. Add positioning context: Compare funding changes with open interest, taker buy/sell volume, long/short ratios, and liquidation spikes. Write down when high funding looks persistent versus crowded. Sources: [BINANCE_OPEN_INTEREST_STATS] [BINANCE_TAKER_VOLUME] [BINANCE_LIQUIDATIONS]
- 4. Shadow the carry trade: For each candidate, record the executable spot buy and perp short prices, then mark funding PnL and basis PnL separately after settlement. Sources: [HMRV2022] [BINANCE_SPOT_MARKET] [BINANCE_ORDER]
- 5. Turn failures into gates: Convert losing cases into no-trade rules: funding rollover, widening basis, stale books, thin spot hedge depth, margin stress, or poor post-funding markout. Sources: [RUAN2022] [YANG2025]
Workflow
- 1. Record public futures and spot data: Collect mark-price streams, funding history, depth, trades, book tickers, open interest, long/short ratios, taker buy/sell volume, liquidations, and spot hedge data. Sources: [BINANCE_MARK_WS] [BINANCE_FUNDING] [BINANCE_DEPTH] [BINANCE_SPOT_WS]
- 2. Build the funding calendar: Normalize native funding rates, 8-hour equivalents, next funding time, previous funding time, interval length, and cap or clamp metadata where exposed. Sources: [BINANCE_MARK] [AHJ2024]
- 3. Align features by receive time: Generate feature rows at fixed times and event boundaries using only data received before the forecast timestamp. Avoid final settled funding leakage. Sources: [INAN2025] [BINANCE_FUNDING]
- 4. Forecast and score after costs: Forecast next funding bps, sign, persistence, flip risk, and post-funding markout, then subtract execution costs, exit costs, hedge drift, and margin buffers. Sources: [YANG2025] [RUAN2022]
- 5. Replay and paper trade: Replay receive-time events, walk spot and futures depth, simulate partial fills, apply actual funding settlements, and report funding PnL separately from basis PnL. Sources: [HMRV2022] [BINANCE_FUNDING] [BINANCE_SPOT_MARKET]
- 6. Add guarded private workflows later: Read-only account reconciliation comes before trade keys. Live mode requires explicit enablement, tiny notional caps, client order IDs, margin guards, and kill switches. Sources: [BINANCE_ORDER] [SDK_README]
Controlled Rollout
- Phase 0: Public recorder for funding snapshots, mark/index price, depth, trades, open interest, positioning, liquidations, and spot hedge books. Sources: [BINANCE_MARK_WS] [BINANCE_FUNDING]
- Phase 1: Forecast research with no-change, rolling mean, EWMA, and interpretable models validated by time-to-funding buckets. Sources: [INAN2025]
- Phase 2: Shadow carry simulation against live public books with no credentials or order endpoints. Sources: [BINANCE_SPOT_MARKET] [BINANCE_DEPTH]
- Phase 3: Paper trading with partial-fill and hedge-drift handling, still without live orders. Sources: [YANG2025]
- Phase 4: Read-only account reconciliation for positions, balances, actual funding payments, and fees. Sources: [SDK_README] [BINANCE_ORDER]
- Phase 5: Tiny live pilot on one liquid symbol only, with explicit live flag, minimum size, no leverage above approved limits, and manual start. Sources: [BINANCE_ORDER]
Hard Risk Gates
- Funding snapshot, mark price, public book, or private order stream is stale. Sources: [BINANCE_MARK_WS] [BINANCE_DEPTH]
- Funding sign flips, funding moves near cap or floor, or predicted net carry no longer clears exit cost. Sources: [BINANCE_MARK] [AHJ2024]
- Spot-perp hedge drift, basis stress, or liquidation distance breaches configured limits. Sources: [HMRV2022] [BINANCE_ORDER]
- Actual funding ledger payment differs materially from expected settlement. Sources: [BINANCE_FUNDING] [SDK_ENDPOINTS]
- Open interest, liquidation flow, spread, volatility, or slippage is outside the approved regime. Sources: [BINANCE_OPEN_INTEREST_STATS] [BINANCE_LIQUIDATIONS]
- Order reject rate, partial-fill rate, cancel latency, daily loss, or manual stop is triggered. Sources: [BINANCE_ORDER]
SDK Implementation Surfaces
- USD-M REST market data: USDMClient.getMarkPrice(), getFundingRateHistory(), getFundingRates(), getOpenInterest(), getOpenInterestStatistics(), getGlobalLongShortAccountRatio(), and getTakerBuySellVolume(). Sources: [SDK_ENDPOINTS] [BINANCE_MARK] [BINANCE_FUNDING] [BINANCE_OPEN_INTEREST]
- Public WebSockets: WebsocketClient subscriptions for btcusdt@markPrice@1s, btcusdt@depth@100ms, btcusdt@aggTrade, btcusdt@bookTicker, and !forceOrder@arr where supported. Sources: [SDK_README] [BINANCE_MARK_WS] [BINANCE_DEPTH] [BINANCE_LIQUIDATIONS]
- Spot hedge data: MainClient.getOrderBook(), getExchangeInfo(), bookTicker, depth, and trade streams for the spot leg used in long-spot short-perp carry. Sources: [SDK_ENDPOINTS] [BINANCE_SPOT_MARKET] [BINANCE_FILTERS]
- Private reconciliation: Only after public replay and paper trading: verify futures positions, spot balances, open orders, fills, fees, funding-income records, margin ratio, and client order IDs. Sources: [SDK_README] [BINANCE_ORDER]
Automation Workflow
- Capture funding snapshots: Persist every mark-price and funding snapshot with exchange event time, local receive time, symbol, next funding time, mark price, index price, and estimated funding rate. Sources: [BINANCE_MARK] [BINANCE_MARK_WS]
- Build no-lookahead labels: The label is the next settled funding rate or realized net carry; feature rows may only use values received before the decision timestamp. Sources: [INAN2025] [BINANCE_FUNDING]
- Benchmark simple models: Compare no-change, rolling mean, EWMA, and simple interpretable models before adding gradient boosting or more complex learners. Sources: [INAN2025]
- Paper the hedge: Simulate long spot plus short perp with depth walking, precision rounding, fees, slippage, partial fills, hedge drift, funding payments, and exit costs. Sources: [YANG2025] [BINANCE_SPOT_MARKET] [BINANCE_ORDER]
- Reconcile before live: Add private state only after public replay is deterministic, then verify actual funding payments, fills, position size, margin ratio, and fee currency. Sources: [SDK_README] [BINANCE_ORDER]
Public Funding Bootstrap Snippet
import { DefaultLogger, MainClient, USDMClient, WebsocketClient } from 'binance';
const symbol = 'BTCUSDT';
const streamSymbol = symbol.toLowerCase();
const spot = new MainClient({ beautifyResponses: true });
const futures = new USDMClient({ beautifyResponses: true });
const ws = new WebsocketClient({ beautify: true }, DefaultLogger);
async function loadPublicFundingContext() {
const [
spotBook,
spotExchangeInfo,
markPrice,
fundingHistory,
openInterest,
openInterestStats,
longShortRatio,
takerVolume,
] = await Promise.all([
spot.getOrderBook({ symbol, limit: 1000 }),
spot.getExchangeInfo({ symbol }),
futures.getMarkPrice({ symbol }),
futures.getFundingRateHistory({ symbol, limit: 100 }),
futures.getOpenInterest({ symbol }),
futures.getOpenInterestStatistics({ symbol, period: '5m', limit: 288 }),
futures.getGlobalLongShortAccountRatio({ symbol, period: '5m', limit: 288 }),
futures.getTakerBuySellVolume({ symbol, period: '5m', limit: 288 }),
]);
return {
spotBook,
spotExchangeInfo,
markPrice,
fundingHistory,
openInterest,
openInterestStats,
longShortRatio,
takerVolume,
};
}
ws.on('response', (response) => {
// Treat exchange subscription acknowledgements as readiness events.
console.log('ws response', response);
});
ws.on('message', (rawEvent) => {
const receiveTimeMs = Date.now();
// Persist rawEvent before normalization. Feature rows must use receiveTimeMs
// so replay cannot accidentally see future funding settlements.
console.log('raw event received', receiveTimeMs, rawEvent);
});
ws.on('reconnecting', () => {
// Pause forecasts and paper decisions until streams and books are rebuilt.
});
ws.subscribe(
[
`${streamSymbol}@markPrice@1s`,
`${streamSymbol}@depth@100ms`,
`${streamSymbol}@aggTrade`,
`${streamSymbol}@bookTicker`,
'!forceOrder@arr',
],
'usdm',
);
await loadPublicFundingContext();
Paper And Guarded Order Snippet
import { MainClient, USDMClient } from 'binance';
const spot = new MainClient({
api_key: process.env.BINANCE_API_KEY,
api_secret: process.env.BINANCE_API_SECRET,
beautifyResponses: true,
});
const futures = new USDMClient({
api_key: process.env.BINANCE_API_KEY,
api_secret: process.env.BINANCE_API_SECRET,
beautifyResponses: true,
});
const liveTradingEnabled = process.env.LIVE_TRADING_ENABLED === 'true';
const paperTradingEnabled = process.env.PAPER_TRADING_ENABLED !== 'false';
if (!paperTradingEnabled && !liveTradingEnabled) {
throw new Error('Funding carry starts in public replay or paper mode');
}
const clientOrderPrefix = 'funding-BTCUSDT-20260425';
// Paper model first:
const paperIntent = {
strategy: 'spot_perp_funding_carry',
spotLeg: { symbol: 'BTCUSDT', side: 'BUY', type: 'LIMIT', timeInForce: 'IOC' },
perpLeg: { symbol: 'BTCUSDT', side: 'SELL', type: 'LIMIT', timeInForce: 'IOC' },
reason: 'predicted funding clears modeled costs',
};
console.log('paper funding-carry intent', paperIntent);
if (!liveTradingEnabled) {
throw new Error('Refusing live spot/perp orders without LIVE_TRADING_ENABLED=true');
}
// Live pilot only after public replay, paper trading, and read-only reconciliation pass.
await spot.submitNewOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'LIMIT',
timeInForce: 'IOC',
quantity: '0.001',
price: '65005.00',
newClientOrderId: `${clientOrderPrefix}-spot-buy`,
});
await futures.submitNewOrder({
symbol: 'BTCUSDT',
side: 'SELL',
type: 'LIMIT',
timeInForce: 'IOC',
quantity: '0.001',
price: '65000.00',
newClientOrderId: `${clientOrderPrefix}-perp-sell`,
});
Baseline Carry Signal
predictedFundingBps =
0.45 * currentFundingBps
+ 0.20 * meanFundingBps_last3
+ 0.15 * basisZScore
+ 0.10 * openInterestChangeZ
+ 0.10 * takerBuySellImbalanceZ
expectedNetCarryBps =
predictedFundingBps
- spotEntryCostBps
- perpEntryCostBps
- expectedExitCostBps
- slippageBufferBps
- hedgeDriftBufferBps
- marginRiskBufferBps
- postFundingMarkoutBufferBps
carryCandidate =
predictedFundingBps > minFundingBps
and probabilityPositive > 0.65
and expectedNetCarryBps > minNetCarryBps
and timeToFundingMs between 30 minutes and 4 hours
and abs(perpSpotBasisBps - entryBasisBps) < maxBasisStressBps
and spotDepth >= minSpotDepth
and perpDepth >= minPerpDepth
and marginRatioAfterTrade >= minMarginRatio
and marketDataFresh
and privateStateFresh if execution is enabled
Complete Implementation Prompt
Want to test this idea? Use the prompt below to ask an AI coding agent to build a public-data-first workflow. Keep live trading disabled until replay, the paper carry simulator, and reconciliation prove the data path.
Goal: Build a Binance BTCUSDT funding-rate forecasting and spot-perp carry strategy pipeline with a paper carry simulator.
Runtime prerequisite: Node.js LTS must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing.
Use:
- Package: binance
- Siebly Binance JavaScript SDK guide: https://siebly.io/sdk/binance/javascript
- Siebly AI guide: https://siebly.io/ai
- This article: https://siebly.io/research/crypto-funding-rate-forecasting
- Website llms.txt: https://siebly.io/llms.txt
- Website llms-full.txt: https://siebly.io/llms-full.txt
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
- Binance SDK repository: https://github.com/tiagosiebler/binance
- Binance SDK endpoint reference: https://github.com/tiagosiebler/binance/blob/master/docs/endpointFunctionList.md
- Binance USD-M Mark Price and Funding Rate: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price
- Binance USD-M Funding Rate History: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Rate-History
- Binance USD-M Mark Price Stream: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream
- Binance USD-M Open Interest: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest
- Binance USD-M Open Interest Statistics: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest-Statistics
- Binance USD-M Long/Short Ratio: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Long-Short-Ratio
- Binance USD-M Taker Buy/Sell Volume: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Taker-BuySell-Volume
- Binance USD-M Liquidation Stream: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams
- Binance USD-M Diff Book Depth Stream: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams
- Binance USD-M New Order Endpoint: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Order
- Binance Spot WebSocket Streams: https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams
- Binance Spot Market Data Endpoints: https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints
- Research references to inspect before modeling: https://arxiv.org/abs/2212.06888, https://www.nber.org/papers/w32936, https://papers.ssrn.com/sol3/papers.cfm?abstract_id=5576424, https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4218907
Safety boundary:
- Treat this as engineering research only, not financial advice, investment guidance, trade signals, yield advice, or a recommendation to trade.
- Default to public endpoints, deterministic replay, and paper mode.
- Do not add live trading unless the user explicitly asks for it after public capture, replay, the paper carry simulator, and read-only reconciliation pass.
- The default worked trade is long spot and short perpetual for positive predicted funding. Reverse carry is out of scope unless borrow availability, borrow cost, margin, and liquidation risk are explicitly modeled.
- Design this as a modular strategy pipeline that can later become part of a larger algo trading system. Keep exchange adapters, recorder, normalizer, feature state, signal logic, paper executor, risk gates, account reconciliation, and live execution adapter separated.
Attribution requirements:
- Add this exact README section:
## Attribution
This project was made with the help of the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "This project was made with the help of the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
- README must also state that the project is research and engineering output only, not financial, investment, legal, tax, compliance, or security advice, and that live trading is disabled by default.
Requirements:
- Before writing code, inspect the linked docs, examples, endpoint map, source types, llms files, SDK catalog, Siebly Binance docs, Binance USD-M docs, and Binance spot docs. Verify the real method names, request shapes, topic names, event fields, acknowledgement events, reconnect hooks, order parameters, rate limits, product scopes, and shutdown methods.
- Implement a public recorder that collects BTCUSDT USD-M mark-price funding updates, funding history, current open interest, open-interest history, global long/short ratio, taker buy/sell volume, liquidation snapshots, perp depth/trade/book-ticker streams, and spot depth/trade/book-ticker streams.
- Record raw events with exchange event time, local receive time, connection/request ID, stream name, sequence/update IDs where available, raw payload, and resync markers.
- Build a funding calendar with native funding rate, 8-hour equivalent, funding APR, next funding time, funding interval, previous funding time, and cap or clamp metadata where exposed.
- Align feature rows without lookahead. Do not train on the final settled funding rate as if it was known before the decision timestamp. REST backfills may populate labels only after the simulated decision time.
- Create labels for next funding bps, funding sign, funding persistence, realized net carry, basis PnL, funding PnL, and post-funding markout.
- Implement no-change, rolling mean, EWMA, and at least one interpretable model before any complex model. Report forecast MAE, RMSE, sign precision/recall, calibration, and performance by time-to-funding bucket.
- Derive features for funding z-score, funding slope, funding percentile, perp-index basis, spot-perp basis, time to funding, open-interest change, long/short ratio, taker buy/sell imbalance, liquidation imbalance, spread, depth, volatility, and stale-data flags.
- Create a cost-aware carry signal that only emits a paper candidate when predicted funding exceeds spot entry cost, perp entry cost, expected exit cost, slippage, hedge drift, margin buffer, funding uncertainty, and post-funding markout buffer.
- Simulate paper carry for long spot plus short perp with executable depth, precision rounding, fees, partial fills, hedge drift, actual funding settlement, basis PnL, and exit costs. Report funding PnL separately from basis PnL.
- Add risk gates for stale funding snapshots, stale books, funding flips, basis stress, hedge drift, liquidation distance, actual funding payment mismatch, high liquidation flow, high spread, slippage breach, order rejects, daily loss, and manual stop.
- Keep live trading disabled by default. If a later live phase is requested, require LIVE_TRADING_ENABLED=true, tiny notional caps, client order IDs, private account reconciliation, margin guards, and explicit operator approval.
Acceptance criteria:
- The public recorder runs without API keys.
- Feature rows use only data available before each forecast timestamp.
- Replay reproduces funding forecasts, paper decisions, cost estimates, skipped-trade reasons, and risk gates from raw events.
- Baselines include no-change and EWMA, and any advanced model must beat them out of sample after costs.
- The paper carry simulator reports funding PnL, basis PnL, fees, slippage, hedge drift, margin utilization, and post-funding markout separately.
- No order path can run before the configured public/paper/live phase allows it.
- README includes Node.js LTS requirement, install and run commands, public/paper/live modes, env vars, symbol config, replay limitations, risk controls, attribution, and the research-only disclaimer.
- At the end, print the exact commands to run recorder, replay, forecast evaluation, the paper carry simulator, and guarded live mode, with live mode disabled by default.
Siebly provides this prompt for informational engineering research only. It is not financial, investment, legal, tax, security, compliance, or professional engineering advice, and it is not a recommendation to trade. To the maximum extent permitted by law, Siebly accepts no responsibility for losses, failed orders, missed trades, security incidents, regulatory issues, or other consequences arising from AI-generated output, your prompts, your code, your trading strategy, or your implementation decisions.
References
- [HMRV2022] Academic paper: He, Manela, Ross, von Wachter - Fundamentals of Perpetual Futures Research on perpetual futures mechanics, price deviations, funding payments, and implied carry opportunities in crypto markets.
- [AHJ2024] Academic paper: Ackerer, Hugonnier, Jermann - Perpetual Futures Pricing Derives no-arbitrage pricing bounds for perpetual futures and emphasizes how funding formulas, clamps, and trading costs affect fair value.
- [DLY2025] Academic paper: Dai, Li, Yang - Arbitrage in Perpetual Contracts Studies arbitrage and frictions in perpetual contracts, including how funding and market design affect exploitability.
- [YANG2025] Academic paper: Yang et al. - Risk and Return Profiles of Funding Rate Arbitrage Compares funding-rate arbitrage return and risk profiles and highlights the importance of costs, venue design, and risk controls.
- [INAN2025] Academic paper: Inan - Predictability of Funding Rates Finds that Bitcoin funding rates can be forecast out of sample with models that account for time-varying stability and volatility.
- [RUAN2022] Academic paper: Ruan, Streltsov - Perpetual Futures Contracts and Cryptocurrency Market Quality Studies how perpetual-futures funding cycles interact with liquidity, adverse selection, and market quality.
- [BEHAVIOR2023] Academic paper: Predictability of crypto returns: The impact of trading behavior Research linking crypto futures trading behavior and positioning-style measures to predictability and market dynamics.
- [BINANCE_MARK] Exchange documentation: Binance USD-M Mark Price and Funding Rate Official REST endpoint for mark price, index price, estimated funding rate, interest rate, and next funding time.
- [BINANCE_FUNDING] Exchange documentation: Binance USD-M Funding Rate History Official endpoint for historical funding rates, used for labels, baselines, and settlement-calendar validation.
- [BINANCE_MARK_WS] Exchange documentation: Binance USD-M Mark Price Stream Official WebSocket stream for mark price and funding-rate updates, including 1-second update options.
- [BINANCE_OPEN_INTEREST] Exchange documentation: Binance USD-M Open Interest Official endpoint for current open interest on a USD-M futures symbol.
- [BINANCE_OPEN_INTEREST_STATS] Exchange documentation: Binance USD-M Open Interest Statistics Official endpoint for open-interest history, useful for positioning features and crowding detection.
- [BINANCE_LONG_SHORT] Exchange documentation: Binance USD-M Long/Short Ratio Official long/short ratio endpoints for account and top-trader positioning context where available.
- [BINANCE_TAKER_VOLUME] Exchange documentation: Binance USD-M Taker Buy/Sell Volume Official taker buy/sell volume statistics that can help distinguish persistent demand from exhausted positioning.
- [BINANCE_LIQUIDATIONS] Exchange documentation: Binance USD-M Liquidation Stream Official all-market liquidation-order stream. Binance documents that it pushes the latest liquidation order snapshot per symbol at 1000 ms cadence.
- [BINANCE_DEPTH] Exchange documentation: Binance USD-M Diff Book Depth Stream Official futures depth stream for local perpetual order-book reconstruction and executable-depth checks.
- [BINANCE_ORDER] Exchange documentation: Binance USD-M New Order Endpoint Official futures order endpoint documenting order side, type, time in force, reduce-only behavior, position side, and client order IDs.
- [BINANCE_SPOT_WS] Exchange documentation: Binance Spot WebSocket Streams Official Spot streams for the hedge leg, including depth, trade, aggregate trade, and book-ticker streams.
- [BINANCE_SPOT_MARKET] Exchange documentation: Binance Spot Market Data Endpoints Official Spot REST market-data endpoints for order-book snapshots, book tickers, and public trades.
- [BINANCE_FILTERS] Exchange documentation: Binance Spot Filters Official symbol and exchange filters needed for tick size, lot size, notional floors, and precision-safe hedge orders.
- [SDK_README] SDK documentation: Binance JavaScript SDK README SDK overview for MainClient, USDMClient, WebsocketClient, connection events, REST clients, WebSocket subscriptions, and lifecycle handling.
- [SDK_ENDPOINTS] SDK documentation: Binance SDK Endpoint Function List SDK endpoint map linking Binance REST and WebSocket API paths to current client method names.
- [SIEBLY_BINANCE] Siebly documentation: Siebly Binance JavaScript SDK guide Siebly guide for using the Binance JavaScript and TypeScript SDK from local agent workflows.