Strategy · Pine Script v5 · On the chart

Breaking fractals

by DaniilOkrug· code credited to icewalk

This strategy identifies trend changes using fractals from a higher timeframe and the current chart timeframe.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code571
Settings23inputs
LicenceMIT
Last update4 years ago15 Dec 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

571 lines of Pine Script v5 from Breaking fractals (2).txt, published under MIT. Keep the author's credit and licence lines when you reuse it.

Breaking fractals (2).txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © icewalk

// Описание стратегии. Не удалять. Описание необходимо для напоминания об алгоритме стратегии.
// Стратегия включает 2 режима торговли: Обычный и Усредняющий.
// Обычный режим использует фракталы страшего таймфрема(параметр) и текущего таймфрема для поиска точек входа.
// Фракталы старшего таймфрема используются для определения тренда. Фракталы младшего для открытия ордеров. 
// Оредра открываются на смене тренда или пробитии фракталов по тренду на текущем таймфрейме.
// Усредняющий режим используется только при активном режиме ордеров - ЛОНГ(в стартегии будут открываться только лонг оредра)
// Данный режим имеет 2 разных вида: пирамидинг 1 и пирамидинг больше одного.

//@version=5
strategy("[Order] Breaking fractals", overlay=true, margin_long=100, margin_short=100, default_qty_type=strategy.percent_of_equity, default_qty_value=1, pyramiding = 99, calc_on_every_tick=false, max_bars_back=500)

//--Импортирование библиотке----------------------------------------------------

//Загружаем библиотеку с фракталами
import icewalk/Fractals/1

//--Импортирование библиотек конец----------------------------------------------

//---Ввод Данных----------------------------------------------------------------
// /--Первая группа входных параметров--/
GRP1 = "Фракталы"
higherTimeframe = input.timeframe("D", title="Крупный таймфрейм ", group=GRP1)
n_daily = input.int(2, title="Период для крупного фрактала", minval=2, group=GRP1)
current_n = input.int(2, title="Период для текущего фрактала", minval=2, group=GRP1)
showFractals = input.string("Никакие", title="Какие фрактала показать", options=["Текущий таймфрейм", "Крупный таймфрейм", "Никакие"], group=GRP1)
stopLossType = "Дневной"

// /--Вторая группа входных параметров--/
GRP2 = "Настройка торговли"
tradingMode_tooltipMessage = "Обычный - ордера открываются при пробитии фрактала и закрываются при смене тренда. Усреднение - если при смене тренда сделки находятся в убытке, то они остаются открытыми и усредняются по ходу такого же тренда. Работает только для режима ордеров ЛОНГ!"
tradingMode = input.string("Обычный", title="Торговый режим", options=["Обычный", "Усреднение"], tooltip=tradingMode_tooltipMessage, group=GRP2)

// /--Третья группа входных параметров--/
GRP3 = "Режим Усреднение"
pyramidingMode_tooltipMessage = "Один ордер - в тренде открывается один ордер и 1 усредняющий ордер на каждый слудующий тренд. Множественные ордера - в тренде открывается сетка ордеров и в слудеющих тренда усредняется на определенный объем."
pyramidingMode = input.string("Один ордер", title="Режим пирмадинга", options=["Один ордер", "Множественные ордера"], group=GRP3)
takeProfit_tooltipMessage = "Работает для обоих режимов пирамидинга. [Один ордер] При достижении TP сделки закрываются и ищется новый сигнал. Если 0, тогда сделки закрываются только на смене тренда при наличии прибыли. В ином случае, сделки продолжат усредняться. [Множественные ордера] При достижении TP, стоплосс переносится на 1% прибыли. Сделки закрываются на смене трнеда, если они имеют прибыль."
takeProfit_percent = input.float(1, title="TP(%)", step=1, tooltip=takeProfit_tooltipMessage, group=GRP3) / 100
orderSizeAveragingSizePercent = input.float(5, title="Объем усредняющей сделки(%)", tooltip="Для пирамидинга - Множественные ордера", group=GRP3) / 100
noLoss_close = input.bool(false, title="Закрыть позиции в безубыток", group=GRP3)
showTakeProfit = input.bool(false, title="Показать TP", group=GRP3)
showStopLoss = input.bool(false, title="Показать SL", tooltip="SL для режима пирамидинга 'Множественные ордера'", group=GRP3)


