Example output
Sure! Here's a comprehensive Pine Script for a custom trading strategy using the Relative Strength Index (RSI) as the main signal for Bitcoin trading, complete with risk management, backtesting, and visualization.
```pinescript
//@version=5
strategy("Bitcoin RSI Strategy", overlay=true)
// === INPUT PARAMETERS ===
// Configurable RSI settings
rsi_length = input.int(14, title="RSI Length")
rsi_overbought = input.int(70, title="RSI Overbought Level", minval=50, maxval=100)
rsi_oversold = input.int(30, title="RSI Oversold Level", minval=0, maxval=50)
// Timeframe configuration
timeframe = input.timeframe("1D", title="Timeframe")
// Stop-loss and Take-profit
use_stop_loss = input.bool(true, title="Use Stop-Loss")
stop_loss_perc = input.float(1.5, title="Stop Loss (%)", minval=0.1)
use_take_profit = input.bool(true, title="Use Take-Profit")
take_profit_perc = input.float(3.0, title="Take Profit (%)", minval=0.1)
// Backtesting period
start_date = input.time(timestamp("2023-01-01 00:00"), title="Backtest Start Date")
end_date = input.time(timestamp("2024-01-01 00:00"), title="Backtest End Date")
// === RSI CALCULATION ===
rsi = ta.rsi(close, rsi_length)
// === TRADING LOGIC ===
// Conditions for buy: RSI crossing below the oversold level
buy_condition = ta.crossover(rsi, rsi_oversold)
// Conditions for sell: RSI crossing above the overbought level
sell_condition = ta.crossunder(rsi, rsi_overbought)
// === STOP-LOSS AND TAKE-PROFIT ===
// Calculate stop-loss and take-profit levels
var float stop_loss_level = na
var float take_profit_level = na
if buy_condition
stop_loss_level := close * (1 - stop_loss_perc / 100)
take_profit_level := close * (1 + take_profit_perc / 100)
if sell_condition
stop_loss_level := close * (1 + stop_loss_perc / 100)
take_profit_level := close * (1 - take_profit_perc / 100)
// Execute trades based on conditions within the defined period
if (buy_condition and time >= start_date and time <= end_date)
strategy.entry("Buy", strategy.long)
if use_stop_loss
strategy.exit("Stop Loss", from_entry="Buy", stop=stop_loss_level)
if use_take_profit
strategy.exit("Take Profit", from_entry="Buy", limit=take_profit_level)
if (sell_condition and time >= start_date and time <= end_date)
strategy.entry("Sell", strategy.short)
if use_stop_loss
strategy.exit("Stop Loss", from_entry="Sell", stop=stop_loss_level)
if use_take_profit
strategy.exit("Take Profit", from_entry="Sell", limit=take_profit_level)
// === PLOTTING ===
plot(rsi, title="RSI", color=color.blue)
hline(rsi_overbought, "Overbought", color=color.red)
hline(rsi_oversold, "Oversold", color=color.green)
// Mark buy and sell signals on chart
plotshape(series=buy_condition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="Buy")
plotshape(series=sell_condition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell")
// === BACKTESTING RESULTS ===
// Calculate performance metrics
var float total_profit = 0.0
var int win_count = 0
var int loss_count = 0
if (strategy.opentrades == 0)
total_profit := strategy.netprofit
if (strategy.closedtrades > 0)
win_count := strategy.wintrades
loss_count := strategy.losstrades
// Plot win rate and profit factor
var label stats = na
if (na(stats))
stats := label.new(x=bar_index[1], y=high, style=label.style_label_down, color=color.white, textcolor=color.black, text="Win Rate: " + tostring(win_count/(win_count+loss_count)*100) + "%\nProfit Factor: " + tostring(total_profit/abs(strategy.netloss)))
else
label.set_xy(stats, bar_index[1], high)
label.set_text(stats, "Win Rate: " + tostring(win_count/(win_count+loss_count)*100) + "%\nProfit Factor: " + tostring(total_profit/abs(strategy.netloss)))
```
### Features in the script:
1. **Buy and Sell Conditions**:
- Buy when RSI crosses below the oversold level (default 30).
- Sell when RSI crosses above the overbought level (default 70).
2. **Risk Management**:
- Configurable stop-loss and take-profit levels as a percentage of the entry price.
- Toggle stop-loss and take-profit on/off with `use_stop_loss` and `use_take_profit`.
3. **Backtesting**:
- Define a backtesting period with `start_date` and `end_date`.
- Trade entries and exits are only evaluated within this date range.
4. **Performance Metrics**:
- Calculates the win rate and profit factor (ratio of total profit to total loss).
- Displays these metrics on the chart.
5. **Chart Plotting**:
- RSI is plotted on the chart with overbought and oversold levels.
- Buy and Sell signals are plotted as arrows (green for buy, red for sell).
6. **Configurable Parameters**:
- Adjust RSI length, overbought/oversold thresholds, and risk management settings via the script’s input options.
### How to Use:
1. Copy and paste this script into TradingView's Pine Script editor.
2. Customize the parameters for different timeframes and markets.
3. Run the backtest over your desired time period to see results.
4. The performance metrics (Win Rate and Profit Factor) will be displayed directly on the chart.