커뮤니티

예스랭귀지 Q&A

글쓰기

오말리 님에 의해서 삭제되었습니다.

프로필 이미지
오말리
2025-10-27
25
글번호 227327
종목검색
답변완료

문의

indicator('Consolidation Range with Signals (Zeiierman)', overlay=true, max_labels_count = 500, max_lines_count = 500) //~~}// ~~ Tooltips { var string t1 = "Select the method used for detecting ranging market conditions.\n\n ADX: Uses the Average Directional Index to identify non-trending periods when ADX is below a set threshold.\n\n Volatility: Detects ranges by identifying periods of compression in volatility using standard deviation, variance, and ATR filters.\n\n Price Action: Confirms range by measuring the high-low percentage contraction and requiring a minimum number of DMI crosses, suggesting indecision or balance in price action." var string t2 = "Length or period used for detecting the range." var string t3 = "Multiplier applied to the calculated band distance." var string t4 = "Toggle to display Take Profit and Stop Loss levels on the chart." var string t5 = "Minimum number of bars between two consecutive SL/TP entries." var string t6 = "Stop Loss multiplier from the filtered base value." var string t7 = "Take Profit 1 multiplier from the filtered base value." var string t8 = "Take Profit 2 multiplier from the filtered base value." var string t9 = "Take Profit 3 multiplier from the filtered base value." var string t10 = "ADX threshold under which the market is considered ranging." var string t11 = "Smoothing period used for the ADX calculation." var string t12 = "Standard deviation compression threshold used to detect low volatility." var string t13 = "Variance compression threshold used to detect low volatility." var string t14 = "ATR compression threshold used to detect low volatility." //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Inputs { // ~~ Range { method = input.string("ADX", options=["ADX", "Volatility"], title="Range Detection Method", group="Range Detection", tooltip=t1) len = input.int(10, minval=2, title="Range Period", group="Range Detection", tooltip=t2) band_mult = input.float(1.8, step=0.1, minval=0.01,title="Range Multiplier", group="Range Detection", tooltip=t3) upper_col = input.color(#0060e6, title="Range", group="Range Detection", inline="bandcol") lower_col = input.color(#29fafa, title="", group="Range Detection", inline="bandcol") pos_col = input.color(#0060e6, title="Trend", group="Range Detection", inline="trendcol") neg_col = input.color(#29fafa, title="", group="Range Detection", inline="trendcol") //~~} // ~~ SL/TP { showTP = input.bool(true, title="Show SL/TP Levels", group="Targets", tooltip=t4) cooldown = input.int(20, title="SL/TP Cooldown (Bars)", group="Targets", tooltip=t5) sl_mult = input.float(0.4, step=0.1, minval=0.01,title="SL", group="Targets", inline="sl", tooltip=t6) showsl = input.bool(true, title="", group="Targets", inline="sl", tooltip=t6) tp1_mult = input.float(0.5, step=0.1, minval=0.01,title="TP1", group="Targets", inline="tp1", tooltip=t7) showtp1 = input.bool(true, title="", group="Targets", inline="tp1", tooltip=t7) tp2_mult = input.float(1.0, step=0.1, minval=0.01,title="TP2", group="Targets", inline="tp2", tooltip=t8) showtp2 = input.bool(false, title="", group="Targets", inline="tp2", tooltip=t8) tp3_mult = input.float(2.0, step=0.1, minval=0.01,title="TP3", group="Targets", inline="tp3", tooltip=t9) showtp3 = input.bool(false, title="", group="Targets", inline="tp3", tooltip=t9)entry_col = input.color(color.blue, title="Entry", group="Targets", inline="tpcol") sl_col = input.color(#ff0000, title="SL", group="Targets", inline="tpcol") bullColor = input.color(#09c10f, title="TP", group="Targets", inline="tpcol") bearColor = input.color(#ff69cb, title="", group="Targets", inline="tpcol") //~~} // ~~ ADX { adx_thresh = input.int(17, step=1, minval=0,title="ADX Threshold", group="ADX", tooltip=t10) adx_smooth = input.int(10, step=1, minval=0,title="ADX Smoothing", group="ADX", tooltip=t11) //~~} // ~~ Volatility { vol_mult_std = input.float(0.8, step=0.1, minval=0.001, title="StdDev Multiplier", group="Volatility", tooltip=t12) vol_mult_var = input.float(0.8, step=0.1, minval=0.001,title="Variance Multiplier", group="Volatility", tooltip=t13) vol_mult_atr = input.float(0.9, step=0.1, minval=0.001,title="ATR Multiplier", group="Volatility", tooltip=t14) //~~} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ ADX { [_, _, adx] = ta.dmi(len, adx_smooth) isADX = adx < adx_thresh //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Volatility Compression { logret = math.log(close / close[1]) std_now = ta.stdev(logret, len) std_avg = ta.sma(std_now, len) atr_now = ta.atr(len) atr_avg = ta.sma(atr_now, len) var_now = ta.variance(logret, len) var_avg = ta.sma(var_now, len) isVolatility = std_now < std_avg * vol_mult_std and var_now < var_avg * vol_mult_var and atr_now < atr_avg * vol_mult_atr //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Switch { methodDetected = (method == "ADX" and isADX) or (method == "Volatility" and isVolatility) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Var { var float rngfilt = close var color trendColor = na var bool rangeVisible = false var float prev_hi = na var float prev_lo = na var int rangeStartBar = na var int rangeBarsActive = 0 var int lastBreakoutBar = naif methodDetected and na(rangeStartBar) rangeStartBar := bar_index else if not methodDetected rangeStartBar := naif methodDetected rangeVisible := true //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Range Calculation { diff = math.abs(high - low[1]) r = ta.sma(2.618 * diff, 2000) * band_mult //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Range Calculation Functions { pricejump(prev) => highJump = prev + math.abs(close - prev) / r * r lowJump = prev - math.abs(close - prev) / r * r [highJump, lowJump]rangefilter(hhjump, lljump, prev) => hhBreak = close > prev hhTooClose = close - r < prev hhShift = close - r llTooClose = close + r > prev llShift = close + r step1 = hhBreak ? (hhTooClose ? prev : hhShift) : (llTooClose ? prev : llShift) hhAbove = close >= prev + r llBelow = close <= prev - r hhAbove ? hhjump : llBelow ? lljump : step1bands(filt) => [filt + r, filt - r] trenddir(filt) => [filt > nz(filt[1]), filt < nz(filt[1])] trendcomp(filt) => [filt, ta.sma(filt, 2), ta.sma(filt, 4)]prev = nz(rngfilt[1]) [hhJ, llJ] = pricejump(prev) rngfilt := rangefilter(hhJ, llJ, prev) prev_rngfilt = nz(rngfilt[1]) rngfilt_step_up = rngfilt > prev_rngfilt rngfilt_step_down = rngfilt < prev_rngfilt[hiband, loband] = bands(rngfilt) [up, down] = trenddir(rngfilt) [TrendFast, TrendMed, TrendLong] = trendcomp(rngfilt)if methodDetected prev_hi := hiband prev_lo := lobandif not methodDetected and (close[1] > prev_hi or close[1] < prev_lo) rangeVisible := falseMIDX1 = (hiband - rngfilt) / 3 MID1 = rngfilt + MIDX1 MID2 = MID1 + MIDX1 MIDX2 = (rngfilt - loband) / 3 MID3 = rngfilt - MIDX2 MID4 = MID3 - MIDX2 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Plot { trendColor := up ? pos_col : down ? neg_col : trendColor[1] plotTrend = plot(rangeVisible ? TrendFast : close, "Trend", rangeVisible ? trendColor:color.new(trendColor,100), 1)plotMid1 = plot(rangeVisible ? MID1 : close, "MID1", rangeVisible ?color.new(upper_col, 50):color.new(upper_col, 100), style= plot.style_stepline) plotMid2 = plot(rangeVisible ? MID2 : close, "MID2", rangeVisible ?color.new(upper_col, 50):color.new(upper_col, 100), style= plot.style_stepline) plotMid3 = plot(rangeVisible ? MID3 : close, "MID3", rangeVisible ?color.new(lower_col, 50):color.new(lower_col, 100), style= plot.style_stepline) plotMid4 = plot(rangeVisible ? MID4 : close, "MID4", rangeVisible ?color.new(lower_col, 50):color.new(lower_col, 100), style= plot.style_stepline) fill(plotMid2, plotTrend, MID2, TrendFast, color.new(upper_col, 60),na) fill(plotMid4, plotTrend, MID4, TrendFast, color.new(lower_col, 60),na) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ TP and SL { rangeBarsActive := na(rangeStartBar) ? 0 : bar_index - rangeStartBar canTriggerBreakout = (na(lastBreakoutBar) or bar_index - lastBreakoutBar >= cooldown) enterLong = rangeVisible and rngfilt_step_up and canTriggerBreakout enterShort = rangeVisible and rngfilt_step_down and canTriggerBreakoutcalcSLTP(isLong) => base = rngfilt offset = r * sl_mult tp1off = r * tp1_mult tp2off = r * tp2_mult tp3off = r * tp3_mult stop_ = isLong ? base - offset : base + offset tp1_ = isLong ? base + tp1off : base - tp1off tp2_ = isLong ? base + tp2off : base - tp2off tp3_ = isLong ? base + tp3off : base - tp3off [stop_, tp1_, tp2_, tp3_]drawLevels(entry, sl, tp1, tp2, tp3, col) => if showTP line.new(bar_index, entry, bar_index + 20, entry, color=entry_col, width=2) if showsl line.new(bar_index, sl, bar_index + 20, sl, color=color.new(sl_col, 0), width=2) if showtp1 line.new(bar_index, tp1, bar_index + 20, tp1, color=color.new(col, 0), width=2) if showtp2 line.new(bar_index, tp2, bar_index + 20, tp2, color=color.new(col, 0), width=2) if showtp3 line.new(bar_index, tp3, bar_index + 20, tp3, color=color.new(col, 0), width=2) if showTP label.new(bar_index+ 20, entry, "Entry", style=label.style_label_left, color=entry_col, textcolor=color.white, size = size.tiny) if showsl label.new(bar_index+ 20, sl, "SL", style=label.style_label_left, color=color.new(sl_col, 0), textcolor=color.white, size = size.tiny) if showtp1 label.new(bar_index+ 20, tp1, "TP 1", style=label.style_label_left, color=color.new(col, 0), textcolor=color.white, size = size.tiny) if showtp2 label.new(bar_index+ 20, tp2, "TP 2", style=label.style_label_left, color=color.new(col, 0), textcolor=color.white, size = size.tiny) if showtp3 label.new(bar_index+ 20, tp3, "TP 3", style=label.style_label_left, color=color.new(col, 0), textcolor=color.white, size = size.tiny)var float SL = na var float TP1 = na var float TP2 = na var float TP3 = naif enterLong and showTP and (na(lastBreakoutBar) or bar_index - lastBreakoutBar >= cooldown) [s, t1_, t2_, t3_] = calcSLTP(true) SL := s, TP1 := t1_, TP2 := t2_, TP3 := t3_ drawLevels(close, SL, TP1, TP2, TP3, bullColor) lastBreakoutBar := bar_indexif enterShort and showTP and (na(lastBreakoutBar) or bar_index - lastBreakoutBar >= cooldown) [s, t1_, t2_, t3_] = calcSLTP(false) SL := s, TP1 := t1_, TP2 := t2_, TP3 := t3_ drawLevels(close, SL, TP1, TP2, TP3, bearColor) lastBreakoutBar := bar_index //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} 예스로 부탁드립니다
프로필 이미지
레전드
2025-10-27
112
글번호 227326
지표
답변완료

