Strategy · Pine Script v5 · On the chart

X Trend

by Sikako· code credited to jpgoswami

X Trend is an overlay strategy that identifies trend direction and potential entry points using a custom X Trend trailing line, exponential moving averages, and Half Trend calculations.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code271
Settings13inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago4 Jun 2023

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

271 lines of Pine Script v5 from x trend.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

x trend.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jpgoswami

//@version=5
strategy('X Trend', max_bars_back=5000, overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.04, initial_capital = 1000, process_orders_on_close = true)

// date
var startTime = input.time(timestamp("1 Apr 2023 00:00 +0800"), "開始時間", group = "回測時間")
var endTime = input.time(timestamp("7 Apr 2023 00:00 +0800"), "結束時間", group = "回測時間")
window()  => time >= startTime and time <= endTime ? true : false


//inp_Amplitude = input(2, title = "Amplitude", type = input.integer)
longEMALength = input(21, title = "EMA長度")

longEMA = ta.ema(close, longEMALength)

// ------------------------------------------------x trend
Lowest_Low = ta.lowest(low, 3)
MA_Low = ta.ema(low, 3)

Highest_High = ta.highest(high, 2)
MA_High = ta.sma(high, 2)

ATR_Half = ta.atr(100) / 2

Next_Trend = 0
Next_Trend := nz(Next_Trend[1], Next_Trend)

Trend = 0
Trend := nz(Trend[1], Trend)

Low_Max = low[1]
Low_Max := nz(Low_Max[1], Low_Max)

High_Min = high[1]
High_Min := nz(High_Min[1], High_Min)

Arrow_Shift = 0.0
Line_Color = color.gray

if Next_Trend == 1
    Low_Max := math.max(Low_Max, Lowest_Low)
    // if MA_High < Low_Max and close < low[1]
    if MA_High < Low_Max
        Trend := 1
        Next_Trend := 0
        High_Min := Highest_High
        High_Min


if Next_Trend == 0
    High_Min := math.min(High_Min, Highest_High)
    // if MA_Low > High_Min and close > high[1]
    if MA_Low > High_Min
        Trend := 0
        Next_Trend := 1
        Low_Max := Lowest_Low
        Low_Max



Line_HT = close
Line_HT := nz(Line_HT[1], Line_HT)

if Trend == 0
    Line_Color := color.blue
    if Trend[1] == 0
        Line_HT := math.max(Low_Max, Line_HT[1])
        Line_HT
    if Trend[1] == 1
        Arrow_Shift := -1 * ta.atr(10)
        Arrow_Shift

if Trend == 1
    Line_Color := color.orange
    if Trend[1] == 1
        Line_HT := math.min(High_Min, Line_HT[1])
        Line_HT
    if Trend[1] == 0
        Arrow_Shift := 1 * ta.atr(10)
        Arrow_Shift

plot(Line_HT, color=color.new(Line_Color, 0), linewidth=2, title='X Trend')
plot(longEMA, title='200 EMA', color=color.new(color.gray, 0), linewidth=2)
plotshape(Arrow_Shift > 0 ? Line_HT + Arrow_Shift : na, style=shape.triangledown, location=location.absolute, color=color.new(Line_Color, 0), size=size.tiny)
plotshape(Arrow_Shift < 0 ? Line_HT + Arrow_Shift : na, style=shape.triangleup, location=location.absolute, color=color.new(Line_Color, 0), size=size.tiny)



// -------------------------------------------------------------------------half trend

amplitude = input(2, title="Amplitude", group = "Half Trend")
channelDeviation = input(3, title="Channel Deviation", group = "Half Trend")
showChannels = input(true, title="Show Channels", group = "Half Trend")

var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)

var float up = 0.0
var float down = 0.0
float atrHigh = 0.0 // 空單止損
float atrLow = 0.0  // 多單止損
float arrowUp = na
float arrowDown = na

atr2 = ta.atr(100) / 2
dev = channelDeviation * atr2

highPrice = high[math.abs(ta.highestbars(amplitude))]
lowPrice = low[math.abs(ta.lowestbars(amplitude))]
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)

if nextTrend == 1
    maxLowPrice := math.max(lowPrice, maxLowPrice)

    if highma < maxLowPrice and close < nz(low[1], low)
        trend := 1
        nextTrend := 0
        minHighPrice := highPrice
