Pine Script v4 · Strategy
cRSI + Waves Strategy with VWMA overlay + sessions and order qty
A Pine Script v4 strategy built on VWMA or WMA (close, 21), MACD (close, 12) and RMA or Change (max(change(src), 0), cyclelen). It has 4 order rules and no entry of its own. Exits wait for a signal; there is no stop loss. Each trade is one contract and pays no commission. 24 settings; defaults include Max Order Size 4, Session 1: Start Hour 3 and Session 1: Start Minute 57.
Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.
- Does cRSI + Waves Strategy with VWMA overlay + sessions and order qty repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
- How did cRSI + Waves Strategy with VWMA overlay + sessions and order qty do on BTCUSDT 1D with default settings?
- Not measured
- It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its entry conditions never all held on this data. It closed no trades on the other markets either. A backtest, not investment advice.
- Can cRSI + Waves Strategy with VWMA overlay + sessions and order qty be converted to Pine Script v5?
- Not tested
- The steps are shown below, but neither version placed a trade on any market tested, so there was nothing to compare and no download is offered.
- What alerts does cRSI + Waves Strategy with VWMA overlay + sessions and order qty have?
- 2
- Bull - cRSI above WMA; Bear - cRSI below WMA.
- Does cRSI + Waves Strategy with VWMA overlay + sessions and order qty use a stop loss?
- No
- Every exit waits for a signal; nothing limits a losing trade before it fires.
BTCUSDT · 1D · default settings
- VWMA High band
- VWMA Low band
- VWMA
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- 0.00%
- $0.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 0
- 0 won · 0 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 0.00%
- $0.00
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
No stop loss
Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses iff(), which v5 removed line 292
iff() on line 292, 305. v5 writes it as the ternary c ? a : b.
-
Note
Uses transp =, which v5 removed line 230
transp = on line 230, 231, 232, 233, 389, 393, 601, 602, 617, 618, 619, 620, 621, 622, 623, 688, 689, 740, 741. v5 folds the transparency into the colour with color.new(c, transp).
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
- Upgrading to v5 renames round → math.round, vwma → ta.vwma, wma → ta.wma, macd → ta.macd, rma → ta.rma, max → math.max, change → ta.change, min → math.min.
v4 → v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 4: //@version=4 → //@version=5
- Line 72: input(type = input.integer) → input.int()
- Line 75: input(type = input.integer) → input.int()
- Line 77: input(type = input.integer) → input.int()
- Line 79: input(type = input.integer) → input.int()
- Line 81: input(type = input.integer) → input.int()
48 more edits
- Line 83: input(type = input.integer) → input.int()
- Line 85: input(type = input.integer) → input.int()
- Line 87: input(type = input.integer) → input.int()
- Line 89: input(type = input.integer) → input.int()
- Line 102: in is reserved in v5: renamed in_
- Line 114: round → math.round
- Line 198: input(type = input.integer) → input.int()
- Line 199: vwma → ta.vwma
- Line 200: vwma → ta.vwma
- Line 201: vwma → ta.vwma
- Line 203: wma → ta.wma
- Line 204: wma → ta.wma
- Line 205: wma → ta.wma
- Line 230: transp = bandTrans → color.new(vwma_color, bandTrans)
- Line 231: transp = bandTrans → color.new(vwma_color, bandTrans)
- Line 232: transp = fillTrans → color.new(vwma_color, fillTrans)
- Line 233: transp = bandTrans → color.new(vwma_color, bandTrans)
- Line 239: macd → ta.macd
- Line 267: rma → ta.rma
- Line 267: max → math.max
- Line 267: change → ta.change
- Line 268: rma → ta.rma
- Line 268: min → math.min
- Line 268: change → ta.change
- Line 292: iff(c, a, b) → (c ? a : b)
- Line 305: iff(c, a, b) → (c ? a : b)
- Line 318: input(type = input.integer) → input.int()
- Line 321: wma → ta.wma
- Line 389: transp = 80 → color.new(color.silver, 80)
- Line 393: transp = 75 → color.new(bullBearColor, 75)
- Line 405: input(type = input.integer) → input.int()
- Line 601: transp = 0 → color.new(color.navy, 0)
- Line 602: transp = 0 → color.new(color.purple, 0)
- Line 617: transp = 0 → color.new(color.blue, 0)
- Line 618: transp = 0 → color.new(color.red, 0)
- Line 619: transp = 0 → color.new(color.green, 0)
- Line 620: transp = 0 → color.new(color.maroon, 0)
- Line 621: transp = 0 → color.new(color.lime, 0)
- Line 622: transp = 0 → color.new(color.fuchsia, 0)
- Line 623: transp = 0 → color.new(color.aqua, 0)
- Line 688: transp = 0 → color.new(color.green, 0)
- Line 689: transp = 20 → color.new(color.green, 20)
- Line 740: transp = 0 → color.new(color.red, 0)
- Line 741: transp = 20 → color.new(color.red, 20)
- Line 832: round → math.round
- Line 834: strategy.order(…, false) → strategy.order(…, strategy.short)
- Line 862: round → math.round
- Line 864: strategy.order(…, true) → strategy.order(…, strategy.long)
⋯//-//@version=4+//@version=5//⋯DEBUG = false-maxOrderSize = input(defval=4, title="Max Order Size", type=input.integer,+maxOrderSize = input.int(defval=4, title="Max Order Size", minval=2)useSessions = input(defval=true, title="Limit Signals to Trading Sessions?")-sess1_startHour = input(defval=3, title="Session 1: Start Hour",- type=input.integer, minval=0, maxval=23)+sess1_startHour = input.int(defval=3, title="Session 1: Start Hour", minval=0, maxval=23)-sess1_startMinute = input(defval=57, title="Session 1: Start Minute",- type=input.integer, minval=0, maxval=59)+sess1_startMinute = input.int(defval=57, title="Session 1: Start Minute", minval=0, maxval=59)-sess1_stopHour = input(defval=10, title="Session 1: Stop Hour",- type=input.integer, minval=0, maxval=23)+sess1_stopHour = input.int(defval=10, title="Session 1: Stop Hour", minval=0, maxval=23)-sess1_stopMinute = input(defval=30, title="Session 1: Stop Minute",- type=input.integer, minval=0, maxval=59)+sess1_stopMinute = input.int(defval=30, title="Session 1: Stop Minute", minval=0, maxval=59)-sess2_startHour = input(defval=12, title="Session 2: Start Hour",- type=input.integer, minval=0, maxval=23)+sess2_startHour = input.int(defval=12, title="Session 2: Start Hour", minval=0, maxval=23)-sess2_startMinute = input(defval=57, title="Session 2: Start Minute",- type=input.integer, minval=0, maxval=59)+sess2_startMinute = input.int(defval=57, title="Session 2: Start Minute", minval=0, maxval=59)-sess2_stopHour = input(defval=14, title="Session 2: Stop Hour",- type=input.integer, minval=0, maxval=23)+sess2_stopHour = input.int(defval=14, title="Session 2: Stop Hour", minval=0, maxval=23)-sess2_stopMinute = input(defval=57, title="Session 2: Stop Minute",- type=input.integer, minval=0, maxval=59)+sess2_stopMinute = input.int(defval=57, title="Session 2: Stop Minute", minval=0, maxval=59)sess1_closeAll = input(defval=false, title="Close All at End of Session 1")⋯// function to look for a price in the lookback that is recently above the current price-recentAbove(in, thresh, lookback) =>+recentAbove(in_, thresh, lookback) => found = false for i=0 to lookback- if in[i] >= thresh+ if in_[i] >= thresh found := true⋯// is value rising or falling based on history-isRisingFalling(in, lookback) =>+isRisingFalling(in_, lookback) =>- cntThresh = round(lookback*0.6) // majority = greater than 50%+ cntThresh = math.round(lookback*0.6) // majority = greater than 50% cntUp = 0⋯ for i=1 to lookback- if in[0] > in[i]+ if in_[0] > in_[i] cntUp := cntUp + 1- else if in[0] < in[i]+ else if in_[0] < in_[i] cntDown := cntDown + 1⋯useVolume = input(title="Use Volume for VWMA (uncheck if equity does not have volume)", defval=true)-vwmaLen = input(defval=21, title="VWMA Length", type=input.integer, minval=1, maxval=200) +vwmaLen = input.int(defval=21, title="VWMA Length", minval=1, maxval=200) -vwma = vwma(close, vwmaLen)+vwma = ta.vwma(close, vwmaLen)-vwma_high = vwma(high, vwmaLen)+vwma_high = ta.vwma(high, vwmaLen)-vwma_low = vwma(low, vwmaLen)+vwma_low = ta.vwma(low, vwmaLen)if not(useVolume)- vwma := wma(close, vwmaLen)+ vwma := ta.wma(close, vwmaLen)- vwma_high := wma(high, vwmaLen)+ vwma_high := ta.wma(high, vwmaLen)- vwma_low := wma(low, vwmaLen)+ vwma_low := ta.wma(low, vwmaLen)// +1 when above, -1 when below, 0 when inside⋯// ***** Plot VWMA *****-highband = plot(plotVWMA?fixnan(vwma_high):na, title='VWMA High band', color = vwma_color, linewidth=1, transp=bandTrans)+highband = plot(plotVWMA?fixnan(vwma_high):na, title='VWMA High band', color = color.new(vwma_color, bandTrans), linewidth=1)-lowband = plot(plotVWMA?fixnan(vwma_low):na, title='VWMA Low band', color = vwma_color, linewidth=1, transp=bandTrans)+lowband = plot(plotVWMA?fixnan(vwma_low):na, title='VWMA Low band', color = color.new(vwma_color, bandTrans), linewidth=1)-fill(lowband, highband, title='VWMA Band fill', color=vwma_color, transp=fillTrans)+fill(lowband, highband, title='VWMA Band fill', color=color.new(vwma_color, fillTrans))-plot(plotVWMA?vwma:na, title='VWMA', color = vwma_color, linewidth=3, transp=bandTrans)+plot(plotVWMA?vwma:na, title='VWMA', color = color.new(vwma_color, bandTrans), linewidth=3)//=================================================================================================================================⋯//=================================================================================================================================-[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)+[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)// Is the histogram rising or falling⋯phasingLag = (vibration - 1) / 2.0-up = rma(max(change(src), 0), cyclelen)+up = ta.rma(math.max(ta.change(src), 0), cyclelen)-down = rma(-min(change(src), 0), cyclelen)+down = ta.rma(-math.min(ta.change(src), 0), cyclelen)rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)⋯ for m = 0 to cyclicmemory - 1 by 1- below := below + iff(crsi[m] < testvalue, 1, 0)+ below := below + (crsi[m] < testvalue ? 1 : 0) below⋯ for m = 0 to cyclicmemory - 1 by 1- above := above + iff(crsi[m] >= testvalue, 1, 0)+ above := above + (crsi[m] >= testvalue ? 1 : 0) above⋯//=================================================================================================================================-crsiMaLen = input(title="cRSI Moving Average Length", defval=50, minval=0, step=5, type=input.integer)+crsiMaLen = input.int(title="cRSI Moving Average Length", defval=50, minval=0, step=5)// crsiSMA = sma(crsi,crsiMaLen)// crsiEMA = ema(crsi,crsiMaLen)-crsiWMA = wma(crsi,crsiMaLen)+crsiWMA = ta.wma(crsi,crsiMaLen)// plot(crsiSMA, "CRSI SMA", color.red, linewidth=2)⋯h1 = hline(plotCRSI?30:na, title="Oversold", linestyle=hline.style_dashed, linewidth=2)-fill(h1, h2, color=color.silver, transp=80)+fill(h1, h2, color=color.new(color.silver, 80))// cRSI⋯crsiHB2 = plot(plotCRSI?crsiHighband:na, "cRSI HighBand", bullBearColor)-fill(crsiLB2, crsiHB2, bullBearColor, transp=75)+fill(crsiLB2, crsiHB2, color.new(bullBearColor, 75))plot(plotCRSI?crsiWMA:na, "CRSI WMA", color.fuchsia, linewidth=2)⋯// TOP AND BOTTOM ARE DETECTED ONE BAR LATE!!!-topBottomLookback = input(title="cRSI Top/Bottom Detector Lookback (3 is more robust but misses smaller)", defval=2, minval=2, maxval=3, step=1, type=input.integer)+topBottomLookback = input.int(title="cRSI Top/Bottom Detector Lookback (3 is more robust but misses smaller)", defval=2, minval=2, maxval=3, step=1)crsiTop = isTop(crsi, topBottomLookback)⋯impWaveSz = size.tiny-plotshape(plotStrong and waveStrongImpulse?crsi[1]:na, text="s", title='Strong Impulse', style=shape.labeldown, location=location.absolute, color=color.navy, transp=0, offset=-1, textcolor=color.white, size=impWaveSz)+plotshape(plotStrong and waveStrongImpulse?crsi[1]:na, text="s", title='Strong Impulse', style=shape.labeldown, location=location.absolute, color=color.new(color.navy, 0), offset=-1, textcolor=color.white, size=impWaveSz)-plotshape(plotWeak and waveWeakImpulse?crsi[1]:na, text="w", title='Weak Impulse', style=shape.labeldown, location=location.absolute, color=color.purple, transp=0, offset=-1, textcolor=color.white, size=impWaveSz)+plotshape(plotWeak and waveWeakImpulse?crsi[1]:na, text="w", title='Weak Impulse', style=shape.labeldown, location=location.absolute, color=color.new(color.purple, 0), offset=-1, textcolor=color.white, size=impWaveSz)//---------------------⋯corWaveSz = size.small-plotshape(plotWaves and waveA?crsi[1]:na, text="A", title='Wave A', style=shape.labelup, location=location.absolute, color=color.blue, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotWaves and waveA?crsi[1]:na, text="A", title='Wave A', style=shape.labelup, location=location.absolute, color=color.new(color.blue, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotWaves and waveB?crsi[1]:na, text="B", title='Wave B', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotWaves and waveB?crsi[1]:na, text="B", title='Wave B', style=shape.labeldown, location=location.absolute, color=color.new(color.red, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotWaves and waveC?crsi[1]:na, text="C", title='Wave C', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotWaves and waveC?crsi[1]:na, text="C", title='Wave C', style=shape.labelup, location=location.absolute, color=color.new(color.green, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotWaves and waveD?crsi[1]:na, text="D", title='Wave D', style=shape.labeldown, location=location.absolute, color=color.maroon, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotWaves and waveD?crsi[1]:na, text="D", title='Wave D', style=shape.labeldown, location=location.absolute, color=color.new(color.maroon, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotWaves and waveE?crsi[1]:na, text="E", title='Wave E', style=shape.labelup, location=location.absolute, color=color.lime, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotWaves and waveE?crsi[1]:na, text="E", title='Wave E', style=shape.labelup, location=location.absolute, color=color.new(color.lime, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotWaves and waveF?crsi[1]:na, text="F", title='Wave F', style=shape.labeldown, location=location.absolute, color=color.fuchsia, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotWaves and waveF?crsi[1]:na, text="F", title='Wave F', style=shape.labeldown, location=location.absolute, color=color.new(color.fuchsia, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotWaves and waveG?crsi[1]:na, text="G", title='Wave G', style=shape.labelup, location=location.absolute, color=color.aqua, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotWaves and waveG?crsi[1]:na, text="G", title='Wave G', style=shape.labelup, location=location.absolute, color=color.new(color.aqua, 0), offset=-1, textcolor=color.white, size=corWaveSz)//---------------------⋯[regularBullish,hiddenBullish] = bullish(crsiLows, crsi, close)-plotshape(plotBull and regularBullish?crsi[1]-12:na, text="Bull", title='Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotBull and regularBullish?crsi[1]-12:na, text="Bull", title='Bull', style=shape.labelup, location=location.absolute, color=color.new(color.green, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotHiddenBull and hiddenBullish?crsi[1]-12:na, text="H Bull", title='Hidden Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=20, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotHiddenBull and hiddenBullish?crsi[1]-12:na, text="H Bull", title='Hidden Bull', style=shape.labelup, location=location.absolute, color=color.new(color.green, 20), offset=-1, textcolor=color.white, size=corWaveSz)//------------------------------------------------------------------------------⋯[regularBearish,hiddenBearish] = bearish(crsiHighs, crsi, close)-plotshape(plotBear and regularBearish?crsi[1]+10:na, text="Bear", title='Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotBear and regularBearish?crsi[1]+10:na, text="Bear", title='Bear', style=shape.labeldown, location=location.absolute, color=color.new(color.red, 0), offset=-1, textcolor=color.white, size=corWaveSz)-plotshape(plotHiddenBear and hiddenBearish?crsi[1]+10:na, text="H Bear", title='Hidden Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=20, offset=-1, textcolor=color.white, size=corWaveSz)+plotshape(plotHiddenBear and hiddenBearish?crsi[1]+10:na, text="H Bear", title='Hidden Bear', style=shape.labeldown, location=location.absolute, color=color.new(color.red, 20), offset=-1, textcolor=color.white, size=corWaveSz)//==================================================================================================================================================================================================================================================================⋯sellSize := sellSize < maxSellOrderSize/3 ? 0 : sellSize-sellSize := round(sellSize)+sellSize := math.round(sellSize)if (Sell and newTrades)- strategy.order("Sell", false, sellSize)+ strategy.order("Sell", strategy.short, sellSize)//--------------------------------------------------------------------------------------------⋯buySize := buySize < maxSellOrderSize/3 ? 0 : buySize-buySize := round(buySize)+buySize := math.round(buySize)if (Buy and newTrades)- strategy.order("Buy", true, buySize)+ strategy.order("Buy", strategy.long, buySize)// Close open position at end of Session 1, if enabled⋯Clean v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 74: input() → input.bool()
- Line 83: input() → input.bool()
- Line 84: input() → input.bool()
- Line 189: input() → input.bool()
- Line 250: input() → input.int()
- Line 590: input() → input.bool()
6 more edits
- Line 591: input() → input.bool()
- Line 607: input() → input.bool()
- Line 623: input() → input.bool()
- Line 624: input() → input.bool()
- Line 625: input() → input.bool()
- Line 626: input() → input.bool()
⋯ minval=2)-useSessions = input(defval=true, title="Limit Signals to Trading Sessions?")+useSessions = input.bool(defval=true, title="Limit Signals to Trading Sessions?")sess1_startHour = input.int(defval=3, title="Session 1: Start Hour", minval=0, maxval=23)⋯sess2_stopMinute = input.int(defval=57, title="Session 2: Stop Minute", minval=0, maxval=59)-sess1_closeAll = input(defval=false, title="Close All at End of Session 1")+sess1_closeAll = input.bool(defval=false, title="Close All at End of Session 1")-sess2_closeAll = input(defval=true, title="Close All at End of Session 2")+sess2_closeAll = input.bool(defval=true, title="Close All at End of Session 2")//=================================================================================================================================⋯// check if volume is available for this equity-useVolume = input(title="Use Volume for VWMA (uncheck if equity does not have volume)", defval=true)+useVolume = input.bool(title="Use Volume for VWMA (uncheck if equity does not have volume)", defval=true)vwmaLen = input.int(defval=21, title="VWMA Length", minval=1, maxval=200) ⋯src = close-domcycle = input(10, minval=5, title="cRSI Dominant Cycle Length (persist after high/low)") //12+domcycle = input.int(10, minval=5, title="cRSI Dominant Cycle Length (persist after high/low)") //12crsi = 0.0⋯// Impulse waves-plotStrong = input(title="Plot Strong Impulse Waves (above upper band)", defval=true) and plotCRSI+plotStrong = input.bool(title="Plot Strong Impulse Waves (above upper band)", defval=true) and plotCRSI-plotWeak = input(title="Plot Weak Impulse Waves (below upper band)", defval=true) and plotCRSI+plotWeak = input.bool(title="Plot Weak Impulse Waves (below upper band)", defval=true) and plotCRSIimpWaveSz = size.tiny⋯// plotshape(waveABCDE?crsi[1]:na, title='Wave ABCDE', style=shape.triangleup, location=location.absolute, color=color.green, transp=0, offset=-1, text="ABCDE", textcolor=color.green, size=size.small)-plotWaves = input(title="Plot Corrective Waves (ABC,ABCDE)", defval=true) and plotCRSI+plotWaves = input.bool(title="Plot Corrective Waves (ABC,ABCDE)", defval=true) and plotCRSIcorWaveSz = size.small⋯//=================================================================================================================================-plotBull = input(title="Plot Bullish (cRSI Higher-Low : Price Lower-Low)", defval=true) and plotCRSI+plotBull = input.bool(title="Plot Bullish (cRSI Higher-Low : Price Lower-Low)", defval=true) and plotCRSI-plotHiddenBull = input(title="Plot Hidden Bullish (cRSI Lower-Low : Price Higher-Low)", defval=true) and plotCRSI+plotHiddenBull = input.bool(title="Plot Hidden Bullish (cRSI Lower-Low : Price Higher-Low)", defval=true) and plotCRSI-plotBear = input(title="Plot Bearish (cRSI Lower-High : Price Higher-High", defval=true) and plotCRSI+plotBear = input.bool(title="Plot Bearish (cRSI Lower-High : Price Higher-High", defval=true) and plotCRSI-plotHiddenBear = input(title="Plot Hidden Bearish (cRSI Higher-High : Price Lower-High)", defval=true) and plotCRSI+plotHiddenBear = input.bool(title="Plot Hidden Bearish (cRSI Higher-High : Price Lower-High)", defval=true) and plotCRSI//------------------------------------------------------------------------------⋯Does it run in Pine Script v6?
Not tested
Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯//-//@version=5+//@version=6//⋯Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Max Order Size | 4 | int (written input.integer) · min 2 | maxSellOrderSize maxBuyOrderSize |
| Limit Signals to Trading Sessions? | true | bool | line 794 |
| Session 1: Start Hour | 3 | int (written input.integer) · min 0 · max 23 | line 795 line 797 |
| Session 1: Start Minute | 57 | int (written input.integer) · min 0 · max 59 | line 795 |
| Session 1: Stop Hour | 10 | int (written input.integer) · min 0 · max 23 | close_all line 797 line 799 line 866 |
| Session 1: Stop Minute | 30 | int (written input.integer) · min 0 · max 59 | close_all line 799 line 866 |
| Session 2: Start Hour | 12 | int (written input.integer) · min 0 · max 23 | line 801 line 803 |
| Session 2: Start Minute | 57 | int (written input.integer) · min 0 · max 59 | line 801 |
| Session 2: Stop Hour | 14 | int (written input.integer) · min 0 · max 23 | close_all line 803 line 805 line 870 |
| Session 2: Stop Minute | 57 | int (written input.integer) · min 0 · max 59 | close_all line 805 line 870 |
| Close All at End of Session 1 | false | bool | close_all line 866 |
| Close All at End of Session 2 | true | bool | close_all line 870 |
| Use Volume for VWMA (uncheck if equity does not have volume) | true | bool | line 202 |
| VWMA Length | 21 | int (written input.integer) · min 1 · max 200 | vwma vwma_high vwma_low |
| cRSI Dominant Cycle Length (persist after high/low) | 10 | int · min 5 | cyclelen cyclicmemory |
| cRSI Moving Average Length | 50 | int (written input.integer) · min 0 · step 5 | crsiWMA |
| cRSI Top/Bottom Detector Lookback (3 is more robust but misses smaller) | 2 | int (written input.integer) · min 2 · max 3 · step 1 | crsiTop crsiBottom Buy4 Buy5 |
| Plot Strong Impulse Waves (above upper band) | true | bool | Strong Impulse |
| Plot Weak Impulse Waves (below upper band) | true | bool | Weak Impulse |
| Plot Corrective Waves (ABC,ABCDE) | true | bool | Wave A Wave B Wave C Wave D Wave E Wave F Wave G |
| Plot Bullish (cRSI Higher-Low : Price Lower-Low) | true | bool | Bull |
| Plot Hidden Bullish (cRSI Lower-Low : Price Higher-Low) | true | bool | Hidden Bull |
| Plot Bearish (cRSI Lower-High : Price Higher-High | true | bool | Bear |
| Plot Hidden Bearish (cRSI Higher-High : Price Lower-High) | true | bool | Hidden Bear |
What it calculates
- VWMA / WMA (
vwma,ta.vwmain v5)close, VWMA Length (21)vwma · line 199 - VWMA / WMA (
vwma,ta.vwmain v5)high, VWMA Length (21)vwma_high · line 200 - VWMA / WMA (
vwma,ta.vwmain v5)low, VWMA Length (21)vwma_low · line 201 - MACD (
macd,ta.macdin v5)close, 12, 26, 9macdLine · line 239 - MACD (
macd,ta.macdin v5)close, 12, 26, 9signalLine · line 239 - MACD (
macd,ta.macdin v5)close, 12, 26, 9histLine · line 239 - RMA / Change (
rma,ta.rmain v5)max(change(src), 0), cyclelenup · line 267 - RMA / Change (
rma,ta.rmain v5)-min(change(src), 0), cyclelendown · line 268 - WMA (
wma,ta.wmain v5)crsi, cRSI Moving Average Length (50)crsiWMA · line 321
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
The script has 132 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| order Sell short | (Sell and newTrades) | On | 834 |
| order Buy long | (Buy and newTrades) | On | 864 |
| Close | (sess1_closeAll and hour == sess1_stopHour and minute >= sess1_stopMinute ) | On | 867 |
| Close | (sess2_closeAll and hour == sess2_stopHour and minute >= sess2_stopMinute ) | On | 871 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| Bull - cRSI above WMA | alertcondition | Bull - cRSI above WMA | 378 |
| Bear - cRSI below WMA | alertcondition | Bear - cRSI below WMA | 379 |
Does it repaint?
No
No repainting patterns in the source.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | 0.0% | +102.5% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | 0.0% | +9.8% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | 0.0% | +8.4% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | 0.0% | +16.7% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | 0.0% | +21.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | 0.0% | +148.3% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | 0.0% | +17.1% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| cRSI + Waves Strategy with VWMA overlay + sessions and order qty this page | — | v4 strategy | 0.0% | 0 | 0.0% |
| cRSI + Waves Strategy with VWMA overlay by Dr_Roboto | vwma macd rma wma rising falling | v4 strategy | No trades on this market | ||
| Trading Day and Time Session by Dannnnnnny | vwma rising falling | v5 strategy | No trades on this market | ||
| Linear On MACD by stocktechbot | macd rising falling vwma | v5 strategy | +1.5% | 16 | 5.6% |
| Quarterly Returns in Strategies vs Buy & Hold by Dannnnnnny | vwma rising falling | v4 strategy | +80.2% | 4 | 10.7% |
| TEMA-DEMA-HMA Strategy by Tuned_Official | wma rising falling | v4 strategy | +73.8% | 4 | 30.6% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 95 ms | With a workaround 1,000 bars in 3,954 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
Zeal Terminal's engine currently reads an order side written as false, true as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 834, 864) so the engine trades the way the script says.
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © Dr_Roboto; forked May 7, 2021 by jadamcraig////@version=4//// This indicator uses the cyclic smoothed Relative Strength Index (cRSI) instead of the traditional Relative Strength Index (RSI). See below for more info on the benefits to the cRSI.//// [b]My key contributions[/b]// 1) A Weighted Moving Average (WMA) to track the general trend of the cRSI signal. This is very helpful in determining when the equity switches from bullish to bearish, which can be used to determine buy/sell points. // This is then is used to color the region between the upper and lower cRSI bands (green above, red below).// 2) An attempt to detect the motive (impulse) and corrective and waves. Corrective waves are indicated A, B, C, D, E, F, G. F and G waves are not technically Elliot Waves, but the way I detect waves it is really hard // to always get it right. Once and a while you could actually see G and F a second time. Motive waves are identified as s (strong) and w (weak). Strong waves have a peak above the cRSI upper band and weak waves have a peak below the upper band.// 3) My own divergence indicator for bull, hidden bull, bear, and hidden bear. I was not able to replicate the TradingView style of drawing a line from peak to peak, but for this indicator I think in the end it makes the chart cleaner.// 4) I have also added "alert conditions" for most of the key events. Select the equity you want (such as: SPX) and the desired timeframe (such as: D).// Go to the TradingView "Alerts" tab (click the alarm clock icon) --> Create Alert (alarm clock with a +) --> Change the first condition drop down to "Cyclic Smoothed RSI with Motive-Corrective Wave Indicator" --> in the // drop down below that select the alert that you want (such as: Bull - cRSI Above WMA). You will want to give the alert a good name that includes the ticker name and time frame, for example "SPX 1D: Bull - cRSI above WMA"//// There is a latency issue with an indicator like this that is based on moving averages. That means they tend to trigger right after key events. Perfect timing is not possible strictly with these indicators, but they do work // very well "on average." However, my implementation has minimal latency as peaks (tops/bottoms) only require one bar to detect.//// As a bit of an Easter Egg, this code can be tweaked and run as a strategy to get buy/sell signals. I use this code for both my indicator and for trading strategy. Just copy and past it into a new strategy script and just // change it from study to something like.// strategy("cRSI + Waves Strategy with VWMA overlay", overlay=overlay)// The buy/sell code is at the end and just needs to be uncommented. I make no promises or guarantees about how good it is as a strategy, but it gives you some code and ideas to work with.//// [b]Tuning[/b]// 1) Volume Weighted Moving Average (VWMA): This is a “hidden strategy” feature implemented that will display the high-low bands of the VWMA on the price chart if run the code using “overlay = true”. // - [Use Volume for VWMA] If the equity does not have volume, then the VWMA will not show up. Uncheck this box and it will use the regular WMA (no volume).// - [VWMA Length] defines how far back the WMA averages price.//// 2) cRSI (Black line in the indicator)// - [CRSI Dominate Cycle Length] Increase to length that amount of time a band (upper/lower) stays high/low after a peak. Reduce the value to shorten the time. Just increment it up/down to see the effect.// - [CRSI Moving Average Length] defines how far back the SMA averages the cRSI. This affects the purple line in the indicator.// - [CRSI Top/Bottom Detector Lookback] defines how many bars back the peak detector looks to determine if a peak has occurred. For example, a top is detected like this: current-bar down relative to the 1-bar-back, // 1-bar-back up relative to 2-bars-back (look back = 1), c) 2-bars-back up relative to 3-bars-back (lookback = 2), and d) 3-bars-back up relative to 4-bars-back (lookback = 3). I hope that makes sense. There are // only 2 options for this setting: 2 or 3 bars. 2 bars will be able to detect small peaks but create more “false” peaks that may not be meaningful. 3 bars will be more robust but can miss short duration peaks.//// 3) Waves// - The check boxes are self explanatory for which labels they turn on and off on the plot.//// 4) Divergence Indicators// - The check boxes are self explanatory for which labels they turn on and off on the plot.//// [b]Hints[/b]// - The most common parameter to change is the [CRSI Top/Bottom Detector Lookback]. Different stocks will have different levels of strength in their peaks. A setting of 2 may generate too many corrective waves.// - Different times scales will give you different wave counts. This is to be expected. A conunter impulse wave inside a corrective wave may actually go above the cRSI WMA on a smaller time frame. You may need to increase it one or two levels to see large waves.// - Just because you see divergence (bear or hidden bear) does not mean a price is going to go down. Often price continues to rise through bears, so take note and that is normal. Bulls are usually pretty good indicators especially if you see them on C,E,G waves.////// ---------------------------------------// cyclic smoothed RSI (cRSI) indicator// ---------------------------------------// The “core” code for the cyclic smoothed RSI (cRSI) indicator was written by Lars von Theinen and is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/. Copyright (C) 2017 CC BY, // whentotrade / Lars von Thienen. For more details on the cRSI Indicator: https://www.tradingview.com/script/TmqiR1jp-RSI-cyclic-smoothed-v2///// The cyclic smoothed RSI indicator is an enhancement of the classic RSI, adding// 1) additional smoothing according to the market vibration,// 2) adaptive upper and lower bands according to the cyclic memory and// 3) using the current dominant cycle length as input for the indicator.// It is much more responsive to market moves than the basic RSI. The indicator uses the dominant cycle as input to optimize signal, smoothing, and cyclic memory. To get more in-depth information on the cyclic-smoothed // RSI indicator, please read Decoding The Hidden Market Rhythm - Part 1: Dynamic Cycles (2017), Chapter 4: "Fine-tuning technical indicators." You need to derive the dominant cycle as input parameter for the cycle length as described in chapter 4.//=================================================================================================================================//=================================================================================================================================overlay = true // plots VWMA (need to close and re-added)// overlay = false // plots cRSI (need to close and re-added)strategy("cRSI + Waves Strategy with VWMA overlay + sessions and order qty", overlay=overlay)//=================================================================================================================================//=================================================================================================================================// Disables cRSI and VWMA plotting so debug data can be plotted// DEBUG = trueDEBUG = falsemaxOrderSize = input(defval=4, title="Max Order Size", type=input.integer, minval=2)useSessions = input(defval=true, title="Limit Signals to Trading Sessions?")sess1_startHour = input(defval=3, title="Session 1: Start Hour", type=input.integer, minval=0, maxval=23)sess1_startMinute = input(defval=57, title="Session 1: Start Minute", type=input.integer, minval=0, maxval=59)sess1_stopHour = input(defval=10, title="Session 1: Stop Hour", type=input.integer, minval=0, maxval=23)sess1_stopMinute = input(defval=30, title="Session 1: Stop Minute", type=input.integer, minval=0, maxval=59)sess2_startHour = input(defval=12, title="Session 2: Start Hour", type=input.integer, minval=0, maxval=23)sess2_startMinute = input(defval=57, title="Session 2: Start Minute", type=input.integer, minval=0, maxval=59)sess2_stopHour = input(defval=14, title="Session 2: Stop Hour", type=input.integer, minval=0, maxval=23)sess2_stopMinute = input(defval=57, title="Session 2: Stop Minute", type=input.integer, minval=0, maxval=59)sess1_closeAll = input(defval=false, title="Close All at End of Session 1")sess2_closeAll = input(defval=true, title="Close All at End of Session 2")//=================================================================================================================================//=================================================================================================================================// Helper Functions//=================================================================================================================================//=================================================================================================================================// function to convert bool to intb2i(bval) => ival = bval ? 1 : 0// function to look for a price in the lookback that is recently above the current pricerecentAbove(in, thresh, lookback) => found = false for i=0 to lookback if in[i] >= thresh found := true break if found res = true else res = false// is value rising or falling based on historyisRisingFalling(in, lookback) => cntThresh = round(lookback*0.6) // majority = greater than 50% cntUp = 0 cntDown = 0 rising = false falling = false // count up the times it is above or below the current value for i=1 to lookback if in[0] > in[i] cntUp := cntUp + 1 else if in[0] < in[i] cntDown := cntDown + 1 // rising if cntUp > cntThresh rising := true else rising := false // falling if cntDown > cntThresh falling := true else falling := false // flat flat = not(rising) and not(falling) // if flat, then select preivous value for rising and falling if flat rising := rising[1] falling := falling[1] // return tuple [rising,falling,flat]// Do the last several prices form a topisTop(price, lookback) => if lookback == 3 // 3 prices back -> 3rd check helps ensure there was a down trend, but can miss some small reversals // up->up->down if (price[2] > price[3]) and (price[1] > price[2]) and (price[0] < price[1]) top = true else top = false else // 2 places back // up->down if (price[1] > price[2]) and (price[0] < price[1]) top = true else top = false // Do the last several prices form a bottomisBottom(price, lookback) => if lookback == 3 // 3 prices back -> 3rd check helps ensure there was a down trend, but can miss some small reversals // down->down->up if (price[2] < price[3]) and (price[1] < price[2]) and (price[0] > price[1]) bottom = true else bottom = false else // 2 prices back // down->up if (price[1] < price[2]) and (price[0] > price[1]) bottom = true else bottom = false// function to filter multiple signals in a rowfilterSignal(signalFlag, lookback) => signalFlagFilt = signalFlag for i = 1 to lookback signalFlagFilt := signalFlagFilt[0] == true and signalFlagFilt[i] == true ? false : signalFlagFilt//=================================================================================================================================//=================================================================================================================================// Price Movement//=================================================================================================================================//=================================================================================================================================priceRising = close[0] >= close[1] and close[1] >= close[2]priceFalling = close[0] <= close[1] and close[1] <= close[2]// plot(priceRising?1.0:0,color=color.green)// plot(priceFalling?1.0:0,color=color.red)//=================================================================================================================================//=================================================================================================================================// Volume Weighted Moving Average (VWMA)//=================================================================================================================================//=================================================================================================================================plotVWMA = overlay and not(DEBUG)// check if volume is available for this equityuseVolume = input(title="Use Volume for VWMA (uncheck if equity does not have volume)", defval=true)vwmaLen = input(defval=21, title="VWMA Length", type=input.integer, minval=1, maxval=200) vwma = vwma(close, vwmaLen)vwma_high = vwma(high, vwmaLen)vwma_low = vwma(low, vwmaLen)if not(useVolume) vwma := wma(close, vwmaLen) vwma_high := wma(high, vwmaLen) vwma_low := wma(low, vwmaLen)// +1 when above, -1 when below, 0 when insidevwmaSignal(priceOpen, priceClose, vwmaHigh, vwmaLow) => sig = 0 color = color.gray if priceClose > vwmaHigh sig := 1 color := color.green else if priceClose < vwmaLow sig := -1 color := color.red else sig := 0 color := color.gray [sig,color][vwma_sig, vwma_color] = vwmaSignal(open, close, vwma_high, vwma_low)priceAboveVWMA = vwma_sig == 1 ? true : falsepriceBelowVWMA = vwma_sig == -1 ? true : false// plot(priceAboveVWMA?2.0:0,color=color.blue)// plot(priceBelowVWMA?2.0:0,color=color.maroon)// bandTrans = input(defval=70, title="VWMA Band Transparancy (100 invisible)", type=input.integer, minval=0, maxval=100)// fillTrans = input(defval=70, title="VWMA Fill Transparancy (100 invisible)", type=input.integer, minval=0, maxval=100)bandTrans = 70fillTrans = 70// ***** Plot VWMA *****highband = plot(plotVWMA?fixnan(vwma_high):na, title='VWMA High band', color = vwma_color, linewidth=1, transp=bandTrans)lowband = plot(plotVWMA?fixnan(vwma_low):na, title='VWMA Low band', color = vwma_color, linewidth=1, transp=bandTrans)fill(lowband, highband, title='VWMA Band fill', color=vwma_color, transp=fillTrans)plot(plotVWMA?vwma:na, title='VWMA', color = vwma_color, linewidth=3, transp=bandTrans)//=================================================================================================================================//=================================================================================================================================// Moving Average Convergence Divergence (MACD)//=================================================================================================================================//=================================================================================================================================[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)// Is the histogram rising or fallinghistLineRising = histLine[0] >= histLine[1] and histLine[1] >= histLine[2]histLineFalling = histLine[0] <= histLine[1] and histLine[1] <= histLine[2]// Did the histogram cross over zerohistLineCrossNeg2Pos = histLine[0] >= 0.0 and histLine[1] < 0.0histLineCrossPos2Neg = histLine[0] <= 0.0 and histLine[1] > 0.0// plot(histLineRising?1.0:0,color=color.green)// plot(histLineFalling?1.0:0,color=color.red)// plot(histLineCrossNeg2Pos?1.0:0,color=color.green)// plot(histLineCrossPos2Neg?1.0:0,color=color.red)//=================================================================================================================================//=================================================================================================================================// Cyclic Smoothed Relative Strength Index (cRSI)//=================================================================================================================================//=================================================================================================================================plotCRSI = not(overlay) and not(DEBUG)//src = input(title="cRSI Source", defval=close)src = closedomcycle = input(10, minval=5, title="cRSI Dominant Cycle Length (persist after high/low)") //12crsi = 0.0cyclelen = domcycle / 2vibration = 10leveling = 10.0cyclicmemory = domcycle * 2//set min/max ranges?torque = 2.0 / (vibration + 1)phasingLag = (vibration - 1) / 2.0up = rma(max(change(src), 0), cyclelen)down = rma(-min(change(src), 0), cyclelen)rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)crsi := torque * (2 * rsi - rsi[phasingLag]) + (1 - torque) * nz(crsi[1])// there is a bug that can cause the lower bound to be bigger than the upper bound with a value of 999999.0// lmax = -999999.0// lmin = 999999.0lmax = 0.0 // don't konw why, but this fixes the buglmin = 0.0for i = 0 to cyclicmemory - 1 by 1 if nz(crsi[i], -999999.0) > lmax lmax := nz(crsi[i]) lmax else if nz(crsi[i], 999999.0) < lmin lmin := nz(crsi[i]) lminmstep = (lmax - lmin) / 100aperc = leveling / 100crsiLowband = 0.0for steps = 0 to 100 by 1 testvalue = lmin + mstep * steps above = 0 below = 0 for m = 0 to cyclicmemory - 1 by 1 below := below + iff(crsi[m] < testvalue, 1, 0) below ratio = below / cyclicmemory if ratio >= aperc crsiLowband := testvalue break else continuecrsiHighband = 0.0for steps = 0 to 100 by 1 testvalue = lmax - mstep * steps above = 0 for m = 0 to cyclicmemory - 1 by 1 above := above + iff(crsi[m] >= testvalue, 1, 0) above ratio = above / cyclicmemory if ratio >= aperc crsiHighband := testvalue break else continue//=================================================================================================================================//=================================================================================================================================// cRSI moving average//=================================================================================================================================//=================================================================================================================================crsiMaLen = input(title="cRSI Moving Average Length", defval=50, minval=0, step=5, type=input.integer)// crsiSMA = sma(crsi,crsiMaLen)// crsiEMA = ema(crsi,crsiMaLen)crsiWMA = wma(crsi,crsiMaLen)// plot(crsiSMA, "CRSI SMA", color.red, linewidth=2)// plot(crsiEMA, "CRSI EMA", color.green, linewidth=2)// plot(crsiWMA, "CRSI WMA", color.fuchsia, linewidth=2)//=================================================================================================================================//=================================================================================================================================// cRSI Feature Analysis//=================================================================================================================================//=================================================================================================================================// Crossing of upper bandcrsiAboveHighband = crsi >= crsiHighbandcrsiBelowHighband = not(crsiAboveHighband)crsiCrossAboveHighband = crsiAboveHighband[0] and crsiBelowHighband[1] ? true : falsecrsiCrossBelowHighband = crsiBelowHighband[0] and crsiAboveHighband[1] ? true : false// plot(crsiAboveHighband?2.0:0,color=color.black)// plot(crsiBelowHighband?2.25:0,color=color.red)// plot(crsiCrossAboveHighband?2.5:0,color=color.green)// plot(crsiCrossBelowHighband?2.75:0,color=color.blue)//-----------------------------------------------------------------------------// Crossing of lower bandcrsiAboveLowband = crsi >= crsiLowbandcrsiBelowLowband = not(crsiAboveLowband)crsiCrossAboveLowband = crsiAboveLowband[0] and crsiBelowLowband[1] ? true : falsecrsiCrossBelowLowband = crsiBelowLowband[0] and crsiAboveLowband[1] ? true : false// plot(crsiAboveLowband?1.0:0,color=color.black)// plot(crsiBelowLowband?1.25:0,color=color.red)// plot(crsiCrossAboveLowband?1.5:0,color=color.green)// plot(crsiCrossBelowLowband?1.75:0,color=color.blue)//-----------------------------------------------------------------------------// Crossing of WMAcrsiAboveWMA = crsi >= crsiWMAcrsiBelowWMA = not(crsiAboveWMA)crsiCrossAboveWMA = crsiAboveWMA[0] and crsiBelowWMA[1] ? true : falsecrsiCrossBelowWMA = crsiBelowWMA[0] and crsiAboveWMA[1] ? true : false// plot(crsiAboveWMA?1.0:0,color=color.black)// plot(crsiBelowWMA?1.25:0,color=color.red)// plot(crsiCrossAboveWMA?1.5:0,color=color.blue)// plot(crsiCrossBelowWMA?1.75:0,color=color.maroon)//-----------------------------------------------------------------------------// Crossing of 50 levelcrsiAbove50 = crsi >= 50crsiBelow50 = not(crsiAbove50)crsiCrossAbove50 = crsiAbove50[0] and crsiBelow50[1] ? true : falsecrsiCrossBelow50 = crsiBelow50[0] and crsiAbove50[1] ? true : false//-----------------------------------------------------------------------------// CRSI falling or risingcrsiRising = crsi[0] >= crsi[1]crsiFalling = crsi[0] < crsi[1]// plot(crsiRising?3.0:0,color=color.green)// plot(crsiFalling?3.0:0,color=color.red)//-----------------------------------------------------------------------------// Compare cRSI to crsiWMA to determine if equity is bullish (motive) or bearish (corrective)bull = crsiAboveWMAbear = not(bull)bullBearColor = bull ? color.green : color.redbullStart = bull[0] and bear[1] ? true : falsebearStart = bear[0] and bull[1] ? true : falsealertcondition(bullStart, title='Bull - cRSI above WMA', message='Bull - cRSI above WMA')alertcondition(bearStart, title='Bear - cRSI below WMA', message='Bear - cRSI below WMA')//=================================================================================================================================//=================================================================================================================================// Plot cRSI colored by Bull or Bear//=================================================================================================================================//=================================================================================================================================// Basic RSIhline(plotCRSI?50:na, title="Middle Line", linestyle=hline.style_dashed, linewidth=2)h2 = hline(plotCRSI?70:na, title="Overbought", linestyle=hline.style_dashed, linewidth=2)h1 = hline(plotCRSI?30:na, title="Oversold", linestyle=hline.style_dashed, linewidth=2)fill(h1, h2, color=color.silver, transp=80)// cRSIcrsiLB2 = plot(plotCRSI?crsiLowband:na, "cRSI LowBand", bullBearColor)crsiHB2 = plot(plotCRSI?crsiHighband:na, "cRSI HighBand", bullBearColor)fill(crsiLB2, crsiHB2, bullBearColor, transp=75)plot(plotCRSI?crsiWMA:na, "CRSI WMA", color.fuchsia, linewidth=2)plot(plotCRSI?crsi:na, "CRSI", color.black, linewidth=4)//=================================================================================================================================//=================================================================================================================================// Moitve (impulse) and Corrective Waves//=================================================================================================================================//=================================================================================================================================// THIS IS A MAJOR ASSUMPTION TO THIS APPROACH!!!motiveWave = bullcorrectiveWave = bear // TOP AND BOTTOM ARE DETECTED ONE BAR LATE!!!topBottomLookback = input(title="cRSI Top/Bottom Detector Lookback (3 is more robust but misses smaller)", defval=2, minval=2, maxval=3, step=1, type=input.integer)crsiTop = isTop(crsi, topBottomLookback)crsiBottom = isBottom(crsi,topBottomLookback)// Top above high bandcrsiTopAboveHighband = crsiTop and crsiAboveHighband[1]waveStrongImpulse = crsiTopAboveHighband// Top that does not break high band but is above WMAcrsiTopBelowHighband = (crsiTop and crsiBelowHighband[1]) and (crsi > crsiWMA)waveWeakImpulse = crsiTopBelowHighband//-----------------------------------------------------------------------------// Determine the ABC, ABCDE, ABCDEFG sequence// Note that ABCDEFG is not a true Elliott corrective wave sequence, but for this approach is shows up once in a blue moonpossibleWaveA = crsiBottom and crsiBelowLowband[1]possibleWaveB = (crsiTop and crsiBelowWMA[1]) or (crsiTop and crsiBelow50[1]) // Also catch the tops that are above wma but stay under RSI 50 (rare)possibleWaveC = possibleWaveA or (crsiBottom and crsiBelowWMA[1]) // sometimes wave C is above the lower band but below the WMA// Wave ABfindWaveAB(possibleWaveA, possibleWaveB, correctiveWave) => isWaveAB = false foundMatch = false // start with Wave B if possibleWaveB // search backwards and look for wave A for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if possibleWaveA[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match an A and B wave? if foundMatch isWaveAB := true else isWaveAB := false else isWaveAB := false waveAB = findWaveAB(possibleWaveA, possibleWaveB, correctiveWave)// Wave ABCfindWaveABC(possibleWaveC, waveAB, correctiveWave) => isWaveABC = false foundMatch = false if possibleWaveC // search backwards and look for wave AB for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveAB[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveAB with C? if foundMatch isWaveABC := true else isWaveABC := false else isWaveABC := falsewaveABC = findWaveABC(possibleWaveC, waveAB, correctiveWave)// Wave ABCDfindWaveABCD(possibleWaveB, waveABC, correctiveWave) => isWaveABCD = false foundMatch = false if possibleWaveB // search backwards and look for wave ABC for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABC[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with D? if foundMatch isWaveABCD := true else isWaveABCD := false else isWaveABCD := falsewaveABCD = findWaveABCD(possibleWaveB, waveABC, correctiveWave) // Wave ABCDEfindWaveABCDE(possibleWaveC, waveABCD, correctiveWave) => isWaveABCDE = false foundMatch = false if possibleWaveC // search backwards and look for another wave ABC in this correction for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABCD[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with another waveABC? if foundMatch isWaveABCDE := true else isWaveABCDE := false else isWaveABCDE := falsewaveABCDE = findWaveABCDE(possibleWaveC, waveABCD, correctiveWave)// Wave ABCDEFfindWaveABCDEF(possibleWaveB, waveABCDE, correctiveWave) => isWaveABCDEF = false foundMatch = false if possibleWaveB // search backwards and look for another wave ABC in this correction for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABCDE[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with another waveABC? if foundMatch isWaveABCDEF := true else isWaveABCDEF := false else isWaveABCDEF := falsewaveABCDEF = findWaveABCDEF(possibleWaveB, waveABCDE, correctiveWave)// Wave ABCDEFGfindWaveABCDEFG(possibleWaveC, waveABCDEF, correctiveWave) => isWaveABCDEFG = false foundMatch = false if possibleWaveC // search backwards and look for another wave ABC in this correction for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABCDEF[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with another waveABC? if foundMatch isWaveABCDEFG := true else isWaveABCDEFG := false else isWaveABCDEFG := falsewaveABCDEFG = findWaveABCDEFG(possibleWaveC, waveABCDEF, correctiveWave)// Determine individual corrective waveswaveA = possibleWaveA and not(waveABC) and not(waveABCDE)waveB = waveAB and not(waveABCD)waveC = waveABCwaveD = waveABCDwaveE = waveABCDEwaveF = waveABCDEFwaveG = waveABCDEFG//-----------------------------------------------------------------------------// Plot key cRSI points// plot(crsiCrossBelowHighband?crsi:na, title='cRSI cross below high band', color=color.red, linewidth=7, style=plot.style_circles)// plot(crsiCrossAboveLowband?crsi:na, title='cRSI cross above low band', color=color.green, linewidth=7, style=plot.style_circles)// plot(crsiCrossBelowWMA?crsi:na, title='cRSI cross below WMA', color=color.red, linewidth=5, style=plot.style_cross)// plot(crsiCrossAboveWMA?crsi:na, title='cRSI cross above WMA', color=color.green, linewidth=5, style=plot.style_cross)// plot(crsiCrossAbove50?crsi:na, title='cRSI cross above 50', color=color.black, linewidth=7, style=plot.style_circles)// plot(crsiCrossBelow50?crsi:na, title='cRSI cross below 50', color=color.black, linewidth=7, style=plot.style_circles)// plot(crsiTop?crsi[1]:na, title='cRSI Top', color=color.blue, linewidth=4, style=plot.style_cross, offset=-1)// plot(crsiBottom?crsi[1]:na, title='cRSI Top', color=color.purple, linewidth=4, style=plot.style_cross, offset=-1)//--------------------// Impulse wavesplotStrong = input(title="Plot Strong Impulse Waves (above upper band)", defval=true) and plotCRSIplotWeak = input(title="Plot Weak Impulse Waves (below upper band)", defval=true) and plotCRSIimpWaveSz = size.tinyplotshape(plotStrong and waveStrongImpulse?crsi[1]:na, text="s", title='Strong Impulse', style=shape.labeldown, location=location.absolute, color=color.navy, transp=0, offset=-1, textcolor=color.white, size=impWaveSz)plotshape(plotWeak and waveWeakImpulse?crsi[1]:na, text="w", title='Weak Impulse', style=shape.labeldown, location=location.absolute, color=color.purple, transp=0, offset=-1, textcolor=color.white, size=impWaveSz)//---------------------// Corrective waves// plot(possibleWaveC?crsi[1]:na, title='Possible Wave C', color=color.green, linewidth=6, style=plot.style_circles, offset=-1)// plot(possibleWaveB?crsi[1]:na, title='Possible Wave B', color=color.blue, linewidth=6, style=plot.style_circles, offset=-1)// plot(possibleWaveA?crsi[1]:na, title='Possible Wave A', color=color.purple, linewidth=6, style=plot.style_circles, offset=-1)// plot(waveAB?crsi[1]:na, title='Wave AB', color=color.black, linewidth=5, style=plot.style_cross, offset=-1)// plot(waveABC?crsi[1]:na, title='Wave ABC', color=color.black, linewidth=7, style=plot.style_cross, offset=-1)// plot(waveABCDE?crsi[1]:na, title='Wave ABCDE', color=color.black, linewidth=9, style=plot.style_cross, offset=-1)// plotshape(waveAB?crsi[1]:na, title='Wave AB', style=shape.triangledown, location=location.absolute, color=color.orange, transp=0, offset=-1, text="AB", textcolor=color.orange, size=size.small)// plotshape(waveABC?crsi[1]:na, title='Wave ABC', style=shape.triangleup, location=location.absolute, color=color.blue, transp=0, offset=-1, text="ABC", textcolor=color.blue, size=size.small)// plotshape(waveABCD?crsi[1]:na, title='Wave ABCD', style=shape.triangledown, location=location.absolute, color=color.red, transp=0, offset=-1, text="ABCD", textcolor=color.red, size=size.small)// plotshape(waveABCDE?crsi[1]:na, title='Wave ABCDE', style=shape.triangleup, location=location.absolute, color=color.green, transp=0, offset=-1, text="ABCDE", textcolor=color.green, size=size.small)plotWaves = input(title="Plot Corrective Waves (ABC,ABCDE)", defval=true) and plotCRSIcorWaveSz = size.smallplotshape(plotWaves and waveA?crsi[1]:na, text="A", title='Wave A', style=shape.labelup, location=location.absolute, color=color.blue, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotWaves and waveB?crsi[1]:na, text="B", title='Wave B', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotWaves and waveC?crsi[1]:na, text="C", title='Wave C', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotWaves and waveD?crsi[1]:na, text="D", title='Wave D', style=shape.labeldown, location=location.absolute, color=color.maroon, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotWaves and waveE?crsi[1]:na, text="E", title='Wave E', style=shape.labelup, location=location.absolute, color=color.lime, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotWaves and waveF?crsi[1]:na, text="F", title='Wave F', style=shape.labeldown, location=location.absolute, color=color.fuchsia, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotWaves and waveG?crsi[1]:na, text="G", title='Wave G', style=shape.labelup, location=location.absolute, color=color.aqua, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)//---------------------// PRICE CHANGE BETWEEN IMPULSE AND WAVE A//=================================================================================================================================//=================================================================================================================================// Divergence Indicator Using cRSI//=================================================================================================================================//=================================================================================================================================plotBull = input(title="Plot Bullish (cRSI Higher-Low : Price Lower-Low)", defval=true) and plotCRSIplotHiddenBull = input(title="Plot Hidden Bullish (cRSI Lower-Low : Price Higher-Low)", defval=true) and plotCRSIplotBear = input(title="Plot Bearish (cRSI Lower-High : Price Higher-High", defval=true) and plotCRSIplotHiddenBear = input(title="Plot Hidden Bearish (cRSI Higher-High : Price Lower-High)", defval=true) and plotCRSI//------------------------------------------------------------------------------crsiHighs = waveStrongImpulse or waveWeakImpulsecrsiLows = possibleWaveA or possibleWaveC//------------------------------------------------------------------------------// Regular Bullish --> cRSI makes a Higher-Low, but price makes a Lower-Low// Hidden Bullish --> cRSI makes a Lower-Low, but price makes a Higher-Lowbullish(crsiLows, crsi, price) => foundLow = false crsiHigherLow = false priceHigher = false regularBullish = false hiddenBullish = false if crsiLows[0] == true for i=1 to 50 if crsiLows[i] == true foundLow := true // crsi higher or lower? if crsi[0] > crsi[i] crsiHigherLow := true else crsiHigherLow := false // price higher or lower if price[0] > price[i] priceHigher := true else priceHigher := false // found low, stop looking break else continue if foundLow // Regular Bullish --> cRSI makes a Higher-Low, but price makes a Lower-Low if (crsiHigherLow==true) and (priceHigher==false) regularBullish := true hiddenBullish := false // Hidden Bullish --> cRSI makes a Lower-Low, but price makes a Higher-Low else if (crsiHigherLow==false) and (priceHigher==true) regularBullish := false hiddenBullish := true else regularBullish := false hiddenBullish := false else regularBullish := false hiddenBullish := false else // this is not a low regularBullish := false hiddenBullish := false // return tuple [regularBullish,hiddenBullish] [regularBullish,hiddenBullish] = bullish(crsiLows, crsi, close)plotshape(plotBull and regularBullish?crsi[1]-12:na, text="Bull", title='Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotHiddenBull and hiddenBullish?crsi[1]-12:na, text="H Bull", title='Hidden Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=20, offset=-1, textcolor=color.white, size=corWaveSz)//------------------------------------------------------------------------------// Regular Bearish --> cRSI makes a Lower-High, but price makes a Higher-High// Hidden Bearish --> cRSI makes a Higher-High, but price makes a Lower-Highbearish(crsiHighs, crsi, price) => foundHigh = false crsiHigherHigh = false priceHigher = false regularBearish = false hiddenBearish = false if crsiHighs[0] == true for i=1 to 50 if crsiHighs[i] == true foundHigh := true // crsi higher or lower? if crsi[0] > crsi[i] crsiHigherHigh := true else crsiHigherHigh := false // price higher or lower if price[0] > price[i] priceHigher := true else priceHigher := false // found high, stop looking break else continue if foundHigh // Regular Bearish --> cRSI makes a Lower-High, but price makes a Higher-High if (crsiHigherHigh==false) and (priceHigher==true) regularBearish := true hiddenBearish := false // Hidden Bearish --> cRSI makes a Higher-High, but price makes a Lower-High else if (crsiHigherHigh==true) and (priceHigher==false) regularBearish := false hiddenBearish := true else regularBearish := false hiddenBearish := false else regularBearish := false hiddenBearish := false else // this is not a low regularBearish := false hiddenBearish := false // return tuple [regularBearish,hiddenBearish] [regularBearish,hiddenBearish] = bearish(crsiHighs, crsi, close)plotshape(plotBear and regularBearish?crsi[1]+10:na, text="Bear", title='Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)plotshape(plotHiddenBear and hiddenBearish?crsi[1]+10:na, text="H Bear", title='Hidden Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=20, offset=-1, textcolor=color.white, size=corWaveSz)//==================================================================================================================================================================================================================================================================//==================================================================================================================================================================================================================================================================//==================================================================================================================================================================================================================================================================// Buy/Sell Strategy//==================================================================================================================================================================================================================================================================//==================================================================================================================================================================================================================================================================//==================================================================================================================================================================================================================================================================// Remove duplicate buy/sells if one was already executed recentlyfilterLookback = 5// normalize a value in a range between min and maxnormalize(val, valMin, valMax) => valNorm = val valNorm := valNorm < valMin ? valMin : valNorm valNorm := valNorm > valMax ? valMax : valNorm valNorm := (valNorm-valMin) / (valMax-valMin)recentWave(wave, lookback) => ret = false found = false for i=0 to lookback if wave[i] == true found := true break if found ret := true else ret := false//-----------------------------------------------------------------------------// Levels for upper band - HighcrsiHighband_extremeHighLevel = 90crsiHighband_highLevel = 70crsiHighband_highWeight = normalize(crsiHighband, crsiHighband_highLevel, crsiHighband_extremeHighLevel)// Levels for upper band - LowcrsiHighband_extremeLowLevel = 45crsiHighband_lowLevel = 55crsiHighband_lowWeight = 1.0 - normalize(crsiHighband, crsiHighband_extremeLowLevel, crsiHighband_lowLevel)// plot(crsiHighband_highWeight,color=color.blue)// plot(crsiHighband_lowWeight,color=color.red)//-----------------------------------------------------------------------------// // Levels for lower band - HighcrsiLowband_extremeHighLevel = 80crsiLowband_highLevel = 60crsiLowband_higheight = normalize(crsiLowband, crsiLowband_highLevel, crsiLowband_extremeHighLevel)// Levels for lower band - LowcrsiLowband_extremeLowLevel = 20crsiLowband_lowLevel = 45crsiLowband_lowWeight = 1.0 - normalize(crsiLowband, crsiLowband_extremeLowLevel, crsiLowband_lowLevel)// plot(crsiLowband_highWeight,color=color.blue)// plot(crsiLowband_lowWeight,color=color.red)//--------------------------------------------------------------------------------------------// DETERMINE IF NEW TRADES ARE PERMITTED//--------------------------------------------------------------------------------------------newTrades = falseif (useSessions) if ( hour == sess1_startHour and minute >= sess1_startMinute ) newTrades := true else if ( hour > sess1_startHour and hour < sess1_stopHour ) newTrades := true else if ( hour == sess1_stopHour and minute < sess1_stopMinute ) newTrades := true else if ( hour == sess2_startHour and minute >= sess2_startMinute ) newTrades := true else if ( hour > sess2_startHour and hour < sess2_stopHour ) newTrades := true else if ( hour == sess2_stopHour and minute < sess2_stopMinute ) newTrades := true else newTrades := falseelse newTrades := true//--------------------------------------------------------------------------------------------// SELL//--------------------------------------------------------------------------------------------maxSellOrderSize = maxOrderSizecrsiHighband_above_crsiHighband_highLevel = crsiHighband > crsiHighband_highLevel ? true : falseSell1 = waveStrongImpulseSell2 = crsiAboveHighband and crsiFalling ? true : false // Above high band and now fallingSell3 = crsiAboveHighband[1] and crsiFalling ? true : false // 1x previous was above high band and now falling (sometimes it can be off by a bar)Sell4 = crsiAboveHighband[2] and crsiFalling ? true : false // 2x previous was above high band and now falling (sometimes it can be off by a bar)//Sell = Sell1 //and crsiHighband_above_crsiHighband_highLevel// Sell = Sell1 //and crsiHighband_above_crsiHighband_highLevel// Sell = (Sell1 or Sell2) //and crsiHighband_above_crsiHighband_highLevel// Sell = (Sell1 or Sell2 or Sell3) //and crsiHighband_above_crsiHighband_highLevelSell = (Sell1 or Sell2 or Sell3 or Sell4) and crsiHighband_above_crsiHighband_highLevelSell := filterSignal(Sell, filterLookback)// Base sell size on how high the Highband issellSize = crsiHighband_highWeight *maxSellOrderSize // When in doubt, DON'T SELL! Stonks only go up ;) // extreme cRSIsellSize := crsi > crsiHighband_extremeHighLevel ? 1.5*maxSellOrderSize : sellSize// if the sell size is small, just make min sellsellSize := sellSize < maxSellOrderSize/3 ? 0 : sellSizesellSize := round(sellSize)if (Sell and newTrades) strategy.order("Sell", false, sellSize)//--------------------------------------------------------------------------------------------// BUY - Price can continue to fall even when cRSI is rising!!!//--------------------------------------------------------------------------------------------maxBuyOrderSize = maxOrderSize// Wait until it crosses back above WMA so it is clear that motive wave is clear.// Buying at the bottom is really hard because RSI can start to rise yet price will continue to fallBuy1 = bullStart// Using waves can help do a better job timing the bottom, but big corrections can go much deeper than just Wave C (Zig Zag)Buy2 = waveA and regularBullishBuy3 = waveC and regularBullishBuy4 = waveE and (topBottomLookback == 3) // usullay max is a wave E with topBottomLookback == 3Buy5 = waveG and (topBottomLookback == 2) // can see a G wave when topBottomLookback == 2Buy = Buy1 or Buy2 or Buy3 or Buy4 or Buy5Buy := filterSignal(Buy, filterLookback)// Base buy size on how low the Lowband isbuySize = crsiLowband_lowWeight*maxBuyOrderSize// buySize := buySize < 1 ? 1 : buySize // When in doubt, BUY! Stonks only go up ;)// Look for recent wave endings that can increase our guess of buying at a lowrecentWaveC = recentWave(waveC, 10)recentWaveE = recentWave(waveE, 10)recentWaveG = recentWave(waveG, 10)// buySize := recentWaveE ? 1.5*maxBuyOrderSize : buySize// buySize := recentWaveG ? 1.5*maxBuyOrderSize : buySizebuySize := recentWaveE ? maxBuyOrderSize : buySizebuySize := recentWaveG ? maxBuyOrderSize : buySize// if the buy size is small, just make min buybuySize := buySize < maxSellOrderSize/3 ? 0 : buySizebuySize := round(buySize)if (Buy and newTrades) strategy.order("Buy", true, buySize)// Close open position at end of Session 1, if enabledif (sess1_closeAll and hour == sess1_stopHour and minute >= sess1_stopMinute ) strategy.close_all() // Close open position at end of Session 2, if enabledif (sess2_closeAll and hour == sess2_stopHour and minute >= sess2_stopMinute ) strategy.close_all()