// /--Четвертая группа входных параметров--/
GRP4 = "Настройки ордеров"
ordersAllowedSide = input.string("Обе", title="В какую сторону открывать сделки", options=["Обе", "Лонг", "Шорт"], group=GRP4)
ordersOnTrend = input.bool(false, title="Докупать по тренду", group=GRP4)
openZeroOrder = input.bool(true, title="Открыть нулевой ордер", group=GRP4)
allowOrdersDistance = input.bool(false, title="Использовать расстояние между ордерами", group=GRP4)
ordersDistance = input.float(5, title="Минимальное расстояние между ордерами(%)", step=0.1, group=GRP4) / 100

// /--Пятая группа входных параметров--/
GRP5 = "Визуальная часть"
showFractalsLineForBreaking = input.bool(true, title="Показать фракталы с пробоем", group=GRP5)
showTrend = input.bool(true, title="Показать тренд", group=GRP5)
showStopLossTrend = input.bool(true, title="Показать стоплосс", group=GRP5)
showStatistics = input.bool(true, title="Показать статистику", group=GRP5)
showAveragePriceOfOpenOrders = input.bool(true, title="Показать среднюю цену открытых позиций", group=GRP5)
showTrendLine = input.bool(false, title="Показать линию тренда", inline="Линия тренда", group=GRP5)
showLineLabel = input.bool(false, title="Показать информацию о тренде", inline="Линия тренда", tooltip="Может быть активна только с параметром 'Показать линию тренда'", group=GRP5)

//---Ввод Данных конец----------------------------------------------------------

//---Проверка условии стратегии-------------------------------------------------

//Если условия стратегии не совпадают с входными параметрами, то выводится ошибка
if tradingMode == "Усреднение" and ordersAllowedSide != "Лонг"
    runtime.error("Для режима торговли 'Усреднения' должен быть включен режим 'Лонг' ордеров. Активные параметры -> Торговый режим: Усреднение. В какую сторону открывать сделки: " + ordersAllowedSide)
    
//---Проверка условии стратегии конце-------------------------------------------

//---Фракталы крупного таймфрейма-----------------------------------------------

//Верх и низ свечи с другого таймфрейма
[high_daily, low_daily] = request.security(syminfo.tickerid, higherTimeframe, [high, low], barmerge.gaps_on)

// Врехний фрактал
var high_dailyArr = array.new_float(2*n_daily+5)
var low_dailyArr = array.new_float(2*n_daily+5)

bool upflagDownFrontier_daily = true
bool upflagUpFrontier0_daily = true
bool upflagUpFrontier1_daily = true
bool upflagUpFrontier2_daily = true
bool upflagUpFrontier3_daily = true
bool upflagUpFrontier4_daily = true

bool flagUpFrontier_daily = na
bool upFractal_daily = na

if nz(high_daily) != 0 
    array.unshift(high_dailyArr, high_daily)
    array.pop(high_dailyArr)

    for i = 1 to n_daily
        upflagDownFrontier_daily := upflagDownFrontier_daily and (array.get(high_dailyArr, n_daily-i) < array.get(high_dailyArr, n_daily))
        upflagUpFrontier0_daily := upflagUpFrontier0_daily and (array.get(high_dailyArr, n_daily+i) < array.get(high_dailyArr, n_daily))
        upflagUpFrontier1_daily := upflagUpFrontier1_daily and (array.get(high_dailyArr, n_daily+1) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+i + 1) < array.get(high_dailyArr, n_daily))
        upflagUpFrontier2_daily := upflagUpFrontier2_daily and (array.get(high_dailyArr, n_daily+1) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+2) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+i + 2) < array.get(high_dailyArr, n_daily))
        upflagUpFrontier3_daily := upflagUpFrontier3_daily and (array.get(high_dailyArr, n_daily+1) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+2) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+3) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+i + 3) < array.get(high_dailyArr, n_daily))
        upflagUpFrontier4_daily := upflagUpFrontier4_daily and (array.get(high_dailyArr, n_daily+1) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+2) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+3) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+4) <= array.get(high_dailyArr, n_daily) and array.get(high_dailyArr, n_daily+i + 4) < array.get(high_dailyArr, n_daily))
    flagUpFrontier_daily := upflagUpFrontier0_daily or upflagUpFrontier1_daily or upflagUpFrontier2_daily or upflagUpFrontier3_daily or upflagUpFrontier4_daily
    
