Can Anybody Create JSON For This Strategy

// @version=5
// Open-Range-Breakout strategy
// No license. Free and Open Source.

strategy(‘Strategy: ORB’, shorttitle=“ORB”, overlay=true , currency=currency.NONE, initial_capital=100000)

// Inputs
period = input.int(defval=15, title=“TimeRange”, tooltip=“The range in minutes (default: 15m)”)
sessionInput = input.session(defval=“0915-0930”, title=“Time Range”, group=“ORB settings”, tooltip=‘What is the timeperiod (default 9:15AM to 9:30AM, exchange timezone’)
hide = input.bool(defval = false, title=“Hide ORB Range”, group=“ORB setting”, tooltip = ‘Hide the ORB range drawing’)

// SL Related
slAtrLen = input.int(defval=14, title=“ATR Period for placing SL”, group=“StopLoss settings”)
showSLLines = input.bool(defval=false, title=“Show SL lines in chart”, tooltip=“Show SL lines also as dotted lines in chart. Note: chart may look untidy.”, group=“StopLoss settings”)

// Further Filtering
ignoreMementumVolume = input.bool(defval=false, title=“Ignore Momentum & Volume”, tooltip=“Ignore Momentum & Volume to find out trades”, group=“Strengh Settings”)
rsiLen = input.int(defval=14, title=“Momentum Period”, group=“Strengh Settings”, tooltip = ‘To determine the momentum, RSI period is set default to 100’)
rsiBullish = input.int(defval=50, step=1, title=“Bullish Momentum”, group=“Strengh Settings”, tooltip = ‘Bullish Momentum, default set to RSI as 50’)
rsiBearish = input.int(defval=50, step=1, title=“Bearish Momentum”, group=“Strengh Settings”, tooltip = ‘Bearish Momentum, default set to RSI as 50’)
volAvg = input.int(defval=20, step=1, title=“Volume Average Period”, group=“Strengh Settings”, tooltip = ‘To calculate average volume, how many historical bars are considered. Default: 20.’)
volThreshold = input.float(defval=1, step=0.1, title=“Volume Strengh”, group=“Strengh Settings”, tooltip = ‘Multiplier: How big the current bar volume compared to average of last 20’)

trendPeriod = input.int(defval=200, step=1, title=“Trend Period”, group=“Trend Settings”, tooltip = ‘To calculate trend, what period is considered. Default: 200.’)
hideTrend = input.bool(defval = false, title=“Hide the trend line”, group=“Trend Settings”, tooltip = ‘Hide the trend’)

hidePDHCL = input.bool(defval = false, title=“Hide the PDHCL (prev day High Close Low range) & VWAP”, tooltip = ‘Hide the Previous Day High, Close, Low lines, including VWAP’)

hideTable = input.bool(defval = false, title=“Hide the Summary Table”, tooltip = ‘Hide the summary table.’)

// Trade related
rrRatio = input.float(title=‘Risk:Reward’, step=0.1, defval=2.0, group=“Trade settings”)
endOfDay = input.int(defval=1500, title=“Close all trades, default is 3:00 PM, 1500 hours (integer)”, group=“Trade settings”)
mktAlwaysOn = input.bool(defval=true, title=“Markets that never closed (Crypto, Forex, Commodity)”, tooltip=“Some markers never closes. For those cases, make this checked.”, group=“Trade settings”)
lotSize = input.int(title=‘Lot Size’, step=1, defval=1, group=“Trade settings”)

// Util method

is_newbar(res) =>
timeframe.change(time(res)) != 0

annotatePlots(txt, val, hide) =>
if (not hide)
var l1 = label.new(bar_index, hidePDHCL ? na : val, txt, style=label.style_label_left, size = size.tiny, textcolor = color.white, tooltip = txt)
label.set_xy(l1, bar_index, hidePDHCL ? na : val)

// print table
printTable(txt) =>
var table t = table.new(position.bottom_right, 1, 1)
table.cell(t, 0, 0, txt, text_halign = text.align_left, bgcolor = color.lime)

// globals
t = time(timeframe.period, sessionInput + “:1234567”) // everyday
in_session = not na(t)
is_first = in_session and not in_session[1]
is_end_session = in_session[1] and not in_session
green(open, close) => close > open ? true : false
red(open, close) => close < open ? true : false

var float orb_high = na
var float orb_low = na
if is_first
orb_high := high
orb_low := low
else
orb_high := orb_high[1]
orb_low := orb_low[1]
if high > orb_high and in_session
orb_high := high
if low < orb_low and in_session
orb_low := low

plot(hide ? na : orb_high, style=plot.style_line, color=orb_high[1] != orb_high ? na : color.green, title=“ORB High”, linewidth=2)
annotatePlots(‘ORB-H’, orb_high, hide)
plot(hide ? na : orb_low, style=plot.style_line, color=orb_low[1] != orb_low ? na : color.red, title=“ORB Low”, linewidth=2)
annotatePlots(‘ORB-L’, orb_low, hide)

// PDHCL (Previous Day High Close Low)
[dh,dl,dc] = request.security(syminfo.ticker, “D”, [high[1],low[1], close[1]], lookahead=barmerge.lookahead_on)
plot(hidePDHCL ? na : dh, title=“Prev High”, color=color.red, linewidth=2, trackprice=true, show_last = 1)
annotatePlots(‘PDH’, dh, hidePDHCL)
plot(hidePDHCL ? na : dl, title=“Prev Low”, color=color.green, linewidth=2, trackprice=true, show_last = 1)
annotatePlots(‘PDL’, dl, hidePDHCL)
plot(hidePDHCL ? na : dc, title=“Prev Close”, color=color.black, linewidth=2, trackprice=true, show_last = 1)
annotatePlots(‘PDC’, dc, hidePDHCL)
plot(hidePDHCL ? na : ta.vwap(close), title=“VWAP”, color=color.fuchsia, linewidth=2, trackprice=true, show_last = 1)
annotatePlots(‘VWAP’, ta.vwap(close), hidePDHCL)

// For SL calculation
atr = ta.atr(slAtrLen)
highestHigh = ta.highest(high, 7)
lowestLow = ta.lowest(low, 7)
longStop = showSLLines ? lowestLow - (atr * 1) : na
shortStop = showSLLines ? highestHigh + (atr * 1) : na
plot(longStop, title=“Buy SL”, color=color.green, style=plot.style_cross)
plot(shortStop, title=“Sell SL”, color=color.red, style=plot.style_cross)
annotatePlots(‘SL-Long’, longStop, showSLLines)
annotatePlots(‘SL-Short’, shortStop, showSLLines)

// Momentum: rsi
rsi = ta.rsi(close, rsiLen)

// trend: EMA200
ema = ta.ema(close, trendPeriod)
plot(hideTrend ? na : ema, “EMA Trend”, color=close > ema ? color.green : color.red, linewidth = 1)
annotatePlots(‘Trendline’, ema, hideTrend)

// Volume-Weighed Moving Average calculation
vwmaAvg = ta.vwma(close, volAvg)
vwma_latest = volume
// plotshape((barstate.isconfirmed and (vwma_latest > (vwmaAvg * volThreshold))), title=‘VolumeData’, text=‘’, location=location.abovebar, style=shape.diamond, color=color.gray, textcolor=color.gray, size=size.tiny)

// Trade signals

longCond = barstate.isconfirmed and (ta.crossover(close, orb_high) or ta.crossover(close, dh)) and green(open, close) and (ignoreMementumVolume ? true : rsi > rsiBullish and (vwma_latest > (vwmaAvg * volThreshold)))
shortCond = barstate.isconfirmed and (ta.crossunder(close, orb_low) or ta.crossunder(close, dl)) and red(open, close) and (ignoreMementumVolume ? true : rsi < rsiBearish and (vwma_latest > (vwmaAvg * volThreshold)))

plotshape(longCond, title=‘Breakout’, text=‘BO’, location=location.belowbar, style=shape.triangleup, color=color.green, textcolor=color.green)
plotshape(shortCond, title=‘Breakout’, text=‘BD’, location=location.abovebar, style=shape.triangledown, color=color.red, textcolor=color.red)

// Trade execute
h = hour(time(‘1’), syminfo.timezone)
m = minute(time(‘1’), syminfo.timezone)
hourVal = h * 100 + m
totalTrades = strategy.opentrades + strategy.closedtrades
if (mktAlwaysOn or (hourVal < endOfDay))
// Entry
var float sl = na
var float target = na
if (longCond)
strategy.entry(“enter long”, strategy.long, lotSize, limit=na, stop=na, comment=“Enter Long”)
sl := longStop
target := close + ((close - longStop) * rrRatio)
alert(‘Buy:’ + syminfo.ticker + ’ ,SL:’ + str.tostring(math.floor(sl)) + ‘, Target:’ + str.tostring(target), alert.freq_once_per_bar)
if (shortCond)
strategy.entry(“enter short”, strategy.short, lotSize, limit=na, stop=na, comment=“Enter Short”)
sl := shortStop
target := close - ((shortStop - close) * rrRatio)
alert(‘Sell:’ + syminfo.ticker + ’ ,SL:’ + str.tostring(math.floor(sl)) + ‘, Target:’ + str.tostring(target), alert.freq_once_per_bar)

// Exit: target or SL
if ((close >= target) or (close <= sl))
    strategy.close("enter long", comment=close < sl ? "Long SL hit" : "Long target hit")
if ((close <= target) or (close >= sl))
    strategy.close("enter short", comment=close > sl ? "Short SL hit" : "Short target hit")

else if (not mktAlwaysOn)
// Close all open position at the end if Day
strategy.close_all(comment = “Close all entries at end of day.”)

// Plotting table
if (not hideTable and is_end_session)
message = syminfo.ticker + " :\n\nORB Upper: " + str.tostring(math.round(orb_high)) + "\nORB Lower: " + str.tostring(math.round(orb_low)) + "\nPDH: " + str.tostring(math.round(dh)) + "\nPDC: " + str.tostring(math.round(dc)) + "\nPDL: " + str.tostring(math.round(dl)) + "\nVWAP: " + str.tostring(math.round(ta.vwap(close)))
printTable(message)
alert(message, alert.freq_once_per_bar_close)

Hello @arbind04

You can take some idea from @t7support’s session: Exclusive Webinar: Pine Script for Beginners by t7support 🚀

hi i have visited the webinar.but i have some problem which is not covered in the webinar.
i have a orb strategy which is increasing +1 quantity after exit of 1st trade,the quantity increases till 5th entry.
In this strategy if the price is above orb range on long alert atm ce has to be buy and if there is a short signal atm pe has to be buy.after exit of 1st buy of atm ce or atm pe 2nd buy of atm ce or pe with 2 quantity.Iam unable to create jason for this.my developer developer this file …please check it and notify me if there is any correction

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at Mozilla Public License, version 2.0
// © kaharkaboodi

//@version=5
strategy(“Orb”, overlay=true,max_lines_count = 500)
SecretCode = input.string(“ZYyoi”)
StartTime = input.string(“0915-0000”)
Session = input(“0915-1215”)

t = time(timeframe.period, Session,timezone =“UTC+5:30”)
rangemax = input.float(60)
rangemin = input.float(30)
farfromUPDown = input.float(20)
tp = input.float(2000)
BufferLine = input.bool(true)
BufferPoint = input.int(20)
// FirstBuySellStop = input.string(“H2”,options = [“H2”,“L1”])
FirstBuySellStop = “H2”

//ADX
ADX = input.bool(true)
adxlen = input(14, title=“ADX Smoothing”)
dilen = input(14, title=“DI Length”)
dirmov(len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)

bool ADXCond = na
if ADX
ADXCond := sig > sig[1]
if ADX == false
ADXCond := true

var buy = false
var sell = false

var YouHaveAllow = false
var dotrade = false
var Count = 0
var SlBuyCounter = 1
//controler
var bool FirstBuy = false
var bool FirstSell = false
var secSellControl = false

if ((high - low > rangemin) and (high - low < rangemax)) and Count == 1
YouHaveAllow := false

if ((high - low > rangemin) and (high - low < rangemax) and Count == 0 )
YouHaveAllow := true
Count := 1
isNewDay = time == time(“1D”, StartTime,timezone = “UTC+5:30”)
if isNewDay
Count := 0
dotrade := false
FirstBuy := false
FirstSell := false
SlBuyCounter := 1
buy := false
sell := false
strategy.close_all(“Closed For New Day”)
if na(t)
strategy.close_all(“Closed For New Day”)
if isNewDay[1]
FirstBuy := false
FirstSell := false
SlBuyCounter := 1
buy := false
sell := false
bgcolor(isNewDay ? color.red : na)
bgcolor(not na(t) ? #1bbeff5d : na)

var line UpLine = na
var line UpLine2 = na
var line LowLine = na
var line LowLine2 = na
var line BufferUp = na
var line BufferDown = na

barcolor(YouHaveAllow and (high - low > rangemin and high - low < rangemax) ? color.white : na)

if YouHaveAllow and (high - low > rangemin and high - low < rangemax) and not na(t)
dotrade := true
UpLine := line.new(bar_index, high, bar_index + 5, high)
LowLine := line.new(bar_index, low, bar_index + 5, low)
UpLine2 := line.new(bar_index, high - ((farfromUPDown / 100) * (high - low)), bar_index + 5, high - ((farfromUPDown / 100) * (high - low)), color=color.aqua)
LowLine2 := line.new(bar_index, low + ((farfromUPDown / 100) * (high - low)), bar_index + 5, low + ((farfromUPDown / 100) * (high - low)), color=color.aqua)
if BufferLine
BufferDown := line.new(bar_index, low - (BufferPoint * syminfo.pointvalue), bar_index + 5, low - (BufferPoint * syminfo.pointvalue), color=color.gray)
BufferUp := line.new(bar_index, high + (BufferPoint * syminfo.pointvalue), bar_index + 5, high + (BufferPoint * syminfo.pointvalue), color=color.gray)

GreenBuyZone = (close < UpLine2.get_y2() or close > UpLine.get_y2())
GreenSellZone = close < LowLine.get_y1() or close > LowLine2.get_y1()
Qty = 1

if strategy.closedtrades.entry_id(strategy.closedtrades - 1) == “FirstBuy” and bar_index == strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) and strategy.closedtrades.exit_comment(strategy.closedtrades - 1) != “Closed For New Day”
// label.new(bar_index,high)
FirstBuy := true

if strategy.closedtrades.entry_id(strategy.closedtrades - 1) == “FirstSell” and bar_index == strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) and strategy.closedtrades.exit_comment(strategy.closedtrades - 1) != “Closed For New Day”
FirstSell := true

