top of page

Unleashing the Power of Coded Trading Strategies: A Deep Dive into Two RSI Approaches

Writer: Kirtiman Gupta
Kirtiman Gupta
Mar 2, 2025
6 min read

In the electrifying arena of cryptocurrency trading, where fortunes can pivot in an instant, coded strategies offer a beacon of precision and discipline. This article explores two Relative Strength Index (RSI) trading strategies with data from backtesting it on Bitcoin ($BTC), both crafted in Pine Script version 5 for TradingView, to uncover how subtle differences in strategy can lead to vastly different outcomes. 

My thesis: While both strategies harness the RSI to navigate Bitcoin’s wild price swings, their trade management philosophies—long-only versus long-short—produce distinct performance profiles, empowering traders to align their approach with market realities and personal goals. 

By dissecting their mechanics, calculating performance metrics from a detailed trade list for Code 1, and inferring Code 2’s results from its logic and visual cues, we deliver an unbiased, compelling analysis that bridges code and real-world impact.

Codes Used:

Code 1

strategy("Bitcoin RSI Strategy", overlay=true, shorttitle="BTC RSI Strat")

// Input parameters for customization
rsiPeriod = input.int(14, title="RSI Period", minval=1)
buyLower = input.float(45, title="Buy Lower RSI", minval=0, maxval=100)
buyUpper = input.float(55, title="Buy Upper RSI", minval=0, maxval=100)
sellLevel = input.float(72, title="Sell RSI Level", minval=0, maxval=100)

// Calculate RSI
rsi = ta.rsi(close, rsiPeriod)

// Define buy and sell conditions
buyCondition = rsi >= buyLower and rsi <= buyUpper
sellCondition = ta.crossunder(rsi, sellLevel)

// Execute trades
if (buyCondition)
    strategy.entry("Long", strategy.long)
if (sellCondition)
    strategy.close("Long")

// Visualize RSI and levels
plot(rsi, title="RSI", color=color.blue, linewidth=2)
hline(buyLower, "Buy Lower (45)", color=color.green, linestyle=hline.style_dashed)
hline(buyUpper, "Buy Upper (55)", color=color.green, linestyle=hline.style_dashed)
hline(sellLevel, "Sell Level (72)", color=color.red, linestyle=hline.style_dashed)"

Code 2

strategy("Bitcoin RSI Strategy", overlay=true, shorttitle="BTC RSI Strat")

// Input parameters for customization
rsiPeriod = input.int(14, title="RSI Period", minval=1)
buyLower = input.float(45, title="Buy Lower RSI", minval=0, maxval=100)
buyUpper = input.float(55, title="Buy Upper RSI", minval=0, maxval=100)
sellLevel = input.float(72, title="Sell RSI Level", minval=0, maxval=100)

// Calculate RSI
rsi = ta.rsi(close, rsiPeriod)

// Define conditions
buyCondition = rsi >= buyLower and rsi <= buyUpper
sellCondition = ta.crossunder(rsi, sellLevel)

// When sell condition is met while long, close the long and enter a short position.
if (sellCondition and strategy.position_size > 0)
    strategy.close("Long")
    strategy.entry("Short", strategy.short)

// When buy condition is met:
// - If in a short position, close it first.
// - If no position exists, then enter a long position.
if (buyCondition)
    if (strategy.position_size < 0)
        strategy.close("Short")
    if (strategy.position_size == 0)
        strategy.entry("Long", strategy.long)

// Visualize RSI and levels
plot(rsi, title="RSI", color=color.blue, linewidth=2)
hline(buyLower, "Buy Lower (45)", color=color.green, linestyle=hline.style_dashed)
hline(buyUpper, "Buy Upper (55)", color=color.green, linestyle=hline.style_dashed)
hline(sellLevel, "Sell Level (72)", color=color.red, linestyle=hline.style_dashed)"

Understanding the Strategies: Code Under the Hood

Both strategies leverage the RSI—a momentum oscillator gauging price movement intensity over a 14-period default—to trigger trades. They share identical thresholds: a buy range of RSI 45–55 and a sell level at 72. Yet, their execution diverges, reflecting unique trading philosophies.

Code 1: The Long-Only Contender This strategy is a purist’s play, betting solely on Bitcoin’s upside. Here’s how it operates:


  • Buy Logic: Enters a long position when RSI is between 45 and 55


rsi >= buyLower and rsi <= buyUpper

targeting neutral or slightly oversold conditions that hint at an impending rally.


  • Sell Logic: Closes the long when RSI crosses under 72 


ta.crossunder(rsi, sellLevel)

exiting after a potentially overbought surge.


  • Visualization: Overlays the RSI (blue line) on the price chart, with green dashed lines at 45 and 55 and a red dashed line at 72, spotlighting trade zones.


Code 1 is a one-way street—long entries only—designed to ride Bitcoin’s upward waves while sidestepping short-side risks. It’s simple, focused, and bets on the crypto’s historical bullish bias.

Code 2: The Long-Short Maverick This strategy ups the ante, embracing both sides of the market. Its logic is more intricate:


  • Sell-to-Short Transition: When RSI crosses under 72 and a long position is active, it closes the long and flips to a short 


strategy.close("Long")
strategy.entry("Short", strategy.short)

aiming to profit from downturns.


  • Buy Dynamics: When RSI hits 45–55, it closes any short position (strategy.close("Short") if strategy.position_size < 0) or enters a long if neutral


 if (strategy.position_size == 0)
        strategy.entry("Long", strategy.long)

  • Visualization: Mirrors Code 1’s RSI plotting, but expect more action on the chart with both long and short signals.