// Нижний фрактал
bool downflagDownFrontier_daily = true
bool downflagUpFrontier0_daily = true
bool downflagUpFrontier1_daily = true
bool downflagUpFrontier2_daily = true
bool downflagUpFrontier3_daily = true
bool downflagUpFrontier4_daily = true

bool flagDownFrontier_daily = na
bool downFractal_daily = na

if nz(low_daily) != 0 
    array.unshift(low_dailyArr, low_daily)
    array.pop(low_dailyArr)
    
    for i = 1 to n_daily
        downflagDownFrontier_daily := downflagDownFrontier_daily and (array.get(low_dailyArr, n_daily-i) > array.get(low_dailyArr, n_daily))
        downflagUpFrontier0_daily := downflagUpFrontier0_daily and (array.get(low_dailyArr, n_daily+i) > array.get(low_dailyArr, n_daily))
        downflagUpFrontier1_daily := downflagUpFrontier1_daily and (array.get(low_dailyArr, n_daily+1) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+i + 1) > array.get(low_dailyArr, n_daily))
        downflagUpFrontier2_daily := downflagUpFrontier2_daily and (array.get(low_dailyArr, n_daily+1) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+2) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+i + 2) > array.get(low_dailyArr, n_daily))
        downflagUpFrontier3_daily := downflagUpFrontier3_daily and (array.get(low_dailyArr, n_daily+1) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+2) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+3) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+i + 3) > array.get(low_dailyArr, n_daily))
        downflagUpFrontier4_daily := downflagUpFrontier4_daily and (array.get(low_dailyArr, n_daily+1) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+2) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+3) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+4) >= array.get(low_dailyArr, n_daily) and array.get(low_dailyArr, n_daily+i + 4) > array.get(low_dailyArr, n_daily))
    flagDownFrontier_daily := downflagUpFrontier0_daily or downflagUpFrontier1_daily or downflagUpFrontier2_daily or downflagUpFrontier3_daily or downflagUpFrontier4_daily
    
        
upFractal_daily := higherTimeframe != timeframe.period ? (upflagDownFrontier_daily and flagUpFrontier_daily) : Fractals.getUpFractal(n_daily)
downFractal_daily := higherTimeframe != timeframe.period? (downflagDownFrontier_daily and flagDownFrontier_daily) : Fractals.getDownFractal(n_daily)
//---Фракталы крупного таймфрейма-----------------------------------------------

//---Фракталы текущего таймфрейм------------------------------------------------

upFractal = Fractals.getUpFractal(current_n)

downFractal = Fractals.getDownFractal(current_n)

//---Фракталы текущего таймфрейма конце---------------------------------------------------------------

//---Основной алгорит---------------------------------------------------------------

var float upFractal_highDaily = na      //Цена верхнего фрактала для крупного таймфрейма
var float downFractal_lowDaily = na     //Цена ниженго фрактала для крупного таймфрейма
var float upFractal_high = na           //Цена верхнего фрактала для текущего таймфрейма
var float downFractal_low = na          //Цена нижнего фрактала для текущего фрактала

var float previousOrderPrice = na       //Цена предыдущего ордера

var float stopLoss_trend = na           //Стоплосс отвечает за смену тренда
var float trendBegining_price = na      //Цена начала тренда

var float stopLoss = na                 //Стоплосс ордеров -> для режима 'Усреднение'
var float takeProfit = na               //Тейкпрофит -> для режима 'Усреднение'

var int upFractalBarIndex = na          //Индекс бара для верхнего фрактала на крупном таймфрейме
var int downFractalBarIndex = na        //Индекс бара для нижнего фрактала на крупном таймфрейме
var int trendBegining_barIndex = na     //Индекс бара на котором начался тренд

var int averagingCounter = 0            //Количество усреднений ордеров для режима 'Усреднение' с пирамидинг режимом 'Множественные ордера'

var bool isTrendBullish = na            //Определяет тренд
var bool isTrendChanged = na            //Определяет продолжение тренда
var bool breakingHighBecame = na        //Определяет пробитие верхнего фрактала
var bool breakingLowBecame = na         //Определяет пробитие нижнего фрактала