//trailing stoploss
// Configure trail stop level with input options (optional)
trailStop = input.bool(false)
trailafterX = input.int(100)
longTrailPerc = input.float(10, title=“Buy TSL (Point)”,
minval=0.0, step=0.1)
shortTrailPerc = input.float(10, title=“Sell TSL (Point)”,
minval=0.0, step=0.1)

// Determine trail stop loss prices
longStopPrice = 0.0

longStopPrice := if strategy.position_size > 0 and high > strategy.opentrades.entry_price(strategy.opentrades - 1) + (syminfo.pointvaluetrailafterX)
stopValue = high - (longTrailPerc
syminfo.pointvalue)
// math.max(stopValue, longStopPrice[1])
else
stopValue = UpLine2.get_y1()
// Determine trailing short price
shortStopPrice = 0.0

shortStopPrice := if strategy.position_size < 0 and low < strategy.opentrades.entry_price(strategy.opentrades - 1) - (trailafterXsyminfo.pointvalue)
stopValue =low + (shortTrailPerc
syminfo.pointvalue)
// math.min(stopValue, shortStopPrice[1])
else
stopValue = LowLine2.get_y1()

// if bar_index == strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) and strategy.closedtrades.entry_id(strategy.closedtrades - 1) == “FirstBuy”

// if strategy.closedtrades.exit_price(strategy.closedtrades - 1) < strategy.closedtrades.entry_price(strategy.closedtrades - 1)
// if (close < UpLine2.get_y1() and close > LowLine2.get_y1()) and sell and not na(t)
// if SlBuyCounter > 5
// SlBuyCounter := 5
// if strategy.opentrades == 0
// strategy.entry(“Secshort”,strategy.short,qty = SlBuyCounter*Qty,alert_message = )
// SlBuyCounter := SlBuyCounter + 1

