A Conversion Challenge...

netarchitech

Well-known member
pts-Scripts-for-Trading-and-Investing-Trading-View.png


Link: https://www.tradingview.com/script/jja8TYjc-RedK-Auto-Stepping-Ladder-Trader/

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

//@version=5
indicator(title='RedK Auto-Step Ladder Trader', shorttitle='Ladder_Trader v2.0', overlay=true, timeframe='', timeframe_gaps=false)
// ===========================================================================================================
//                              Functions Section
// ===========================================================================================================
// step function (version 2)
// this function picks a step size based on the price range
// it will then scale the step value up/down based on TF changes
// change and personalize these ranges as needed
f_step(x) =>
    initstep =
      x < 2     ? 0.01  : x < 5     ? 0.02  :
      x < 10    ? 0.10  : x < 30    ? 0.20  :
      x < 100   ? 1.00  : x < 300   ? 2.00  :
      x < 500   ? 5.00  : x < 1000  ? 10.0  :
      x < 2000  ? 20.0  : x < 5000  ? 50.0  :
      x < 10000 ? 100.0 : x < 20000 ? 200.0 :
      x < 50000 ? 500.  : 1000.0

    //Adjust step value up or down for different timeframes
    adjstep = timeframe.isweekly ? initstep * 2 :
      timeframe.ismonthly ? initstep * 5 :
      timeframe.isintraday and timeframe.multiplier > 60 ? initstep / 2 :
      timeframe.isintraday and timeframe.multiplier <= 60 ? initstep / 5 :
      initstep

    // need to replace the 4's in weekly and minutes with 5's
    // cause we want to track the mental increments of traders - round values are more effective
    _incstr = str.tostring(adjstep)
    _newstr = str.replace_all(_incstr, '4', '5')
    str.tonumber(_newstr)
// =============================================================================
// the rounding function chooses the type of step rounding to apply
// we can use either a regular rounding up/down to nearest step (ex: for step size = 10, a value of 17 becomes 20 and a value of 13 becomes 10)
// or an integer type, which considers only the "fully completed" step level (ex: for step size = 10, both values of 13 and 17 become 10)
f_rounding(_value, _step, _option) =>
    _option == 'Round up/down' ? math.round(_value / _step) * _step : int(_value / _step) * _step

//==============================================================================  
// Compund Ratio Moving Average function
f_CoraWave(_source, _length, _s) =>
    numerator   = 0.0, denom = 0.0
    c_weight    = 0.0, r_multi = 2.0
    Start_Wt    = 0.01     // Start Weight & r_multi are set to basic values here.
    End_Wt      = _length    // use length as initial End Weight to calculate base "r"
   
    r = math.pow(End_Wt / Start_Wt, 1 / (_length - 1)) - 1
    base = 1 + r * r_multi

    for i = 0 to _length - 1 by 1
        c_weight    := Start_Wt * math.pow(base, _length - i)
        numerator   += _source[i] * c_weight
        denom       += c_weight
        denom

    cora_raw    = numerator / denom
    cora_wave   = ta.wma(cora_raw, _s)
    cora_wave
// =========================================================================================================== //                              inputs
// ===========================================================================================================
avgtype     = input.string  (title='Ladder Line Type', defval='Donchian Midline', options=['CoRa_Wave', 'Donchian Midline'],    inline='MA Type')
length      = input.int     (title='  Length',              defval=10, minval=1,                                                inline='MA Type')
price       = input.source  (title='(CoRa Only) Source',    defval=hlc3,                                                    inline='Cora Only')
smooth      = input.int     (title='Smoothing',             defval=3, minval=1,                                             inline='Cora Only')



s_use       = input.bool    (title='',                      defval=true,                                                    inline='Step',  group='Step')
s_size      = input.float   (title='Step        Size [0 = Auto]', defval=0.0, minval=0,                                     inline='Step',  group='Step')
r_option    = input.string  (title='Step Calculation', defval='Round up/down', options=['Round up/down', 'Whole Step'],                     group='Step')

