Rajandran R Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

Algomojo – Tradingview Pinescript Library Launched

9 min read

Tradingview recently updated their Pinescript from Version 4 to Version 5 which brings very interesting features and one among them is Tradingview Libraries. So we thought of launching Algomojo Pinescript library to bring single code access to connect any Algomojo supported broker of your choice.

It is a common library to access Algomojo connected brokers where users can select brokers from the list and place orders automatically by adding 4 blocks to any existing strategies.

Requirement

Algomojo Pro Subscription or Higher Plans, Algomojo Access, Algomojo Supported Broker.

We know that the Tradingview PRO account or higher subscription supports Webhook Alerts. Which can be used to transmit any information to 3rd Party Applications. Remember Webhook is more of one-way communication.

What is Webhook?

Webhook is a unique way of communicating in realtime from one application to another application. Webhooks are automatic. You don’t have to manually utilize them in order to make them work — once they’re set up, they run on their own.

TradingView Webhook

Tradingview Webhooks allow you to send a POST request to a certain URL every time the alert is triggered. This feature can be enabled when you create or edit an alert.

How to Add the library to the Pinescript trading strategy?

The following pinescript code needs to be added at the top of the strategy inorder to access the Pinescript Library Function

import algomojo/automation/9

API Controls + Algomojo Order Configuration – Block 1

Pinescript: Contains Algomojo order placement Input controls where traders will be provided a choice to select a broker with whom they want to trade automatically.

Note : Users have to setup the API Parameters and Order Parameters before creating the Tradingview Alerts for Automated Trading

//Block 1 : API Controls + Algomojo Input Controls


//Enter Your Algomojo API Key and API Secret Key

am_client_id = input.string(title='Client ID', defval='RR0884', group='AlgoControls')
am_api_key = input.string(title='API Key', defval='e883a8175acfb3db2643d53f42eb88da', group='AlgoControls')
am_api_secret = input.string(title='API Secret Key', defval='fc1d7b4992894a7d5e42a66c14c2539c', group='AlgoControls')
am_broker = input.string(title='Broker', defval='ALICEBLUE', options=['ALICEBLUE', 'ANGELONE', 'FIRSTOCK', 'FYERS','MASTERTRUST','SAMCO','TRADEJINI','UPSTOX','ZEBU','ZERODHA'], group='AlgoControls')
am_strategy = input.string(title='Strategy Name', defval='Supertrend Strategy', group='AlgoControls')
am_symbol = input.string(title='Trading Symbol', defval='RELIANCE-EQ', group='AlgoControls')
am_exchange = input.string(title='Exchange', defval='NSE', options=['NSE', 'NFO', 'MCX', 'BSE'], group='AlgoControls')
am_quantity = input.int(title='Quantity', defval=1, group='AlgoControls')
am_OrderType = input.string(title='Order Type', defval='MARKET', group='AlgoControls')
am_Product = input.string(title='Product', defval='INTRADAY', options=['NORMAL', 'INTRADAY', 'DELIVERY', 'MARGIN'], group='AlgoControls')
am_Mode = input.string(title='Algo Mode', defval='ENABLE', options=['ENABLE', 'LONGONLY', 'SHORTONLY'], group='AlgoControls')


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

Autotrading API data configuration – Block 2

Block2 of Pinescript code contains only the library function algomodule which builds the API Data configuration required to be transmitted from Tradingview to Algomojo API. The function in turn returns 6 parameters

BE – Buy Entry (1x qty buy)

API data messaging variables

BE – variables that control the api message for Buy Entry (Fresh Buy – 1x qty)
SX – variables that control the api message for Short Exit (Short Exit – 1x qty)
BSR -variables that control the api message for Buy Stop Reverse (2x qty)

SE – variables that control the api message for Short Entry (Fresh Shorts – 1x qty)
BX – variables that control the api message for Buy Exit (Buy Exit – 1x qty)
SSR -variables that control the api message for Short Stop Reverse (2x qty)

Later these variables need to be connected appropriately with corresponding strategy functions to transmit orders accordingly. (which will be covered in Block 4)

//Block 2 : Autotrading API data configuration

[BE,SX,BSR,SE,BX,SSR] = automation.algomodule(am_client_id, am_api_key,am_api_secret,am_broker,am_strategy,am_symbol,am_exchange,am_quantity,am_OrderType, am_Product)


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

Backtesting Module – For Positional Strategies

This module is useful to send the first order at the start of the day with 1x times the quantity and followed by leaving the control to algo for fully automated trading.

From Month, From Day, From Year needs to be set before the start of the trading day and when you are starting the Algo for the first time. And Enter the day’s date from when you want to start the positional Algo.

If in case you are closing the positions manually then one should delete the Alert and should recreate the alert by repeating the above procedures to restart the Algo.

//Block 3 : Backtesting Controls & Live Automation Purpose

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


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

Strategy Module : Block 4

This module is the main module that connects appropriate signals into orders when the signal alerts are getting triggered. And this module needs to be carefully configured and could vary depending upon the strategy to strategy. However if your strategy involves a simple buy, sell, short & cover signal then here is the sample code and mostly fits any kind of positional/intraday module if the strategy is straightforward with only signal to signal.

//Block 4 : Execution Controls

if longCondition and strategy.position_size == 0
    strategy.entry('BUY', strategy.long, qty=1, when=window(), alert_message=BE)
if longCondition and strategy.position_size < 0
    strategy.entry('BUY', strategy.long, qty=1, when=window(), alert_message=BSR)
if shortCondition and strategy.position_size == 0
    strategy.entry('SELL', strategy.short, qty=1, when=window(), alert_message=SE)
if shortCondition and strategy.position_size > 0
    strategy.entry('SELL', strategy.short, qty=1, when=window(), alert_message=SSR)

Once all the three blocks are properly configured in your pinescript trading strategy configuring the Alerts are likely to be a very minimal effort.

Now Create an Alert with proper webhook and placeholder message as shown below (different broker different webhook URL needs to be used as instructed below the super trend AFL code)

The PlaceOrder – Webhook Url

The Placeorder – Webhook Url varies from broker to broker. In order to know the endpoint URL follow the steps

1)Login to Algomojo and on the left handside menu click on AM-API which opens the API Documentation

2)Now goto the PlaceOrder Section where you will be able to get the PlaceOrder URL as shown below

3)Copy the Url and paste it into the Webhook URL while creating the alert.
Note: For different brokers, the URL varies and needs to be collected after login to Algomojo by doing the above mentioned procedures.

Adding the Tradingview Alert

Alert Message Section

Alert Message Section is simplified to the end-user to configure only the placeholder  {{strategy.order.alert_message}} in the Message Box so that end-user need not know about the complexity of configuring the API data in JSON format. All the complexities are handled at the pine script coding level.

Sample Tradingview Pinescript – Supertrend Positional Trading System to Access Algomojo Connected Brokers

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradestudio
// Algomojo Trading Strategy Carry Forward Strategy


//@version=5
strategy('SuperTrend Algomojo Trading Strategy', shorttitle='Supertrend Algomojo', overlay=true)


import algomojo/automation/9

//Block 1 : API Controls + Algomojo Input Controls


//Enter Your Algomojo API Key and API Secret Key

am_client_id = input.string(title='Client ID', defval='RR0884', group='AlgoControls')
am_api_key = input.string(title='API Key', defval='e883a8175acfb3db2643d53f42eb88da', group='AlgoControls')
am_api_secret = input.string(title='API Secret Key', defval='fc1d7b4992894a7d5e42a66c14c2539c', group='AlgoControls')
am_broker = input.string(title='Broker', defval='ALICEBLUE', options=['ALICEBLUE', 'ANGELONE', 'FIRSTOCK', 'FYERS','MASTERTRUST','SAMCO','TRADEJINI','UPSTOX','ZEBU','ZERODHA'], group='AlgoControls')
am_strategy = input.string(title='Strategy Name', defval='Supertrend Strategy', group='AlgoControls')
am_symbol = input.string(title='Trading Symbol', defval='RELIANCE-EQ', group='AlgoControls')
am_exchange = input.string(title='Exchange', defval='NSE', options=['NSE', 'NFO', 'MCX', 'BSE'], group='AlgoControls')
am_quantity = input.int(title='Quantity', defval=1, group='AlgoControls')
am_OrderType = input.string(title='Order Type', defval='MARKET', group='AlgoControls')
am_Product = input.string(title='Product', defval='INTRADAY', options=['NORMAL', 'INTRADAY', 'DELIVERY', 'MARGIN'], group='AlgoControls')


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



