← К каталогу
Исходный код · ID 5062

Trend Entry_0 [TS_Indie]

#trend_enter .pine
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

Стратегия «Trend Entry_0 [TS_Indie]» предназначена для симуляции сделок в тестере TradingView. Она определяет изменение структуры цены на основе свинг-хаев и свинг-лоу и совершает входы в позицию при пробое структуры вверх или вниз. Визуально отображает линии текущей структуры тренда и метки точек входа и выхода.

Стратегия поддерживает фильтрацию по датам, позволяя ограничивать период тестирования. Доступны настройки включения/отключения сделок Long и Short, выбора стиля и цвета линий структуры, а также позиции таблицы результатов на графике.

Встроенная таблица результатов отображает статистику по всем сделкам, а также отдельно по Long и Short: количество сделок, выигрышные и убыточные, процент выигрышных и коэффициент Profit Factor. Коэффициент может подсвечиваться цветом в зависимости от заданных пользователем пороговых значений.

Настройки программы

НастройкаОписание
s_date Начальная дата фильтрации периода тестирования стратегии.
en_date Конечная дата фильтрации периода тестирования стратегии.
show_line Включает или отключает отображение линий структуры тренда на графике.
sw_line_style Стиль отображения линий структуры тренда (сплошной, пунктирный или точечный).
Color_sw Цвет линий структуры тренда и меток на графике.
B_long Включает или отключает возможность входа в длинную позицию (Long) при изменении структуры вверх.
S_short Включает или отключает возможность входа в короткую позицию (Short) при изменении структуры вниз.
Show_result Включает или отключает отображение таблицы результатов торгов на графике.
select_position Позиция размещения таблицы результатов на графике.
Factor_up Пороговое значение Profit Factor выше которого соответствующие показатели подсвечиваются цветом Factor_up_color.
Factor_up_color Цвет подсветки значений Profit Factor, которые выше установленного порога Factor_up.
Factor_donw Пороговое значение Profit Factor ниже которого соответствующие показатели подсвечиваются цветом Factor_donw_color.
Factor_donw_color Цвет подсветки значений Profit Factor, которые ниже установленного порога Factor_donw.

Поиск по коду файла

strategy("Trend Entry_0 [TS_Indie]" , overlay=true, max_labels_count=500 , max_lines_count = 500 ,max_boxes_count = 500, max_bars_back = 5000 , margin_long=0, margin_short=0 , initial_capital = 100000 )

Time_Filter = "Time Filter"
s_date = input.time(timestamp("01 Jan 1970"),"Start" , group = Time_Filter )
en_date = input.time(timestamp("01 Jan 2500"), "End ", group = Time_Filter )

