Programming language: algoZ

April 23, 2013

Beginners, don’t worry if you don’t understand when you read this manual. We will explain how to code your technical analysis strategy in the “Code your strategy” section.

Programming language

This blog contains short examples that demonstrate how to perform common, basic tasks such as identifying securities within a specific price range, increase in volatility, crossing over of an indicator, and so forth. You can cut and paste many of these examples right into the NEST Pulse’s programming area on Zerodha Trader.

Also this blog contains a reference of functions, properties, and constants supported by the NEST Pulse language as well as hands-on trading system examples. This method of organization allows the beginning programmer to see results immediately while learning at his or her own pace. NEST Pulse is the engine that drives the scripting language in your trading software. It is a non-procedural scientific vector programming language that was designed specifically for developing trading systems. A script is simply a set of instructions that tells the NEST Pulse engine to do something useful, such as provide an alert when the price of one stock reaches a new high, crosses over a moving average, or drops by a certain percentage. There are many uses.

Introduction: Important Concepts

NEST Pulse is a powerful and versatile programming language for traders.

The language provides the framework required to build sophisticated trading programs piece by piece without extensive training or programming experience.

The following script is a very simple example that identifies markets that are trading higher than the opening price:


It almost goes without saying that the purpose of this script is to identify when the last price is trading higher than the open price. It is nearly as plain as English language.

Just as a spoken language gives you many ways to express each idea, the NEST Pulse programming language provides a wide variety of ways to program a Trading System. Scripts can be very simple as just shown or extremely complex, consisting of many hundreds of lines of instructions. But for most systems, scripts usually consist of just a few lines of code.

The examples outlined in the first section of this blog are relatively short and simple but provide a foundation for the development of more complex scripts.

Boolean Logic

The scripts shown in this first section may be linked together using Boolean logic just by adding the AND or the OR keyword, for example:

Script 1 evaluates to true when the last price is higher than the open price:


Script 2 evaluates to true when volume is two times the previous day’s volume:


You can aggregate scripts so that your script returns results for securities that are higher than the open and with the volume two times the previous volume:


Likewise, you can change the AND into an OR to find securities that are either trading higher than the open or have a volume two times the previous volume:


Once again, the instructions are nearly is plain as the English language. The use of Boolean logic with the AND and OR keywords is a very important concept that is used extensively by the NEST Pulse programming language.

Program Structure

It does not matter if your code is all on a single line or on multiple lines. It is often easier to read a script where the code is broken into multiple lines. The following script will work exactly as the previous example, but is somewhat easier to read:


It is good practice to structure your scripts to make them as intuitive as possible for future reference. In some cases it may be useful to add comments to a very complex script. A comment is used to include explanatory remarks in a script.

Whenever the pound sign is placed at the beginning of a line, the script will ignore the words that follow. The words will only serve as a comment or note to make the script more understandable:

# Evaluates to true when the last price is higher than the open or the volume is 2 X’s the previous volume:


The script runs just as it did before with the only difference being that you can more easily understand the design and purpose of the script.


The NEST Pulse language provides many built-in functions that make programming easier. When functions are built into the core of a programming language they are referred to as primitives. The TREND function is one example:


In this example, the TREND function tells NEST Pulse to identify trades where the closing price is in a 30-day uptrend.

The values that are contained inside a function (such as the REF function or the TREND function) are called arguments. Here there are two arguments in the TREND function. Argument #1 is the closing price, and argument #2 is 30, as in “30 days” or “30 periods”

Only one of two things will occur if you use a function incorrectly will automatically fix the problem and the script will still run, or NEST Pulse will report an error, tell you what’s wrong with the script, and then allow you to fix the problem and try again.

In other words, user input errors will never cause NEST Pulse to break or return erroneous results without first warning you about a potential problem.

Let’s take CLOSE out of the TREND function and then try to run the script again:

TREND(30) = UP

The following error occurs:

Error: argument of “TREND” function not optional.

We are given the option to fix the script and try again.

Vector Programming

Vector programming languages (also known as array or multidimensional languages) generalize operations on scalars to apply transparently to vectors, matrices, and higher dimensional arrays.

