핫트레이딩

트레이딩뷰(Pine Script v5) 기반의 "Market Bias" 지표 본문

주식 경제이야기

트레이딩뷰(Pine Script v5) 기반의 "Market Bias" 지표

HOTT 2025. 3. 11. 22:44

트레이딩뷰 기반의 "Market Bias" 지표

 

 

트레이딩뷰 기반의 "Market Bias" 지표

 

 

트레이딩뷰 기반의 "Market Bias" 지표

 

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

//@version=5

indicator(title='Market Bias (CEREBR)', shorttitle='Market Bias', overlay=true)

//#region -----> INPUTS, FUCNTIONS

// FUNCTIONS
//@function This function forces the current timeframe on inputs that shouldn't take lower timeframes
FORCE_CTF(str_tf) =>
    i_tf_sec = timeframe.in_seconds(str_tf)
    ctf_sec = timeframe.in_seconds('')
    
    // Returns the CTF if the passed timeframe is lower
    i_tf_sec < ctf_sec ? '' : str_tf
//

// INPUTS
ha_htf = FORCE_CTF(input.timeframe('', 'Timeframe', tooltip="This timeframe must be equal to or greater than the chart's timeframe", group="HA Market Bias"))
ha_len = input(100, 'Period', group="HA Market Bias")
ha_len2 = input(100, 'Smoothing', group="HA Market Bias")

show_ha = input.bool(true, "Show HA Candles", inline='ha/mb display', group='Display Settings')
show_mb = input.bool(true, "Show Market Bias", inline='ha/mb display', group='Display Settings')
col_bull = input.color(color.lime, 'Color: Bullish', inline='bull/bear color', group='Display Settings', display=display.none)
col_bear = input.color(color.red, 'Bearish', inline='bull/bear color', group='Display Settings', display=display.none)


// These add an offset during data importation to avoid lookahead bias
indexHighTF = timeframe.in_seconds(ha_htf) == timeframe.in_seconds('') ? 0 : barstate.isrealtime ? 1 : 0
indexCurrTF = timeframe.in_seconds(ha_htf) == timeframe.in_seconds('') ? 0 : barstate.isrealtime ? 0 : 1

//@function Handles the import of data from other timeframes, while preventing repainting
//@param _resolution (str) : This is the timeframe to import data from.
//@param _expression (float | int) : This is the data to be imported
f_no_repaint_request(string _resolution, _expression) =>
     request.security(syminfo.tickerid, _resolution, _expression[indexHighTF])[indexCurrTF]
//#endregion



//#region -----> CALCULATIONS

// Smoothen the OHLC values 
o = ta.ema(open, ha_len)
c = ta.ema(close, ha_len)
h = ta.ema(high, ha_len)
l = ta.ema(low, ha_len)

// Calculate the Heikin Ashi OHLC values from it
haclose = f_no_repaint_request(ha_htf, (o + h + l + c) / 4)
xhaopen = f_no_repaint_request(ha_htf, (o + c) / 2)
haopen = na(xhaopen[1]) ? (o + c) / 2 : (xhaopen[1] + haclose[1]) / 2
hahigh = math.max(h, math.max(haopen, haclose))
halow = math.min(l, math.min(haopen, haclose))

// Smoothen the Heiken Ashi Candles
o2 = f_no_repaint_request(ha_htf, ta.ema(haopen, ha_len2))
c2 = f_no_repaint_request(ha_htf, ta.ema(haclose, ha_len2))
h2 = f_no_repaint_request(ha_htf, ta.ema(hahigh, ha_len2))
l2 = f_no_repaint_request(ha_htf, ta.ema(halow, ha_len2))

ha_avg = (h2 + l2) / 2


//TODO: Publish the Oscillator version of the indicator
// Oscillator {
osc_len = input.int(7, "Oscillator Period", group="HA Market Bias")

osc_bias = 100 * (c2 - o2)
osc_smooth = ta.ema(osc_bias, osc_len)

sigcolor = switch
    (osc_bias > 0) and (osc_bias >= osc_smooth) => color.new(col_bull, 35)
    (osc_bias > 0) and (osc_bias < osc_smooth) => color.new(col_bull, 75)
    (osc_bias < 0) and (osc_bias <= osc_smooth) => color.new(col_bear, 35)
    (osc_bias < 0) and (osc_bias > osc_smooth) => color.new(col_bear, 75)
    => color(na)
