Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Sending Futures/Spot – Signals to Two-Legged Options Execution Module – Tradingview Pinescript Module

16 min read

Thought of making an open-source Tradingview Pinescript code demanded by most of the option traders to control the cost, control the risk, and configure the two-legged option trading strategy of their choice with slicing larger orders feature. So here is a two-legged options execution Tradingview module for the Algomojo trading platform where users can configure modules on top of their own trading logic to convert any spot/futures signals into 9 types of two-legged options execution modules.

Tradingview Pinescript Module Explained

Block 1 : API Controls + Algomojo Input Controls and Option Strike Calculation

Block 2 : Backtesting Controls & Target and Stoploss Controls

Block 3 : Trading Strategy and Controls (write your trading strategy in the block

Block 4 : Buy and Sell Signal Mapping (Buy,Sell, Short,Cover Signal Mapping is required)

Block 5 : Framing Option Symbols and Multi Order API Messaging Structure

Block 6 : Trade Execution Controls

Block 7 : Plotting Trading Dashboard

What is a Two-Legged Options Strategy?

A two-legged options trading strategy involves buying or selling two options at the same time, typically with different strike prices or expiration dates. The strategy is designed to take advantage of the price difference between the two options and can be used for a variety of purposes, such as hedging, speculation, or income generation.

Features of the Two-Legged Options Execution Module

1)Configure various styles of two-legged options execution strategies. Supports 9 types of two-legged options trading strategies.
2)Configure separate options trading strategies for long-entry and short-entry signals in spot/futures charts
3)Place Larger Option Orders by Splitting Larger Orders into multiple small orders.
4)Option Strike calculation at Tradingview end (Trades can configure the Underlying symbol as Spot./Futures) based on their trading requirement) accordingly, options strikes will be calculated.
5)Easy to configure the module by configuring block 3 and mapping the signals to block 4 in the below-mentioned code

Here are the Supported two-legged options trading strategies:

Credit Spread: Selling an option at one strike price and buying an option at a lower strike price.

Debit Spread: Buying an option at one strike price and selling an option at a higher strike price.

Straddle: buying a call and a put option with the same strike price and expiration date.

Strangle: buying a call option with a higher strike price and a put option with a lower strike price

Synthetic Futures: Buying/Selling a call option and selling/Buying a put option of the same strike price and expiration date

Diagonal Spread: Buying a call or put option with a longer expiration date and selling a call or put option with a shorter expiration date and a different strike price.

Calendar Spread: Buying a call or put option with a longer expiration date and selling a call or put option with a shorter expiration date.

Ratio Spread: Buying a call or put option at one strike price and selling multiple options at a different strike price

Ratio Back Spread: Buying multiple options at one strike price and selling an option at a different strike price

Webhook URL for Trade Automation

This code uses Algomojo Consolidated API and uses placemultiorder API functionality and sends two leg orders in options. Here is the webhook URL that needs to be used for all the supported Algomojo brokers,

https://amapi.algomojo.com/v1/PlaceMultiOrder

Pinescript Trading Strategy Module

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © algomojo
// Module  - Two Leg Options Strategy Module
// Description - Build your Trading Logic in Spot/Futures - Two Leg Options Trade Execution Module
// Webhook Url : https://amapi.algomojo.com/v1/PlaceMultiOrder
// Coded by Rajandran R - Co-Creator - Algomojo
// Module V1.0 
// Date 26th Jan 2023
////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Trading Block Description

//Block 1 : API Controls + Algomojo Input Controls and Option Strike Calculation
//Block 2 : Backtesting Controls & Target and Stoploss Controls
//Block 3 : Trading Strategy and Controls (write your trading strategy in the block
//Block 4 : Buy and Sell Signal Mapping (Buy,Sell,Short,Cover Signal Mapping is required)
//Block 5 : Framing Option Symbols and Multi Order API Messaging Structure
//Block 6 : Trade Execution Controls
//Block 7 : Plotting Trading Dashboard



///////////////////////////////////////////////////////////////////////////////////////////////////////////

//@version=5
strategy('Supertrend Spot/Futures to Two Leg Options Execution Module', overlay=true, calc_on_every_tick=false, process_orders_on_close = true)


//Block 1 : API Controls + Algomojo Input Controls


//Enter Your Algomojo API Key and API Secret Key



api_key = input.string(title='API Key', defval='xxxxxxxxxxxx', group='AlgoControls')
api_secret = input.string(title='API Secret Key', defval='xxxxxxxxxxxx', group='AlgoControls')
br = input.string(title='Broker', defval='ALICEBLUE', options=['ALICEBLUE', 'ANGELONE', 'FIRSTOCK', 'FYERS','MASTERTRUST','SAMCO','TRADEJINI','UPSTOX','ZEBU','ZERODHA'], group='AlgoControls')
strategy = input.string(title='Strategy Name', defval='TwoLegOptions', group='AlgoControls')
Symbol = input.symbol(title='UnderlyingSymbol',defval='NSE:NIFTY', group='AlgoControls')
exchange = input.string(title='Exchange', defval='NFO', group='AlgoControls')
iInterval = input.int(title='Strike Interval', defval=50, group='AlgoControls')
lotsize = input.int(title='Lot Size', defval=50, group='AlgoControls')

expiry_leg1 = input.string(title='Expiry Date (Leg1)',defval='25JAN23' , group='AlgoControls')
expiry_leg2 = input.string(title='Expiry Date (Leg2)',defval='25JAN23' , group='AlgoControls')

quantity_leg1 = input.int(title='Quantity1(lot size)', defval=1, group='AlgoControls')*lotsize
quantity_leg2 = input.int(title='Quantity2(lot size)', defval=1, group='AlgoControls')*lotsize

opttype_buyleg1 = input.string(title='Option Type1(Buy)', defval='CE', options=['CE', 'PE'], group='AlgoControls')
opttype_buyleg2 = input.string(title='Option Type2(Buy)', defval='CE', options=['CE', 'PE'], group='AlgoControls')

tradetype_buyleg1 = input.string(title='Trade Type1(Buy)', defval='BUY', options=['BUY', 'SELL'], group='AlgoControls')
tradetype_buyleg2 = input.string(title='Trade Type2(Buy)', defval='BUY', options=['BUY', 'SELL'], group='AlgoControls')

offset_buyleg1 = input.int(title='Offset1(Buy)', defval=0,minval=-40,maxval=40, group='AlgoControls')
offset_buyleg2 = input.int(title='Offset2(Buy)', defval=0,minval=-40,maxval=40, group='AlgoControls')

opttype_shortleg1 = input.string(title='Option Type1(Short)', defval='CE', options=['CE', 'PE'], group='AlgoControls')
opttype_shortleg2 = input.string(title='Option Type2(Short)', defval='CE', options=['CE', 'PE'], group='AlgoControls')

tradetype_shortleg1 = input.string(title='Trade Type1(Short)', defval='BUY', options=['BUY', 'SELL'], group='AlgoControls')
tradetype_shortleg2 = input.string(title='Trade Type2(Short)', defval='BUY', options=['BUY', 'SELL'], group='AlgoControls')

offset_shortleg1 = input.int(title='Offset1(Short)', defval=0,minval=-40,maxval=40, group='AlgoControls')
offset_shortleg2 = input.int(title='Offset2(Short)', defval=0,minval=-40,maxval=40, group='AlgoControls')

pricetype = input.string(title='Price Type', defval='MARKET', options=['MARKET'], group='AlgoControls')
product = input.string(title='Product Type', defval='NRML', options=['NRML','MIS'], group='AlgoControls')
splitorder = input.string(title='Split Order?', defval='NO', options=['NO', 'YES'], group='AlgoControls')
split_quantity = input.int(title='Split Quantity', defval=1, group='AlgoControls')
price = '0'
disclosed_quantity = '0'
trigger_price = '0'
amo = 'NO'