조건검색 문의

//@version=5 indicator("Middle Line Breakout from RSI Shift Zone", overlay=true)// --------------------------------------------------------------------------------------------------------------------{ // Middle Line Calculation from RSI Shift Zone rsi_len = input.int(14, "RSI length") upper_level = input.int(70, "Upper RSI Level", minval = 50) lower_level = input.int(30, "Lower RSI Level", maxval = 50) min_channel_len = input.int(15, "Minimal bars length of the channel")var start = int(na) var trigger = false var float upper = na var float lower = na var channel_color = color(na)rsi = ta.rsi(close, rsi_len)channel_upper = ta.crossover(rsi, upper_level) and not trigger channel_lower = ta.crossunder(rsi, lower_level) and not triggerif channel_upper or channel_lower start := bar_index trigger := true upper := high lower := lowif bar_index-start >= min_channel_len trigger := falsetrigger_change = channel_upper != channel_upper[1] or channel_lower != channel_lower[1]// Middle Line Calculation middle_line = trigger_change ? na : math.avg(upper, lower) // --------------------------------------------------------------------------------------------------------------------}// --------------------------------------------------------------------------------------------------------------------{ // Middle Line Breakout Signals middle_line_breakout_up = ta.crossover(close, middle_line) middle_line_breakout_down = ta.crossunder(close, middle_line)// Plot Middle Line plot(middle_line, "Middle Line", color=color.blue, linewidth=2)// Plot Breakout Signals plotshape(middle_line_breakout_up, "Breakout Up", shape.triangleup, location.belowbar, color=color.green, size=size.small) plotshape(middle_line_breakout_down, "Breakout Down", shape.triangledown, location.abovebar, color=color.red, size=size.small)// Alerts alertcondition(middle_line_breakout_up, "Middle Line Breakout Up", "Middle Line Bullish Breakout") alertcondition(middle_line_breakout_down, "Middle Line Breakout Down", "Middle Line Bearish Breakout") // --------------------------------------------------------------------------------------------------------------------}위 트뷰 신호 스크립트를 예스트레이더 검색기로 만들어 주시면 감사드리겠습니다 (__)2번째 트뷰 스크립트 신호 요청 식 //@version=5indicator("Upper Line from RSI Shift Zone", overlay=true)// --------------------------------------------------------------------------------------------------------------------{// Upper Line Calculation from RSI Shift Zonersi_len = input.int(14, "RSI length")upper_level = input.int(70, "Upper RSI Level", minval = 50)lower_level = input.int(30, "Lower RSI Level", maxval = 50)min_channel_len = input.int(15, "Minimal bars length of the channel")var start = int(na)var trigger = falsevar float upper = navar float lower = navar channel_color = color(na)rsi = ta.rsi(close, rsi_len)channel_upper = ta.crossover(rsi, upper_level) and not triggerchannel_lower = ta.crossunder(rsi, lower_level) and not triggerif channel_upper or channel_lower start := bar_index trigger := true upper := high lower := lowif bar_index-start >= min_channel_len trigger := falsetrigger_change = channel_upper != channel_upper[1] or channel_lower != channel_lower[1]// Upper Line Calculationupper_line = trigger_change ? na : upper// --------------------------------------------------------------------------------------------------------------------}// --------------------------------------------------------------------------------------------------------------------{// Upper Line Breakout Signalsupper_line_breakout_up = ta.crossover(close, upper_line)upper_line_breakout_down = ta.crossunder(close, upper_line)// Plot Upper Lineplot(upper_line, "Upper Line", color=color.red, linewidth=2)// Plot Breakout Signalsplotshape(upper_line_breakout_up, "Upper Breakout Up", shape.triangleup, location.belowbar, color=color.green, size=size.small)plotshape(upper_line_breakout_down, "Upper Breakout Down", shape.triangledown, location.abovebar, color=color.red, size=size.small)// Alertsalertcondition(upper_line_breakout_up, "Upper Line Breakout Up", "Upper Line Bullish Breakout")alertcondition(upper_line_breakout_down, "Upper Line Breakout Down", "Upper Line Bearish Breakout")// Optional: Display current upper line valuevar label upper_label = naif not na(upper_line) if na(upper_label) upper_label := label.new(bar_index, upper_line, "U: " + str.tostring(math.round(upper_line, 2)), style=label.style_label_left, color=color.red, textcolor=color.white, size=size.small) else label.set_xy(upper_label, bar_index, upper_line) label.set_text(upper_label, "U: " + str.tostring(math.round(upper_line, 2)))// --------------------------------------------------------------------------------------------------------------------}위 스크립트는 첫번째 요청 스크립트와 약간 다른 스크립트입니다. 위 2번째 스크립트 또한 예스트레이더 검색기로 변환시켜주시면 감사드리겠습니다 (__)
프로필 이미지
사공하늘
2025-10-27
81
글번호 227325
검색
답변완료

