예스스탁
예스스탁 답변
2023-11-28 16:40:37
안녕하세요
예스스탁입니다.
관련언어에 익숙하지 않아 해당 내용 읽어보고 변환해 드리는데 시간이 많이 소모됩니다.
업무상 일정시간 이상 요구되는 내용은 저희가 답변이 어렵습니다.
도움을 드리지 못해 죄송합니다.
즐거운 하루되세요
> 잘하고프다 님이 쓴 글입니다.
> 제목 : 시스템 변환 문의드립니다.
> 지표문의를 드리고 시스템 매매를 해보려고합니다.
input : length(14);
input : mult(1.0);
var : src(0),stdev(0),Emav(0),upper(0),lower(0);
var : bullish(0),bearish(0),bull_den(0),bear_den(0);
var : bull(0),bear(0);
src = close;
stdev = std(src, length) * mult;
emav = ema(src, length);
upper = emav + stdev;
lower = emav - stdev;
bullish = AccumN(max(src - upper, 0), length);
bearish = AccumN(max(lower - src, 0), length);
bull_den = AccumN(abs(src - upper), length);
bear_den = AccumN(abs(lower - src), length);
bull = bullish/bull_den*100;
bear = bearish/bear_den*100;
여기까지가 문의 답변주셔서 변환한 지표였고 위 지표를 기반으로 밑에있는 파인스크립트 코드를 변환해서 손익절을 하고싶습니다. 손익절 기준이 여러가지가 있었는데 ATR 기준으로 하고싶어서 ATR만 남기고 다 빼려고 노력했습니다만.. 여기까지가 한계라서 문의드립니다ㅜㅜ 코드에 트레일링스탑이 있는데 그것도 변환이 가능할까요?
bool openLongPosition = ta.crossover(bull, bear)
bool openShortPosition = ta.crossunder(bull , bear)
// LOGIC ============================================================================================================
// the open signals when not already into a position
bool validOpenLongPosition = openLongPosition and not (strategy.opentrades.size(strategy.opentrades - 1) > 0)
bool validOpenShortPosition = openShortPosition and not (strategy.opentrades.size(strategy.opentrades - 1) < 0)
bool longIsActive = validOpenLongPosition or strategy.opentrades.size(strategy.opentrades - 1) > 0
bool shortIsActive = validOpenShortPosition or strategy.opentrades.size(strategy.opentrades - 1) < 0
// INPUT ============================================================================================================
atrLength = input.int(defval = 14, title = 'ATR Length', minval = 1, tooltip = 'How many previous candles to use for the ATR calculation.', group = 'General')
// LOGIC ============================================================================================================
// take profit has to communicate its exeution with the stop loss logic when 'TP' mode is seleced
var bool longTrailingTakeProfitExeuted = false
var bool shortTrailingTakeProfitExeuted = false
float openAtr = ta.valuewhen(validOpenLongPosition or validOpenShortPosition, ta.atr(atrLength), 0)
// INPUT ============================================================================================================
stopLossMethod = input.string(defval = 'ATR', title = 'Stop Loss Method', options = ['ATR'], tooltip = 'The method to calculate the Stop Loss (percentagewise, based on initial ATR or based on ATR changing over time).', group = 'Stop Loss - Target')
longStopLossAtrMul = input.float(defval = 10.0, title = 'ATR Long/Short Mul', minval = 0.1, step = 0.1, inline = 'Trailing Stop Loss ATR Multiplier', group = 'Stop Loss - Target')
shortStopLossAtrMul = input.float(defval = 10.0, title = '', minval = 0.1, step = 0.1, tooltip = 'ATR multiplier to be used for the long/short Stop Loss.', inline = 'Trailing Stop Loss ATR Multiplier', group = 'Stop Loss - Target')
stopLossTrailingEnabled = input.string(defval = 'TP', title = 'Enable Trailing', options = ['TP', 'ON', 'OFF'], tooltip = 'Enable the trailing for Stop Loss when Take Profit order is exeted (TP) or from the start of the entry order (ON) or not at all (OFF).', group = 'Stop Loss - Trailing')
breakEvenEnabled = input.bool(defval = false, title = 'Break Even', tooltip = 'When Take Profit price target is hit, move the Stop Loss to the entry price (or to a more strict price defined by the Stop Loss %/ATR Multiplier).', group = 'Stop Loss - Trailing')
// LOGIC ============================================================================================================
getLongStopLossPrice(baseSrc) =>
switch stopLossMethod
'ATR' => baseSrc - longStopLossAtrMul * openAtr
=> na
// trailing starts when the take profit price is reached if 'TP' mode is set or from the very begining if 'ON' mode is seleced
bool longTakeProfitTrailingEnabled = stopLossTrailingEnabled == 'ON' or stopLossTrailingEnabled == 'TP' and longTrailingTakeProfitExeuted
// calculate trailing stop loss price when enter long position and peserve its value until the position closes
var float longStopLossPrice = na
longStopLossPrice := if (longIsActive)
if (validOpenLongPosition)
getLongStopLossPrice(close)
else
stopPrice = getLongStopLossPrice(longTakeProfitTrailingEnabled ? high : strategy.opentrades.entry_price(strategy.opentrades - 1))
stopPrice := breakEvenEnabled and longTrailingTakeProfitExeuted ? math.max(stopPrice, strategy.opentrades.entry_price(strategy.opentrades - 1)) : stopPrice
math.max(stopPrice, nz(longStopLossPrice[1]))
else
na
getShortStopLossPrice(baseSrc) =>
switch stopLossMethod
'ATR' => baseSrc + shortStopLossAtrMul * openAtr
=> na
// trailing starts when the take profit price is reached if 'TP' mode is set or from the very begining if 'ON' mode is seleced
bool shortTakeProfitTrailingEnabled = stopLossTrailingEnabled == 'ON' or stopLossTrailingEnabled == 'TP' and shortTrailingTakeProfitExeuted
// calculate trailing stop loss price when enter short position and peserve its value until the position closes
var float shortStopLossPrice = na
shortStopLossPrice := if (shortIsActive)
if (validOpenShortPosition)
getShortStopLossPrice(close)
else
stopPrice = getShortStopLossPrice(shortTakeProfitTrailingEnabled ? low : strategy.opentrades.entry_price(strategy.opentrades - 1))
stopPrice := breakEvenEnabled and shortTrailingTakeProfitExeuted ? math.min(stopPrice, strategy.opentrades.entry_price(strategy.opentrades - 1)) : stopPrice
math.min(stopPrice, nz(shortStopLossPrice[1], 999999.9))
else
na
// PLOT =============================================================================================================
var stopLossColor = color.new(color.maroon, 0)
plot(series = longStopLossPrice, title = 'Long Stop Loss', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 1)
plot(series = shortStopLossPrice, title = 'Short Stop Loss', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 1)
//#endregion ========================================================================================================
//#region TAKE PROFIT
// INPUT ============================================================================================================
takeProfitQuantityPerc = input.float(defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = 'The percentage of the position that will be withdrawn when the take profit price target is reached.', group = 'Take Profit - Quantity')
takeProfitMethod = input.string(defval = 'ATR', title = 'Take Profit Method', options = ['ATR'], tooltip = 'The method to calculate the Take Profit price.', group = 'Take Profit - Target')
//longTakeProfitPerc = input.float(defval = 1.0, title = 'Long/Short Take Profit %', minval = 0.05, step = 0.05, inline = 'Take Profit Perc', group = 'Take Profit - Target') / 100
//shortTakeProfitPerc = input.float(defval = 1.0, title = '', minval = 0.05, step = 0.05, tooltip = 'The percentage of the price increase/decrease to set the take profit price target for long/short positions.', inline = 'Take Profit Perc', group = 'Take Profit - Target') / 100
longTakeProfitAtrMul = input.float(defval = 10.0, title = 'ATR Long/Short Mul ', minval = 0.1, step = 0.1, inline = 'Take Profit ATR Multiplier', group = 'Take Profit - Target')
shortTakeProfitAtrMul = input.float(defval = 10.0, title = '', minval = 0.1, step = 0.1, tooltip = 'ATR multiplier to be used for the long/short Take Profit.', inline = 'Take Profit ATR Multiplier', group = 'Take Profit - Target')
takeProfitTrailingEnabled = input.bool(defval = true, title = 'Enable Trailing', tooltip = 'Enable or disable the trailing for take profit.', group = 'Take Profit - Trailing')
distanceMethod = input.string(defval = 'ATR', title = 'Distance Method', options = ['ATR'], tooltip = 'The method to calculate the Distance for the Trailing Take Profit.', group = 'Take Profit - Trailing')
distancePerc = input.float(defval = 1.0, title = 'Distance %', minval = 0.01, maxval = 100, step = 0.05, tooltip = 'The percentage wise step to be used for following the price, when the take profit target is reached.', group = 'Take Profit - Trailing') / 100
distanceAtrMul = input.float(defval = 1.0, title = 'Distance ATR Mul', minval = 0.01, step = 0.05, tooltip = 'Multiplier to be used on the initial entrys` ATR to calculate the step for following the price, when the take profit target is reached.', group = 'Take Profit - Trailing')
// LOGIC ============================================================================================================
getLongTakeProfitPrice() =>
switch takeProfitMethod
'ATR' => close + longTakeProfitAtrMul * openAtr
=> na
getLongTakeProfitPerc() =>
(close - getLongTakeProfitPrice()) / close
// calculate take profit price when enter long position and peserve its value until the position closes
var float longTakeProfitPrice = na
longTakeProfitPrice := if (longIsActive and not longTrailingTakeProfitExeuted)
if (validOpenLongPosition)
getLongTakeProfitPrice()
else
nz(longTakeProfitPrice[1], getLongTakeProfitPrice())
else
na
longTrailingTakeProfitExeuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTrailingTakeProfitExeuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= longTakeProfitPrice)
longTrailingTakeProfitStepTicks = switch distanceMethod
'ATR' => distanceAtrMul * openAtr / syminfo.mintick
=> na
getShortTakeProfitPrice() =>
switch takeProfitMethod
'ATR' => close - shortTakeProfitAtrMul * openAtr
=> na
getShortTakeProfitPerc() =>
(getShortTakeProfitPrice() - close) / close
// calculate take profit price when enter short position and peserve its value until the position closes
var float shortTakeProfitPrice = na
shortTakeProfitPrice := if (shortIsActive and not shortTrailingTakeProfitExeuted)
if (validOpenShortPosition)
getShortTakeProfitPrice()
else
nz(shortTakeProfitPrice[1], getShortTakeProfitPrice())
else
na
shortTrailingTakeProfitExeuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTrailingTakeProfitExeuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= shortTakeProfitPrice)
shortTrailingTakeProfitStepTicks = switch distanceMethod
'ATR' => distanceAtrMul * openAtr / syminfo.mintick
=> na
// PLOT =============================================================================================================
var takeProfitColor = color.new(color.teal, 0)
plot(series = longTakeProfitPrice, title = 'Long Take Profit', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 1)
plot(series = shortTakeProfitPrice, title = 'Short Take Profit', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 1)
// LOGIC ============================================================================================================
// getting into LONG position
if (validOpenLongPosition)
strategy.entry(id = 'Long Entry', direction = strategy.long, alert_message = 'Long(' + syminfo.ticker + '): Start')
else
strategy.cancel(id = 'Long Entry')
if (longIsActive)
strategy.exit(id = 'Long Take Profit / Stop Loss', from_entry = 'Long Entry', qty_percent = takeProfitQuantityPerc, limit = takeProfitTrailingEnabled ? na : longTakeProfitPrice, stop = longStopLossPrice, trail_price = takeProfitTrailingEnabled ? longTakeProfitPrice : na, trail_offset = takeProfitTrailingEnabled ? longTrailingTakeProfitStepTicks : na, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss exeuted')
strategy.exit(id = 'Long Stop Loss', from_entry = 'Long Entry', stop = longStopLossPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss exeuted')
// getting into SHORT position
if (validOpenShortPosition)
strategy.entry(id = 'Short Entry', direction = strategy.short, alert_message = 'Short(' + syminfo.ticker + '): Start')
else
strategy.cancel(id = 'Short Entry')
if (shortIsActive)
strategy.exit(id = 'Short Take Profit / Stop Loss', from_entry = 'Short Entry', qty_percent = takeProfitQuantityPerc, limit = takeProfitTrailingEnabled ? na : shortTakeProfitPrice, stop = shortStopLossPrice, trail_price = takeProfitTrailingEnabled ? shortTakeProfitPrice : na, trail_offset = takeProfitTrailingEnabled ? shortTrailingTakeProfitStepTicks : na, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss exeuted')
strategy.exit(id = 'Short Stop Loss', from_entry = 'Short Entry', stop = shortStopLossPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss exeuted')
// PLOT =============================================================================================================
var posColor = color.new(color.gray, 0)
plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position', color = posColor, linewidth = 1, style = plot.style_linebr)
//#endregion ========================================================================================================