// if time == strategy.closedtrades.exit_time(strategy.closedtrades - 1) and strategy.closedtrades.entry_id(strategy.closedtrades - 1) == “FirstSell”

// if strategy.closedtrades.exit_price(strategy.closedtrades - 1) > strategy.closedtrades.entry_price(strategy.closedtrades - 1)
// if (close < UpLine2.get_y1() and close > LowLine2.get_y1()) and buy and not na(t)
// if SlBuyCounter > 5
// SlBuyCounter := 5
// if strategy.opentrades == 0
// strategy.entry(“Secbuy”,strategy.long,qty = SlBuyCounter*Qty,alert_message = )
// SlBuyCounter := SlBuyCounter + 1

// StrikForBuy = UpLine.get_y2()
// StrikForSell = LowLine.get_y1()

StrikForBuy = close
StrikForSell = close

BuyJson = ‘{“secret”:’+str.tostring(SecretCode)+‘,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“B”,“orderType”:“MKT”,“quantity”:{{strategy.position_size}},“exchange”:“NSE”,“symbol”:“BANKNIFTY”,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“CE”,“strike_price”:’+ str.tostring(StrikForBuy) +‘,“expiry_date”:“2025-01-30”}]}’

SellJson = ‘{“secret”:’+str.tostring(SecretCode)+‘,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“B”,“orderType”:“MKT”,“quantity”:{{strategy.position_size}},“exchange”:“NSE”,“symbol”:“BANKNIFTY”,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“PE”,“strike_price”:’+ str.tostring(StrikForSell) +‘,“expiry_date”:“2025-01-30”}]}’