종목검색식 부탁드림니다.

항상 노고에 감사드림니다.아래의 수식을 종목검색식으로 부탁드림니다.SHORT = MA(VOLUME,12);LONG = MA(VOLUME,26);VO = ((SHORT - LONG) / LONG) * 100;MA60 = MA(VO,60);PMA60 = MA(CLOSE,60);Signal2 = (VO > 0) AND (REF(VO,1) <= 0) AND (CLOSE > PMA60) AND (VO > MA60);Signal2;
프로필 이미지
존슨비치
2025-10-26
94
글번호 227321
종목검색
답변완료

문의드립니다

현재 가격이 아래의 라인을 돌파하는 종목의 검색식 부탁 드립니다. 조건up = L > H(2) * ( 1 + ratio/100) && L > H(1) && L(1) < H(2);A = ValueWhen(1, 조건up, L);조건dn = L(2) > H * ( 1 + ratio/100) && L(2) < H(1) && L(1) < H;B = ValueWhen(1, 조건dn, H);K = if(조건up, A, if(조건dn, B, 0));ValueWhen(1, 조건up or 조건dn, K)* 지표조건 Ratio 3감사합니다.
프로필 이미지
ikksoo
2025-10-26
83
글번호 227320
종목검색
답변완료

번호 추가 좀 요청 드림니다.

