You are a professional trader and script writer in pine. Make a script to be applied in…
- User
You are a professional trader and script writer in pine. Make a script to be applied in trading view where we take entry at 10:19 am everyday and exit if stoploss hits 100 points down or profit is 200 points up. Enter trade only when following conditions are met:
-
Take call trade if market opens gap up
-
Take sell trade if market opens gap down
Back testing period - 1 January 2024 to 14 November 2024
-
- Assistant
Certainly! Below is a Pine Script (version 5) for TradingView that implements your specified trading strategy. This script will:
- Enter a trade at 10:19 AM each trading day:
- Long (buy) if the market opens with a gap up.
- Short (sell) if the market opens with a gap down.
- Exit the trade when either:
- A stop loss of 100 points is hit.
- A take profit of 200 points is achieved.
- Backtests the strategy from January 1, 2024 to November 14, 2024.
Important Notes:
-
Point Definition: This script assumes that "points" refer to the price movement based on the instrument's price scale. If you're trading an asset with a different tick size or denomination, you may need to adjust the
stopLossandtakeProfitvalues accordingly. -
Time Zone: The script uses the exchange's time zone. Ensure that the exchange time aligns with your intended trading hours. You can modify the
time_in_sessionfunction if needed. -
Backtesting Period: Pine Script's built-in backtester will automatically respect the date range if specified. Ensure your chart includes the specified period for accurate backtesting.
-
Order Execution: This script uses
strategy.entryandstrategy.closefunctions to simulate trade entries and exits. Remember that real trading may involve slippage and other factors not accounted for in backtesting.
Pine Script Code:
//@version=5 strategy("Gap Up/Down Strategy", overlay=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.05) // Define the backtesting period startDate = timestamp("2024-01-01T00:00:00") endDate = timestamp("2024-11-14T23:59:59") if (time < startDate or time > endDate) strategy.close_all() // Function to determine if there's a gap up/down gapUp = (open > close[1]) gapDown = (open < close[1]) noGap = (open == close[1]) // Define the time for entry: 10:19 AM entryHour = 10 entryMinute = 19 isEntryTime = (hour == entryHour and minute == entryMinute) // Initialize variables to track positions var bool inTrade = false var float entryPrice = na var string positionType = "" // Define Stop Loss and Take Profit in points stopLoss = 100 takeProfit = 200 // Check for entry conditions at 10:19 AM if (isEntryTime and not inTrade and (gapUp or gapDown)) if (gapUp) strategy.entry("Long", strategy.long) positionType := "Long" else if (gapDown) strategy.entry("Short", strategy.short) positionType := "Short" inTrade := true entryPrice := open // Define Exit Conditions if (inTrade) if (positionType == "Long") // Calculate Stop Loss and Take Profit levels stopLevel = entryPrice - stopLoss * syminfo.mintick takeLevel = entryPrice + takeProfit * syminfo.mintick // Exit conditions if (low <= stopLevel) strategy.close("Long", comment="Stop Loss") inTrade := false if (high >= takeLevel) strategy.close("Long", comment="Take Profit") inTrade := false else if (positionType == "Short") // Calculate Stop Loss and Take Profit levels stopLevel = entryPrice + stopLoss * syminfo.mintick takeLevel = entryPrice - takeProfit * syminfo.mintick // Exit conditions if (high >= stopLevel) strategy.close("Short", comment="Stop Loss") inTrade := false if (low <= takeLevel) strategy.close("Short", comment="Take Profit") inTrade := false // Plotting for visualization plotshape(series=gapUp and isEntryTime, location=location.belowbar, color=color.green, style=shape.labelup, text="Gap Up Long") plotshape(series=gapDown and isEntryTime, location=location.abovebar, color=color.red, style=shape.labeldown, text="Gap Down Short")Explanation of the Script:
-
Strategy Declaration:
initial_capital: Starting with $100,000 (adjust as needed).default_qty_typeanddefault_qty_value: Allocates 10% of equity per trade.commission: 0.05% per trade (adjust based on your broker).
-
Backtesting Period:
- The script defines a specific time range from January 1, 2024, to November 14, 2024.
- Trades outside this period are ignored, and any open positions are closed.
-
Gap Detection:
gapUp: Today's open is higher than yesterday's close.gapDown: Today's open is lower than yesterday's close.
-
Trade Entry:
- At 10:19 AM, if there's a gap up, enter a long position.
- At 10:19 AM, if there's a gap down, enter a short position.
- The script ensures only one trade is active at a time.
-
Trade Exit:
- For Long Positions:
- Stop Loss: 100 points below the entry price.
- Take Profit: 200 points above the entry price.
- For Short Positions:
- Stop Loss: 100 points above the entry price.
- Take Profit: 200 points below the entry price.
- The script monitors the price to exit the trade when either condition is met.
- For Long Positions:
-
Visualization:
plotshapefunctions mark the entry points on the chart for easy visualization:- Green labels for Gap Up Long entries.
- Red labels for Gap Down Short entries.
How to Use This Script:
-
Open TradingView:
- Navigate to TradingView and log in to your account.
-
Open Pine Editor:
- At the bottom of the TradingView interface, click on the "Pine Editor" tab.
-
Paste the Script:
- Copy the entire Pine Script provided above and paste it into the Pine Editor.
-
Add to Chart:
- Click on "Add to Chart". The strategy will compile and apply to your current chart.
-
Adjust Settings as Needed:
- You can modify the
initial_capital,default_qty_value,stopLoss, andtakeProfitvariables to better fit your trading preferences or the specific instrument you're trading.
- You can modify the
-
View Backtest Results:
- Navigate to the "Strategy Tester" tab at the bottom to see performance metrics, including net profit, drawdown, number of trades, etc., for the specified backtesting period.
Final Recommendations:
-
Instrument Selection: Ensure that the asset you're applying this strategy to has sufficient liquidity and typical price movements that align with the stop loss and take profit levels.
-
Time Frames: This script assumes you're using a time frame that allows precise execution at 10:19 AM (e.g., minute charts). Adjust the chart's time frame accordingly.
-
Optimization: Consider optimizing the stop loss and take profit values based on historical volatility or Average True Range (ATR) for better performance.
-
Risk Management: Always ensure that your risk management aligns with your overall trading goals and risk tolerance.
Feel free to further customize the script to better fit your specific trading needs. Happy Trading!
- Enter a trade at 10:19 AM each trading day: