Development of a backtesting system with funding rate accounting

Strategy returns on historical data diverge from live trading if the funding rate is accounted for approximately. We develop backtesting systems where the rate is modeled using actual data and your trading conditions. The result is that the gap between testing and live results is reduced severalfold, and decisions are based on verified numbers.

Blockchain Development Services

Frequently Asked Questions

Latest works

  • Development of a web application for FEEDME
    Development of a web application for FEEDME
    1376
  • Development of an online store for the company FURNORO
    Development of an online store for the company FURNORO
    1350
  • B2B Advance company logo design
    B2B Advance company logo design
    798
  • Development of a web application for Enviok
    Development of a web application for Enviok
    1088
  • AIDER company logo development
    AIDER company logo development
    1034
  • CRM development for Chasseurs
    CRM development for Chasseurs
    1130

Backtesting funding rate: where a strategy breaks on historical data

Perpetual contracts have no expiration date, so the price is kept near spot by the funding rate mechanism: every few hours, one side pays the other. In backtesting, funding rate is most often simply not accounted for — the engine closes the trade at mark price and stops there.

The gap between test and trading accumulates exactly here: a strategy that holds positions for days and weeks pays for carry on a real account at every settlement interval.

The cost of the error depends on the market regime. In a sustained trend, the rate stays one-sided, and accumulated payments take a noticeable share of profit — when holding for months, this is no longer a third-decimal adjustment but the difference between profit and loss.

In a sideways market, the opposite is true: the rate can turn out to be greater than the price move itself, and the strategy gives away on carry everything it earned on the fluctuation.

A correct funding rate calculation is based on the exchange's historical data, not on the current value. You need rates for each settlement moment, a history of changes to the formula and limits, periods when the settlement interval changed and when the rate was zeroed out.

A position pays only if it is open at the settlement moment — the test reproduces this from trade timestamps rather than accruing the rate proportionally to holding time.

Testing a strategy on such a model immediately shows which part of the growth was drawn by carry.

Therefore, fees, spread, and execution at mark price are added to the test, and history is taken from the same exchange and the same instrument where trading is planned — otherwise both the rates and the liquidation rules diverge. Below is how we build such a loop so that the test and the real account calculate the same thing.

What funding rate accounting adds to return calculation

The funding rate is not a one-time entry fee but a periodic cash flow: while a position is open, it receives or pays it at fixed settlement moments.

If this flow is not built into the order execution model, the backtest counts only price movement and overstates the result in any market where the sign of the rate is stable.

The accrual mechanics differ from venue to venue — on Binance it is tied to the deviation of the mark price from the index, so in the engine the rate is treated as a separate flow component rather than a percentage of the trade.

The second layer is discretization. If a position is opened within the accrual interval, the rate is accrued proportionally to holding time and with a sign that depends on direction and hedging.

Without this, the strategy's return curve is built from candle closing prices and turns into a staircase: flat within the interval, a step at the boundary. With short holding periods, such an error outweighs the trading result itself.

On the curve, this is visible as a change in shape: in a trend with a positive rate, a long position gives up part of the profit, and the rise becomes smoother, while in a sideways market the smooth growth disappears, which in a naive calculation has nothing behind it.

Therefore, resilience to market regimes is checked with separate runs — sideways, trending, volatile — and you look at what share of the result came from price and what share from carrying risk.

A specific class of failures goes away: strategies whose positive returns held up only in a run without the rate are filtered out at the validation stage, not at the first change of its sign in live trading.

Methods of modeling the rate: comparison of approaches

The method of reconstructing the funding rate in history is not a detail of the methodology but part of it: a perpetual instrument accrues it between longs and shorts several times a day, and over a long horizon it can contribute more than the trading signal itself.

If the rate is modeled incorrectly, the backtest will show profit where there was none, or take it away from a strategy that works in reality. Below are the approaches we choose between when building the system, with applicability conditions and boundaries for each.