BuyExitJson= ‘{“secret”:’+str.tostring(SecretCode)+‘,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“S”,“orderType”:“MKT”,“quantity”:{{strategy.position_size}},“exchange”:“NSE”,“symbol”:“BANKNIFTY”,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“CE”,“strike_price”:’+ str.tostring(StrikForBuy) +‘,“expiry_date”:“2025-01-30”}]}’
SellExitJson = ‘{“secret”:’+str.tostring(SecretCode)+‘,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“S”,“orderType”:“MKT”,“quantity”:{{strategy.position_size}},“exchange”:“NSE”,“symbol”:“BANKNIFTY”,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“PE”,“strike_price”:’+ str.tostring(StrikForSell) +‘,“expiry_date”:“2025-01-30”}]}’
// log.warning(BuyJson)

if low < LowLine.get_y1() and (FirstBuy or FirstSell)
buy := true
sell := false
if high > UpLine.get_y2() and (FirstBuy or FirstSell)

buy := false 
sell := true

//sell
if dotrade and close < LowLine.get_y1() and GreenSellZone and ADXCond and not na(t)
if BufferLine
if close >= BufferDown.get_y2()
if SlBuyCounter > 5
SlBuyCounter := 5
if strategy.opentrades == 0
strategy.entry(“FirstSell”,strategy.short,qty = SlBuyCounterQty,alert_message = SellJson)
SlBuyCounter := SlBuyCounter + 1
else
if SlBuyCounter > 5
SlBuyCounter := 5
if strategy.opentrades == 0
strategy.entry(“FirstSell”,strategy.short,qty = SlBuyCounter
Qty,alert_message = SellJson)
SlBuyCounter := SlBuyCounter + 1

