candlestickb
candlestickb

Reputation: 59

Can't get user inputs to adjust closes above or below ema in PineScript

I have my code here for 'buy if I get 2 closes above the ema10 and sell if I get 3 closes below the ema10'. So far so good, but I want to be able to adjust the number of bars closing above or below the ema with my user inputs I created, I just cant figure out how to do that?

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © elasticc

//@version=5
strategy("S7",
 initial_capital=4000, 
 default_qty_type=strategy.percent_of_equity, 
 default_qty_value=100,
 overlay=true, 
 use_bar_magnifier=true)

// Get Inputs

i_closeabove    = input.int(title="Closes Above EMA", defval=2)
i_closebelow    = input.int(title="Closes Below EMA", defval=3)
i_ema           = input.int(title="EMA Length", defval=10)
i_startTime     = input.time(title="Start Filter", defval=timestamp("01 Jan 1995       13:30 +0000"))
i_endTime       = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30  +0000"))

// Date Filter

f_dateFilter    = time >= i_startTime and time <= i_endTime


// Get ema

ema             = ta.ema(close, i_ema)


// Buy Conditions
var float buyPrice = 0
buyCondition    = (close > ema) and (close[1] > ema[1]) and f_dateFilter and   strategy.position_size == 0

// Sell Conditions

three_close_under_ema = (close < ema) and (close[1] < ema[1]) and (close[2] < ema[2])
sellCondition   = three_close_under_ema and strategy.position_size >0

// Enter Trade

if buyCondition
strategy.entry(id="Long", direction=strategy.long)
buyPrice := open
 
// Exit Trade

if sellCondition
strategy.close(id="Long", comment="Exit")
 
 
// Plot on Chart

plot(ema, color=color.teal)

Any ideas would be really appreciated, Thanks

Upvotes: 0

Views: 153

Answers (1)

elod008
elod008

Reputation: 1362

Change your line defining "three_close_under_ema" as follows:

three_close_under_ema = ta.barssince(close > ema) >= i_closebelow

by that you determine if you are for at least i_closebelow bars below your ema. Similar solution for the opposite.

Upvotes: 0

Related Questions