else
    minHighPrice := math.min(highPrice, minHighPrice)

    if lowma > minHighPrice and close > nz(high[1], high)
        trend := 0
        nextTrend := 1
        maxLowPrice := lowPrice

if trend == 0
    if not na(trend[1]) and trend[1] != 0
        up := na(down[1]) ? down : down[1]
        arrowUp := up - atr2
    else
        up := na(up[1]) ? maxLowPrice : math.max(maxLowPrice, up[1])
    atrHigh := up + dev
    atrLow := up - dev
else
    if not na(trend[1]) and trend[1] != 1 
        down := na(up[1]) ? up : up[1]
        arrowDown := down + atr2
    else
        down := na(down[1]) ? minHighPrice : math.min(minHighPrice, down[1])
    atrHigh := down + dev
    atrLow := down - dev

ht = trend == 0 ? up : down

var color buyColor = color.blue
var color sellColor = color.red

htColor = trend == 0 ? buyColor : sellColor
// htPlot = plot(ht, title="HalfTrend", linewidth=2, color=htColor)

atrHighPlot = plot(showChannels ? atrHigh : na, title="ATR High", style=plot.style_circles, color=sellColor)
atrLowPlot = plot(showChannels ? atrLow : na, title="ATR Low", style=plot.style_circles, color=buyColor)

// fill(htPlot, atrHighPlot, title="ATR High Ribbon", color=color.new(sellColor, 90))
// fill(htPlot, atrLowPlot, title="ATR Low Ribbon", color=color.new(buyColor, 90))

// buySignal = not na(arrowUp) and (trend == 0 and trend[1] == 1)
// sellSignal = not na(arrowDown) and (trend == 1 and trend[1] == 0)

// plotshape(showArrows and buySignal ? atrLow : na, title="Arrow Up", style=shape.triangleup, location=location.absolute, size=size.tiny, color=buyColor)
// plotshape(showArrows and sellSignal ? atrHigh : na, title="Arrow Down", style=shape.triangledown, location=location.absolute, size=size.tiny, color=sellColor)

// --------------------------------------------------------------------------------------imacd
enableImacd = input(true, title = "開啟IMACD過濾盤整", group = "imacd")
lengthMA = input(13, title = "IMACD LengthMA", group = "imacd")
lengthSignal = input(8, title = "IMACD Length Signal", group = "imacd")
imacd_threshold = input.float(15, title = "IMACD 開倉門檻", group = "imacd")
calc_smma(src, len) =>
    smma = 0.0
    smma := na(smma[1]) ? ta.sma(src, len) : (smma[1] * (len - 1) + src) / len
    smma

calc_zlema(src, length) =>
    ema1=ta.ema(src, length)
    ema2=ta.ema(ema1, length)
    d=ema1-ema2
    ema1+d

src=hlc3
hi=calc_smma(high, lengthMA)
lo=calc_smma(low, lengthMA)
mi=calc_zlema(src, lengthMA) 

md=(mi>hi)? (mi-hi) : (mi<lo) ? (mi - lo) : 0
sb=ta.sma(md, lengthSignal)
sh=md-sb

// plot(0, color=color.gray, linewidth=1, title="MidLine")
plot(md, color=color.red, linewidth=2, title="ImpulseMACD", display = display.status_line+display.data_window)
plot(sb, color=color.yellow, linewidth=2, title="ImpulseMACDCDSignal", display = display.status_line+display.data_window)

// ---------------------------------------------------------------------------------------trade
tick_size = syminfo.mintick
entry_bar_index = strategy.opentrades.entry_bar_index(strategy.opentrades - 1)
entry_price = strategy.opentrades.entry_price(strategy.opentrades - 1)
entry_id = strategy.opentrades.entry_id(strategy.opentrades - 1)

g = close > open
r = close < open

var canbuy = true
if ta.cross(close, Line_HT) and strategy.position_size == 0
    canbuy := true

var firstTrade = true




imacdCondition = not ((imacd_threshold > md and md > -1*imacd_threshold) or (imacd_threshold > sb and sb > -1*imacd_threshold))

buyLongSignal = enableImacd ? (Trend == 0 and close > longEMA and close > Line_HT and imacdCondition) : (Trend == 0 and close > longEMA and close > Line_HT)
buyShortSignal = enableImacd ? (Trend == 1 and close < longEMA and close < Line_HT and imacdCondition) : (Trend == 1 and close < longEMA and close < Line_HT)

