本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Algorithms_ATS
//@version=6
indicator("Funk RSI: Break the Rules [Almazov Trade]", overlay=false, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_bars_back=5000)
string ui_language = input.string("English", "Language / Язык", options=["English", "Русский"], group="Language / Язык", display=display.none)
bool use_ru = ui_language=="Русский"
tr(string en, string ru)=>
use_ru ? ru : en
int swing_bars = input.int(1, "Swing: bars on each side / Свинг: баров слева и справа", minval=1, maxval=60, group="Swing / Свинг", tooltip="The same number of bars on each side of the central candle for Swing High and Swing Low. Equal highs and lows are allowed. Entry uses the close of the last confirming candle. Directions are reversed: Swing High gives LONG, Swing Low gives SHORT. Skip Swing High if the central candle and all right-side candles are bearish; skip Swing Low if they are all bullish. / Одинаковое количество баров по обе стороны центральной свечи для Swing High и Swing Low. Равные экстремумы допускаются. Вход по закрытию последней подтверждающей свечи. Направления перевёрнуты: Swing High даёт ЛОНГ, Swing Low даёт ШОРТ. Swing High пропускается, если центральная свеча и все правые бары красные; Swing Low — если все зелёные.", display=display.none)
int rsi_length = input.int(14, "RSI length / Период RSI", minval=1, maxval=4880, group="RSI / RSI", tooltip="From the earliest qualifying RSI candle inside the swing, go back this many bars. LONG stop: that candle's Low. SHORT stop: its High. Trades with a stop on the wrong side of entry or missing history are skipped. The upper limit reserves 120 bars for the swing within Pine's history buffer. / От первого по времени бара свинга, где RSI вышел за нужный порог, отступаем назад на указанное количество баров. Стоп ЛОНГ: Low той свечи. Стоп ШОРТ: её High. Если стоп с неправильной стороны входа или не хватает истории, сделка пропускается. Верхняя граница оставляет 120 баров под свинг в буфере истории Pine.", display=display.none)
float rsi_lower = input.float(30, "Lower RSI threshold / Нижний порог RSI", minval=0, maxval=100, step=1, group="RSI / RSI", tooltip="Swing Low → SHORT: RSI must be strictly below this value on at least one candle in the entire swing, including the central candle. / Swing Low → ШОРТ: RSI должен быть строго ниже порога хотя бы на одной свече всего свинга, включая центральную.", display=display.none)
float rsi_upper = input.float(70, "Upper RSI threshold / Верхний порог RSI", minval=0, maxval=100, step=1, group="RSI / RSI", tooltip="Swing High → LONG: RSI must be strictly above this value on at least one candle in the entire swing, including the central candle. Simultaneous LONG and SHORT signals are skipped. / Swing High → ЛОНГ: RSI должен быть строго выше порога хотя бы на одной свече всего свинга, включая центральную. Одновременные сигналы ЛОНГ и ШОРТ пропускаются.", display=display.none)
int trade_history = input.int(40, "Trade history on chart / Сделок на графике", minval=1, maxval=60, group="Trades / Сделки", tooltip="Drawing history only; statistics include all closed trades in the loaded chart history. Fills are modeled from closed-bar OHLC, without Bar Magnifier, fees or slippage. / Только история разметки; статистика учитывает все закрытые сделки на загруженной истории графика. Исполнение моделируется по OHLC закрытых свечей: без Bar Magnifier, комиссий и проскальзывания.", display=display.none)
bool show_setups = input.bool(true, "Entry and exit drawings / Разметка входов и выходов", group="Appearance / Оформление", display=display.none)
bool show_zones = input.bool(true, "Risk and reward zones / Зоны риска и прибыли", group="Appearance / Оформление", display=display.none)
color up_trend = input.color(#26A69A, "LONG color / Цвет ЛОНГ", group="Appearance / Оформление", display=display.none)
color down_trend = input.color(#EF5350, "SHORT color / Цвет ШОРТ", group="Appearance / Оформление", display=display.none)
bool show_table = input.bool(true, "Statistics / Статистика", group="Table / Таблица", display=display.none)
int table_font = input.int(12, "Font size / Размер шрифта", minval=9, maxval=18, group="Table / Таблица", display=display.none)
float rsi_value = ta.rsi(close, rsi_length)
get_swing_state(int cnt)=>
bool swing_high = false
bool swing_low = false
bool rsi_high = false
bool rsi_low = false
if bar_index>=2*cnt
swing_high:=true
swing_low:=true
float H = high[cnt]
float L = low[cnt]
for int i=0 to 2*cnt
if high[i]>H
swing_high:=false
if low[i]<L
swing_low:=false
if not na(rsi_value[i])
if rsi_value[i]>rsi_upper
rsi_high:=true
if rsi_value[i]<rsi_lower
rsi_low:=true
[swing_high, swing_low, rsi_high, rsi_low]
get_candle_direction(int cnt)=>
bool bullish = false
bool bearish = false
if bar_index>=cnt
bullish:=true
bearish:=true
for int i=0 to cnt
if close[i]<=open[i]
bullish:=false
if close[i]>=open[i]
bearish:=false
[bullish, bearish]
get_direction(bool long_signal, bool short_signal)=>
int ans = 0
if long_signal and not short_signal
ans:=1
else if short_signal and not long_signal
ans:=-1
ans
get_reversed_direction(int original_direction, bool bullish, bool bearish)=>
int ans = 0
if original_direction==1 and not bullish
ans:=-1
else if original_direction==-1 and not bearish
ans:=1
ans
get_first_rsi_bar(int direction, int cnt)=>
int ans = na
if bar_index>=2*cnt
for int i=0 to 2*cnt
if not na(rsi_value[i])
if (direction==1 and rsi_value[i]>rsi_upper) or (direction==-1 and rsi_value[i]<rsi_lower)
ans:=i
ans
get_stop(int direction, int rsi_bar, int length)=>
float ans = na
if not na(rsi_bar)
int offset = rsi_bar+length
if bar_index>=offset
if direction==1
ans:=low[offset]
else if direction==-1
ans:=high[offset]
ans
valid_setup(int direction, float entry, float stop, float take)=>
bool ans = false
if not na(entry) and not na(stop) and not na(take)
ans:=direction*(entry-stop)>0 and direction*(take-entry)>0
ans
get_result_percent(int direction, float entry, float fill)=>
direction*(fill-entry)/entry*100.0
// Display only: no stage is saved or used to allow or block trades.
get_stage(int position, bool ready, bool has_rsi, bool conflict, bool rejected_color, int direction, int validity)=>
int ans = 1
if position==1
ans:=4
else if position==-1
ans:=5
else if not ready
ans:=0
else if not has_rsi
ans:=1
else if conflict
ans:=7
else if rejected_color
ans:=6
else if direction==0
ans:=2
else if validity==2
ans:=9
else if validity==3
ans:=8
else if validity==4
ans:=10
else
ans:=3
ans
stage_text(int stage)=>
switch stage
0 => tr("RSI warm-up", "Прогрев RSI")
1 => tr("Wait RSI", "Ждём RSI")
2 => tr("Wait Swing", "Ждём свинг")
3 => tr("Wait Close", "Ждём закрытие")
4 => tr("LONG open", "ЛОНГ открыт")
5 => tr("SHORT open", "ШОРТ открыт")
6 => tr("Skip: candle color", "Пропуск: цвет свечей")
7 => tr("Skip: both signals", "Пропуск: два сигнала")
8 => tr("Skip: invalid SL", "Пропуск: неверный стоп")
9 => tr("Skip: no SL history", "Пропуск: нет истории SL")
10 => tr("Skip: invalid TP", "Пропуск: неверный тейк")
=> "—"
// Same OHLC path model as the reference: nearest extreme first; ties visit Low first.
// Exit checks apply only to a position already open before the candle begins.
trace_exit(int d, float sl, float tp, float op, float hg, float lw, float cl)=>
float exit_fill = na
int reason = 0
bool high_first = math.abs(op-hg)<math.abs(op-lw)
array<float> path = array.from(op, hg, lw, cl)
if not high_first
path.set(1, lw)
path.set(2, hg)
if d*(op-sl)<=0
exit_fill:=op
reason:=-1
else if d*(op-tp)>=0
exit_fill:=op
reason:=1
if reason==0
for int segment=0 to 2
float a = path.get(segment)
float b = path.get(segment+1)
bool hit_sl = math.min(a, b)<=sl and math.max(a, b)>=sl
bool hit_tp = math.min(a, b)<=tp and math.max(a, b)>=tp
if hit_sl or hit_tp
bool stop_first = hit_sl and (not hit_tp or math.abs(sl-a)<=math.abs(tp-a))
if stop_first
exit_fill:=sl
reason:=-1
else
exit_fill:=tp
reason:=1
break
[exit_fill, reason]
type mytrade
float entry
float stop
float take
float rr
int direction
int entry_bar
int entry_time
line entry_line
line stop_line
line take_line
box loss_box
box profit_box
label entry_label
label exit_label
var array< mytrade > trades = array.new<mytrade>(0)
var mytrade active_trade = na
var label entry_tag = na
var label stop_tag = na
var label take_tag = na
update_trade(mytrade w, int right_bar)=>
if not na(w.entry_line)
w.entry_line.set_x2(right_bar)
w.stop_line.set_x2(right_bar)
w.take_line.set_x2(right_bar)
if not na(w.loss_box)
w.loss_box.set_right(right_bar)
w.profit_box.set_right(right_bar)
0
delete_trade(mytrade w)=>
line.delete(w.entry_line)
line.delete(w.stop_line)
line.delete(w.take_line)
box.delete(w.loss_box)
box.delete(w.profit_box)
label.delete(w.entry_label)
label.delete(w.exit_label)
0
start_trade(mytrade w, bool after_exit)=>
if show_setups
color col = w.direction==1 ? up_trend : down_trend
w.entry_line:=line.new(w.entry_bar, w.entry, bar_index+5, w.entry, xloc=xloc.bar_index, color=#B0BED2, style=line.style_dotted, width=1, force_overlay=true)
w.stop_line:=line.new(w.entry_bar, w.stop, bar_index+5, w.stop, xloc=xloc.bar_index, color=#EF6376, width=2, force_overlay=true)
w.take_line:=line.new(w.entry_bar, w.take, bar_index+5, w.take, xloc=xloc.bar_index, color=#35D6A0, width=2, force_overlay=true)
if show_zones
w.loss_box:=box.new(left=w.entry_bar, top=math.max(w.entry, w.stop), right=bar_index+5, bottom=math.min(w.entry, w.stop), xloc=xloc.bar_index, border_color=na, bgcolor=color.new(#EF6376, 90), force_overlay=true)
w.profit_box:=box.new(left=w.entry_bar, top=math.max(w.entry, w.take), right=bar_index+5, bottom=math.min(w.entry, w.take), xloc=xloc.bar_index, border_color=na, bgcolor=color.new(#35D6A0, 91), force_overlay=true)
string direction_text = w.direction==1 ? tr("LONG", "ЛОНГ") : tr("SHORT", "ШОРТ")
string entry_info = tr("Confirmation close: ", "Закрытие подтверждения: ")+str.tostring(w.entry, format.mintick)+"\nSL: "+str.tostring(w.stop, format.mintick)+"\nTP: "+str.tostring(w.take, format.mintick)+"\n"+tr("Stop distance: ", "Расстояние до стопа: ")+str.tostring(math.abs(w.entry-w.stop)/w.entry*100.0, "0.00")+"%"
float label_gap = after_exit ? math.max(high-low, syminfo.mintick)*0.5 : 0.0
float label_price = w.direction==1 ? low-label_gap : high+label_gap
w.entry_label:=label.new(w.entry_time, label_price, direction_text+" · RR "+str.tostring(w.rr, "0.00"), xloc=xloc.bar_time, style=w.direction==1 ? label.style_label_up : label.style_label_down, color=col, textcolor=color.white, size=size.small, tooltip=entry_info, force_overlay=true)
trades.push(w)
if trades.size()>trade_history
delete_trade(trades.shift())
w
var int closed_trades = 0
var int winning_trades = 0
var int losing_trades = 0
var float total_percent = 0.0
bool long_entry_signal = false
bool short_entry_signal = false
bool take_profit_exit = false
bool stop_loss_exit = false
float event_entry_price = na
float event_exit_price = na
[swing_high, swing_low, rsi_high, rsi_low] = get_swing_state(swing_bars)
[bullish_candles, bearish_candles] = get_candle_direction(swing_bars)
int original_direction = get_direction(swing_low and rsi_low, swing_high and rsi_high)
int signal_direction = get_reversed_direction(original_direction, bullish_candles, bearish_candles)
if barstate.isconfirmed
if not na(active_trade) and bar_index>active_trade.entry_bar
mytrade w = active_trade
[exit_fill, exit_reason] = trace_exit(w.direction, w.stop, w.take, open, high, low, close)
if exit_reason!=0
float result_percent = get_result_percent(w.direction, w.entry, exit_fill)
closed_trades+=1
total_percent+=result_percent
if result_percent>0
winning_trades+=1
else if result_percent<0
losing_trades+=1
take_profit_exit:=exit_reason==1
stop_loss_exit:=exit_reason==-1
event_exit_price:=exit_fill
update_trade(w, bar_index+5)
if show_setups
color exit_color = exit_reason==1 ? #126A55 : #9D3445
string exit_text = (exit_reason==1 ? tr("TP", "ТЕЙК") : tr("SL", "СТОП"))+" · "+(result_percent>0 ? "+" : "")+str.tostring(result_percent, "0.00")+"%"
w.exit_label:=label.new(time, exit_fill>w.entry ? high : low, exit_text, xloc=xloc.bar_time, style=exit_fill>w.entry ? label.style_label_down : label.style_label_up, color=exit_color, textcolor=color.white, size=size.small, tooltip=tr("Exit: ", "Выход: ")+str.tostring(exit_fill, format.mintick), force_overlay=true)
active_trade:=na
label.delete(entry_tag)
label.delete(stop_tag)
label.delete(take_tag)
entry_tag:=na
stop_tag:=na
take_tag:=na
// Signals during an open trade are ignored, not queued. A new signal at
// this close may be used if the previous position has already exited.
if na(active_trade) and signal_direction!=0
float entry = close
float take = signal_direction==1 ? high[swing_bars] : low[swing_bars]
int rsi_bar = get_first_rsi_bar(signal_direction, swing_bars)
float stop = get_stop(signal_direction, rsi_bar, rsi_length)
if valid_setup(signal_direction, entry, stop, take)
float rr = math.abs(take-entry)/math.abs(entry-stop)
mytrade w = mytrade.new(entry=entry, stop=stop, take=take, rr=rr, direction=signal_direction, entry_bar=bar_index, entry_time=time)
active_trade:=start_trade(w, take_profit_exit or stop_loss_exit)
long_entry_signal:=signal_direction==1
short_entry_signal:=signal_direction==-1
event_entry_price:=entry
if show_setups
entry_tag:=label.new(bar_index+5, entry, tr("Entry ", "Вход ")+str.tostring(entry, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=#26384F, textcolor=color.white, size=size.small, force_overlay=true)
stop_tag:=label.new(bar_index+5, stop, "SL "+str.tostring(stop, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=#9D3445, textcolor=color.white, size=size.small, force_overlay=true)
take_tag:=label.new(bar_index+5, take, "TP "+str.tostring(take, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=#126A55, textcolor=color.white, size=size.small, force_overlay=true)
if not na(active_trade)
int right_bar = bar_index+5
update_trade(active_trade, right_bar)
if not na(entry_tag)
entry_tag.set_x(right_bar)
stop_tag.set_x(right_bar)
take_tag.set_x(right_bar)
// Live setup preview uses the same rolling swing window and levels as entries.
// It is recalculated on each update; it does not queue an RSI event for later.
int position_direction = na(active_trade) ? 0 : active_trade.direction
int setup_validity = 0
if position_direction==0 and signal_direction!=0
float preview_take = signal_direction==1 ? high[swing_bars] : low[swing_bars]
int preview_rsi_bar = get_first_rsi_bar(signal_direction, swing_bars)
float preview_stop = get_stop(signal_direction, preview_rsi_bar, rsi_length)
if na(preview_stop)
setup_validity:=2
else if signal_direction*(close-preview_stop)<=0
setup_validity:=3
else if signal_direction*(preview_take-close)<=0
setup_validity:=4
else
setup_validity:=1
bool conflicting_signals = swing_low and rsi_low and swing_high and rsi_high
bool rejected_candle_color = original_direction!=0 and signal_direction==0
int current_stage = get_stage(position_direction, bar_index>=2*swing_bars and not na(rsi_value), rsi_high or rsi_low, conflicting_signals, rejected_candle_color, signal_direction, setup_validity)
string current_stage_text = stage_text(current_stage)
if current_stage==2 or current_stage==3
string waiting_direction = current_stage==3 ? (signal_direction==1 ? "LONG" : "SHORT") : rsi_high and rsi_low ? "LONG / SHORT" : rsi_high ? "LONG" : "SHORT"
current_stage_text+=" · "+waiting_direction
color panel_bg = #101720
color panel_header = #1A2635
color panel_alternate = #141E2A
color panel_text = #E4EAF2
color panel_muted = #A3B1C2
color panel_accent = #B7CBE3
var table stats_table = table.new(position.top_right, 2, 8, bgcolor=panel_bg, frame_color=#35465B, frame_width=1, border_width=0, force_overlay=true)
stat_row(int row, string caption, string value, color value_color)=>
color row_bg = row%2==0 ? panel_alternate : panel_bg
table.cell(stats_table, 0, row, caption, text_color=panel_muted, bgcolor=row_bg, text_size=table_font, text_halign=text.align_left)
table.cell(stats_table, 1, row, value, text_color=value_color, bgcolor=row_bg, text_size=table_font, text_halign=text.align_right)
float win_rate = closed_trades>0 ? winning_trades*100.0/closed_trades : na
if barstate.islast
if show_table
table.cell(stats_table, 0, 0, tr("STATISTICS", "СТАТИСТИКА"), text_color=panel_accent, bgcolor=panel_header, text_size=table_font-1, text_halign=text.align_left, text_formatting=text.format_bold)
table.cell(stats_table, 1, 0, tr("RESULT", "РЕЗУЛЬТАТ"), text_color=panel_accent, bgcolor=panel_header, text_size=table_font-1, text_halign=text.align_right, text_formatting=text.format_bold)
stat_row(1, tr("Closed trades", "Закрытые сделки"), str.tostring(closed_trades), panel_text)
stat_row(2, tr("Winning trades", "Прибыльные сделки"), str.tostring(winning_trades), #00A078)
stat_row(3, tr("Losing trades", "Убыточные сделки"), str.tostring(losing_trades), #DC4155)
stat_row(4, tr("Win rate", "Доля прибыльных"), closed_trades>0 ? str.tostring(win_rate, "0.00")+"%" : "—", panel_text)
stat_row(5, tr("Sum of returns", "Сумма доходностей"), (total_percent>0 ? "+" : "")+str.tostring(total_percent, "0.00")+"%", total_percent>=0 ? #00A078 : #DC4155)
color live_rsi_color = na(rsi_value) ? panel_muted : rsi_value>rsi_upper ? up_trend : rsi_value<rsi_lower ? down_trend : #BCAFFF
color live_stage_color = current_stage==4 ? up_trend : current_stage==5 ? down_trend : current_stage==3 ? #648FFF : current_stage==2 or current_stage>=6 ? #FFB547 : panel_muted
stat_row(6, tr("Current RSI", "Текущий RSI"), na(rsi_value) ? "—" : str.tostring(rsi_value, "0.00"), live_rsi_color)
stat_row(7, tr("Setup stage", "Этап сделки"), current_stage_text, live_stage_color)
table.cell_set_tooltip(stats_table, 1, 7, tr("Wait Swing: RSI exceeded a threshold within the current 2 × N + 1 candle window. The state expires when that candle leaves the window. Values and the setup preview update live; entries require a closed candle. Skip reasons refer to the current candidate only.", "Ждём свинг: RSI вышел за порог внутри текущего окна из 2 × N + 1 свечей. Когда эта свеча выходит из окна, условие истекает. Значения и предварительный этап обновляются онлайн; входы требуют закрытой свечи. Причина пропуска относится только к текущему кандидату."))
else
table.clear(stats_table, 0, 0, 1, 7)
color rsi_line_color = rsi_value>rsi_upper ? up_trend : rsi_value<rsi_lower ? down_trend : #BCAFFF
rsi_top = hline(100, "RSI 100", color=color.new(#A3B1C2, 85))
rsi_upper_line = hline(rsi_upper, "Upper threshold / Верхний порог", color=color.new(up_trend, 30), linestyle=hline.style_dashed)
hline(50, "RSI 50", color=color.new(#A3B1C2, 65), linestyle=hline.style_dotted)
rsi_lower_line = hline(rsi_lower, "Lower threshold / Нижний порог", color=color.new(down_trend, 30), linestyle=hline.style_dashed)
rsi_bottom = hline(0, "RSI 0", color=color.new(#A3B1C2, 85))
fill(rsi_top, rsi_upper_line, color=color.new(up_trend, 90), title="Upper RSI zone / Верхняя зона RSI")
fill(rsi_upper_line, rsi_lower_line, color=color.new(#8B78DC, 96), title="Neutral RSI zone / Нейтральная зона RSI")
fill(rsi_lower_line, rsi_bottom, color=color.new(down_trend, 90), title="Lower RSI zone / Нижняя зона RSI")
plot(rsi_value, "RSI glow / Подсветка RSI", color=color.new(rsi_line_color, 85), linewidth=6, display=display.pane, editable=false)
plot(rsi_value, "RSI", color=rsi_line_color, linewidth=2, trackprice=true, precision=2)
plot(long_entry_signal ? rsi_value : na, "LONG on RSI / ЛОНГ на RSI", color=up_trend, linewidth=4, style=plot.style_circles, display=display.pane)
plot(short_entry_signal ? rsi_value : na, "SHORT on RSI / ШОРТ на RSI", color=down_trend, linewidth=4, style=plot.style_circles, display=display.pane)
plot(event_entry_price, "Model entry / Модель: вход", display=display.data_window)
plot(event_exit_price, "Model exit / Модель: выход", display=display.data_window)
alertcondition(not use_ru and long_entry_signal, "EN · LONG entry", "Funk RSI: Break the Rules [Almazov Trade] LONG confirmed at bar close: {{ticker}} {{interval}}")
alertcondition(use_ru and long_entry_signal, "RU · Вход ЛОНГ", "Funk RSI: Break the Rules [Almazov Trade] ЛОНГ подтверждён на закрытии свечи: {{ticker}} {{interval}}")
alertcondition(not use_ru and short_entry_signal, "EN · SHORT entry", "Funk RSI: Break the Rules [Almazov Trade] SHORT confirmed at bar close: {{ticker}} {{interval}}")
alertcondition(use_ru and short_entry_signal, "RU · Вход ШОРТ", "Funk RSI: Break the Rules [Almazov Trade] ШОРТ подтверждён на закрытии свечи: {{ticker}} {{interval}}")
alertcondition(not use_ru and take_profit_exit, "EN · Take profit", "Funk RSI: Break the Rules [Almazov Trade] TP: {{ticker}} {{interval}}")
alertcondition(use_ru and take_profit_exit, "RU · Тейк", "Funk RSI: Break the Rules [Almazov Trade] ТЕЙК: {{ticker}} {{interval}}")
alertcondition(not use_ru and stop_loss_exit, "EN · Stop loss", "Funk RSI: Break the Rules [Almazov Trade] SL: {{ticker}} {{interval}}")
alertcondition(use_ru and stop_loss_exit, "RU · Стоп", "Funk RSI: Break the Rules [Almazov Trade] СТОП: {{ticker}} {{interval}}")