ㅇ 매번 도움에 고맙습니다. ㅇ 아래 수식에서 그림 처럼 선이 생기면 번호 부여좀 부탁 드림니다. ㅇ 글자크기 : 30 이상 상승 빨강색 하락 블루 ## 아래 수식 var : TX(0); input : P(20),n(5),틱(20), 굵기(5); var : cnt(0),LL(0),HH(0); Array : LTL[10](0),HTL[10](0),LI[10](0),HI[10](0),Lv[10](0),Hv[10](0);; var : LTL1(0),LTL2(0),LTL3(0),LTL4(0),LTL5(0),LTL6(0); var : HTL1(0),HTL2(0),HTL3(0),HTL4(0),HTL5(0),HTL6(0); if L < Lowest(L,P)[1] and (LL == 0 or (LL > 0 and abs(L-LL) >= PriceScale*틱)) Then { LL = L; For cnt = 9 DownTo 1 { LTL[cnt] = LTL[cnt-1]; Li[cnt] = Li[cnt-1]; Lv[cnt] = Lv[cnt-1]; } LTL[0] = TL_new(sDate,sTime,LL-PriceScale*0,NextBarSdate,NextBarStime,LL-PriceScale*0); Lv[0] = LL; Li[0] = Index; TL_SetColor(LTL[0],RgB(0,0,0)); TL_SetSize(LTL[0],굵기); TL_Delete(LTL[n]); } Else { TL_SetEnd(LTL[0],NextBarSdate,NextBarStime,LL[0]-PriceScale*0); } if H > highest(H,P)[1] and (HH == 0 or (HH > 0 and abs(H-HH) >= PriceScale*틱)) Then { HH = H; For cnt = 9 DownTo 1 { HTL[cnt] = HTL[cnt-1]; Hi[cnt] = Hi[cnt-1]; Hv[cnt] = Hv[cnt-1]; } HTL[0] = TL_new(sDate,sTime,HH+PriceScale*0,NextBarSdate,NextBarStime,HH+PriceScale*0); Hv[0] = HH+PriceScale*0; Hi[0] = Index; TL_SetColor(HTL[0],RgB(255,0,0)); TL_SetSize(HTL[0],굵기); TL_Delete(HTL[n]); } Else { TL_SetEnd(HTL[0],NextBarSdate,NextBarStime,HH+PriceScale*0); } For cnt = 1 to n-1 { if LL[cnt] > 0 and Index <= Li[cnt]+5 Then TL_SetEnd(LTL[cnt],NextBarSdate,NextBarStime,Lv[cnt]); if HH[cnt] > 0 and Index <= Hi[cnt]+5 Then TL_SetEnd(HTL[cnt],NextBarSdate,NextBarStime,Hv[cnt]); } ㅇ 고맙습니다.
프로필 이미지
요타
2025-10-26
89
글번호 227319
지표
답변완료

K-means 클러스터링(K-means clustering)

5일(기본입력값) 고가 돌파매수 저가 이탈매도 지표식을 AI(클러스터링) 방식으로 동적으로 선택하도록 설계한 예스트레이더용 구현 템플릿을 AI 질문했더니아래처럼 제공했습니다만 예스랭귀지에 사용 부적합인지라iM증권 예스트레이더에 부합하는 코드로 변환을 부탁드립니다.// === 입력값 ===input minN = 3input maxN = 10input stepN = 1input perfMemory = 10 // 지수평활(미사용 시 단순평가)input fromCluster = "Best" // "Best" / "Average" / "Worst"input maxIter = 100input maxBars = 1000 // 과거 평가용 봉 수input defaultN = 5 // 안전 기본값// === 후보 N 목록 생성 ===var array<int> candN = array.new()for n = minN to maxN step stepN array.push(candN, n)endfor// === 각 후보의 퍼포먼스 계산 (단순 누적 수익) ===var array<float> perfList = array.new()var array<int> factorList = array.new()// 현재 BAR_COUNT(플랫폼에 따라 이름 다를 수 있음)barsToEvaluate = min(barcount(), maxBars)// for each candidate N, 시뮬레이션for idx = 0 to array.size(candN)-1 N = array.get(candN, idx) cash = 0.0 position = 0 // 0=flat, 1=long entry_price = 0.0 // 시간 흐름: 오래된 -> 최신 (플랫폼 루프 방법에 따라 조정) // 여기서는 i는 과거 offset (barsToEvaluate downto 1) for offset = barsToEvaluate down to 1 // 전봉 기준 N기간 최고/최저 (함수명: HHV / LLV 또는 highest/lowest 로 바꿔서 사용) hh = HHV(high, N, offset) // = offset번째 시점에서의 N기간 최고 (함수명 확인 필요) ll = LLV(low, N, offset) // 현재 바의 종가 (offset 시점) c = ref(close, offset) // 진입: 종가가 전봉 기준 N기간 최고 돌파 (전략 규칙) if position == 0 and c > hh position = 1 entry_price = c endif // 청산: 포지션 중 저가 이탈 if position == 1 and c < ll profit = c - entry_price cash = cash + profit position = 0 entry_price = 0.0 endif endfor // 시뮬레이션 종료 시 미청산 포지션 정리(평가 목적) if position == 1 last_close = close // 최신 종가 cash = cash + (last_close - entry_price) endif array.push(perfList, cash) array.push(factorList, N)endfor// === 퍼포먼스 값에서 초기 centroid 계산 (25/50/75 percentile) ===// 플랫폼에 percentile 함수가 없다면 간단 정렬 후 인덱스로 대체 가능perf_sorted = array.copy(perfList)array.sort(perf_sorted) // 오름차순sizeP = array.size(perf_sorted)p25_idx = max(0, floor(0.25 * (sizeP - 1)))p50_idx = max(0, floor(0.50 * (sizeP - 1)))p75_idx = max(0, floor(0.75 * (sizeP - 1)))centroids = array.new()array.push(centroids, array.get(perf_sorted, p25_idx))array.push(centroids, array.get(perf_sorted, p50_idx))array.push(centroids, array.get(perf_sorted, p75_idx))// === K-means 1D 반복 ===for iter = 1 to maxIter // 초기화 clusters_perf = array.from(array.new(), array.new(), array.new()) clusters_factor = array.from(array.new(), array.new(), array.new()) // 할당 단계 for i = 0 to array.size(perfList)-1 val = array.get(perfList, i) // 거리 계산 d0 = abs(val - array.get(centroids, 0)) d1 = abs(val - array.get(centroids, 1)) d2 = abs(val - array.get(centroids, 2)) // 가장 작은 거리 인덱스 선택 idx_min = 0 if d1 < d0 idx_min = 1 if d2 < d1 idx_min = 2 endif else if d2 < d0 idx_min = 2 endif endif // 클러스터에 추가 array.push(array.get(clusters_perf, idx_min), val) array.push(array.get(clusters_factor, idx_min), array.get(factorList, i)) endfor // 중심 재계산 new_centroids = array.new() for k = 0 to 2 cperf = array.get(clusters_perf, k) if array.size(cperf) > 0 sumv = 0.0 for j = 0 to array.size(cperf)-1 sumv = sumv + array.get(cperf, j) endfor avgv = sumv / array.size(cperf) array.push(new_centroids, avgv) else // 빈 클러스터는 기존 centroid 유지 array.push(new_centroids, array.get(centroids, k)) endif endfor // 수렴 체크 (모두 같다면 종료) if array.get(new_centroids,0) == array.get(centroids,0) and array.get(new_centroids,1) == array.get(centroids,1) and array.get(new_centroids,2) == array.get(centroids,2) break endif centroids := new_centroidsendfor// === 선택 클러스터 매핑 ('Worst'=0, 'Average'=1, 'Best'=2) ===selIdx = 2if fromCluster == "Worst" then selIdx = 0 endifif fromCluster == "Average" then selIdx = 1 endif// 선택 클러스터의 평균 N 계산 (없으면 기본값)chosenN = defaultNsel_factors = array.get(clusters_factor, selIdx)if array.size(sel_factors) > 0 ssum = 0 for i = 0 to array.size(sel_factors)-1 ssum = ssum + array.get(sel_factors, i) endfor chosenN = round(ssum / array.size(sel_factors))endif// === 실시간 시그널: chosenN 사용 ===// 최신 N기간 최고/최저 계산 (함수명 HHV/LLV 사용)curr_hh = HHV(high, chosenN)curr_ll = LLV(low, chosenN)buySignal = close > curr_hhsellSignal = close < curr_ll// 출력(화면 및 알림용)plot_int("ChosenN", chosenN)plot_bool("Buy", buySignal)plot_bool("Sell", sellSignal)// 실제 주문/포지션 관리는 전략 엔진 규칙에 맞춰 작성
프로필 이미지
dedoyes
2025-10-26
88
글번호 227318
지표
답변완료

부탁드립니다

수고하십니다 아래수식을 오류 없게 수정부탁드립니다inputs: ShortLength(50), LongLength(150), RetestSignals(false), CandleColor(true), UpperColor(Magenta), LowerColor(Blue);variables: ATRValue(0), ShortKalman(0), LongKalman(0), // Kalman filter variables for short ShortEstimate(0), ShortErrorEst(1.0), ShortKalmanGain(0), ShortPrediction(0), ShortErrorMeas(0), ShortInitialized(false), // Kalman filter variables for long LongEstimate(0), LongErrorEst(1.0), LongKalmanGain(0), LongPrediction(0), LongErrorMeas(0), LongInitialized(false), TrendUp(false), PrevTrendUp(false), TrendColor(0), TrendColor1(0), CandleCol(0), UpperBoxTop(0), UpperBoxBottom(0), UpperBoxStart(0), LowerBoxTop(0), LowerBoxBottom(0), LowerBoxStart(0), BoxActive(false), R(0.01), Q(0.1);// Calculate ATRATRValue = AvgTrueRange(200) * 0.5;// Kalman Filter for Short LengthShortErrorMeas = R * ShortLength;if not ShortInitialized then begin ShortEstimate = Close; ShortInitialized = true;end;ShortPrediction = ShortEstimate;ShortKalmanGain = ShortErrorEst / (ShortErrorEst + ShortErrorMeas);ShortEstimate = ShortPrediction + ShortKalmanGain * (Close - ShortPrediction);ShortErrorEst = (1 - ShortKalmanGain) * ShortErrorEst + Q / ShortLength;ShortKalman = ShortEstimate;// Kalman Filter for Long LengthLongErrorMeas = R * LongLength;if not LongInitialized then begin LongEstimate = Close; LongInitialized = true;end;LongPrediction = LongEstimate;LongKalmanGain = LongErrorEst / (LongErrorEst + LongErrorMeas);LongEstimate = LongPrediction + LongKalmanGain * (Close - LongPrediction);LongErrorEst = (1 - LongKalmanGain) * LongErrorEst + Q / LongLength;LongKalman = LongEstimate;// Determine trendPrevTrendUp = TrendUp;TrendUp = ShortKalman > LongKalman;// Set colorsif TrendUp then TrendColor = UpperColorelse TrendColor = LowerColor;if ShortKalman > ShortKalman[2] then TrendColor1 = UpperColorelse TrendColor1 = LowerColor;// Candle coloringif CandleColor then begin if TrendUp and ShortKalman > ShortKalman[2] then CandleCol = UpperColor else if not TrendUp and ShortKalman < ShortKalman[2] then CandleCol = LowerColor else CandleCol = DarkGray;end;// Plot Kalman filtersPlot1(ShortKalman, "Short Kalman", TrendColor1);Plot2(LongKalman, "Long Kalman", TrendColor);// Trend change detection and signalsif TrendUp and not PrevTrendUp then begin // Uptrend signal Text_New(Date, Time, Low, "UP"); // Create lower box LowerBoxStart = CurrentBar; LowerBoxTop = Low + ATRValue; LowerBoxBottom = Low; BoxActive = true;end;if not TrendUp and PrevTrendUp then begin // Downtrend signal Text_New(Date, Time, High, "DN"); // Create upper box UpperBoxStart = CurrentBar; UpperBoxTop = High; UpperBoxBottom = High - ATRValue; BoxActive = true;end;// Retest signalsif RetestSignals then begin if not TrendUp and BoxActive then begin if High < UpperBoxBottom and High[1] >= UpperBoxBottom then Text_New(Date, Time, High[1], "x"); end; if TrendUp and BoxActive then begin if Low > LowerBoxTop and Low[1] <= LowerBoxTop then Text_New(Date, Time, Low[1], "+"); end;end;// Apply candle coloringif CandleColor then PlotPB(Open, High, Low, Close, CandleCol, CandleCol);
프로필 이미지
파생돌이
2025-10-26
91
글번호 227316
지표
답변완료