var bool isContinue_LongPositions = na  //Определяет усреднеие лонг позиции -> для режима 'Усреднение'

// for telegram
var float trendBeginingPrice = na

//Обновление тейкпрофита на каждой свече. strategy.opentrades и strategy.position_avg_price обновляются только на следющей свече, поэтому после открытия позиции, на следющих свечах необходимо просчитать TP.
if isTrendBullish and strategy.opentrades > 0 and isContinue_LongPositions and not na(takeProfit)
    takeProfit := strategy.position_avg_price + (strategy.position_avg_price * takeProfit_percent)

//Обновление стоплосса, потому что по тренду открываются новые позиции и средняя цена меняется
if isTrendBullish and strategy.opentrades > 0 and isContinue_LongPositions and not na(stopLoss)
    stopLoss := strategy.position_avg_price + (strategy.position_avg_price * 0.01)

//Выход по безубытку
if noLoss_close and tradingMode == "Усреднение" and isContinue_LongPositions
    if close >= strategy.position_avg_price and strategy.opentrades > 0
        strategy.close_all(comment="[No loss] Close long orders", alert_message='"signal":"SELL", "side":"LONG"')
        
        takeProfit := na
        stopLoss := na
        isContinue_LongPositions := false
        averagingCounter := 0

//Определение дневных фракталов
if upFractal_daily
    upFractal_highDaily := array.get(high_dailyArr, n_daily)
    
    //Определяем индекс бара верхнего фрактала для крупного таймфрема
    for i = 1 to 100000
        if upFractal_highDaily == high[i]
            upFractalBarIndex := bar_index[i] 
            break
    
    if not isTrendBullish
        stopLoss_trend := upFractal_highDaily
        
if downFractal_daily
    downFractal_lowDaily := array.get(low_dailyArr, n_daily)
    
    //Определяем индекс бара верхнего фрактала для крупного таймфрема
    for i = 1 to 100000
        if downFractal_lowDaily == low[i]
            downFractalBarIndex := bar_index[i] 
            break
    
    if isTrendBullish
        stopLoss_trend := downFractal_lowDaily

//Выход по стоплоссу
if isTrendBullish and tradingMode == "Усреднение" and not na(stopLoss)
    if pyramidingMode == "Множественные ордера" and strategy.opentrades > 0 and close <= stopLoss
        strategy.close_all(comment="[StopLoss] Close long orders", alert_message='"signal":"SELL", "side":"LONG"')
        
        isContinue_LongPositions := false
        stopLoss := na
        averagingCounter := 0

//Выход по текйпрофиту
if isTrendBullish and tradingMode == "Усреднение" and not na(takeProfit)
    if pyramidingMode == "Один ордер" and close >= takeProfit
        strategy.close_all(comment="[TakeProfit] Close long orders", alert_message='"signal":"SELL", "side":"LONG"')
        takeProfit := na
        
        isContinue_LongPositions := false
    
    if pyramidingMode == "Множественные ордера" and close >= takeProfit
        takeProfit := na
        
        //Переносим стоплосс на 1% прибыли при достижении тейкпрофита
        stopLoss := strategy.position_avg_price + (strategy.position_avg_price * 0.01)

//Определение тренда на дневном графике
var float pendingOrderPrice = na //Цена отложенного ордера

