PromptBase
Close icon
Explore
General
Home
Marketplace
Apps
Create
Login
Sell
🤖 GPT

Backtesting Strategy With Pine Script

Backtesting Strategy With Pine Script gpt prompt mini thumbnail
5Eye icon
Views
TestedTick icon
TipsTick icon
4 examplesTick icon
This prompt assists traders in creating and backtesting Pine Script strategies, allowing them to analyze and refine their trading approach using historical data, while also providing clarity and transparency in the code.
...more
$6.99
Get prompt
After purchasing, you will gain access to the prompt file which you can use with GPT or the app builder. You'll receive 20 free generation credits with this purchase. By purchasing this prompt, you agree to our terms of service.
2 weeks ago
Related item

Prompt Details

Model
Chat - GPT-4o (gpt-4o)
Token size
146 ($0.00730 / call)
Example input
[Trading Strategy]: Mean Reversion [Time Period]: Last 5 years [Indicator and Indicator 2]: Moving Average (MA)" and "Bollinger Bands
Example output
Here is a Pine Script strategy focused on Mean Reversion using Moving Averages (MA) and Bollinger Bands. This strategy is designed for backtesting over the last five years and includes risk management, position sizing, and performance visualization features. ```pinescript //@version=5 strategy("Mean Reversion Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10, initial_capital=10000, currency=currency.USD) // === Parameters === length = input.int(20, title="Moving Average Length") src = input(close, title="Source") stdDev = input.float(2.0, title="Bollinger Bands Standard Deviation") maType = input.string("SMA", title="Moving Average Type", options=["SMA", "EMA"]) slPercent = input.float(1.0, title="Stop-Loss Percentage") tpPercent = input.float(2.0, title="Take-Profit Percentage") riskPerTrade = input.float(1.0, title="Risk Per Trade (%)") // === Moving Average Calculation === ma = maType == "SMA" ? ta.sma(src, length) : ta.ema(src, length) // === Bollinger Bands Calculation === basis = ta.sma(src, length) dev = stdDev * ta.stdev(src, length) upper = basis + dev lower = basis - dev // === Entry Conditions === // Long Entry: Price crosses below lower Bollinger Band longCondition = ta.crossover(lower, src) // Short Entry: Price crosses above upper Bollinger Band shortCondition = ta.crossover(src, upper) // === Exit Conditions === // Long Exit: Price crosses above the Moving Average or reaches take profit/stop loss longExitCondition = ta.crossover(src, ma) // Short Exit: Price crosses below the Moving Average or reaches take profit/stop loss shortExitCondition = ta.crossunder(src, ma) // === Risk Management === var float stopLoss = na var float takeProfit = na if (longCondition) stopLoss := src * (1 - slPercent / 100) takeProfit := src * (1 + tpPercent / 100) strategy.entry("Long", strategy.long) if (shortCondition) stopLoss := src * (1 + slPercent / 100) takeProfit := src * (1 - tpPercent / 100) strategy.entry("Short", strategy.short) if (strategy.position_size > 0) if src <= stopLoss strategy.close("Long", comment="Stop Loss Hit") if src >= takeProfit strategy.close("Long", comment="Take Profit Hit") if (strategy.position_size < 0) if src >= stopLoss strategy.close("Short", comment="Stop Loss Hit") if src <= takeProfit strategy.close("Short", comment="Take Profit Hit") // Exit at moving average crossover if (longExitCondition and strategy.position_size > 0) strategy.close("Long", comment="MA Exit") if (shortExitCondition and strategy.position_size < 0) strategy.close("Short", comment="MA Exit") // === Position Sizing === riskAmount = strategy.equity * (riskPerTrade / 100) capitalPerTrade = abs(strategy.position_size) * src tradeSize = riskAmount / (src - stopLoss) strategy.set_position_size(tradeSize) // === Annotations for Trade Performance === plotshape(series=longCondition, location=location.belowbar, color=color.green, style=shape.labelup, text="Buy") plotshape(series=shortCondition, location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell") plot(ma, color=color.blue, linewidth=2, title="Moving Average") plot(upper, color=color.red, linewidth=1, title="Upper Bollinger Band") plot(lower, color=color.green, linewidth=1, title="Lower Bollinger Band") // === Alerts and Notifications === alertcondition(longCondition, title="Long Entry Alert", message="Price has crossed below the lower Bollinger Band.") alertcondition(shortCondition, title="Short Entry Alert", message="Price has crossed above the upper Bollinger Band.") alertcondition(longExitCondition, title="Long Exit Alert", message="Price has crossed above the Moving Average.") alertcondition(shortExitCondition, title="Short Exit Alert", message="Price has crossed below the Moving Average.") // === Backtesting Analysis === // Setting the backtest period to the last 5 years backtestStartDate = timestamp("2019-08-26 00:00") backtestEndDate = timestamp("2024-08-26 00:00") if (time < backtestStartDate or time > backtestEndDate) strategy.close_all() // === Comments === // This strategy uses a Mean Reversion approach based on Bollinger Bands and Moving Averages. // The idea is to buy when the price crosses below the lower Bollinger Band (indicating oversold conditions) // and sell when it crosses above the upper Bollinger Band (indicating overbought conditions). // It also includes risk management features such as stop-loss and take-profit levels. ``` ### Explanation of the Strategy: 1. **Indicators Used**: - **Moving Average (MA)**: Used to determine the trend direction. Options are provided to use either Simple Moving Average (SMA) or Exponential Moving Average (EMA). - **Bollinger Bands**: Used for detecting potential reversal points by identifying overbought and oversold conditions. 2. **Entry Rules**: - **Long Position**: When the price crosses below the lower Bollinger Band. - **Short Position**: When the price crosses above the upper Bollinger Band. 3. **Exit Rules**: - **Long Exit**: Price crosses above the Moving Average or reaches the take-profit or stop-loss level. - **Short Exit**: Price crosses below the Moving Average or reaches the take-profit or stop-loss level. 4. **Risk Management**: - **Stop-Loss**: Set a stop-loss based on a percentage of the entry price. - **Take-Profit**: Set a take-profit level based on a percentage of the entry price. - **Position Sizing**: Calculate trade size based on risk percentage of equity. 5. **Backtesting**: - The backtest period is set to the last five years to evaluate the strategy’s effectiveness under different market conditions. 6. **Alerts**: - Alerts are configured to notify when the strategy enters or exits a trade. 7. **Annotations**: - Visual annotations are added to the chart to highlight trade entry and exit points. This strategy can be further optimized by adjusting parameters such as the length of the Moving Average, the standard deviation for Bollinger Bands, and the stop-loss/take-profit percentages.
Browse Marketplace