Search code examples
pine-scripttradingtradingview-api

Pseudocode for Swing Trading script


Can anybody please explain this code in simple words:

no=input(3,title="Swing")

res=highest(high,no)
sup=lowest(low,no)
avd=iff(close>res[1],1,iff(close<sup[1],-1,0))
avn=valuewhen(avd!=0,avd,0)
tsl=iff(avn==1,sup,res)

Thanks.


Solution

  • res=highest(high,no)
    sup=lowest(low,no)
    

    This code defines one resistance and one support which are respectively: highest high of 3 bars back and lowest low of 3 bars back.

    avd=iff(close>res[1],1,iff(close<sup[1],-1,0))
    

    Then avd looks for any close above previous resistance (saved as 1 if it occurs) or any close below previous support (saved as -1 if it occurs). If close is within previous support and previous resistance, default value is saved as 0. Note that, here, "previous" resistance or support can be thought as "current" resistance and support somehow in this case. In fact, the reason for using "previous" is because support and resistance are defined by "3 bars back" lowest/highest, so we don't want current lowest/highest in our way. For example, say we have 4 bars in our dataset with those highs: 30, 50, 20, 60. When we are on the 4th bar (60), the highest high from 3 bars back is 60 as it includes itself. But the previous highest high from 3 bars back is 50. Still, conceptually, 50 is the current resistance for the 4th bar.

    avn=valuewhen(avd!=0,avd,0)
    

    Then avn returns last value of avd when it was either 1 or -1. For example, say we are within support and resistance right now, avn will return 1 if last avd was 1 or -1 if last avd was -1.

    tsl=iff(avn==1,sup,res)
    

    Finally, this will return current support if avn is 1, otherwise it will return resistance.

    NOTES: Generally speaking, this code defines one support and one resistance on every candles. Then, avd looks like a signal to alert when one of this sup/res is broken. avn will keep track of last time a break occurred. Finally tsl will keep track last support when last upside break occurred, or last resistance when last downside break occurred.