var trail_threshold = input(defval = 2, title = "開啟套保門檻(%)", group = "止損") / 100.0
var firstEarnLossRatio = input(1, title = "首單盈虧比", group = "止損")
var addEarnLossRatio = input(2, title = "加倉盈虧比", group = "止損")

// 計算套保價格
get_trail_price(direction) =>
    if direction == "L"
        strategy.opentrades.entry_price( strategy.opentrades - 1) * (1.0 + trail_threshold)
    else if direction == "S"
        strategy.opentrades.entry_price( strategy.opentrades - 1) * (1.0 - trail_threshold)

// 計算止盈價格
var stop_price = 0.0
get_profit(isFirstTrade) =>
    profit = isFirstTrade ? (math.abs(entry_price - stop_price)/tick_size)*firstEarnLossRatio : (math.abs(entry_price - stop_price)/tick_size)*addEarnLossRatio
    profit

plot(entry_id == "short" ? get_trail_price("S") : na, style=plot.style_linebr, title = "空單套保價格", color = color.blue)
plot(entry_id == "long" ? get_trail_price("L") : na, style=plot.style_linebr, title = "多單套保價格", color = color.blue)

if window()
    if Trend != Trend[1]
        canbuy := true

    if buyLongSignal and canbuy and strategy.position_size <= 0
        stop_price := atrLow
        strategy.entry("long", strategy.long)
        canbuy := false
    else if buyShortSignal and canbuy and strategy.position_size >= 0
        stop_price := atrHigh
        strategy.entry("short", strategy.short)
        canbuy := false

    if (strategy.position_size != 0 and strategy.opentrades.entry_id(0) != strategy.closedtrades.entry_id(strategy.closedtrades - 1))
        firstTrade := true

    strategy.exit("exit_long", "long", stop = stop_price, profit = get_profit(firstTrade), comment_loss = "long_loss", comment_profit = "long_profit")
    strategy.exit("exit_short", "short", stop = stop_price, profit = get_profit(firstTrade), comment_loss = "short_loss", comment_profit = "short_profit")

    // 套保
    if  high > get_trail_price("L") and entry_id == "long"
        strategy.exit("exit_long", "long", stop = get_trail_price("L"), profit = get_profit(firstTrade), comment_loss = "trail", comment_profit = "long_profit")
    if low < get_trail_price("S") and entry_id == "short"
        strategy.exit("exit_short", "short", stop = get_trail_price("S"), profit = get_profit(firstTrade), comment_loss = "trail", comment_profit = "short_profit") 

    if strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) == bar_index
        firstTrade := false


plot(firstTrade ? 1 : 0, title = "firstTrade", display = display.data_window)
plot(strategy.position_size, title = "position size", display = display.data_window)

Overview

X Trend includes optional Impulse MACD filtering designed to avoid ranging market conditions. The script plots dynamic trend lines, entry arrow shapes, and a moving average directly on the price chart. Settings allow customization of moving average lengths, Half Trend channel deviation, range filtering thresholds, and backtest execution dates.

Details

Published by

Sikako on GitHub

Code credit

jpgoswami, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

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

SettingTypeDefaultVariable
開始時間timetimestamp("1 Apr 2023 00:00 +0800")startTime
結束時間timetimestamp("7 Apr 2023 00:00 +0800")endTime
EMA長度int21longEMALength
Amplitudeint2amplitude
Channel Deviationint3channelDeviation
Show ChannelsbooltrueshowChannels
開啟IMACD過濾盤整booltrueenableImacd
IMACD LengthMAint13lengthMA
IMACD Length Signalint8lengthSignal
IMACD 開倉門檻float15imacd_threshold
開啟套保門檻(%)int2trail_threshold
首單盈虧比int1firstEarnLossRatio
Show all 13 settings
SettingTypeDefaultVariable
加倉盈虧比int2addEarnLossRatio
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 mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [Alorse]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 7 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
220 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce
106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
104 stars

This overlay strategy combines a Chandelier Exit with a zero-lag least squares moving average. Although the header mentions Heikin Ashi candles, the calculations use ordinary closes. An ATR trailing stop sets long and short levels, and direction flips when pri

Strategy v5 TrendMoving averages
Updated 3 years ago · MIT GitHub repository of Chandelier Exit & ZLSMA Strategy

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers