Almazov Trade: Opening Range FVG Hunter

Algorithms_ATS · study · 620 行 · 点赞 540 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// 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: Opening Range FVG Hunter", overlay=true, 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
 
color range_color = input.color(#2979FF, "Range color / Цвет диапазона", group="Opening Range / Стартовый диапазон", display=display.none)
int fill_transparency = input.int(88, "Range transparency / Прозрачность диапазона", minval=0, maxval=100, group="Opening Range / Стартовый диапазон", display=display.none)
int border_width = input.int(2, "Border width / Толщина рамки", minval=1, maxval=4, group="Opening Range / Стартовый диапазон", display=display.none)
int level_width = input.int(2, "Level width / Толщина уровней", minval=1, maxval=4, group="Opening Range / Стартовый диапазон", display=display.none)
bool show_range_caption = input.bool(true, "Opening Range caption / Подпись Opening Range", group="Opening Range / Стартовый диапазон", display=display.none)
int range_history = input.int(40, "Range history / Диапазонов на графике", minval=1, maxval=60, group="Opening Range / Стартовый диапазон", display=display.none)
bool highlight_breakout = input.bool(true, "Highlight first breakout / Подсвечивать первый пробой", group="Opening Range / Стартовый диапазон", display=display.none)
 
int average_bars = input.int(150, "Average: previous bars / Среднее: предыдущих баров", minval=1, group="FVG / FVG", tooltip="One shared average for bullish and bearish FVGs formed during the previous N bars. Divide by FVG count, not bar count. The current FVG is excluded. Entries require a complete N-bar window. / Общее среднее по бычьим и медвежьим FVG, сформированным за предыдущие N баров. Делим на число FVG, а не баров. Текущий FVG исключён. До накопления N баров входов нет.", display=display.none)
float fvg_multiplier = input.float(2.0, "Size multiplier / Множитель размера", minval=0.0, step=0.1, group="FVG / FVG", tooltip="Select an FVG only when its percentage size is strictly greater than average × multiplier. Bearish FVG: (H − L) / L × 100. Bullish FVG: (H − L) / H × 100. / Отбираем FVG, только если его размер в процентах строго больше среднего × множитель. Медвежий FVG: (H − L) / L × 100. Бычий FVG: (H − L) / H × 100.", display=display.none)
float gp_multiplier = input.float(2.0, "GP: opposing FVG size multiplier / GP: множитель размера встречного FVG", minval=0.0, step=0.1, group="FVG / FVG", tooltip="Close an open long on a new bearish FVG, or a short on a new bullish FVG, when its size is strictly greater than the same previous-N-bar average × this separate multiplier. Execute at the third candle's confirmed close, including the entry candle if applicable. Intrabar SL/TP has priority. Negative exits are labeled Stop; nonnegative exits are labeled GP. / Закрываем открытый лонг при новом медвежьем FVG, шорт — при новом бычьем, если размер строго больше того же среднего за предыдущие N баров × этот отдельный множитель. Выход по close третьей свечи после её закрытия, в том числе на свече входа. Внутрибарные SL/TP имеют приоритет. Убыточный выход обозначается Стоп; неотрицательный — GP.", display=display.none)
float min_rr = input.float(4.0, "Minimum RR, strictly greater / Минимальный RR, строго больше", minval=0, step=0.1, group="Trades / Сделки", display=display.none)
int fvg_history = input.int(60, "FVG drawings / FVG на графике", minval=1, maxval=120, group="Appearance / Оформление", tooltip="Drawing count only. Both entry and target FVGs must qualify at formation. Entry FVGs must form at/after the first NY OR breakout, in its direction, with their third candle closing outside OR. One trade per OR until the next OR starts. Drawing count does not limit stored zones. Partial fills never narrow the original boundaries. / Только число рисунков. Оба FVG должны пройти отбор при образовании. Входной FVG формируется на первом пробое NY OR или позже, по его направлению, с close третьей свечи за OR. Одна сделка на OR до начала следующего. Число рисунков не ограничивает расчёт. Частичные заполнения не сужают исходные границы.", display=display.none)
int trade_history = input.int(40, "Trade history on chart / Сделок на графике", minval=1, maxval=60, group="Trades / Сделки", tooltip="Entry on near-edge touch, SL at far edge, TP at the near edge of the nearest opposing large FVG whose RR is strictly greater than the configured minimum. Skip closer targets with insufficient RR; skip the entry only if no qualifying target exists. One first-touch attempt per entry zone; one position at a time. Both SL/TP on a candle count as SL. Entry candle follows open → nearer extreme → farther extreme → close (ties: Low first), so a target reached before entry is not credited. Signals are confirmed at candle close. Fixed fills without costs; gaps execute at model levels. An open position survives the next OR reset. / Вход при касании ближней границы, стоп на дальней, тейк на ближней границе ближайшего противоположного крупного FVG с RR строго выше заданного минимума. Более близкие цели с недостаточным RR пропускаем; вход пропускаем, только если подходящей цели нет. Одна попытка на первом касании зоны; одна позиция одновременно. Стоп и тейк на одной свече — стоп. Для свечи входа используется путь open → ближайший экстремум → дальний → close (равенство: сначала Low), поэтому тейк до входа не засчитывается. Сигналы подтверждаются на закрытии свечи. Исполнение по модельным уровням без издержек, включая гэпы. Открытая позиция переносится через новый OR.", display=display.none)
bool show_fvg = input.bool(true, "FVG zones / Зоны FVG", group="Appearance / Оформление", 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 myopen = open
float myhigh = high
float mylow = low
float myclose = close
int bar_ms = int(nz(timeframe.in_seconds()*1000, math.max(nz(time-time[1], 60000), 1)))
int right_time = nz(time_close, time)+5*bar_ms
int trade_right_bar = bar_index+5
 
string NY_TIMEZONE = "America/New_York"
string OR_SESSION = "0930-1000:23456"
int timeframe_minutes = timeframe.multiplier
bool valid_timeframe = timeframe.isminutes and timeframe_minutes<=30 and 30%timeframe_minutes==0
if barstate.isfirst
    if not valid_timeframe
        runtime.error(tr("Use 1, 2, 3, 5, 6, 10, 15 or 30 minutes for NY Opening Range 09:30–10:00.", "Используйте 1, 2, 3, 5, 6, 10, 15 или 30 минут для диапазона 09:30–10:00 Нью-Йорка."))
    if not chart.is_standard
        runtime.error(tr("Use a standard OHLC chart. Synthetic charts are not supported.", "Используйте обычный график OHLC. Синтетические графики не поддерживаются."))
 
breakout_side(float cl, float H, float L, bool available)=>
    int ans = 0
    if available
        if cl>H
            ans:=1
        else if cl<L
            ans:=-1
    ans
 
entry_allowed(int direction, int zone_range, bool eligible, int current_range, int breakout_direction, bool ready_range, bool consumed, bool during_range)=>
    bool ans = eligible and zone_range==current_range and direction==breakout_direction and ready_range and not consumed and not during_range
    ans
 
int range_start_time = timestamp(NY_TIMEZONE,year(time,NY_TIMEZONE),month(time,NY_TIMEZONE),dayofmonth(time,NY_TIMEZONE),9,30)
int range_end_time = timestamp(NY_TIMEZONE,year(time,NY_TIMEZONE),month(time,NY_TIMEZONE),dayofmonth(time,NY_TIMEZONE),10,0)
bool in_opening_range = not na(time(timeframe.period,OR_SESSION,NY_TIMEZONE))
bool range_starts = in_opening_range and (not in_opening_range[1] or range_start_time!=range_start_time[1])
int required_range_bars = int(30/timeframe_minutes)
var float range_high = na
var float range_low = na
var bool range_ready = false
var bool range_complete = false
var int range_bar_count = 0
var int range_session_id = na
var int range_direction = 0
var int breakout_bar = na
var bool range_trade_used = false
var box current_range_box = na
var line current_high_line = na
var line current_low_line = na
var array<box> range_boxes = array.new<box>()
var array<line> range_lines = array.new<line>()
var array<label> range_captions = array.new<label>()
 
if range_starts
    if time!=range_start_time and bar_index>0
        runtime.error(tr("The first Opening Range candle must start at 09:30 New York time.", "Первая свеча Opening Range должна начинаться в 09:30 Нью-Йорка."))
    if not na(current_high_line)
        current_high_line.set_extend(extend.none)
        current_high_line.set_x2(time)
        current_high_line:=na
    if not na(current_low_line)
        current_low_line.set_extend(extend.none)
        current_low_line.set_x2(time)
        current_low_line:=na
    range_high:=na
    range_low:=na
    range_ready:=false
    range_complete:=time==range_start_time
    range_bar_count:=0
    range_session_id:=range_start_time
    range_direction:=0
    breakout_bar:=na
    range_trade_used:=false
    if range_complete
        current_range_box:=box.new(left=time,top=high,right=time_close,bottom=low,xloc=xloc.bar_time,border_color=range_color,border_width=border_width,bgcolor=color.new(range_color,fill_transparency))
        range_boxes.push(current_range_box)
        if range_boxes.size()>range_history
            box.delete(range_boxes.shift())
 
if in_opening_range and range_complete
    if na(time_close) or time_close-time!=bar_ms or time_close>range_end_time
        runtime.error(tr("A candle crosses the Opening Range boundary or has an incompatible duration.", "Свеча пересекает границу Opening Range или имеет неподходящую длительность."))
    range_complete:=range_bar_count==0 or time==time_close[1]
    if range_complete
        range_bar_count+=1
        range_high:=na(range_high) ? high : math.max(range_high,high)
        range_low:=na(range_low) ? low : math.min(range_low,low)
        if not na(current_range_box)
            current_range_box.set_right(time_close)
            current_range_box.set_top(range_high)
            current_range_box.set_bottom(range_low)
        if barstate.isconfirmed and time_close==range_end_time
            range_ready:=range_bar_count==required_range_bars
            if range_ready
                current_high_line:=line.new(x1=time_close,y1=range_high,x2=time_close+bar_ms,y2=range_high,xloc=xloc.bar_time,extend=extend.right,color=range_color,width=level_width)
                current_low_line:=line.new(x1=time_close,y1=range_low,x2=time_close+bar_ms,y2=range_low,xloc=xloc.bar_time,extend=extend.right,color=range_color,width=level_width)
                range_lines.push(current_high_line)
                range_lines.push(current_low_line)
                while range_lines.size()>range_history*2
                    line.delete(range_lines.shift())
                if show_range_caption
                    float caption_price = range_high+(range_high-range_low)*0.05
                    label caption = label.new(x=range_start_time,y=caption_price,text="NY OPENING RANGE\n09:30–10:00",xloc=xloc.bar_time,style=label.style_label_down,color=range_color,textcolor=color.white,size=size.tiny)
                    range_captions.push(caption)
                    if range_captions.size()>range_history
                        label.delete(range_captions.shift())
    if not range_complete and not na(current_range_box)
        box.delete(current_range_box)
        current_range_box:=na
 
int first_breakout = breakout_side(close,range_high,range_low,range_ready and not in_opening_range and range_direction==0 and barstate.isconfirmed)
if first_breakout!=0
    range_direction:=first_breakout
    breakout_bar:=bar_index
barcolor(highlight_breakout ? first_breakout==1 ? up_trend : first_breakout==-1 ? down_trend : na : na)
 
type mybar
    float op
    float cl
    float hg
    float lw
type innerarrmybar
    array< mybar > arr
type node
    float L
    float H
    int id
    int bar_id
    int direction
    int range_id = na
    bool entry_eligible = false
    bool used = false
    bool active = true
    bool filled = false
    box area = na
var array<innerarrmybar> bars = array.new<innerarrmybar>()
var array<int> szbars = array.new<int>(1,0)
var array<node> zones = array.new<node>()
var array<node> fvg_drawings = array.new<node>()
if barstate.isfirst
    bars.push(innerarrmybar.new(arr=array.new<mybar>()))
 
isfvgbear(int idtf, int idpos)=>
    if idpos>0 and idpos+1<szbars.get(idtf)
        if bars.get(idtf).arr.get(idpos-1).lw>bars.get(idtf).arr.get(idpos+1).hg
            true
        else
            false
    else
        false
 
getfvgbear(int idtf, int idpos)=>
    if idpos>0 and idpos+1<szbars.get(idtf)
        if bars.get(idtf).arr.get(idpos-1).lw>bars.get(idtf).arr.get(idpos+1).hg
            [bars.get(idtf).arr.get(idpos+1).hg,bars.get(idtf).arr.get(idpos-1).lw]
        else
            [-1,-1]
    else
        [-1,-1]
 
isfvgex(int idtf, int idpos)=>
    if idpos>0 and idpos+1<szbars.get(idtf)
        if bars.get(idtf).arr.get(idpos-1).hg<bars.get(idtf).arr.get(idpos+1).lw
            true
        else
            false
    else
        false
 
getfvgex(int idtf, int idpos)=>
    if idpos>0 and idpos+1<szbars.get(idtf)
        if bars.get(idtf).arr.get(idpos-1).hg<bars.get(idtf).arr.get(idpos+1).lw
            [bars.get(idtf).arr.get(idpos-1).hg,bars.get(idtf).arr.get(idpos+1).lw]
        else
            [-1,-1]
    else
        [-1,-1]
 
addnewbar(int idtf, mybar w)=>
    innerarrmybar q = bars.get(idtf)
    q.arr.push(w)
    bars.set(idtf, q)
 
get_fvg_percent(int direction, float L, float H)=>
    float ans = 0.0
    if direction==1
        ans:=(H-L)/L*100.0
    else
        ans:=(H-L)/H*100.0
    ans
 
valid_setup(int direction, float entry, float stop, float take)=>
    bool ans = direction*(entry-stop)>0 and direction*(take-entry)>0
    ans
 
trace_exit(int d, float sl, float tp, float hg, float lw)=>
    float exit_fill = na
    int reason = 0
    bool hit_sl = d==1 and lw<=sl or d==-1 and hg>=sl
    bool hit_tp = d==1 and hg>=tp or d==-1 and lw<=tp
    if hit_sl
        exit_fill:=sl
        reason:=-1
    else if hit_tp
        exit_fill:=tp
        reason:=1
    [exit_fill, reason]
 
trace_gp_exit(int d, float prior_fill, int prior_reason, bool confirmed, bool window_ready, bool bear_fvg, bool bull_fvg, float sample, float average, float multiplier, float cl)=>
    float exit_fill = prior_fill
    int exit_reason = prior_reason
    bool opposing = d==1 and bear_fvg or d==-1 and bull_fvg
    if confirmed and window_ready and prior_reason==0 and opposing and not na(average)
        if sample>average*multiplier
            exit_fill:=cl
            exit_reason:=2
    [exit_fill,exit_reason]
 
get_result_percent(int direction, float entry, float fill)=>
    direction*(fill-entry)/entry*100.0
 
get_result_r(int direction, float entry, float stop, float fill)=>
    direction*(fill-entry)/math.abs(entry-stop)
 
draw_fvg(node w, int direction, float pct, float average)=>
    if show_fvg
        color col = direction==1 ? up_trend : down_trend
        string caption = "FVG · "+str.tostring(pct, "0.00")+"% · ×"+str.tostring(pct/average, "0.00")
        w.area:=box.new(left=time[2], top=w.H, right=right_time, bottom=w.L, xloc=xloc.bar_time, border_color=color.new(col, 30), border_width=1, bgcolor=color.new(col, 93), text=caption, text_color=color.new(col, 10), text_size=size.tiny, text_halign=text.align_right, text_valign=text.align_center)
        fvg_drawings.push(w)
        if fvg_drawings.size()>fvg_history
            node old = fvg_drawings.shift()
            box.delete(old.area)
            old.area:=na
    0
 
finish_fvg(node w)=>
    w.filled:=true
    w.active:=false
    if not na(w.area)
        w.area.set_right(nz(time_close, time))
        w.area.set_bgcolor(color.new(#7D8CA1, 96))
        w.area.set_border_color(color.new(#7D8CA1, 65))
        w.area.set_border_style(line.style_dotted)
        w.area.set_text_color(color.new(#7D8CA1, 35))
        w.area.set_text(tr("FVG · filled", "FVG · заполнен"))
    0
 
get_pair_rr(int d, float L, float H, float target)=>
    float entry = L
    float stop = H
    if d==1
        entry:=H
        stop:=L
    float ans = na
    if valid_setup(d,entry,stop,target)
        ans:=math.abs(target-entry)/math.abs(entry-stop)
    ans
 
can_touch(int d, float L, float H, int formed_bar, int at_bar, float prev_close, float hg, float lw)=>
    bool ans = false
    if at_bar>formed_bar
        if d==-1
            ans:=prev_close<L and hg>=L
        else
            ans:=prev_close>H and lw<=H
    ans
 
find_entry(int direction, float price)=>
    node ans = na
    float distance = na
    if zones.size()>0
        for int i=0 to zones.size()-1
            node w = zones.get(i)
            float edge = direction==1 ? w.H : w.L
            float gap = direction==1 ? price-edge : edge-price
            if entry_allowed(w.direction,w.range_id,w.entry_eligible,range_session_id,range_direction,range_ready,range_trade_used,in_opening_range) and w.direction==direction and not w.used and not w.filled and gap>0
                if na(ans) or gap<distance
                    ans:=w
                    distance:=gap
    ans
 
find_target(int direction, float entry, float stop, float op, float hg, float lw)=>
    node ans = na
    float distance = na
    bool high_first = math.abs(op-hg)<math.abs(op-lw)
    if zones.size()>0
        for int i=0 to zones.size()-1
            node w = zones.get(i)
            float edge = direction==1 ? w.L : w.H
            float gap = direction*(edge-entry)
            bool gone_first = direction==-1 and (op<=w.L or op<entry and not high_first and lw<=w.L) or direction==1 and (op>=w.H or op>entry and high_first and hg>=w.H)
            if w.direction==-direction and not w.filled and not gone_first and gap>0
                float rr = na
                if valid_setup(direction,entry,stop,edge)
                    rr:=gap/math.abs(entry-stop)
                if not na(rr) and rr>min_rr and (na(ans) or gap<distance)
                    ans:=w
                    distance:=gap
    ans
 
trace_entry_exit(int d, float entry, float sl, float tp, float op, float hg, float lw, float cl)=>
    bool high_first = math.abs(op-hg)<math.abs(op-lw)
    bool hit_sl = d==1 and lw<=sl or d==-1 and hg>=sl
    bool hit_tp = false
    if d==-1
        hit_tp:=((op>=entry or high_first) and lw<=tp) or cl<=tp
    else
        hit_tp:=((op<=entry or not high_first) and hg>=tp) or cl>=tp
    float fill = na
    int reason = 0
    if hit_sl
        fill:=sl
        reason:=-1
    else if hit_tp
        fill:=tp
        reason:=1
    [fill,reason]
 
type mytrade
    node source
    node target
    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_at)=>
    if not na(w.entry_line)
        w.entry_line.set_x2(right_at)
        w.stop_line.set_x2(right_at)
        w.take_line.set_x2(right_at)
    if not na(w.loss_box)
        w.loss_box.set_right(right_at)
        w.profit_box.set_right(right_at)
    0
 
finish_trade(mytrade w, int right_at, float fill, int reason)=>
    update_trade(w,right_at)
    if reason==2
        bool profitable = w.direction*(fill-w.entry)>=0
        color col = profitable ? #35D6A0 : #EF6376
        if not na(w.take_line)
            w.take_line.set_y1(fill)
            w.take_line.set_y2(fill)
            w.take_line.set_color(col)
        if not na(w.profit_box)
            w.profit_box.set_top(math.max(w.entry,fill))
            w.profit_box.set_bottom(math.min(w.entry,fill))
            w.profit_box.set_bgcolor(color.new(col,91))
    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)=>
    if show_setups
        color col = w.direction==1 ? up_trend : down_trend
        w.entry_line:=line.new(w.entry_bar, w.entry, trade_right_bar, w.entry, xloc=xloc.bar_index, color=#B0BED2, style=line.style_dotted, width=1)
        w.stop_line:=line.new(w.entry_bar, w.stop, trade_right_bar, w.stop, xloc=xloc.bar_index, color=#EF6376, width=2)
        w.take_line:=line.new(w.entry_bar, w.take, trade_right_bar, w.take, xloc=xloc.bar_index, color=#35D6A0, width=2)
        if show_zones
            w.loss_box:=box.new(left=w.entry_bar, top=math.max(w.entry, w.stop), right=trade_right_bar, bottom=math.min(w.entry, w.stop), xloc=xloc.bar_index, border_color=na, bgcolor=color.new(#EF6376, 90))
            w.profit_box:=box.new(left=w.entry_bar, top=math.max(w.entry, w.take), right=trade_right_bar, bottom=math.min(w.entry, w.take), xloc=xloc.bar_index, border_color=na, bgcolor=color.new(#35D6A0, 91))
        string direction_text = w.direction==1 ? tr("LONG", "ЛОНГ") : tr("SHORT", "ШОРТ")
        string entry_info = tr("FVG edge entry: ", "Вход на границе FVG: ")+str.tostring(w.entry, format.mintick)+"\nSL: "+str.tostring(w.stop, format.mintick)+"\nTP: "+str.tostring(w.take, format.mintick)+"\n"+tr("Potential return: ", "Потенциальная прибыль: ")+str.tostring(get_result_percent(w.direction, w.entry, w.take), "0.00")+"%"
        w.entry_label:=label.new(time, w.direction==1 ? low : high, 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)
    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_r = 0.0
bool long_entry_signal = false
bool short_entry_signal = false
bool take_profit_exit = false
bool stop_loss_exit = false
bool guaranteed_profit_exit = false
float event_entry_price = na
float event_exit_price = na
 
addnewbar(0, mybar.new(op=myopen, cl=myclose, hg=myhigh, lw=mylow))
if bars.get(0).arr.size()>3
    bars.get(0).arr.shift()
szbars.set(0, bars.get(0).arr.size())
int idpos = szbars.get(0)-2
bool ansbearfvg = isfvgbear(0, idpos)
bool ansexfvg = isfvgex(0, idpos)
[bearL, bearH] = getfvgbear(0, idpos)
[exL, exH] = getfvgex(0, idpos)
float fvg_sample = ansbearfvg ? get_fvg_percent(1, bearL, bearH) : ansexfvg ? get_fvg_percent(-1, exL, exH) : 0.0
float fvg_count = ansbearfvg or ansexfvg ? 1.0 : 0.0
float mean_size_per_bar = ta.sma(fvg_sample[1], average_bars)
float mean_count_per_bar = ta.sma(fvg_count[1], average_bars)
float average_size = mean_count_per_bar>0 ? mean_size_per_bar/mean_count_per_bar : na
bool ready = bar_index>=average_bars and not na(average_size)
 
bool occupied_at_open = not na(active_trade)
bool high_first = math.abs(open-high)<math.abs(open-low)
node short_zone = find_entry(-1,close[1])
node long_zone = find_entry(1,close[1])
node short_target = na
node long_target = na
float short_rr = na
float long_rr = na
bool short_ok = false
bool long_ok = false
if not na(short_zone)
    short_target:=find_target(-1,short_zone.L,short_zone.H,open,high,low)
    if not na(short_target)
        short_rr:=get_pair_rr(-1,short_zone.L,short_zone.H,short_target.H)
        short_ok:=not na(short_rr) and short_rr>min_rr and can_touch(-1,short_zone.L,short_zone.H,short_zone.bar_id,bar_index,close[1],high,low)
if not na(long_zone)
    long_target:=find_target(1,long_zone.H,long_zone.L,open,high,low)
    if not na(long_target)
        long_rr:=get_pair_rr(1,long_zone.L,long_zone.H,long_target.L)
        long_ok:=not na(long_rr) and long_rr>min_rr and can_touch(1,long_zone.L,long_zone.H,long_zone.bar_id,bar_index,close[1],high,low)
int direction = 0
if short_ok and long_ok
    direction:=open>=short_zone.L ? -1 : open<=long_zone.H ? 1 : high_first ? -1 : 1
else if short_ok
    direction:=-1
else if long_ok
    direction:=1
if barstate.isconfirmed and not occupied_at_open and direction!=0
    node source = direction==1 ? long_zone : short_zone
    node target = direction==1 ? long_target : short_target
    float entry = direction==1 ? source.H : source.L
    float stop = direction==1 ? source.L : source.H
    float take = direction==1 ? target.L : target.H
    float rr = direction==1 ? long_rr : short_rr
    mytrade w = mytrade.new(source=source,target=target,entry=entry,stop=stop,take=take,rr=rr,direction=direction,entry_bar=bar_index,entry_time=time)
    source.used:=true
    range_trade_used:=true
    active_trade:=start_trade(w)
    long_entry_signal:=direction==1
    short_entry_signal:=direction==-1
    event_entry_price:=entry
    if not na(source.area)
        source.area.set_border_color(#C8A765)
        source.area.set_border_width(2)
    if not na(target.area)
        target.area.set_border_color(#648FFF)
        target.area.set_border_width(2)
    if show_setups
        entry_tag:=label.new(trade_right_bar,w.entry,tr("Entry  ","Вход  ")+str.tostring(w.entry,format.mintick),xloc=xloc.bar_index,style=label.style_label_left,color=#26384F,textcolor=color.white,size=size.small)
        stop_tag:=label.new(trade_right_bar,w.stop,tr("SL  ","СТОП  ")+str.tostring(w.stop,format.mintick),xloc=xloc.bar_index,style=label.style_label_left,color=#9D3445,textcolor=color.white,size=size.small)
        take_tag:=label.new(trade_right_bar,w.take,tr("TP  ","ТЕЙК  ")+str.tostring(w.take,format.mintick),xloc=xloc.bar_index,style=label.style_label_left,color=#126A55,textcolor=color.white,size=size.small)
 
if barstate.isconfirmed
    if not na(active_trade)
        mytrade w = active_trade
        float exit_fill = na
        int exit_reason = 0
        if bar_index==w.entry_bar
            [f,r] = trace_entry_exit(w.direction,w.entry,w.stop,w.take,open,high,low,close)
            exit_fill:=f
            exit_reason:=r
        else
            [f,r] = trace_exit(w.direction,w.stop,w.take,high,low)
            exit_fill:=f
            exit_reason:=r
        [gp_fill,gp_reason] = trace_gp_exit(w.direction,exit_fill,exit_reason,barstate.isconfirmed,ready,ansbearfvg,ansexfvg,fvg_sample,average_size,gp_multiplier,close)
        exit_fill:=gp_fill
        exit_reason:=gp_reason
        if exit_reason!=0
            float result_r = get_result_r(w.direction, w.entry, w.stop, exit_fill)
            closed_trades+=1
            total_r+=result_r
            if result_r>0
                winning_trades+=1
            else if result_r<0
                losing_trades+=1
            take_profit_exit:=exit_reason==1
            stop_loss_exit:=exit_reason==-1 or (exit_reason==2 and result_r<0)
            guaranteed_profit_exit:=exit_reason==2 and result_r>=0
            event_exit_price:=exit_fill
            finish_trade(w,bar_index,exit_fill,exit_reason)
            if show_setups
                color exit_color = result_r>=0 ? #126A55 : #9D3445
                string exit_name = guaranteed_profit_exit ? tr("GP", "ГП") : exit_reason==1 ? tr("TP", "ТЕЙК") : "SL"
                string exit_text = stop_loss_exit ? exit_name : exit_name+" · "+(result_r>0 ? "+" : "")+str.tostring(result_r, "0.00")+"R"
                string exit_style = exit_fill>w.entry ? label.style_label_down : label.style_label_up
                if guaranteed_profit_exit
                    exit_style:=exit_fill>w.entry ? label.style_label_up : label.style_label_down
                string exit_info = tr("Exit: ", "Выход: ")+str.tostring(exit_fill, format.mintick)+"\n"+tr("Planned TP: ", "Плановый тейк: ")+str.tostring(w.take,format.mintick)
                if exit_reason==2
                    exit_info:=exit_info+"\n"+tr("Opposing FVG confirmed: third candle close.", "Встречный FVG подтверждён: close третьей свечи.")
                w.exit_label:=label.new(time, exit_reason==2 ? exit_fill : exit_fill>w.entry ? high : low, exit_text, xloc=xloc.bar_time, style=exit_style, color=exit_color, textcolor=color.white, size=size.small, tooltip=exit_info)
            active_trade:=na
            label.delete(entry_tag)
            label.delete(stop_tag)
            label.delete(take_tag)
            entry_tag:=na
            stop_tag:=na
            take_tag:=na
 
    int zi = zones.size()-1
    while zi>=0
        node w = zones.get(zi)
        if not w.used and can_touch(w.direction,w.L,w.H,w.bar_id,bar_index,close[1],high,low)
            w.used:=true
        bool filled = w.direction==-1 ? high>=w.H : low<=w.L
        if filled
            finish_fvg(w)
            zones.remove(zi)
        zi-=1
    if ready and fvg_sample>average_size*fvg_multiplier
        int new_direction = ansbearfvg ? -1 : 1
        bool new_zone_eligible = false
        new_zone_eligible:=range_ready and not in_opening_range and not range_trade_used and new_direction==range_direction and not na(breakout_bar) and bar_index>=breakout_bar and (new_direction==1 ? close>range_high : close<range_low)
        node w = node.new(L=ansbearfvg ? bearL : exL,H=ansbearfvg ? bearH : exH,id=bar_index-1,bar_id=bar_index,direction=new_direction,range_id=range_session_id,entry_eligible=new_zone_eligible)
        zones.push(w)
        draw_fvg(w,w.direction,fvg_sample,average_size)
 
if not na(active_trade)
    update_trade(active_trade,trade_right_bar)
    if not na(entry_tag)
        entry_tag.set_x(trade_right_bar)
        stop_tag.set_x(trade_right_bar)
        take_tag.set_x(trade_right_bar)
if fvg_drawings.size()>0
    for int i=0 to fvg_drawings.size()-1
        node w = fvg_drawings.get(i)
        if not w.filled and not na(w.area)
            w.area.set_right(right_time)
plot(event_entry_price,"Model entry / Модель: вход",display=display.data_window)
plot(event_exit_price,"Model exit / Модель: выход",display=display.data_window)
plot(average_size,"Average FVG size, % / Средний размер FVG, %",display=display.data_window)
 
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, 6, bgcolor = panel_bg, frame_color = #35465B, frame_width = 1, border_width = 0)
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 R", "Сумма R"), (total_r > 0 ? "+" : "") + str.tostring(total_r, "0.00") + "R", total_r >= 0 ? #00A078 : #DC4155)
 
    else
        table.clear(stats_table, 0, 0, 1, 5)
alertcondition(not use_ru and long_entry_signal,"EN · LONG entry","Almazov Trade: Opening Range FVG Hunter | LONG edge touch | {{ticker}} | {{interval}}")
alertcondition(use_ru and long_entry_signal,"RU · Вход ЛОНГ","Almazov Trade: Opening Range FVG Hunter | ЛОНГ на касании FVG | {{ticker}} | {{interval}}")
alertcondition(not use_ru and short_entry_signal,"EN · SHORT entry","Almazov Trade: Opening Range FVG Hunter | SHORT edge touch | {{ticker}} | {{interval}}")
alertcondition(use_ru and short_entry_signal,"RU · Вход ШОРТ","Almazov Trade: Opening Range FVG Hunter | ШОРТ на касании FVG | {{ticker}} | {{interval}}")
alertcondition(take_profit_exit,"TP / ТЕЙК","Almazov Trade: Opening Range FVG Hunter | TP | {{ticker}} | {{interval}}")
alertcondition(stop_loss_exit,"SL / СТОП","Almazov Trade: Opening Range FVG Hunter | SL | {{ticker}} | {{interval}}")
alertcondition(not use_ru and guaranteed_profit_exit,"EN · GP","Almazov Trade: Opening Range FVG Hunter | GP | Third candle close | {{ticker}} | {{interval}}")
alertcondition(use_ru and guaranteed_profit_exit,"RU · ГП","Almazov Trade: Opening Range FVG Hunter | ГП | Закрытие третьей свечи | {{ticker}} | {{interval}}")

← 返回列表