TradingView strategy research

Pairs trading strategy: spread construction and testing limits

A pairs trading strategy takes opposing positions in two assets to trade a change in their relative prices. A mean-reversion version buys the relatively cheap leg and sells the relatively expensive leg under a defined spread model. Research must establish the relationship, hedge quantities, entry and exit rules, and costs on both legs. High correlation alone does not establish a mean-reverting spread. A Pine indicator can monitor the relationship; a single-chart strategy report does not validate a complete two-leg portfolio.

See the decision guide

Correlation and cointegration answer different questions

Correlation measures linear co-movement in the series you supply. TradingView's built-in Correlation Coefficient uses closing prices; correlation of returns is a different calculation and must be labeled accordingly. Cointegration asks whether nonstationary series have a stationary linear combination. Two assets can move together while the distance between their prices keeps growing.

  • A simple counterexample is A(t) = 100 + 2t and B(t) = 50 + t. Their price-level correlation is 1, but A - B = 50 + t trends upward. This algebraic example refutes the inference that high correlation makes an unweighted difference revert; it is not a cointegration test.
  • For an Engle-Granger test, the statsmodels documentation specifies a null hypothesis of no cointegration and assumes the input series are I(1). Check integration assumptions, regression specification and lag choices before interpreting a p-value.
  • Rejecting that null on one sample is evidence about that fitted relationship under the test assumptions. It does not establish an enduring relationship, executable profits or future convergence. Screening many pairs also creates selection bias.

Choose a spread, ratio or residual deliberately

Let A and B be synchronized positive prices in the same currency. The examples below use cash equities with a value of one currency unit per one-unit price move per share. Futures multipliers, FX conversion and corporate actions require additional accounting. A z-score rescales the chosen series; it does not repair an unsuitable model.

  • This page uses the linear residual with a positive, fixed beta. A negative beta would imply same-direction holdings for a long residual and falls outside this long/short example.
  • For the log model, the local share relation is qB ≈ beta × qA × A / B. Copying the linear-model share rule into a log-price model changes exposure.
  • Dollar neutrality uses qA × A = qB × B. A regression hedge need not satisfy that equation, and dollar neutrality does not guarantee neutrality to market beta, sector risk or other factors.
ConstructionFormulaMeaning and limitation
Unweighted differenceS = A - BOne share of A against one share of B. Different price scales can dominate the result; equal shares do not imply equal dollars.
Price ratioR = A / B, with B > 0A relative price in dimensionless units. A change in this ratio is not itself the dollar P&L of fixed share quantities.
Linear residualS = A - alpha - beta × BFor fixed beta > 0, one share of A against beta shares of B replicates changes in S. Alpha is a fitted intercept, not a traded leg.
Log residualL = ln(A) - alpha - beta × ln(B)Beta describes a log-price relationship. Approximately beta dollars of B hedge one dollar of A locally; beta is not a share ratio. Rebalancing has costs.
Standardized residualz = (S - mu) / sigma, with sigma > 0Distance from the reference mean in reference standard deviations. State the training window and whether mu and sigma remain fixed.

Freeze the model before testing later dates

A reproducible experiment separates choosing a pair from evaluating it. The following protocol is an illustrative research design, not a recommended parameter set or a measured trading result. Keep a dated record of the candidate universe, rejected candidates and every model tried.

  • Fitting beta or selecting a pair on the entire chart before reporting an earlier backtest leaks later information. Moving the normalization window after a loss also changes the experiment.
  • Use consistently adjusted data for relationship research, then reconcile actual quantities and cash flows for splits and dividends in the execution ledger. An adjustment convention must not create an artificial convergence profit.
StageDecision made with information available then
Data preparationUse matching bar-close timestamps, compatible sessions and a documented price-adjustment policy. Exclude missing observations from both series together. Do not pair a stale close from one exchange with a fresh close from another.
Earlier training intervalExample: 252 synchronized daily observations. Choose the pair, fit A on B with an intercept, assess integration and residual behavior, and estimate residual mu and sigma. Record the test method and selection criteria.
Later evaluation intervalExample: the next 63 synchronized daily observations. Freeze alpha, beta, mu, sigma and trading rules. Do not refit them using these evaluation dates.
Repeat, if predeclaredAdvance the training/evaluation boundary on a fixed schedule. Define whether open trades close before refitting. Include rebalance trades and their costs instead of rewriting old holdings with the new beta.