//Пробой верхнего фрактала на крупном графике
//Смена тренда на бычий
if close > stopLoss_trend and not isTrendBullish
    if tradingMode == "Усреднение"
        if isContinue_LongPositions
            if pyramidingMode == "Один ордер" and strategy.opentrades > 0
                orderMessage = '"signal":"BUY", "side":"LONG"'
                strategy.entry("[Averaging] Long", strategy.long, alert_message=orderMessage)
                
                takeProfit := strategy.position_avg_price + (close * takeProfit_percent)
                
                previousOrderPrice := close
            
            if pyramidingMode == "Множественные ордера" and strategy.opentrades > 0
                //Первое усреднение
                if averagingCounter == 0
                    orderMessage = '"signal":"BUY", "side":"LONG"'
                    strategy.entry("[Averaging] Long", strategy.long, strategy.position_size, alert_message=orderMessage)
                    
                    takeProfit := strategy.position_avg_price + (close * takeProfit_percent)
                    
                    previousOrderPrice := close
                    
                    averagingCounter += 1
                    
                //Повторные устреднения
                if averagingCounter > 0
                    orderMessage = '"signal":"BUY", "side":"LONG"'
                    
                    averagingOrderSize = strategy.position_size * orderSizeAveragingSizePercent
                    strategy.entry("[Averaging] Long", strategy.long, averagingOrderSize, alert_message=orderMessage)
                    
                    takeProfit := strategy.position_avg_price + (strategy.position_avg_price * takeProfit_percent)
                    
                    previousOrderPrice := close
                    
                    averagingCounter += 1
                    
    
    if tradingMode == "Обычный"
        if strategy.opentrades > 0
            strategy.close_all(comment="[Trend changing] Close short orders", alert_message='"signal":"SELL", "side":"SHORT"') //Закрытие всех шортов
            previousOrderPrice := na
        
    stopLoss_trend := downFractal_lowDaily
    
    trendBeginingPrice := close
    isTrendBullish := true //Бычий тренд
    isTrendChanged := true
    breakingHighBecame := true 
    breakingLowBecame := false
    
    pendingOrderPrice := na //Сбрасываем цену отложенной заявки

//Пробой нижнего фрактала на крупном графике
//Смена тренда на медвежий
if close < stopLoss_trend and isTrendBullish
    if tradingMode == "Усреднение"
        if strategy.opentrades > 0 and strategy.openprofit < 0
            isContinue_LongPositions := true
        
        if strategy.opentrades > 0 and strategy.openprofit > 0
            strategy.close_all(comment="[Trend changing] Close long", alert_message='"signal":"SELL", "side":"LONG"')
            
            isContinue_LongPositions := false
            averagingCounter := 0
        
        takeProfit := na
        stopLoss := na

    if tradingMode == "Обычный"
        if strategy.opentrades > 0
            strategy.close_all(comment="[Trend changing] Close long orders", alert_message='"signal":"SELL", "side":"LONG"') //Закрытие всех лонгов
            previousOrderPrice := na
    
    trendBeginingPrice := close
    
    stopLoss_trend := upFractal_highDaily
    
    isTrendBullish := false //Тренд медвежийW
    isTrendChanged := true
    breakingHighBecame := false
    breakingLowBecame := true
    
    pendingOrderPrice := na

if isTrendBullish //Если тренд бычий
    //При появлении нового верхенего фрактала на текущем таймфрейме обновляем цену отложенного ордера
    if upFractal
        pendingOrderPrice := high[current_n]
    
    //Открытие лонга
    if close > pendingOrderPrice and not na(pendingOrderPrice) and barstate.isconfirmed
        pendingOrderPrice := na
        string orderMessage = na
        if strategy.opentrades == 0
            orderMessage := '"signal":"BUY", "side":"LONG"'
        else
            orderMessage := '"signal":"BUY", "side":"LONG"'
        
        longCondition = true
        if not na(previousOrderPrice)
            longCondition := not ordersOnTrend or (ordersOnTrend and close > previousOrderPrice)
        
        if allowOrdersDistance and not na(previousOrderPrice)
            previuosOrderPriceRange_top = previousOrderPrice * (1 + ordersDistance)
            longCondition := longCondition and close > previuosOrderPriceRange_top
        
        tradingMode_condiiton = (tradingMode == "Усреднение" and pyramidingMode == "Один ордер" and strategy.opentrades == 0) or (tradingMode == "Усреднение" and pyramidingMode == "Множественные ордера") or tradingMode == "Обычный"
        if longCondition and ordersAllowedSide != "Шорт" and tradingMode_condiiton
            strategy.entry("long", strategy.long, alert_message=orderMessage)
            previousOrderPrice := close

