// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.
0
at https://mozilla.org/MPL/2.0/
// © BigBeluga
//
//@version=5
indicator("Market Magnet - Algo Indicator", " Market Magnet - Algo Indicator
[Always Grow 🚀 ]",
       overlay = true,
       max_bars_back = 5000,
       max_boxes_count = 500,
       max_labels_count = 500,
       max_lines_count = 500,
       max_polylines_count = 100)
plot(na)
//
MSG = "MARKET STRUCTURE"
VBG = "VOLUMETRIC ORDER BLOCKS"
MST = "Limit market structure calculation to improve memory speed time"
SLT = "[INPUT] Limit swing structure to tot bars back"
IDT = "[INPUT] Start date of the internal structure"
CST = "Color candle based on trend detection system"
OBT = "Display internal buy and sell activity"
OBD = "Show Last number of orderblock"
OBMT = "[Length] Use Length to adjust cordinate of the orderblocks\n[Full] Use
whole candle body"
_
='
                                                         ------------
                               ––––––––––––––––––––––––––   INPUTS
–––––––––––––––––––––––––––
                                                         ------------
'//{
bool windowsis       = input.bool(true, "Window", inline="kla", group=MSG)
int mswindow         = input.int(5000, "", tooltip=MST,group=MSG, inline="kla",
minval=1000)
bool showSwing       = input.bool(true, "Swing", inline="scss", group=MSG)
int swingLimit      = input.int(100, "", tooltip=SLT, inline="scss", group=MSG,
minval=10, maxval=200)
color swingcssup     = input.color(#089981, "", inline="scss", group=MSG)
color swingcssdn     = input.color(#f23645, "", inline="scss", group=MSG)
bool showMapping     = input.bool(false, "Mapping Structure", inline="mapping",
group=MSG)
string mappingStyle = input.string("----", "", options=["⎯⎯⎯⎯", "----"],
inline="mapping", group=MSG)
color mappingcss    = input.color(color.silver, "", tooltip="Display Mapping
Structure", inline="mapping", group=MSG)
bool candlecss       = input.bool(false, "Color Candles", tooltip=CST, group=MSG,
inline="txt")
string mstext        = input.string("Tiny", "", options=["Tiny", "Small", "Normal",
"Large", "Huge"],
 inline="txt", group=MSG)
string msmode       = input.string("Adjusted Points", "Algorithmic Logic",
options=["Extreme Points", "Adjusted Points"]
 , inline="node", group=MSG)
int mslen            = input.int(5, "", inline="node", group=MSG, minval=2)
bool buildsweep     = input.bool(true, "Build Sweep (x)", "Build sweep on market
structure", "znc", MSG)
bool msbubble       = input.bool(true, "Bubbles", tooltip="Display Circle Bubbles",
inline="bubbles", group=MSG)
bool obshow          = input.bool(true, "Show Last", tooltip=OBD, group=VBG,
inline="obshow")
int oblast           = input.int(5, "", group=VBG, inline="obshow", minval=0)
color obupcs        = input.color(color.new(#089981, 90), "", inline="obshow",
group=VBG)
color obdncs        = input.color(color.new(#f23645, 90), "", inline="obshow",
group=VBG)
bool obshowactivity = input.bool(true, "Show Buy/Sell Activity", inline="act",
group=VBG, tooltip=OBT)
color obactup       = input.color(color.new(#089981, 50), "", inline="act",
group=VBG)
color obactdn       = input.color(color.new(#f23645, 50), "", inline="act",
group=VBG)
obshowbb     = input.bool(false, "Show Breakers", inline="bb", group=VBG,
tooltip="Display Breakers")
color bbup          = input.color(color.new(#089981, 100), "", inline="bb",
group=VBG)
color bbdn          = input.color(color.new(#f23645, 100), "", inline="bb",
group=VBG)
obmode       = input.string("Length", "Construction", options=["Length", "Full"],
tooltip=OBMT, inline="atr", group=VBG)
len           = input.int(5, "", inline="atr", group=VBG, minval=1)
obmiti        = input.string("Close", "Mitigation Method", options=["Close", "Wick",
"Avg"],
 tooltip="Mitigation method for when to trigger order blocks", group=VBG)
obtxt        = input.string("Normal", "Metric Size", options=["Tiny", "Small",
"Normal", "Large", "Huge", "Auto"],
 tooltip="Order block Metrics text size", inline="txt", group=VBG)
showmetric    = input.bool(true, "Show Metrics", group=VBG)
showline      = input.bool(true, "Show Mid-Line", group=VBG)
overlap       = input.bool(true, "Hide Overlap", group=VBG, inline="ov")
wichlap       = input.string("Recent", "", options=["Recent", "Old"], inline="ov",
group=VBG)
fvg_enable   = input.bool(false, "", inline="1", group="FAIR VALUE GAP",
tooltip="Display fair value gap")
what_fvg     = input.string("FVG", "", inline="1", group="FAIR VALUE GAP",
tooltip="Display fair value gap",
 options=["FVG", "Breakers"])
fvg_num      = input.int(5, "Show Last", inline="1a", group="FAIR VALUE GAP",
tooltip="Number of fvg to show", minval=0)
fvg_upcss     = input.color(color.new(#089981, 80), "", inline="1", group="FAIR
VALUE GAP")
fvg_dncss     = input.color(color.new(#f23645, 80), "", inline="1", group="FAIR
VALUE GAP")
fvgbbup        = input.color(color.new(#089981, 100), "", inline="1", group="FAIR
VALUE GAP")
fvgbbdn        = input.color(color.new(#f23645, 100), "", inline="1", group="FAIR
VALUE GAP")
fvg_src        = input.string("Close", "Mitigation",
 inline="3",
 group="FAIR VALUE GAP",
 tooltip="[Close] Use the close of the body as trigger\n\n[Wick] Use the extreme
point of the body as trigger",
 options=["Close", "Wick", "Avg"])
fvgthresh    = input.float(0, "Threshold", tooltip="Filter out non significative
FVG", group="FAIR VALUE GAP",
 inline="asd", minval=0, maxval=2, step=0.1)
fvgoverlap     = input.bool(true, "Hide Overlap", "Hide overlapping FVG", group="FAIR
VALUE GAP")
fvgline        = input.bool(true, "Show Mid-Line", group="FAIR VALUE GAP")
fvgextend      = input.bool(false, "Extend FVG", group="FAIR VALUE GAP")
dispraid       = input.bool(false, "Display Raids", inline="raid", group="FAIR VALUE
GAP")
//}
_
='
                                                       ------------
                             ––––––––––––––––––––––––––     UDT
–––––––––––––––––––––––––––
                                                       ------------
'//{
type hqlzone
      box   pbx
      box   ebx
      box   lbx
      label plb
      label elb
      label lbl
type Zphl
    line     top
    line     bottom
    label    top_label
    label    bottom_label
    bool     stopcross
    bool     sbottomcross
    bool     itopcross
    bool     ibottomcross
    string txtup
    string txtdn
    float    topy
    float    bottomy
    float    topx
    float    bottomx
    float    tup
    float    tdn
    int      tupx
    int      tdnx
    float    itopy
    float    itopx
    float    ibottomy
    float    ibottomx
    float    uV
    float    dV
type entered
    bool normal      = false
    bool breaker = false
type store
    line      [] ln
    label     [] lb
    box       [] bx
    linefill[] lf
type structure
    int     zn
    float   zz
    float   bos
    float   choch
    int     loc
    int     temp
    int     trend
    int     start
    float   main
    int     xloc
    bool    upsweep
    bool    dnsweep
    string txt = na
type drawms
    int     x1
    int     x2
    float   y
    string txt
    color   css
    string style
type ob
    bool    bull
    float top
    float btm
    float avg
    int    loc
    color css
    float vol
    int    dir
    int    move
    int    blPOS
    int    brPOS
    int    xlocbl
    int    xlocbr
    bool   isbb     = false
    int    bbloc
type FVG
    float top        = na
    float btm        = na
    int    loc       = bar_index
    bool   isbb      = false
    int    bbloc     = na
    bool   israid    = false
    float raidy      = na
    int    raidloc = na
    int    raidx2    = na
    bool   active    = false
    color raidcs     = na
type SFP
    float y
    int    loc
    float ancor
type sfpbuildlbl
    int      x
    float    y
    string style
    color    css
    string txt
type sfpbuildline
    int     x1
    int     x2
    float y
    color css
    float ancor
    int     loc
type equalbuild
    int      x1
    float    y1
    int      x2
    float    y2
    color    css
    string style
type equalname
    int      x
    float    y
    string txt
    color    css
    string style
type ehl
    float pt
    int     t
    float pb
    int     b
type sellbuyside
      float   top
      float   btm
      int     loc
      color   css
      string txt
      float   vol
type timer
      bool start = false
      int   count = 0
//}
_
='
                                                          ------------
                                ––––––––––––––––––––––––––    SETUP
–––––––––––––––––––––––––––
                                                          ------------
'//{
var store bin = store.new(
                        array.new<   line   >()
                    , array.new<     label >()
                    , array.new<      box   >()
                    , array.new<linefill>()
var entered blobenter        = entered.new()
var entered brobenter        = entered.new()
var entered blfvgenter       = entered.new()
var entered brfvgenter       = entered.new()
var entered blarea           = entered.new()
var entered brarea           = entered.new()
var timer      lc            = timer.new    ()
if barstate.islast
      for obj in bin.ln
         obj.delete()
      for obj in bin.lb
         obj.delete()
      for obj in bin.bx
         obj.delete()
      for obj in bin.lf
         obj.delete()
      bin.ln.clear()
      bin.lb.clear()
      bin.bx.clear()
      bin.lf.clear()
invcol = #ffffff00
float      atr =               (ta.atr(200) / (5/len))
//}
_
='
                                                         ------------
                             ––––––––––––––––––––––––––     UTILITY
–––––––––––––––––––––––––––
                                                         ------------
'//{
method txSz(string s) =>
      out = switch s
         "Tiny"    => size.tiny
         "Small"   => size.small
         "Normal" => size.normal
         "Large"   => size.large
         "Huge"    => size.huge
          "Auto"    => size.auto
    out
method lstyle(string style) =>
    out = switch style
          '⎯⎯⎯⎯'   => line.style_solid
          '----'   => line.style_dashed
          '····'   => line.style_dotted
ghl() => [high[2], low[2], close[1], open[1], close, open, high, low, high[1],
low[1], ta.atr(200)]
method IDMIDX(bool use_max, int loc) =>
    min = 99999999.
    max = 0.
    idx = 0
    if use_max
          for i = 0 to (bar_index - loc)
              max := math.max(high[i], max)
              min := max == high[i] ? low[i] : min
              idx := max == high[i] ? i : idx
    else
          for i = 0 to (bar_index - loc)
              min := math.min(low[i], min)
              max := min == low[i] ? high[i] : max
              idx := min == low[i] ? i : idx
    idx
SFPData() => [high, high[1] , high[2] , low, low[1] , low[2] , close, volume, time,
bar_index , time[1]]
SFPcords() =>
    RealTF = barstate.isrealtime ? 0 : 1
    [h, h1, h2, l, l1, l2, c, v, t, n, t1] =    SFPData()
    [h[RealTF], h1[RealTF], h2[RealTF], l[RealTF], l1[RealTF], l2[RealTF],
c[RealTF], v[RealTF], t[RealTF], n[RealTF], t1[RealTF]]
method find(structure ms, bool use_max, bool sweep, bool useob) =>
    min = 99999999.
    max = 0.
    idx = 0
    if not sweep
        if ((bar_index - ms.loc) - 1) > 0
              if use_max
                  for i = 0 to (bar_index - ms.loc) - 1
                      max := math.max(high[i], max)
                      min := max ==    high[i] ? low[i] : min
                      idx := max ==    high[i] ?      i : idx
                  if useob
                      if high[idx + 1] > high[idx]
                           max := high[idx + 1]
                           min := low [idx + 1]
                           idx :=      idx + 1
              else
                  for i = 0 to (bar_index - ms.loc) - 1
                      min := math.min(low[i], min)
                      max := min ==    low[i] ? high[i] : max
                      idx := min ==    low[i] ?       i : idx
                  if useob
                      if low[idx + 1] < low[idx]
                           max := high[idx + 1]
                           min := low [idx + 1]
                           idx :=      idx + 1
    else
        if use_max
            for i = 0 to (bar_index - ms.loc)
                max := math.max(high[i], max)
                min := max ==    high[i] ? low[i] : min
                idx := max ==    high[i] ?      i : idx
            if useob
                if high[idx + 1] > high[idx]
                     max := high[idx + 1]
                     min := low [idx + 1]
                     idx :=      idx + 1
        else
            for i = 0 to (bar_index - ms.loc)
                min := math.min(low[i], min)
                max := min ==    low[i] ? high[i] : max
                idx := min ==    low[i] ?       i : idx
            if useob
                if low[idx + 1] < low[idx]
                     max := high[idx + 1]
                     min := low [idx + 1]
                     idx :=      idx + 1
else
    if ((bar_index - ms.xloc) - 1) > 0
        if use_max
            for i = 0 to (bar_index - ms.xloc) - 1
                max := math.max(high[i], max)
                min := max ==    high[i] ? low[i] : min
                idx := max ==    high[i] ?      i : idx
        if useob
            if high[idx + 1] > high[idx]
                 max := high[idx + 1]
                 min := low [idx + 1]
                 idx :=      idx + 1
    else
        for i = 0 to (bar_index - ms.xloc) - 1
            min := math.min(low[i], min)
            max := min ==    low[i] ? high[i] : max
            idx := min ==    low[i] ?        i : idx
        if useob
            if low[idx + 1] < low[idx]
                 max := high[idx + 1]
                 min := low [idx + 1]
                 idx :=      idx + 1
else
    if use_max
        for i = 0 to (bar_index - ms.xloc)
            max := math.max(high[i], max)
            min := max ==    high[i] ? low[i] : min
            idx := max ==    high[i] ?       i : idx
        if useob
            if high[idx + 1] > high[idx]
                 max := high[idx + 1]
                 min := low [idx + 1]
                 idx :=      idx + 1
    else
        for i = 0 to (bar_index - ms.xloc)
            min := math.min(low[i], min)
                        max := min ==       low[i] ? high[i] : max
                        idx := min ==       low[i] ?       i : idx
                    if useob
                        if low[idx + 1] < low[idx]
                              max := high[idx + 1]
                              min := low [idx + 1]
                              idx :=        idx + 1
    idx
method fnOB(ob[] block, bool bull, float cords, int idx) =>
    switch bull
          true =>
              blobenter.normal       := false
              blobenter.breaker := false
              block.unshift(
                     ob.new(
                             true
                         , cords
                         , low      [idx]
                         , math.avg(cords, low[idx])
                         , time     [idx]
                         , obupcs
                         , volume[idx]
                         , close [idx]      > open[idx] ? 1 : -1
                         , 1
                         , 1
                         , 1
                         , time     [idx]
          false =>
            brobenter.normal      := false
            brobenter.breaker := false
            block.unshift(
                 ob.new(
                         false
                     , high      [idx]
                     , cords
                     , math.avg(cords, high[idx])
                     , time      [idx]
                     , obdncs
                     , volume[idx]
                     , close [idx]       > open[idx] ? 1 : -1
                     , 1
                     , 1
                     , 1
                     , time      [idx]
method mitigated(ob[] block) =>
    if barstate.isconfirmed
        for [i, stuff] in block
            if not stuff.isbb
                switch stuff.bull
                    true =>
                          if obmiti == "Close" ? math.min(close, open) < stuff.btm :
obmiti == "Wick" ? low    < stuff.btm : obmiti == "Avg" ? low < stuff.avg : na
                              stuff.isbb              := true
                              stuff.bbloc             := time
                              if not obshowbb
                                    block.remove(i)
                     false =>
                        if obmiti == "Close" ? math.max(close, open) > stuff.top :
obmiti == "Wick" ? high > stuff.top : obmiti == "Avg" ? high > stuff.avg : na
                               stuff.isbb            := true
                               stuff.bbloc           := time
                               if not obshowbb
                                   block.remove(i)
            else
                 switch stuff.bull
                     true =>
                        if obmiti == "Close" ? math.max(close, open) > stuff.top :
obmiti == "Wick" ? high > stuff.top : obmiti == "Avg" ? high > stuff.avg : na
                               block.remove(i)
                     false =>
                         if obmiti == "Close" ? math.min(close, open) < stuff.btm :
obmiti == "Wick" ? low   < stuff.btm : obmiti == "Avg" ? low < stuff.avg : na
                               block.remove(i)
overlap(ob[] bull, ob[] bear) =>
    if bull.size() > 1
        for i        = bull.size() - 1 to 1
            stuff    = bull.get(i)
            current = bull.get(0)
            v        = wichlap == "Recent" ? i : 0
            switch
                 stuff.btm > current.btm and stuff.btm < current.top =>
bull.remove(v)
                 stuff.top < current.top and stuff.btm > current.btm =>
bull.remove(v)
                 stuff.top > current.top and stuff.btm < current.btm =>
bull.remove(v)
                 stuff.top < current.top and stuff.top > current.btm =>
bull.remove(v)
   if bear.size() > 1
       for i         = bear.size() - 1 to 1
            stuff    = bear.get(i)
            current = bear.get(0)
            v        = wichlap == "Recent" ? i : 0
            switch
                 stuff.btm > current.btm and stuff.btm < current.top =>
bear.remove(v)
                 stuff.top < current.top and stuff.btm > current.btm =>
bear.remove(v)
                 stuff.top > current.top and stuff.btm < current.btm =>
bear.remove(v)
                 stuff.top < current.top and stuff.top > current.btm =>
bear.remove(v)
   if bull.size() > 0 and bear.size() > 0
       for i         = bull.size() - 1 to 0
            stuff    = bull.get(i)
            current = bear.get(0)
            v        = wichlap == "Recent" ? 0 : i
            switch
                 stuff.btm > current.btm and stuff.btm < current.top =>
bull.remove(v)
                 stuff.top < current.top and stuff.btm > current.btm =>
bull.remove(v)
                 stuff.top > current.top and stuff.btm < current.btm =>
bull.remove(v)
                 stuff.top < current.top and stuff.top > current.btm =>
bull.remove(v)
   if bull.size() > 0 and bear.size() > 0
       for i         = bear.size() - 1 to 0
            stuff    = bear.get(i)
            current = bull.get(0)
            v         = wichlap == "Recent" ? 0 : i
            switch
                  stuff.btm > current.btm and stuff.btm < current.top =>
bear.remove(v)
                  stuff.top < current.top and stuff.btm > current.btm =>
bear.remove(v)
                  stuff.top > current.top and stuff.btm < current.btm =>
bear.remove(v)
                  stuff.top < current.top and stuff.top > current.btm =>
bear.remove(v)
overlapFVG(FVG[] blFVG, FVG[] brFVG) =>
    if blFVG.size() > 1
        for i         = blFVG.size() - 1 to 1
            stuff     = blFVG.get(i)
            current = blFVG.get(0)
            switch
                  stuff.btm > current.btm and stuff.btm < current.top =>
blFVG.remove(i)
                  stuff.top < current.top and stuff.btm > current.btm =>
blFVG.remove(i)
                  stuff.top > current.top and stuff.btm < current.btm =>
blFVG.remove(i)
                  stuff.top < current.top and stuff.top > current.btm =>
blFVG.remove(i)
    if brFVG.size() > 1
        for i         = brFVG.size() - 1 to 1
            stuff     = brFVG.get(i)
            current = brFVG.get(0)
            switch
                  stuff.btm > current.btm and stuff.btm < current.top =>
brFVG.remove(i)
                  stuff.top < current.top and stuff.btm > current.btm =>
brFVG.remove(i)
                  stuff.top > current.top and stuff.btm < current.btm =>
brFVG.remove(i)
                  stuff.top < current.top and stuff.top > current.btm =>
brFVG.remove(i)
    if blFVG.size() > 0 and brFVG.size() > 0
        for i         = blFVG.size() - 1 to 0
            stuff     = blFVG.get(i)
            current = brFVG.get(0)
            switch
                  stuff.btm > current.btm and stuff.btm < current.top =>
blFVG.remove(i)
                  stuff.top < current.top and stuff.btm > current.btm =>
blFVG.remove(i)
                  stuff.top > current.top and stuff.btm < current.btm =>
blFVG.remove(i)
                  stuff.top < current.top and stuff.top > current.btm =>
blFVG.remove(i)
    if blFVG.size() > 0 and brFVG.size() > 0
        for i         = brFVG.size() - 1 to 0
            stuff     = brFVG.get(i)
            current = blFVG.get(0)
            switch
                  stuff.btm > current.btm and stuff.btm < current.top =>
brFVG.remove(i)
                  stuff.top < current.top and stuff.btm > current.btm =>
brFVG.remove(i)
                  stuff.top > current.top and stuff.btm < current.btm =>
brFVG.remove(i)
                  stuff.top < current.top and stuff.top > current.btm =>
brFVG.remove(i)
method umt(ob metric) =>
    switch metric.dir
        1 =>
            switch metric.move
                  1 => metric.blPOS := metric.blPOS + 1, metric.move := 2
                  2 => metric.blPOS := metric.blPOS + 1, metric.move := 3
                  3 => metric.brPOS := metric.brPOS + 1, metric.move := 1
        -1 =>
            switch metric.move
                  1 => metric.brPOS := metric.brPOS + 1, metric.move := 2
                  2 => metric.brPOS := metric.brPOS + 1, metric.move := 3
                  3 => metric.blPOS := metric.blPOS + 1, metric.move := 1
    if (time - time[1]) == (time[1] - time[2])
        metric.xlocbl := metric.loc + (time - time[1]) * metric.blPOS
        metric.xlocbr := metric.loc + (time - time[1]) * metric.brPOS
method display(ob id, ob[] full, int i) =>
    if not id.isbb
        bin.bx.unshift(box.new    (top = id.top, bottom = id.btm, left = id.loc,
right    = time      , border_color = na    , bgcolor = id.css, xloc =
xloc.bar_time))
        bin.bx.unshift(box.new    (top = id.top, bottom = id.btm, left = time     ,
right   = time + 1 , border_color = na     , bgcolor = id.css, xloc =
xloc.bar_time, extend = extend.right))
    else
        bin.bx.unshift(box.new    (top = id.top, bottom = id.btm, left = id.loc   ,
right = id.bbloc , border_color = na     , bgcolor = id.css                , xloc =
xloc.bar_time))
        bin.bx.unshift(box.new    (top = id.top, bottom = id.btm, left = id.bbloc ,
right = time     , border_color = id.css , bgcolor = id.bull ? bbup : bbdn , xloc =
xloc.bar_time, border_width = 2))
        bin.bx.unshift(box.new    (top = id.top, bottom = id.btm, left = time     ,
right = time + 1 , border_color = id.css , bgcolor = id.bull ? bbup : bbdn , xloc =
xloc.bar_time, extend = extend.right))
    if obshowactivity
        bin.bx.unshift(box.new    (top = id.top, bottom = id.avg, left = id.loc       ,
right = id.xlocbl, border_color = na     , bgcolor = obactup, xloc =
xloc.bar_time))
        bin.bx.unshift(box.new    (top = id.avg, bottom = id.btm, left = id.loc       ,
right = id.xlocbr, border_color = na     , bgcolor = obactdn, xloc =
xloc.bar_time))
    if showline
        bin.ln.unshift(line.new(
                x1     = id.loc
         , x2      = time
         , y1      = id.avg
         , y2      = id.avg
         , color = color.new(id.css, 0)
         , xloc    = xloc.bar_time
         , style = line.style_dashed
if showmetric
   if i == math.min(oblast - 1, full.size() - 1)
        float     tV = 0
        float[] dV = array.new<float>()
        seq         = math.min(oblast - 1, full.size() - 1)
        for j = 0 to seq
              cV = full.get(j)
              tV += cV.vol
              if j == seq
                  for y = 0 to seq
                      dV.push(
                             math.floor(
                                 (full.get(y).vol / tV) * 100)
                      ids = full.get(y)
                      bin.lb.unshift(label.new(
                               bar_index - 1
                             , ids.avg
                             , textcolor = color.new(ids.css, 0)
                             , style       = label.style_label_left
                             , size        = obtxt.txSz()
                             , color     = #ffffff00
                             , text      =
                                 str.tostring(
                                     math.round(full.get(y).vol, 3), format =
format.volume) + " (" + str.tostring(dV.get(y)) + "%)"
method dispFVG(FVG fvg, int i, bool bull) =>
    ext = fvgextend ? extend.right : extend.none
    if not fvg.isbb
        bin.bx.unshift(box .new(top = fvg.top, bottom = fvg.btm, left = fvg.loc
, right = time                   , border_color = na   , bgcolor = bull ? fvg_upcss
: fvg_dncss            , xloc = xloc.bar_time, extend = ext))
        if fvgline
            bin.ln.unshift(line.new(x1 = fvg.loc, x2 = time        , y1 =
math.avg(fvg.top, fvg.btm), y2 = math.avg(fvg.top, fvg.btm), xloc = xloc.bar_time,
color = color.new(bull ? fvg_upcss : fvg_dncss, 0)                      , extend =
ext))
        if dispraid
            bin.ln.unshift(line.new(x1 = fvg.raidloc, x2 = fvg.raidx2, y1 =
fvg.raidy, y2 = fvg.raidy, xloc = xloc.bar_time, color = fvg.raidcs))
            bin.lb.unshift(label.new(x = int(math.avg(fvg.raidloc, fvg.raidx2)), y
= fvg.raidy, text = "x", xloc = xloc.bar_time, textcolor = fvg.raidcs, style = bull
? label.style_label_up : label.style_label_down, size = size.small, color =
#ffffff00))
    else
        bin.bx.unshift(box .new(top = fvg.top , bottom = fvg.btm, left = fvg.loc
, right = fvg.bbloc              , border_color = na
, bgcolor = bull ? fvg_upcss : fvg_dncss, xloc = xloc.bar_time))
        bin.bx.unshift(box .new(top = fvg.top , bottom = fvg.btm, left = fvg.bbloc
, right = time                   , border_color = bull ? fvg_dncss : fvg_upcss
, bgcolor = bull ? fvg_dncss : fvg_upcss, xloc = xloc.bar_time, extend = ext))
        if fvgline
            bin.ln.unshift(line.new(x1 = fvg.loc , x2 = fvg.bbloc , y1      =
math.avg(fvg.top, fvg.btm), y2 = math.avg(fvg.top, fvg.btm), color = color.new(bull
? fvg_upcss : fvg_dncss, 0)                                        , xloc =
xloc.bar_time))
            bin.ln.unshift(line.new(x1 = fvg.bbloc, x2 = time        , y1   =
math.avg(fvg.top, fvg.btm), y2 = math.avg(fvg.top, fvg.btm), color = color.new(bull
? fvg_dncss : fvg_upcss, 0)                                              , xloc =
xloc.bar_time, extend = ext, style = line.style_dashed))
//}
_
='
                                                          ------------
                                ––––––––––––––––––––––––––   FUNCTION
–––––––––––––––––––––––––––
                                                          ------------
'//{
mapping() =>
      var float      up           = na
      var float      dn           = na
      var float point             = na
      var int     trend           = 0
      var int       idx           = na
      var int       sum           = na
      var int project             = na
      var chart.point[] charts = array.new<chart.point>()
      if na(up)
          up := high
          idx := bar_index
      if na(dn)
          dn := low
          idx := bar_index
      if high > up
          if trend == -1
                id = IDMIDX(false, idx)
                charts.unshift(
                     chart.point.from_time(
                            time[id]
                          , low [id]
                      )
        idx     := bar_index
        point := low [id]
        sum     := time[id]
   up         := high
   dn         := low
   project := time
   trend      := 1
if low < dn
   if trend == 1
        id = IDMIDX(true, idx)
        charts.unshift(
               chart.point.from_time(
                         time[id]
                     , high[id]
        idx     := bar_index
        point := high[id]
        sum     := time[id]
   up         := high
   dn         := low
   project := time
   trend := -1
if barstate.islast
   var line          ln = na
   var polyline pl = na
   ln.delete()
         pl.delete()
         ln := na
         pl := na
         ln := line.new(
                     x1 = sum
                 , x2 = project
                 , y1 = point
                 , y2 = trend == 1 ? up : dn
                 , xloc = xloc.bar_time
                 , color = color.red
         pl := polyline.new(
                     charts
                 , line_color = mappingcss
                 , xloc = xloc.bar_time
                 , line_style = mappingStyle.lstyle()
dFVG() =>
    [h2, l2, c1, o1, c, o, h, l, h1, l1, fvatr] = ghl()
    var FVG[] blFVG = array.new<FVG>()
    var FVG[] brFVG = array.new<FVG>()
    bool          upfvg = false
    bool          dnfvg = false
    float         blth    = l1 + (fvatr[1] * fvgthresh)
    float         brth    = h1 - (fvatr[1] * fvgthresh)
    cc      =                            timeframe.change()
    switch
         what_fvg == "FVG" or what_fvg == "Breakers" =>
                if l > h2 and cc and c1 > blth
                      upfvg := true
        if l2 > h and cc and c1 < brth
              dnfvg := true
if upfvg[1]
   if blFVG.size() > 0
        fvg = blFVG.get(0)
        if fvg.israid == true and fvg.active == false
              fvg.active     := true
              fvg.raidloc := na
              fvg.raidx2     := na
              fvg.raidy      := na
              fvg.raidcs     := #ffffff00
   blFVG.unshift(
         FVG.new(
                   l   [1]
               , h2    [1]
               , time[3]
               , false
               , na
if dnfvg[1]
   if brFVG.size() > 0
        fvg = brFVG.get(0)
        if fvg.israid == true and fvg.active == false
              fvg = brFVG.get(0)
              fvg.active := true
              fvg.active     := true
                fvg.raidloc := na
                fvg.raidx2        := na
                fvg.raidy         := na
                fvg.raidcs        := #ffffff00
        brFVG.unshift(
             FVG.new(
                       l2   [1]
                   , h      [1]
                   , time[3]
                   , false
                   , na
    if blFVG.size() > 0
        for [i, fvg] in blFVG
            if not fvg.isbb
                if fvg_src      == "Close" ? math.min(c, o) < fvg.btm : fvg_src ==
"Wick" ? l < fvg.btm : fvg_src == "Avg" ? l < math.avg(fvg.top, fvg.btm) : na
                        fvg.isbb                 := true
                        fvg.bbloc                := time
                        if what_fvg == "FVG"
                             blFVG.remove(i)
            else
                if (fvg_src == "Close" ? math.max(c, o) > fvg.top : fvg_src ==
"Wick" ? h > fvg.top : fvg_src == "Avg" ? h > math.avg(fvg.top, fvg.btm) : na) and
what_fvg == "Breakers"
                        blFVG.remove(i)
    if brFVG.size() > 0
        for [i, fvg] in brFVG
            if not fvg.isbb
                if (fvg_src     == "Close" ? math.max(c, o) > fvg.top : fvg_src ==
"Wick" ? h > fvg.top : fvg_src == "Avg" ? h > math.avg(fvg.top, fvg.btm) : na)
                      fvg.isbb               := true
                      fvg.bbloc              := time
                      if what_fvg == "FVG"
                          brFVG.remove(i)
            else
                if (fvg_src == "Close" ? math.min(c, o) < fvg.btm : fvg_src ==
"Wick" ? l < fvg.btm : fvg_src == "Avg" ? l < math.avg(fvg.top, fvg.btm) : na) and
what_fvg == "Breakers"
                      brFVG.remove(i)
    if fvgoverlap
        overlapFVG(blFVG, brFVG)
    if dispraid
        for [i, fvg] in blFVG
            if not fvg.israid and not fvg.isbb
                  if low < fvg.top and close > fvg.top
                      fvg.israid   := true
                      fvg.raidloc := time
                      fvg.raidx2   := time
                      fvg.raidy    := low
                      fvg.raidcs   := chart.fg_color
            else
                  if low <= fvg.raidy and fvg.active == false and not fvg.isbb
                fvg.active := true
                fvg.raidx2 := time
            else
                if fvg.active == false and not fvg.isbb
                     fvg.raidx2 := time
   for [i, fvg] in brFVG
        if not fvg.israid and not fvg.isbb
            if high > fvg.btm and close < fvg.btm and not fvg.isbb
                fvg.israid   := true
                fvg.raidloc := time
                fvg.raidy    := high
                fvg.raidx2   := time
                fvg.raidcs   := chart.fg_color
        else
            if high >= fvg.raidy and fvg.active == false and not fvg.isbb
                fvg.active := true
                fvg.raidx2 := time
            else
                if fvg.active == false and not fvg.isbb
                     fvg.raidx2 := time
if barstate.islast
   if blFVG.size() > 0 and fvg_num > 0
        for i = 0 to math.min(fvg_num - 1, blFVG.size() - 1)
            fvg = blFVG.get(i)
            dispFVG(fvg, i, true)
   if brFVG.size() > 0 and fvg_num > 0
        for i = 0 to math.min(fvg_num - 1, brFVG.size() - 1)
            fvg = brFVG.get(i)
                   dispFVG(fvg, i, false)
structure(color upcss, color dncss, bool draw, bool internal, int limit) =>
    var structure ms     = structure.new(start = 0)
    var       ob      [] blob         = array.new<      ob    >()
    var       ob      [] brob         = array.new<      ob    >()
    var drawms        [] bldw         = array.new<   drawms   >()
    var drawms        [] brdw         = array.new<   drawms   >()
    var sellbuyside[] sellside = array.new<sellbuyside>()
    var sellbuyside[] buyside         = array.new<sellbuyside>()
    bool        crossup =        false
    bool        crossdn =        false
    var float up         =       na
    var float dn         =       na
    idbull               =   ms.find(false, false, true)
    idbear               =   ms.find(true , false, true)
    btmP              = obmode == "Length" ? (high[idbear] - 1 * atr[idbear]) <
low [idbear] ? low [idbear] : (high[idbear] - 1 * atr[idbear]) : low [idbear]
    topP              = obmode == "Length" ? (low [idbull] + 1 * atr[idbull]) >
high[idbull] ? high[idbull] : (low [idbull] + 1 * atr[idbull]) : high[idbull]
    atr                  = ta.atr (200)
    buy                  = low    + atr
    sel                  = high - atr
    ph                   = ta.pivothigh(high, mslen, mslen)
    pl                   = ta.pivotlow (low , mslen, mslen)
    var int    [] phn    = array.new< int >(1, na)
    var int    [] pln    = array.new< int >(1, na)
    var float[] php      = array.new<float>(1, na)
    var float[] plp      = array.new<float>(1, na)
    if internal
          blob.clear()
        brob.clear()
    if ph
        phn.unshift(bar_index[mslen])
        php.unshift(high[mslen])
    if pl
        pln.unshift(bar_index[mslen])
        plp.unshift(low[mslen])
    if php.size() > 0
        if high > php.get(0)
             php.clear()
             phn.clear()
    if plp.size() > 0
        if low < plp.get(0)
             plp.clear()
             pln.clear()
    if na(up)
        up        := high
    if na(dn)
        dn        := low
    if high > up
        up        := high
        dn        := low
        crossup := true
    if low < dn
        up        := high
        dn        := low
        crossdn := true
    if ms.start == 0
        ms         := structure.new(bar_index, na, high, low , bar_index,
bar_index, 0, 1, na, bar_index)
        if draw
            bldw.unshift(drawms.new(time, time, high     , "CHoCH"    , upcss,
line.style_dashed))
            brdw.unshift(drawms.new(time, time, low      , "CHoCH"    , dncss,
line.style_dashed))
    ms.upsweep := false
    ms.dnsweep := false
    if ms.start == 1
        switch
            low <= ms.choch and close >= ms.choch and buildsweep =>
                  ms.dnsweep     := true
                  ms.choch       := low
                  ms.xloc        := bar_index
                  if draw
                      dw          = brdw.get(0)
                      dw.x2      := time
                      dw.style := line.style_dotted
                      dw.txt     := "x"
                      brdw.unshift(
                             drawms.new(
                                     time
                                 , time
                                 , low
                                 , "CHoCH"
                                 , dncss
                                 , line.style_dashed
            high >= ms.bos and close <= ms.bos and buildsweep =>
    ms.upsweep     := true
    ms.bos         := high
    ms.xloc        := bar_index
    if draw
        dw          = bldw.get(0)
        dw.x2      := time
        dw.style := line.style_dotted
        dw.txt     := "x"
        bldw.unshift(
               drawms.new(
                       time
                   , time
                   , high
                   , "CHoCH"
                   , upcss
                   , line.style_dashed
close <= ms.choch =>
    ms.txt         := "choch"
    lc.start := true
    lc.count := 0
    blob.fnOB(true, topP, idbull)
    ms.trend       := -1
    ms.choch       := ms.bos
    ms.bos         := na
            ms.start     := 2
            ms.loc       := bar_index
            ms.main      := low
            ms.temp      := ms.loc
            ms.xloc      := bar_index
            if draw
                dw          = brdw.get(0)
                dw.x2    := time
                dw.style := internal ? line.style_dashed : line.style_solid
        close >= ms.bos =>
            ms.txt       := "choch"
            lc.start := true
            lc.count := 0
            brob.fnOB(false, btmP, idbear)
            ms.trend     := 1
            ms.choch     := ms.choch
            ms.bos       := na
            ms.start     := 2
            ms.loc       := bar_index
            ms.main      := high
            ms.temp      := ms.loc
            ms.xloc      := bar_index
            if draw
                dw          = bldw.get(0)
                dw.x2    := time
                dw.style := internal ? line.style_dashed : line.style_solid
if ms.start == 2
       switch ms.trend
            -1 =>
                 if low <= ms.main
                     ms.main       := low
                     ms.temp       := bar_index
                 if bar_index % mslen * 2 == 0
                     if not na(ms.bos) and msmode == "Adjusted Points" and
php.size() > 0
                         if php.get(0) < ms.choch
                               // ms.xloc    := phn.get(0)
                               ms.choch := php.get(0)
                               ms.loc    := phn.get(0)
                               ms.xloc   := phn.get(0)
                               ms.temp   := phn.get(0)
                               if draw
                                   choch       = bldw.get(0)
                                   choch.x1 := time [bar_index - phn.get(0)]
                                   choch.x2 := time
                                   choch.y    := php.get(0)
                 if na(ms.bos)
                     if crossup and close > open and close[1] > open[1]
                         ms.bos    := ms.main
                         ms.loc    := ms.temp
                         ms.xloc := ms.loc
                         if draw
                               brdw.unshift(
                                    drawms.new(
                                            time[bar_index - ms.loc]
                                         , time
                                         , low [bar_index - ms.loc]
                                         , "BOS"
                                         , dncss
                                         , line.style_dashed
                if not na(ms.bos) and draw
                    dw          = brdw.get(0)
                    dw.x2      := time
                if draw
                    choch       = bldw.get(0)
                    choch.x2 := time
                switch
                    low <= ms.bos and close >= ms.bos and not na(ms.bos) and
buildsweep =>
                          ms.dnsweep     := true
                          ms.bos         := low
                          if draw
                              dw          = brdw.get(0)
                              dw.x2      := time
                              dw.style := line.style_dotted
                              dw.txt     := "x"
                              brdw.unshift(
                                    drawms.new(
                                             time
                                         , time
                                         , low
                                         , "BOS"
                                         , dncss
                                         , line.style_dashed
                                        )
                       ms.xloc         := bar_index
                   close <= ms.bos and not na(ms.bos) =>
                       ms.txt          := "bos"
                       ms.zz           := ms.bos
                       ms.zn           := bar_index
                       lc.start := true
                       lc.count := 0
                       brob.fnOB(false, btmP, idbear)
                       id           = ms.find(true, false, false)
                       ms.xloc   := bar_index
                       ms.bos    := na
                       ms.choch := high          [id]
                       ms.loc    := bar_index[id]
                       if draw
                            dw          = brdw.get(0)
                            dw.x2      := time
                            dw.style := internal ? line.style_dashed :
line.style_solid
                            choch       = bldw.get(0)
                            choch.x1 := time [id]
                            choch.x2 := time
                            choch.y    := high [id]
switch
    high >= ms.choch and close <= ms.choch and buildsweep =>
         ms.upsweep     := true
         ms.choch       := high
         ms.xloc        := bar_index
         if draw
             dw          = bldw.get(0)
             dw.x2      := time
             dw.style := line.style_dotted
             dw.txt     := "x"
             bldw.unshift(
                    drawms.new(
                            time
                        , time
                        , high
                        , "CHoCH"
                        , upcss
                        , line.style_dashed
    close >= ms.choch =>
         ms.txt         := "choch"
         ms.zz          := ms.choch
         ms.zn          := bar_index
               lc.start := true
               lc.count := 0
               blob.fnOB(true, topP, idbull)
               id          = ms.find(false, false, false)
               switch
                    na(ms.bos) =>
                         ms.choch := low[id]
                         if draw
                             brdw.unshift(
                                    drawms.new(
                                         time
                                        , time
                                        , low
                                        , "BOS"
                                        , dncss
                                        , line.style_dashed
                             choch = brdw.get(0)
                             choch.x1 := time[bar_index - ms.temp]
                    => ms.choch := ms.bos//low[id + 1] < low[id] ? low[id +
1] : low[id]
               ms.bos     := na
               ms.main    := high
               ms.trend := 1
               ms.loc     := bar_index
               ms.xloc    := bar_index
               ms.temp    := ms.loc
               if draw
                    dw            = bldw.get(0)
                              dw.x2       := time
                              dw.txt      := "CHoCH"
                              dw.style    := internal ? line.style_dashed :
line.style_solid
                              choch        = brdw.get(0)
                              choch.x2    := time
                              choch.y     := ms.choch
                              choch.txt := "CHoCH"
                        ms.xloc           := bar_index
                        blarea.normal := false
            1 =>
                if high >= ms.main
                    ms.main       := high
                    ms.temp       := bar_index
                if na(ms.bos)
                    if crossdn and close < open and close[1] < open[1]
                        ms.bos    := ms.main
                        ms.loc    := ms.temp
                        ms.xloc := ms.loc
                        if draw
                              bldw.unshift(
                                   drawms.new(
                                           time[bar_index - ms.loc]
                                         , time
                                         , high[bar_index - ms.loc]
                                         , "BOS"
                                         , upcss
                                          , line.style_dashed
                 if bar_index % mslen * 2 == 0
                     if not na(ms.bos) and msmode == "Adjusted Points" and
plp.size() > 0
                           if plp.get(0) > ms.choch
                               // ms.xloc        := pln.get(0)
                               ms.choch := plp.get(0)
                               ms.loc     := pln.get(0)
                               ms.xloc    := pln.get(0)
                               ms.temp    := pln.get(0)
                               // ms.loc         := pln.get(0)
                               if draw
                                     choch         = brdw.get(0)
                                     choch.x1 := time [bar_index - pln.get(0)]
                                     choch.x2 := time
                                     choch.y      := plp.get(0)
                 if not na(ms.bos) and draw
                     dw             = bldw.get(0)
                     dw.x2       := time
                 if draw
                     choch          = brdw.get(0)
                     choch.x2    := time
                 switch
                     high >= ms.bos and close <= ms.bos and not na(ms.bos) and
buildsweep =>
                           ms.upsweep     := true
                           ms.bos         := high
                           if draw
         dw          = bldw.get(0)
         dw.x2      := time
         dw.style := line.style_dotted
         dw.txt     := "x"
         bldw.unshift(
              drawms.new(
                        time
                    , time
                    , high
                    , "BOS"
                    , upcss
                    , line.style_dashed
    ms.xloc         := bar_index
close >= ms.bos and not na(ms.bos) =>
    ms.txt          := "bos"
    ms.zz           := ms.bos
    ms.zn           := bar_index
    lc.start := true
    lc.count := 0
    blob.fnOB(true, topP, idbull)
    id           = ms.find(false, false, false)
    ms.xloc   := bar_index
    ms.bos    := na
    ms.choch := low            [id]
    ms.loc    := bar_index[id]
                          if draw
                              dw          = bldw.get(0)
                              dw.x2      := time
                              dw.style := internal ? line.style_dashed :
line.style_solid
                              choch       = brdw.get(0)
                              choch.x1 := time [id]
                              choch.x2 := time
                              choch.y    := low    [id]
                switch
                    low    <= ms.choch and close >= ms.choch and buildsweep =>
                          ms.dnsweep     := true
                          ms.choch       := low
                          ms.xloc        := bar_index
                          if draw
                              dw          = brdw.get(0)
                              dw.x2      := time
                              dw.style := line.style_dotted
                              dw.txt     := "x"
                              brdw.unshift(
                                     drawms.new(
                                           time
                                         , time
                                         , low
                                         , "CHoCH"
                                         , dncss
                                         , line.style_dashed
                                          )
                                        )
                    close <= ms.choch =>
                          ms.txt        := "choch"
                          ms.zz         := ms.choch
                          ms.zn         := bar_index
                          lc.start := true
                          lc.count := 0
                          brob.fnOB(false, btmP, idbear)
                          id         = ms.find(true, false, false)
                          switch
                               na(ms.bos) =>
                                   ms.choch := high[id]
                                   if draw
                                       bldw.unshift(
                                             drawms.new(
                                                     time
                                                 , time
                                                 , high
                                                 , "BOS"
                                                 , upcss
                                                 , line.style_dashed
                                       choch = bldw.get(0)
                                       choch.x1 := time[bar_index - ms.temp]
                               => ms.choch := ms.bos//high[id + 1] > high[id] ?
high[id + 1] : high[id]
                          ms.bos    := na
                         ms.main   := low
                         ms.trend := -1
                         ms.loc    := bar_index
                         ms.temp   := ms.loc
                         if draw
                             dw           = brdw.get(0)
                             dw.x2      := time
                             dw.txt     := "CHoCH"
                             dw.style   := internal ? line.style_dashed :
line.style_solid
                             choch        = bldw.get(0)
                             choch.y    := ms.choch
                             choch.x2   := time
                             choch.txt := "CHoCH"
                         ms.xloc        := bar_index
   if blob.size() > 0
       ob = blob.get(0)
       if not ob.isbb
            if low   < ob.top
                if blobenter.normal          == false
                     blobenter.normal          := true
       else
            if high > ob.btm
                if blobenter.breaker         == false
                 blobenter.breaker     := true
if brob.size() > 0
    ob = brob.get(0)
    if not ob.isbb
        if high > ob.btm
            if brobenter.normal        == false
                 brobenter.normal      := true
    else
        if low   < ob.top
            if brobenter.breaker      == false
                 brobenter.breaker     := true
if obshow and oblast > 0
    if barstate.isconfirmed
        blob.mitigated()
        brob.mitigated()
        if overlap
            overlap(blob, brob)
    if blob.size() > 0
        for [i, metric] in blob
            metric.umt()
    if brob.size() > 0
        for [i, metric] in brob
            metric.umt()
    if barstate.islast
        if blob.size() > 0
            for i = 0 to math.min(oblast - 1, blob.size() - 1)
                 obs = blob.get(i)
                    display(obs, blob, i)
            if brob.size() > 0
                for i = 0 to math.min(oblast - 1, brob.size() - 1)
                    obs = brob.get(i)
                    display(obs, brob, i)
    if barstate.islast and draw and bldw.size() > 0 and brdw.size() > 0
        for i = 0 to bldw.size() - 1
            obj = bldw.get(i)
            if i <= limit
                bin.ln.unshift(
                     line.new(
                               x1    = obj.x1
                           , x2      = obj.x2
                           , y1      = obj.y
                           , y2      = obj.y
                           , color = obj.css
                           , style = obj.style
                           , xloc    = xloc.bar_time
                bin.lb.unshift(
                     label.new(
                               x         = int(math.avg(bin.ln.get(0).get_x1(),
bin.ln.get(0).get_x2()))
                           , y           = obj.y
                           , xloc        = xloc.bar_time
                           , color       = #ffffff00
                           , style       = label.style_label_down
                           , textcolor = obj.css
                           , size        = mstext.txSz()
                 , text             = obj.txt
        if msbubble
            bin.lb.unshift(
                 label.new(
                            x       = obj.x1
                        , y         = obj.y
                        , xloc      = xloc.bar_time
                        , color = color.new(obj.css, 80)
                        , style = label.style_circle
                        , size      = size.tiny
for i = 0 to brdw.size() - 1
    obj = brdw.get(i)
    if i <= limit
        bin.ln.unshift(
             line.new(
                     x1         = obj.x1
                 , x2           = obj.x2
                 , y1           = obj.y
                 , y2           = obj.y
                 , color = obj.css
                 , style = obj.style
                 , xloc         = xloc.bar_time
        bin.lb.unshift(
                     label.new(
                               x               = int(math.avg(bin.ln.get(0).get_x1(),
bin.ln.get(0).get_x2()))
                           , y                 = obj.y
                           , xloc              = xloc.bar_time
                           , color             = #ffffff00
                           , style             = label.style_label_up
                           , textcolor = obj.css
                           , size              = mstext.txSz()
                           , text              = obj.txt
                if msbubble
                    bin.lb.unshift(
                                   label.new(
                                           x       = obj.x1
                                       , y         = obj.y
                                       , xloc      = xloc.bar_time
                                       , color = color.new(obj.css, 80)
                                       , style = label.style_circle
                                       , size      = size.tiny
      ms
//}
_
='
                                                                 ------------
                               ––––––––––––––––––––––––––          EXECUTION
–––––––––––––––––––––––––––
                                                                 ------------
'//{
structure        ms = na
if windowsis
    if (bar_index > last_bar_index - mswindow)
          ms := structure(swingcssup , swingcssdn , showSwing   , false, swingLimit)
if windowsis == false
    ms := structure(swingcssup , swingcssdn , showSwing     , false, swingLimit)
// if showInternal and inZone
//     structure ims = structure(interncssup, interncssdn, showInternal, true ,
swingLimit)
color css    = na
method darkcss(color css, float factor) =>
    blue    = color.b(css) * (1 - factor)
    red     = color.r(css) * (1 - factor)
    green = color.g(css) * (1 - factor)
    color.rgb(red, green, blue, 0)
if windowsis ? (bar_index > last_bar_index - mswindow) : true
    css := ms.trend == 1 ? swingcssup : swingcssdn
    css := (ms.txt == "bos" ? css : css.darkcss(0.3))
barcolor(candlecss ? css : na)
if fvg_enable
    dFVG()
if showMapping
    mapping()
var phl = Zphl.new(
   na
 , na
 , label.new(na , na , color = invcol , textcolor = swingcssdn , style =
label.style_label_down , size = size.tiny , text = "")
 , label.new(na , na , color = invcol , textcolor = swingcssup , style =
label.style_label_up   , size = size.tiny , text = "")
 , true
 , true
 , true
 , true
 , ""
 , ""
 , 0
 , 0
 , 0
 , 0
 , high
 , low
 , 0
 , 0
 , 0
 , 0
 , 0
 , 0
 , na
 , na
// === Inputs ===
length = input.int(14, title="ATR Length")
sl_multiplier = input.float(0.5, title="Stop Loss Multiplier", minval=0.0,
step=0.1)
pt_multiplier = input.float(2.25, title="Profit Target Multiplier", minval=0.0,
step=0.05)
trade_type = input.string("Long", title="Trade Direction", options=["Long",
"Short"])
// === ATR Calculation ===
atr_value = ta.atr(length)
// === SL & PT Calculation ===
sl_value = (1 + sl_multiplier) * atr_value
pt_value = pt_multiplier * sl_value
// === Inputs ===
adxLength = input.int(14, title="ADX Length")
threshold = input.int(20, title="ADX Threshold")
// === Get ADX from DMI function ===
[plusDI, minusDI, adx] = ta.dmi(adxLength, 14)
// === Determine Trend Status ===
trendStatus = adx > threshold ? "Trending - OK ✅" : "Sideways - Avoid 🔴"
trendColor = adx > threshold ? color.green : color.red
// === Table Creation ===
var table statusTable = table.new(position.top_right, 2, 2, border_width = 1)
// === Update Table ===
if bar_index % 1 == 0
    table.cell(statusTable, 0, 0, "ADX Value", text_color=color.white,
bgcolor=color.blue)
    table.cell(statusTable, 1, 0, str.tostring(adx, "#.##"),
text_color=color.white, bgcolor=color.blue)
    table.cell(statusTable, 0, 1, "Status", text_color=#000000, bgcolor=#ffe70e)
    table.cell(statusTable, 1, 1, trendStatus, text_color=color.white,
bgcolor=trendColor)
//MarketMagnet
// === INPUTS ===
nATRPeriod = input.int(21, title="ATR Period 🕒")
nATRMultip = input.float(6.3, title="ATR Multiplier 🔢", minval=0.5, maxval=1000,
step=0.1)
vwmaLen = input.int(100, title="VWMA Length 📏", minval=1)
// === ATR TRAILING STOP ===
xATR = ta.atr(nATRPeriod)
nLoss = nATRMultip * xATR
var float xATRTrailingStop = na
xATRTrailingStop := if close > nz(xATRTrailingStop[1], close)
    close > nz(xATRTrailingStop[1], close) and close[1] > nz(xATRTrailingStop[1],
close) ? math.max(nz(xATRTrailingStop[1]), close - nLoss) : close - nLoss
else
    close < nz(xATRTrailingStop[1], close) and close[1] < nz(xATRTrailingStop[1],
close) ? math.min(nz(xATRTrailingStop[1]), close + nLoss) : close + nLoss
// === POSITION LOGIC ===
var int pos = 0
pos := close[1] < nz(xATRTrailingStop[1], close) and close >
nz(xATRTrailingStop[1], close) ? 1 : close[1] > nz(xATRTrailingStop[1], close) and
close < nz(xATRTrailingStop[1], close) ? -1 : nz(pos[1], 0)
// === TRADING STATE ===
var bool isLong = false
var bool isShort = false
// Buy/Sell Signals
bool LONG = pos == 1 and not isLong
bool SHORT = pos == -1 and not isShort
// Update States
if LONG
    isLong := true
    isShort := false
if SHORT
    isLong := false
    isShort := true
// === VWMA ===
vwma = ta.vwma(close, vwmaLen)
avg1 = math.avg(vwma, xATRTrailingStop)
// === PLOTTING ===
plotshape(LONG, title="Buy", style=shape.labelup, location=location.belowbar,
color=color.green, text="CE BUY ", textcolor=color.white, size=size.normal)
plotshape(SHORT, title="Sell", style=shape.labeldown, location=location.abovebar,
color=color.red, text="PE BUY", textcolor=color.white, size=size.normal)
// === ALERTS ===
alertcondition(LONG, title="Buy Signal", message="CE BUY 📈")
alertcondition(SHORT, title="Sell Signal", message="PE BUY 📉")
// === MULTI-TIMEFRAME SIGNALS ===
f_getSignal(tf) =>
    [pos_tf, long_tf, short_tf] = request.security(syminfo.tickerid, tf, [pos,
LONG, SHORT], barmerge.gaps_off, barmerge.lookahead_off)
    signal = long_tf ? "LONG ⚖️
                             " : short_tf ? "SHORT " : "Neutral ⚖️"
    signal
// Timeframes
tf_1m = f_getSignal("1")
tf_5m = f_getSignal("5")
tf_15m = f_getSignal("15")
tf_30m = f_getSignal("30")
tf_4h = f_getSignal("240")
// === TABLE ===
var table signalTable = table.new(position.bottom_left, 2, 6, border_width=2,
border_color=color.new(#de26ff, 0), bgcolor=#0749ff)
if barstate.isconfirmed
    table.cell(signalTable, 0, 0, "Timeframe ⏰", text_color=color.white,
bgcolor=color.new(color.blue, 40), text_size=size.large,
text_halign=text.align_center)
    table.cell(signalTable, 1, 0, "Signal 🌟", text_color=color.white,
bgcolor=color.new(color.blue, 40), text_size=size.large,
text_halign=text.align_center)
    table.cell(signalTable, 0, 1, "1m ", text_color=color.white,
bgcolor=color.new(color.teal, 60), text_size=size.normal,
text_halign=text.align_center)
    table.cell(signalTable, 1, 1, tf_1m, text_color=tf_1m == "LONG 📈" ?
color.lime : tf_1m == "SHORT 📉" ? color.red : color.yellow, bgcolor=color.new(tf_1m
== "LONG 📈" ? color.green : tf_1m == "SHORT 📉" ? color.red : color.yellow, 70),
text_size=size.normal, text_halign=text.align_center)
    table.cell(signalTable, 0, 2, "5m ", text_color=color.white,
bgcolor=color.new(color.teal, 60), text_size=size.normal,
text_halign=text.align_center)
    table.cell(signalTable, 1, 2, tf_5m, text_color=tf_5m == "LONG 📈" ?
color.lime : tf_5m == "SHORT 📉" ? color.red : color.yellow, bgcolor=color.new(tf_5m
== "LONG 📈" ? color.green : tf_5m == "SHORT 📉" ? color.red : color.yellow, 70),
text_size=size.normal, text_halign=text.align_center)
    table.cell(signalTable, 0, 3, "15m ", text_color=color.white,
bgcolor=color.new(color.teal, 60), text_size=size.normal,
text_halign=text.align_center)
    table.cell(signalTable, 1, 3, tf_15m, text_color=tf_15m == "LONG 📈" ?
color.lime : tf_15m == "SHORT 📉" ? color.red : color.yellow,
bgcolor=color.new(tf_15m == "LONG 📈" ? color.green : tf_15m == "SHORT 📉" ?
color.red : color.yellow, 70), text_size=size.normal,
text_halign=text.align_center)
    table.cell(signalTable, 0, 4, "30m ", text_color=color.white,
bgcolor=color.new(color.teal, 60), text_size=size.normal,
text_halign=text.align_center)
    table.cell(signalTable, 1, 4, tf_30m, text_color=tf_30m == "LONG 📈" ?
color.lime : tf_30m == "SHORT 📉" ? color.red : color.yellow,
bgcolor=color.new(tf_30m == "LONG 📈" ? color.green : tf_30m == "SHORT 📉" ?
color.red : color.yellow, 70), text_size=size.normal,
text_halign=text.align_center)
    table.cell(signalTable, 0, 5, "4h ", text_color=color.white,
bgcolor=color.new(color.teal, 60), text_size=size.normal,
text_halign=text.align_center)
    table.cell(signalTable, 1, 5, tf_4h, text_color=tf_4h == "LONG 📈" ?
color.lime : tf_4h == "SHORT 📉" ? color.red : color.yellow, bgcolor=color.new(tf_4h
== "LONG 📈" ? color.green : tf_4h == "SHORT 📉" ? color.red : color.yellow, 70),
text_size=size.normal, text_halign=text.align_center)
// Input Groups
var string atr_settings      = "════════ ATR Settings ════════"
var string score_settings    = "════════ Dynamic Score Settings ════════"
var string bar_coloring      = "════════ Bar Coloring ════════"
// Descriptions for inputs (Tooltips)
tooltip_atr_length           = "Length of the Average True Range (ATR) used to
calculate the Supertrend bands. A higher length will make the Supertrend smoother."
tooltip_atr_multiplier       = "Multiplier applied to the ATR value to calculate
the Supertrend bands. Increasing the multiplier will widen the bands, making trend
changes less frequent."
tooltip_window_length        = "The length of the window over which the dynamic
score is calculated. A longer window will consider more data points, resulting in a
slower but more stable score."
tooltip_uptrend_threshold    = "Threshold value above which an uptrend is detected.
Increase to make trend signals less sensitive."
tooltip_downtrend_threshold = "Threshold value below which a downtrend is
detected. Decrease to make trend signals less sensitive."
tooltip_bar_coloring           = "Enable or disable bar coloring based on the
detected trend direction."
tooltip_bg_coloring            = "Enable or disable background coloring based on
trend direction."
// ATR Settings
atr_length                     = input.int(14, "ATR Length", group=atr_settings,
tooltip=tooltip_atr_length)
atr_multiplier               = input.float(2.0, "ATR Multiplier",
group=atr_settings, tooltip=tooltip_atr_multiplier)
// Dynamic Score Settings
window_len                   = input.int(50, "Window Length", group=score_settings,
tooltip=tooltip_window_length)
uptrend_threshold            = input.int(40, "Uptrend Threshold",
group=score_settings, tooltip=tooltip_uptrend_threshold)
downtrend_threshold          = input.int(-10, "Downtrend Threshold",
group=score_settings, tooltip=tooltip_downtrend_threshold)
// Bar Coloring Settings
up_color                     = input.color(#00ffaa, "Uptrend Color",
group=bar_coloring, tooltip="Color of the bars during an uptrend.")
down_color                   = input.color(#ff0000, "Downtrend Color",
group=bar_coloring, tooltip="Color of the bars during a downtrend.")
bar                           = input.bool(true, "Color Bars?", group=bar_coloring,
tooltip=tooltip_bar_coloring)
bg_coloring                  = input.bool(false, "Background Coloring?",
group=bar_coloring, tooltip=tooltip_bg_coloring)
//                ╔════════════════════════════════╗              //
//                ║      SUPERTREND CALCULATION    ║              //
//                ╚════════════════════════════════╝              //
dg_atr_len = ta.atr(atr_length)
upper_band = ta.sma(close, atr_length) + atr_value * atr_multiplier
lower_band = ta.sma(close, atr_length) - atr_value * atr_multiplier
supertrend_direction = close > upper_band ? 1 : close < lower_band ? -1 : na
//                ╔════════════════════════════════╗              //
//                ║   QUANT ALGO'S DYNAMIC SCORE   ║              //
//               ╚════════════════════════════════╝             //
var float[] score_array = array.new_float(window_len, 0)
dynamic_score() =>
     float score = 0.0
     for i = 0 to window_len - 1
        float comparison = close > upper_band[i + 1] ? 1 : close < lower_band[i +
1] ? -1 : 0
         array.set(score_array, i, comparison)
         score += comparison
     score
trend_score = dynamic_score()
//               ╔════════════════════════════════╗             //
//               ║          TREND DETECTION       ║             //
//               ╚════════════════════════════════╝             //
bool long_condition   = trend_score > uptrend_threshold
bool short_condition = trend_score < downtrend_threshold
var int trend_direction_final = 0
if (long_condition and not short_condition)
     trend_direction_final := 1
else if (short_condition)
     trend_direction_final := -1
//               ╔════════════════════════════════╗             //
//               ║          VISUALIZATION         ║             //
//               ╚════════════════════════════════╝             //
// Plot Supertrend lines with gradient fill between trend lines and body middle
bullish_trend_plot     = plot(trend_direction_final == 1 ? lower_band : na,
color=color.new(up_color, 10), linewidth=3, style=plot.style_linebr)
bearish_trend_plot     = plot(trend_direction_final == -1 ? upper_band : na,
color=color.new(down_color, 10), linewidth=3, style=plot.style_linebr)
// === Hardcoded EMA lengths ===
fastLen = 20
slowLen = 200
// === Trend Logic ===
getTrend(tf) =>
    fast = request.security(syminfo.tickerid, tf, ta.ema(close, fastLen))
    slow = request.security(syminfo.tickerid, tf, ta.ema(close, slowLen))
    fast > slow ? "↑" : fast < slow ? "↓" : "→"
// === Table Setup ===
var table t = table.new(position.bottom_right, 2, 8, border_width=1)
if bar_index == 1
    table.cell(t, 0, 0, "TF", text_color=color.white, bgcolor=color.black,
text_halign=text.align_center)
    table.cell(t, 1, 0, "Trend", text_color=color.white, bgcolor=color.black,
text_halign=text.align_center)
// === Row Render Function ===
renderRow(row, label, tf) =>
    trend = getTrend(tf)
    bg = trend == "↑" ? color.green : trend == "↓" ? color.red : color.gray
    table.cell(t, 0, row, label, text_color=color.white, bgcolor=color.rgb(40, 42,
54), text_halign=text.align_center)
    table.cell(t, 1, row, trend, text_color=color.white, bgcolor=bg,
text_halign=text.align_center)
// === Render Fixed Rows ===
renderRow(1, "3m", "3")
renderRow(2, "5m", "5")
renderRow(3, "15m", "15")
renderRow(4, "1H", "60")
renderRow(5, "4H", "240")
renderRow(6, "1D", "D")
renderRow(7, "1W", "W")