Approach When it fits Limitations
Actual venue rates Backtesting a strategy on the past, short and medium horizons, reconciliation with real results Depends on archive completeness: gaps, changes in calculation rules, lack of history for delisted instruments
Constant: period average Quick estimate, comparing strategies to each other, sensitivity analysis Smooths out spikes — divergence from reality grows with the position holding period
Forecast by components: spot premium, order book depth, limits Future periods not present in history, long horizons Error accumulates, regular calibration and input data quality control are needed
Time series model, moving average Stable regimes, stress tests Does not capture regime changes and extreme spikes; over a long window, extrapolation diverges

In practice, the approaches are combined: the baseline is calculated on actual rates, future periods on a forecast, and strategy resilience is checked with a stress grid where the rate is multiplied and changes sign.

A separate task is the source of the historical calculation: we store our own rate snapshots so that results do not depend on how long a venue keeps its archive and how often it changes accrual rules.

If the system diverges from the actual result on the same trades, the cause is usually here — in the source and modeling method, not in the signal logic.

Stages of building a backtesting system for your strategy

A data audit almost always changes the problem statement: gaps are found during contract rollovers, duplicate candles, and discrepancies between index price and last trade price.

Therefore, before code, we fix a calculation agreement: which events are included in the model and how funding is accrued.

  1. Data audit. We consolidate the history of trades, candles, and accruals; look for gaps, timestamp shifts, and contract specification changes. The output is a suitability map: where calculation is possible, where reconstruction is needed.
  2. Calculation scheme. We formalize the rules: funding accrual moment, tie to index price, accounting for leverage, fees, and slippage. The agreed scheme becomes the reference for reconciliation.
  3. Calculation pipeline setup. The order and execution flow runs separately from the accrual flow, and results are collected at one point. The run is deterministic — repeating on the same data produces the same numbers.
  4. Historical validation. We reconcile model accruals with actual exports and run edge cases: negative rate, holding a position through the accrual moment, trading halt.
  5. Stress test. We calculate the strategy on trending and sideways segments: it shows where the result rests on rare events and where it rests on a sustainable edge.
  6. System handover. We provide configurations, the calculation scheme, the data update procedure, and launch on your side; a new strategy can be added without rewriting the core.

What we hand over: artifacts and procedures

Calculation with funding rate accounting rests on assumptions: when exactly the payment is debited, how exchange time zones are handled, how the rate is rounded, where the history comes from.

While these agreements live in chat, the run result is not reproducible, and comparing strategies turns into a dispute about numbers. That is why we deliver not only code — we hand over a set of descriptions your engineer can use to run the calculation without us.

  • Calculation configurations — funding periods per instrument, rounding rules, accounting for fees and slippage; stored in files rather than hardcoded.
  • Data flow diagrams — the path from loading rate and price history to normalization and writing to storage, with notes on segments where gaps are possible.
  • Validation report — reconciliation of the calculated rate with exchange exports on reference intervals: where it matched, where it diverged, and why.
  • Run procedure — on what window and how often to run tests, what divergence is considered normal, and at what point the run stops.
  • Support instructions — connecting a new instrument or exchange, changing the data source, editing calculation rules.
  • Assumption log and metric dictionary — unambiguous definitions of return, drawdown, and average holding time so that reports are read consistently.

We hand over each item with a walkthrough and a trial run on your side — you confirm that the package is self-sufficient before the work is closed.

Case study: how we reduced the divergence between test and live trading

Before: 18% divergence between test and account

The client ran a market-neutral strategy via Binance: spot against a short in perpetual futures, with income from funding rate payments every eight hours.

On history, the curve looked smooth, but on a live account the actual result differed from the calculation by 18% per month; on days when the rate sign changed, by more than twofold.

The causes turned out to be mundane: the rate in the backtest was accrued as an averaged constant, positions opened and closed within the payout window received no accruals at all, and slippage during rebalancing was not modeled.

After: 4% and preserved result under a regime change

The backtesting with funding rate accounting was rewritten as an event-driven model: each payment is calculated using the actual rate at the settlement moment, with constraints on minimum order size and price tick.

We added execution based on order book history and a fee schedule by volume tier — the test stopped “seeing” trades that the exchange would not have allowed.

