4

Just playing around, learning how to write strategies. The one I'm trying right now is (pseudo-code)...

if(previousCandle == red 
   ... AND previousCandle.high >= sma
   ... AND previousCandle.low <= sma 
   ... AND currentPrice > previousCandle.high)
    
    enter trade

What I have in Pine Script is...

redTouch = close < open and high >= ma and low <= ma

longCond = redTouch[1] and close > high[1]

strategy.entry("Long", strategy.long, when = longCond)

The redTouch candles are all identified correctly (checked previously using BG colors), but for the longCond I don't want close > high[1], because that enters the trade only on the next candle (and too late).

The following screenshot shows where the trade is currently being entered (blue line on red candle), and where I'd like it to trigger/enter (yellow line on green candle).

Late and desired trades

How do I change close > high[1] to price > high[1] or a similar intra-candle crossover trigger? Or can you only enter trades in the next candle in Pine Script?

Birrel
  • 4,754
  • 6
  • 38
  • 74
  • About tradingview's execution model - https://www.tradingview.com/pine-script-docs/en/v4/language/Execution_model.html – e2e4 Jan 16 '21 at 19:49
  • This article might also be helpful - https://backtest-rookies.com/2017/11/15/backtesting-101-trades-delayed/ – e2e4 Jan 16 '21 at 19:50
  • @e2e4 Thanks for the links. By all accounts it seems that backtesting only uses full candles for the period length. Looks like I'll have to mix and match period lengths to trick it into working. Thanks again! – Birrel Jan 16 '21 at 22:17

1 Answers1

5

You'll need to do a few things to get the behavior you're looking for.

  1. Add process_orders_on_close=true to your strategy declaration statement to get the Strategy tester to process on the bar that triggers the condition instead of the next bar's open.
  2. Store the price you want to enter in a variable, maybe high[1]+somenumber
  3. Add limit=YourEntryPriceVariable to your strategy.entry statement

This will create a limit order to enter at the price you specify on the bar that it happens.

kmarryat
  • 156
  • 4
  • Thanks, I appreciate you taking the time to answer my question. I've moved on from that strategy for now, and so I don't have it coded up to test at the moment. I'm having some issues with my exits though, if you wanted to take a look at my new question [here](https://stackoverflow.com/questions/65838172/pine-script-strategy-set-exit-limit-stop-based-on-atr-at-entry). Thanks again! – Birrel Jan 22 '21 at 01:33