if GreenBuyZone and ADXCond and not na(t)
if (close < UpLine2.get_y1() and close > LowLine2.get_y1()) and not na(t)
if buy
if SlBuyCounter > 5
SlBuyCounter := 5
if strategy.opentrades == 0
strategy.entry(“Secbuy”,strategy.long,qty = SlBuyCounter*Qty,alert_message = BuyJson)
SlBuyCounter := SlBuyCounter + 1

    if sell 
        if SlBuyCounter > 5
            SlBuyCounter := 5 
        if strategy.opentrades == 0 
            strategy.entry("Secshort",strategy.short,qty = SlBuyCounter*Qty,alert_message = SellJson)
            SlBuyCounter := SlBuyCounter + 1

if dotrade and close > UpLine.get_y1() and GreenBuyZone and ADXCond and not na(t)
if BufferLine
if close <= BufferUp.get_y2()
if SlBuyCounter > 5
SlBuyCounter := 5
if strategy.opentrades == 0
strategy.entry(“FirstBuy”,strategy.long,qty = SlBuyCounterQty,alert_message = BuyJson)
SlBuyCounter := SlBuyCounter + 1
else
if SlBuyCounter > 5
SlBuyCounter := 5
if strategy.opentrades == 0
strategy.entry(“FirstBuy”,strategy.long,qty = SlBuyCounter
Qty,alert_message = BuyJson)
SlBuyCounter := SlBuyCounter + 1

