Search code examples
pine-scriptpine-script-v5tradingview-api

How can I enter and exit a trade at a given time?


I am trying to backtest a strategy in Tradingview on an hourly chart that goes short AUDJPY at 5am Japan time and exits with a market order at 7am on the same day. I am using the hour(time) function and the IANA timezone 'Asia/Tokyo'.

Below is the code. I verified that the variable hr picks up the right hour by plotting it in the chart. But when I run the Strategy Tester the result is "No Data" and no trades appear on the screen after I apply "Add to chart" to the script.

strategy("Foreign JPY", overlay=true, currency = currency.USD)

hr = hour(time, "Asia/Tokyo")

shortCondition = hr == 5
if (shortCondition)
    strategy.entry("short", strategy.short, 100000)

exitCondition = hr == 7 and strategy.position_size < 0
if (exitCondition)
    strategy.close("exit", 100000)

Solution

  • The exit condition in your example is executed only for entries with an "exit" id=. If you want to point to the existing short order, use its id= in the strategy.close() parameter:

    if (exitCondition)
        strategy.close("short", 100000)