The fundamental idea behind vector programming is that operations apply at once to an entire set of values (a vector or field). This allows you to think and operate on whole aggregates of data, without having to resort to explicit loops of individual scalar operations.

As an example, to calculate a simple moving average based on the median price of a stock over 30 days, in a traditional programming language such as BASIC you would be required to write a program similar to this:

For each symbol
    For bar = 30 to max
        Average = 0
        For n = bar - 30 to bar
            median = (CLOSE + OPEN) / 2
            Average = Average + median
        MedianAverages(bar) = Average / 30
    Next bar
Next symbol

Nine to ten lines of code would be required to create the “MedianAverages†vector. But with NEST Pulse, you can effectively accomplish the same thing using only one line:

SET MedianAverage = SimpleMovingAverage((CLOSE + OPEN) / 2, 30)

And now MedianAverage is actually a new vector that contains the 30-period simple moving average of the median price of the stock at each point.

It is not uncommon to find array programming language “one-liners” that require more than a couple of pages of BASIC, Java or C++ code.

The REF Function

At this point you may be wondering what “REF” and “TREND” are. These are two of the very useful primitives that are built into the NEST Pulse language.

The REF function is used whenever you want to reference a value at any specific point in a vector. Assume the MedianAverage vector contains the average median price of a stock. In order to access a particular element in the vector using a traditional programming language, you would write:

SET A = MedianAverage[n]

Using NestPulse you would write:

SET A = REF(MedianAverage, n)

The main difference other than a variation in syntax is that traditional languages reference the points in a vector starting from the beginning, or 0 if the vectors are zero-based. NEST Pulse on the other hand references values backwards, from the end. This is most convenient since the purpose of NEST Pulse is of course, to develop trading systems. It is always the last, most recent value that is of most importance. To get the most recent value in the MedianAverage vector we could write:

SET A = REF(MedianAverage, 0)

Which is the same as not using the REF function at all. Therefore the preferred way to get the last value (the most recent value) in a vector is to simply write:

SET A = MedianAverage

The last value of a vector is always assumed when the REF function is absent.

To get the value as of one bar ago, we would write:

SET A = REF(MedianAverage, 1)

Or two bars ago:

SET A = REF(MedianAverage, 2)

The TREND Function

Stock traders often refer to “trending” as a state when the price of a stock has been increasing (up-trending) or decreasing (down-trending) for several days, weeks, months, or years. The typical investor or trader would avoid opening a new long position of a stock that has been in a downtrend for many months.

NEST Pulse provides a primitive function aptly named TREND especially for detecting trends in stock price, volume, or indicators: TREND(CLOSE, 30) = UP

This tells NEST Pulse to identify trades where the closing price is in a 30-day uptrend. Similarly, you could also use the TREND function to find trends in volume or technical indicators:

# The volume has been in a downtrend for at least 10 days:


# The 14-day CMO indicator has been up-trending for at least 20 days:

TREND(CMO(CLOSE, 14), 20) = UP

It is useful to use the TREND function for confirming a trading system signal.

Suppose we have a trading system that buys when the close price crosses above a 20-day Simple Moving Average. The script may look similar to this:

# Gives a buy signal when the close price crosses above the 20-day SMA

CROSSOVER(CLOSE, SimpleMovingAverage(CLOSE, 20)) = TRUE

It would be helpful in this case to narrow the script down to only the securities that have been in a general downtrend for some time. We can add the following line of code to achieve this:


TREND tells us if a vector has been trending upwards, downwards, or sideways, but does not tell us the degree of which it has been trending. We can use the REF function in order to determine the range in which the data has been trending. To find the change from the most current price and the price 40 bars ago, we could write:


Price Gaps and Volatility

Although the TREND function can be used for identifying trends and the REF function can be used for determining the degree in which a stock has moved, it is often very useful to identify gaps in prices and extreme volume changes, which may be early indications of a change in trend.

We can achieve this by writing:

# Returns true when the price has gapped up



# Returns true when the price has gapped down


You can further specify a minimum percentage for the price gap:

# Returns true when the price has gapped up at least 1%

LOW >REF(HIGH, 1) * 1.01

And with a slight variation we can also the volume is either up or down by a large margin:

# the volume is up 1000%


