pine script - How to set orders that execute at a particular time within a day in Pinescript - Stack Overflow

admin2025-05-01  2

I'm new to Pinescript language in Tradingview. I want to backtest a simple day trading strategy where I buy $4000 worth of AAPL shares everyday at market open (9:30 AM EST) and sell them 1 minute before market close (3:59 PM EST) from Oct 1, 2024 to Dec 31, 2024. Below is the code I wrote with ChatGPT's help. It doesn't have any syntax errors, but backtesting closed only 14 trades and trades started only from Dec 9, 2024. I set the AAPL chart with 1 minute intervals. I'm not sure what's going wrong. I attached some pics for clarity.

I'm trying this to get a hang of how to set trades that execute at a particular time within a day and then repeat the same the next trading day. Any help that teaches me how to do that correctly is highly appreciated.

Thanks a lot!

Trades starting only from Dec 9, 2024 Strategy inputs are correct. But backtesting date range starts from Dec 9, 2024

//@version=6
strategy("Intraday Buy-Sell Strategy", overlay=true)

// Input parameters
capital = 4000 // USD to buy stock
startDate = input.time(timestamp("2024-01-01 00:00:00"), "Start Date")
endDate = input.time(timestamp("2024-12-30 00:00:00"), "End Date")

// Extract year, month, and day from the current time
currentYear = year(time)
currentMonth = month(time)
currentDay = dayofmonth(time)

// Market session times
marketOpenTime = timestamp(currentYear, currentMonth, currentDay, 9, 30)
marketCloseTime = timestamp(currentYear, currentMonth, currentDay, 15, 59) // Close at 3:59 PM

// Time filters
isWithinDateRange = (time >= startDate) and (time <= endDate)
isMarketOpen = (time >= marketOpenTime) and (time <= marketCloseTime)

// Track whether a trade has been executed for the current day
var float lastTradeDay = na
currentTradeDay = timestamp(currentYear, currentMonth, currentDay, 0, 0)

// Buy and sell logic
if isWithinDateRange and isMarketOpen and (na(lastTradeDay) or currentTradeDay != lastTradeDay)
    // Buy at market open
    openPrice = request.security(syminfo.tickerid, "D", open)
    shares = capital / openPrice
    strategy.entry("Daily Trade", strategy.long, qty=shares)
    lastTradeDay := currentTradeDay // Mark that a trade was made today

if isWithinDateRange and isMarketOpen and currentTradeDay == lastTradeDay and time >= marketCloseTime
    // Sell at market close
    strategy.close("Daily Trade")
转载请注明原文地址:http://anycun.com/QandA/1746093992a91579.html