show_line = input.bool(true,'Line', inline="1" , group = Time_Filter)
sw_line_style = input.string('⎯⎯⎯', '' , options = ['⎯⎯⎯', '----', '····'] , inline = '1' , group = Time_Filter)
Color_sw = input(title = " " , defval = #f700ff  , inline = "1" , group = Time_Filter)

Entry_Position = "Entry Condition"
B_long = input.bool( true ,"Long   |" , inline="2", group = Entry_Position)
S_short = input.bool( false ," Short" , inline="2", group = Entry_Position)

position(select) =>
    switch select
        "bottom_right"  => position.bottom_right
        "bottom_center" => position.bottom_center
        "bottom_left"   => position.bottom_left
        "top_center"    => position.top_center
        "top_left"      => position.top_left
        "top_right"     => position.top_right
        "mid_center"    => position.middle_center
        "mid_left"      => position.middle_left
        "mid_right"     => position.middle_right

result_group = "====== Trading Result Table ======"
Show_result = input.bool( true ,"Show Result" , inline = "1" , group = result_group ,tooltip = "The Profit Factor here is calculated using the formula:\n\(Number of Wins x Risk-Reward Ratio) / Number of Losses\n\This formula is based on the assumption that the risk per losing trade is fixed — for example, every losing trade costs exactly 1% of the account.\n\Because of this assumption, the calculated Profit Factor will not match TradingView’s result, since TradingView uses:\n\Gross Profit / Gross Loss\n\And in actual TradingView trades, the loss amount of each trade is not always equal, because the system doesn’t enforce a fixed-risk rule for every losing trade. " )
select_position = input.string("bottom_right", "", options = ["bottom_right", "bottom_center", "bottom_left", "top_center", "top_left" , "top_right" , "mid_center" , "mid_left" , "mid_right" ], group = result_group  , inline="1" , display = display.data_window)
Factor_up = input.float( 1.3 ,"Profit Factor > " , step=0.1 , inline = "2" , group = result_group )
Factor_up_color = input(title = "   " , defval = #a5d6a7  , inline = "2" , group = result_group)
Factor_donw = input.float( 1 ,"Profit Factor < " , step=0.1 , inline = "3" , group = result_group )
Factor_donw_color = input(title = "   " , defval = #faa1a4  , inline = "3" , group = result_group)

get_line_style(style) =>
    out = switch style
        '⎯⎯⎯'  => line.style_solid
        '----' => line.style_dashed
        '····' => line.style_dotted

var float big_high = na , var float big_low = na , var int Bar_big_high = 0 , var int Bar_big_low = 0
var float s_high = na , var float s_low = na , var int Bar_s_high = 0 , var int Bar_s_low = 0

var bool Structure_Trend = false
bool Change_up = false , bool Change_down = false

In_up_color = color.teal
In_down_color = #f23645

var H_bar_ary = array.new_int(0,na)  , var L_bar_ary = array.new_int(0,na)
var High_ary = array.new_float(0,na)  , var Low_ary = array.new_float(0,na) 

if na(s_high) and barstate.isconfirmed
    if close > open
        Structure_Trend := true
    s_high := high
    s_low := low

if not Structure_Trend and not na(s_high) and barstate.isconfirmed

    if close > s_high
        if low <= s_low 
            big_low := low , Bar_big_low := bar_index 
        if low > s_low 
            big_low := s_low , Bar_big_low := Bar_s_low

        array.unshift(Low_ary , big_low) , array.unshift(L_bar_ary , Bar_big_low)

        Structure_Trend := true , Change_up := true
        s_high := high , s_low := low , Bar_s_high := bar_index , Bar_s_low := bar_index 

    if not Change_up and low <= s_low 
        s_high := high , s_low := low , Bar_s_high := bar_index , Bar_s_low := bar_index 

if Structure_Trend and not na(s_high) and barstate.isconfirmed

    if close < s_low
        if high >= s_high
            big_high := high , Bar_big_high := bar_index
        if high < s_high
            big_high := s_high , Bar_big_high := Bar_s_high

        array.unshift(High_ary , big_high) , array.unshift(H_bar_ary , Bar_big_high)

        Structure_Trend := false , Change_down := true
        s_high := high , s_low := low , Bar_s_high := bar_index , Bar_s_low := bar_index 

    if not Change_down and high >= s_high 
        s_high := high , s_low := low , Bar_s_high := bar_index , Bar_s_low := bar_index 

var line sm_line = na , var line sm_line2 = na

if show_line
    if Change_up
        big_line = line.new( Bar_big_high[1] , big_high[1] , Bar_big_low , big_low  ,xloc = xloc.bar_index , color = Color_sw , style = get_line_style(sw_line_style))
    if Change_down
        big_line = line.new( Bar_big_high , big_high , Bar_big_low[1] , big_low[1]  ,xloc = xloc.bar_index , color = Color_sw , style = get_line_style(sw_line_style))

    line.delete(sm_line[1]) ,  line.delete(sm_line2[1])
    bb_bar = Structure_Trend ? Bar_big_low : Bar_big_high  ,    bb_price = Structure_Trend ? big_low : big_high
    cc_bar = Structure_Trend ? Bar_s_high : Bar_s_low      ,    cc_price = Structure_Trend ? s_high : s_low
    sm_line := line.new(  bb_bar  , bb_price , cc_bar , cc_price  ,xloc = xloc.bar_index , color = Color_sw , style = get_line_style(sw_line_style))

    sm_line2 := line.new( cc_bar , cc_price , bar_index , close ,xloc = xloc.bar_index , color = Color_sw , style = get_line_style(sw_line_style))

con_time = time >= s_date and time <= en_date

Label_Long = false , Label_Short = false
Label_Close_Long = false , Label_Close_Short = false

if Change_up and con_time and B_long and not S_short
    strategy.entry("Long", strategy.long , comment = "Long" )
    Label_Long := true

if Change_down and B_long and not S_short and strategy.position_size != 0
    strategy.close_all("Close")
    Label_Close_Long := true

if Change_down and con_time and S_short and not B_long
    strategy.entry("Short" , strategy.short , comment = "Short" )
    Label_Short := true

if Change_up and S_short and not B_long and strategy.position_size != 0
    strategy.close_all("Close")
   

Показано первые 50% кода (символов: 10241)