本页源码来自 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("Almazov Trade: MTF Structure & BOS Entries", overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_bars_back=100)
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
bool custom_tf = input.bool(false, "Set higher timeframe manually / Задать старший таймфрейм вручную", group="Timeframes / Таймфреймы", display=display.none)
int higher_tf = input.int(240, "Higher timeframe (minutes) / Старший таймфрейм, минут", minval=1, group="Timeframes / Таймфреймы", tooltip="Default: 4 times the chart timeframe. Custom HTF must be a larger integer multiple of the chart timeframe, up to 100 times. / Без галочки старший таймфрейм в 4 раза выше текущего. Свой ТФ должен быть больше текущего, кратен ему и превышать его не более чем в 100 раз.", display=display.none)
int D_swing_high = input.int(2, "Swing high: bars on each side / Swing high: баров слева и справа", minval=1, maxval=60, group="Structure / Структура", display=display.none)
int D_swing_low = input.int(2, "Swing low: bars on each side / Swing low: баров слева и справа", minval=1, maxval=60, group="Structure / Структура", display=display.none)
var int need_choch = input.bool(true, "Show CHoCH / BOS lines and labels / Показывать линии и подписи CHoCH / BOS", group="Structure / Структура", display=display.none) ? 1 : 0
float min_rr = input.float(1, "Minimum RR / Минимальный RR", minval=0.1, step=0.1, group="Trades / Сделки", tooltip="Target distance / stop distance. Setups below this ratio are skipped. / Расстояние до тейка / расстояние до стопа. Сделки с меньшим отношением пропускаются.", display=display.none)
int trade_history = input.int(40, "Trade history on chart / Сетапов на графике", minval=1, maxval=60, group="Trades / Сделки", tooltip="Drawing history only. Fills use closed-bar OHLC, without Bar Magnifier, fees or slippage. This is not a Strategy Tester report. / Только история разметки. Исполнение моделируется по OHLC закрытых свечей: без Bar Magnifier, комиссий и проскальзывания. Это не отчёт тестера.", display=display.none)
bool show_zones = input.bool(true, "Risk and reward zones / Зоны риска и прибыли", group="Trades / Сделки", display=display.none)
color up_trend = input.color(#26A69A, "LTF: bullish / Младшая: восходящая", group="Appearance / Оформление", display=display.none)
color down_trend = input.color(#EF5350, "LTF: bearish / Младшая: нисходящая", group="Appearance / Оформление", display=display.none)
color global_up_trend = input.color(#648FFF, "HTF: bullish / Старшая: восходящая", group="Appearance / Оформление", display=display.none)
color global_down_trend = input.color(#FFB547, "HTF: bearish / Старшая: нисходящая", group="Appearance / Оформление", display=display.none)
bool show_table = input.bool(true, "Structure and levels table / Таблица структуры и уровней", group="Appearance / Оформление", display=display.none)
int table_font = input.int(12, "Table font size / Размер шрифта таблицы", minval=8, maxval=18, group="Appearance / Оформление", display=display.none)
bool show_active = input.bool(true, "Active Swing High / Low levels / Активные уровни Swing High / Low", group="Analysis / Анализ", display=display.none)
bool show_taken = input.bool(true, "Broken BOS / CHoCH levels / Снятые уровни BOS / CHoCH", group="Analysis / Анализ", display=display.none)
bool show_sweeps = input.bool(true, "Mark sweeps / Отмечать Sweep", group="Analysis / Анализ", tooltip="Price crossed an existing level and closed back inside. Visual observation only; does not filter trades. / Тень пересекла существующий уровень, закрытие вернулось за него. Только дополнительная отметка; не фильтрует сделки.", display=display.none)
bool show_setups = input.bool(true, "Entry and exit drawings / Разметка входов и выходов", group="Analysis / Анализ", display=display.none)
var array<int> event_choch = array.new<int>(2, 0)
var array<bool> event_sweep_high = array.new<bool>(2, false)
var array<bool> event_sweep_low = array.new<bool>(2, false)
var array<label> sweep_labels = array.new<label>()
for int k=0 to 1
event_choch.set(k, 0)
event_sweep_high.set(k, false)
event_sweep_low.set(k, false)
var array< int > tfs = array.new<int>(0)
var int n = na
var int tfmul=timeframe.multiplier
if bar_index==0
if not timeframe.isminutes or not chart.is_standard
runtime.error(tr("Use standard minute or hourly charts only.", "Индикатор работает только на стандартных минутных и часовых графиках."))
if custom_tf and (higher_tf<=tfmul or higher_tf%tfmul!=0 or higher_tf>100*tfmul)
runtime.error(tr("HTF must be a larger integer multiple of the chart timeframe, up to 100 times.", "Старший ТФ должен быть больше текущего, кратен ему и превышать его не более чем в 100 раз."))
tfs.push(1)
tfs.push(custom_tf ? int(higher_tf/tfmul) : 4)
n:=tfs.size()
type mypair
float q
int bar_id
int sup_id
int bar_time
type mybar
float hg
float lw
int high_id
int low_id
int high_time
int low_time
type innerarrmybar
array< mybar > arr
var array<innerarrmybar> bars = array.new<innerarrmybar>()
var array< int > sz_bars = array.new<int>(n, 0)
var int dh = D_swing_high+1
var int dl = D_swing_low+1
get_high_id(int cnt)=>
float mx = high
int ans = bar_index
int pos=bar_index
for int i=0 to cnt-1
if high[i]>mx
mx:=high[i]
ans:=pos
pos-=1
ans
get_low_id(int cnt)=>
float mn = low
int ans = bar_index
int pos=bar_index
for int i=0 to cnt-1
if low[i]<mn
mn:=low[i]
ans:=pos
pos-=1
ans
get_high(int cnt)=>
float mx = high
for int i=0 to cnt-1
if high[i]>mx
mx:=high[i]
mx
get_low(int cnt)=>
float mn = low
for int i=0 to cnt-1
if low[i]<mn
mn:=low[i]
mn
cT = time
currentTime = int(cT / (1000*60*timeframe.multiplier))
is_swing_high(int idtf, int pos)=>
ans = true
if pos-D_swing_high<0 or pos+D_swing_high>=sz_bars.get(idtf)
ans:=false
else
float H = bars.get(idtf).arr.get(pos).hg
for int i=pos-D_swing_high to pos+D_swing_high
if bars.get(idtf).arr.get(i).hg>H and i!=pos
ans:=false
ans
is_swing_low(int idtf, int pos)=>
ans = true
if pos-D_swing_low<0 or pos+D_swing_low>=sz_bars.get(idtf)
ans:=false
else
float L = bars.get(idtf).arr.get(pos).lw
for int i=pos-D_swing_low to pos+D_swing_low
if bars.get(idtf).arr.get(i).lw<L and i!=pos
ans:=false
ans
get_min(int idtf, int l, int r)=>
float ans = 100000000
if l<=r
for int i=l to r
ans:=math.min(ans, bars.get(idtf).arr.get(i).lw)
ans
get_max(int idtf, int l, int r)=>
float ans = -1
if l<=r
for int i=l to r
ans:=math.max(ans, bars.get(idtf).arr.get(i).hg)
ans
fnd_sw_low(int idtf, int l, int r, int from_bar, int to_bar)=>
mypair res = mypair.new(-1, -1, -1, -1)
if l<=r
for int i=l to r
if bars.get(idtf).arr.get(i).low_id>from_bar and bars.get(idtf).arr.get(i).low_id<to_bar and (res.q==-1 or res.q>bars.get(idtf).arr.get(i).lw) and is_swing_low(idtf, i)
res := mypair.new(bars.get(idtf).arr.get(i).lw, bars.get(idtf).arr.get(i).low_id, i, bars.get(idtf).arr.get(i).low_time)
res
fnd_sw_high(int idtf, int l, int r, int from_bar, int to_bar)=>
mypair res = mypair.new(-1, -1, -1, -1)
if l<=r
for int i=l to r
if bars.get(idtf).arr.get(i).high_id>from_bar and bars.get(idtf).arr.get(i).high_id<to_bar and (res.q==-1 or res.q<bars.get(idtf).arr.get(i).hg) and is_swing_high(idtf, i)
res := mypair.new(bars.get(idtf).arr.get(i).hg, bars.get(idtf).arr.get(i).high_id, i, bars.get(idtf).arr.get(i).high_time)
res
type innerline
line[] arr
var array<innerline> lines_trand = array.new<innerline>()
var mypair nelem = mypair.new(-1, -1, -1, -1)
var array< mypair > now_low = array.new<mypair>(n, nelem)
var array< mypair > now_high = array.new<mypair>(n, nelem)
var array< int > first_build = array.new<int>(n, -2)
var array< int > started = array.new<int>(n, -1)
var array< int > type_of_trend = array.new<int>(n, 0)
var array< bool > trend_known = array.new<bool>(n, false)
var array< int > bos_dir = array.new<int>(n, 0)
var array< float > bos_entry = array.new<float>(n, na)
var array< float > bos_stop = array.new<float>(n, na)
var array< int > bos_step = array.new<int>(n, na)
var array< int > bos_high_id = array.new<int>(n, -1)
var array< int > bos_low_id = array.new<int>(n, -1)
var array< label > rr_labels = array.new<label>(0)
var array< line > choch_lines = array.new<line>(0)
var array< label > choch_labels = array.new<label>(0)
if bar_index==0
for i = 0 to n-1
bars.push(innerarrmybar.new(arr = array.new<mybar>(0)))
lines_trand.push(innerline.new(arr = array.new<line>(0)))
compact_history(int idtf)=>
innerarrmybar q = bars.get(idtf)
int count = q.arr.size()
if count>=80000
int removed = count-40000
int padding = math.max(D_swing_high, D_swing_low)
mypair hg = now_high.get(idtf)
mypair lw = now_low.get(idtf)
bool rebuild = (hg.q!=-1 and hg.sup_id<removed+padding) or (lw.q!=-1 and lw.sup_id<removed+padding)
array< mybar > tail = array.copy(array.slice(q.arr, removed, count))
q.arr.clear()
q.arr.concat(tail)
bars.set(idtf, q)
sz_bars.set(idtf, q.arr.size())
if rebuild
now_high.set(idtf, mypair.new(-1, -1, -1, -1))
now_low.set(idtf, mypair.new(-1, -1, -1, -1))
first_build.set(idtf, -2)
started.set(idtf, -1)
trend_known.set(idtf, false)
innerline r = lines_trand.get(idtf)
if r.arr.size()>0
for int j=0 to r.arr.size()-1
line.delete(r.arr.get(j))
r.arr.clear()
lines_trand.set(idtf, r)
else
if hg.q!=-1
now_high.set(idtf, mypair.new(hg.q, hg.bar_id, hg.sup_id-removed, hg.bar_time))
if lw.q!=-1
now_low.set(idtf, mypair.new(lw.q, lw.bar_id, lw.sup_id-removed, lw.bar_time))
0
addnewbar(int idtf, mybar w)=>
compact_history(idtf)
innerarrmybar q = bars.get(idtf)
q.arr.push(w)
bars.set(idtf, q)
sz_bars.set(idtf, q.arr.size())
set_val_line_trend(int idtf, mypair w)=>
innerline q = lines_trand.get(idtf)
line x=q.arr.get(q.arr.size()-1)
x.set_x2(w.bar_time)
x.set_y2(w.q)
q.arr.set(q.arr.size()-1, x)
lines_trand.set(idtf, q)
add_new_line_trend(int idtf, line w)=>
innerline q = lines_trand.get(idtf)
q.arr.push(w)
if q.arr.size()>100
line.delete(q.arr.shift())
lines_trand.set(idtf, q)
get_rr(float entry, float stop, float take)=>
math.abs(take-entry)/math.abs(entry-stop)
get_signal(int direction, float entry, float stop, float take, float rr)=>
bool ans = false
if direction!=0 and not na(entry) and not na(stop) and not na(take)
if direction*(entry-stop)>0 and direction*(take-entry)>0
ans:=get_rr(entry, stop, take)>=rr
ans
get_bos_step(int direction, float entry, float invalid, float op, float hg, float lw, float cl)=>
int ans = na
bool high_first = math.abs(op-hg)<math.abs(op-lw)
array< float > path = array.from(op, high_first ? hg : lw, high_first ? lw : hg, cl)
if direction*(op-entry)>0
ans:=-1
else if direction*(op-invalid)>=0
for int step=0 to 2
float price = path.get(step+1)
if direction*(price-invalid)<0
break
if direction*(price-entry)>0
ans:=step
break
ans
get_tf_name(int minutes)=>
string ans = str.tostring(minutes)+tr(" min", " мин")
if minutes%60==0
ans:=str.tostring(int(minutes/60))+tr(" h", " ч")
ans
draw_choch(int idtf, mypair w, color col, bool is_bos)=>
if show_taken
line x = line.new(x1=w.bar_time, y1=w.q, x2=time, y2=w.q, xloc=xloc.bar_time, color=col, style=line.style_dashed, width=idtf==0 ? 1 : 2)
label y = label.new(int((w.bar_time+time)/2), w.q, xloc=xloc.bar_time, color=color.new(chart.bg_color, 10), textcolor=col, style=label.style_label_center, text=(is_bos ? "BOS · " : "CHoCH · ")+get_tf_name(tfs.get(idtf)*tfmul), size=size.tiny)
choch_lines.push(x)
choch_labels.push(y)
if choch_lines.size()>60
line.delete(choch_lines.shift())
label.delete(choch_labels.shift())
0
type mytrade
float entry
float stop
float take
float rr
int direction
int entry_bar
int entry_time
int local_level_id
int target_level_id
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 mytrade pending_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, float fill_price, int fill_bar, int fill_time)=>
w.entry:=fill_price
w.entry_bar:=fill_bar
w.entry_time:=fill_time
if show_setups
color col = w.direction==1 ? up_trend : down_trend
w.entry_line:=line.new(fill_bar, fill_price, bar_index+5, fill_price, xloc=xloc.bar_index, color=#B0BED2, style=line.style_dotted, width=1)
w.stop_line:=line.new(fill_bar, w.stop, bar_index+5, w.stop, xloc=xloc.bar_index, color=#EF6376, width=2)
w.take_line:=line.new(fill_bar, w.take, bar_index+5, w.take, xloc=xloc.bar_index, color=#35D6A0, width=2)
if show_zones
w.loss_box:=box.new(left=fill_bar, top=math.max(fill_price, w.stop), right=bar_index+5, bottom=math.min(fill_price, w.stop), xloc=xloc.bar_index, border_color=na, bgcolor=color.new(#EF6376, 90))
w.profit_box:=box.new(left=fill_bar, top=math.max(fill_price, w.take), right=bar_index+5, bottom=math.min(fill_price, w.take), xloc=xloc.bar_index, border_color=na, bgcolor=color.new(#35D6A0, 91))
w.entry_label:=label.new(fill_time, fill_price, (w.direction==1 ? "LONG" : "SHORT")+" · 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)
trades.push(w)
if trades.size()>trade_history
delete_trade(trades.shift())
w
if barstate.isconfirmed
for int k=0 to 1
mypair h = now_high.get(k)
mypair l = now_low.get(k)
bool sh = h.q>0 and high>h.q and close<h.q and bos_high_id.get(k)!=h.bar_id
bool sl = l.q>0 and low<l.q and close>l.q and bos_low_id.get(k)!=l.bar_id
event_sweep_high.set(k, sh)
event_sweep_low.set(k, sl)
if show_sweeps and (sh or sl)
if sh
sweep_labels.push(label.new(time, high, "Sweep H · "+get_tf_name(tfmul*tfs.get(k)), xloc=xloc.bar_time, style=label.style_label_down, color=color.new(down_trend, 75), textcolor=down_trend, size=size.tiny))
if sl
sweep_labels.push(label.new(time, low, "Sweep L · "+get_tf_name(tfmul*tfs.get(k)), xloc=xloc.bar_time, style=label.style_label_up, color=color.new(up_trend, 75), textcolor=up_trend, size=size.tiny))
while sweep_labels.size()>60
label.delete(sweep_labels.shift())
int entry_global_trend = type_of_trend.get(1)==1 ? 1 : -1
float entry_global_high = now_high.get(1).q
float entry_global_low = now_low.get(1).q
int entry_global_high_broken = bos_high_id.get(1)
int entry_global_low_broken = bos_low_id.get(1)
int entry_global_high_id = now_high.get(1).bar_id
int entry_global_low_id = now_low.get(1).bar_id
for int i=0 to n-1
bos_dir.set(i, 0)
bos_entry.set(i, na)
bos_stop.set(i, na)
bos_step.set(i, na)
int direction = type_of_trend.get(i)==1 ? 1 : -1
mypair level = direction==1 ? now_high.get(i) : now_low.get(i)
mypair opposite = direction==1 ? now_low.get(i) : now_high.get(i)
int broken_id = direction==1 ? bos_high_id.get(i) : bos_low_id.get(i)
if barstate.isconfirmed and trend_known.get(i) and level.q>0 and opposite.q>0 and broken_id!=level.bar_id
int step = get_bos_step(direction, level.q, opposite.q, open, high, low, close)
if not na(step)
bos_dir.set(i, direction)
bos_entry.set(i, level.q)
bos_stop.set(i, math.round_to_mintick(opposite.q-direction*syminfo.mintick))
bos_step.set(i, step)
if direction==1
bos_high_id.set(i, level.bar_id)
else
bos_low_id.set(i, level.bar_id)
if need_choch==1
color col = i==0 ? (direction==1 ? up_trend : down_trend) : (direction==1 ? global_up_trend : global_down_trend)
draw_choch(i, level, col, true)
for int i=0 to n-1
int tf=tfs.get(i)
color now_up_trend = i==0 ? up_trend : global_up_trend
color now_down_trend = i==0 ? down_trend : global_down_trend
int now_width = i==0 ? 2 : 4
if barstate.isconfirmed and bar_index>=tf-1 and (currentTime+1)%tf==0 and int(time[tf-1]/(60000*tf*tfmul))==int(time/(60000*tf*tfmul))
addnewbar(i, mybar.new(get_high(tf), get_low(tf), get_high_id(tf), get_low_id(tf), time[bar_index-get_high_id(tf)], time[bar_index-get_low_id(tf)]))
sw_low = is_swing_low(i, sz_bars.get(i)-D_swing_low-1)
sw_high = is_swing_high(i, sz_bars.get(i)-D_swing_high-1)
if first_build.get(i)!=0
if sw_low==true and now_low.get(i).q==-1
now_low.set(i, mypair.new(bars.get(i).arr.get(sz_bars.get(i)-dl).lw, bars.get(i).arr.get(sz_bars.get(i)-dl).low_id, sz_bars.get(i)-dl, bars.get(i).arr.get(sz_bars.get(i)-dl).low_time))
first_build.set(i, first_build.get(i)+1)
if sw_high==true and now_high.get(i).q==-1
now_high.set(i, mypair.new(bars.get(i).arr.get(sz_bars.get(i)-dh).hg, bars.get(i).arr.get(sz_bars.get(i)-dh).high_id, sz_bars.get(i)-dh, bars.get(i).arr.get(sz_bars.get(i)-dh).high_time))
first_build.set(i, first_build.get(i)+1)
if started.get(i)==-1
if now_low.get(i).q!=-1 and now_low.get(i).q>get_min(i, now_low.get(i).sup_id, sz_bars.get(i)-1)
now_low.set(i, fnd_sw_low(i, now_low.get(i).sup_id+1, sz_bars.get(i)-dl, -1, bar_index+1))
if now_low.get(i).q!=-1 and now_low.get(i).q>get_min(i, now_low.get(i).sup_id, sz_bars.get(i)-1)
now_low.set(i, mypair.new(-1, -1, -1, -1))
if now_high.get(i).q!=-1 and now_high.get(i).q<get_max(i, now_high.get(i).sup_id, sz_bars.get(i)-1)
now_high.set(i, fnd_sw_high(i, now_high.get(i).sup_id+1, sz_bars.get(i)-dh, -1, bar_index+1))
if now_high.get(i).q!=-1 and now_high.get(i).q<get_max(i, now_high.get(i).sup_id, sz_bars.get(i)-1)
now_high.set(i, mypair.new(-1, -1, -1, -1))
first_build.set(i, (now_low.get(i).q==-1 ? -1 : 0)+(now_high.get(i).q==-1 ? -1 : 0))
if started.get(i)==1
if type_of_trend.get(i)==1
if sw_high==true and bars.get(i).arr.get(sz_bars.get(i)-dh).hg>now_high.get(i).q
new_low = fnd_sw_low(i, now_high.get(i).sup_id, math.min(sz_bars.get(i)-dl, sz_bars.get(i)-dh), now_high.get(i).bar_id, bars.get(i).arr.get(sz_bars.get(i)-dh).high_id)
new_high = mypair.new(bars.get(i).arr.get(sz_bars.get(i)-dh).hg, bars.get(i).arr.get(sz_bars.get(i)-dh).high_id, sz_bars.get(i)-dh, bars.get(i).arr.get(sz_bars.get(i)-dh).high_time)
if new_low.q!=-1 and new_low.q<=get_min(i, new_low.sup_id, sz_bars.get(i)-1) and new_low.bar_id>now_high.get(i).bar_id and new_low.q<now_high.get(i).q
now = line.new(x1=now_high.get(i).bar_time, y1=now_high.get(i).q, x2=new_low.bar_time, y2=new_low.q, color=now_up_trend, width = now_width, xloc=xloc.bar_time)
add_new_line_trend(i, now)
now := line.new(x1=new_low.bar_time, y1=new_low.q, x2=new_high.bar_time, y2=new_high.q, color=now_up_trend, width = now_width, xloc=xloc.bar_time)
add_new_line_trend(i, now)
now_high.set(i, new_high)
now_low.set(i, new_low)
else
set_val_line_trend(i, new_high)
now_high.set(i, new_high)
if bars.get(i).arr.get(sz_bars.get(i)-1).lw<now_low.get(i).q
event_choch.set(i, -1)
if need_choch==1
draw_choch(i, now_low.get(i), now_down_trend, false)
now_low.set(i, mypair.new(-1, -1, -1, -1))
first_build.set(i, -1)
started.set(i, -1)
type_of_trend.set(i, 0)
else
if sw_low==true and bars.get(i).arr.get(sz_bars.get(i)-dl).lw<now_low.get(i).q
new_high = fnd_sw_high(i, now_low.get(i).sup_id, math.min(sz_bars.get(i)-dh, sz_bars.get(i)-dl), now_low.get(i).bar_id, bars.get(i).arr.get(sz_bars.get(i)-dl).low_id)
new_low = mypair.new(bars.get(i).arr.get(sz_bars.get(i)-dl).lw, bars.get(i).arr.get(sz_bars.get(i)-dl).low_id, sz_bars.get(i)-dl, bars.get(i).arr.get(sz_bars.get(i)-dl).low_time)
if new_high.q!=-1 and new_high.q>=get_max(i, new_high.sup_id, sz_bars.get(i)-1) and new_high.bar_id>now_low.get(i).bar_id and new_high.q>now_low.get(i).q
now = line.new(x1=now_low.get(i).bar_time, y1=now_low.get(i).q, x2=new_high.bar_time, y2=new_high.q, color=now_down_trend, width = now_width, xloc=xloc.bar_time)
add_new_line_trend(i, now)
now := line.new(x1=new_high.bar_time, y1=new_high.q, x2=new_low.bar_time, y2=new_low.q, color=now_down_trend, width = now_width, xloc=xloc.bar_time)
add_new_line_trend(i, now)
now_low.set(i, new_low)
now_high.set(i, new_high)
else
set_val_line_trend(i, new_low)
now_low.set(i, new_low)
if bars.get(i).arr.get(sz_bars.get(i)-1).hg>now_high.get(i).q
event_choch.set(i, 1)
if need_choch==1
draw_choch(i, now_high.get(i), now_up_trend, false)
now_high.set(i, mypair.new(-1, -1, -1, -1))
first_build.set(i, -1)
started.set(i, -1)
type_of_trend.set(i, 1)
if started.get(i)==-1 and first_build.get(i)==0
started.set(i, 1)
trend_known.set(i, true)
if now_low.get(i).bar_id<now_high.get(i).bar_id
if lines_trand.get(i).arr.size()>0
set_val_line_trend(i, now_low.get(i))
now = line.new(x1=now_low.get(i).bar_time, y1=now_low.get(i).q, x2=now_high.get(i).bar_time, y2=now_high.get(i).q, color=now_up_trend, width = now_width, xloc=xloc.bar_time)
add_new_line_trend(i, now)
type_of_trend.set(i, 1)
else
if lines_trand.get(i).arr.size()>0
set_val_line_trend(i, now_high.get(i))
now = line.new(x1=now_high.get(i).bar_time, y1=now_high.get(i).q, x2=now_low.get(i).bar_time, y2=now_low.get(i).q, color=now_down_trend, width = now_width, xloc=xloc.bar_time)
add_new_line_trend(i, now)
type_of_trend.set(i, 0)
trace_orders(int d, float ent, float sl, float tp, bool was_active, float op, float hg, float lw, float cl)=>
float fill = na
float exit_fill = na
int reason = 0
bool positioned = was_active
bool high_first = math.abs(op-hg)<math.abs(op-lw)
array<float> path = array.from(op, high_first ? hg : lw, high_first ? lw : hg, cl)
if not positioned and d*(op-ent)>=0
fill:=op
positioned:=true
if positioned
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)
if not positioned and d*(a-ent)<=0 and d*(b-ent)>=0
fill:=ent
positioned:=true
a:=ent
if positioned
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))
exit_fill:=stop_first ? sl : tp
reason:=stop_first ? -1 : 1
break
[fill, exit_fill, reason]
bool filled_this_bar = not na(active_trade)
bool event_entry = false
bool event_exit = false
bool event_setup = false
bool event_rr = false
int event_direction = 0
float event_entry_price = na
float event_exit_price = na
int event_exit_reason = 0
var int model_closed = 0
var int last_entry_bar = na
var float last_entry_price = na
var float last_exit_price = na
var int last_exit_bar = na
var int last_exit_reason = 0
var int last_direction = 0
mytrade candidate = not na(active_trade) ? active_trade : pending_trade
if barstate.isconfirmed and not na(candidate)
[fill, exit_fill, exit_reason] = trace_orders(candidate.direction, candidate.entry, candidate.stop, candidate.take, not na(active_trade), open, high, low, close)
if not na(fill)
active_trade:=start_trade(candidate, fill, bar_index, time)
pending_trade:=na
event_entry:=true
event_direction:=active_trade.direction
event_entry_price:=fill
last_entry_bar:=bar_index
last_entry_price:=fill
last_direction:=active_trade.direction
if not na(active_trade)
filled_this_bar:=true
if active_trade.direction==1
bos_high_id.set(0, math.max(bos_high_id.get(0), active_trade.local_level_id))
else
bos_low_id.set(0, math.max(bos_low_id.get(0), active_trade.local_level_id))
if exit_reason!=0
mytrade w = active_trade
update_trade(w, bar_index+5)
if show_setups
w.exit_label:=label.new(time, exit_fill>w.entry ? high : low, exit_reason==1 ? "TP" : "SL", xloc=xloc.bar_time, style=exit_fill>w.entry ? label.style_label_down : label.style_label_up, color=exit_reason==1 ? #126A55 : #9D3445, textcolor=color.white, size=size.small)
if exit_reason==1
if w.direction==1
bos_high_id.set(1, math.max(bos_high_id.get(1), w.target_level_id))
else
bos_low_id.set(1, math.max(bos_low_id.get(1), w.target_level_id))
event_exit:=true
event_direction:=w.direction
event_exit_price:=exit_fill
event_exit_reason:=exit_reason
model_closed+=1
last_exit_price:=exit_fill
last_exit_bar:=bar_index
last_exit_reason:=exit_reason
active_trade:=na
pending_trade:=na
label.delete(entry_tag)
label.delete(stop_tag)
label.delete(take_tag)
entry_tag:=na
stop_tag:=na
take_tag:=na
if event_entry and not na(active_trade) and show_setups
entry_tag:=label.new(bar_index+5, active_trade.entry, tr("Entry ", "Вход ")+str.tostring(active_trade.entry, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=#26384F, textcolor=color.white, size=size.small)
stop_tag:=label.new(bar_index+5, active_trade.stop, "SL "+str.tostring(active_trade.stop, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=#9D3445, textcolor=color.white, size=size.small)
take_tag:=label.new(bar_index+5, active_trade.take, "TP "+str.tostring(active_trade.take, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, color=#126A55, textcolor=color.white, size=size.small)
if not filled_this_bar and bos_dir.get(0)!=0
int direction = bos_dir.get(0)
float entry = bos_entry.get(0)
float stop = bos_stop.get(0)
float take = direction==1 ? entry_global_high : entry_global_low
int target_id = direction==1 ? entry_global_high_id : entry_global_low_id
int broken_id = direction==1 ? entry_global_high_broken : entry_global_low_broken
if direction!=entry_global_trend or target_id==broken_id or take<=0
take:=na
if not get_signal(direction, entry, stop, take, min_rr)
event_rr:=true
string reason = na(take) ? tr("No active HTF BOS target in the entry direction: RR is undefined.", "Нет активного старшего BOS в сторону входа: RR не определён.") : direction*(take-entry)<=0 ? tr("The HTF BOS target is not beyond the entry: invalid RR.", "Старший BOS не находится впереди входа: RR не подходит.") : "RR "+str.tostring(get_rr(entry, stop, take), "0.00")+" < "+str.tostring(min_rr, "0.00")+tr(". Entry skipped.", ". Вход пропущен.")
label mark = label.new(bar_index, entry, "RR\n✕", xloc=xloc.bar_index, style=label.style_label_down, color=color.new(chart.bg_color, 100), textcolor=#FFB547, size=size.small, tooltip=reason)
rr_labels.push(mark)
if rr_labels.size()>60
label.delete(rr_labels.shift())
float previous_setup_entry = na(pending_trade) ? na : pending_trade.entry
float previous_setup_stop = na(pending_trade) ? na : pending_trade.stop
float previous_setup_take = na(pending_trade) ? na : pending_trade.take
int previous_setup_direction = na(pending_trade) ? 0 : pending_trade.direction
if na(active_trade) and barstate.isconfirmed
pending_trade:=na
int direction = type_of_trend.get(0)==1 ? 1 : -1
int global_trend = type_of_trend.get(1)==1 ? 1 : -1
mypair level = direction==1 ? now_high.get(0) : now_low.get(0)
mypair opposite = direction==1 ? now_low.get(0) : now_high.get(0)
mypair target = direction==1 ? now_high.get(1) : now_low.get(1)
int broken_id = direction==1 ? bos_high_id.get(0) : bos_low_id.get(0)
int target_broken_id = direction==1 ? bos_high_id.get(1) : bos_low_id.get(1)
float entry = level.q
float stop = math.round_to_mintick(opposite.q-direction*syminfo.mintick)
float take = target.q
bool available = trend_known.get(0) and direction==global_trend and entry>0 and opposite.q>0 and take>0 and broken_id!=level.bar_id and target_broken_id!=target.bar_id and direction*(entry-close)>=0
if available and get_signal(direction, entry, stop, take, min_rr)
pending_trade:=mytrade.new(entry=entry, stop=stop, take=take, rr=get_rr(entry, stop, take), direction=direction, local_level_id=level.bar_id, target_level_id=target.bar_id)
event_setup:=na(previous_setup_entry) or entry!=previous_setup_entry or stop!=previous_setup_stop or take!=previous_setup_take or direction!=previous_setup_direction
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)
var array<line> active_lines = array.new<line>(4, na)
var array<label> active_labels = array.new<label>(4, na)
if barstate.islast
for int k=0 to 3
int idtf = int(k/2)
bool is_high = k%2==0
mypair level = is_high ? now_high.get(idtf) : now_low.get(idtf)
int broken = is_high ? bos_high_id.get(idtf) : bos_low_id.get(idtf)
line.delete(active_lines.get(k))
label.delete(active_labels.get(k))
active_lines.set(k, na)
active_labels.set(k, na)
if show_active and level.q>0 and level.bar_id!=broken
color col = idtf==0 ? (is_high ? up_trend : down_trend) : (is_high ? global_up_trend : global_down_trend)
string txt = (is_high ? "Swing High · " : "Swing Low · ")+get_tf_name(tfmul*tfs.get(idtf))
active_lines.set(k, line.new(level.bar_time, level.q, time_close, level.q, xloc=xloc.bar_time, extend=extend.right, color=col, width=idtf==0 ? 1 : 2))
active_labels.set(k, label.new(time_close, level.q, txt, xloc=xloc.bar_time, style=label.style_label_right, color=color.new(chart.bg_color, 15), textcolor=col, size=size.tiny))
color panel_bg = #0B1220
color panel_text = #E7EDF7
color panel_muted = #8C9EB8
color panel_accent = #8DB1FF
var table panel = table.new(position.top_right, 3, 13, bgcolor=panel_bg, frame_color=#304665, frame_width=1)
cell(int c, int r, string cell_text, color col)=>
table.cell(panel, c, r, cell_text, text_color=col, text_size=table_font, text_halign=c==0 ? text.align_left : text.align_right)
level_text(mypair w, int broken)=>
w.q<=0 ? "—" : str.tostring(w.q, format.mintick)+(w.bar_id==broken ? tr(" · broken", " · снят") : "")
distance_text(mypair w)=>
w.q>0 and close!=0 ? (w.q>=close ? "+" : "")+str.tostring(100*(w.q-close)/close, "0.00")+"%" : "—"
if bar_index==0
table.merge_cells(panel, 0, 0, 2, 0)
table.merge_cells(panel, 0, 12, 2, 12)
if barstate.islast
if show_table
cell(0, 0, "ALMAZOV TRADE · STRUCTURE", panel_accent)
cell(0, 1, tr("Timeframe", "Таймфрейм"), panel_muted)
for int k=0 to 1
color col = k==0 ? (type_of_trend.get(k)==1 ? up_trend : down_trend) : (type_of_trend.get(k)==1 ? global_up_trend : global_down_trend)
cell(k+1, 1, get_tf_name(tfmul*tfs.get(k)), panel_text)
cell(k+1, 2, not trend_known.get(k) ? "—" : type_of_trend.get(k)==1 ? tr("↑ BULLISH", "↑ РОСТ") : tr("↓ BEARISH", "↓ СНИЖЕНИЕ"), col)
cell(k+1, 3, level_text(now_high.get(k), bos_high_id.get(k)), panel_text)
cell(k+1, 4, distance_text(now_high.get(k)), panel_muted)
cell(k+1, 5, level_text(now_low.get(k), bos_low_id.get(k)), panel_text)
cell(k+1, 6, distance_text(now_low.get(k)), panel_muted)
cell(0, 2, tr("Direction", "Направление"), panel_muted)
cell(0, 3, "Swing High", panel_muted)
cell(0, 4, tr("To high", "До High"), panel_muted)
cell(0, 5, "Swing Low", panel_muted)
cell(0, 6, tr("To low", "До Low"), panel_muted)
mytrade w = not na(active_trade) ? active_trade : pending_trade
cell(0, 7, tr("Status", "Состояние"), panel_muted)
cell(1, 7, na(w) ? tr("WAITING", "ОЖИДАНИЕ") : not na(active_trade) ? tr("ENTRY CONFIRMED", "ВХОД ПОДТВЕРЖДЁН") : tr("SETUP", "СЕТАП"), panel_accent)
cell(2, 7, na(w) ? "—" : w.direction==1 ? "LONG" : "SHORT", panel_text)
cell(0, 8, tr("Entry", "Вход"), panel_muted)
cell(1, 8, na(w) ? "—" : str.tostring(w.entry, format.mintick), panel_text)
cell(0, 9, "SL", panel_muted)
cell(1, 9, na(w) ? "—" : str.tostring(w.stop, format.mintick), down_trend)
cell(0, 10, "TP", panel_muted)
cell(1, 10, na(w) ? "—" : str.tostring(w.take, format.mintick), up_trend)
cell(0, 11, "RR", panel_muted)
cell(1, 11, na(w) ? "—" : str.tostring(w.rr, "0.00")+" : 1", panel_accent)
cell(0, 12, tr("OHLC · confirmed at bar close", "OHLC · подтверждение на закрытии свечи"), panel_muted)
else
table.clear(panel, 0, 0, 2, 12)
plot(trend_known.get(0) ? (type_of_trend.get(0)==1 ? 1 : -1) : na, color=type_of_trend.get(0)==1 ? up_trend : down_trend, title="LTF trend / Младший тренд", display=display.status_line)
plot(trend_known.get(1) ? (type_of_trend.get(1)==1 ? 1 : -1) : na, color=type_of_trend.get(1)==1 ? global_up_trend : global_down_trend, title="HTF trend / Старший тренд", display=display.status_line)
plot(event_entry ? event_entry_price : na, "Model entry / Модель: вход", display=display.data_window)
plot(event_exit ? event_exit_price : na, "Model exit / Модель: выход", display=display.data_window)
plot(event_entry ? event_direction : na, "Model direction / Модель: направление", display=display.data_window)
plot(event_exit ? event_exit_reason : na, "Model exit reason (+1 TP, -1 SL) / Модель: выход (+1 TP, -1 SL)", display=display.data_window)
alertcondition(not use_ru and (event_entry and event_direction==1), "EN · LONG entry", "BOS LONG confirmed at bar close: {{ticker}} {{interval}}")
alertcondition(use_ru and (event_entry and event_direction==1), "RU · Вход LONG", "BOS LONG подтверждён на закрытой свече: {{ticker}} {{interval}}")
alertcondition(not use_ru and (event_entry and event_direction==-1), "EN · SHORT entry", "BOS SHORT confirmed at bar close: {{ticker}} {{interval}}")
alertcondition(use_ru and (event_entry and event_direction==-1), "RU · Вход SHORT", "BOS SHORT подтверждён на закрытой свече: {{ticker}} {{interval}}")
alertcondition(not use_ru and (event_exit and event_exit_reason==1), "EN · TP reached", "HTF BOS / TP reached: {{ticker}} {{interval}}")
alertcondition(use_ru and (event_exit and event_exit_reason==1), "RU · Достигнут TP", "Достигнут старший BOS / TP: {{ticker}} {{interval}}")
alertcondition(not use_ru and (event_exit and event_exit_reason==-1), "EN · SL reached", "SL reached: {{ticker}} {{interval}}")
alertcondition(use_ru and (event_exit and event_exit_reason==-1), "RU · Достигнут SL", "Достигнут SL: {{ticker}} {{interval}}")
alertcondition(not use_ru and (event_setup), "EN · Potential setup", "BOS to BOS setup ready: {{ticker}} {{interval}}. Entry has not filled yet.")
alertcondition(use_ru and (event_setup), "RU · Потенциальный сетап", "Подготовлен сетап BOS → BOS: {{ticker}} {{interval}}. Это ещё не исполненный вход.")
alertcondition(not use_ru and (event_rr), "EN · Entry rejected: RR", "BOS skipped: invalid RR or no active HTF target. {{ticker}} {{interval}}")
alertcondition(use_ru and (event_rr), "RU · Вход отклонён: RR", "BOS пропущен: неподходящий RR или нет активной цели старшего ТФ. {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and bos_dir.get(0)!=0), "EN · LTF BOS", "LTF BOS: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and bos_dir.get(0)!=0), "RU · BOS младшего ТФ", "BOS младшего ТФ: {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and bos_dir.get(1)!=0), "EN · HTF BOS", "HTF BOS: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and bos_dir.get(1)!=0), "RU · BOS старшего ТФ", "BOS старшего ТФ: {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and event_choch.get(0)!=0), "EN · LTF CHoCH", "LTF CHoCH: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and event_choch.get(0)!=0), "RU · CHoCH младшего ТФ", "CHoCH младшего ТФ: {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and event_choch.get(1)!=0), "EN · HTF CHoCH", "HTF CHoCH: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and event_choch.get(1)!=0), "RU · CHoCH старшего ТФ", "CHoCH старшего ТФ: {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and event_sweep_high.get(0)), "EN · LTF Sweep High", "LTF Sweep High: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and event_sweep_high.get(0)), "RU · Sweep High младшего ТФ", "Sweep High младшего ТФ: {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and event_sweep_low.get(0)), "EN · LTF Sweep Low", "LTF Sweep Low: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and event_sweep_low.get(0)), "RU · Sweep Low младшего ТФ", "Sweep Low младшего ТФ: {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and event_sweep_high.get(1)), "EN · HTF Sweep High", "HTF Sweep High: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and event_sweep_high.get(1)), "RU · Sweep High старшего ТФ", "Sweep High старшего ТФ: {{ticker}} {{interval}}")
alertcondition(not use_ru and (barstate.isconfirmed and event_sweep_low.get(1)), "EN · HTF Sweep Low", "HTF Sweep Low: {{ticker}} {{interval}}")
alertcondition(use_ru and (barstate.isconfirmed and event_sweep_low.get(1)), "RU · Sweep Low старшего ТФ", "Sweep Low старшего ТФ: {{ticker}} {{interval}}")