커뮤니티
예스랭귀지 Q&A
[공지] 예스랭귀지 AI 어시스턴트, '예스나 AI' 출시 및 무료 체험 안내
안녕하세요, 예스스탁 입니다.복잡한 수식 공부 없이 여러분의 아이디어를 말하면 시스템 트레이딩 언어 예스랭귀지로 작성해주는 서비스예스나 AI(YesNa AI)가 출시되었습니다.지금 예스나 AI를 직접 경험해 보실 수 있도록 20크레딧(질문권 20회)를 무료로 증정해 드리고 있습니다.바로 여러분의 아이디어를 코드로 변환해보세요.--------------------------------------------------🚀 YesNa AI 핵심 기능- 지표식/전략식/종목검색식 생성: 자연어로 요청하면 예스랭귀지 문법에 맞는 코드를 작성합니다.- 종목검색식 변환 지원: K증권의 종목 검색식을 예스랭귀지로 변환 지원합니다.- 컴파일 검증: 작성된 코드가 실행 가능한지 컴파일러를 통해 문법 검증을 거쳐 결과물을 제공합니다.상세한 서비스 개요 및 활용 방법은 [서비스 소개 페이지]에서 확인하실 수 있습니다.▶ 서비스 소개 페이지: 바로가기서비스 사용 유의사항 및 결제 환불정책은 [이용약관]을 참고 부탁드립니다.▶ 서비스 이용약관: 바로가기💬 이용 문의사용 중 문의사항은 [프로그램 사용법 Q&A] 게시판에서 [예스나 AI] 카테고리를 설정 후 문의해 주시면 상세히 안내해 드리겠습니다.--------------------------------------------------앞으로도 AI를 활용한 다양한 트레이딩 기능들을 지속적으로 선보일 예정입니다.많은 관심과 기대 부탁드립니다.
2026-02-27
1314
글번호 230811
답변완료
시스템 수식 문의 드립니다.
안녕하세요.
기존 사용하는 수식에 덧붙여서 사용할 수 있는 수식 부탁드립니다.
매수진입 또는 매도진입하여 청산수익이 300달러이상 되었을때
시스템자동 매수 또는 매도 재진입 안되도록 하는 수식을 부탁드립니다.
언제나 감사드립니다.
2025-06-06
270
글번호 191474
답변완료
문의드립니다.
필요한 수식을 검색하던 중 이전에 어떤 분이 요청한 수식에 대한 답변(92732번)을 아래와 같이 주셔서 적용해봤는데(같은 기간값적용) 첨부된 그림과 같이 트레이딩뷰와 다른 부분이 나옵니다.
번거로우시겠지만 다시한번 검토해주시면 감사하겠습니다.
매번 도움을 받아서 감사드립니다.!!!
=============================
지표라인만 작성해 드립니다.
나머지 부가적인 표시들은 업무상 시간이 많이 소모되어 추가해 드리기 어렵습니다.
input : vidya_length(10);
input : vidya_momentum(20);
input : band_distance(2);
input : up_trend_color(Green);
input : down_trend_color(Red);
input : shadow(true);
var : pivot_left_bars(3),pivot_right_bars(0),source(0);
var : pivot_line(Nan);
var : volume_value(Nan);
var : smoothed_value(Nan);
var : is_trend_up(False);
var : up_trend_volume(False);
var : down_trend_volume(Nan);
Array : liquidity_lines_low[500](0),liquidity_lines_high[500](0);
pivot_left_bars = 3;
pivot_right_bars = 3;
source = close;
var : al(0),atr_value(0);
al = 1/200;
atr_value = IFf(IsNan(atr_value[1]) == true,ma(TrueRange, 200) , al * TrueRange + (1 - al) * IFf(IsNaN(atr_value[1])==true,0,atr_value[1]));
var : momentum(0),sum_pos_momentum(0),sum_neg_momentum(0),abs_cmo(0),alpha(0),vidya_v(0),vidya_value(0);
momentum = source-source[1];
sum_pos_momentum = AccumN(IFf(momentum >= 0, momentum , 0), vidya_momentum);
sum_neg_momentum = AccumN(IFf(momentum >= 0, 0, -momentum), vidya_momentum);
abs_cmo = abs(100 * (sum_pos_momentum - sum_neg_momentum) / (sum_pos_momentum + sum_neg_momentum));
alpha = 2 / (vidya_length + 1);
vidya_v = alpha * abs_cmo / 100 * source + (1 - alpha * abs_cmo / 100) * iff(IsNan(vidya_v[1])==true,0,vidya_v[1]);
vidya_value = ma(vidya_v, 15);
var : upper_band(0),lower_band(0);
upper_band = vidya_value + atr_value * band_distance;
lower_band = vidya_value - atr_value * band_distance;
// Detect trend direction using crossovers of source with bands
if CrossUp(source, upper_band) Then
is_trend_up = true ;
if CrossDown(source, lower_band) Then
is_trend_up = false ;
// Set trend-based smoothing variable
if is_trend_up == true Then
smoothed_value = lower_band;
if is_trend_up == False Then
smoothed_value = upper_band;
if is_trend_up != is_trend_up[1] Then
smoothed_value = Nan;
// Calculate pivot highs and lows for price action
var : pivot_high(0),pivot_low(0);
pivot_high = SwingHigh(1,high,pivot_left_bars, pivot_right_bars,pivot_left_bars+pivot_right_bars+1);
pivot_low = SwingLow(1, close, pivot_left_bars, pivot_right_bars,pivot_left_bars+pivot_right_bars+1);
if smoothed_value > 0 Then
plot1(smoothed_value,"smoothed_value",iff(is_trend_up , up_trend_color ,down_trend_color));
Else
NoPlot(1);
var : tx(0);
if is_trend_up == is_trend_up[1] and is_trend_up[1] != is_trend_up[2] Then
{
if is_trend_up == true Then
{
tx = Text_New(sDate,sTime,smoothed_value,"▲");
Text_SetStyle(tx,2,0);
Text_SetColor(tx,up_trend_color);
Text_SetSize(tx,20);
}
if is_trend_up == False Then
{
tx = Text_New(sDate,sTime,smoothed_value,"▼");
Text_SetStyle(tx,2,1);
Text_SetColor(tx,down_trend_color);
Text_SetSize(tx,20);
}
}
================
트레이딩뷰 수식
//@version=6
indicator('Volumatic Variable Index Dynamic Average [BigBeluga]', 'Volumatic VIDYA [BigBeluga]', overlay = true, max_lines_count = 500, max_labels_count = 500)
// INPUTS ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Input parameters for length, momentum, and source data
int vidya_length = input.int(10, 'VIDYA Length') // Length of the VIDYA calculation
int vidya_momentum = input.int(20, 'VIDYA Momentum') // Momentum length for VIDYA
float band_distance = input.float(2, 'Distance factor for upper/lower bands', step = 0.1) // Distance factor for upper/lower bands
// Define pivot parameters
int pivot_left_bars = 3 // Left side pivot bars
int pivot_right_bars = pivot_left_bars // Right side pivot bars
float source = input.source(close, 'Source') // Source for VIDYA calculation
// Define colors for up and down trends
color up_trend_color = input(#17dfad, '+', group = 'Color', inline = 'c') // Color for uptrend
color down_trend_color = input(#dd326b, '-', group = 'Color', inline = 'c') // Color for downtrend
bool shadow = input.bool(true, 'Shadow', group = 'Color', inline = 'c')
// Initialize variables for line, volume, and trend state
var line pivot_line = na // Variable for storing line references
var float volume_value = na // Variable for storing volume data
float smoothed_value = na // Smoothing variable for VIDYA trend levels
var bool is_trend_up = false // Boolean variable for tracking trend direction
// Initialize arrays for storing line and volume information
var array<line> liquidity_lines_low = array.new<line>(500) // Array for storing lines for lows
var array<line> liquidity_lines_high = array.new<line>(500) // Array for storing lines for highs
var float up_trend_volume = na // Volume accumulated during uptrend
var float down_trend_volume = na // Volume accumulated during downtrend
// }
// FUNCTIONS―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Define VIDYA (Variable Index Dynamic Average) function
vidya_calc(src, vidya_length, vidya_momentum) =>
float momentum = ta.change(src)
float sum_pos_momentum = math.sum(momentum >= 0 ? momentum : 0.0, vidya_momentum)
float sum_neg_momentum = math.sum(momentum >= 0 ? 0.0 : -momentum, vidya_momentum)
float abs_cmo = math.abs(100 * (sum_pos_momentum - sum_neg_momentum) / (sum_pos_momentum + sum_neg_momentum))
float alpha = 2 / (vidya_length + 1)
var float vidya_value = 0.0
vidya_value := alpha * abs_cmo / 100 * src + (1 - alpha * abs_cmo / 100) * nz(vidya_value[1])
ta.sma(vidya_value, 15)
// Method to extend lines and add labels for liquidity levels
method extend_liquidity_lines(array<line> line_array, float price_level, bool is_cross, volume_val) =>
if line_array.size() > 0 and last_bar_index - bar_index < 5000
for i = 0 to line_array.size() - 1 by 1
if i < line_array.size()
line liquidity_line = line_array.get(i)
float current_line_level = line.get_y2(liquidity_line)
bool price_cross = is_cross ? price_level < current_line_level and price_level[1] >= current_line_level : price_level > current_line_level and price_level[1] <= current_line_level
bool is_short_line = bar_index - line.get_x1(liquidity_line) < 50
if price_cross and is_short_line
line.set_x2(liquidity_line, bar_index)
line_array.remove(i)
// Add volume label to the liquidity zone
label.new(bar_index - 1, price_level[1], str.tostring(volume_val, format.volume), color = color.rgb(0, 0, 0, 99), style = is_cross ? label.style_label_lower_left : label.style_label_upper_left, textcolor = chart.fg_color, size = size.small)
// Add a circle label to represent liquidity zone
label.new(bar_index - 1, price_level[1], text = '◉', color = #00000003, textcolor = is_cross ? down_trend_color : up_trend_color, style = label.style_label_center, size = size.normal)
// }
// CALCULATIONS――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Calculate the Average True Range (ATR)
float atr_value = ta.atr(200) // ATR calculation with length of 200
// Calculate the VIDYA (Variable Index Dynamic Average)
vidya_value = vidya_calc(source, vidya_length, vidya_momentum)
// Calculate upper and lower bands based on VIDYA and ATR
float upper_band = vidya_value + atr_value * band_distance
float lower_band = vidya_value - atr_value * band_distance
// Detect trend direction using crossovers of source with bands
if ta.crossover(source, upper_band)
is_trend_up := true
is_trend_up
if ta.crossunder(source, lower_band)
is_trend_up := false
is_trend_up
// Set trend-based smoothing variable
if is_trend_up
smoothed_value := lower_band
smoothed_value
if not is_trend_up
smoothed_value := upper_band
smoothed_value
if ta.change(is_trend_up)
smoothed_value := na
smoothed_value
// Calculate pivot highs and lows for price action
bool pivot_high = not na(ta.pivothigh(pivot_left_bars, pivot_right_bars))
bool pivot_low = not na(ta.pivotlow(close, pivot_left_bars, pivot_right_bars))
// Create and store lines for pivot lows (support zones)
if low[pivot_right_bars] > smoothed_value and pivot_low
pivot_line := line.new(bar_index[pivot_right_bars], low[pivot_right_bars], bar_index[pivot_right_bars] + 5, low[pivot_right_bars], color = color.new(up_trend_color, 50))
liquidity_lines_low.push(pivot_line)
volume_value := math.sum(volume, pivot_right_bars + pivot_left_bars) / (pivot_right_bars + pivot_left_bars)
volume_value
// Create and store lines for pivot highs (resistance zones)
if high[pivot_right_bars] < smoothed_value and pivot_high
pivot_line := line.new(bar_index[pivot_right_bars], high[pivot_right_bars], bar_index[pivot_right_bars] + 5, high[pivot_right_bars], color = color.new(down_trend_color, 50))
liquidity_lines_high.push(pivot_line)
volume_value := math.sum(-volume, pivot_right_bars + pivot_left_bars) / (pivot_right_bars + pivot_left_bars)
volume_value
// Extend lines to track price movements
liquidity_lines_high.extend_liquidity_lines(smoothed_value, true, volume_value)
liquidity_lines_low.extend_liquidity_lines(smoothed_value, false, volume_value)
// Detect changes in the trend direction
bool trend_cross_up = not is_trend_up[1] and is_trend_up
bool trend_cross_down = not is_trend_up and is_trend_up[1]
// Reset volume counters when trend changes
if ta.change(trend_cross_up) or ta.change(trend_cross_down)
up_trend_volume := 0
down_trend_volume := 0
down_trend_volume
// Accumulate volume during trends
if not(ta.change(trend_cross_up) or ta.change(trend_cross_down))
up_trend_volume := up_trend_volume + (close > open ? volume : 0)
down_trend_volume := down_trend_volume + (close < open ? volume : 0)
down_trend_volume
// Calculate average volume
float avg_volume_delta = (up_trend_volume + down_trend_volume) / 2
// Determine the color of the trend
color trend_color = is_trend_up ? up_trend_color : not is_trend_up ? down_trend_color : chart.fg_color
// Calculate delta volume percentage
string delta_volume = str.tostring((up_trend_volume - down_trend_volume) / avg_volume_delta * 100, format.percent) == 'NaN%' ? '0%' : str.tostring((up_trend_volume - down_trend_volume) / avg_volume_delta * 100, format.percent)
// }
// PLOT ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Display labels for volume and trend statistics on the last bar
if barstate.islast
label.delete(label.new(bar_index, smoothed_value, 'Buy: ' + str.tostring(up_trend_volume, format.volume) + '₩n Sell: ' + str.tostring(down_trend_volume, format.volume) + '₩nDelta Volume: ' + delta_volume, color = color.new(trend_color, 90), style = is_trend_up ? label.style_label_upper_left : label.style_label_lower_left, textcolor = chart.fg_color)[1])
label.delete(label.new(bar_index, smoothed_value, text = '✪', color = #00000003, textcolor = trend_color, style = label.style_label_center, size = size.large)[1])
// Plot the VIDYA trend line
p1 = plot(smoothed_value, color = trend_color, linewidth = 2, style = plot.style_linebr)
p2 = plot(hl2, display = display.none)
// Fill between the plot and the VIDYA line
fill(p1, p2, smoothed_value, hl2, color.new(trend_color, shadow ? 80 : 100), na)
// Plot trend change markers (up and down arrows)
plotshape(series = trend_cross_up[1] ? smoothed_value[0] : na, title = 'Trend Up', style = shape.labelup, location = location.absolute, color = color.new(up_trend_color, 50), text = '▲', textcolor = chart.fg_color)
plotshape(series = trend_cross_down[1] ? smoothed_value[0] : na, title = 'Trend Down', style = shape.labeldown, location = location.absolute, color = color.new(down_trend_color, 50), text = '▼', textcolor = chart.fg_color)
// }
2025-06-06
638
글번호 191473
답변완료
수식요청
오랜만입니다.
종전에 수식요청드린 건인데
아래 중간의 a1=sonar(150)*100;이하부분이 누락된 거라 새로이 수식을 작성하여,
30분봉에서 검색-->예스스팟에서 자동매매를 걸어놓으려고 합니다.
귀찮더라도 한번 수식요청을 드려봅니다.
a=bbandsup(17,2);
b=bbandsup(40,2);
m=envelopeup(20,6);
(c>ma(h,5) and crossup(a,m))or
(c>ma(h,5) and b>m and crossup(a,b))
or(a>b and b > m and crossup(c,a))
or(crossup(c,a) and crossup(c,b) and crossup(c,m));
a1=sonar(150)*100;
a2=(c-avg(C,200)) / stdev(C,200);
a3=a2>0 or crossup(a2,0);
a4=crossup(a1,0);
a5=a3 && a4 && c>tavg(c,180);
a5
and
c>dayopen()*1.005
2025-06-06
341
글번호 191472
어떤하루 님에 의해서 삭제되었습니다.
2025-06-05
1
글번호 191471
답변완료
부탁드립니다.
그림과 같이 30분단위 선이 그려집니다.
첫번째 수정
첫봉 종가 기준으로 노란선이 연결되는데 초록색 선처럼 첫봉 시가로 선이 생기면 좋겠습니다.
두번째는 노랑색 초록색 둘다 같이 생기도록 부탁드립니다.
var : cnt1(0), cnt2(0);
var : S1(0),D1(0),TM(0),TF(0);
if Bdate != Bdate[1] Then
{
S1 = TimeToMinutes(stime);
D1 = sdate;
}
if D1 > 0 then
{
if sdate == D1 Then
TM = TimeToMinutes(stime)-S1;
Else
TM = TimeToMinutes(stime)+1440-S1;
TF = TM%60;
if TF >= 0 and TF < 30 Then
{
cnt2 = 0;
cnt1 = cnt1+1;
}
if TF >= 30 Then
{
cnt1 = 0;
cnt2 = cnt2+1;
}
if cnt1 == 1 or cnt2 == 1 Then
Var3 = C;
plot2(Var3);
}
2025-06-18
326
글번호 191470
부활 님에 의해서 삭제되었습니다.
2025-06-05
34
글번호 191469
답변완료
원 글(91906) 시스템 (수정) 추가 문의 드립니다.
원 글(91906) 시스템 (수정) 추가 문의 드립니다.
아래 수식에서 선물의 추세를 추가로 반영하고자 합니다.
즉 전날의 추세가 상승추세면서 매도신호가 뜨면 이 신호는 따라가지 않고 추후에 매수신호가 나오면 다시 따라가는 식으로 변경하고자 합니다.
즉 하락추세나 중립추세의 경우는 모든 신호를 따라가고, 상승추세에 매도신호만 건너뛰는 식으로 변경하고자 합니다.
추세를 상승, 하락, 중립 등으로 구분하여 외부변수 처리해주실 수 있는지요.
케이스를 설명해보겠습니다.
개장전에 외부변수로 추세를 입력한 후, 전일의 추세가 상승추세라면,
1. 당일 첫 신호가 매도가 뜨면 진입하지 않고, 추후 매수신호가 뜰 때 첫 진입을 하고, 이후 다시 매도신호가 뜨면, 매수분 청산하고 매도는 진입하지 않습니다. 일중최대진입회수가 3회라면 이상으로 첫 신호(매도)와 둘째 매수신호, 셋째 매도 신호로 3회가 충족되어 일중 거래를 끝냅니다.
2. 당일 첫 신호가 매수라면 즉시 진입하고, 추후 매도신호가 나오면 매수 청산만 하고 매도 진입은 하지 않으며, 이후 매수신호가 다시 나오면 포지션이 없는 상태에서 매수진입하면서 총 3회의 일중최대진입회수라면 이후에 매도신호가 나오더라도 청산하고 거래를 끝내며, 이후 매도신호가 나오지 않으면 마감 시간에 청산합니다.
답변에 미리 감사드립니다.
==================================================
안녕하세요
예스스탁입니다.
정산가는 별도로 제공되지 않아 외부변수 처리해드립니다.
input : 기준(1),일중최대진입횟수(2),당일손실틱수(100);
input : C1정산가(17000),C2정산가(5100);
var : ST(0,Data1),ET(0,Data1);
var : C1(0,Data1),C2(0,Data2);
var : R1(0,Data1),R2(0,Data2),나에차(0,Data1);
var : Tcond(False),count(0,Data1);
var : TT(0,Data1),N1(0,Data1),dayPL(0,Data1),Xcond(False),당일손실(0,Data1);
TT = TotalTrades;
if ET > 0 and Data1(sDate != sDate[1]) Then
SetStopEndofday(ET);
if data1(Bdate != Bdate[1]) Then
{
SetStopEndofday(0);
if sTime >= 80000 Then
{
ST = 233000;
ET = 060000;
}
Else
{
ST = 223000;
ET = 050000;
}
Xcond = False;
N1 = TT[1];
C1 = Data1(c[1]);
}
daypl = NetProfit-N1;
당일손실 = data1(PriceScale)*당일손실틱수;
if TotalTrades > TotalTrades[1] then
{
if daypl <= -당일손실 Then
Xcond = true;
if (IsExitName("dbl",1) == true or IsExitName("dsl",1) == true) then
Xcond = true;
}
if Data2(Bdate != Bdate[1]) Then
C2 = Data2(c[1]);
R1 = Data1((C-C1정산가)/C1정산가*100);
R2 = Data2((C-C2정산가)/C2정산가*100);
나에차 = R1-R2;
if data1(ET > 0 and
((sdate != sdate[1] and stime >= ET) or
(sdate == sdate[1] and stime >= ET and stime[1] < ET))) Then
{
Tcond = False;
}
if data1(ST > 0 and
((sdate != sdate[1] and stime >= ST) or
(sdate == sdate[1] and stime >= ST and stime[1] < ST))) Then
{
Tcond = true;
count = 0;
if MarketPosition == 0 and 나에차 >= 기준 then
{
count = count+1;
Buy();
}
if MarketPosition == 0 and 나에차 <= 기준 Then
{
count = count+1;
Sell();
}
}
Else
{
if Tcond == true and Xcond == False Then
{
if MarketPosition == 1 and 나에차 < 0 and 나에차[1] < 0 and count < 일중최대진입횟수 Then
{
count = count+1;
Sell("bs");
}
if MarketPosition == -1 and 나에차 > 0 and 나에차[1] > 0 and count < 일중최대진입횟수 Then
{
count = count+1;
Buy("sb");
}
if MarketPosition == 1 and 나에차 < 0 and 나에차[1] < 0 and count == 일중최대진입횟수 Then
{
ExitLong("bx");
}
if MarketPosition == -1 and 나에차 > 0 and 나에차[1] > 0 and count == 일중최대진입횟수 Then
{
ExitShort("sx");
}
}
}
if MarketPosition == 1 then
{
ExitLong("dbl",AtStop,EntryPrice-((당일손실+daypl)/CurrentContracts));
}
if MarketPosition == -1 then{
ExitShort("dsl",AtStop,EntryPrice+((당일손실+daypl)/CurrentContracts));
}
즐거운 하루되세요
> 나스닥에센피 님이 쓴 글입니다.
> 제목 : 원 글(91906) 시스템 (수정) 다시 문의 드립니다.
> 원 글(91906) 시스템 (수정) 다시 문의 드립니다.
아래 수식에서 나에차 계산시,
나에차 = 나스닥100선물% - S&P500선물%
에서 각 선물 등락률이 전일종가 대비로 계산되는 것으로 알고 있는데요.
각각의 선물 등락률을 전일 종가가 아니라 전일 정산가 대비로 계산해 적용하고 싶은데, 각각의 정산가를 외부 변수로 빼서 매일 입력하더라도 변경하고 싶은데 이 시스템을 변경 가능할까요?
아래 시스템 식에서
input : 기준(1),일중최대진입횟수(2),당일손실틱수(100);
var : ST(0,Data1),ET(0,Data1);
var : C1(0,Data1),C2(0,Data2);
var : R1(0,Data1),R2(0,Data2),나에차(0,Data1);
(중략)
R1 = Data1((C-C1)/C1*100);
R2 = Data2((C-C2)/C2*100);
나에차 = R1-R2;
(이하 생략)
즉, 위 시스템의 C1, C2를 "input"변수로 추가하여 매일 수기로 입력하는 방식을 통하더라도 등락률을 정산가 대비로 변경할 수 있을지요?
답변에 미리 감사드립니다.
즐거운 휴일 되시기 바랍니다.
> 예스스탁 님이 쓴 글(2025.03.17)입니다.
> 제목 : Re : 시스템 문의 드립니다
>
안녕하세요
예스스탁입니다.
나스닥100선물을 기본차트로
S&P500선물을 참조데이터로 추가하고 식 적용하시면 됩니다.
차트주기는 수식에서 설정할 수 없습니다. 3분봉으로 직접 설정하셔야 합니다.
실계좌의 손익은 랭귀지에서 알수 없습니다.
아래 식에서는 당일 신호상 당일손익기준으로 지정한 틱수 누적손실이면 청산됩니다.
input : 기준(1),일중최대진입횟수(2),당일손실틱수(100);
var : ST(0,Data1),ET(0,Data1);
var : C1(0,Data1),C2(0,Data2);
var : R1(0,Data1),R2(0,Data2),나에차(0,Data1);
var : Tcond(False),count(0,Data1);
var : TT(0,Data1),N1(0,Data1),dayPL(0,Data1),Xcond(False),당일손실(0,Data1);
TT = TotalTrades;
if ET > 0 and Data1(sDate != sDate[1]) Then
SetStopEndofday(ET);
if data1(Bdate != Bdate[1]) Then
{
SetStopEndofday(0);
if sTime >= 80000 Then
{
ST = 233000;
ET = 060000;
}
Else
{
ST = 223000;
ET = 050000;
}
Xcond = False;
N1 = TT[1];
C1 = Data1(c[1]);
}
daypl = NetProfit-N1;
당일손실 = data1(PriceScale)*당일손실틱수;
if TotalTrades > TotalTrades[1] then
{
if daypl <= -당일손실 Then
Xcond = true;
if (IsExitName("dbl",1) == true or IsExitName("dsl",1) == true) then
Xcond = true;
}
if Data2(Bdate != Bdate[1]) Then
C2 = Data2(c[1]);
R1 = Data1((C-C1)/C1*100);
R2 = Data2((C-C2)/C2*100);
나에차 = R1-R2;
if data1(ET > 0 and
((sdate != sdate[1] and stime >= ET) or
(sdate == sdate[1] and stime >= ET and stime[1] < ET))) Then
{
Tcond = False;
}
if data1(ST > 0 and
((sdate != sdate[1] and stime >= ST) or
(sdate == sdate[1] and stime >= ST and stime[1] < ST))) Then
{
Tcond = true;
count = 0;
if MarketPosition == 0 and 나에차 >= 기준 then
{
count = count+1;
Buy();
}
if MarketPosition == 0 and 나에차 <= 기준 Then
{
count = count+1;
Sell();
}
}
Else
{
if Tcond == true and Xcond == False Then
{
if MarketPosition == 1 and 나에차 < 0 and 나에차[1] < 0 and count < 일중최대진입횟수 Then
{
count = count+1;
Sell("bs");
}
if MarketPosition == -1 and 나에차 > 0 and 나에차[1] > 0 and count < 일중최대진입횟수 Then
{
count = count+1;
Buy("sb");
}
if MarketPosition == 1 and 나에차 < 0 and 나에차[1] < 0 and count == 일중최대진입횟수 Then
{
ExitLong("bx");
}
if MarketPosition == -1 and 나에차 > 0 and 나에차[1] > 0 and count == 일중최대진입횟수 Then
{
ExitShort("sx");
}
}
}
if MarketPosition == 1 then
{
ExitLong("dbl",AtStop,EntryPrice-((당일손실+daypl)/CurrentContracts));
}
if MarketPosition == -1 then{
ExitShort("dsl",AtStop,EntryPrice+((당일손실+daypl)/CurrentContracts));
}
즐거운 하루되세요
> 나스닥에센피 님이 쓴 글입니다.
> 제목 : 시스템 문의 드립니다
> 미국 지수 선물로 아래와 같이 자동매매 프로그램을 만들고자 합니다. 시스템 수식을 부탁드립니다.
자동매매 프로그램 수식 설명:
①차트 표시 주기는 3분 단위로 하며, 첫 진입은 장 개시 첫 3분 경과 후인 22:33분(미국 서머타임 기준 한국 시간)에 나스닥100선물과 S&P500선물 등락률 차(=나스닥100선물% - S&P500선물%, "나에차"라고 한다)가 '+기준'이상이면 당해 3분봉 종가로 매수로, '-기준'이하이면 당해 3분봉 종가로 매도로.(여기서 '외부변수'="나에차", '첫 진입 시간', '손절금액')
②반대 진입은 "나에차"가 기존과 반대 방향으로 '±기준'이상으로 두번 지속되면 한다.
③일중 반대 신호가 두번 나오면 청산만 하고 반대 진입을 더 이상 하지 않는다. 결국 일일 최대 진입 회수는 2회로 한다.
④일중 반대 신호가 두번 나오지 않으면 현물 지수가 마감되는 시간(서머타임 기준 한국 시간 새벽 05시)에 청산하고 거래를 끝낸다.
자동매매 프로그램 로직으로 다시 설명하면,
1. 기본 변수 설정
- `기준`: 매매 신호를 결정하는 기준값.
- `나에차`: 나스닥 100선물과 S&P 500선물의 등락률 차.
- `진입횟수`: 일중 최대 진입 횟수 (최대 2회).
- `진입시간`: 첫 진입 시간 (22:33, 서머타임 기준).
- `청산시간`: 마감 시간 (05:00, 서머타임 기준).
- '손절금액': 일중 계좌 손실 금액
2. 차트 표시 주기 설정
- 차트 주기를 3분으로 설정합니다.
3. 첫 진입 조건
if 현재시간 >= 진입시간 then
나에차 = 나스닥100선물% - S&P500선물%
if 나에차 >= 기준 then
매수(현재 3분봉 종가)
진입횟수 += 1
else if 나에차 <= -기준 then
매도(현재 3분봉 종가)
진입횟수 += 1
```
4. 반대 진입 조건
- 반대 방향 신호가 두 번 지속되는지 체크합니다.
if 나에차의 변화가 기존 방향과 반대이고 |나에차| >= 기준 then
반대신호카운트 += 1
if 반대신호카운트 >= 2 then
if 현재 포지션이 매수이면
매도(현재 3분봉 종가)
else if 현재 포지션이 매도이면
매수(현재 3분봉 종가)
반대신호카운트 = 0
진입횟수 += 1
```
5. 청산 조건
- 일중 반대 신호가 두 번 나왔는지 체크 후, 두 번 나오면 청산만 합니다.
if 반대신호카운트 >= 2 then
청산(현재 포지션)
진입횟수 = 0
```
6. 마감 시간 청산
- 마감 시간에 청산합니다.
if 현재시간 >= 청산시간 then
청산(현재 포지션)
```
답변에 미리 감사드립니다.
행복한 주말 보내세요.
2025-06-05
387
글번호 191468
답변완료
수식변환 부탁드립니다.
안녕하세요
수식변환 부탁드립니다.
//@version=6
indicator("카르마RSI", overlay=true, max_bars_back = 500)
// 채널 설정
int length = input.int(150, "채널 길이", group = "CHANNEL")
float channel_width = input.float(1.5, "채널 폭", step = 0.1, group = "CHANNEL")
bool mid_disp = input.bool(true, "50선", inline = "s", group = "CHANNEL")
bool fill_band = input.bool(true, "백그라운드", inline = "s", group = "CHANNEL")
color col_up = input.color(#a7abb9, "라인 색상:ㅤㅤ상단", group = "CHANNEL", inline = "Col")
color col_mid = input.color(color.gray, "중앙", group = "CHANNEL", inline = "Col")
color col_low = input.color(#a7abb9, "하단", group = "CHANNEL", inline = "Col")
// RSI 설정
int lengtht = input.int(14, "길이", inline = "rsi", group = "RSI")
color osc_col_base = input.color(color.rgb(161, 0, 182), "", inline = "rsi", group = "RSI")
int rsiOpacity = input.int(70, "RSI 선 투명도 (0~100)", minval=0, maxval=100, group="RSI")
int upper_threshold = input.int(70, "Scale", group = "RSI", inline = "rsi1")
bool show_threshold_labels = input.bool(true, "기준선 라벨 표시", group = "RSI")
bool sig_disp = input.bool(true, "Signal Line", inline = "sig")
int length_sig = input.int(14, "", inline = "sig")
color sig_line = input.color(color.rgb(255, 0, 0), "", inline = "sig")
// 채널 구조
f_log_regression(src, length) =>
float sumX = 0.0, sumY = 0.0, sumXSqr = 0.0, sumXY = 0.0
for i = 0 to length - 1
val = math.log(src[i])
per = i + 1.0
sumX += per
sumY += val
sumXSqr += per * per
sumXY += val * per
slope = (length * sumXY - sumX * sumY) / (length * sumXSqr - sumX * sumX)
intercept = (sumY - slope * sumX) / length
[slope, intercept]
[slope, intercept] = f_log_regression(close, length)
reg_start = math.exp(intercept + slope * length)
reg_end = math.exp(intercept)
deviation = ta.stdev(close, length)
upper_start = reg_start + deviation * channel_width
upper_end = reg_end + deviation * channel_width
lower_start = reg_start - deviation * channel_width
lower_end = reg_end - deviation * channel_width
var line mid_line = na
var line upper_line = na
var line lower_line = na
if na(mid_line) and mid_disp
mid_line := line.new(bar_index[length], reg_start, bar_index, reg_end, color=col_mid, style=line.style_dashed)
else
line.set_xy1(mid_line, bar_index[length], reg_start)
line.set_xy2(mid_line, bar_index, reg_end)
if na(upper_line)
upper_line := line.new(bar_index[length], upper_start, bar_index, upper_end, width=2, color=col_up)
else
line.set_xy1(upper_line, bar_index[length], upper_start)
line.set_xy2(upper_line, bar_index, upper_end)
if na(lower_line)
lower_line := line.new(bar_index[length], lower_start, bar_index, lower_end, width=2, color=col_low)
else
line.set_xy1(lower_line, bar_index[length], lower_start)
line.set_xy2(lower_line, bar_index, lower_end)
// RSI 계산
lower_threshold = 100 - upper_threshold
slope_ = (reg_start - reg_end) / length
step = (upper_end - lower_end) / (upper_threshold - lower_threshold)
rsi = ta.rsi(close, lengtht)
sma_osc = ta.sma(rsi, length_sig)
osc_col = color.new(osc_col_base, 100 - rsiOpacity)
// 시각화
polyline_disp(float src, bool display, bool shadow = true, color_, width = 1) =>
if barstate.islast and display
points = array.new<chart.point>()
for i = 0 to length - 1
val = src[i] - lower_threshold
lower = lower_end + slope_ * i
cp = chart.point.from_index(bar_index[i], lower + step * val)
array.push(points, cp)
p1 = polyline.new(points, line_color=color_, closed=false, force_overlay=true, line_width=width)
polyline.delete(p1[1])
if shadow
label.delete(label.new(bar_index, lower_end + step * (src - lower_threshold), "कर्म RSI: " + str.tostring(src, "#.##"), style=label.style_label_left, color=color(na), textcolor=chart.fg_color)[1])
if show_threshold_labels
label.delete(label.new(bar_index, lower_end, str.tostring(lower_threshold, " ##.#"), style=label.style_label_left, color=color(na), textcolor=chart.fg_color)[1])
label.delete(label.new(bar_index, upper_end, str.tostring(upper_threshold, " ##.#"), style=label.style_label_left, color=color(na), textcolor=chart.fg_color)[1])
// 배경
if fill_band
linefill.new(upper_line, lower_line, color.new(osc_col, 95))
// Plot
polyline_disp(rsi, true, true, osc_col, 4)
polyline_disp(sma_osc, sig_disp, false, sig_line, 2)
2025-06-05
486
글번호 191467
고도산 님에 의해서 삭제되었습니다.
2025-06-07
217
글번호 191466