本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jabez4jc
//@version=6
// @description Option chain on TradingView data. `row()` requests one strike's call and put (last price and volume)
// and scores it: an SWMA-smoothed volume put/call ratio and a price/volume flow score. `summary()` gives
// the chain-wide PCR and flow, the `*At()` methods look a strike up, and the text helpers label biases.
// Tickers use TradingView's option format, e.g. NSE:NIFTY260224C23500.
library("OptionChain", overlay = true)
import jabez4jc/UIKit/1 as ui
//#region ———————————————————— Scoring
// @function Volume put/call ratio.
// @param putVol (series float) Put volume.
// @param callVol (series float) Call volume.
// @returns (float) put / call; 0 when both are 0, 10 when only the call side is 0, `na` when either is `na`.
export volumePcr(float putVol, float callVol) =>
float pcr = na
if not na(putVol) and not na(callVol)
pcr := callVol > 0 ? putVol / callVol : putVol <= 0 ? 0.0 : 10.0
pcr
// @function Price / volume flow score of one option, from the underlying's point of view. Call: price and volume up
// = +2 (buyers), price up on falling volume = +1, price down on rising volume = -2 (writers), else 0.
// Put: the mirror, plus price and volume down = +1.
// @param px (series float) Option price.
// @param prevPx (series float) Previous option price.
// @param vol (series float) Option volume.
// @param prevVol (series float) Previous option volume.
// @param isCall (series bool) `true` for a call, `false` for a put.
// @returns (float) The score, or `na` when any input is `na`.
export pvFlow(float px, float prevPx, float vol, float prevVol, bool isCall) =>
float score = na
if not na(px) and not na(prevPx) and not na(vol) and not na(prevVol)
float dPx = px - prevPx
float dVol = vol - prevVol
score := isCall ? (dPx > 0 and dVol > 0 ? 2 : dPx > 0 and dVol < 0 ? 1 : dPx < 0 and dVol > 0 ? -2 : 0)
: (dPx > 0 and dVol > 0 ? -2 : dPx > 0 and dVol < 0 ? -1 : dPx < 0 and dVol > 0 ? 2 : dPx < 0 and dVol < 0 ? 1 : 0)
score
// @function Flow bias label: >= 3 "Strong Bull", >= 1 "Bull", <= -3 "Strong Bear", <= -1 "Bear", else "Neutral".
// @param score (series float) A flow score.
// @returns (string) The label, or "NA".
export flowBias(float score) =>
na(score) ? "NA" : score >= 3 ? "Strong Bull" : score >= 1 ? "Bull" : score <= -3 ? "Strong Bear" : score <= -1 ? "Bear" : "Neutral"
// @function PCR bias label.
// @param pcr (series float) A put/call ratio.
// @param bullAbove (series float) Bullish above this PCR.
// @param bearBelow (series float) Bearish below this PCR.
// @returns (string) "Bullish", "Bearish", "Neutral" or "NA".
export pcrBias(float pcr, float bullAbove, float bearBelow) =>
na(pcr) ? "NA" : pcr > bullAbove ? "Bullish" : pcr < bearBelow ? "Bearish" : "Neutral"
// @function Combined PCR + flow setup: LONG when both are bullish (Strong when flow >= 3), SHORT when both are
// bearish, otherwise WAIT (Conflict / Unconfirmed / Neutral).
// @param pcr (series float) A put/call ratio.
// @param flow (series float) A flow score.
// @param bullAbove (series float) Bullish above this PCR.
// @param bearBelow (series float) Bearish below this PCR.
// @returns (string) The setup label.
export setupText(float pcr, float flow, float bullAbove, float bearBelow) =>
bool pcrBull = pcr > bullAbove
bool pcrBear = pcr < bearBelow
bool flowBull = flow >= 1
bool flowBear = flow <= -1
na(pcr) or na(flow) ? "Setup NA"
: pcrBull and flowBull ? (flow >= 3 ? "Setup LONG (Strong)" : "Setup LONG")
: pcrBear and flowBear ? (flow <= -3 ? "Setup SHORT (Strong)" : "Setup SHORT")
: (pcrBull and flowBear) or (pcrBear and flowBull) ? "Setup WAIT (Conflict)"
: pcrBull or pcrBear or flowBull or flowBear ? "Setup WAIT (Unconfirmed)"
: "Setup WAIT (Neutral)"
//#endregion
//#region ———————————————————— Chain rows
// @type One strike of the chain, returned by `row()`. `*Prev` fields hold the previous bar's values.
// @field strike Strike price.
// @field ceLtp Call last price.
// @field ceVol Call volume.
// @field peLtp Put last price.
// @field peVol Put volume.
// @field ceLtpPrev Previous call last price.
// @field ceVolPrev Previous call volume.
// @field peLtpPrev Previous put last price.
// @field peVolPrev Previous put volume.
// @field pcr SWMA-smoothed volume PCR (a missing PCR counts as 1).
// @field pcrPrev Previous smoothed PCR.
// @field flow Call + put flow score (`na` when both are `na`).
export type Row
int strike
float ceLtp
float ceVol
float peLtp
float peVol
float ceLtpPrev
float ceVolPrev
float peLtpPrev
float peVolPrev
float pcr
float pcrPrev
float flow
// @function Requests one strike's call and put (two `request.security()` calls on the chart timeframe; a strike
// that doesn't exist returns `na` values) and scores it. Call it once per bar per strike, unconditionally,
// so each call keeps its own history.
// @param exch (series string) TradingView exchange of the options, e.g. "NSE".
// @param root (series string) Underlying root symbol, e.g. "NIFTY".
// @param expiry (series string) Expiry in TradingView's YYMMDD form, e.g. "260224".
// @param strike (series int) Strike price.
// @returns (Row) The strike's data and scores.
export row(string exch, string root, string expiry, int strike) =>
string base = exch + ":" + root + expiry
[ceLtp, ceVol] = request.security(base + "C" + str.tostring(strike), timeframe.period, [close, volume], barmerge.gaps_off, barmerge.lookahead_off, ignore_invalid_symbol = true)
[peLtp, peVol] = request.security(base + "P" + str.tostring(strike), timeframe.period, [close, volume], barmerge.gaps_off, barmerge.lookahead_off, ignore_invalid_symbol = true)
float pcr = ta.swma(nz(volumePcr(peVol, ceVol), 1.0))
float ceFlow = pvFlow(ceLtp, ceLtp[1], ceVol, ceVol[1], true)
float peFlow = pvFlow(peLtp, peLtp[1], peVol, peVol[1], false)
float flow = na(ceFlow) and na(peFlow) ? na : nz(ceFlow) + nz(peFlow)
Row.new(strike, ceLtp, ceVol, peLtp, peVol, ceLtp[1], ceVol[1], peLtp[1], peVol[1], pcr, pcr[1], flow)
// @function Chain-wide readings: the SWMA-smoothed PCR of the total put and call volume, and the SWMA-smoothed sum
// of the row flow scores. Call it once per bar, unconditionally.
// @param rows (array<Row>) The chain's rows.
// @returns ([float, float]) The smoothed chain PCR, and the smoothed chain flow (`na` when no row has a flow score).
export summary(array<Row> rows) =>
float ceTotal = 0.0
float peTotal = 0.0
float flowSum = 0.0
int nFlow = 0
for r in rows
ceTotal += nz(r.ceVol)
peTotal += nz(r.peVol)
if not na(r.flow)
flowSum += r.flow
nFlow += 1
float pcr = ta.swma(nz(volumePcr(peTotal, ceTotal), 1.0))
float flow = ta.swma(nFlow > 0 ? flowSum : 0.0)
[pcr, nFlow > 0 ? flow : na]
findRow(array<Row> rows, int strike) =>
Row found = na
for r in rows
if r.strike == strike
found := r
break
found
// @function Smoothed PCR of a strike.
// @param rows (array<Row>) The chain's rows.
// @param strike (series int) Strike to look up.
// @returns (float) The strike's smoothed PCR, or `na` when the strike isn't in the chain.
export method pcrAt(array<Row> rows, int strike) =>
Row r = findRow(rows, strike)
na(r) ? na : r.pcr
// @function Call last price of a strike.
// @param rows (array<Row>) The chain's rows.
// @param strike (series int) Strike to look up.
// @returns (float) The call's last price, or `na` when the strike isn't in the chain.
export method ceLtpAt(array<Row> rows, int strike) =>
Row r = findRow(rows, strike)
na(r) ? na : r.ceLtp
// @function Put last price of a strike.
// @param rows (array<Row>) The chain's rows.
// @param strike (series int) Strike to look up.
// @returns (float) The put's last price, or `na` when the strike isn't in the chain.
export method peLtpAt(array<Row> rows, int strike) =>
Row r = findRow(rows, strike)
na(r) ? na : r.peLtp
//#endregion
//#region ———————————————————— Chain table
// "▲ " / "▼ " / "• " for a value that rose, fell or did not change
trendMarker(float cur, float prev) =>
na(cur) or na(prev) ? "• " : cur > prev ? "▲ " : cur < prev ? "▼ " : "• "
trendText(float cur, float prev, string valueText) =>
na(cur) ? "—" : trendMarker(cur, prev) + valueText
trendColor(float cur, float prev, color up, color down, color flat) =>
na(cur) or na(prev) ? flat : cur > prev ? up : cur < prev ? down : flat
// Change of a reading against its bias: "Stronger" / "Weaker" with a bias, "Rising" / "Falling" without one
trendState(float cur, float prev, bool bull, bool bear) =>
na(cur) or na(prev) ? "NA" : cur == prev ? "Flat" : bull ? (cur > prev ? "Stronger" : "Weaker") : bear ? (cur < prev ? "Stronger" : "Weaker") : cur > prev ? "Rising" : "Falling"
pcrColor(float pcr, float bullAbove, float bearBelow, ui.Theme th) =>
na(pcr) ? th.neutral : pcr > bullAbove ? th.up : pcr < bearBelow ? th.down : th.warn
flowColor(float score, ui.Theme th) =>
na(score) ? th.neutral : score >= 3 ? th.up : score <= -3 ? th.down
: score >= 1 ? (th.dark ? color.rgb(110, 225, 125) : color.rgb(20, 130, 40))
: score <= -1 ? (th.dark ? color.rgb(255, 170, 120) : color.rgb(170, 70, 0)) : th.neutral
fmtPcr(float pcr) =>
na(pcr) ? "—" : str.tostring(pcr, "#.##")
// @function Draws the chain into a table with 7 columns and `rows.size() + 2` rows (create it with `UIKit.newTable()`):
// CE LTP and volume, strike, smoothed PCR, flow, PE volume and LTP for every strike, each with its change
// against the previous bar, the traded CE / PE strikes and the center strike highlighted, and a footer with
// the chain PCR, chain flow and the combined setup. Call it on the last bar.
// @param rows (array<Row>) The chain's rows, lowest strike first.
// @param t (table) The table.
// @param th (UIKit.Theme) Colours and text size.
// @param center (series int) Center strike (highlighted).
// @param ceStrike (series int) Strike of the call that would be traded (highlighted).
// @param peStrike (series int) Strike of the put that would be traded (highlighted).
// @param cumPcr (series float) Chain PCR from `summary()`.
// @param cumPcrPrev (series float) Chain PCR on the previous bar.
// @param cumFlow (series float) Chain flow from `summary()`.
// @param cumFlowPrev (series float) Chain flow on the previous bar.
// @param bullAbove (series float) Bullish above this PCR.
// @param bearBelow (series float) Bearish below this PCR.
// @returns (void)
export method drawTable(array<Row> rows, table t, ui.Theme th, int center, int ceStrike, int peStrike, float cumPcr, float cumPcrPrev, float cumFlow, float cumFlowPrev, float bullAbove, float bearBelow) =>
array<string> heads = array.from("CE LTP", "CE Vol", "Strike", "SWMA PCR", "Flow C+P", "PE Vol", "PE LTP")
array<color> headCols = array.from(th.up, th.up, th.warn, th.neutral, th.aqua, th.warn, th.down)
for [c, h] in heads
t.cell(c, 0, h, text_color = headCols.get(c), text_size = th.textSize, bgcolor = th.headerBg)
for [i, r] in rows
int row = i + 1
bool isCe = r.strike == ceStrike
bool isPe = r.strike == peStrike
bool isCenter = r.strike == center
color midBg = isCenter or isCe or isPe ? th.accentBg : th.bodyBg
color ceBg = isCe ? th.longBg : th.bodyBg
color peBg = isPe ? th.shortBg : th.bodyBg
t.cell(0, row, trendText(r.ceLtp, r.ceLtpPrev, str.tostring(r.ceLtp, format.mintick)), text_color = isCe ? color.black : trendColor(r.ceLtp, r.ceLtpPrev, th.up, th.down, th.up), text_size = th.textSize, bgcolor = ceBg)
t.cell(1, row, trendText(r.ceVol, r.ceVolPrev, str.tostring(math.round(r.ceVol), format.volume)), text_color = isCe ? color.black : trendColor(r.ceVol, r.ceVolPrev, th.up, th.down, th.up), text_size = th.textSize, bgcolor = ceBg)
t.cell(2, row, str.tostring(r.strike), text_color = isCenter ? th.warn : th.neutral, text_size = th.textSize, bgcolor = isCenter ? th.centerBg : midBg)
t.cell(3, row, trendText(r.pcr, r.pcrPrev, fmtPcr(r.pcr)), text_color = trendColor(r.pcr, r.pcrPrev, th.up, th.down, pcrColor(r.pcr, bullAbove, bearBelow, th)), text_size = th.textSize, bgcolor = midBg)
t.cell(4, row, flowBias(r.flow), text_color = flowColor(r.flow, th), text_size = th.textSize, bgcolor = midBg)
t.cell(5, row, trendText(r.peVol, r.peVolPrev, str.tostring(math.round(r.peVol), format.volume)), text_color = isPe ? color.black : trendColor(r.peVol, r.peVolPrev, th.up, th.down, th.warn), text_size = th.textSize, bgcolor = peBg)
t.cell(6, row, trendText(r.peLtp, r.peLtpPrev, str.tostring(r.peLtp, format.mintick)), text_color = isPe ? color.black : trendColor(r.peLtp, r.peLtpPrev, th.up, th.down, th.down), text_size = th.textSize, bgcolor = peBg)
int foot = rows.size() + 1
bool pcrBull = cumPcr > bullAbove
bool pcrBear = cumPcr < bearBelow
bool flowBull = cumFlow >= 1
bool flowBear = cumFlow <= -1
color setupCol = pcrBull and flowBull ? th.up : pcrBear and flowBear ? th.down : pcrBull or pcrBear or flowBull or flowBear ? th.warn : th.neutral
t.cell(0, foot, "Center " + str.tostring(center), text_color = th.warn, text_size = th.textSize, bgcolor = th.footerBg)
t.cell(1, foot, "CE " + str.tostring(ceStrike), text_color = th.up, text_size = th.textSize, bgcolor = th.footerBg)
t.cell(2, foot, "PE " + str.tostring(peStrike), text_color = th.down, text_size = th.textSize, bgcolor = th.footerBg)
t.cell(3, foot, fmtPcr(cumPcr) + " " + pcrBias(cumPcr, bullAbove, bearBelow) + " (" + trendState(cumPcr, cumPcrPrev, pcrBull, pcrBear) + ")", text_color = pcrColor(cumPcr, bullAbove, bearBelow, th), text_size = th.textSize, bgcolor = th.footerBg)
t.cell(4, foot, (na(cumFlow) ? "NA" : str.tostring(cumFlow, "#.##")) + " " + flowBias(cumFlow) + " (" + trendState(cumFlow, cumFlowPrev, flowBull, flowBear) + ")", text_color = flowColor(cumFlow, th), text_size = th.textSize, bgcolor = th.footerBg)
t.merge_cells(5, foot, 6, foot)
t.cell(5, foot, setupText(cumPcr, cumFlow, bullAbove, bearBelow), text_color = setupCol, text_size = th.textSize, bgcolor = th.footerBg)
//#endregion
//#region ———————————————————— Demo
// 5 strikes around a fixed center. Adjust the expiry and center to a live NIFTY series.
string demoExpiry = input.string("260224", "Expiry (YYMMDD)")
int demoCenter = input.int(23500, "Center strike", step = 50)
array<Row> demoRows = array.from(row("NSE", "NIFTY", demoExpiry, demoCenter - 100), row("NSE", "NIFTY", demoExpiry, demoCenter - 50),
row("NSE", "NIFTY", demoExpiry, demoCenter), row("NSE", "NIFTY", demoExpiry, demoCenter + 50),
row("NSE", "NIFTY", demoExpiry, demoCenter + 100))
[demoPcr, demoFlow] = summary(demoRows)
// Ratios and scores are far from the price scale, so they show in the status line and Data Window only
plot(demoPcr, "Chain PCR (SWMA)", color.orange, display = display.status_line + display.data_window)
plot(demoFlow, "Chain flow (SWMA)", color.aqua, display = display.status_line + display.data_window)
// Looking a strike up, and scoring one row by hand
Row demoAtm = demoRows.get(2)
plot(demoRows.pcrAt(demoCenter), "pcrAt() center", display = display.data_window)
plot(demoRows.ceLtpAt(demoCenter), "ceLtpAt() center", display = display.data_window)
plot(demoRows.peLtpAt(demoCenter), "peLtpAt() center", display = display.data_window)
plot(volumePcr(demoAtm.peVol, demoAtm.ceVol), "volumePcr() center, unsmoothed", display = display.data_window)
plot(pvFlow(demoAtm.ceLtp, demoAtm.ceLtpPrev, demoAtm.ceVol, demoAtm.ceVolPrev, true), "pvFlow() center call", display = display.data_window)
// The chain table, and the text labels in the Pine Logs pane
var table demoTable = ui.newTable("Bottom Right", 7, 7)
if barstate.islast
demoRows.drawTable(demoTable, ui.theme("Auto"), demoCenter, demoCenter + 50, demoCenter - 50, demoPcr, demoPcr[1], demoFlow, demoFlow[1], 1.2, 0.8)
if barstate.islastconfirmedhistory
log.info("PCR {0}, flow {1}, {2}", pcrBias(demoPcr, 1.2, 0.8), flowBias(demoFlow), setupText(demoPcr, demoFlow, 1.2, 0.8))
//#endregion