키움수식 변환

항상 감사드립니다 아래 키움식을 변환해 주시기 바랍니다 *** 키움식*** 1_1.저점매수(단순) BB=BBandsDown(20,2); A20=ma(c,20,단순); A5=ma(c,5,단순); R=RSI(14); c(1)<BB(1) and c(1)<A5(1) and A20(1)>A5(1) and R(1)<30 and c>A5 and c>BB and R>=30 **시스템 :위조건 만족시 매수신호 **지표: 위조건 만족시 +1(돌파봉만) /기준선0**강조표시(YELLOW)1_2.저점매수(가중) BB=BBandsDown(20,2); A20=ma(c,20,가중); A5=ma(c,5,가중); R=RSI(14); c(1)<BB(1) and c(1)<A5(1) and A20(1)>A5(1) and R(1)<30 and c>A5 and c>BB and R>=30 **시스템 :위조건 만족시 매수신호 **지표: 위조건 만족시 +1(돌파봉만) /기준선0 2.super T (매도)S = supertrend(20, 3); M = ma(C, 20); 조건 = M>M(1) && CrossUp(S, M); bs = BarsSince(조건); bs > 0 && CrossDown(S, M) && M > M(1) && C(1) < S(1) **시스템 :위조건 만족시 매도신호 **지표: 위조건 만족시 -1(돌파봉만) /기준선0 3.추돌매수시그널 손 = ma(C, 5); 절 = ma(C, 20); 가 = CrossUp(손, 절); 최고 = HighestSince(1, 가, H); 최고가 = Valuewhen(1, 최고==최고(1) &&최고>H, 최고); 최저=if(절>L, 1, 0); 최저가 = sum(최저); 결론 = 최저가-valuewhen(1,가,최저가(1)); 조건 = crossup(c, 최고가) && 결론>0; 카운트 = countsince(가, 조건)==1; 카운트 && !카운트(1) **시스템 :위조건 만족시 매수신호 **지표: 위조건 만족시 +1(돌파봉만) /기준선0 4. 3분슈퍼추세전환 crossup(c,c(5)) and crossup(c,c(60)) and O<C and V(1)*5<=V **시스템 :위조건 만족시 매수신호 **지표: 위조건 만족시 +1(돌파봉만) /기준선05. 급등전 선취매S=sum(1);M=ma(C,기간);MH=valuewhen(1,M>M(1), M);HH=HighestSince(1, crossup(S, 전체봉수-표시봉수), MH);CrossUP(C,HH) &&HH=HH(1) && HH(1)==HH(2)-전체봉수:600-기간:25-표시봉수:120**시스템 :위조건 만족시 매수신호 **지표: 위조건 만족시 +1(돌파봉만) /기준선06.황금선라인 돌파시그널M = BBandsUP(30, 1.8);LL = Lowest(M, 기간);HH = Highest(M, 기간);NL = Valuewhen(1, M<LL(1),M);Valuewhen(1,BarsSince(M<LL(1))==(기간-k),NL);CrossUp(C,NL)-기간:5-k:2**시스템 :위조건 만족시 매수신호 **지표: 위조건 만족시 +1(돌파봉만) /기준선07.기준선매수a=(highest(high,midPeriod)+lowest(low,midPeriod))/2;shift(crossup(c,a),-1)midperiod:26**시스템 :위조건 만족시 매수신호 **지표: 위조건 만족시 +1(돌파봉만) /기준선0감사합니다
프로필 이미지
조민철
2025-10-26
126
글번호 227315
시스템
답변완료

질문 있습니다.

