Reputation: 134
I want to calculate the Simple Moving Average for a time period of two days from historical data. I am using the following code to get the high low close of the previous day.
// Getting previous 2 days day high low close
prev_daily_high = security(syminfo.tickerid, 'D', high)
prev_daily_low = security(syminfo.tickerid, 'D', low)
prev_daily_close = security(syminfo.tickerid, 'D', close)
But above code fetches only previous day data to calculate Moving average I need two days data.
cp=(prev_daily_high+prev_daily_low+prev_daily_close)/3
bc=(prev_daily_high+prev_daily_low)/2
tc=2*cp-bc
Below Code calculates SMA (Simple moving average) for two days but data I am fetching is for one day' How to fetch two days data and get correct SMA values?
// two days moving average for the central pivot, top central, bottom central
MAC = sma(cp, 2)
MAB = sma(bc, 2)
MAT = sma(tc, 2)
Upvotes: 0
Views: 2030
Reputation: 1
let me know how this works for you:
//@version=3
study("My Script")
// Defining colors using hexadecimal format
color_green = #00FF00
color_orange = #FFA500
color_purple = #800080
// Previous two days OHLC
prev_daily_high_1 = security(tickerid, 'D', high[1], lookahead=barmerge.lookahead_off)
prev_daily_low_1 = security(tickerid, 'D', low[1], lookahead=barmerge.lookahead_off)
prev_daily_close_1 = security(tickerid, 'D', close[1], lookahead=barmerge.lookahead_off)
prev_daily_high_2 = security(tickerid, 'D', high[2], lookahead=barmerge.lookahead_off)
prev_daily_low_2 = security(tickerid, 'D', low[2], lookahead=barmerge.lookahead_off)
prev_daily_close_2 = security(tickerid, 'D', close[2], lookahead=barmerge.lookahead_off)
// Two-day central pivot, top central, and bottom central
cp_1 = (prev_daily_high_1 + prev_daily_low_1 + prev_daily_close_1) / 3
bc_1 = (prev_daily_high_1 + prev_daily_low_1) / 2
tc_1 = 2 * cp_1 - bc_1
cp_2 = (prev_daily_high_2 + prev_daily_low_2 + prev_daily_close_2) / 3
bc_2 = (prev_daily_high_2 + prev_daily_low_2) / 2
tc_2 = 2 * cp_2 - bc_2
// Two-day SMA for central pivot, top central, and bottom central
sma_cp = sma(cp_1 + cp_2, 2)
sma_bc = sma(bc_1 + bc_2, 2)
sma_tc = sma(tc_1 + tc_2, 2)
// Plotting
plot(sma_cp, color=color_green, linewidth=2, title="Two-Day SMA - Central Pivot")
plot(sma_bc, color=color_orange, linewidth=2, title="Two-Day SMA - Bottom Central")
plot(sma_tc, color=color_purple, linewidth=2, title="Two-Day SMA - Top Central")
Upvotes: 0
Reputation: 8779
You need to let security()
make the calculations in its HTF context. Here we use a tuple to fetch all 3 values with one call:
MAC = sma(hlc3, 2)
MAB = sma(hl2, 2)
MAT = sma(2*hlc3-hl2, 2)
[dMAC, dMAB, dMAT] = security(syminfo.tickerid, 'D', [MAC, MAB, MAT])
See:
https://www.tradingview.com/pine-script-reference/v4/#var_hlc3
https://www.tradingview.com/pine-script-reference/v4/#var_hl2
Upvotes: 1