// }

//#endregion
    


//#region ----->  PLOTS, ALERTS {

// Plots
p_h = plot(h2, "Bias High", color=color(na), display=display.data_window, editable=false)
p_l = plot(l2, "Bias Low", color=color(na), display=display.data_window, editable=false)
p_avg = plot(ha_avg, "Bias Avergae", color=color(na), display=display.data_window, editable=false)
fill(p_l, p_h, show_mb ? sigcolor : na)

col = o2 > c2 ? col_bear : col_bull
plotcandle(o2, h2, l2, c2, title='heikin smoothed', color=col, display=show_ha ? display.pane : display.data_window, editable=false)


// Alerts
// Bullish Trend Switch (Bearish -> Bullish)
alertcondition(ta.change(ta.change(math.sign(osc_bias)) > 0), 
  'Bullish Trend Switch (Bearish -> Bullish)', '{{exchange}}:{{ticker}}: Trend is now Bullish.')

// Bullish Trend Strengthens
alertcondition(osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0,
  'Bullish Trend Strengthens', '{{exchange}}:{{ticker}}: Bullish Trend is now Stronger.')

// Bullish Trend Weakens
alertcondition(osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0,
  'Bullish Trend Weakens', '{{exchange}}:{{ticker}}: Bullish Trend is now Weaker.')

// Bearish Trend Switch (Bullish -> Bearish)
alertcondition(ta.change(ta.change(math.sign(osc_bias)) < 0), 
  'Bearish Trend Switch (Bullish -> Bearish)', '{{exchange}}:{{ticker}}: Trend is now Bearish.')

// Bearish Trend Strengthens
alertcondition(osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0,
  'Bearish Trend Strengthens', '{{exchange}}:{{ticker}}: Bearish Trend is now Stronger.')

// Bearish Trend Weakens
alertcondition(osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0,
  'Bearish Trend Weakens', '{{exchange}}:{{ticker}}: Bearish Trend is now Weaker.')
//#endregion



// CUSTOM ALERTS : To enable this functionality, Select and uncomment (Cmd (or Ctrl) + /) the following code block, starting from the next line.
// // {
// use_custom_alerts = input.bool(false, 'Use Custom Alert Messages', group='Alert Messages', display=display.none)
// i_alert_bull_trend_switch = input.text_area('New Bullish Trend', 'Bullish Trend Switch', group='Alert Messages', display=display.none)
// i_alert_bull_trend_strengthen = input.text_area('New Strong Bullish Trend', 'Bullish Trend Strengthens', group='Alert Messages', display=display.none)
// i_alert_bull_trend_weaken = input.text_area('New Weak Bullish Trend', 'Bullish Trend Weakens', group='Alert Messages', display=display.none)
// i_alert_bear_trend_switch = input.text_area('New Bearish Trend', 'Bearish Trend Switch', group='Alert Messages', display=display.none)
// i_alert_bear_trend_strengthen = input.text_area('New Strong Bearish Trend', 'Bearish Trend Strengthens', group='Alert Messages', display=display.none)
// i_alert_bear_trend_weaken = input.text_area('New Weak Bearish Trend', 'Bearish Trend Weakens', group='Alert Messages', display=display.none)


// // Bullish Trend Switch (Bearish -> Bullish)
// if (ta.change(ta.change(math.sign(osc_bias)) > 0))
//     alert(i_alert_bull_trend_switch, alert.freq_once_per_bar)

// // Bullish Trend Strengthens
// if (osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0)
//     alert(i_alert_bull_trend_strengthen, alert.freq_once_per_bar)

// // Bullish Trend Weakens
// if (osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0)
//     alert(i_alert_bull_trend_weaken, alert.freq_once_per_bar)

// // Bearish Trend Switch (Bullish -> Bearish)
// if (ta.change(ta.change(math.sign(osc_bias)) < 0))
//     alert(i_alert_bear_trend_switch, alert.freq_once_per_bar)

// // Bearish Trend Strengthens
// if (osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0)
//     alert(i_alert_bear_trend_strengthen, alert.freq_once_per_bar)

// // Bearish Trend Weakens
// if (osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0)
//     alert(i_alert_bear_trend_weaken, alert.freq_once_per_bar)

// // }

 

 

 

하이킨 아시(Heikin Ashi) 캔들 기반 시장 바이어스 분석

 

트렌드 강도 및 전환 시그널 감지

 

 

이 스크립트는 트레이딩뷰(Pine Script v5) 기반의 "Market Bias" 지표입니다. 핵심 기능을 정리하면 다음과 같습니다.


1. 주요 기능

하이킨 아시(Heikin Ashi) 캔들 기반 시장 바이어스 분석
트렌드 강도 및 전환 시그널 감지
다른 시간 프레임에서 데이터를 가져오는 기능
사용자 지정 경고(Alert) 지원


2. 코드 상세 설명

🔹 타임프레임 조정 (FORCE_CTF 함수)

  • FORCE_CTF() 함수는 선택한 타임프레임이 현재 차트보다 작지 않도록 강제합니다.
  • f_no_repaint_request() 함수는 다른 타임프레임에서 데이터를 가져오면서 리페인트 방지 역할을 합니다.

 

🔹 하이킨 아시 캔들 계산

하이킨 아시 캔들의 Open, High, Low, Close (OHLC)를 EMA(지수 이동 평균)로 스무딩 처리:

 

pinescript

o = ta.ema(open, ha_len)
c = ta.ema(close, ha_len)
h = ta.ema(high, ha_len)
l = ta.ema(low, ha_len)
 
 
 

이후 하이킨 아시 캔들 공식 적용:

haclose = f_no_repaint_request(ha_htf, (o + h + l + c) / 4)
haopen = na(xhaopen[1]) ? (o + c) / 2 : (xhaopen[1] + haclose[1]) / 2
hahigh = math.max(h, math.max(haopen, haclose))
halow = math.min(l, math.min(haopen, haclose))

 

즉, 하이킨 아시를 기존 차트에서 스무딩하여 더 명확한 시장 흐름을 보여줌.

 

🔹 오실레이터 기반 트렌드 분석

  • 트렌드 강도 지표를 만들기 위해 osc_bias를 정의:
osc_bias = 100 * (c2 - o2)
  • 오실레이터 값을 7-period EMA로 스무딩하여 노이즈 감소:
osc_smooth = ta.ema(osc_bias, osc_len)
  • 트렌드 강도를 색상으로 시각화:
 
sigcolor = switch
    (osc_bias > 0) and (osc_bias >= osc_smooth) => color.new(col_bull, 35)  // 강한 상승
    (osc_bias > 0) and (osc_bias < osc_smooth) => color.new(col_bull, 75)   // 약한 상승
    (osc_bias < 0) and (osc_bias <= osc_smooth) => color.new(col_bear, 35)  // 강한 하락
    (osc_bias < 0) and (osc_bias > osc_smooth) => color.new(col_bear, 75)   // 약한 하락
    => color(na)

 

즉, 트렌드 강도에 따라 색상이 달라지며 상승/하락 강도를 구분.

 

🔹 경고 (Alert) 시스템

다양한 트렌드 변화를 감지하여 알림을 제공:

alertcondition(ta.change(ta.change(math.sign(osc_bias)) > 0), 
  'Bullish Trend Switch (Bearish -> Bullish)', '{{exchange}}:{{ticker}}: Trend is now Bullish.')
  • 트렌드 전환 감지
  • 강한 상승/하락 신호 감지
  • 약한 상승/하락 신호 감지

3. 요약

  • 하이킨 아시 기반의 트렌드 분석 지표로, 스무딩된 가격 데이터를 사용하여 노이즈를 줄이고 시장 방향성을 더 명확하게 보여줍니다.
  • 오실레이터를 활용한 상승/하락 강도 분석을 추가하여 트렌드의 신뢰도를 강화합니다.
  • 경고 시스템을 통해 트레이더가 트렌드 변화를 실시간으로 인지할 수 있도록 합니다.

이 지표는 기본적인 트렌드 파악과 트레이딩 진입 시점을 잡는 데 유용할 수 있습니다. 🚀

반응형