Code 2 is a shape-shifter, adapting to rising and falling markets. It’s a high-wire act, balancing increased opportunities against amplified risks, especially in Bitcoin’s volatile domain.


Performance Metrics: Crunching the Numbers for Code 1

List of trades executed:

Trade history table showing investment entries and exits from 2012 to 2024, highlighting profit and loss outcomes in USD.
Trade history table showing investment entries and exits from 2012 to 2024, highlighting profit and loss outcomes in USD.

The trade list for Code 1, spanning June 2012 to December 2024, provides a goldmine of data across 10 trades, each with entry and exit rows. Let’s calculate key metrics to anchor our comparison:


  1. Total Number of Trades: 10 (each trade has an entry and exit, but we count completed trades, not actions).

  2. Total Profit/Loss: Trade 1: +3,000 USD Trade 2: +524,000 USD Trade 3: -301,000 USD Trade 4: +261,000 USD Trade 5: +341,000 USD Trade 6: +995,000 USD Trade 7: -61,000 USD Trade 8: +37,202,000 USD Trade 9: -475,000 USD Trade 10: +39,248,000 USD Total: 3,000 + 524,000 - 301,000 + 261,000 + 341,000 + 995,000 - 61,000 + 37,202,000 - 475,000 + 39,248,000 = 77,717,000 USD

  3. Win Rate: 7 winning trades (positive P/L: Trades 1, 2, 4, 5, 6, 8, 10) out of 10 = 70%.

  4. Average Profit/Loss per Trade: 77,717,000 / 10 = 7,771,700 USD.

  5. Maximum Drawdown: The table lists 6,275,000 USD for Trade 10. Relative to the final exit balance of 52,512,000 USD, that’s 11.95%. (Note: True drawdown requires equity curve analysis, but we use the provided figure.)

  6. Sharpe Ratio (Simplified): Average % profit/loss = 90.117% (sum of % P/L divided by 10). Standard deviation ≈ 165.69% (calculated from variance). Sharpe = 90.117 / 165.69 ≈ 0.544 (assuming a 0% risk-free rate).


Code 1’s numbers are staggering: a $77.7 million profit over 12 years, a 70% win rate, and an average trade profit of $7.77 million. Yet, the 11.95% drawdown and modest Sharpe ratio hint at volatility and risk beneath the surface.


Performance Metrics for Code 2

The data presents an overview of trading performance rom the strategy used in code 2.
The data presents an overview of trading performance rom the strategy used in code 2.

Inferring Code 2’s Performance: Logic Meets Intuition

Without a trade list for Code 2, we lean on its code, the second image’s description, and Bitcoin’s market tendencies (upward bias with sharp corrections) to estimate its performance:


  • Trade Frequency: The long-short mechanic suggests 25–30 trades over the same period, as short entries follow long exits, doubling activity in volatile swings.

  • Profitability: Bitcoin’s long-term uptrend likely punishes shorts during bull runs, reducing total profit (perhaps $50–60 million) compared to Code 1’s $77.7 million. However, shorts could cushion bearish dips.

  • Win Rate: More trades may dilute the win rate to 50–60%, as short positions face headwinds in a rising market.

  • Average P&L: Lower at $2–3 million per trade, reflecting smaller gains or losses per move.

  • Drawdown: Potentially lower (8–10%) due to short-side profits offsetting long-side losses in downturns.

  • Sharpe Ratio: Similar or slightly higher (0.6–0.7), as diversification across market directions might smooth returns.


The results from Code 2 shows more signals, confirming higher activity. Code 2 trades shorter cycles, capturing both rallies and dips, but its short positions have risk of bleeding during Bitcoin’s relentless climbs in the future.


Head-to-Head: Code 1 Dominates

Let’s analyze:


  • Total Profit: Code 1: $77.7 million Code 2: $58,864 (estimated, likely higher with scaling, but still dwarfed)

  • Win Rate: Code 1: 70% (long-only) Code 2: 47.37% (tanked by shorts)

  • Average Profit: Code 1: $7.77 million per trade Code 2: $3,098 per trade

  • Risk: Code 1: Losses capped at corrections (e.g., -10.25% max). Code 2: Shorts bleed hard (e.g., -1,012.50%).


Code 1’s percentage gains—like 588.76% and 461.56%—blow Code 2’s 80.20% long average out of the water. Short trades drag Code 2 into mediocrity, while Code 1 soars on BTC’s bullish wings.

Market Context: From 2012–2024, Bitcoin soared from $5,000 to $95,000, favoring Code 1’s long-only stance. Code 2’s shorts might shine in shorter bear phases (e.g., 2022), but not enough to outpace Code 1’s gains over this bull-dominated stretch.


Conclusion: Your Strategy, Your Edge

For traders, the choice is personal. Bullish optimists should back Code 1, harnessing its simplicity and explosive upside. Risk-savvy pragmatists might tweak Code 2, refining short triggers to tame losses. Better yet, backtest both—adjust RSI levels, test shorter periods, or blend their logic—to forge a hybrid that fits your style. In Bitcoin’s wild frontier, coded strategies aren’t just tools; they’re your compass. Whether you chase Code 1’s windfalls or Code 2’s versatility, success lies in mastering the code, reading the market, and defining your own victory.

 
 
 

Comments


bottom of page