Define entry, convergence and failure separately

This baseline evaluates a frozen linear model once both daily closes are available. It holds at most one pair position, uses no averaging down, and keeps the original quantities until exit. These are research rules for an external two-leg simulator; the Pine example below only plots observations.

  • Risk and operational exits take precedence. Evaluate new entries only when fully flat, with no pending orders; do not reverse on an exit observation. A model-failure exit suspends that pair until the next predeclared review.
  • A close-based z-score exit is a decision rule, not a guaranteed intraday stop price. Set an independent portfolio loss and margin policy in the external test. Missing prices do not make existing risk disappear.
ConditionBaseline action
Flat: 2 ≤ z < 3Short q shares of A and buy beta × q shares of B at the next executable opportunities, subject to available borrow and capital. A is expensive relative to the frozen model.
Flat: -3 < z ≤ -2Buy q shares of A and short beta × q shares of B. Round quantities to tradable lots and record the resulting hedge error.
Flat: |z| ≥ 3Skip entry. A large deviation is also consistent with model failure, so this baseline does not initiate beyond its failure boundary.
Convergence exitFor a short residual, exit when z ≤ 0.5. For a long residual, exit when z ≥ -0.5. Directional comparisons also catch a jump through the mean.
Adverse move or time limitExit a short residual when z ≥ 3, or a long residual when z ≤ -3. Otherwise exit after 20 completed daily observations following entry. Actual fills may be worse than the observed boundary.
Execution or data failureReject new entries with missing data or unavailable borrow. If one leg fills and the other fails, cancel the unfilled remainder and unwind the filled leg at the next executable price; retain that loss. Suspend new entries after a halt or borrow recall and manage existing exposure separately.

Worked example: 100 shares against 120 shares

Assume fictional USD stocks, alpha = 2, beta = 1.2, mu = 0 and sigma = 2, all fixed before evaluation. At A = $102 and B = $80, S = 102 - 2 - 1.2 × 80 = 4 and z = 2. For arithmetic, assume both legs fill at those reference prices before the separate execution-cost allowance below: short 100 A and buy 120 B. The $10,200 short and $9,600 long produce $19,800 gross exposure and a $600 net short dollar exposure.

  • With fixed quantities, the short-residual gross result equals 100 × (Sentry - Sexit). The intercept cancels. This identity fails if quantities change without accounting for the intermediate trades.
  • The first outcome is +$320 / $19,800 ≈ 1.62% of initial gross exposure before costs. That denominator is not account equity, margin usage or an annual return.
Alternative later observationPosition calculationGross P&L
A = $100, B = $81: S = 0.8 and z = 0.4100 × (102 - 100) + 120 × (81 - 80)+$320; the convergence rule requests exit.
A = $106, B = $80: S = 8 and z = 4100 × (102 - 106) + 120 × (80 - 80)-$400 before costs; the adverse boundary was exceeded.
Both legs rise: A = $104, B = $81100 × (102 - 104) + 120 × (81 - 80)-$80; similar direction does not imply a profitable hedge.

Convergence profit must pay for both legs

Apply these hypothetical costs to the +$320 convergence branch, assuming a ten-calendar-day holding period. The borrowing rate and collateral amount are illustrative accounting inputs, not a current broker quote. Interactive Brokers documents borrow fees and short-sale proceeds interest as separate components, with availability and rates subject to change.

  • This example assumes no debit financing, short-proceeds interest or dividend cash flows. A real ledger must add margin-loan interest, borrow-fee collateral conventions, changing daily rates, dividends owed on the short, dividends received on the long and FX costs when applicable.
  • If actual fills already include the spread and slippage, do not subtract the $22 allowance again. A borrow fee applies over elapsed calendar days under the broker convention, including relevant non-trading days.
  • Under the same simplified fee base and holding period, a 60% annual borrow rate costs $170 and leaves $108. At 100%, borrow costs about $283.33 and the net result becomes about -$5.33 despite convergence. These are sensitivity scenarios, not observed rates.
  • A takeover of the short leg, an earnings surprise, a trading halt or recalled borrow can end the relationship or prevent a paired exit. Two positions can therefore increase operational demands even when their price risks partly offset.
Cost assumptionArithmeticDeduction
Four fills at $5 commission each2 entries + 2 exits$20
$0.05 per share per fill for spread and slippage0.05 × (100 + 120) × 2$22
Short borrow: constant $10,200 fee base, 6% annual, 360-day basis10,200 × 0.06 × 10 / 360$17
Net under these assumptions320 - 20 - 22 - 17+$261

A Pine Script monitor with fixed model inputs

Use a standard, time-based chart for leg A and select a second symbol for leg B. Replace every model input with values fitted before the evaluation start. Defaults are placeholders, not a researched pair or calibrated signal. The script checks matching bar endpoints, leaves missing observations blank and plots only on confirmed chart bars. It neither estimates cointegration nor simulates positions.

  • TradingView documents gaps_on as returning missing values where newly confirmed requested data is unavailable. The explicit timestamp comparison also rejects bars with different session boundaries. This can leave many blanks for markets with different trading hours.
  • Matching timestamps does not verify executable quotes, identical adjustment settings or feed quality. Confirm both feeds and sessions; this monitor does not convert currencies or handle corporate-action cash flows.
  • For the numerical example, A = 102 and B = 80 produce z = 2; A = 100 and B = 81 produce z = 0.4. Compare those calculations with the chosen model before using any signal.
Pine Script v6 indicator only. No orders, position state, alerts, parameter fitting or portfolio return calculation. Syntax validation does not validate the economic model.pine
//@version=6
indicator("Fixed-model pairs monitor", overlay = false)
string symbolB = input.symbol("NASDAQ:QQQ", "Leg B (chart is leg A)")
float alpha = input.float(2.0, "Frozen intercept")
float beta = input.float(1.2, "Frozen share hedge ratio", minval = 0.000001)
float mean = input.float(0.0, "Frozen residual mean")
float deviation = input.float(2.0, "Frozen residual standard deviation", minval = 0.000001)
int evaluationStart = input.time(timestamp("01 Jan 2026 00:00 +0000"), "Evaluation start")
[priceB, openTimeB, closeTimeB] = request.security(symbolB, timeframe.period, [close, time, time_close], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off)
bool aligned = not na(priceB) and openTimeB == time and closeTimeB == time_close
bool ready = aligned and barstate.isconfirmed and time >= evaluationStart
float residual = ready ? close - alpha - beta * priceB : na
float z = ready ? (residual - mean) / deviation : na
plot(z, "Frozen-model z-score", color = color.blue, linewidth = 2, style = plot.style_linebr)
hline(0, "Reference mean", color = color.gray)
hline(2, "Upper research threshold", color = color.orange)
hline(-2, "Lower research threshold", color = color.orange)
hline(3, "Upper failure threshold", color = color.red)
hline(-3, "Lower failure threshold", color = color.red)

Validate two-leg execution outside the chart strategy report

Pine can request another symbol for calculations, but request.security does not place a position in that symbol. TradingView's broker emulator uses chart data for simulated orders. A strategy on A with signals derived from B still does not supply independent B fills, borrow accounting and combined portfolio equity. A strategy on a synthetic spread chart also cannot prove those two underlying fills.

  • Use an external simulator or reconciled execution ledger with separate order timestamps, quantities, fills, cash flows and marks for each leg. Track gross exposure, cash, margin, fees and combined equity through open positions.
  • Test asynchronous fills, an unavailable short, a missing bar, a split and a forced exit. Report rejected entries, time exits, model failures and unmatched-leg losses alongside completed convergence trades.
  • Pine Script AI Coding Agent can help draft or revise the monitor from these explicit formulas. Ask for a syntax check and review the output. Pineify does not establish this pair's validity or provide a complete two-leg portfolio execution system through this workflow.
Where Pineify fits

Pine Script AI Coding Agent

Draft a spread-monitoring indicator with explicit symbols, frozen coefficients and missing-data rules. Request syntax validation, then verify the relationship and both legs in a separate research workflow.

Draft a spread monitor

Frequently asked questions

Educational research, not investment advice. All prices, model inputs, thresholds and costs are hypothetical; no performance claim or suitable pair is established. Short selling can incur unbounded losses, borrowing can become unavailable, and a statistical relationship can fail. Syntax validity does not establish trading validity.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.