Or by the average volume:

# the volume is up 1000% over average volume

VOLUME >SimpleMovingAverage(VOLUME, 30) * 10

We can also measure volatility in price or volume by using any one of the built-in technical indicators such as the Volume Oscillator, Chaikin Volatility Index, Coefficient of Determination,Price Rate of Change, Historical Volatility Index, etc.

This blog is a user manual for algoZ and is continued here.

Happy Trading.

India's largest broker trusted by 1.3+ crore investors.

Post a comment

  1. kunwar says:

    dear sir,
    i earlier used this scanner in chart ink with 15 min time frame i,e
    ( cash ( latest open >= latest “(1 candle ago high + 1 candle ago low + 1 candle ago close / 3)” and latest volume > latest sma( latest volume , 50 ) ) )

    can u please change this into pi script code.

  2. Harsh shah says:

    Volume spike code please
    Volume greater then peivous candle (simple moving average volume 1000)*10

  3. Sridhar Venkataraman says:

    Dear Sir,
    Is there a screening method/language for candle stick (5 minutes) and SMA, EMA Bollinger and multiple candles for a continuous intraday screener? thanks

  4. Munibabu says:

    Hi Nitin/Matti

    Could you please let me learn how to code in your PI software TradeScript pdf, or any other video learning youtube channel, to use it in practical way.

    and could you upload any live videos of trading with strategy in stock market if possible, many will like it with more trust on the outcomes of the live trading.

    thank you

  5. Sudhakara says:

    Hi Sir:
    Could you please help me the code for yesterday’s 30 minutes rsi lessthan or greaterthan todays current 30 minutes


    My ID: ZO0818

    Thanks in advance

  6. Subhankar chattaraj says:

    I want code for 5 min candles

  7. Subhankar chattaraj says:

    Dear Sir,
    Can you pls code my indicator given below
    Buy:- when vwap & 50 ema just below heiken ashi candle .
    Sell:- when vwap & 50 ema just above heiken ashi candle.
    Actually when vwap just detached heiken Ashington candle.

  8. Paramjeet Singh Makani says:

    Hi sir. Glad to get this opportunity to be here. i want to work on a algo containing Supertend for 15M, Daily and Weekly time frames at the same time, would that be possible?

  9. Vignesh says:

    Sir I need to code this program.
    Last 500 1 min candle average volume × 10 times current volume

  10. Kishore says:

    Hi ,

    I follow the swing trading signals,
    1. I look for 14 day moving average to look for the trend.
    2. If trend observed in 1 is UP followed by two days of correction (lower lows) then on third day or later whenever the scrip is closing above previous days high I buy with stop just below the lowest low of the correction.
    3. If trend observed in 1 is DOWN followed by two days of rally (higher highs) then on third day or later whenever the scrip is closing below previous days low I sell with stop just above the highest high of the rally.

    I would like to back test the above , can anyone help with the code that I can use in PI.


  11. Arup Nag says:

    Hi Nitin/Matti

    Can you please code an indicator for me based on the formula given below….either for PI or Nest Plus

    (Current bar ‘High’ – Highest ‘Close’ in last 22 bars including the current one)/Highest Close in last 22 bars including the current one) * 100

    And some guide to install this will be highly appreciated


    • Matti says:

      Hey Arup, I suggest you post this query here. A fellow forum member will be able to help you out. Also, I recommend you check out Streak – a platform where you can trade with algos with no coding.

  12. Santosh Agrawal says:


    Can you help me with a test script which uses supertrend.

  13. Soumik Roy says:

    Hi Nitin

    Please guide me the best intraday strategy formulae .

  14. rakesh chotaliya says:

    sir tell me
    TradeScript for Day’s high-low crossover

  15. Sagar Gate says:

    You guys are rocks. Nitin yo u became Idol of million people now.

    Please help me for below. I want use this script for scanner in PI :

    SALE: today’s open > previous day’s high
    BUY : today’s open < previous day's low

    Consider Today is Tueday and previous day is Monday

    Thanks in advance.

  16. Borat says:

    i need help with a script for Selling
    if (bidqty < 100000 && time is < 3:29 pm)
    execute sell .
    also script for buying
    if (askqty< 100000 && time is < 3:29 pm)
    execute buy.
    can someone help me with this?

  17. Amiya Adhikary says:

    Help me to find my exit strategy in Zerodha Pi. For buy entry, Exit Order shall be triggered when price falls below the previous two candle’s low. And for sell entry stop loss shall be triggered when price cross above previous two candle’s high.

  18. raghu says:

    can renko and supertrend be coded together?

  19. raghu says:

    can supertrend indicator and renko be coded together as a strategy in pi or algoz

  20. Nanak says:

    Hey Nitin
    i am new to trading and i want to use this coding and scanner or algo trading etc. but i cant get it or cant understand all this from the discussions above. can you please give me some proper guidance or link to understand all these topics better.


  21. Hardik says:

    hi nitin you are doing a grt work want to understand i want to do HFT trading strategies how can i get tick by tick data does zerodha provides it and if yes then at what cost

  22. radhey says:

    Dear Sir,
    Is it possible to code renko and heikin ashi candle?

  23. santhanam says:

    Is it possible to code strategy using ichimoku indicator for buy/sell.

  24. Sai Krishna says:

    Dear Nithin,

    Can you please ass Wave Trend Oscillator to the PI/ Kite Platforms, it is a very good oscillator, I asked for help in Trading Q&A to code it. Please add it in the next update as standard issue. TW, Kit after update looks great.


  25. Hiren says:

    Hello sir, please help me in making sell script when stock price hits the value grater than 1% of buy price of order.

  26. nitesh says:

    can i use c language programming.

  27. nitesh says:

    Dear sir,
    I want to know how i use use for, while and do while loop in programming . can explan with example.

    • Akshay.A says:

      Nitesh, Check under Pi >> Help >> Tradescript help. You could refer to the examples provided there with the explanation.

  28. Mahesh Dhila says:

    Hello Sir,

    i am face some error problem on expert advisory back test in Pi

    Error is – your script generated an error:
    Error: Scripts generated no Trades.

    How To Solve It


  29. krunal bhadra says:

    You are doing a wonderful job by helping your client building their strategy.
    Can you please help me building this strategy
    Every span of 15 minutes the application takes the price of Nifty and Banknifty high and lows and keep it as a reference price. After then when the 4 high low of nifty and banknifty i.e. 60 minutes remains inside of the high and lows of the reference price; it gives an alert on mobile or on email.

  30. GOVINDRAJ gkon says:

    how to add more than 100 stocks in watch list…………. i also made changes in settings >market watch>stocks to display 250 ……….in live market …….nothing happened……….i was able to put only 50 stocks …………????????

  31. GOVINDRAJ gkon says:

    Dear sir,
    i opened my zerodha account few days before….my query is…
    in order to do backtest and scanner ……what to mention for PREVIOUS HIGH, PREVIOUS LOW,CURRENT MARKET PRICE. ( i mean exact words )..
    suppose if i want to sell a stock say “abhirlanuvo” ….if its previous high is 1200 and todays current market price is 1180.
    i want to sell if cmp goes between ( 0.1 percent *previous high+previous high) AND (previous high-0.1 PERCENT *previous high).

    please reply and solve this SIR


    Dear Sir,
    I am a beginner and just started working with you. I want code a simple price action strategy. The purpose is to buy when the price equals to or greater than certain cmp and sell when price equals to or less than certain price. .I want to implement it in currency futures. the example below is for eurinrfmar2017. if it is right i want to implement it in other futcur also. if wrong please provide me the correct code. here it is
    buy :
    SET A = 70.84
    SET B = 70.84
    A >= B = TRUE
    SET A = 70.62
    SET B = 70.62
    A <= B = TRUE

    kindly revert asap

  33. Darshan Deshpande says:

    Hello Nitin

    I am new to use this application,I have gone through Tradescript software Guide,but could not find sapce where we can write the code.I am starting with simple code such as Close>SMA(Close,100),also basic tasks such as identifying securities within a specific price range, increase in volatility, crossing over of an indicator, and so forth.Please help,my cell no is 9819982084.


    Darshan Deshpande.

  34. Nishanth K says:

    I’m getting error while loading the script -> “your script generated an error”

    here is my code

    SET A = REF(CLOSE,1)
    SET B = REF(HIGH,1)
    SET C = REF(OPEN,1)
    SET D = REF(LOW,1)

  35. pravesh bajaj says:

    hello nithin sir,
    i am newly start to learn “tradescript language(algoZ)”.i tried to back taste ‘IDEA’ with simple code. i choose :– periodicity=day,barinterval=1, months=50.(i am not write any code in exit long/short script)
    buy scripte code -OPEN=LOW
    SELL script code -open=high
    “it means that if open price equal to low price a buy signal is generated and if open price is equal to high price a sell signal is generated”
    some signal are generated,buy signal when o=l and sell signal when o=h, but i observed that some day also where open price equal to low price and where open =high price there is no signal is generated.
    following are some day when no signal is generated while all condition are satisfied:-
    2/6/2016-open =low
    7/4/2016-open =high
    above are the date(dd/mm/yy) when condition is satisfied but buy/sell signal is not generated,there are many days which have same issue but problem is data box not shown date on many candle bar(chart generated by back testing) so i write only some dates only.i am also confirm from historical data of NSE.
    sir kindly guide me that there is any mistake in my code and cross chek if it is possible.

  36. Ravi says:

    Hi Nithin,

    I would like to run load or create query for below strategy in Pi|Scanner.
    Strategy would be:
    Previous close = Today’s Open = Today’s High
    Previous close = Today’s Open = Today’s Low
    And i would like to add or run this function for all the NSE scripts meaning, i don’t need to select each and individual scripts for adding.

    Many thanks for your constant effort on improving tools, techniques for investors and traders.


  37. Vellayan says:

    A script worked fine around midnight. The same script returned “your script generated an error” repeatedly for several stocks and various time frames around 8 am in the morning.

  38. Vellayan says:

    How to refer previous day’s moving average in the script? Need to compare the value of present MA with previous days’ MA.

  39. chirjeev singh says:

    pls code this for me:
    supertrend 10,3 and supertread 7,3 giving buy signal on same candle then BUY
    supertrend 10,3 and supertread 7,3 giving sell signal on same candle then SELL

  40. Akash says:

    Can you please help me code the following condition:
    If RSI of a red candle>previous green candle RSI:Buy
    If RSI of a green candle<previous red candle RSI:Sell

  41. Isaac Maria says:

    Hello Sir, I have some doubts

    1. What is the difference between Zerodha NEST and Zerodha PI ?
    2. Is the programming language same for both?

  42. kiran patel says:


  43. Mj says:

    Can you please help me code the following condition:

    Chart type: intraday
    Candle duration: 15 mins


    That particular has made a high which is equal to the days high (double top) or the script has made a new high which is within the range 0.2% of the days high on the lower side and that particular candle hasn’t broken the days high in that 15 minute duration.

    Like if days high is 100, the candle makes a high of 100 or somewhere between 99.80 to 100 that is 0.2% and the candle does not break the high in that 15 min duration.

    I am basically looking for a code to detect double top pattern with 0.2% margin of error on the lower side while making the second top.

    Hope I explained properly.

  44. Imran khan says:

    Dear Mr. Venu / Nithin,

    Can u please provide me the code for:

    If the 5min bar closes below the supertrend line then sell and
    If the 5min bar closes above the supertrend line then buy.

    I tried to create a code. But I was not able to create it. Kindly help me on this.

  45. Sanjay Vadgbalka says:

    Dear sir,
    I am trading in nifty options. I am a layman and referring sharekhan graphs for taking decisions of buy and sell. I am trading from kite but unable to understand how to use graphs in kite to trade. Is there anybody in mumbai whom i can approach to learn what you have been discussing in this blog or forum whatever you say to it.
    Kindly inform me on my email given or you can tell here in reply,
    Sanjay V

  46. ajit14 says:

    U r giving too much but in difficult manner for a layman . U can convert it in a simple manner directly to understand . Now i want in intraday after one hour opening to SCAN nifty scripts in comparison with nifty for last five days then how to get result ? U have opened so many platform but no information we get . There has to be a systematic training on connecting teamviewer step by step manner so as to digest it practically . Let it take 4/5 days

    • Venu says:

      There are some things that can be simplified and some that need you to have certain skillset. We have simplified things to the best of our capabilities and will continue to do so. If you’re not into coding, you can post your requirement on and someone will help you in coding it.

  47. RAVIKANT YADAV says:

    please code it

  48. kris says:

    can some one help me code. i want to buy the script on open at market price

  49. sudipta Bhaarat says:

    Dear Nithin,

    I want to write a script that will alert me if the price of a stock touches a Trend Line. Is this possible?
    If this is possible then plz suggest me how to script it.


  50. DJ9724 says:

    I am user of Afl in amibroker, is there anyway to apply AFL to Pi Script, or can u help me to make Script for Pi from AFL of Amibroker.

    I am not at all good at coding.

  51. Arun says:

    Dear Nithin Sir,
    what would be the strategy for one hour time frame where PSR(.2,.2)>PSR(.02,.2) and Rsi indicator on hourly chart below 30.

    Arun kumar

  52. Fahad Malik says:

    Need Reverse 10 EMA Strategy on NEST/Pi

    _SECTION_BEGIN(“Reverse 10 EMA Strategy”);
    GraphXSpace = 15;
    SetChartBkColor(ParamColor(“bkcolor”,ColorRGB(0,0, 0)));
    SetBarFillColor(IIf(C>O,ParamColor(“Candle UP Color”, colorGreen),IIf(CO,ParamColor(“Wick UP Color”, colorDarkGreen),IIf(C<=O,ParamColor("Wick Down Color", colorDarkRed),colorLightGrey)),64,0,0,0,0);

    par1 = Optimize("par1",10,5,50,1);
    A = EMA(C,par1);
    Buy = Cross(A,C);
    Sell= Cross(C,A);

    Short = Sell;
    Cover = Buy;

    Optimize( "max. loss stop level", 58, 50, 300, 1 ),
    True );

    PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
    PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
    PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
    PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
    PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
    PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);


  53. shiva says:

    hey nithin kindly help us in making the strategy expression thats been with u from long time with ticket number 415322 ……regards

  54. Sir, how to code the following parameters;Buy when Close Price crossing above upper Bollinger Bands + Money flow index entering overbought level (above 75)

  55. Satya Dani says:

    what is the algoz code for
    – buy if K%>D%
    – sell if D%>K%

  56. tvsreelatha says:

    what is the algoz code for

    !) buy if (high+low)/2+atr*3 of the previous bar = price

    2) exit when the open of the next bar or when the the open of the bar below the upper bolinger band

    3) sell if (high+low)/2- atr*3 of the previous bar = price

    4)exit when the open of the next bar or when the the open of the bar above the lower bolinger band

  57. Mayank Joshi says:

    Hi, may get code for Supertrend Indicator ATR 10 & multiplier 3 for 10min chart?

    and code for Parabolic SAR cross over for 10min chart?

    Can I place both pop up during the market?

  58. Ayan says:

    Hi, I would like to know whether it is possible to trade using AlgoZ using the Zerodha HTM (Z5). The examples provided in the blogs are for the desktop trader application only. Thanks

  59. vinesh2202 says:

    dear nithin sir
    i want a nest pulse strategy which can generate an alert when any one of scrips on my marketwatch open out side the bolinger bands.

  60. Rajiv says:

    Hi Nithin,

    is it possible to write one strategy and apply to all scrips on the watchlist?.

  61. Kabir says:

    Hi Nithin,
    I want to write a script, whish will alert me, when current Willams AD(accumulation/distribution) crosses 30 period SimpleMovingAverage of Willams AD. Could you please help me to do this. I cannot find any function for Willams AD.

    Thanks in advance.

  62. Ashish says:

    Hello Nithin, I just tried that when I’m going live with my strategy, Bracket order and trailing tick is disabled. How to enable those parameters ?

    • Hanan says:

      Bracket orders and trailing stop losses are not yet available on ZT. This will be made available on the new release of ZT which we expect to come about within the next month or so.

  63. Ashish says:

    Hello team, I’m unable to get EMA function under moving average. there are other VMA,WMA etc. but unable to see EMA. What could be the reason behind this?

    • Ashish, EMA is exponential moving average, so yes you can use that, it might have been missed in the above post.

      • Ashish says:

        Thanks Nithin. I had another query on backtesting. Is it possible to backtest the strategy including stop loss order. Currently backtesting result shows the overall profit and loss but I would like get the result by taking stoploss order consideration so that overall loss will get reduced.

        • Ashish,

          In your exit script, have an OR condition separating your Target and your Stop. The only thing with this is that you can’t have stop as a numerical value, it will again have to be a technical analysis condition.


          • Ashish says:

            Thanks Nithin… Since it required more workaround, It would be much better if you can introduce trailing stop loss order. Is there any plan for this ?

  64. Varughese K Eappen says:

    I want to code this :Buy when MACD line crosses above Signal line and MACD above zero and RSI>50

    • Hanan says:

      Here’s the answer from the Nest Plus team…

      Please find the algoZ codes based on the logic provided.

      (MACD(13, 26, 9,EXPONENTIAL) > MACDSignal(13,26, 9, EXPONENTIAL)) and (MACD(13, 26, 9,EXPONENTIAL) > 0) and (Rsi(Close, 14) > 50)

      Please Back test them to assess the performance before applying live.

  65. Ravikumar says:

    How can i find the slope for SMA with 30 periods .


    • Hanan says:

      Ravi, could you please elaborate on your question? If I understand you right, we don’t have a Slope indicator on Zerodha Trader for SMA but there are loads of other indicators that you can try out.

      • Ravikumar says:

        Can you help me for this.
        Make a sell call, WHEN SMA (30) is decreasing and make buy when SMA(30) is increasing

  66. Ravikumar says:

    Can you help me to get this strategy

    I’ve the following Indicator

    1. Angle of EMA(CLOSE,14) is less than 0 ‘
    2. EMA(CLOSE,14) crosses SMA(CLOSE,40) from up
    Angle of EMA(close,14) gets near 0′

    And vice versa for Buy Call

  67. Ravikumar says:

    Hi Team,
    I’m using Renko Chart type.
    Can you please give me the equation for the following
    SEll if 2 renko red bars are formed ,exit when one green bar is formed
    BUY if 2 renko green bars are formed ,exit when one red bar is formed

  68. Lokesh_Choudhary says:


    I would like to code a strategy for for Nifty futures. Kindly help.

    If Last Traded Price of Ambuja Cem > Current Price then A = 10
    else A = -10

    If Last Traded Price of Sun Pharma > Current Price then A = 20
    else A = -20

    If Last Traded Price of RCom > Current Price then A = 30
    else A = -30

    If Last Traded Price of Yes Bank > Current Price then A = 40
    else A = -40

    Sum = A + B + C + D

    IF Sum > 60 Buy NIfty futures and if Sum < 60 Sell Nifty Futures.

    Stop loss =

    Nifty Low + 5 % Nifty Low If Sum < 60
    Nifth High – 5% Nifty High If Sum > 60

    And is there any code to get VWAP for shares.

  69. aviator1123 says:

    Dear Nitin,
    Want to plot trend .
    Trend Factor = 4
    ATR Periods = 10
    EMA = 30
    Line count = 5
    Peak change % = 20.

    How can I code this in Nest plus ?


  70. gilari says:

    What is the code for Parabolic Sar cross over?

  71. debjani says:

    Lot of thanks for your splendid initiative.Hope the blog continues to teach and help to develop trading system of the members.I tried my hand to write a few programs
    which produced good result until I was stucked in the following program for BUY or SELL Exit:


    When I put it to back test NEST TRADER error was ” Back Test Script Error:Error:Undefined Function “VOLUME” ”
    Pls help me out.


    • Nithin Kamath says:

      Debjani this would be the code:

      SET V = VOLUME
      (V > SMA (V,20) *10) OR (REF (V,1) > SMA (V, 20)*10) OR (REF (V, 2) > SMA (V, 20)*10) OR (REF(V, 3) > SMA(V, 20)*10) OR (REF (V, 4) > SMA (V, 20)*10) OR (REF (V, 5) > SMA (V, 20) *10) OR (REF (V, 6) > SMA (V, 20)*10)