broker = switch br
    "ALICEBLUE" => "ab"
	"ANGELONE" => "an"
	"FIRSTOCK" => "fs"
	"FYERS" => "fy"
	"GOODWILL" => "gw"
	"MASTERTRUST" => "mt"
	"PAYTM" => "pt"
	"SAMCO" => "sm"
	"TRADEJINI" => "tc"
	"UPSTOX" => "up"
	"ZEBU" => "zb"
	"ZERODHA" => "ze"
	=>
		runtime.error("No matching broker found.")
		string(na)

am_Mode = input.string(title='Algo Mode', defval='ENABLE', options=['ENABLE', 'LONGONLY', 'SHORTONLY'], group='AlgoControls')
    

//Get the Strike Interval
SpotC1 = request.security(Symbol, timeframe.period,close)
SpotC = SpotC1[1]

//Calculate the ATM,ITM,OTM Options based on the Offset Selected
strike = SpotC % iInterval > iInterval/2 ? SpotC - (SpotC%iInterval) + iInterval : SpotC - (SpotC%iInterval)

strike_buyleg1 = opttype_buyleg1=="CE" ? strike + (offset_buyleg1 * iInterval) : opttype_buyleg1=="PE" ? strike - (offset_buyleg1 * iInterval) : na
strike_buyleg2 = opttype_buyleg2=="CE" ? strike + (offset_buyleg2 * iInterval) : opttype_buyleg2=="PE" ? strike - (offset_buyleg2 * iInterval) : na


strike_shortleg1 = opttype_shortleg1=="CE" ? strike + (offset_shortleg1 * iInterval) : opttype_shortleg1=="PE" ? strike - (offset_shortleg1 * iInterval) : na
strike_shortleg2 = opttype_shortleg2=="CE" ? strike + (offset_shortleg2 * iInterval) : opttype_shortleg2=="PE" ? strike - (offset_shortleg2 * iInterval) : na





////////////////////////////////////////Block 1 Module Ends////////////////////////////////////////////////////////////////////////



//Block 2 : Backtesting Controls & Target and Stoploss Controls

FromMonth = input.int(defval=9, title='From Month', minval=1, maxval=12, group='Backtesting')
FromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group='Backtesting')
FromYear = input.int(defval=2018, title='From Year', minval=999, group='Backtesting')
ToMonth = input.int(defval=1, title='To Month', minval=1, maxval=12, group='Backtesting')
ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31, group='Backtesting')
ToYear = input.int(defval=9999, title='To Year', minval=999, group='Backtesting')
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window() =>
    time >= start and time <= finish ? true : false



highlighting = input.bool(title='Highlighter On/Off ?', defval=true, group='Intraday Controls')
barcoloring = input.bool(title='Bar Coloring On/Off ?', defval=true, group='Intraday Controls')

////////////////////////////////////////Block 2 Module Ends////////////////////////////////////////////////////////////////////////




//Block 3 : Trading Strategy and Controls

src = input(hl2, title='Source', group='Supertrend Controls')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0, group='Supertrend Controls')
Periods = input.int(title='ATR Period', defval=10, group='Supertrend Controls')
changeATR = input.bool(title='Change ATR Calculation Method ?', defval=true, group='Supertrend Controls')
showsignals = input.bool(title='Show Buy/Sell Signals ?', defval=true, group='Supertrend Controls')


atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
up = src - Multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend


//Plots
upPlot = plot(trend == 1 ? up : na, title='Up Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal  ? up : na, title='UpTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.green, 0))
//plotshape(buySignal and showsignals ? up : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
dnPlot = plot(trend == 1 ? na : dn, title='Down Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0))
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title='DownTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.red, 0))
//plotshape(sellSignal and showsignals ? dn : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0)

longFillColor = highlighting ? trend == 1 ? color.new(color.green,90) : na : na
shortFillColor = highlighting ? trend == -1 ? color.new(color.red,90) : na : na
fill(mPlot, upPlot, title='UpTrend Highligter', color=longFillColor)
fill(mPlot, dnPlot, title='DownTrend Highligter', color=shortFillColor)

////////////////////////////////////////Block 3 Module Ends////////////////////////////////////////////////////////////////////////


//Block 4 : Buy and Sell Signal Mapping


buy = buySignal
sell = sellSignal

short = sell
cover = buy

buy1 = buy[1]
sell1 = sell[1]





//Block 5 : Framing Option Symbols and Multi Order API Messaging Structure

flip(series1,series2) =>
	result = series1
    series1_index = ta.valuewhen(series1, bar_index, 0)
    series2_index = ta.valuewhen(series2, bar_index, 0)
    if (series1_index > series2_index)
        result := true
    result

buycontinue = flip(buy,sell)
shortcontinue = flip(short,cover)

entrysymbol_buyleg1 = ""
entrysymbol_buyleg2 = ""
entrysymbol_shortleg1 = ""
entrysymbol_shortleg2 = ""

exitsymbol_buyleg1 = ""
exitsymbol_buyleg2 = ""
exitsymbol_shortleg1 = ""
exitsymbol_shortleg2 = ""

ExitStrike_buyleg1 = ta.valuewhen(buy,strike_buyleg1,0)
ExitStrike_buyleg2 = ta.valuewhen(buy,strike_buyleg2,0)

ExitStrike_shortleg1 = ta.valuewhen(short,strike_shortleg1,0)
ExitStrike_shortleg2 = ta.valuewhen(short,strike_shortleg2,0)

spot = str.replace_all(Symbol,"NSE:","")
spot := str.replace_all(spot,"1!","")
spot := str.replace_all(spot,"2!","")

if(broker=="tc" or broker=="fs")
    opttype_buy_leg1 = opttype_buyleg1=="CE" ? "C" : "P"
    opttype_buy_leg2 = opttype_buyleg2=="CE" ? "C" : "P"
    opttype_short_leg1 = opttype_shortleg1=="CE" ? "C" : "P"
    opttype_short_leg2 = opttype_shortleg2=="CE" ? "C" : "P"
    entrysymbol_buyleg1 := spot + expiry_leg1 + opttype_buy_leg1 + str.tostring(ExitStrike_buyleg1) 
    entrysymbol_buyleg2 := spot + expiry_leg2 + opttype_buy_leg2 + str.tostring(ExitStrike_buyleg2) 
    entrysymbol_shortleg1 := spot + expiry_leg1 + opttype_short_leg1 + str.tostring(ExitStrike_shortleg1) 
    entrysymbol_shortleg2 := spot + expiry_leg2 + opttype_short_leg2 + str.tostring(ExitStrike_shortleg2) 
    exitsymbol_buyleg1 :=  spot + expiry_leg1 + opttype_buy_leg1 + str.tostring(ExitStrike_buyleg1) 
    exitsymbol_buyleg2 :=  spot + expiry_leg2 + opttype_buy_leg2 + str.tostring(ExitStrike_buyleg2) 
    exitsymbol_shortleg1 :=  spot + expiry_leg1 + opttype_short_leg1 + str.tostring(ExitStrike_shortleg1) 
    exitsymbol_shortleg2 :=  spot + expiry_leg2 + opttype_short_leg2 + str.tostring(ExitStrike_shortleg2) 

else
    entrysymbol_buyleg1 := spot + expiry_leg1  + str.tostring(ExitStrike_buyleg1) + opttype_buyleg1 
    entrysymbol_buyleg2 := spot + expiry_leg2  + str.tostring(ExitStrike_buyleg2) + opttype_buyleg2 
    entrysymbol_shortleg1 := spot + expiry_leg1  + str.tostring(ExitStrike_shortleg1) + opttype_shortleg1 
    entrysymbol_shortleg2 := spot + expiry_leg2 + str.tostring(ExitStrike_shortleg2)  + opttype_shortleg2
    exitsymbol_buyleg1 :=   spot + expiry_leg1 + str.tostring(ExitStrike_buyleg1) +  opttype_buyleg1 
    exitsymbol_buyleg2 :=  spot + expiry_leg2 + str.tostring(ExitStrike_buyleg2) +  opttype_buyleg2 
    exitsymbol_shortleg1 :=  spot + expiry_leg1 + str.tostring(ExitStrike_shortleg1) +  opttype_shortleg1 
    exitsymbol_shortleg2 :=  spot + expiry_leg2 + str.tostring(ExitStrike_shortleg2) +  opttype_shortleg2 



//

//api data configuration

buyentryorder = ""
buyexitorder = ""
shortentryorder = ""
shortexitorder = ""

exittradetype_buyleg1 = ""
exittradetype_buyleg2 = ""
exittradetype_shortleg1 = ""
exittradetype_shortleg2 = ""


if(tradetype_buyleg1=="BUY")    
    exittradetype_buyleg1 := "SELL"
if(tradetype_buyleg1=="SELL")   
    exittradetype_buyleg1 := "BUY"

if(tradetype_buyleg2=="BUY")    
    exittradetype_buyleg2 := "SELL"
if(tradetype_buyleg2=="SELL")   
    exittradetype_buyleg2 := "BUY"

if(tradetype_shortleg1=="BUY")    
    exittradetype_shortleg1 := "SELL"
if(tradetype_shortleg1=="SELL")   
    exittradetype_shortleg1 := "BUY"

if(tradetype_shortleg2=="BUY")    
    exittradetype_shortleg2 := "SELL"
if(tradetype_shortleg2=="SELL")   
    exittradetype_shortleg2 := "BUY"

if(tradetype_buyleg1=="BUY")
    buyentryorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_buyleg1+'",     "action":"'+tradetype_buyleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0",  "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO", "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_buyleg2+'",     "action":"'+tradetype_buyleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'
else
    buyentryorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_buyleg2+'",     "action":"'+tradetype_buyleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_buyleg1+'",     "action":"'+tradetype_buyleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'

if(tradetype_buyleg1=="BUY")
    buyexitorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_buyleg1+'",     "action":"'+exittradetype_buyleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_buyleg2+'",     "action":"'+exittradetype_buyleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'
else
    buyexitorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_buyleg2+'",     "action":"'+exittradetype_buyleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_buyleg1+'",     "action":"'+exittradetype_buyleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'

if(tradetype_shortleg1=="BUY") 
    shortentryorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_shortleg1+'",     "action":"'+tradetype_shortleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_shortleg2+'",     "action":"'+tradetype_buyleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'
else
    shortentryorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_shortleg2+'",     "action":"'+tradetype_shortleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+entrysymbol_shortleg1+'",     "action":"'+tradetype_buyleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'
if(tradetype_shortleg1=="BUY")     
    shortexitorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_shortleg1+'",     "action":"'+exittradetype_shortleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_shortleg2+'",     "action":"'+exittradetype_buyleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'
else
    shortexitorder := '{     "api_key":"'+ api_key +'",  "api_secret":"'+ api_secret +'",    "data":      {     "orders" :  [  {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_shortleg2+'",     "action":"'+exittradetype_shortleg2+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg2)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}, {   "api_key":"'+ api_key +'", "api_secret":"'+ api_secret +'",  "data":      {   "broker": "'+ broker +'", "strategy":"'+ strategy +'", "exchange":"'+ exchange +'",     "symbol":"'+exitsymbol_shortleg1+'",     "action":"'+exittradetype_buyleg1+'",    "product":"'+product+'",    "pricetype":"'+pricetype+'",   "quantity":"'+ str.tostring(quantity_leg1)+'",  "price":"0", "trigger_price":"0",  "disclosed_quantity":"0",  "amo":"NO",  "splitorder":"'+splitorder+'",  "split_quantity":"'+str.tostring(split_quantity)+'"  }}   ]   } }'

//Block 6 : Trade Execution Controls


if(am_Mode=="ENABLE")
    //Buy Entry Order
    if buy and strategy.position_size == 0 and window()
        strategy.entry('Buy', strategy.long, alert_message=buyentryorder)

    if sell and strategy.position_size > 0 and window()
        strategy.close('Buy', alert_message=buyexitorder)
        
    
    //Short Entry Order
    if short and strategy.position_size == 0 and window()
        strategy.entry('Short', strategy.short, alert_message=shortentryorder)

    if cover and strategy.position_size < 0 and window()
        strategy.close('Short', alert_message=shortexitorder)
        
    
    
    //Short Exit and Buy Entry
    if buy and cover and strategy.position_size < 0 and window()
        strategy.close('ShortEntry', alert_message=shortexitorder)
        strategy.entry('BuyEntry', strategy.long, alert_message=buyentryorder)
    
    //Buy Exit and Short Entry
    if short and sell and strategy.position_size > 0 and window()
        strategy.close('BuyEntry', alert_message=buyexitorder)
        strategy.entry('ShortEntry', strategy.short, alert_message=shortentryorder)
        
if(am_Mode=="LONGONLY")
    //Buy Fresh Call Option
    if buy and strategy.position_size == 0 and window()
        strategy.entry('Buy', strategy.long, alert_message=buyentryorder)
    
    if sell and strategy.position_size > 0 and window()
        strategy.close('Buy', alert_message=buyexitorder)
        
        
if(am_Mode=="SHORTONLY")
    //Exit Old Call Credit and Selling Fresh Put Credit Spread (Buy)
    if cover and strategy.position_size < 0 and window()
        strategy.close('Short', alert_message=shortexitorder)
        
        
     //Selling Call Credit Spread
    if short and strategy.position_size == 0 and window()
        strategy.entry('Short', strategy.short, alert_message=shortentryorder)

////////////////////////////////////////Block 6 Module Ends////////////////////////////////////////////////////////////////////////



//Block 7 : Plotting Trading Dashboard


entry1text = ''
entry2text = ''
exit1text = ''
exit2text = ''

if(buycontinue)
    entry1text := tradetype_buyleg1 +" "+ opttype_buyleg1 + ":  " + entrysymbol_buyleg1
    entry2text := tradetype_buyleg2 +" "+ opttype_buyleg2 + ":  " + entrysymbol_buyleg2
    exit1text := "exit" +" "+ opttype_shortleg1 + ":  " + exitsymbol_shortleg1
    exit2text := "exit"  +" "+ opttype_shortleg2 + ":  " + exitsymbol_shortleg2
if(shortcontinue)
    entry1text := tradetype_shortleg1 +" "+ opttype_shortleg1 + ":  " + entrysymbol_shortleg1
    entry2text := tradetype_shortleg2 +" "+ opttype_shortleg2 + ":  " + entrysymbol_shortleg2
    exit1text := "exit"  +" "+ opttype_buyleg1 + ":  " + exitsymbol_buyleg1
    exit2text := "exit"  +" "+ opttype_buyleg1 + ":  " + exitsymbol_buyleg2
//Trading Dashboard
var tLog = table.new(position = position.bottom_right, rows = 4, columns = 2, bgcolor = color.black, border_width=1)
table.cell(tLog, row = 0, column = 1, text = entry1text, text_color = color.green)
table.cell_set_text(tLog, row = 0, column = 1, text = entry1text)
table.cell(tLog, row = 1, column = 1, text = entry2text, text_color = color.red)
table.cell_set_text(tLog, row = 1, column = 1, text = entry2text )
table.cell(tLog, row = 2, column = 1, text = exit1text, text_color = color.green)
table.cell_set_text(tLog, row = 2, column = 1, text = exit1text)
table.cell(tLog, row = 3, column = 1, text = exit2text, text_color = color.red)
table.cell_set_text(tLog, row = 3, column = 1, text = exit2text )

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Introducing OpenAlgo V1.0: The Ultimate Open-Source Algorithmic Trading Framework…

OpenAlgo V1.0 is an open-source algorithmic trading platform to automate your trading strategies using Amibroker, Tradingview, Metatrader, Python etc. Designed with the modern trader...
Rajandran R
2 min read

Dive Into the TradingView Paper Trading Competition: A Chance…

Welcome to an exhilarating opportunity presented by TradingView – a paper trading competition that not only tests your trading acumen but also offers a...
Rajandran R
1 min read

Introducing PineGPT – To Build Better Tradingview Pinescript Codes

PineGPT is a customGPT for ChatGPT4 users designed to provide expert guidance on creating and understanding TradingView Pine Script indicators and trading strategies. PineGPT...
Rajandran R
1 min read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More