//Block 2 : Autotrading API data configuration

[BE,SX,BSR,SE,BX,SSR] = automation.algomodule(am_client_id, am_api_key,am_api_secret,am_broker,am_strategy,am_symbol,am_exchange,am_quantity,am_OrderType, am_Product)


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

//Block 3 : Backtesting Controls & Live Automation Purpose

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


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



//inputs
Periods = input(title='ATR Period', defval=10, group='Indicator Controls')
src = input(hl2, title='Source', group='Indicator Controls')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0, group='Indicator Controls')
changeATR = input(title='Change ATR Calculation Method ?', defval=true, group='Indicator Controls')
showsignals = input(title='Show Buy/Sell Signals ?', defval=true, group='Indicator Controls')
highlighting = input(title='Highlighter On/Off ?', defval=true, group='Indicator Controls')
barcoloring = input(title='Bar Coloring On/Off ?', defval=true, group='Indicator 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) : color.white : color.white
shortFillColor = highlighting ? trend == -1 ? color.new(color.red,90) : color.white : color.white
fill(mPlot, upPlot, title='UpTrend Highligter', color=longFillColor)
fill(mPlot, dnPlot, title='DownTrend Highligter', color=shortFillColor)


//assign signals

longCondition = buySignal
shortCondition = sellSignal

//Block 4 : Execution Controls

if longCondition and strategy.position_size == 0
    strategy.entry('BUY', strategy.long, qty=1, when=window(), alert_message=BE)
if longCondition and strategy.position_size < 0
    strategy.entry('BUY', strategy.long, qty=1, when=window(), alert_message=BSR)
if shortCondition and strategy.position_size == 0
    strategy.entry('SELL', strategy.short, qty=1, when=window(), alert_message=SE)
if shortCondition and strategy.position_size > 0
    strategy.entry('SELL', strategy.short, qty=1, when=window(), alert_message=SSR)

////////////////////////////////////////Block 4 Module Ends////////////////////////////////////////////////////////////////////////

buy1 = ta.barssince(buySignal)
sell1 = ta.barssince(sellSignal)
color1 = buy1[1] < sell1[1] ? color.green : buy1[1] > sell1[1] ? color.red : na
barcolor(barcoloring ? color1 : na)

Sample Tradingview Pinescript – Supertrend Intraday Trading System to Access Algomojo Connected Brokers

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradestudio

//@version=5
strategy('Supertrend - Intraday', overlay=true, calc_on_every_tick=false)
import algomojo/automation/9

//Block 1 : API Controls + Algomojo Input Controls


//Enter Your Algomojo API Key and API Secret Key

am_client_id = input.string(title='Client ID', defval='RR0884', group='AlgoControls')
am_api_key = input.string(title='API Key', defval='e883a8175acfb3db2643d53f42eb88da', group='AlgoControls')
am_api_secret = input.string(title='API Secret Key', defval='fc1d7b4992894a7d5e42a66c14c2539c', group='AlgoControls')
am_broker = input.string(title='Broker', defval='ALICEBLUE', options=['ALICEBLUE', 'ANGELONE', 'FIRSTOCK', 'FYERS','MASTERTRUST','SAMCO','TRADEJINI','UPSTOX','ZEBU','ZERODHA'], group='AlgoControls')
am_strategy = input.string(title='Strategy Name', defval='Supertrend Strategy', group='AlgoControls')
am_symbol = input.string(title='Trading Symbol', defval='RELIANCE-EQ', group='AlgoControls')
am_exchange = input.string(title='Exchange', defval='NSE', options=['NSE', 'NFO', 'MCX', 'BSE'], group='AlgoControls')
am_quantity = input.int(title='Quantity', defval=1, group='AlgoControls')
am_OrderType = input.string(title='Order Type', defval='MARKET', group='AlgoControls')
am_Product = input.string(title='Product', defval='INTRADAY', options=['NORMAL', 'INTRADAY', 'DELIVERY', 'MARGIN'], group='AlgoControls')
am_Mode = input.string(title='Algo Mode', defval='ENABLE', options=['ENABLE', 'LONGONLY', 'SHORTONLY'], group='AlgoControls')


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



//Block 2 : Autotrading API data configuration

[BE,SX,BSR,SE,BX,SSR] = automation.algomodule(am_client_id, am_api_key,am_api_secret,am_broker,am_strategy,am_symbol,am_exchange,am_quantity,am_OrderType, am_Product)


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

//Block 3 : Backtesting Controls & Live Automation Purpose

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


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

var i_marketSession = input.session(title='Market session', defval='0915-1500', confirm=true, group='Indicator Controls')
var float i_multiplier = input.float(title='Multiplier', defval=3, step=0.1, confirm=true, group='Indicator Controls')
var int i_atrPeriod = input.int(title='ATR Period', defval=10, confirm=true, group='Indicator Controls')
var bool highlighting = input(title='Highlighter On/Off ?', defval=true, group='Indicator Controls')

barInSession(sess) =>
    time(timeframe.period, sess) != 0


//Computing Supertrend
[superTrend, dir] = ta.supertrend(i_multiplier, i_atrPeriod)

trendcolor = dir==1  ? color.green  : color.red

//Plot Supertrend TSL
plot(superTrend, color=trendcolor, linewidth=2)


// Long/short condition
longCondition = close > superTrend
shortCondition = close < superTrend


// Check if intraday session is active
bool intradaySession = barInSession(i_marketSession)

buy = longCondition and intradaySession
short = shortCondition and intradaySession

if(am_Mode=="ENABLE")
    if (buy and strategy.position_size==0)
        strategy.entry(id='Long', direction=strategy.long, when=buy,alert_message=BE)
    if (buy and strategy.position_size<0)
        strategy.entry(id='Long', direction=strategy.long, when=buy,alert_message=BSR)
    if (short and strategy.position_size==0)
        strategy.entry(id='Short', direction=strategy.short, when=short,alert_message=SE)
    if (short and strategy.position_size>0)
        strategy.entry(id='Short', direction=strategy.short, when=short,alert_message=SSR)
        
if(am_Mode=="LONGONLY")
    if (buy and strategy.position_size==0)
        strategy.entry(id='Long', direction=strategy.long, when=buy,alert_message=BE)
    if (short and strategy.position_size>0)
        strategy.entry(id='Short', direction=strategy.short, when=short,alert_message=BX)
        
if(am_Mode=="SHORTONLY")
    if (buy and strategy.position_size<0)
        strategy.entry(id='Long', direction=strategy.long, when=buy,alert_message=SX)
    if (short and strategy.position_size==0)
        strategy.entry(id='Short', direction=strategy.short, when=short,alert_message=SE)


longsquareOff = not intradaySession and strategy.position_size > 0
strategy.close(id='Long', when=longsquareOff, comment='Long Square-off',alert_message=BX)
shortsquareOff = not intradaySession and strategy.position_size < 0
strategy.close(id='Short', when=shortsquareOff, comment='Short Square-off',alert_message=SX)


Rajandran R Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

AllinOneAlerts – Amibroker Alerts Module for Amibroker Users

AllinOneAlerts is one of the most important and most requested modules to bring all sorts of alerts with no extra coding efforts. Now even...
Rajandran R
5 min read

Intraday Straddle Execution Module – Amibroker for AngelOne Users

This tutorial focus on how to automate your time-based index straddle/strangle management with intraday stop-loss levels with time-based entry and exits using Algomojo Platform...
Rajandran R
11 min read

Intraday Straddle Execution Module – Amibroker for Upstox Users

This tutorial focus on how to automate your time-based index straddle/strangle management with intraday stop-loss levels with time-based entry and exits using Algomojo Platform...
Rajandran R
11 min read

Leave a Reply

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