We separately ran trend reversal and negative rate scenarios so that strategy resilience was tested across more than one market regime.

The divergence decreased from 18% to 4% per month, and missed accruals went from 6 out of 90 windows to zero. In the stress scenario with a change in the sign of the rate, drawdown increased by no more than one-fifth, and the strategy remained profitable. The decision to increase leverage is now made based on test results, not intuition.

How actual rate calculation differs from forecasting it

The forecast rate is a reference that the exchange recalculates based on the premium of the mark to the spot index within the settlement window. The actual one is what was debited at the settlement moment.

It is convenient to pull the forecast from candles, but by settlement it may change sign, and the backtest will show a return that did not exist.

The settlement mode determines what exactly goes into the model: the interval (one hour, four, eight), the settlement moment, and the boundaries of the premium averaging window.

If you take the rate from a candle rather than from the settlement journal, you average over the window and shift the event timestamp — a position that survives dozens of settlements accumulates this shift.

The choice of source is the second fork. The settlement journal of a specific venue gives exactly the events that affected your position. A third-party aggregator is more convenient, but it has a different set of trading pairs, its own publication lag, and its own rounding.

Rates from different venues are not interchangeable: transferring them to someone else's position means calculating someone else's risk.

The sensitivity of the result is nonlinear. In trend strategies with short holding periods, the rate drowns in the price movement.

Where it is the source of income — neutral arbitrage, perpetual contract hedging — substituting the actual with a forecast reverses the sign of the final curve.

Practical takeaway: calculate from actuals, from the settlement journal of the venue where the trades were actually executed, and leave the forecast for “what if” scenarios. Then the strategy metric answers a question about the past, not about an assumption.

Technical doubts and limitations of the approach

The correctness of backtesting results with funding rate accounting rests on four things: completeness of history, matching with real execution, versioning of exchange rules, and run speed. Below are typical engineering doubts that we address before starting work.

What if candles or funding payments are missing from the history?

A gap is marked explicitly rather than filled with zero: a zero rate mistakenly makes the position profitable. We restore missing intervals from a second source or leave them as an uncertainty zone, and such segments are excluded from the final statistics.

How closely will the result match live trading?

The run follows an execution model: order submission delay, fee, spread, slippage on volume, and liquidity at the moment of the funding payment.

We calibrate the model using actual trades at a small position size and compare the divergence by the share of profitable trades — the forecast and actual metrics must converge.

What should be done if the exchange changes the rate calculation rules?

We store the rules with versions: each period has its own payout schedule and formula. We do not rewrite history to match current rules — otherwise past results stop being reproducible and strategies can no longer be compared to each other.

How fast does a multi-year history run?

We calculate incrementally: we recompute only the affected segment and take the rest from previously calculated results. A run over a long sample fits into minutes, so parameters are iterated in batches rather than one by one — and the result has time to pass a robustness check.

Let's discuss the task and come back with an estimate and plan

To come back with an estimate and work plan rather than clarifying questions, we need one pass from your side. The more specific the input data, the more accurate the timeline and the fewer assumptions inside the calculation.

  • Venues and instruments: where we trade, perpetuals or spot, which pairs and how many.
  • Data history: date range, candle frequency, how to handle gaps and breaks in the funding rate series.
  • Strategy logic: entry and exit rules, position size, leverage, margin handling, and protective stops.
  • Funding rate accounting: the venue's accrual schedule, the sign of the rate, the debit moment relative to candle close.
  • Cost model: venue fees for aggressive and passive trades, slippage, order execution delay.
  • Reporting requirements: which metrics matter, whether period breakdowns are needed, file output or interactive charts.
  • Calculation constraints: what we consider unacceptable — look-ahead bias, parameter fitting to history, manual edits to the series.
  • Infrastructure: where we run calculations, whether connections to your services are needed, whether there are data storage requirements.

With this set, we assemble an estimate and work plan: stages, timelines, what you see at which step. We will discuss the task and the format of work separately — iterations with intermediate results, repository access, or handover of the finished loop to your team.

Describe everything in free form, even if some points are not yet defined: we will close the gaps with questions on a call.