Repaints Gaps Trend [ChartPrime] for ThinkOrSwim

Repaints

samer800

Moderator - Expert
VIP
Lifetime
LT2dkwY.png


Author Message:

The Gaps Trend - ChartPrime indicator is designed to detect Fair Value Gaps (FVGs) in the market and apply a trailing stop mechanism based on those gaps. It identifies both bullish and bearish gaps and provides traders with a way to manage trades dynamically as gaps appear. The indicator visually highlights gaps and uses the detected momentum to assess trend direction, helping traders identify price imbalances caused by strong buy or sell pressure.

CODE:

CSS:
#// Indicator for TOS
#//@ChartPrime
#indicator("Gaps Trend [ChartPrime]", overlay = true, max_boxes_count = 500
# Converted by Sam4Cok@Samer800    - 09/2024

input colorBars = no;
input showGapSize = yes;
input FilterGaps = 0.5; #, "Filter Gaps", step = 0.01)
input ShowGapLevels = no; #(false, "Show Gap Levels")
input showTrailingStop = yes; #(true, "", inline = "1", group = "Trailing Stop")
input TrailingStopLength  = 10; #, "Trailing Stop Length", inline = "1", group = "Trailing Stop")

def na = Double.NaN;
def last = isNaN(close);
def pos = Double.POSITIVE_INFINITY;
def neg = Double.NEGATIVE_INFINITY;
DefineGlobalColor("dUP", CreateColor(0, 82, 82));
DefineGlobalColor("dDn", CreateColor(82, 0, 82));
#// 𝙄𝙉𝘿𝙄𝘾𝘼𝙏𝙊𝙍 𝘾𝘼𝙇𝘾𝙐𝙇𝘼𝙏𝙄𝙊𝙉𝙎
#// Calculate bearish and bullish gap sizes, normalized by the standard deviation
def bearish_gap_size = (low[2] - high) / StDev(low[2] - high, 100);
def bullish_gap_size = (low - high[2]) / StDev(low - high[2], 100);
#// @function Detects Fair Value Gaps (FVG)
#// @returns [bool, float, float] Returns whether FVG is detected and its upper/lower levels
#// Conditions to detect bullish and bearish gaps
def bullish_gap_condition = low > high[2] and high[1] > high[2] and bullish_gap_size > FilterGaps;
def bearish_gap_condition = high < low[2] and low[1] < low[2]   and bearish_gap_size > FilterGaps;

#// Bullish FVG logic
def trend_direction;
def trailing_stop;

def tsHi = highest(high, TrailingStopLength + 1);
def tsLo = lowest(low, TrailingStopLength + 1);

def trendDir = if bullish_gap_condition then 1 else
               if bearish_gap_condition then 0 else trend_direction[1];

def fvg_upper; def fvg_lower; def line; def col; def cond; def gapSize;
if bullish_gap_condition {
    line      = high[2];
    fvg_upper = high[2];
    fvg_lower = low;
    gapSize = Round(bullish_gap_size, 2);
    col = 1;
} else if bearish_gap_condition {
    line      = low[2];
    fvg_upper = low[2];
    fvg_lower = high;
    gapSize = Round(bearish_gap_size, 2);
    col = -1;
    } else {
    line      = if cond[1] then na else line[1];
    fvg_upper = fvg_upper[1];
    fvg_lower = fvg_lower[1];
    gapSize = na;
    col = col[1];
}
cond = high > fvg_upper and low < fvg_upper;

def trailingStop = if trendDir==1 then tsLo else
                   if trendDir==0 then tsHi else trailing_stop[1];

if trailingStop == low {
    trailing_stop = neg;
    trend_direction = 0;
} else if trailingStop == high {
    trailing_stop = pos;
    trend_direction = 0;
    } else {
    trailing_stop = trailingstop;
    trend_direction = trenddir;
}
#// Set the trend color based on trailing stop and price position
def trend_color = close > trailing_stop; # ? bull_color : bear_color
def crossesTS   = (close > trailing_stop and close[1] <= trailing_stop[1]) or
                  (close < trailing_stop and close[1] >= trailing_stop[1]);

# -- plots
plot sizeBull = if showGapSize and bullish_gap_condition[-1] then gapSize[-1] else na;
plot sizeBear = if showGapSize and bearish_gap_condition[-1] then gapSize[-1] else na;
plot crosTS = if crossesTS and trailing_stop then trailing_stop else na;
plot ts_plot = if showTrailingStop and trailing_stop then if crossesTS then na else trailing_stop else na;

ts_plot.AssignValueColor(if trend_color then Color.CYAN else Color.MAGENTA);
crosTS.SetLineWeight(2);
crosTS.AssignValueColor(if trend_color then Color.CYAN else Color.MAGENTA);
crosTS.SetPaintingStrategy(PaintingStrategy.SQUARES);
sizeBull.SetDefaultColor(Color.WHITE);
sizeBear.SetDefaultColor(Color.WHITE);
sizeBull.SetPaintingStrategy(PaintingStrategy.VALUES_BELOW);
sizeBear.SetPaintingStrategy(PaintingStrategy.VALUES_ABOVE);

AddCloud(if (ts_plot!=pos and ts_plot!=neg) then ohlc4 else na, ts_plot, GlobalColor("dUP"), GlobalColor("dDN"));

#-- Lines
def cnt = if bullish_gap_condition then 0 else if bearish_gap_condition then 0 else cnt[1] + 1;
def fvgupper = if cnt[-2] <= 5  then
               if bullish_gap_condition[-6] then lowest(fvg_upper[-6], 5) else highest(fvg_upper[-6], 5) else na;
def fvgLower = if cnt[-2] <= 5  then
               if bullish_gap_condition[-6] then lowest(fvg_lower[-6], 5) else highest(fvg_lower[-6], 5) else na;

plot fvgLine = if ShowGapLevels and !last and line[-1] then line[-1] else na;

fvgLine.AssignValueColor(if col[-1]>0 then Color.GREEN else Color.RED);
fvgLine.SetPaintingStrategy(PaintingStrategy.DASHES);

AddCloud(fvgLower, fvgupper, Color.CYAN, Color.MAGENTA);

#-- bar color

AssignPriceColor(if !colorBars then Color.CURRENT else
            if (trailing_stop!=pos and trailing_stop!=neg) and trend_direction then color.GREEN else
            if (trailing_stop!=pos and trailing_stop!=neg) and !trend_direction then Color.RED else Color.GRAY);
#-- END of CODE
 
Another Awesome Submission by the great @samer800.

A note for newer traders, who are not familiar with the workings of fair value gap coding.
It does not chart in real time.
To identify the gap, it waits 6 bars into the future and then goes back in time to create the plots that appear on the chart.

While many traders are familiar with the repainters, whose signals are real-time but appear and disappear. The future-bar repainters are a different species. Because it has to wait 6 bars into the future; it has a severe lag.

No Watchlists -- No Alerts -- No Scans.
Because the data has to wait 6 bars into the future; it is not possible to create watchlists, alerts. scans on this script. As ToS widgets are designed to report real-time not future data.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
293 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top