It looks like you've provided a Pine Script strategy code for TradingView, aiming to implement a HARSI Strategy with several confirmations and risk management features. I'll help you by reviewing your code, pointing out any issues, and suggesting improvements to ensure it works as intended.
1. General Overview
Your strategy includes:
- HARSI Heikin Ashi candles calculations for trend indication.
- RSI and Stochastic RSI for momentum analysis.
- Confirmation indicators like EMA, Volume Oscillator, ADX, and Vortex Indicator.
- Risk management with Take Profit (TP), Stop Loss (SL), and Trailing Stop Loss (TSL).
2. Issues and Corrections
a. Multiple strategy.exit Calls
In Pine Script, when using strategy.exit multiple times for the same entry, you need to manage the order and exit IDs properly.
Issue:
You're using different exit IDs ("Take Profit", "Stop Loss", "Trailing Stop") but the same from_entry ("Long"). This can cause conflicts because strategy.exit will cancel any existing exit orders for the same from_entry when a new one is placed.
Correction:
Use the same exit ID in all your strategy.exit calls or manage exit orders within one strategy.exit call by setting both limit and stop parameters.
Option 1: Single strategy.exit Call
// Combine TP and SL in one exit order
strategy.exit("Exit", from_entry="Long", limit=tp_enabled ? tp_price : na, stop=sl_enabled ? sl_price : na)
Option 2: Ensure Only One Exit Order is Active
Before placing a new exit order, cancel any existing ones.
if (tp_enabled or sl_enabled)
strategy.cancel("Exit")
strategy.exit("Exit", from_entry="Long", limit=tp_enabled ? tp_price : na, stop=sl_enabled ? sl_price : na)
b. Trailing Stop Loss Implementation
Issue:
You're using both trail_offset and trail_points in your strategy.exit call, which is redundant. Also, using strategy.exit inside an if condition that depends on price crossing a level might not arm the trailing stop as intended.
Correction:
- Use either
trail_points (in ticks) or trail_offset (in price units), not both.
- Set up the trailing stop loss in a way that TradingView can manage it without needing to check for price crossing a trigger level.
Revised Trailing Stop Loss Code:
if (tsl_enabled)
// Convert percentage to price difference
trail_amount = strategy.position_avg_price * (tsl_percent / 100)
strategy.exit("Trailing Stop", from_entry="Long", trail_stop=trail_amount)
Note: Unfortunately, Pine Script doesn't support arming a trailing stop loss after a certain profit level is reached directly. To implement an armed trailing stop loss, you need to simulate it using custom code, which can be complex.
c. Potential Repainting with calc_on_every_tick=true
Issue:
Using calc_on_every_tick=true can cause repainting issues, especially when using close in conditions, as the close price updates on every tick during a live bar.
Correction:
- Consider setting
calc_on_every_tick=false to only calculate on bar close, reducing repainting risks.
- If you need real-time calculations, ensure your logic accounts for intra-bar price changes appropriately.
d. Variable Shadowing and Initialization
Issue:
In your f_rsiHeikinAshi function, you have:
var float _open = na
- The use of
var inside a function can lead to unexpected behavior, as var variables are initialized only once and retain their value across function calls.
Correction:
- Remove the
var keyword inside the function to ensure _open is re-initialized properly on each call.
float _open = na
e. Unused Inputs and Variables
Issue:
- The input
i_mode is defined but not used.
- The variable
i_ribbon is declared but not utilized in your code.
Correction:
- Remove or implement the logic for these inputs to avoid confusion.
3. Suggestions for Improvement
a. Optimize RSI and Stochastic RSI Calculations
- Since you're calculating
RSI_z = RSI - 50 and plotting it as a histogram, ensure that this aligns with your strategy's logic.
- If
i_mode was intended to switch between smoothed and regular RSI, implement the smoothing logic.
b. Enhance Confirmation Indicator Conditions
- For EMA confirmation, consider checking the relationship between price and EMA more robustly, possibly incorporating a buffer.
ema_confirmation = ema_enabled ? close > ema_val : true
c. Adjust ADX Confirmation Logic
- It's common to consider the ADX trend strength along with the direction:
adx_confirmation = adx_enabled ? (adx_val > adx_threshold and diplus_val > diminus_val) : true
d. Implement Stochastic Ribbon Visualization
- Since you have
i_ribbon as an input, you might want to create a color ribbon to show the overbought and oversold regions indicated by Stochastic RSI.
if i_showStoch and i_ribbon
ribbon_color = StochK_smoothed > StochD ? color.green : color.red
plot(StochK_smoothed, "StochK", color=ribbon_color, linewidth=2)
plot(StochD, "StochD", color=color.gray, linewidth=1)
e. Improve Risk Management Calculations
- Ensure that your TP and SL levels are calculated relative to the position price, accounting for long and short positions if you plan to extend the strategy.
4. Cleaned and Corrected Code Sample
Here's a corrected version of the critical parts of your code:
// Trailing Stop Loss Exit
if (tsl_enabled)
// Convert percentage to price difference
trail_amount = strategy.position_avg_price * (tsl_percent / 100)
strategy.exit("Trailing Stop", from_entry="Long", trail_stop=trail_amount)
// Combine TP and SL in one exit order
if (tp_enabled or sl_enabled)
strategy.exit("Exit", from_entry="Long", limit=tp_enabled ? tp_price : na, stop=sl_enabled ? sl_price : na)
// Remove var keyword inside function
f_rsiHeikinAshi(_length) =>
_closeRSI = rsi(close, _length) - 50
_openRSI = nz(_closeRSI[1], _closeRSI)
_highRSI_raw = rsi(high, _length) - 50
_lowRSI_raw = rsi(low, _length) - 50
_highRSI = math.max(_highRSI_raw, _lowRSI_raw)
_lowRSI = math.min(_highRSI_raw, _lowRSI_raw)
_close = (_openRSI + _highRSI + _lowRSI + _closeRSI) / 4
float _open = na
_open := na(_open[1]) ? (_openRSI + _closeRSI) / 2 : ((_open[1] * i_smoothing) + _closeRSI) / (i_smoothing + 1)
_high = math.max(_highRSI, math.max(_open, _close))
_low = math.min(_lowRSI, math.min(_open, _close))
[_open, _high, _low, _close]
5. Final Notes
- Testing: After making these corrections, thoroughly test your strategy using TradingView's Strategy Tester to ensure it behaves as expected.
- Parameters Adjustment: Experiment with different parameter values to optimize performance.
- Documentation: Add comments to your code to explain your logic, making it easier for others (and yourself) to understand in the future.
- Stay Updated: Pine Script evolves over time. Make sure to consult the latest Pine Script Reference Manual for any updates or changes.
I hope this helps you refine your strategy code. If you have any specific questions or need further assistance with any part of the script, feel free to ask!