g_source    = input.source  (title='Source', defval=hlc3,                                                       inline='Signal',  group='Signal')
g_length    = input.int     (title='Length', defval=5, minval=2,                                                inline='Signal',  group='Signal')
g_smooth    = input.int     (title='Smooth', defval=3, minval=1,                                                inline='Signal',  group='Signal')


tr_show     = input.bool    (title='', defval=true, inline='ATR Envelope', group='Envelopes')
tr_len      = input.int     (title='ATR Envelope   Length', defval=20, minval=0, step=1,                        inline='ATR Envelope', group='Envelopes')
tr_multi    = input.float   (title='Multi', defval=1.25, minval=0, step=0.25,                                   inline='ATR Envelope', group='Envelopes')

e_show      = input.bool    (title='', defval=false,                                                            inline='Pct Envelope', group='Envelopes')
e_pct       = input.float   (title='Pct Envelope           %', defval=2.0, minval=0, step=0.25,                 inline='Pct Envelope', group='Envelopes')

// ===========================================================================================================
//                          Calculation
// ===========================================================================================================


// Ladder Line calculation
ladder      = avgtype == 'CoRa_Wave' ? f_CoraWave(price, length, smooth) : (ta.highest(length) + ta.lowest(length)) / 2

//Apply Stepping to Ladder Line -- added condition that base price needs to be > 0.01, as micro prices will break this part
//also removed cases with div/0
// -- may come back and fine tune the auto-step algo for micro prices
s_apply     = s_use and price > 0.01

s           = s_apply ? s_size == 0.0 ? f_step(price) : s_size : 0.0
ladder_s    = s_apply and s > 0.0 ? f_rounding(ladder, s, r_option) : ladder


// Signal Calculation  -- signal line is a CoRa_Wave with (default) fast speed and relatively large smoothness (5 & 3) - as a proxy for price

Signal      = f_CoraWave(g_source, g_length, g_smooth)

// Calculate Envelopes
e_upper     = ladder_s * (1 + e_pct / 100)
e_lower     = ladder_s * (1 - e_pct / 100)

// while the pct envelope is a static absolute value, the ATR will change with each bar
// below we use a new ATR value only when the channel step changes - non-stepping/unrestricted ATR is still avaialble by disabling the stepping option

ATR         = ta.atr(tr_len) * tr_multi
ATR_us      = ATR
ATR_ls      = ATR
ATR_us      := ta.change(ladder_s) != 0 ? ATR : ATR_us[1]
ATR_ls      := ta.change(ladder_s) != 0 ? ATR : ATR_ls[1]
ATR_upper   = ladder_s + ATR_us
ATR_lower   = ladder_s - ATR_ls


// ===========================================================================================================
//                              Plot
// ===========================================================================================================

c_up    = color.new(color.aqua, 0)
c_dn    = color.new(color.orange, 0)
c_lad   = Signal >= ladder_s ? c_up : c_dn

c_env   = color.new(color.silver, 50)
c_ATR   = color.new(color.yellow, 50)

//v2.0 - Display the step size on the indicator status line & in the Data Window
plotchar(s, title = "Step Size", char = "", location=location.top, color=color.white)

//Signal plot is hidden by default - recommend to expose only when tweaking settings
plot(Signal, title='Signal', color=color.white, display=display.none)

PStyle = plot.style_line
plot_ladder = plot(ladder_s, title='Ladder Line', style=PStyle, color=c_lad, linewidth=3)


//PStyle1 = plot.style_stepline
PStyle1 = plot.style_line  //change default plot style to regular line for consistency

plot(tr_show ? ATR_upper : na, 'Upper ATR Envelope', style=PStyle1, color=c_ATR)
plot(tr_show ? ATR_lower : na, 'Lower ATR Envelope', style=PStyle1, color=c_ATR)

plot(e_show ? e_upper : na, 'Upper Pct Envelope', style=PStyle1, color=c_env)
plot(e_show ? e_lower : na, 'Lower Pct Envelope', style=PStyle1, color=c_env)

// ===========================================================================================================
// v2.0 - Enable alerts for direction change up or down or either
// ===========================================================================================================

