Erstelle mir bitte in pinescript in der aktuellen...

생성일: 2025년 7월 1일

답변에 사용된 모델 O3 by Chat01

질문

Erstelle mir bitte in pinescript in der aktuellen version für tradingview aus diesem Indikator eine neue Strategie:

Nimm folgenden Indikator als Grundlage und baue ihn so um:

Die Strategie einstellbar für „long only“, „short only“ und „both“

Die up signals als long entry.
Die down signals als long exit.
Für short entsprechend umgekehrt.

Ein einfacher, einstellbarer stop loss zur Kapitalsicherung dazu. Kein trailing.

Hier die Vorlage: //@version=6
indicator('Multi Kernel Regression [ChartPrime]', overlay = true, max_lines_count = 500, max_bars_back = 500, max_labels_count = 500)

repaint = input.bool(true, 'Repaint')

kernel = input.string('Quartic', 'Kernel Select', ['Triangular', 'Gaussian', 'Epanechnikov', 'Logistic', 'Log Logistic', 'Cosine', 'Sinc', 'Laplace', 'Quartic', 'Parabolic', 'Exponential', 'Silverman', 'Cauchy', 'Tent', 'Wave', 'Power', 'Morters'])

bandwidth = input.int(14, 'Bandwidth', 1)
source = input.source(close, 'Source')
deviations = input.float(2.0, 'Deviation', 0, 100, 0.25, inline = 'dev')
style = input.string('Solid', 'Line Style', ['Solid', 'Dotted', 'Dashed'])
enable = input.bool(false, '', inline = 'dev')
label_size = input.string('Tiny', 'Labels', ['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], inline = 'label')
labels = input.bool(true, '', inline = 'label')
bullish_color = input.color(color.rgb(84, 194, 148), 'Colors', inline = 'color')
bearish_color = input.color(color.rgb(235, 57, 57), '', inline = 'color')
text_color = input.color(color.rgb(8, 12, 20), '', inline = 'color')

size = switch label_size
'Auto' => size.auto
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge

line_style = switch style
'Solid' => line.style_solid
'Dotted' => line.style_dotted
'Dashed' => line.style_dashed

sq(source) =>
math.pow(source, 2)

gaussian(source, bandwidth) =>
math.exp(-sq(source / bandwidth) / 2) / math.sqrt(2 * math.pi)

triangular(source, bandwidth) =>
math.abs(source / bandwidth) <= 1 ? 1 - math.abs(source / bandwidth) : 0.0

epanechnikov(source, bandwidth) =>
math.abs(source / bandwidth) <= 1 ? 3 / 4. * (1 - sq(source / bandwidth)) : 0.0

quartic(source, bandwidth) =>
if math.abs(source / bandwidth) <= 1
15 / 16. * math.pow(1 - sq(source / bandwidth), 2)
else
0.0

logistic(source, bandwidth) =>
1 / (math.exp(source / bandwidth) + 2 + math.exp(-source / bandwidth))

cosine(source, bandwidth) =>
math.abs(source / bandwidth) <= 1 ? math.pi / 4 * math.cos(math.pi / 2 * (source / bandwidth)) : 0.0

laplace(source, bandwidth) =>
1 / (2 * bandwidth) * math.exp(-math.abs(source / bandwidth))

exponential(source, bandwidth) =>
1 / bandwidth * math.exp(-math.abs(source / bandwidth))

silverman(source, bandwidth) =>
if math.abs(source / bandwidth) <= 0.5
0.5 * math.exp(-(source / bandwidth) / 2) * math.sin(source / bandwidth / 2 + math.pi / 4)
else
0.0

tent(source, bandwidth) =>
if math.abs(source / bandwidth) <= 1
1 - math.abs(source / bandwidth)
else
0.0

cauchy(source, bandwidth) =>
1 / (math.pi * bandwidth * (1 + sq(source / bandwidth)))

sinc(source, bandwidth) =>
if source == 0
1
else
math.sin(math.pi * source / bandwidth) / (math.pi * source / bandwidth)

wave(source, bandwidth) =>
if math.abs(source / bandwidth) <= 1
(1 - math.abs(source / bandwidth)) * math.cos(math.pi * source / bandwidth)
else
0.0

parabolic(source, bandwidth) =>
if math.abs(source / bandwidth) <= 1
1 - math.pow(source / bandwidth, 2)
else
0.0

power(source, bandwidth) =>
if math.abs(source / bandwidth) <= 1
math.pow(1 - math.pow(math.abs(source / bandwidth), 3), 3)
else
0.0

loglogistic(source, bandwidth) =>
1 / math.pow(1 + math.abs(source / bandwidth), 2)

morters(source, bandwidth) =>
if math.abs(source / bandwidth) <= math.pi
(1 + math.cos(source / bandwidth)) / (2 * math.pi * bandwidth)
else
0.0

kernel(source, bandwidth, style) =>
switch style
'Triangular' => triangular(source, bandwidth)
'Gaussian' => gaussian(source, bandwidth)
'Epanechnikov' => epanechnikov(source, bandwidth)
'Logistic' => logistic(source, bandwidth)
'Log Logistic' => loglogistic(source, bandwidth)
'Cosine' => cosine(source, bandwidth)
'Sinc' => sinc(source, bandwidth)
'Laplace' => laplace(source, bandwidth)
'Quartic' => quartic(source, bandwidth)
'Parabolic' => parabolic(source, bandwidth)
'Exponential' => exponential(source, bandwidth)
'Silverman' => silverman(source, bandwidth)
'Cauchy' => cauchy(source, bandwidth)
'Tent' => tent(source, bandwidth)
'Wave' => wave(source, bandwidth)
'Power' => power(source, bandwidth)
'Morters' => morters(source, bandwidth)

type coefficients
array<float> weights
float sumw

precalculate(float bandwidth, string kernel) =>
var array<coefficients> c = array.new<coefficients>()
if barstate.isfirst
for i = 0 to 499 by 1
coefficients w = coefficients.new(array.new<float>(), 0)
float sumw = 0

text
for j = 0 to 499 by 1 diff = i - j weight = kernel(diff, bandwidth, kernel) sumw := sumw + weight w.weights.push(weight) w.sumw := sumw c.push(w) c else c

precalculate_nrp(bandwidth, kernel) =>
var array<float> weights = array.new<float>()
var float sumw = 0
if barstate.isfirst
for i = 0 to bandwidth - 1 by 1
j = math.pow(i, 2) / math.pow(bandwidth, 2)
weight = kernel(j, 1, kernel)
weights.push(weight)
sumw := sumw + weight
sumw
[weights, sumw]
else
[weights, sumw]

multi_kernel_regression(source, bandwidth, deviations, style, labels, enable, line_style, text_color, bullish_color, bearish_color, size, repaint) =>
var estimate_array = array.new<line>(500, line.new(na, na, na, na))
var dev_upper_array = array.new<line>(500, line.new(na, na, na, na))
var dev_lower_array = array.new<line>(500, line.new(na, na, na, na))
var up_labels = array.new<label>(500, label.new(na, na))
var down_labels = array.new<label>(500, label.new(na, na))

text
float current_price = na float previous_price = na float previous_price_delta = na float std_dev = na float upper_1 = na float lower_1 = na float upper_2 = na float lower_2 = na line estimate = na line dev_upper = na line dev_lower = na label bullish = na label bearish = na float nrp_sum = na float nrp_stdev = na color nrp_color = na if not repaint [weights, sumw] = precalculate_nrp(bandwidth, kernel) float sum = 0.0 float sumsq = 0.0 for i = 0 to bandwidth - 1 by 1 weight = weights.get(i) sum := sum + nz(source[i]) * weight sum nrp_sum := sum / sumw direction = nrp_sum - nrp_sum[1] > 0 nrp_color := direction ? bullish_color : bearish_color for i = 0 to bandwidth - 1 by 1 sumsq := sumsq + math.pow(source[i] - nrp_sum[i], 2) sumsq nrp_stdev := math.sqrt(sumsq / (bandwidth - 1)) * deviations if labels if ta.crossover(nrp_sum, nrp_sum[1]) label.new(bar_index, nrp_sum, 'Up', xloc.bar_index, yloc.belowbar, bullish_color, label.style_label_up, text_color, size) if ta.crossunder(nrp_sum, nrp_sum[1]) label.new(bar_index, nrp_sum, 'Down', xloc.bar_index, yloc.abovebar, bearish_color, label.style_label_down, text_color, size) [nrp_sum, nrp_color, nrp_stdev] else array<coefficients> c = precalculate(bandwidth, kernel) if barstate.isfirst for i = 499 to 0 by 1 array.set(estimate_array, i, line.new(na, na, na, na)) if enable array.set(dev_upper_array, i, line.new(na, na, na, na)) array.set(dev_lower_array, i, line.new(na, na, na, na)) if labels array.set(up_labels, i, label.new(na, na)) array.set(down_labels, i, label.new(na, na)) if barstate.islast for i = 0 to math.min(bar_index, 499) by 1 coefficient = c.get(i) float sum = 0 float sumsq = 0 for j = 0 to math.min(bar_index, 499) by 1 diff = i - j weight = coefficient.weights.get(j) sum := sum + source[j] * weight sumsq := sumsq + sq(source[j]) * weight sumsq current_price := sum / coefficient.sumw delta = current_price - previous_price if enable std_dev := math.sqrt(math.max(sumsq / coefficient.sumw - sq(current_price), 0)) upper_2 := current_price + deviations * std_dev lower_2 := current_price - deviations * std_dev lower_2 estimate := array.get(estimate_array, i) if enable dev_upper := array.get(dev_upper_array, i) dev_lower := array.get(dev_lower_array, i) dev_lower line.set_xy1(estimate, bar_index - i + 1, previous_price) line.set_xy2(estimate, bar_index - i, current_price) line.set_style(estimate, line_style) line.set_color(estimate, current_price > previous_price ? bearish_color : bullish_color) line.set_width(estimate, 3) if enable line.set_xy1(dev_upper, bar_index - i + 1, upper_1) line.set_xy2(dev_upper, bar_index - i, upper_2) line.set_style(dev_upper, line_style) line.set_color(dev_upper, current_price > previous_price ? bearish_color : bullish_color) line.set_width(dev_upper, 3) line.set_xy1(dev_lower, bar_index - i + 1, lower_1) line.set_xy2(dev_lower, bar_index - i, lower_2) line.set_style(dev_lower, line_style) line.set_color(dev_lower, current_price > previous_price ? bearish_color : bullish_color) line.set_width(dev_lower, 3) if labels bullish := array.get(up_labels, i) bearish := array.get(down_labels, i) if delta > 0 and previous_price_delta < 0 label.set_xy(bullish, bar_index - i + 1, source[i]) label.set_text(bullish, 'Up') label.set_color(bullish, bullish_color) label.set_textcolor(bullish, text_color) label.set_textalign(bullish, text.align_center) label.set_size(bullish, size) label.set_style(bullish, label.style_label_up) label.set_yloc(bullish, yloc.belowbar) if delta < 0 and previous_price_delta > 0 label.set_xy(bearish, bar_index - i + 1, source[i]) label.set_text(bearish, 'Down') label.set_textcolor(bearish, text_color) label.set_color(bearish, bearish_color) label.set_textalign(bearish, text.align_center) label.set_size(bearish, size) label.set_style(bearish, label.style_label_down) label.set_yloc(bearish, yloc.abovebar) previous_price := current_price upper_1 := upper_2 lower_1 := lower_2 previous_price_delta := delta previous_price_delta if barstate.isconfirmed for i = array.size(up_labels) - 1 to 0 by 1 label.set_xy(array.get(up_labels, i), na, na) for i = array.size(down_labels) - 1 to 0 by 1 label.set_xy(array.get(down_labels, i), na, na) [nrp_sum, nrp_color, nrp_stdev]

[nrp_sum, nrp_color, nrp_stdev] = multi_kernel_regression(source, bandwidth, deviations, kernel, labels, enable, line_style, text_color, bullish_color, bearish_color, size, repaint)

plot(nrp_sum, 'Non Repaint MA', nrp_color)
plot(nrp_sum + nrp_stdev, 'Non Repaint STDEV', nrp_color, display = enable ? display.all : display.none)
plot(nrp_sum - nrp_stdev, 'Non Repaint STDEV', nrp_color, display = enable ? display.all : display.none)

사고

Building the Pine Script strategy

The user asked for a TradingView strategy in Pine Script version 6, adjusting a provided indicator code. They want to add customizable trade direction options ("long only," "short only," and "both") and set up long entries on up signals, and exits on down signals—reversed for shorts. Additionally, they prefer a basic adjustable stop loss for capital protection without trailing. So, I’ll need to write a strategy that reflects their needs using Pine Script with these specifications. I’ll take care of it!

Designing the Pine Script strategy

To create the strategy the user wants, I'll use Pine Script’s strategy() function, making the trade direction and stop loss adjustable. To set up the entry and exit conditions, I'll replicate the ta.crossover and ta.crossunder logic for long and short signals. For simplicity, I’ll calculate direction from the difference of nrp_sum values. I'll make the strategy allow for a stop loss percentage input and trade options: long only, short only, or both. We can use strategy.exit to close trades at the stop loss.

Writing the Pine Script strategy

To create the Pine Script strategy, I’m setting up the necessary inputs such as trade direction, bandwidth, kernel selection, and stop loss percentage. I'll calculate nrp_sum using a simplified, non-repainting version of the function and define up/down signals with ta.crossover and ta.crossunder. Depending on the user's desired trade direction, I'll trigger the strategy.entry() and close positions with strategy.exit() for both long and short. The script will also include adjustable stop loss settings for capital protection. I'll make sure to implement the exit conditions based on the signals.

Thought for 31 seconds

답변

Hier ein kompletter Pine-Script-Entwurf (v6) für eine Strategie auf Basis deines Multi-Kernel-Regression-Indikators.
Du kannst in den Einstellungen wählen, ob nur Long-, nur Short- oder beide Seiten gehandelt werden, und einen einfachen (nicht-trailenden) prozentualen Stop-Loss setzen.

pinescript
//@version=6 strategy("Multi-Kernel Regression Strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 10) //----- BENUTZER­EINSTELLUNGEN ----- tradeSide = input.string("both", "Trade Direction", options = ["long only", "short only", "both"]) kernelType = input.string("Quartic", "Kernel", options = ['Triangular','Gaussian','Epanechnikov','Logistic','Log Logistic','Cosine','Sinc','Laplace','Quartic','Parabolic','Exponential','Silverman','Cauchy','Tent','Wave','Power','Morters']) bandwidth = input.int(14, "Bandwidth", minval = 1) devs = input.float(2.0,"Deviation") src = input.source(close,"Source") stopPerc = input.float(2.0,"Stop-Loss % (ohne Trailing)", minval = 0.0) //----- KERNEL-FUNKTIONEN (wie im Original) ----- sq(x) => math.pow(x, 2) gaussian(x,bw) => math.exp(-sq(x/bw)/2)/math.sqrt(2*math.pi) triangular(x,bw) => math.abs(x/bw)<=1 ? 1-math.abs(x/bw) : 0.0 epanechnikov(x,bw) => math.abs(x/bw)<=1 ? 3/4.*(1-sq(x/bw)) : 0.0 quartic(x,bw) => math.abs(x/bw)<=1 ? 15/16.*math.pow(1-sq(x/bw),2) : 0.0 logistic(x,bw) => 1/(math.exp(x/bw)+2+math.exp(-x/bw)) cosine(x,bw) => math.abs(x/bw)<=1 ? math.pi/4*math.cos(math.pi/2*(x/bw)) : 0.0 laplace(x,bw) => 1/(2*bw)*math.exp(-math.abs(x/bw)) exponential(x,bw) => 1/bw*math.exp(-math.abs(x/bw)) silverman(x,bw) => math.abs(x/bw)<=0.5 ? 0.5*math.exp(-(x/bw)/2)*math.sin(x/bw/2+math.pi/4) : 0.0 tent(x,bw) => math.abs(x/bw)<=1 ? 1-math.abs(x/bw) : 0.0 cauchy(x,bw) => 1/(math.pi*bw*(1+sq(x/bw))) sinc(x,bw) => x==0 ? 1 : math.sin(math.pi*x/bw)/(math.pi*x/bw) wave(x,bw) => math.abs(x/bw)<=1 ? (1-math.abs(x/bw))*math.cos(math.pi*x/bw) : 0.0 parabolic(x,bw) => math.abs(x/bw)<=1 ? 1-sq(x/bw) : 0.0 power(x,bw) => math.abs(x/bw)<=1 ? math.pow(1-math.pow(math.abs(x/bw),3),3) : 0.0 loglogistic(x,bw) => 1/math.pow(1+math.abs(x/bw),2) morters(x,bw) => math.abs(x/bw)<=math.pi ? (1+math.cos(x/bw))/(2*math.pi*bw) : 0.0 kernel(x,bw,style)=> switch style 'Triangular' => triangular(x,bw) 'Gaussian' => gaussian(x,bw) 'Epanechnikov' => epanechnikov(x,bw) 'Logistic' => logistic(x,bw) 'Log Logistic' => loglogistic(x,bw) 'Cosine' => cosine(x,bw) 'Sinc' => sinc(x,bw) 'Laplace' => laplace(x,bw) 'Quartic' => quartic(x,bw) 'Parabolic' => parabolic(x,bw) 'Exponential' => exponential(x,bw) 'Silverman' => silverman(x,bw) 'Cauchy' => cauchy(x,bw) 'Tent' => tent(x,bw) 'Wave' => wave(x,bw) 'Power' => power(x,bw) 'Morters' => morters(x,bw) //----- GEWICHTE EINMAL VORBERECHNEN (Non-repaint Variante) ----- var float sumW = na var array<float> wArr = array.new<float>() if barstate.isfirst float tmpSum = 0.0 for i = 0 to bandwidth-1 j = math.pow(i,2)/math.pow(bandwidth,2) weight = kernel(j,1,kernelType) array.push(wArr, weight) tmpSum += weight sumW := tmpSum //----- NR-Regression pro Bar berechnen ----- var float nrp = na float _sum = 0.0 for i = 0 to bandwidth-1 _sum += nz(src[i]) * array.get(wArr,i) nrp := _sum / sumW //----- UP / DOWN Signale (wie im Indikator) ----- upSig = ta.crossover(nrp, nrp[1]) downSig = ta.crossunder(nrp, nrp[1]) //----- STRATEGIE-LOGIK ----- canLong = tradeSide != "short only" canShort = tradeSide != "long only" // Long-Ein-/Ausstiege if canLong and upSig strategy.entry("Long", strategy.long) if canLong and downSig strategy.close("Long") // Short-Ein-/Ausstiege (umgekehrte Signale) if canShort and downSig strategy.entry("Short", strategy.short) if canShort and upSig strategy.close("Short") //----- Fester (nicht-trailender) Stop-Loss ----- if strategy.position_size > 0 // Long sl = strategy.position_avg_price * (1 - stopPerc/100) strategy.exit("L-SL", from_entry = "Long", stop = sl) else if strategy.position_size < 0 // Short sl = strategy.position_avg_price * (1 + stopPerc/100) strategy.exit("S-SL", from_entry = "Short", stop = sl) //----- PLOTS (optional, für visuelle Kontrolle) ----- plot(nrp, color = color.aqua, title = "NRP-MA") plot(nrp + devs * ta.stdev(src, bandwidth), title = "Upper Dev", color = color.gray) plot(nrp - devs * ta.stdev(src, bandwidth), title = "Lower Dev", color = color.gray) plotshape(upSig, title="Up Signal", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny) plotshape(downSig, title="Down Signal", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny)

So passt du die Strategie an

EinstellungBedeutung
Trade Direction„long only“, „short only“ oder „both“
Bandwidth / Kernel / DeviationWie im Original-Indikator
Stop-Loss %Fixer Abstand in % vom Einstiegskurs (kein Trailing)

Hinweis:

  • Die Signale basieren 1 : 1 auf den „Up“-/„Down“-Labels der Non-Repaint-Version deines Indicators (Crossover / Crossunder des geglätteten Werts).
  • Die Stop-Loss-Orders werden bei jedem neuen Bar aktualisiert, bleiben aber starr auf dem einmal berechneten Abstand.
  • Passe bei Bedarf „default_qty_value“ oder andere strategy()-Parameter an deine Money-Management-Vorgaben an.

Viel Erfolg beim Back- und Live-Testen!

이 Q&A 공유하기