本页源码来自 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 Helpers for strategies that route orders to OpenAlgo through TradingView alerts: symbol and expiry
// conversion between OpenAlgo (NFO:NIFTY24FEB2623500CE) and TradingView (NSE:NIFTY260224C23500)
// formats, ATM strike rounding, the OpenAlgo order JSON, custom alert templates, an end-of-day time
// check and an all-selected-filters gate.
library("OpenAlgo", overlay = true)
//#region ———————————————————— Symbols
// @function Converts an OpenAlgo expiry (DDMMMYY, e.g. "24FEB26") to TradingView's YYMMDD (e.g. "260224").
// @param expiry (series string) Expiry in DDMMMYY form.
// @returns (string) The expiry in YYMMDD form ("00" as the month when it isn't recognised).
export tvExpiry(string expiry) =>
int m = array.from("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC").indexof(str.upper(str.substring(expiry, 2, 5))) + 1
string mm = (m < 10 ? "0" : "") + str.tostring(m)
str.substring(expiry, 5, 7) + mm + str.substring(expiry, 0, 2)
// @function Exchange prefix of a ticker, e.g. "NSE" for "NSE:NIFTY1!".
// @param tickerid (series string) A ticker with or without an exchange prefix.
// @param dflt (series string) Returned when there is no prefix. Optional. Default is "NSE".
// @returns (string) The exchange.
export exchangeOf(string tickerid, string dflt = "NSE") =>
int p = str.pos(tickerid, ":")
na(p) or p < 0 ? dflt : str.substring(tickerid, 0, p)
// @function Root symbol of a ticker: the exchange prefix and continuous-contract suffixes ("1!", "2!", "!") removed,
// e.g. "NIFTY" for "NSE:NIFTY1!".
// @param tickerid (series string) A ticker with or without an exchange prefix.
// @returns (string) The root symbol.
export rootSymbol(string tickerid) =>
int p = str.pos(tickerid, ":")
string sym = na(p) or p < 0 ? tickerid : str.substring(tickerid, p + 1, str.length(tickerid))
str.replace_all(str.replace_all(str.replace_all(sym, "1!", ""), "2!", ""), "!", "")
// @function Nearest strike to a price on a strike grid (a remainder of exactly half an interval rounds down).
// @param price (series float) Underlying price.
// @param interval (series int) Strike interval, e.g. 50.
// @returns (float) The strike.
export atmStrike(float price, int interval) =>
float rem = price % interval
rem > interval / 2 ? price - rem + interval : price - rem
// @function OpenAlgo option symbol, e.g. "NIFTY24FEB2623500CE".
// @param root (series string) Root symbol, e.g. "NIFTY".
// @param expiry (series string) Expiry in DDMMMYY form, e.g. "24FEB26".
// @param strike (series float) Strike (rounded to an integer).
// @param isCall (series bool) `true` for CE, `false` for PE.
// @returns (string) The option symbol.
export optionSymbol(string root, string expiry, float strike, bool isCall) =>
root + expiry + str.tostring(math.round(strike)) + (isCall ? "CE" : "PE")
//#endregion
//#region ———————————————————— Orders and alerts
// @function OpenAlgo `placesmartorder` JSON payload.
// @param apikey (series string) OpenAlgo API key.
// @param strategyName (series string) Strategy name.
// @param symbol (series string) OpenAlgo symbol.
// @param action (series string) "BUY" or "SELL".
// @param exch (series string) OpenAlgo exchange, e.g. "NFO".
// @param priceType (series string) "MARKET" or "LIMIT".
// @param price (series string) Limit price ("0" for market orders).
// @param product (series string) "MIS", "NRML" or "CNC".
// @param quantity (series string) Order quantity, in lots.
// @param positionSize (series string) Target position after the order ("0" = flat, "-N" = short N).
// @returns (string) The JSON payload.
export orderJson(string apikey, string strategyName, string symbol, string action, string exch, string priceType, string price, string product, string quantity, string positionSize) =>
'{ "apikey":"' + apikey + '", "strategy":"' + strategyName + '", "symbol":"' + symbol + '", "action":"' + action + '", "exchange":"' + exch + '", "pricetype":"' + priceType + '", "price":"' + price + '", "product":"' + product + '", "quantity":"' + quantity + '", "position_size":"' + positionSize + '" }'
// @function Fills a custom alert template. Placeholders: {{signal}}, {{exchange}}, {{symbol}}, {{action}}, {{price}},
// {{quantity}}, {{strategy}}.
// @param template (series string) The template.
// @param signal (series string) Signal name, e.g. "BUY" or "COVER".
// @param symbol (series string) Symbol.
// @param action (series string) Order action.
// @param exch (series string) Exchange.
// @param price (series string) Price.
// @param quantity (series string) Quantity.
// @param strategyName (series string) Strategy name.
// @returns (string) The filled message.
export fillTemplate(string template, string signal, string symbol, string action, string exch, string price, string quantity, string strategyName) =>
string msg = str.replace_all(template, "{{signal}}", signal)
msg := str.replace_all(msg, "{{exchange}}", exch)
msg := str.replace_all(msg, "{{symbol}}", symbol)
msg := str.replace_all(msg, "{{action}}", action)
msg := str.replace_all(msg, "{{price}}", price)
msg := str.replace_all(msg, "{{quantity}}", quantity)
str.replace_all(msg, "{{strategy}}", strategyName)
//#endregion
//#region ———————————————————— Strategy gates
// @function Whether the bar's time (in the exchange time zone) is at or past an HHMM time, e.g. for an end-of-day
// square-off.
// @param hhmm (series int) Time as HHMM, e.g. 1525.
// @returns (bool) `true` from that minute to the end of the day.
export pastTime(int hhmm) =>
int h = hour(time, syminfo.timezone)
int m = minute(time, syminfo.timezone)
h > hhmm / 100 or (h == math.floor(hhmm / 100) and m >= hhmm % 100)
// @function Filter gate: `true` when at least one filter is enabled and every enabled filter passed.
// @param enabled (array<bool>) Which filters are enabled.
// @param passed (array<bool>) Which filters passed, in the same order.
// @returns (bool) The gate.
export allPass(array<bool> enabled, array<bool> passed) =>
int nOn = 0
int nOk = 0
for [i, on] in enabled
if on
nOn += 1
nOk += passed.get(i) ? 1 : 0
nOn > 0 and nOk == nOn
//#endregion
//#region ———————————————————— Demo
// Option symbols for the at-the-money call, in OpenAlgo and TradingView formats
string demoExpiry = "24FEB26"
string demoRoot = rootSymbol("NSE:NIFTY1!")
float demoStrike = atmStrike(close, 50)
string demoSymbol = optionSymbol(demoRoot, demoExpiry, demoStrike, true)
string demoTv = exchangeOf("NSE:NIFTY1!") + ":" + demoRoot + tvExpiry(demoExpiry) + "C" + str.tostring(math.round(demoStrike))
// A filter gate (trend and momentum enabled, a third filter disabled) and the end-of-day square-off window
bool demoGate = allPass(array.from(true, true, false), array.from(close > ta.ema(close, 20), ta.rsi(close, 14) > 50, false))
plotshape(demoGate and not demoGate[1], "allPass() gate opened", shape.triangleup, location.belowbar, color.teal, size = size.tiny)
bgcolor(pastTime(1515) ? color.new(color.red, 90) : na, title = "pastTime(1515)")
// The order payload and a custom alert message for that call
var label demoInfo = label.new(na, na, "", color = color.new(color.gray, 80), style = label.style_label_left, textcolor = chart.fg_color, textalign = text.align_left)
if barstate.islast
string json = orderJson("YOUR_API_KEY", "Demo", demoSymbol, "BUY", "NFO", "MARKET", "0", "MIS", "1", "1")
string msg = fillTemplate("{{signal}}: {{action}} {{quantity}} x {{symbol}} on {{exchange}} at {{price}} ({{strategy}})", "BUY", demoSymbol, "BUY", "NFO", str.tostring(close, format.mintick), "1", "Demo")
demoInfo.set_xy(bar_index + 2, close)
demoInfo.set_text(demoSymbol + "\nTradingView: " + demoTv + "\n" + msg + "\n" + json)
//#endregion