else //Если медвежий тренд
    //При появлении нового нижнего фрактала на текущем таймфрейме обновляем цену отложенного ордера
    if downFractal
        pendingOrderPrice := low[current_n]
    
    //Открытие шорта
    if close < pendingOrderPrice and not na(pendingOrderPrice) and barstate.isconfirmed and not isContinue_LongPositions
        pendingOrderPrice := na
        string orderMessage = na
        if strategy.opentrades == 0
            orderMessage := '"signal":"BUY", "side":"SHORT"'
        else
            orderMessage := '"signal":"BUY", "side":"SHORT"'
        
        shortCondition = true
        if not na(previousOrderPrice)
            shortCondition := not ordersOnTrend or (ordersOnTrend and close < previousOrderPrice)
        
        if allowOrdersDistance and not na(previousOrderPrice)
            previuosOrderPriceRange_bottom = previousOrderPrice * (1 - ordersDistance)
            shortCondition := shortCondition and close < previuosOrderPriceRange_bottom
        
        if shortCondition and ordersAllowedSide != "Лонг"
            strategy.entry("short", strategy.short, alert_message=orderMessage)
            previousOrderPrice := close

//Открытие нулевого ордера
if isTrendChanged and (not isContinue_LongPositions or strategy.opentrades == 0)
    if isTrendBullish
        if openZeroOrder and ordersAllowedSide != "Шорт"
            zeroOrderMessage = '"signal":"BUY", "side":"LONG"'
            strategy.entry("longZero", strategy.long, alert_message=zeroOrderMessage)
    else
        if openZeroOrder and ordersAllowedSide != "Лонг"
            zeroOrderMessage = '"signal":"BUY", "side":"SHORT"'
            strategy.entry("shortZero", strategy.short, alert_message=zeroOrderMessage)
//---Основной алгоритм конец----------------------------------------------------

//---Рисуем фракталы------------------------------------------------------------

bool showCurrentUpFractal = na
bool showCurrentDownFractal = na
bool showDailyUpFractal = na
bool showDailyDownFractal = na

var int dailyUpFractal_barIndex = na
var int dailyDownFractal_barIndex = na

//Определяем какие фракталы показывать
if showFractals == "Крупный таймфрейм"
    if upFractal_daily
        showDailyUpFractal := true
        
        for i = 1 to 100000
            if upFractal_highDaily == high[i]
                dailyUpFractal_barIndex := bar_index[i] - bar_index
                break

    if downFractal_daily
        showDailyDownFractal := true
        
        for i = 1 to 100000
            if downFractal_lowDaily == low[i]
                dailyDownFractal_barIndex := bar_index[i] - bar_index
                break

if showFractals == "Текущий таймфрейм"
    showCurrentUpFractal := upFractal
    showCurrentDownFractal := downFractal


