네, 트레이딩뷰에서 비트코인 5분봉 차트에 스윙 고점과 저점을 식별하고, 이를 매수/매도 라벨 및 시각적인 연결선으로 표시하는 Pine Script 코드를 창의적으로 작성해 드리겠습니다.
이 스크립트는 단순히 고점/저점에 라벨을 붙이는 것을 넘어, 각 스윙 포인트를 잠재적인 매수/매도 기회로 해석하여 직접적인 신호 라벨을 표시하고, 이전 스윙 포인트와 연결하여 가격의 흐름과 구조를 시각적으로 명확하게 보여줍니다.
창의적/창조적 요소:
직관적인 매수/매도 라벨: 스윙 저점에 "Buy" 라벨을, 스윙 고점에 "Sell" 라벨을 표시하여 잠재적인 거래 방향을 직관적으로 제시합니다. 가격 정보도 함께 표시하여 편리성을 높입니다.
가격 흐름 연결선: 이전 스윙 고점과 새로운 스윙 저점 (하락), 이전 스윙 저점과 새로운 스윙 고점 (상승)을 선으로 연결하여 차트상에 파동의 형태를 시각적으로 그려줍니다. 이는 가격 움직임의 구조를 이해하는 데 도움을 줍니다.
조절 가능한 민감도: 스윙 포인트를 정의하는 좌우 캔들 수를 입력 변수로 제공하여, 사용자가 차트의 특성이나 자신의 전략에 맞게 스윙 포인트 감지 민감도를 조절할 수 있습니다. '신속하고 정확한' 정도는 이 파라미터에 따라 달라집니다.
Pine Script 코드 (버전 5)
pine
//@version=5
indicator(title="BTC 5분봉 스윙 매수/매도 신호 라벨 및 연결선", shorttitle="BTC 5m Swing Trader", overlay=true)
// --- 입력 변수 ---
// 스윙 고점/저점을 판단할 때 현재 캔들 기준 좌/우 몇 개의 캔들을 비교할지 설정합니다.
// 값이 작을수록 더 많은, 작은 스윙을 잡고 신호가 빨라지지만 노이즈가 많아질 수 있습니다.
// 값이 클수록 더 적은, 의미있는 스윙을 잡고 신호가 늦어지지만 신뢰도가 높아질 수 있습니다.
leftBars = input.int(5, title="좌측 캔들 수 (Swing Lookback)", minval=1)
rightBars = input.int(5, title="우측 캔들 수 (Swing Lookforward)", minval=1)
// --- 스윙 고점/저점 감지 ---
// ta.pivothigh(left, right) 함수는 현재 캔들에서 left개 전부터 right개 후까지의 범위에서
// right개 전 캔들이 고점이면 해당 고가(high) 값을 반환하고, 아니면 na를 반환합니다.
// 즉, 이 함수는 스윙 고점이 확정되는 시점 (rightBars 개 이후 캔들)에서 동작합니다.
float swingHighPrice = ta.pivothigh(leftBars, rightBars)
float swingLowPrice = ta.pivotlow(leftBars, rightBars)
// 스윙 고점/저점이 실제로 발생한 캔들의 인덱스 (현재 캔들 - rightBars)
// 확정은 현재 캔들에서 되지만, 라벨과 선은 실제 스윙 캔들에 그려야 합니다.
int swingHighIndex = bar_index[rightBars]
int swingLowIndex = bar_index[rightBars]
// --- 이전 스윙 포인트 정보 저장 ---
// 이전 스윙 포인트를 저장하여 새로운 스윙 포인트와 연결선을 그리기 위해 사용합니다.
var int lastConfirmedHighIndex = na
var float lastConfirmedHighPrice = na
var int lastConfirmedLowIndex = na
var float lastConfirmedLowPrice = na
// --- 라벨 표시 및 연결선 그리기 ---
// 스윙 고점이 현재 캔들에서 확정되었다면 (swingHighPrice 값이 na가 아니라면)
if not na(swingHighPrice)
// 이전 확정된 저점 정보가 있다면, 그 저점에서 현재 확정된 고점까지 연결선 그리기 (매수 구간 상승 시도 시각화)
if not na(lastConfirmedLowIndex)
line.new(x1=lastConfirmedLowIndex, y1=lastConfirmedLowPrice, x2=swingHighIndex, y2=swingHighPrice,
color=color.green, width=2, style=line.style_solid, extend=extend.none)
// 스윙 고점 캔들에 "Sell" 라벨 표시 (잠재적 매도 신호)
label.new(x=swingHighIndex, y=swingHighPrice,
text="Sell\n" + str.tostring(swingHighPrice, format.mintick), // 가격 정보 포함
style=label.style_label_down, // 아래 화살표 라벨
color=color.red, // 빨간색 (매도/하락)
textcolor=color.white, // 글자색 흰색
yloc=yloc.above_bar, // 캔들 위쪽 표시
size=size.small) // 라벨 크기
// 최신 확정된 고점 정보 업데이트
lastConfirmedHighIndex := swingHighIndex
lastConfirmedHighPrice := swingHighPrice
// 스윙 저점이 현재 캔들에서 확정되었다면 (swingLowPrice 값이 na가 아니라면)
if not na(swingLowPrice)
// 이전 확정된 고점 정보가 있다면, 그 고점에서 현재 확정된 저점까지 연결선 그리기 (매도 구간 하락 시도 시각화)
if not na(lastConfirmedHighIndex)
line.new(x1=lastConfirmedHighIndex, y1=lastConfirmedHighPrice, x2=swingLowIndex, y2=swingLowPrice,
color=color.red, width=2, style=line.style_solid, extend=extend.none)
// 스윙 저점 캔들에 "Buy" 라벨 표시 (잠재적 매수 신호)
label.new(x=swingLowIndex, y=swingLowPrice,
text="Buy\n" + str.tostring(swingLowPrice, format.mintick), // 가격 정보 포함
style=label.style_label_up, // 위 화살표 라벨
color=color.green, // 초록색 (매수/상승)
textcolor=color.white, // 글자색 흰색
yloc=yloc.below_bar, // 캔들 아래쪽 표시
size=size.small) // 라벨 크기
// 최신 확정된 저점 정보 업데이트
lastConfirmedLowIndex := swingLowIndex
lastConfirmedLowPrice := swingLowPrice
// 참고: 이 지표는 가격의 스윙 구조를 시각적으로 표시하고 잠재적인 전환점을 라벨링하는 도구입니다.
// 라벨과 연결선은 해당 스윙 포인트가 확정된 후에 표시됩니다 (Lookforward 캔들 수 만큼의 지연 발생).
// 실제 매매 결정은 이 지표뿐만 아니라 다른 분석 도구 및 개인의 판단과 함께 신중하게 내려야 합니다.
코드 사용 방법:
트레이딩뷰에서 비트코인 5분봉 차트를 엽니다.
차트 하단의 Pine 에디터 탭을 클릭합니다.
위 코드를 복사하여 Pine 에디터에 붙여넣습니다.
"차트에 추가" 버튼을 클릭합니다.
설정 방법:
스크립트가 차트에 추가되면 설정 (톱니바퀴 아이콘) 버튼을 클릭합니다.
좌측 캔들 수 (Swing Lookback): 스윙 고점/저점을 판단할 때 해당 캔들 기준 왼쪽 몇 개의 캔들을 비교할지 설정합니다.
우측 캔들 수 (Swing Lookforward): 스윙 고점/저점을 판단할 때 해당 캔들 기준 오른쪽 몇 개의 캔들을 비교할지 설정합니다. 스윙 포인트는 이 rightBars 갯수 이후에 확정됩니다. 값이 작을수록 신호는 빨리 나오지만 덜 확정적이며, 값이 클수록 신호는 늦게 나오지만 더 확정적입니다.
설명:
스크립트는 ta.pivothigh와 ta.pivotlow 함수를 사용하여 스윙 고점과 저점을 효율적으로 감지합니다. 이 함수들은 rightBars 갯수만큼의 캔들이 지난 후에야 스윙 포인트를 확정합니다. 따라서 라벨과 선은 실제 스윙이 발생한 캔들에 표시되지만, 그 표시는 rightBars 갯수 이후의 캔들에서 이루어집니다.
스윙 저점이 확정되면 해당 캔들에 "Buy" 라벨과 가격이 표시되고, 이전 스윙 고점에서 현재 저점까지 빨간색 선이 그려져 하락 파동을 시각화합니다.
스윙 고점이 확정되면 해당 캔들에 "Sell" 라벨과 가격이 표시되고, 이전 스윙 저점에서 현재 고점까지 초록색 선이 그려져 상승 파동을 시각화합니다.
이 스크립트는 비트코인 5분봉 차트에서 가격의 주요 변곡점(스윙 고/저점)을 포착하고, 이를 잠재적인 매수/매도 영역으로 해석하여 시각적으로 명확하게 표시해 줌으로써 트레이딩에 도움을 줄 수 있습니다.
User
트레이딩뷰에서 선행지표로 가장 신뢰할 수 있는 것은?
Assistant
트레이딩뷰에서 "가장 신뢰할 수 있는 선행 지표"를 하나만 꼽는 것은 매우 어렵고 사실상 불가능합니다. 그 이유는 다음과 같습니다.
어떤 지표도 미래를 100% 예측할 수 없습니다: 모든 기술 지표는 과거 가격 데이터를 기반으로 계산됩니다. 선행 지표는 과거 패턴을 분석하여 잠재적인 미래 움직임을 시사하지만, 절대적인 확정 신호를 제공하지는 않습니다. 시장은 예측 불가능한 다양한 요인에 의해 움직입니다.
신뢰도는 시장 상황에 따라 다릅니다: 특정 지표는 특정 시장 환경(예: 추세장, 횡보장)에서 더 잘 작동할 수 있습니다. 어떤 지표가 '가장 신뢰할 수 있다'는 것은 어떤 시장 상황에서, 어떤 종목(비트코인), 어떤 시간대(5분봉)에 적용하는지에 따라 달라집니다.
신뢰도는 사용자 해석에 따라 다릅니다: 지표의 신호는 사용자가 어떻게 해석하고 다른 분석 도구와 함께 어떻게 사용하는지에 따라 그 유효성이 달라집니다.
그럼에도 불구하고, 트레이더들이 상대적으로 선행적인 신호를 포착하는 데 사용하고 신뢰성을 높이기 위해 노력하는 지표들은 다음과 같습니다. 이러한 지표들은 단독으로 사용하기보다는 다른 지표, 가격 움직임, 시장 구조 분석 등과 함께 사용할 때 더 유의미한 신호를 제공하는 경향이 있습니다.
트레이딩뷰에서 선행적인 신호로 활용될 수 있는 지표들 (절대적 신뢰도 순위 아님):
모멘텀 오실레이터 (RSI, 스토캐스틱, MACD 히스토그램 등):
왜 선행적인가? 가격 자체보다 움직임의 속도와 강도를 측정하여, 가격이 정점에 도달하기 전에 모멘텀이 약해지는 신호(다이버전스)를 먼저 보여주는 경향이 있습니다. 과매수/과매도 영역은 잠재적인 가격 반전을 시사할 수 있습니다.
신뢰도: 다이버전스는 비교적 신뢰할 만한 선행 신호로 여겨지지만, 강력한 추세에서는 과매수/과매도 영역에 오래 머물며 속임수 신호를 줄 수도 있습니다.
비트코인 5분봉: 5분봉은 변동성이 크고 노이즈가 많아 작은 다이버전스는 속임수가 많을 수 있습니다. 더 큰 시간봉에서의 추세와 함께 보거나, 여러 오실레이터를 함께 보는 것이 좋습니다.
거래량 (Volume):
왜 선행적인가? 가격 움직임에 대한 시장 참여자들의 '확신'이나 '관심' 정도를 보여줍니다. 예를 들어, 저항 돌파 시 거래량이 폭발적으로 증가하면 강력한 상승 추세의 시작을 알리는 선행 신호일 수 있습니다. 반대로, 상승 추세 중에 거래량이 점차 감소하면 추세 약화를 시사하는 선행 신호일 수 있습니다.
신뢰도: 거래량 패턴은 해석이 다소 주관적일 수 있으며, 갑작스러운 대량 매매에 의해 일시적으로 왜곡될 수도 있습니다. 그러나 가격 움직임과 함께 분석할 때 강력한 확인 또는 선행 신호가 될 수 있습니다.
비트코인 5분봉: 5분봉에서도 단기적인 매수/매도 압력을 파악하는 데 유용합니다. 특정 가격대에서의 거래량 집중 등도 볼 수 있습니다.
피보나치 되돌림/확장 (Fibonacci Retracement/Extension):
왜 선행적인가? 과거의 중요한 고점과 저점을 기준으로 잠재적인 미래의 지지/저항 레벨을 미리 예측하고 설정하는 도구입니다.
신뢰도: 피보나치 레벨은 많은 트레이더들이 참고하기 때문에 일종의 자가 충족적 예언처럼 작용하기도 합니다. 그러나 이 레벨들이 반드시 지지/저항으로 작용한다는 보장은 없으며, 어떤 스윙 포인트를 기준으로 피보나치를 그릴지 선택하는 것이 중요합니다.
비트코인 5분봉: 단기적인 스윙에서도 피보나치 레벨을 적용하여 반등 또는 조정 목표가를 예측해 볼 수 있습니다.
엘리어트 파동 이론 (Elliott Wave Theory - 자체 지표는 아니지만 분석 도구):
왜 선행적인가? 시장 가격이 반복되는 파동 패턴을 따른다고 가정하고, 현재 파동의 위치를 파악하여 앞으로 이어질 파동을 예측하려는 시도입니다.
신뢰도: 해석이 매우 주관적이고 복잡하며, 잘못된 파동 카운팅은 완전히 다른 예측으로 이어집니다. 높은 신뢰도를 얻기 위해서는 많은 경험과 숙련도가 필요합니다.
5분봉 같은 짧은 시간봉에서는 노이즈가 많고 파동 카운팅이 더 어렵고 신뢰성이 떨어질 수 있습니다.
User
Ichimoku 기반 자동 매수/매도 비주얼 스크립트 작성해저
Assistant
네, 트레이딩뷰에서 이치모쿠 킨코 효(Ichimoku Kinko Hyo) 지표를 기반으로 한 자동 매수/매도 신호를 차트에 시각적으로 표시해주는 Pine Script 코드를 창의적인 방식으로 작성해 드리겠습니다.
이 스크립트는 가장 일반적인 이치모쿠 신호 중 하나인 전환선(Tenkan-sen)과 기준선(Kijun-sen)의 교차를 기반으로 하되, 가격이 구름대(Kumo) 위에 있는지 아래 있는지 여부로 신뢰성을 추가하고, 신호 발생 시점에 직접적인 매수/매도 라벨을 표시해 줍니다. 구름대 및 다른 선들도 함께 그려져 이치모쿠 지표 자체도 시각적으로 활용할 수 있습니다.
창의적/창조적 요소:
결합된 신호: 단순한 선 교차뿐만 아니라 가격과 구름대의 상대적 위치를 함께 고려하여 신호의 정확도를 높이려고 시도합니다. (이치모쿠의 다양한 요소를 결합)
직관적인 라벨: 신호 발생 캔들에 'BUY' 또는 'SELL' 라벨을 크고 명확하게 표시하여 차트에서 바로 신호를 인지할 수 있도록 합니다.
표준 이치모쿠 플롯: 신호 라벨과 함께 이치모쿠 지표의 모든 구성 요소(전환선, 기준선, 선행 스팬 A/B, 후행 스팬)를 차트에 함께 그려, 트레이더가 신호의 맥락을 이해하고 다른 이치모쿠 분석과 병행할 수 있도록 합니다.
Pine Script 코드 (버전 5)
pine
User
아래 코드를 해결해줘
//@version=5
indicator('1 Pivot Points High Low v3-1', overlay = true, max_labels_count = 500, max_lines_count = 500, max_bars_back = 5000)
// 굵은 유니코드 숫자 변환 함수
toBoldUnicode(strIn) =>
string result = strIn
result := str.replace_all(result, '0', '𝟬')
result := str.replace_all(result, '1', '𝟭')
result := str.replace_all(result, '2', '𝟮')
result := str.replace_all(result, '3', '𝟯')
result := str.replace_all(result, '4', '𝟰')
result := str.replace_all(result, '5', '𝟱')
result := str.replace_all(result, '6', '𝟲')
result := str.replace_all(result, '7', '𝟳')
result := str.replace_all(result, '8', '𝟴')
result := str.replace_all(result, '9', '𝟵')
result
// 시그모이드 활성화 함수
sigmoid(x) =>
1.0 / (1.0 + math.exp(-x))
Assistant
제공해주신 Pine Script 코드는 스윙 고점/저점을 찾고 라벨과 선으로 표시하며, 여기에 신경망(Neural Network) 예측 및 확률 계산 로직을 추가하려는 시도를 포함하고 있습니다.
코드에는 몇 가지 수정이 필요한 부분이 있습니다:
신경망 부분: 제공된 신경망 코드는 실제 학습된 모델이 아니라 가중치가 하드코딩된 단순 계산입니다. 실제 신경망 예측을 위해서는 외부 라이브러리나 데이터를 사용해야 하며, 이는 Pine Script의 기능 범위를 넘어섭니다. 따라서 이 부분은 **개념적인 목업(Mockup)**으로 간주해야 하며, 실제 트레이딩 신호로 사용하기에는 신뢰도가 매우 낮습니다. 코드 자체는 작동하지만, '신경망'이라는 이름에 맞는 동작은 아닙니다.
메모리 관리 (cleanupOldElements): 라벨 및 라인 배열에서 가장 오래된 요소를 삭제할 때, array.remove(..., 0)를 사용하는 것은 비효율적이며 예상치 못한 동작을 유발할 수 있습니다. 배열의 시작에서 요소를 삭제하면 나머지 요소들이 앞으로 이동하기 때문입니다. 오래된 요소들을 삭제할 때는 array.shift()를 반복적으로 사용하거나, 삭제할 인덱스 목록을 만든 후 뒤에서부터 삭제하는 것이 더 안전합니다. 가장 간단한 방법은 array.shift()를 사용하는 것입니다.
n 변수 사용: var int n = bar_index는 스크립트가 로드된 첫 번째 캔들의 bar_index만 저장하고 이후 업데이트되지 않습니다. 피봇 위치 계산 등에 n - length를 사용하면 현재 캔들의 bar_index가 아니라 첫 캔들의 bar_index를 기준으로 계산되므로 잘못된 위치에 라벨과 선이 그려집니다. 현재 캔들의 인덱스는 bar_index 변수를 직접 사용해야 합니다.
adjustBarPos 함수 및 xloc 사용: adjustBarPos 함수는 max_bars_back 범위 내로 bar_index를 제한하려는 시도입니다. 그러나 label.new 및 line.new 함수는 xloc.bar_time 또는 xloc.bar_index와 함께 사용할 때 플랫폼이 max_bars_back 내에서 역사적 캔들 위치를 자동으로 처리합니다. 수동으로 조정하는 것보다 내장 기능을 사용하는 것이 일반적으로 더 정확합니다. 이 함수는 제거하고 bar_index를 직접 사용하는 것이 좋습니다.
라벨 Y 위치 조정 (createLabel): price + price * yOffset / 100는 가격에 대한 백분율 오프셋을 계산하는데, 이는 가격이 높은 자산에서는 라벨이 매우 멀리 떨어져 표시되게 합니다. yloc 파라미터 (yloc.above_bar, yloc.below_bar)가 이미 라벨 위치를 캔들 위/아래로 고정하므로, 추가적인 가격 기반 오프셋은 불필요하거나 다른 방식으로 구현해야 합니다. yloc을 사용하면서 오프셋을 사용하고 싶다면, 픽셀 단위 오프셋 (yolk=yloc.above_bar, style=label.style_label_down, text='...', y=high, yoffset=5 처럼)을 고려할 수 있습니다. 현재 코드에서는 yloc을 사용하고 있으므로 yOffset 계산 및 적용 부분을 제거하는 것이 자연스럽습니다.
마지막 라벨 (yellow_lbl) 및 라인 (yellow_line) 로직: 이 부분이 if barstate.islast 블록 안에 있어서 차트의 마지막 캔들에서만 실행됩니다. 의도하신 바가 현재 진행 중인 스윙의 최저점/최고점 및 확률을 실시간으로 추적하여 보여주는 것이라면, 이 블록은 if barstate.islast 밖으로 나와서 모든 캔들에서 실행되어야 합니다. 또한, "확률" 계산 로직 (array.size(prices) - idx) / array.size(prices) * 100.0이 무엇을 의미하는지 명확하지 않습니다. 이는 스윙 시작점에서 현재 극점까지의 거리를 전체 스윙 구간 길이(현재까지의 길이)로 나눈 비율에 가까워 보입니다. 99.9% 조건은 이 극점이 거의 마지막 캔들에 있어야만 만족되어 "✔" 라벨이 거의 표시되지 않을 것입니다.
비트코인 5분봉:
결론적으로:
"가장 신뢰할 수 있는 선행 지표"는 존재하지 않습니다. 트레이딩뷰에서 비트코인 5분봉 매매에 선행적인 신호를 활용하고 싶다면, 모멘텀 오실레이터의 다이버전스, 거래량 패턴, 피보나치 레벨 등을 단독으로 사용하기보다는 종합적으로 분석하는 것이 가장 중요합니다.
예를 들어, 5분봉 차트에서 RSI가 상승 다이버전스를 보이고(잠재적 매수 신호), 동시에 해당 저점 근처에서 거래량이 유의미하게 증가했으며(매수 압력 시사), 이전 하락 파동에 대한 피보나치 되돌림 레벨(예: 0.618)에서 지지받는다면, 이러한 여러 선행/확인 신호들이 모여서 비교적 신뢰할 만한 매수 기회로 해석될 수 있습니다.
어떤 지표를 사용하든, 과거 데이터로 백테스팅을 해보고 자신에게 맞는 설정값(예: RSI나 스토캐스틱의 기간 설정)을 찾는 것이 중요합니다. 또한, 손절매 설정을 통해 예측이 틀렸을 때의 위험을 관리하는 것이 필수적입니다.
//@version=5
indicator(title="이치모쿠 자동 매수/매도 비주얼 신호", shorttitle="이치모쿠 신호", overlay=true)
// --- 입력 변수 ---
// 이치모쿠 지표의 기간 설정을 조절합니다.
tenkanPeriod = input.int(9, title="전환선 기간", minval=1) // Tenkan-sen period (usually 9)
kijunPeriod = input.int(26, title="기준선 기간", minval=1) // Kijun-sen period (usually 26)
senkouPeriod = input.int(52, title="선행 스팬 B 기간", minval=1) // Senkou Span B period (usually 52)
displacementPeriod = input.int(26, title="지연/선행 이동 기간", minval=1) // Displacement (usually 26)
// 신호 라벨의 크기를 설정합니다.
labelSize = input.string("small", title="신호 라벨 크기", options=["tiny", "small", "normal", "large", "auto"])
// --- 이치모쿠 지표 계산 ---
// 전환선: (최고가 + 최저가) / 2 over N periods
tenkan = (ta.highest(high, tenkanPeriod) + ta.lowest(low, tenkanPeriod)) / 2
// 기준선: (최고가 + 최저가) / 2 over M periods
kijun = (ta.highest(high, kijunPeriod) + ta.lowest(low, kijunPeriod)) / 2
// 선행 스팬 A: (전환선 + 기준선) / 2, X 기간 앞으로 이동
senkouA = (tenkan[displacementPeriod] + kijun[displacementPeriod]) / 2 // Calculate based on past values
// 선행 스팬 B: (최고가 + 최저가) / 2 over O periods, X 기간 앞으로 이동
senkouB = (ta.highest(high, senkouPeriod)[displacementPeriod] + ta.lowest(low, senkouPeriod)[displacementPeriod]) / 2 // Calculate based on past values
// 후행 스팬: 현재 종가, X 기간 뒤로 이동
chikou = close[displacementPeriod] // Current close plotted backward
// --- 이치모쿠 지표 플롯 (차트에 그리기) ---
plot(tenkan, color=color.blue, title="전환선")
plot(kijun, color=color.red, title="기준선")
// 구름대 (Kumo) 채우기
plotSenkouA = plot(senkouA, color=color.green, title="선행 스팬 A")
plotSenkouB = plot(senkouB, color=color.red, title="선행 스팬 B")
// 구름대 색상: 선행 A > 선행 B 이면 초록색 (상승 추세), 선행 A < 선행 B 이면 빨간색 (하락 추세)
fill(plotSenkouA, plotSenkouB, color=senkouA > senkouB ? color.new(color.green, 90) : color.new(color.red, 90), title="구름대")
plot(chikou, color=color.purple, title="후행 스팬")
// --- 매수/매도 신호 조건 정의 ---
// 신호 조건 1: 전환선이 기준선을 상향 돌파 (골든 크로스)
buySignalCondition1 = ta.crossover(tenkan, kijun)
// 신호 조건 2: 전환선이 기준선을 하향 돌파 (데드 크로스)
sellSignalCondition1 = ta.crossunder(tenkan, kijun)
// 신호 조건 3: 가격이 구름대 위에 있는지 확인 (매수 신호 신뢰성 추가)
// 참고: 여기서 `senkouA`와 `senkouB`는 현재 캔들에서 계산된 '미래'의 구름대 값입니다.
// 가격이 현재 '미래' 구름대 위에 있다는 것은 강세 추세에 있음을 시사합니다.
priceAboveKumo = close > math.max(senkouA, senkouB)
// 신호 조건 4: 가격이 구름대 아래 있는지 확인 (매도 신호 신뢰성 추가)
priceBelowKumo = close < math.min(senkouA, senkouB)
// 최종 매수 신호: 전환선 골든 크로스 AND 가격이 구름대 위
finalBuySignal = buySignalCondition1 and priceAboveKumo
// 최종 매도 신호: 전환선 데드 크로스 AND 가격이 구름대 아래
finalSellSignal = sellSignalCondition1 and priceBelowKumo
// --- 신호 발생 시 라벨 표시 ---
// 매수 신호 발생 캔들에 'BUY' 라벨 표시
if finalBuySignal
label.new(x=bar_index, y=low, // 캔들 아래쪽에 표시
text="BUY",
color=color.green, // 녹색 라벨
textcolor=color.white, // 흰색 글자
style=label.style_label_up, // 위쪽 화살표 스타일
yloc=yloc.below_bar, // 캔들 아래 고정
size=labelSize) // 사용자 지정 크기 적용
// 매도 신호 발생 캔들에 'SELL' 라벨 표시
if finalSellSignal
label.new(x=bar_index, y=high, // 캔들 위쪽에 표시
text="SELL",
color=color.red, // 빨간색 라벨
textcolor=color.white, // 흰색 글자
style=label.style_label_down, // 아래쪽 화살표 스타일
yloc=yloc.above_bar, // 캔들 위 고정
size=labelSize) // 사용자 지정 크기 적용
// 참고: 이 스크립트는 이치모쿠 기반의 자동 매수/매도 '신호'를 시각적으로 표시해주는 도구입니다.
// 표시되는 신호는 백테스팅을 거치지 않은 단순 조건 기반 신호이며,
// 실제 매매에 사용하기 전에는 반드시 충분한 검증과 테스트가 필요합니다.
// 어떤 지표나 신호도 100% 정확하지 않으므로, 다른 분석 방법과 함께 사용하고
// 항상 손절매 계획을 세우는 것이 중요합니다.
코드 사용 방법:
트레이딩뷰에서 원하는 비트코인 차트와 시간봉 (예: 5분봉)을 엽니다.
차트 하단의 Pine 에디터 탭을 클릭합니다.
위 코드를 복사하여 Pine 에디터에 붙여넣습니다.
"차트에 추가" 버튼을 클릭합니다.
설정 방법:
스크립트가 차트에 추가되면 설정 (톱니바퀴 아이콘) 버튼을 클릭합니다.
전환선 기간, 기준선 기간, 선행 스팬 B 기간, 지연/선행 이동 기간: 이치모쿠 지표의 각 선을 계산하는 데 사용되는 기간을 조절합니다. 표준 설정값은 9, 26, 52, 26입니다.
신호 라벨 크기: 차트에 표시되는 'BUY', 'SELL' 라벨의 크기를 조절합니다.
스크립트 설명:
이치모쿠 계산: 표준 공식에 따라 전환선, 기준선, 선행 스팬 A/B, 후행 스팬을 계산하고 차트에 그립니다. 구름대는 선행 스팬 A와 B 사이 영역을 채워서 표시합니다.
신호 정의:
매수 신호: 전환선이 기준선을 상향 돌파하는 시점에서, 현재 캔들의 종가가 계산된 구름대(미래 구름대 영역) 위에 있을 때 발생합니다.
매도 신호: 전환선이 기준선을 하향 돌파하는 시점에서, 현재 캔들의 종가가 계산된 구름대(미래 구름대 영역) 아래에 있을 때 발생합니다.
가격이 구름대 위에/아래에 있는 조건을 추가하여 단순 골든/데드 크로스보다 더 강한 추세에서의 신호에 집중하도록 했습니다.
라벨 표시: 위에서 정의된 매수/매도 신호 조건이 만족되는 캔들에서 해당 캔들의 저점(매수) 또는 고점(매도)에 'BUY' 또는 'SELL' 라벨을 표시합니다. 라벨의 색상, 스타일, 크기는 가독성을 높이도록 설정되었습니다.
주의 사항:
이 스크립트는 이치모쿠 지표의 특정 조건에 따라 시각적인 신호 라벨을 표시해주는 도구이며, 자동으로 주문을 실행하지 않습니다.
표시되는 신호는 이치모쿠의 여러 해석 중 하나이며, 모든 시장 상황에서 100% 정확하지 않습니다. 특히 횡보장에서는 속임수 신호가 자주 발생할 수 있습니다.
5분봉과 같은 짧은 시간봉에서는 노이즈가 많아 신호의 신뢰성이 떨어질 수 있습니다. 더 큰 시간봉에서의 추세와 함께 분석하는 것이 좋습니다.
이 지표는 트레이딩 결정에 도움을 주기 위한 참고 자료일 뿐, 재정적 조언이 아닙니다. 실제 매매 시에는 본인의 책임 하에 신중하게 판단해야 하며, 반드시 손절매 계획을 세워야 합니다.
이 스크립트를 통해 비트코인 5분봉 차트에서 이치모쿠 기반의 잠재적인 매수/매도 구간을 빠르게 시각적으로 파악하는 데 도움을 받으실 수 있습니다.
// 특징 추출 함수
extractFeatures() =>
var features = array.new_float(4)
array.clear(features)
// 신경망 예측 함수
predictPattern(features) =>
var weights = array.new_float(4)
array.clear(weights)
// 학습된 가중치 (실제로는 더 복잡한 학습 과정이 필요)
array.push(weights, 0.7) // 가격 변동성 가중치
array.push(weights, 0.3) // 거래량 가중치
array.push(weights, 0.5) // 피봇 강도 가중치
array.push(weights, 0.8) // 추세 가중치
code
sum = 0.0
for i = 0 to array.size(features) - 1
weight = array.get(weights, i)
value = array.get(features, i)
sum := sum + weight * value
sigmoid(sum)
// 변수 초기화
var array zigzagLines = array.new_line()
var line ghost_level = na
var line yellow_line = na
var label yellow_lbl = na
var float max_val = na
var float min_val = na
var int max_x1 = 0
var int min_x1 = 0
var int os = -1
var float py1 = na
var int px1 = na
var float confirmed_probability = 0.0
var float last_prediction = na
var label prediction_label = na
var array labels = array.new_label(0)
var int n = bar_index
// 메모리 관리 함수
cleanupOldElements() =>
if array.size(labels) > maxLabels
for i = 0 to array.size(labels) - maxLabels - 1 by 1
label.delete(array.get(labels, i))
array.remove(labels, 0)
code
if array.size(zigzagLines) > maxLines
for i = 0 to array.size(zigzagLines) - maxLines - 1 by 1
line.delete(array.get(zigzagLines, i))
array.remove(zigzagLines, 0)
// 라인 생성 시 위치 조정 함수
adjustBarPos(pos) =>
max_lookback = 5000 // max_bars_back 설정과 일치
math.max(math.min(pos, bar_index), bar_index - max_lookback)
// 라벨 생성 함수
createLabel(pos, price, isHigh, labelColor, styleType, sizeType) =>
var string labelText = na
var float yOffset = na
if high[length] >= max_val and not na(high[length])
max_x1 := n - length
if low[length] <= min_val and not na(low[length])
min_x1 := n - length
if not na(ghost_level)
line.set_x2(ghost_level, n)
// Pivot High 처리
if not na(ph)
if show_miss and os == 1
labelObj = createLabel(min_x1, min_val, false, miss_pl_css, label.style_label_up, label_size_normal)
if not na(labelObj)
array.push(labels, labelObj)
if show_lines and not na(px1) and not na(py1)
t1 = time[px1 - bar_index]
t2 = time[min_x1 - bar_index]
lineObj = line.new(t1, py1, t2, min_val, color = miss_pl_css, style = style_map, width = line_width, xloc = xloc.bar_time)
if not na(lineObj)
array.push(zigzagLines, lineObj)
px1 := min_x1
py1 := min_val
code
if show_reg
labelObj2 = createLabel(n - length, ph, true, reg_ph_css, label.style_label_down, label_size_normal)
if not na(labelObj2)
array.push(labels, labelObj2)
if show_lines and not na(px1) and not na(py1)
t1 = time[px1 - bar_index]
t2 = time[n - length - bar_index]
lineObj2 = line.new(t1, py1, t2, ph, color = reg_ph_css, style = style_map, width = line_width, xloc = xloc.bar_time)
if not na(lineObj2)
array.push(zigzagLines, lineObj2)
py1 := ph
px1 := n - length
os := 1
max_val := ph
min_val := ph
// Pivot Low 처리
if not na(pl)
if show_miss and os == 0
newLabel = createLabel(max_x1, max_val, true, miss_ph_css, label.style_label_down, label_size_normal)
array.push(labels, newLabel)
if show_lines
barPos1 = adjustBarPos(px1)
barPos2 = adjustBarPos(max_x1)
newLine = line.new(barPos1, py1, barPos2, max_val, color = miss_ph_css, style = style_map, width = line_width)
array.push(zigzagLines, newLine)
px1 := max_x1
py1 := max_val
// 확률 계산 및 노란색 라벨 처리
if barstate.islast
features = extractFeatures()
prediction = predictPattern(features)
last_prediction := prediction
code
if show_predictions and not na(prediction)
if not na(prediction_label)
label.delete(prediction_label)
prediction_label := na
prediction_color = prediction > nn_threshold ? color.green : color.red
prediction_text = '🤖 ' + str.tostring(prediction * 100, '#.##') + '%'
prediction_label := label.new(x = bar_index, y = high, text = prediction_text, color = prediction_color, style = label.style_label_down, textcolor = color.white, size = size.small)
// Process price data for probability calculation
var array<float> prices = array.new_float()
var array<int> prices_x = array.new_int()
var float y = na
var int x = na
var int idx = na
var string bold_length = ''
var string bold_prob = ''
if not na(px1) and not na(py1)
array.clear(prices)
array.clear(prices_x)
for i = 0 to n - px1 - 1
array.push(prices, os == 1 ? low[i] : high[i])
array.push(prices_x, n - i)
y := os == 1 ? array.min(prices) : array.max(prices)
idx := array.indexof(prices, y)
if not na(idx)
x := array.get(prices_x, idx)
confirmed_probability := (array.size(prices) - idx) / array.size(prices) * 100.0
// 기존 라벨 삭제
if not na(yellow_lbl)
label.delete(yellow_lbl)
yellow_lbl := na
// 값 업데이트
bold_length := toBoldUnicode(str.tostring(length))
bold_prob := toBoldUnicode(str.tostring(confirmed_probability, '#.##'))
// 확률 기반 라벨 생성
bool hasValid = array.size(prices) > 0 and not na(idx)
bool hasHighProb = false
bool hasValidPattern = false
if hasValid
confirmed_probability := (array.size(prices) - idx) / array.size(prices) * 100.0
hasHighProb := confirmed_probability >= 99.9
hasValidPattern := (os == 1 and y > py1) or (os == 0 and y < py1)
if hasValid and hasHighProb and hasValidPattern
var string labelText = na
var float yOffset = na
style_val = os == 1 ? label.style_label_up : label.style_label_down
color_val = os == 1 ? color.red : color.green
yOffset := label_position == 'auto' ? (os == 1 ? -last_label_offset : last_label_offset) : (label_position == 'above' ? math.abs(last_label_offset) : -math.abs(last_label_offset))
labelText := '✔ ' + bold_length + ' ' + bold_prob + '%'
// bar_index 범위 제한 및 조정
barPos = adjustBarPos(x)
yellow_lbl := label.new(x = barPos, y = y + y * yOffset / 100, text = labelText, textcolor = color_val, style = style_val, color = color_val, size = label_size_large == 'tiny' ? size.tiny : label_size_large == 'small' ? size.small : label_size_large == 'normal' ? size.normal : label_size_large == 'large' ? size.large : size.normal)
else
var string labelText = na
var float yOffset = na
style_val = os == 1 ? label.style_label_up : label.style_label_down
yOffset := label_position == 'auto' ? (os == 1 ? -last_label_offset : last_label_offset) : (label_position == 'above' ? math.abs(last_label_offset) : -math.abs(last_label_offset))
labelText := '👻 ' + bold_length + ' ' + bold_prob + '%'
// bar_index 범위 제한 및 조정
barPos = adjustBarPos(x)
yellow_lbl := label.new(x = barPos, y = y + y * yOffset / 100, text = labelText, textcolor = os == 1 ? color.red : color.green, style = style_val, color = color.yellow, size = label_size_large == 'tiny' ? size.tiny : label_size_large == 'small' ? size.small : label_size_large == 'normal' ? size.normal : label_size_large == 'large' ? size.large : size.normal)
if not na(px1) and not na(py1)
line.delete(yellow_line)
t1 = time[px1 - bar_index]
t2 = time[x - bar_index]
yellow_line := line.new(t1, py1, t2, y,
color = os == 1 ? color.red : color.green,
style = line.style_dotted,
width = int(line_width * 1.5),
xloc = xloc.bar_time)
// 메모리 정리
cleanupOldElements()
px1, py1, os 업데이트 로직: ph 또는 pl이 na가 아닐 때 px1, py1, os가 업데이트되는데, 이 로직이 Regular와 Missed 피봇 처리 안에 중복되어 있거나 혼란스럽습니다. 확정된 정규 피봇이 발생했을 때만 마지막 피봇 정보를 업데이트하도록 수정해야 합니다. 또한, Missed Pivot 로직은 복잡하며 제공된 코드만으로는 정확하게 작동하는지 판단하기 어렵습니다. 이 부분은 제거하고 정규 피봇 및 마지막 스윙 구간 추적에 집중하는 것이 코드를 단순화하고 문제를 해결하는 데 도움이 됩니다.
max_val, min_val, max_x1, min_x1 변수: 이 변수들은 주로 Missed Pivot 로직과 관련 있어 보이며, 현재 코드의 사용 방식이 명확하지 않습니다. Missed Pivot 로직을 제거한다면 이 변수들도 제거할 수 있습니다.
라인 생성 시 xloc: 라인 생성 시 time[px1 - bar_index]와 같이 시간 인덱스를 계산하는 대신, xloc=xloc.bar_time 또는 xloc=xloc.bar_index와 함께 바 인덱스 (px1, n - length 등)를 직접 전달하는 것이 표준적이고 오류를 줄입니다.
다음은 위 문제점들을 해결하고 코드를 정리한 버전입니다. 특히 신경망 부분은 개념적인 목업임을 다시 강조하고, 마지막 라벨/라인 로직을 모든 캔들에서 실행되도록 수정했습니다. Missed Pivot 로직은 제거했습니다.
pine
//@version=5
indicator('1 Pivot Points High Low v3-1 (Revised)', overlay = true, max_labels_count = 500, max_lines_count = 500, max_bars_back = 5000)
// User Inputs
length = input.int(233, 'Pivot Length')
maxLabels = input.int(50, '최대 라벨 수', minval = 1, maxval = 500) // 라벨 수를 좀 더 늘려 기본 설정
maxLines = input.int(50, '최대 라인 수', minval = 1, maxval = 500) // 라인 수를 좀 더 늘려 기본 설정
// Label Settings
show_length = input.bool(true, '라벨에 Length 표시', group = 'Label Settings')
// 라벨 위치 조정은 yloc 사용으로 대체
// label_offset = input.float(0, '일반 라벨 위치 조정', minval = -10.0, maxval = 10.0, step = 0.1, group = 'Label Settings') // 제거
// last_label_offset = input.float(0, '마지막 라벨 위치 조정', minval = -10.0, maxval = 10.0, step = 0.1, group = 'Label Settings') // 제거
// label_position = input.string('auto', '라벨 위치', options = ['auto', 'above', 'below'], group = 'Label Settings') // yloc과 조합하여 사용
show_reg = input.bool(true, 'Regular Pivots', inline = 'inline1')
reg_ph_css = input.color(color.teal, 'High', inline = 'inline1')
reg_pl_css = input.color(color.red, 'Low', inline = 'inline1')
// Missed Pivot 로직은 제거
// show_miss = input.bool(true, 'Missed Pivots', inline = 'inline2') // 제거
// miss_ph_css = input.color(color.teal, 'High', inline = 'inline2') // 제거
// miss_pl_css = input.color(color.red, 'Low', inline = 'inline2') // 제거
show_lines = input.bool(true, 'Show Lines', group = 'Line Settings')
line_width = input.int(2, 'Line Width', minval = 1, maxval = 5, group = 'Line Settings')
line_style = input.string('solid', 'Line Style', options = ['solid', 'dashed', 'dotted'], group = 'Line Settings')
style_map = line_style == 'solid' ? line.style_solid : line_style == 'dashed' ? line.style_dashed : line_style == 'dotted' ? line.style_dotted : line.style_solid
all_label_textcolor = input.color(color.rgb(245, 247, 250), 'All Labels Text Color')
label_size_normal = input.string('normal', 'Regular Label Size', options = ['tiny', 'small', 'normal', 'large'], group = 'Label Settings')
label_size_large = input.string('large', 'Last Label Size', options = ['tiny', 'small', 'normal', 'large'], group = 'Label Settings')
// Neural Network Settings (Conceptual Mockup - Not a real trained NN)
// 하드코딩된 가중치를 사용하므로 실제 예측 모델이 아님. 단순 참고용.
nn_lookback = input.int(10, '학습 기간 (개념적)', minval = 5, maxval = 50, group = 'Neural Network Settings')
nn_threshold = input.float(0.7, '예측 임계값', minval = 0.1, maxval = 1.0, step = 0.1, group = 'Neural Network Settings')
show_predictions = input.bool(true, '예측 표시', group = 'Neural Network Settings')
nn_label_offset_y = input.int(15, '예측 라벨 Y 오프셋 (px)', minval=0, group = 'Neural Network Settings')
// 굵은 유니코드 숫자 변환 함수
toBoldUnicode(strIn) =>
string result = strIn
result := str.replace_all(result, '0', '𝟬')
result := str.replace_all(result, '1', '𝟭')
result := str.replace_all(result, '2', '𝟮')
result := str.replace_all(result, '3', '𝟯')
result := str.replace_all(result, '4', '𝟰')
result := str.replace_all(result, '5', '𝟱')
result := str.replace_all(result, '6', '𝟲')
result := str.replace_all(result, '7', '𝟳')
result := str.replace_all(result, '8', '𝟴')
result := str.replace_all(result, '9', '𝟵')
result
// 정규화 함수
normalize(value, min, max) =>
range = max - min
math.max(0.0, math.min(1.0, (value - min) / math.max(range, 1e-9))) // 0~1 범위로 클램핑, 0으로 나누기 방지
// 시그모이드 활성화 함수
sigmoid(x) =>
1.0 / (1.0 + math.exp(-x))
// 특징 추출 함수 (개념적)
extractFeatures() =>
var features = array.new_float() // 빈 배열 생성
array.clear(features) // 혹시 모를 이전 데이터 클리어
// 특징 계산 (nn_lookback 기간 기준)
float high_nn = ta.highest(high, nn_lookback)
float low_nn = ta.lowest(low, nn_lookback)
float volume_nn = ta.sma(volume, nn_lookback) // 단순 평균 거래량
// 가격 변동성 (현재 high-low를 nn_lookback 기간의 high-low 범위로 정규화)
high_low_range_nn = high_nn - low_nn
high_low_ratio = normalize(high - low, 0, math.max(high_low_range_nn, 1e-9)) // 0으로 나누기 방지
// 거래량 변동성 (현재 volume과 nn_lookback 평균 volume 비교)
volume_change = normalize(volume, 0, math.max(volume_nn * 2, 1e-9)) // 대략적인 범위로 정규화
// 피봇 강도 (현재 캔들의 몸통 크기를 high-low 범위로 정규화)
pivot_strength = normalize(math.abs(close - open), 0, math.max(high - low, 1e-9)) // 0으로 나누기 방지
// 추세 방향 (nn_lookback 기간의 종가 변화를 해당 기간 가격 범위로 정규화)
price_change_nn = close - close[nn_lookback]
trend_range_nn = high_nn - low_nn
trend = normalize(price_change_nn, -math.max(trend_range_nn, 1e-9), math.max(trend_range_nn, 1e-9)) // -1~1 범위 정규화 후 0~1로 스케일링
trend := (trend + 1) / 2.0 // -1~1 -> 0~1 범위로 조정
array.push(features, high_low_ratio)
array.push(features, volume_change)
array.push(features, pivot_strength)
array.push(features, trend)
features
// 신경망 예측 함수 (개념적)
predictPattern(features) =>
// 실제 학습된 가중치 대신 예시 가중치 사용 (이 부분은 학습이 필요함)
var weights = array.new_float()
if array.size(weights) == 0 // 최초 한 번만 초기화
array.push(weights, 0.7) // 가격 변동성 가중치
array.push(weights, 0.3) // 거래량 가중치
array.push(weights, 0.5) // 피봇 강도 가중치
array.push(weights, 0.8) // 추세 가중치
sum = 0.0
for i = 0 to math.min(array.size(features), array.size(weights)) - 1 // 최소 크기만큼 반복
weight = array.get(weights, i)
value = array.get(features, i)
sum := sum + weight * value
sigmoid(sum) // 시그모이드 활성화 함수 적용 (출력값 0~1)
// 변수 초기화 및 상태 저장
var array<line> zigzagLines = array.new_line()
var line ghost_level = na // 사용되지 않는 변수로 보임 (제거 고려)
var line current_segment_line = na // 마지막 스윙 ~ 현재 극점 연결선
var label current_segment_label = na // 현재 스윙 극점 라벨
// 마지막 확정된 정규 피봇 정보
var float last_pivot_price = na
var int last_pivot_index = na
var int last_pivot_type = na // 1: High, 0: Low
// 신경망 예측 라벨 저장
var label prediction_label = na
// 일반 피봇 라벨 저장
var array<label> regular_pivot_labels = array.new_label(0)
// 메모리 관리 함수 - array.shift() 사용
cleanupOldElements() =>
// 라벨 수 제한
while array.size(regular_pivot_labels) > maxLabels
label.delete(array.shift(regular_pivot_labels)) // 가장 오래된 라벨 삭제
// 라인 수 제한
while array.size(zigzagLines) > maxLines
line.delete(array.shift(zigzagLines)) // 가장 오래된 라인 삭제
// 라벨 생성 함수
createRegularPivotLabel(pos, price, isHigh, labelColor, sizeType) =>
var string labelText = show_length ? str.tostring(length) : ''
styleType = isHigh ? label.style_label_down : label.style_label_up
ylocType = isHigh ? yloc.above_bar : yloc.below_bar
labelObj = label.new(x=pos, y=price, text=labelText, textcolor=all_label_textcolor, color=labelColor, style=styleType, yloc=ylocType,
size=sizeType == 'tiny' ? size.tiny : sizeType == 'small' ? size.small : sizeType == 'normal' ? size.normal : sizeType == 'large' ? size.large : size.normal,
xloc=xloc.bar_time) // xloc.bar_time 사용
labelObj
// 피봇 포인트 계산 - ta.pivothigh/low는 확정된 피봇의 가격을 반환
float ph = ta.pivothigh(high, length, length)
float pl = ta.pivotlow(low, length, length)
// 정규 피봇 처리
bool regularPivotConfirmed = false
if not na(ph)
if show_reg // 정규 피봇 표시 옵션 켜져 있을 때만
// 라벨 생성 및 배열에 추가
labelObj = createRegularPivotLabel(bar_index - length, ph, true, reg_ph_css, label_size_normal)
if not na(labelObj)
array.push(regular_pivot_labels, labelObj)
// 라인 생성 (이전 확정 피봇 -> 현재 확정 피봇)
if show_lines and not na(last_pivot_index) and not na(last_pivot_price)
lineObj = line.new(x1=last_pivot_index, y1=last_pivot_price, x2=bar_index - length, y2=ph,
color = last_pivot_type == 0 ? reg_pl_css : reg_ph_css, // 이전 피봇 타입에 따라 라인 색상 결정? 아니면 현재 피봇 색상? 현재 피봇 색상으로 통일
style = style_map, width = line_width, xloc = xloc.bar_time) // xloc.bar_time 사용
if not na(lineObj)
array.push(zigzagLines, lineObj)
// 마지막 확정된 정규 피봇 정보 업데이트
last_pivot_price := ph
last_pivot_index := bar_index - length
last_pivot_type := 1 // High 피봇
else if not na(pl) // High 피봇이 아니면 Low 피봇 확인
if show_reg // 정규 피봇 표시 옵션 켜져 있을 때만
// 라벨 생성 및 배열에 추가
labelObj = createRegularPivotLabel(bar_index - length, pl, false, reg_pl_css, label_size_normal)
if not na(labelObj)
array.push(regular_pivot_labels, labelObj)
// 라인 생성 (이전 확정 피봇 -> 현재 확정 피봇)
if show_lines and not na(last_pivot_index) and not na(last_pivot_price)
lineObj = line.new(x1=last_pivot_index, y1=last_pivot_price, x2=bar_index - length, y2=pl,
color = last_pivot_type == 1 ? reg_ph_css : reg_pl_css, // 이전 피봇 타입에 따라 라인 색상 결정? 현재 피봇 색상으로 통일
style = style_map, width = line_width, xloc = xloc.bar_time) // xloc.bar_time 사용
if not na(lineObj)
array.push(zigzagLines, lineObj)
// 마지막 확정된 정규 피봇 정보 업데이트
last_pivot_price := pl
last_pivot_index := bar_index - length
last_pivot_type := 0 // Low 피봇
// 현재 진행 중인 스윙 구간의 최저점/최고점 및 확률 처리 (모든 캔들에서 실행)
// 이 로직은 마지막 확정 피봇 이후의 가격 움직임을 추적합니다.
if not na(last_pivot_index) and not na(last_pivot_price)
var float extreme_price_in_segment = last_pivot_price // 현재 스윙 구간 내 극점 가격
var int extreme_index_in_segment = last_pivot_index // 현재 스윙 구간 내 극점 캔들 인덱스
// 마지막 피봇 이후의 가격 데이터에서 최저점(High 피봇 이후) 또는 최고점(Low 피봇 이후) 찾기
// 루프는 마지막 확정 피봇 다음 캔들부터 현재 캔들까지 역순으로 탐색
float current_extreme = na
int current_extreme_index = na
int bars_since_last_pivot = bar_index - last_pivot_index
if bars_since_last_pivot > 0 // 마지막 피봇이 현재 캔들보다 이전에 있을 때만
if last_pivot_type == 1 // 마지막 피봇이 High 였다면 -> 이후 최저점 찾기 (하락 스윙)
current_extreme = low[0] // 현재 low부터 시작
current_extreme_index = bar_index
for i = 1 to math.min(bars_since_last_pivot, length * 2) // 최근 length*2 캔들 또는 전체 구간 탐색 (과도한 루프 방지)
if bar_index - i <= last_pivot_index // 마지막 피봇 캔들까지 도달하면 중단
break
if low[i] < current_extreme
current_extreme = low[i]
current_extreme_index = bar_index - i
// 최저점이 마지막 피봇 가격보다 내려갔는지 확인 (필요하다면)
// bool isValidSegmentExtreme = current_extreme < last_pivot_price // 예시 조건
else if last_pivot_type == 0 // 마지막 피봇이 Low 였다면 -> 이후 최고점 찾기 (상승 스윙)
current_extreme = high[0] // 현재 high부터 시작
current_extreme_index = bar_index
for i = 1 to math.min(bars_since_last_pivot, length * 2) // 최근 length*2 캔들 또는 전체 구간 탐색
if bar_index - i <= last_pivot_index // 마지막 피봇 캔들까지 도달하면 중단
break
if high[i] > current_extreme
current_extreme = high[i]
current_extreme_index = bar_index - i
// 최고점이 마지막 피봇 가격보다 올라갔는지 확인 (필요하다면)
// bool isValidSegmentExtreme = current_extreme > last_pivot_price // 예시 조건
// 극점 정보 업데이트
// 현재 캔들이거나, 이전 극점보다 더 극심한 값일 때 업데이트
bool isNewExtreme = false
if last_pivot_type == 1 // 하락 스윙 중, 더 낮은 저점 발견 시
if na(extreme_price_in_segment) or extreme_price_in_segment > current_extreme
isNewExtreme = true
else if last_pivot_type == 0 // 상승 스윙 중, 더 높은 고점 발견 시
if na(extreme_price_in_segment) or extreme_price_in_segment < current_extreme
isNewExtreme = true
// 마지막 캔들에서의 극점 정보만 표시
if barstate.islast // 현재 캔들에서만 최신 극점 정보 표시
if not na(current_extreme) and not na(current_extreme_index)
extreme_price_in_segment := current_extreme
extreme_index_in_segment := current_extreme_index
else // 과거 캔들에서는 현재 캔들 극점 정보를 업데이트하지 않음
// 과거 캔들에서는 해당 캔들 시점에서의 극점을 계산해야 하지만, 이는 복잡하므로 마지막 캔들 정보만 사용하거나 로직을 수정해야 함.
// 여기서는 단순화를 위해 마지막 캔들에서만 극점 라벨과 선을 그립니다.
pass // 또는 과거 캔들 로직 추가
// 확률 계산 (개념적 - 마지막 피봇 ~ 현재까지의 구간 내에서 극점의 위치 비율)
// 이 확률 계산은 신경망 예측과는 별개입니다.
float confirmed_probability_segment = 0.0
if bars_since_last_pivot > 0 and not na(extreme_index_in_segment) and extreme_index_in_segment >= last_pivot_index
// 극점이 마지막 피봇 캔들 이후에 발생했을 때만 유효
distance_to_extreme = extreme_index_in_segment - last_pivot_index
confirmed_probability_segment := (float(distance_to_extreme) / math.max(float(bars_since_last_pivot), 1e-9)) * 100.0 // 마지막 피봇으로부터의 거리 비율
// 기존 라벨 및 선 삭제
if not na(current_segment_label)
label.delete(current_segment_label)
current_segment_label := na
if not na(current_segment_line)
line.delete(current_segment_line)
current_segment_line := na
// 라벨 및 선 생성 (마지막 캔들에서만 표시)
if barstate.islast and not na(extreme_index_in_segment) and not na(extreme_price_in_segment)
var string bold_length = toBoldUnicode(str.tostring(length))
var string bold_prob = toBoldUnicode(str.tostring(confirmed_probability_segment, '#.##'))
// 신경망 예측 결과 (last_prediction은 if show_predictions 블록에서 업데이트됨)
float current_nn_prediction = nz(last_prediction, 0.0) // na일 경우 0으로 처리
bool nn_prediction_is_bullish = current_nn_prediction > nn_threshold // 예측 임계값 사용
// 라벨 텍스트 및 색상 결정
string labelText = ''
color labelColor = color.yellow // 기본은 노란색
color textColor = color.black // 기본 글자색
bool isBullishSegment = last_pivot_type == 0 // 마지막 피봇이 Low면 상승 스윙
if show_predictions // 예측 표시 옵션이 켜져 있으면 예측 결과 반영
if nn_prediction_is_bullish // 신경망 예측이 강세 (상승 확률 높음)
labelText := (isBullishSegment ? '👍' : '❓') + ' NN: ' + str.tostring(current_nn_prediction * 100, '#.##') + '%'
labelColor := color.green // 강세 예측 시 녹색 계열
textColor = color.white
else // 신경망 예측이 약세 (하락 확률 높음)
labelText := (isBullishSegment ? '❓' : '👎') + ' NN: ' + str.tostring(current_nn_prediction * 100, '#.##') + '%'
labelColor := color.red // 약세 예측 시 빨간색 계열
textColor = color.white
else // 예측 표시 옵션이 꺼져 있으면 세그먼트 진행도 확률만 표시
labelText := '👻 ' + bold_length + ' ' + bold_prob + '%'
labelColor := isBullishSegment ? color.green : color.red // 스윙 방향에 따라 색상
// 라벨 위치 및 스타일
style_val = isBullishSegment ? label.style_label_up : label.style_label_down
yloc_val = isBullishSegment ? yloc.below_bar : yloc.above_bar
// 라벨 생성 (마지막 캔들에서만)
current_segment_label := label.new(x = extreme_index_in_segment, y = extreme_price_in_segment, text = labelText, textcolor = textColor,
style = style_val, color = labelColor, size = label_size_large == 'tiny' ? size.tiny : label_size_large == 'small' ? size.small : label_size_large == 'normal' ? size.normal : label_size_large == 'large' ? size.large : size.normal,
xloc = xloc.bar_time, yloc = yloc_val, yoffset = isBullishSegment ? nn_label_offset_y : -nn_label_offset_y)
// 라인 생성 (마지막 캔들에서만)
lineColor = show_predictions ? (nn_prediction_is_bullish ? color.green : color.red) : (isBullishSegment ? color.green : color.red) // 예측 또는 스윙 방향에 따라 색상
current_segment_line := line.new(x1 = last_pivot_index, y1 = last_pivot_price, x2 = extreme_index_in_segment, y2 = extreme_price_in_segment,
color = lineColor, style = line.style_dotted, width = int(line_width * 1.5), xloc = xloc.bar_time)
// 신경망 예측 라벨 (마지막 캔들에서만 표시)
if barstate.islast and show_predictions
features = extractFeatures() // 현재 캔들의 특징 추출
last_prediction := predictPattern(features) // 예측 수행
if not na(last_prediction)
if not na(prediction_label)
label.delete(prediction_label)
prediction_label := na
prediction_color = last_prediction > nn_threshold ? color.green : color.red
prediction_text = 'NN Pred: ' + str.tostring(last_prediction * 100, '#.##') + '%'
prediction_label := label.new(x = bar_index, y = high, text = prediction_text, color = prediction_color, style = label.style_label_down, textcolor = color.white, size = size.small, yloc = yloc.above_bar, yoffset = nn_label_offset_y) // 캔들 위에 표시, Y 오프셋 적용
// 메모리 정리 (각 캔들 끝에서 실행)
cleanupOldElements()
// 참고: 이 스크립트의 신경망 부분은 실제 학습된 모델이 아니라 개념적 목업입니다.
// 예측 결과는 단순 계산에 기반하며 실제 시장 예측에 사용할 수 없습니다.
// 표시되는 피봇 및 라벨은 기술적 분석에 참고용으로 활용하되,
// 실제 트레이딩 결정은 신중하게 여러 분석과 함께 내려야 합니다.
// Missed Pivot 로직은 복잡성으로 인해 제거되었으며, 필요하다면 별도로 구현해야 합니다.
수정된 내용 요약:
n 변수를 제거하고 bar_index를 직접 사용하도록 변경했습니다.
adjustBarPos 함수를 제거하고 라벨/라인 생성 시 xloc.bar_time과 바 인덱스를 사용하도록 변경했습니다.
cleanupOldElements 함수에서 array.remove(..., 0) 대신 array.shift()를 사용하여 메모리 관리를 개선했습니다.
createRegularPivotLabel 함수에서 가격 기반 Y 오프셋 계산을 제거하고 yloc.above_bar/yloc.below_bar에 의존하도록 수정했습니다.
Missed Pivot 관련 로직 및 변수 (show_miss, miss_ph_css, miss_pl_css, max_val, min_val, max_x1, min_x1)를 제거하여 코드를 단순화하고 정규 피봇 및 현재 스윙 구간 추적에 집중했습니다.
last_pivot_price, last_pivot_index, last_pivot_type 변수를 사용하여 마지막 확정된 정규 피봇 정보를 정확히 추적하도록 수정했습니다.
"확률 계산 및 노란색 라벨 처리" 블록을 if barstate.islast 밖으로 이동하여 모든 캔들에서 현재 스윙 구간의 극점(extreme_price_in_segment, extreme_index_in_segment)을 추적하도록 했습니다. 다만, 라벨과 라인은 가독성을 위해 기본적으로 마지막 캔들에서만 표시되도록 유지했습니다 (if barstate.islast).
신경망 예측 (predictPattern)은 여전히 하드코딩된 가중치를 사용하며, 그 결과를 마지막 캔들에서 별도의 라벨로 표시하거나 현재 스윙 구간 라벨/선의 색상 결정에 활용하도록 변경했습니다. 신경망 라벨에 Y 오프셋 입력 변수를 추가했습니다.
"확률" 계산 로직은 마지막 피봇 이후 구간에서 극점이 발생한 바 인덱스의 상대적인 위치를 나타내도록 수정하고, 그 의미를 코드 내 주석으로 설명했습니다. 이 값이 99.9% 이상이라는 조건은 제거하고 항상 계산된 확률을 라벨에 표시합니다.
신경망 특징 추출 및 예측 함수에 대한 주석을 추가하여 이것이 개념적 목업임을 명확히 했습니다.
normalize 함수에서 0으로 나누기 오류를 방지하고 0~1 범위로 클램핑하도록 개선했습니다.
라벨 및 라인 배열의 초기 max_labels_count 및 max_lines_count를 입력 변수 기본값과 일치하도록 500으로 설정했습니다.
이 수정된 코드는 원래 코드의 의도를 최대한 살리면서 발견된 문제점들을 해결했습니다. 하지만 신경망 부분은 여전히 단순 계산이며, 실제 트레이딩에 사용하기 전에는 반드시 충분한 테스트와 검증이 필요합니다.