strategy.exit(“Cbuy”,“FirstBuy”,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) + (tpsyminfo.pointvalue),stop = trailStop == false ? (FirstBuySellStop == “L1” ? LowLine.get_y1() : UpLine2.get_y1()) : longStopPrice,alert_message =BuyExitJson)
strategy.exit(“CSell”,“FirstSell”,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) - (tp
syminfo.pointvalue),stop = trailStop == false ? (FirstBuySellStop == “L1” ? UpLine.get_y1() : LowLine2.get_y1()) :shortStopPrice,alert_message = SellExitJson)

strategy.exit(“CSecbuy”,“Secbuy”,limit = UpLine2.get_y1(),stop = LowLine.get_y2(),alert_message =BuyExitJson)
strategy.exit(“CSecshort”,“Secshort”,limit = LowLine2.get_y1(),stop = UpLine.get_y2(),alert_message =SellExitJson)

Best person for this will be @t7support

@Anoop_Yadav broadly I would say free code debugging support from my side is limited on the community. Consider this as a one time pointer to info that you may use to fix the issue.

  • First check whether your code compiles well. If not correct the sytnax errors to make it compile
  • In the JSON for the quantity you have just given {{strategy.position_size}} which will give the size of the current position. It will not help you place a multiple of the first entry position size. “SlBuyCounter” variable which u want to use to update the position size is not used in the JSON.

You may be able to use the strategy.position_size variable better to accomplish what you want

Fetch the previous pos size

Fire orders till a certain pos size is reached

You will be able to get more info on this and other pine script topics here - https://www.tradingcode.net/tradingview/strategy-position-size/. Consider this as an additional resource to learn pine in addition to documentation from Tradingview and what I put in the webinar.