질문의 요점: 1분봉 차트에서 시간대별(진입 기준) 순수익 계산이 정확하지 않습니다안녕하세요저번주에 답변 주신 글번호 227224 NetProfit 차이 방식으로 시간대별 손익을 계산하고 있는데, 1분봉 차트에서 결과가 정확하지 않아 다시 문의드립니다.=== 현재 사용 중인 코드 ===Input : StartHour(8), EndHour(18);var : NP(0), NP1(0), dayPL(0);NP = NetProfit;// 8시 직전까지의 총손익 저장if CurrentHour == StartHour and CurrentHour != CurrentHour[1] Then { NP1 = NP[1];}// 8시~18시 사이 당일손익 계산if CurrentHour >= StartHour and CurrentHour <= EndHour Then { dayPL = (NP - NP1) / PriceScale;}Else { dayPL = dayPL[1]; // 거래 시간 외 이전 값 유지}// 19시 출력if CurrentHour == (EndHour + 1) and CurrentHour != CurrentHour[1] Then { Text_New(sDate, sTime, H + 2.0, NumToStr(dayPL, 0) + "T");}```>>문제 상황 1번 계산 오류 있습니다.차트는 1분봉 입니다.실제로 8-18시 진입 거래를 하면- 6회 진입: -31, +58, -37, +245, -43, +22 = +214틱로 계산 됩니다. (차트에 표시된 진입/청산 시 수익/손실 표시를 수동 계산했음)그러나 시스템 표시 결과를 보면 혼란스럽니다.- 19시 표시는 -299틱 으로 나왔고 순수익 +214 표시가 잘 되지 않습니다.NetProfit 흐름은 아래와 같습니다.- 8시 이전: -201틱- 19시 전체: -500틱- 계산: -500 - (-201) = -299틱로 이렇게 표시 된 것 같습니다.문제는 실제 8-18시 진입 거래는 +214틱인데 -299틱으로 표시되어서 그렇습니다.. ---------------------------------------------------------------------------->>문제 상황 2번 18시 이전 진입 → 19시 이후 청산 케이스인데더 복잡한 문제가 있습니다:예를 들면```17:55 매수 진입 (8-18시 거래 시간 내)18:00 거래 시간 종료 그러나 청산 조건 때문에 18:00 넘어 포지션 홀딩한 경우임19:15 청산 +50틱 (19시 이후)```질문입니다.- 진입은 8-18시 내, 청산은 19시 이후인 경우- 이 +50틱을 8-18시 손익에 포함해야 할까요?제 의도는 아래와 같습니다.- "8-18시 사이에 진입한 모든 거래의 최종 손익"을 계산하고 싶습니다- 청산 시간은 무관하게, 진입 시간 기준 으로 추적하고- 해당 거래들이 모두 청산 완료된 후 에 최종 손익 표시하고 싶습니다. === 원하는 동작 ===1. 8-18시 사이 진입한 거래만 추적2. 해당 거래들이 모두 청산될 때까지 대기3. 마지막 거래 청산 완료 시점에 → "8-18시(진입기준) 최종: +XXX틱" 표시=== 핵심 질문 ===1. 1분봉에서 "18시 마지막 봉" 구분 방법```18:00, 18:01, 18:02 ... 18:59 봉들이 모두 CurrentHour = 18인데,18시 구간의 마지막 봉(18:59)을 어떻게 정확히 잡나요?```2. 18시 이후 거래 제외 방법- 18시 이후(18-24시)에도 거래가 계속되는데, 18시까지의 NP만 저장하려면?- `if CurrentHour == 19 and CurrentHour[1] == 18` 조건으로 18:59의 NP[1]을 읽어야 하나요?3. 진입 시간 기준 손익 계산 방법```예시 코드:var : InTime_Entry(0); // 시간대 내 진입 플래그var : InTime_Count(0); // 시간대 내 진입한 미결제 건수// 진입 시 기록if Buy신호 and CurrentHour >= 8 and CurrentHour <= 18 Then { InTime_Entry = 1; InTime_Count = InTime_Count + 1;}// 청산 시 카운트 감소if 청산 and InTime_Entry == 1 Then { InTime_Count = InTime_Count - 1;}// 모든 포지션 청산 완료 후 표시if CurrentHour > 18 and InTime_Count == 0 and 미표시 Then { Text_New(..., "8-18시 최종: +XXX틱");}이런 방식이 가능한가요?4. 1분봉 차트에서 시간대별 손익 계산 시 주의사항이 있을까요?요약 하자면 아래와 같습니다.문제 1: 기본 NetProfit 차이 계산이 부정확 (-299 vs +214)문제 2: 18시 전 진입 → 19시 후 청산 케이스 처리 방법원하는 결과: 진입 시간 기준으로 모든 거래 청산 후 최종 손익 표시 희망구체적인 코드 예시와 함께 답변 부탁드립니다. ㅠㅠ감사합니다!!!!
프로필 이미지
스오어스
2025-10-26
76
글번호 227314
시스템