// alertcondition() supports variable resolution
AlertUp = ta.crossover(Signal, ladder_s)
AlertDn = ta.crossunder(Signal, ladder_s)

alertcondition(AlertUp,             "Price Swing Up",      "Ladder: Price Swing Up Detected!")                // explicit swing up
alertcondition(AlertDn,             "Price Swing Down",    "Ladder: Price Swing Down Detected!")              // explicit swing down
alertcondition(AlertUp or AlertDn,  "Price Swing Up/Down", "Ladder: Price Swing Up/Down Detected!")           // Any swing

Additional Notes:

The RedK Auto-Stepping Ladder Trader is an experimental tool to help identify trade entry and exits for various types of trades (Trend / Momentum / Breakout and Swing trades)

The underlying concept here is loosely similar to the SMAC script - in case you'd like to read some of the "script-specific" write-up. I even borrowed some of the SMAC code, but upgraded the script to Pine v5 while working. So i won't repeat write-up here on how the script works - and we'll get right into how to use in trading

How to use / trade the Ladder Trader:
-------------------------------------------------
The idea is to set the auto-stepping ladder to a higher timeframe, the "ladder view" helps simplify the price action to show a clear direction, then use the lower timeframe to find best entries (close or at the ladder line) and exits (on the ATR as TP target)

  • Entries should be as close to the ladder line as possible - a trader may decide to have a small margin above or below the ladder line where they set entry limit order
  • note that when stepping is enabled, the auto-stepping algo will choose the step value based on the underlying price range and the selected timeframe to move with common trader "mental values" where traders will usually gravitate
  • exits can be set using the optional ATR or Pct channels - by default, there's an ATR channel (golden color) for that purpose

Possible usage scenarios of the Ladder Trader:
--------------------------------------------------------------
- Trend / long(er) term: enter position once the ladder line switches to the color corresponding to my desired direction (example: blue for long), and hold all the way until the color changes

- Swing: Take only trades in the direction of the ladder (long with blue, short with orange) - enter at the ladder line value, set TP at the desired ATR, repeat as long as the direction holds

- Feel free to experiment and share back other uses you find. There are so many settings and tweaks provided for flexibility - the downside is this adds a certain level of complexity - however, i hope this will be a valuable tool to add to your trading.

Few Notes:
-----------------------
  • The Auto-stepping algo is a bit improved to be more FOREX and Crypto-friendly - i do not trade these instruments myself, but will continue to improve the auto-stepping technique in upcoming updates
  • the signal line (hidden by default, and is what causes the ladder to change color) is based on my Compound Ratio Moving Average - since it's the moving average i found to provide best combination of speed and smoothness. It is used as a proxy to the price, to signal when the price is above or below the ladder level - while removing some of the whipsaws if we use the price value directly.

  • Broader analysis of price action should still be made using other indicators - and possibly other chart setups - we shouldn't rely on the Ladder Trader signal only - Check for overall momentum, volume movement and market sentiment before using the Ladder Trader
  • Also test your settings in PaperMoney - i noticed that different instruments may need different settings (for Ladder Type, Length, Rounding Technique, ATR multiplier..etc) for optimal setup that shows best signals.. Get very familiar with the Ladder Trader and it should hopefully become more helpful to you as a trading tool.
 
Last edited:
Realizing this challenge may be beyond the abilities of ThinkScript, I remain hopeful that one or more of the talented 'scripters on this forum might be able to successfully conquer this challenge...Thanks in advance to any 'scripter out there willing to take the time necessary to contemplate converting this script... :cool:
 
I would love to see someone be able to translate. Short of the full translation of the above, RedK also posts a similar code portion which is also interesting especially given the images and narrative on this page - https://www.tradingview.com/script/NgLjvBWA-RedK-Compound-Ratio-Moving-Average-CoRa-Wave/. I wonder if anyone far more talented than me, could begin with just the translation of the CoRa moving average and/or the open and close version he posted an interesting screenshot. This appears to be a worth project given the comparisons to other moving averages, nd it also might facilitate the work toward the more challenging one above.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
336 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top