//Показываем фракталы
plotshape(showCurrentDownFractal, title="Нижний фрактал текущего таймфрейма",style=shape.cross, location=location.belowbar, offset=-current_n, color=#F44336, size = size.small)
plotshape(showCurrentUpFractal, title="Верхний фрактал текущего таймфрейма", style=shape.cross,   location=location.abovebar, offset=-current_n, color=#009688, size = size.small)
 
plotshape(showDailyUpFractal, title="Верхний фрактал высшего таймфрейма", style=shape.cross, location=location.abovebar, offset=dailyUpFractal_barIndex, color=#009688, size = size.small)
plotshape(showDailyDownFractal, title="Нижний фрактал высшего таймфрейма", style=shape.cross, location=location.belowbar, offset=dailyDownFractal_barIndex, color=#F44336, size = size.small)

// /---Показывае линию пробой---

var float fractalHigh_forShowing = na
var float fractalLow_forShowing = na

if showFractalsLineForBreaking
    if breakingHighBecame //Момент когда прозошла смена тренда на бычий
        breakingHighBecame := false
        line.new(x1=upFractalBarIndex, y1=upFractal_highDaily, x2=bar_index, y2=upFractal_highDaily, style=line.style_arrow_right)
        
    if breakingLowBecame //Момент когда прозошла смена тренда на медвежий
        breakingLowBecame := false
        line.new(x1=downFractalBarIndex, y1=downFractal_lowDaily, x2=bar_index, y2=downFractal_lowDaily, style=line.style_arrow_right)
    
// /---Показываем линию пробоя конец---

// /---Показываем тренд---

var color colorTrend = na

if showTrend
    if isTrendBullish and not na(isTrendBullish)
        colorTrend := color.new(color.green, 90)
    if not isTrendBullish and not na(isTrendBullish)
        colorTrend := color.new(color.red, 90)
    if na(isTrendBullish)
        colorTrend := color.new(color.gray, 90)

bgcolor(colorTrend, title="Цвет тренда")

// /---Показываем тренд конец---

// /---Показываем стоплосс---

var line stopLossTrend_line = na
var line stopLoss_line = na

line.delete(stopLossTrend_line)
line.delete(stopLoss_line)

if showStopLossTrend
    stopLossTrend_line := line.new(x1=isTrendBullish ? downFractalBarIndex : upFractalBarIndex, y1=stopLoss_trend, extend=extend.right, x2=bar_index, y2=stopLoss_trend, color=color.red, style=line.style_dashed)   

if showStopLoss and tradingMode == "Усреднение" and pyramidingMode == "Множественные ордера" and  strategy.opentrades > 0
    stopLoss_line := line.new(x1=bar_index[1], y1=stopLoss, x2=bar_index, y2=stopLoss, extend=extend.both, color=color.purple, style=line.style_dashed) 

// /---Показываем стоплосс---

// /---Показываем тейкпрофит---

var line takeProfit_line = na

line.delete(takeProfit_line)

if showTakeProfit and not na(takeProfit)
    takeProfit_line := line.new(x1=bar_index[1], y1=takeProfit, x2=bar_index, y2=takeProfit, extend=extend.both, color=color.lime, style=line.style_dashed)

// /---Показываем тейкпрофит---

// /---Показываем среднюю цену открытых позиций---

var line averagePriceOfOpenedOrders = na

line.delete(averagePriceOfOpenedOrders)

if showAveragePriceOfOpenOrders
    if strategy.position_size != 0
        averagePriceOfOpenedOrders := line.new(x1=bar_index-10, y1=strategy.position_avg_price, x2=bar_index, y2=strategy.position_avg_price, extend=extend.both, color=color.blue, style=line.style_dashed)

// /---Показываем среднюю цену открытых позиций конец---

// /---Показываем линию соединения начала и конца тренда---

if isTrendChanged
    isTrendChanged := false
    
    if showTrendLine
        line.new(trendBegining_barIndex, trendBegining_price, bar_index, close, color=color.blue, style=line.style_dotted)
        
        if showLineLabel
            labelPoisition_x = math.round((trendBegining_barIndex + bar_index) / 2)
            labelPoisition_y = (trendBegining_price + close) / 2
            
            priceChangingPecent_inTrend = math.round((math.abs(trendBegining_price - close) / close) * 100, 2) //Процент изменения цены внутри тренда
            barsNumber_inTrend = bar_index - trendBegining_barIndex
            labelText = str.tostring(priceChangingPecent_inTrend) + "%, " + str.tostring(barsNumber_inTrend)
            
            //Определяем цену линии в ее середине
            float middlePriceOfLine = na    //Цена линии в ее середине 
            if close > trendBegining_price
                middlePriceOfLine := close - math.abs(close - trendBegining_price) / 2
            else
                middlePriceOfLine := close + math.abs(close - trendBegining_price) / 2
            
            //Определяем стиль лейбла
            //Если цена бара выше цены линии на баре, где стоит лейбл, то лейбл будет находится ниже линии.
            //В противоположном случае лейбл находится выше. 
            string labelStyle = na          //Стиль линии
            
            labelOffset = math.round(bar_index - labelPoisition_x)
            if close[labelOffset] > middlePriceOfLine
                labelStyle := label.style_label_up
            else
                labelStyle := label.style_label_down
            
            //Создаем лейбл
            label.new(labelPoisition_x, labelPoisition_y, labelText, color=color.black, style=labelStyle, textcolor=color.white)
            
    trendBegining_barIndex := bar_index
    trendBegining_price := close

// /---Показываем линию соединения начала и конца тренда конец---

// /---Показываем статистику по открытым ордерам---

var table statistics = na
var float income = na

if showStatistics
    income := strategy.openprofit / (strategy.position_size * strategy.position_avg_price) * 100
    if not isTrendBullish
        income *= -1
    
    statistics := table.new(position.top_right, 2, 4)
    table.cell(statistics, 0, 0, "Кол-во открытых сделок: ")
    table.cell(statistics, 1, 0, str.tostring(strategy.opentrades))
    table.cell(statistics, 0, 1, "Доход от открытых сделок: ")
    table.cell(statistics, 1, 1, str.tostring(math.round(income, 2)) + "% ")
    table.cell(statistics, 0, 2, "Объем открытых сделок: ")
    table.cell(statistics, 1, 2, str.tostring(math.round(strategy.position_size, 2)) + syminfo.basecurrency)
    table.cell(statistics, 0, 3, "Средняя цена открытых ордеров: ")
    table.cell(statistics, 1, 3, str.tostring(math.round(strategy.position_avg_price, 4)) + syminfo.currency)

// /---Показываем статистику конец---

//---Рисуем фракталы конец------------------------------------------------------

Overview

Breaking fractals opens buy or sell orders on breaks of lower-timeframe fractals aligned with the higher-timeframe trend. Normal trading mode exits on trend reversal while averaging mode continues positions to average into the trend. Main settings adjust fractal periods, trading mode, pyramiding rules, and position sizing. It plots fractals, trend lines, and statistics on the price chart.

Details

Published by

DaniilOkrug on GitHub

Code credit

icewalk, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Breakout, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction
  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Крупный таймфрейм timeframeDhigherTimeframe
Период для крупного фракталаint2n_daily
Период для текущего фракталаint2current_n
Какие фрактала показатьstringНикакиеshowFractals
Торговый режимstringОбычныйtradingMode
Режим пирмадингаstringОдин ордерpyramidingMode
TP(%)float1takeProfit_percent
Объем усредняющей сделки(%)float5orderSizeAveragingSizePercent
Закрыть позиции в безубытокboolfalsenoLoss_close
Показать TPboolfalseshowTakeProfit
Показать SLboolfalseshowStopLoss
В какую сторону открывать сделкиstringОбеordersAllowedSide
Show all 23 settings
SettingTypeDefaultVariable
Докупать по трендуboolfalseordersOnTrend
Открыть нулевой ордерbooltrueopenZeroOrder
Использовать расстояние между ордерамиboolfalseallowOrdersDistance
Минимальное расстояние между ордерами(%)float5ordersDistance
Показать фракталы с пробоемbooltrueshowFractalsLineForBreaking
Показать трендbooltrueshowTrend
Показать стоплоссbooltrueshowStopLossTrend
Показать статистикуbooltrueshowStatistics
Показать среднюю цену открытых позицийbooltrueshowAveragePriceOfOpenOrders
Показать линию трендаboolfalseshowTrendLine
Показать информацию о трендеboolfalseshowLineLabel
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This trend-following strategy executes a classic Donchian channel breakout system designed to cross-validate backtest results against external framework benchmarks. It triggers a long entry when the closing price breaks above the highest high of the prior entr

Strategy v6 BreakoutTrend
Updated today · AGPL-3.0 GitHub repository of Forven S01509 - Simple Donchian 20/10 Breakout
257 stars

This strategy plots running pivot highs as red R circles and pivot lows as blue S circles directly on the price chart. It computes an EMA 3 and a Cto trend line from close prices, then generates long signals on upward EMA-Cto crossovers combined with price pos

Strategy v6 TrendMoving averages Repaints
Updated 6 weeks ago · None stated GitHub repository of Best Chart 1m Strategy Candle Bar
106 stars

Calculates multi-period logarithmic regression trend channels and deviation bands across up to twenty selectable lookback lengths directly on the price chart. It evaluates channel slopes and Pearson's correlation coefficient to detect market trends and generat

Strategy v5 TrendSupport & resistance Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of Advanced Trend Detection Strategy

This trend breakout strategy plots Donchian Channels consisting of upper, lower, and middle bands directly on the main price chart. Long positions enter when price touches the upper channel and pulls back to or below the middle band, placing a stop loss at the

Strategy v6 TrendBreakout
Updated 2 months ago · MPL-2.0 GitHub repository of Donchian Strategy - Dynamic TP, Fixed SL, 1% Risk, Daily Target
43 stars

This strategy executes trades on short-term cryptocurrency charts using a combination of pivot support and resistance levels and a multi-pole smoothed trend filter. Entries trigger when price crosses the smoothed trend line and confirms above or below a short-

Strategy v5 TrendBreakout Repaints
Updated 2 years ago · None stated GitHub repository of SOL 1m - Strategy Candle Bar

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers