Wrong value from a second time interval in pine script

Viewed 155

Good morning,

I have a little problem there.

I would like work with data from two different time interval. for example, BTC (1 day time interval) and BTC (4 hour time interval) chart.

The main time interval is the 4 hour. The value "HA_C", this is the close value of "BTC 1 Day". The "close BTC 1 Day time interval" value displayed correct in the 4 hour chart. But the value "test" with a simple arithmetic problem differs greatly and is wrong.

You can test this as follows: Loads the strategy in "BTC", time interval "1 Day", note from one day the "BTC Close" value and the "test" value.

Then switch to "BTC" 4 hour time interval. You will see, that the "HA_C Close" from the 1 hour time interval is the correct value, but the "test" value is displayed incorrectly.

Why is the "test" value after a calculation incorrectly, although the "Close" value is correct ???

I have find out, that the problem is the "ta.ema (source, length)" function. Can someone give me a formula, that calculates the same value as the "ta.ema (source, length)" function.

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

//@version=5
strategy("TEST", process_orders_on_close=true, overlay=true, calc_on_every_tick=true, pyramiding=30) 

varip test = 0.0

HA_Symbol = ticker.heikinashi("BINANCE:BTCUSDT")
HA_C      = request.security(HA_Symbol, "1D", close)


test:= ta.ema(HA_C, 7) * 1.05


plot (HA_C)
plot (test)**
2 Answers

I have finde the correct code. Here is it:

c2_1D = request.security(ticker.heikinashi('BINANCE:BTCUSDT'), "1D", t3_D (close, T3Length_1D, T3FactorCalc_1D))

It is due to the context you have called the ema function. If your chart is H4 and you perform your test calculation in the global scope, it is using 7 x H4 bars of HA_C. On BTCUSDT, over the last 7 H4 bars, it would have been 7 bars made up of multiples of only 2 daily values, hence the incorrect result.

enter image description here

When you change the chart to D1, it shows the correct result because now the global context of the script is now operating in the same timeframe as the security call.

If you want the correct value from the ema using 7 x 1D bars it has to be done within the context of the security call. For example :

test = request.security(ticker.heikinashi("BINANCE:BTCUSDT"), "D", ta.ema(close, 7))

If you need to perform multiple operations using the same ticker, you can also wrap them in a function and just pass the one function to a single security call. For example, this will return the daily close and the daily ema 7 :

f_ema_and_close(_src, _len) =>
    _ema = ta.ema(_src, _len)
    [_src, _ema]
    
[D1_close, D1_ema7] = request.security(ticker.heikinashi("BINANCE:BTCUSDT"), "D", f_ema_and_close(close, 7))

plot(D1_close, color = color.yellow)
plot(D1_ema7, color = color.red)
Related