Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //@version=6
- indicator("Flux Chartsβ’ - SFX Algo", shorttitle = "Flux Chartsβ’ - SFX Algo", overlay = true, max_labels_count = 500, max_lines_count = 500, max_bars_back = 500)
- const string GRP_ALGO = "Algorithm Settings"
- const string GRP_TP = "Take Profit Settings"
- const string GRP_OVR = "Overlays"
- const string GRP_DASH = "Dashboard"
- const string GRP_ALERT = "Alerts"
- const string GRP_THEME = "Theme"
- const string TT_SENS = "Sensitivity determines how frequently signals appear. A higher sensitivity would lead to more frequent signals (Buy & Sell) appearing on your chart."
- const string TT_STRENGTH = "Signal Strength helps filter out low-rated signals based on our Stochastic Weighting Algorithm. A higher signal strength will lead to fewer signals on your chart. A higher-rated signal doesn't necessarily make it a better signal than a lower-rated signal."
- const string TT_TIME = "Time Weighting allows you to choose how much historic data the indicator uses when interpreting data for the signals.\n\nRecent Trends: only recent market data is used (recency bias).\nMixed Trends: a balance between enough data points and recency bias.\nLongterm Trends: more historic data is used, weighting the overall past performance of each metric."
- const string TT_MINSTAR = "Filters out signals with a star rating below this value (1 - 5)."
- const string TT_STYLE = "Adapts the algorithm's internal lengths to your trading approach. Scalper = faster, Day Trader = balanced, Swing Trader = slower and smoother."
- const string TT_AI = "Automatically finds and sets the best sensitivity for the current ticker by evaluating multiple sensitivity candidates against recent price action. The Sensitivity input is used during the warm-up period."
- const string TT_METHOD = "Dynamic: TP levels use the take profit inputs (% Profit or ATR) and the Auto Stop-Loss uses the SFX sub-trend with your Risk Tolerance.\nKey Levels: TP & SL are placed at nearby market structure key levels (swing highs / lows).\nVolatility Bands: TP & SL are placed at the volatility band layers.\nSignal Rating: TP & SL distances adapt to the star rating of the signal."
- const string TT_TP = "Enable / disable each take profit level (labels & notifications). Values are used by the Dynamic TP / SL Method as % Profit from entry or as ATR multiples."
- const string TT_REPEAT = "When enabled, a new take profit signal & notification is generated every time price retests a take profit level that was already reached."
- const string TT_TPOPT = "Dynamic method only. Optimizes the take profit distances using the average maximum favorable excursion of the most recent SFX signals."
- const string TT_AUTOSL = "Automatically finds stop-loss exits. With the Dynamic method the SFX Algo's sub-trends are combined with your Risk Tolerance setting."
- const string TT_RISK = "Low = tighter stop-loss, Medium = balanced, High = wider stop-loss."
- const string TT_RT = "Draws realtime TP & SL lines and labels for the latest signal. Only available for the Key Levels TP / SL Method."
- const string TT_VB = "The volatility bands show areas of potential reversals. Tight bands = consolidation, which could lead to an impulsive move."
- const string TT_TC = "The colored candles (green & red) simplify the market into basic uptrends and downtrends."
- const string TT_STARS = "Displays the star rating (1 - 5) within the Buy & Sell labels. When disabled, stronger signals are marked with a '+' symbol."
- const string TT_RATINGLBL = "Displays a label every time the rating of the active signal is upgraded or downgraded. Buy & Sell labels take priority over rating labels."
- const string TT_TRAIL = "Displays the SFX trend trail and its fill towards price."
- const string TT_WAVE = "Highlights the retracement zone (0.382 - 0.618) of the current SFX trend leg."
- const string TT_GAUSS = "The Gauss Ribbon smooths out recent price movements using a Gaussian algorithm. The space between the upper and lower bands shows how volatile the market is. Band retests can confirm the strength of the trend."
- const string TT_WEBHOOK = "Formats all alert() notifications as JSON for webhooks: signal, rating, pre-determined TP & SL levels, ticker id object (incl. futures data) and Heikin Ashi safe prices."
- const int AI_CANDIDATES = 10
- const int AI_WARMUP = 200
- const int RT_EXTEND = 25
- const int PIVOT_MEMORY = 60
- const int MFE_MEMORY = 30
- int sensitivityInput = input.int(75, "Sensitivity", minval = 1, maxval = 100, group = GRP_ALGO, tooltip = TT_SENS)
- int signalStrength = input.int(25, "Signal Strength", minval = 0, maxval = 100, group = GRP_ALGO, tooltip = TT_STRENGTH)
- string timeWeighting = input.string("Recent Trends", "Time Weighting", options = ["Recent Trends", "Mixed Trends", "Longterm Trends"], group = GRP_ALGO, tooltip = TT_TIME)
- int minStarRating = input.int(4, "Minimum Star Rating", minval = 1, maxval = 5, group = GRP_ALGO, tooltip = TT_MINSTAR)
- string tradingStyle = input.string("Swing Trader", "Trading Style", options = ["Scalper", "Day Trader", "Swing Trader"], group = GRP_ALGO, tooltip = TT_STYLE)
- bool aiOptimizer = input.bool(false, "AI Sensitivity Optimizer", group = GRP_ALGO, tooltip = TT_AI)
- string tpSlMethod = input.string("Key Levels", "TP / SL Method", options = ["Dynamic", "Key Levels", "Volatility Bands", "Signal Rating"], group = GRP_TP, tooltip = TT_METHOD)
- bool tp1On = input.bool(true, "", inline = "tp1", group = GRP_TP)
- float tp1Val = input.float(0.5, "Take profit 1 at", minval = 0.0, step = 0.1, inline = "tp1", group = GRP_TP)
- string tp1Unit = input.string("% Profit", "", options = ["% Profit", "ATR"], inline = "tp1", group = GRP_TP, tooltip = TT_TP)
- bool tp2On = input.bool(true, "", inline = "tp2", group = GRP_TP)
- float tp2Val = input.float(1.5, "Take profit 2 at", minval = 0.0, step = 0.1, inline = "tp2", group = GRP_TP)
- string tp2Unit = input.string("% Profit", "", options = ["% Profit", "ATR"], inline = "tp2", group = GRP_TP)
- bool tp3On = input.bool(true, "", inline = "tp3", group = GRP_TP)
- float tp3Val = input.float(3.0, "Take profit 3 at", minval = 0.0, step = 0.1, inline = "tp3", group = GRP_TP)
- string tp3Unit = input.string("% Profit", "", options = ["% Profit", "ATR"], inline = "tp3", group = GRP_TP)
- bool repeatTP = input.bool(false, "Repeat Take Profit Signals", group = GRP_TP, tooltip = TT_REPEAT)
- bool tpOptimize = input.bool(false, "Take Profit Level Optimization", group = GRP_TP, tooltip = TT_TPOPT)
- bool autoSL = input.bool(true, "Auto Stop-Loss", group = GRP_TP, tooltip = TT_AUTOSL)
- string riskTolerance = input.string("Medium", "Risk Tolerance", options = ["Low", "Medium", "High"], group = GRP_TP, tooltip = TT_RISK)
- bool realtimeLines = input.bool(false, "Realtime TP / SL Lines & Labels", group = GRP_TP, tooltip = TT_RT)
- bool showVB = input.bool(true, "Volatility Bands", group = GRP_OVR, tooltip = TT_VB)
- bool showTPLabel = input.bool(true, "Take Profit Label", group = GRP_OVR)
- bool showTrendColor = input.bool(true, "Trend Coloring", group = GRP_OVR, tooltip = TT_TC)
- string trendColorMode = input.string("Bar Color", "Trend Coloring Mode", options = ["Bar Color", "Bar Color + Wicks"], group = GRP_OVR)
- bool showStrength = input.bool(true, "Strength Rating", group = GRP_OVR, tooltip = TT_STARS)
- bool showRatingLabels = input.bool(false, "Signal Rating Labels", group = GRP_OVR, tooltip = TT_RATINGLBL)
- bool showTrail = input.bool(true, "Trend Trail", group = GRP_OVR, tooltip = TT_TRAIL)
- bool showWave = input.bool(false, "Retracement Wave", group = GRP_OVR, tooltip = TT_WAVE)
- bool showGauss = input.bool(false, "Gauss Ribbon", group = GRP_OVR, tooltip = TT_GAUSS)
- bool showRatingDash = input.bool(false, "Signal Ratings Dashboard", inline = "rd", group = GRP_DASH)
- string ratingDashPos = input.string("Bottom Right", "", options = ["Top Right", "Middle Right", "Bottom Right", "Top Left", "Middle Left", "Bottom Left", "Top Center", "Bottom Center"], inline = "rd", group = GRP_DASH)
- bool showTrendDash = input.bool(false, "Trend Dashboard", inline = "td", group = GRP_DASH)
- string trendDashPos = input.string("Top Right", "", options = ["Top Right", "Middle Right", "Bottom Right", "Top Left", "Middle Left", "Bottom Left", "Top Center", "Bottom Center"], inline = "td", group = GRP_DASH)
- string tableSizeInput = input.string("Small", "Table Size", options = ["Tiny", "Small", "Normal", "Large"], group = GRP_DASH)
- bool alertTP = input.bool(true, "Take Profit", group = GRP_ALERT)
- bool alertBuy = input.bool(false, "Buy Alert", inline = "bs", group = GRP_ALERT)
- bool alertSell = input.bool(false, "Sell Alert", inline = "bs", group = GRP_ALERT)
- bool alertSL = input.bool(false, "Stop Loss", group = GRP_ALERT)
- bool alertUpgrade = input.bool(false, "Rating Upgrade", inline = "rt", group = GRP_ALERT)
- bool alertDowngrade = input.bool(false, "Rating Downgrade", inline = "rt", group = GRP_ALERT)
- bool webhookOn = input.bool(false, "Webhook Formatting", group = GRP_ALERT, tooltip = TT_WEBHOOK)
- color bullColor = input.color(#089981, "Bullish", inline = "trend", group = GRP_THEME)
- color bearColor = input.color(#f23645, "Bearish", inline = "trend", group = GRP_THEME)
- color vbUpperColor = input.color(#f23645, "Volatility Bands", inline = "vb", group = GRP_THEME)
- color vbLowerColor = input.color(#089981, "", inline = "vb", group = GRP_THEME)
- color tpMarkerColor = input.color(#2962ff, "Take Profit Marker", group = GRP_THEME)
- color tpLineColor = input.color(#089981, "TP Lines", inline = "lv", group = GRP_THEME)
- color slLineColor = input.color(#f23645, "SL Lines", inline = "lv", group = GRP_THEME)
- color labelTextColor = input.color(color.white, "Label Text", group = GRP_THEME)
- string labelSizeInput = input.string("Normal", "Label Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = GRP_THEME)
- type TradeState
- int dir = 0
- float entry = na
- int entryBar = na
- float tp1 = na
- float tp2 = na
- float tp3 = na
- float sl = na
- bool hit1 = false
- bool hit2 = false
- bool hit3 = false
- bool armed1 = false
- bool armed2 = false
- bool armed3 = false
- bool slHit = false
- bool active = false
- int rating = 0
- float maxFav = na
- f_factor(float sens) =>
- 0.5 + (100.0 - sens) / 100.0 * 5.5
- f_rating(float frac) =>
- float f = nz(frac, 0.0)
- math.max(1, math.min(5, 1 + int(math.floor(f * 5.0))))
- f_stars(int rating) =>
- string s = ""
- for i = 1 to 5
- s := s + (i <= rating ? "β " : "β")
- s
- f_signalText(int dir, int rating, bool showStars) =>
- string base = dir == 1 ? "BUY" : "SELL"
- showStars ? base + " " + str.tostring(rating) + "β" : rating >= 4 ? base + "+" : base
- f_fmt(float price, string pattern) =>
- na(price) ? "-" : str.tostring(math.round_to_mintick(price), pattern)
- f_num(float v) =>
- na(v) ? "null" : str.tostring(math.round_to_mintick(v))
- f_size(string s) =>
- switch s
- "Tiny" => size.tiny
- "Small" => size.small
- "Normal" => size.normal
- "Large" => size.large
- "Huge" => size.huge
- => size.normal
- f_position(string p) =>
- switch p
- "Top Right" => position.top_right
- "Middle Right" => position.middle_right
- "Bottom Right" => position.bottom_right
- "Top Left" => position.top_left
- "Middle Left" => position.middle_left
- "Bottom Left" => position.bottom_left
- "Top Center" => position.top_center
- "Bottom Center" => position.bottom_center
- => position.top_right
- f_trail(float factor, simple int atrLen) =>
- float atrValue = ta.atr(atrLen)
- float upBase = hl2 - factor * atrValue
- float dnBase = hl2 + factor * atrValue
- var float up = na
- var float dn = na
- var int dir = 1
- float prevUp = nz(up, upBase)
- float prevDn = nz(dn, dnBase)
- up := close[1] > prevUp ? math.max(upBase, prevUp) : upBase
- dn := close[1] < prevDn ? math.min(dnBase, prevDn) : dnBase
- if dir == -1 and close > prevDn
- dir := 1
- else if dir == 1 and close < prevUp
- dir := -1
- float trailValue = dir == 1 ? up : dn
- [trailValue, dir, up, dn]
- f_logFactor(int prediction, int outcome, float lossMag, float eta) =>
- bool wrong = prediction != 0 and outcome != 0 and prediction != outcome
- wrong ? math.log(1.0 - eta * lossMag) : 0.0
- f_sfxCore(float factor, simple int atrLen, simple int wmWindow, simple int rsiLen, simple int fastLen, simple int slowLen, simple int midLen, simple int stLen) =>
- [trailValue, trailDirection, trailUpper, trailLower] = f_trail(factor, atrLen)
- float atrValue = ta.atr(atrLen)
- float rsiValue = ta.rsi(close, rsiLen)
- [macdLine, macdSignal, macdHist] = ta.macd(close, fastLen, slowLen, 9)
- [stValue, stDirection] = ta.supertrend(3.0, stLen)
- float chBasis = ta.ema(close, midLen)
- var int chDir = 1
- if close > chBasis + atrValue
- chDir := 1
- else if close < chBasis - atrValue
- chDir := -1
- float emaFast = ta.ema(close, fastLen)
- float emaSlow = ta.ema(close, slowLen)
- int p1 = rsiValue >= 50 ? 1 : -1
- int p2 = macdLine >= macdSignal ? 1 : -1
- int p3 = stDirection < 0 ? 1 : -1
- int p4 = chDir
- int p5 = emaFast >= emaSlow ? 1 : -1
- int p6 = chBasis >= nz(chBasis[1], chBasis) ? 1 : -1
- float move = close - nz(close[1], close)
- int outcome = move > 0 ? 1 : move < 0 ? -1 : 0
- float prevAtr = nz(atrValue[1])
- float lossMag = prevAtr > 0 ? math.min(1.0, 0.5 + 0.5 * math.abs(move) / prevAtr) : 0.5
- float eta = 0.4
- float lw1 = nz(math.sum(f_logFactor(nz(p1[1]), outcome, lossMag, eta), wmWindow))
- float lw2 = nz(math.sum(f_logFactor(nz(p2[1]), outcome, lossMag, eta), wmWindow))
- float lw3 = nz(math.sum(f_logFactor(nz(p3[1]), outcome, lossMag, eta), wmWindow))
- float lw4 = nz(math.sum(f_logFactor(nz(p4[1]), outcome, lossMag, eta), wmWindow))
- float lw5 = nz(math.sum(f_logFactor(nz(p5[1]), outcome, lossMag, eta), wmWindow))
- float lw6 = nz(math.sum(f_logFactor(nz(p6[1]), outcome, lossMag, eta), wmWindow))
- float lwMax = math.max(lw1, lw2, lw3, lw4, lw5, lw6)
- float w1 = math.exp(lw1 - lwMax)
- float w2 = math.exp(lw2 - lwMax)
- float w3 = math.exp(lw3 - lwMax)
- float w4 = math.exp(lw4 - lwMax)
- float w5 = math.exp(lw5 - lwMax)
- float w6 = math.exp(lw6 - lwMax)
- float wSum = w1 + w2 + w3 + w4 + w5 + w6
- float bullW = (p1 == 1 ? w1 : 0.0) + (p2 == 1 ? w2 : 0.0) + (p3 == 1 ? w3 : 0.0) + (p4 == 1 ? w4 : 0.0) + (p5 == 1 ? w5 : 0.0) + (p6 == 1 ? w6 : 0.0)
- float bullFraction = wSum > 0 ? bullW / wSum : 0.5
- [trailValue, trailDirection, trailUpper, trailLower, bullFraction, atrValue]
- f_signalEngine(int trailDirection, float bullFraction, float strengthPct, int minStars) =>
- var int pendDir = 0
- var int pendBar = 0
- bool flip = trailDirection != nz(trailDirection[1], trailDirection)
- if flip
- pendDir := trailDirection
- pendBar := bar_index
- float dirFrac = trailDirection == 1 ? bullFraction : 1.0 - bullFraction
- int rating = f_rating(dirFrac)
- bool inWindow = pendDir != 0 and trailDirection == pendDir and bar_index - pendBar <= 3
- bool passes = inWindow and dirFrac * 100.0 >= strengthPct and rating >= minStars
- bool buySig = passes and pendDir == 1
- bool sellSig = passes and pendDir == -1
- if passes or (pendDir != 0 and not inWindow)
- pendDir := 0
- [buySig, sellSig, rating]
- f_sfxSentiment(float factor, simple int atrLen, simple int wmWindow, simple int rsiLen, simple int fastLen, simple int slowLen, simple int midLen, simple int stLen, float strengthPct, int minStars) =>
- [tValue, tDir, tUp, tDn, bFrac, aValue] = f_sfxCore(factor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen)
- [bSig, sSig, sRating] = f_signalEngine(tDir, bFrac, strengthPct, minStars)
- var int state = 0
- if bSig
- state := 1
- else if sSig
- state := -1
- state == 0 ? tDir : state
- f_gaussAlpha(int period, int poles) =>
- float beta = (1.0 - math.cos(2.0 * math.pi / period)) / (math.pow(2.0, 1.0 / poles) - 1.0)
- math.sqrt(beta * beta + 2.0 * beta) - beta
- f_pole(float src, float alpha) =>
- var float state = na
- state := na(state) ? src : na(src) ? state : alpha * src + (1.0 - alpha) * state
- state
- f_gauss(float src, float alpha) =>
- float s1 = f_pole(src, alpha)
- float s2 = f_pole(s1, alpha)
- float s3 = f_pole(s2, alpha)
- f_pole(s3, alpha)
- f_dynDist(float value, string unitType, float entry, float atrValue) =>
- unitType == "% Profit" ? entry * value / 100.0 : value * atrValue
- f_keyLevels(int dir, array<float> resArr, array<float> supArr, float entry, float unit) =>
- array<float> tpPool = supArr
- array<float> slPool = resArr
- if dir == 1
- tpPool := resArr
- slPool := supArr
- array<float> dists = array.new<float>()
- for v1 in tpPool
- float dv1 = (v1 - entry) * dir
- if dv1 > unit * 0.25
- dists.push(dv1)
- dists.sort(order.ascending)
- float d1 = na
- float d2 = na
- float d3 = na
- float lastD = 0.0
- int found = 0
- for dv2 in dists
- if found >= 3
- break
- if dv2 - lastD >= unit * 0.5
- found += 1
- if found == 1
- d1 := dv2
- else if found == 2
- d2 := dv2
- else
- d3 := dv2
- lastD := dv2
- float stepD = unit * 1.5
- d1 := na(d1) ? stepD : d1
- d2 := na(d2) ? d1 + stepD : d2
- d3 := na(d3) ? d2 + stepD : d3
- float sd = na
- for v3 in slPool
- float dv3 = (entry - v3) * dir
- if dv3 > unit * 0.25
- sd := na(sd) ? dv3 : math.min(sd, dv3)
- sd := na(sd) ? unit * 2.0 : sd + unit * 0.1
- [entry + d1 * dir, entry + d2 * dir, entry + d3 * dir, entry - sd * dir]
- f_sanitize(int dir, float entry, float t1, float t2, float t3, float sl, float unit) =>
- float u = math.max(nz(unit, syminfo.mintick), syminfo.mintick)
- float d1 = math.max(nz((t1 - entry) * dir, u), u * 0.25)
- float d2 = math.max(nz((t2 - entry) * dir, d1 + u), d1 + u * 0.25)
- float d3 = math.max(nz((t3 - entry) * dir, d2 + u), d2 + u * 0.25)
- float ds = math.max(nz((entry - sl) * dir, u * 1.5), u * 0.25)
- [math.round_to_mintick(entry + dir * d1), math.round_to_mintick(entry + dir * d2), math.round_to_mintick(entry + dir * d3), math.round_to_mintick(entry - dir * ds)]
- f_tpCheck(int dir, float level, bool wasHit, bool wasArmed, bool repeatOn) =>
- bool fire = false
- bool retest = false
- bool hitState = wasHit
- bool armedState = wasArmed
- if not na(level) and dir != 0
- bool touched = dir == 1 ? high >= level : low <= level
- bool closedBack = dir == 1 ? close < level : close > level
- if not hitState
- if touched
- fire := true
- hitState := true
- armedState := closedBack
- else
- if armedState and touched and repeatOn
- retest := true
- armedState := closedBack or (armedState and not touched)
- [fire, retest, hitState, armedState]
- f_recordMfe(TradeState t, array<float> hist, int memory) =>
- if t.dir != 0 and not na(t.entry) and t.entry > 0 and not na(t.maxFav)
- hist.push(math.max((t.maxFav - t.entry) * t.dir / t.entry * 100.0, 0.0))
- if hist.size() > memory
- hist.shift()
- true
- f_tickerJson() =>
- string j = '{"symbol":"' + syminfo.ticker + '","exchange":"' + syminfo.prefix + '","type":"' + syminfo.type + '","currency":"' + syminfo.currency + '"'
- if syminfo.type == "futures"
- j := j + ',"root":"' + syminfo.root + '","pointvalue":' + str.tostring(syminfo.pointvalue) + ',"mintick":' + str.tostring(syminfo.mintick)
- j + '}'
- f_webhookJson(string action, string evt, int dir, float price, int rating, float t1, float t2, float t3, float sl, string extra) =>
- string j = '{"action":"' + action + '","event":"' + evt + '","direction":"' + (dir == 1 ? 'bullish' : 'bearish') + '"'
- j := j + ',"ticker":"' + syminfo.ticker + '","ticker_id":' + f_tickerJson()
- j := j + ',"interval":"' + timeframe.period + '","time":' + str.tostring(time, '#')
- j := j + ',"price":' + f_num(price) + ',"chart_close":' + f_num(close) + ',"rating":' + str.tostring(rating)
- j := j + ',"tp1":' + f_num(t1) + ',"tp2":' + f_num(t2) + ',"tp3":' + f_num(t3) + ',"sl":' + f_num(sl)
- j + extra + '}'
- f_plainMsg(string evt, float price, string details, string pattern) =>
- "Flux Chartsβ’ - SFX Algo | " + evt + " | " + syminfo.ticker + " (" + timeframe.period + ") | Price: " + f_fmt(price, pattern) + details
- f_levelDetails(int rating, float t1, float t2, float t3, float sl, string pattern) =>
- " | Rating: " + str.tostring(rating) + "β | TP1: " + f_fmt(t1, pattern) + " | TP2: " + f_fmt(t2, pattern) + " | TP3: " + f_fmt(t3, pattern) + " | SL: " + f_fmt(sl, pattern)
- f_tpAlert(int lvl, int dir, float lvlPrice, bool isRetest, bool asJson, float price, int rating, float t1, float t2, float t3, float sl, string pattern) =>
- string evt = "Take Profit " + str.tostring(lvl) + (isRetest ? " Retest" : "")
- string side = dir == 1 ? " (Bullish)" : " (Bearish)"
- string ext = ',"tp_level":' + str.tostring(lvl) + ',"tp_price":' + f_num(lvlPrice) + ',"retest":' + (isRetest ? 'true' : 'false')
- asJson ? f_webhookJson("take_profit", evt, dir, price, rating, t1, t2, t3, sl, ext) : f_plainMsg(evt + side, price, " | Level: " + f_fmt(lvlPrice, pattern), pattern)
- f_rtText(int kind, float price, bool done, string pattern) =>
- (kind == 0 ? "SL " : "TP ") + f_fmt(price, pattern) + (done ? (kind == 0 ? " β" : " β ") : "")
- var string pricePattern = "#,##0"
- if barstate.isfirst
- int dec = 0
- float mt = syminfo.mintick
- while dec < 8 and math.abs(mt * math.pow(10, dec) - math.round(mt * math.pow(10, dec))) > 0.0000001
- dec += 1
- pricePattern := dec > 0 ? "#,##0." + str.repeat("0", dec) : "#,##0"
- float styleMult = tradingStyle == "Scalper" ? 0.7 : tradingStyle == "Swing Trader" ? 1.5 : 1.0
- int baseWindow = timeWeighting == "Recent Trends" ? 30 : timeWeighting == "Mixed Trends" ? 75 : 150
- int atrLen = math.max(2, math.round(10 * styleMult))
- int rsiLen = math.max(2, math.round(14 * styleMult))
- int fastLen = math.max(2, math.round(12 * styleMult))
- int slowLen = math.max(fastLen + 1, math.round(26 * styleMult))
- int midLen = math.max(5, math.round(50 * styleMult))
- int stLen = math.max(2, math.round(10 * styleMult))
- int wmWindow = math.max(5, math.round(baseWindow * styleMult))
- int vbLen = math.max(20, math.round(100 * styleMult))
- int vbSmooth = math.max(2, math.round(vbLen * 0.3))
- int gaussLen = math.max(10, math.round(60 * styleMult))
- int pivLen = math.max(3, math.round(5 * styleMult))
- float riskMult = riskTolerance == "Low" ? 0.75 : riskTolerance == "High" ? 1.5 : 1.0
- float atrMain = ta.atr(atrLen)
- var array<float> aiUp = array.new<float>(AI_CANDIDATES, na)
- var array<float> aiDn = array.new<float>(AI_CANDIDATES, na)
- var array<int> aiDir = array.new<int>(AI_CANDIDATES, 1)
- var array<float> aiScore = array.new<float>(AI_CANDIDATES, 0.0)
- var float aiBestSens = float(sensitivityInput)
- float aiDecay = 1.0 - 1.0 / math.max(50.0, wmWindow * 4.0)
- if aiOptimizer and barstate.isconfirmed and not na(atrMain) and bar_index > 0
- float barRet = close[1] != 0 ? close / close[1] - 1.0 : 0.0
- float flipCost = close != 0 ? 0.25 * atrMain / close : 0.0
- int bestIdx = -1
- float bestVal = na
- for i = 0 to AI_CANDIDATES - 1
- float cFactor = f_factor(10.0 * (i + 1))
- float upBase = hl2 - cFactor * atrMain
- float dnBase = hl2 + cFactor * atrMain
- float pUp = nz(aiUp.get(i), upBase)
- float pDn = nz(aiDn.get(i), dnBase)
- int pDir = aiDir.get(i)
- float nUp = close[1] > pUp ? math.max(upBase, pUp) : upBase
- float nDn = close[1] < pDn ? math.min(dnBase, pDn) : dnBase
- int nDir = pDir == -1 and close > pDn ? 1 : pDir == 1 and close < pUp ? -1 : pDir
- float nScore = aiScore.get(i) * aiDecay + pDir * barRet - (nDir != pDir ? flipCost : 0.0)
- aiUp.set(i, nUp)
- aiDn.set(i, nDn)
- aiDir.set(i, nDir)
- aiScore.set(i, nScore)
- if na(bestVal) or nScore > bestVal
- bestVal := nScore
- bestIdx := i
- if bar_index >= AI_WARMUP and bestIdx >= 0
- aiBestSens := 10.0 * (bestIdx + 1)
- float effSensitivity = aiOptimizer and bar_index >= AI_WARMUP ? aiBestSens : float(sensitivityInput)
- float effFactor = f_factor(effSensitivity)
- [trailLine, trailDir, trailUp, trailDn, bullFrac, atrVal] = f_sfxCore(effFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen)
- [subLine, subDir, subUp, subDn] = f_trail(effFactor * 0.5, atrLen)
- [buySignal, sellSignal, signalRating] = f_signalEngine(trailDir, bullFrac, signalStrength, minStarRating)
- float smBullFrac = ta.ema(bullFrac, 5)
- float vbBasis = ta.ema(ta.ema(hlc3, vbLen), vbSmooth)
- float vbDev = ta.ema(ta.stdev(hlc3, vbLen), vbSmooth)
- float vbUpIn = vbBasis + vbDev * 1.5
- float vbUpMid = vbBasis + vbDev * 2.25
- float vbUpOut = vbBasis + vbDev * 3.0
- float vbLoIn = vbBasis - vbDev * 1.5
- float vbLoMid = vbBasis - vbDev * 2.25
- float vbLoOut = vbBasis - vbDev * 3.0
- float gaussAlpha = f_gaussAlpha(gaussLen, 4)
- float gaussMid = f_gauss(close, gaussAlpha)
- float gaussRange = f_gauss(ta.tr(true), gaussAlpha)
- float gaussUp = gaussMid + gaussRange * 1.5
- float gaussLo = gaussMid - gaussRange * 1.5
- bool gaussBull = gaussMid >= nz(gaussMid[1], gaussMid)
- float pivHigh = ta.pivothigh(high, pivLen, pivLen)
- float pivLow = ta.pivotlow(low, pivLen, pivLen)
- var array<float> resLevels = array.new<float>()
- var array<float> supLevels = array.new<float>()
- if not na(pivHigh)
- resLevels.unshift(pivHigh)
- if resLevels.size() > PIVOT_MEMORY
- resLevels.pop()
- if not na(pivLow)
- supLevels.unshift(pivLow)
- if supLevels.size() > PIVOT_MEMORY
- supLevels.pop()
- float swingLowRef = ta.lowest(low, pivLen * 2)
- float swingHighRef = ta.highest(high, pivLen * 2)
- float mtfFactor = f_factor(sensitivityInput)
- int mtf3S = request.security(syminfo.tickerid, "3", f_sfxSentiment(mtfFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen, signalStrength, minStarRating))
- int mtf15S = request.security(syminfo.tickerid, "15", f_sfxSentiment(mtfFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen, signalStrength, minStarRating))
- int mtf30S = request.security(syminfo.tickerid, "30", f_sfxSentiment(mtfFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen, signalStrength, minStarRating))
- int mtf60S = request.security(syminfo.tickerid, "60", f_sfxSentiment(mtfFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen, signalStrength, minStarRating))
- int mtf240S = request.security(syminfo.tickerid, "240", f_sfxSentiment(mtfFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen, signalStrength, minStarRating))
- int mtfDS = request.security(syminfo.tickerid, "D", f_sfxSentiment(mtfFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen, signalStrength, minStarRating))
- int mtfWS = request.security(syminfo.tickerid, "W", f_sfxSentiment(mtfFactor, atrLen, wmWindow, rsiLen, fastLen, slowLen, midLen, stLen, signalStrength, minStarRating))
- float realClose = request.security(ticker.standard(syminfo.tickerid), timeframe.period, close)
- var array<float> mfeHistory = array.new<float>()
- float avgMfe = mfeHistory.size() > 0 ? mfeHistory.avg() : na
- var TradeState trade = TradeState.new()
- bool newSignal = buySignal or sellSignal
- int checkDir = trade.dir
- float chkT1 = trade.tp1
- float chkT2 = trade.tp2
- float chkT3 = trade.tp3
- float chkSL = trade.sl
- int chkRate = trade.rating
- bool tp1Fire = false
- bool tp2Fire = false
- bool tp3Fire = false
- bool tp1Retest = false
- bool tp2Retest = false
- bool tp3Retest = false
- bool slFire = false
- if trade.active and bar_index > trade.entryBar
- trade.maxFav := trade.dir == 1 ? math.max(nz(trade.maxFav, high), high) : math.min(nz(trade.maxFav, low), low)
- [f1, r1, h1, a1] = f_tpCheck(trade.dir, trade.tp1, trade.hit1, trade.armed1, repeatTP)
- [f2, r2, h2, a2] = f_tpCheck(trade.dir, trade.tp2, trade.hit2, trade.armed2, repeatTP)
- [f3, r3, h3, a3] = f_tpCheck(trade.dir, trade.tp3, trade.hit3, trade.armed3, repeatTP)
- trade.hit1 := h1
- trade.hit2 := h2
- trade.hit3 := h3
- trade.armed1 := a1
- trade.armed2 := a2
- trade.armed3 := a3
- tp1Fire := f1 and tp1On
- tp2Fire := f2 and tp2On
- tp3Fire := f3 and tp3On
- tp1Retest := r1 and tp1On
- tp2Retest := r2 and tp2On
- tp3Retest := r3 and tp3On
- if not na(trade.sl)
- bool slTouched = trade.dir == 1 ? low <= trade.sl : high >= trade.sl
- if slTouched
- slFire := true
- trade.slHit := true
- trade.active := false
- f_recordMfe(trade, mfeHistory, MFE_MEMORY)
- bool tp1Event = tp1Fire or tp1Retest
- bool tp2Event = tp2Fire or tp2Retest
- bool tp3Event = tp3Fire or tp3Retest
- bool anyTPEvent = tp1Event or tp2Event or tp3Event
- bool longTPEvent = anyTPEvent and checkDir == 1
- bool shortTPEvent = anyTPEvent and checkDir == -1
- if newSignal
- if trade.active
- f_recordMfe(trade, mfeHistory, MFE_MEMORY)
- int d = buySignal ? 1 : -1
- float entry = close
- float unit = nz(atrVal, close * 0.01)
- float rT1 = na
- float rT2 = na
- float rT3 = na
- float rSL = na
- if tpSlMethod == "Dynamic"
- bool useOpt = tpOptimize and mfeHistory.size() >= 3 and not na(avgMfe)
- float optPct = useOpt ? avgMfe : 0.0
- rT1 := entry + d * (useOpt ? entry * optPct * 0.4 / 100.0 : f_dynDist(tp1Val, tp1Unit, entry, unit))
- rT2 := entry + d * (useOpt ? entry * optPct * 0.8 / 100.0 : f_dynDist(tp2Val, tp2Unit, entry, unit))
- rT3 := entry + d * (useOpt ? entry * optPct * 1.2 / 100.0 : f_dynDist(tp3Val, tp3Unit, entry, unit))
- float subRef = d == 1 ? subUp : subDn
- float subDist = na(subRef) ? unit * 1.5 : math.max((entry - subRef) * d, unit * 0.25)
- rSL := entry - d * subDist * riskMult
- else if tpSlMethod == "Key Levels"
- [k1, k2, k3, kS] = f_keyLevels(d, resLevels, supLevels, entry, unit)
- rT1 := k1
- rT2 := k2
- rT3 := k3
- rSL := kS
- else if tpSlMethod == "Volatility Bands"
- rT1 := d == 1 ? vbUpIn : vbLoIn
- rT2 := d == 1 ? vbUpMid : vbLoMid
- rT3 := d == 1 ? vbUpOut : vbLoOut
- rSL := d == 1 ? vbLoOut : vbUpOut
- else
- float rUnit = unit * (0.6 + 0.3 * signalRating)
- rT1 := entry + d * rUnit
- rT2 := entry + d * rUnit * 2.0
- rT3 := entry + d * rUnit * 3.0
- rSL := entry - d * unit * (2.5 - 0.25 * signalRating)
- [c1, c2, c3, cS] = f_sanitize(d, entry, rT1, rT2, rT3, rSL, unit)
- trade.dir := d
- trade.entry := entry
- trade.entryBar := bar_index
- trade.tp1 := c1
- trade.tp2 := c2
- trade.tp3 := c3
- trade.sl := autoSL ? cS : na
- trade.hit1 := false
- trade.hit2 := false
- trade.hit3 := false
- trade.armed1 := false
- trade.armed2 := false
- trade.armed3 := false
- trade.slHit := false
- trade.active := true
- trade.maxFav := entry
- int prevRating = trade.rating
- int ratingDelta = 0
- if newSignal
- trade.rating := signalRating
- else if trade.dir != 0 and barstate.isconfirmed
- float liveFrac = trade.dir == 1 ? nz(smBullFrac, 0.5) : 1.0 - nz(smBullFrac, 0.5)
- int upCand = f_rating(liveFrac - 0.03)
- int dnCand = f_rating(liveFrac + 0.03)
- if upCand > trade.rating
- ratingDelta := upCand - trade.rating
- trade.rating := upCand
- else if dnCand < trade.rating
- ratingDelta := dnCand - trade.rating
- trade.rating := dnCand
- bool ratingUpgrade = ratingDelta > 0
- bool ratingDowngrade = ratingDelta < 0
- var float waveStart = na
- var float waveExt = na
- if newSignal
- waveStart := trade.dir == 1 ? math.min(nz(swingLowRef, low), low) : math.max(nz(swingHighRef, high), high)
- waveExt := trade.dir == 1 ? high : low
- else if trade.dir == 1
- waveExt := math.max(waveExt, high)
- waveStart := math.min(waveStart, low)
- else if trade.dir == -1
- waveExt := math.min(waveExt, low)
- waveStart := math.max(waveStart, high)
- float waveRange = math.abs(waveExt - waveStart)
- float wave382 = trade.dir == 1 ? waveExt - waveRange * 0.382 : waveExt + waveRange * 0.382
- float wave618 = trade.dir == 1 ? waveExt - waveRange * 0.618 : waveExt + waveRange * 0.618
- bool waveVisible = showWave and trade.dir != 0 and not newSignal
- string labelSize = f_size(labelSizeInput)
- pVbUpIn = plot(showVB ? vbUpIn : na, "Upper Band Inner", color.new(vbUpperColor, 80), 1, editable = false)
- pVbUpMid = plot(showVB ? vbUpMid : na, "Upper Band Middle", color.new(vbUpperColor, 85), 1, editable = false)
- pVbUpOut = plot(showVB ? vbUpOut : na, "Upper Band Outer", color.new(vbUpperColor, 80), 1, editable = false)
- pVbLoIn = plot(showVB ? vbLoIn : na, "Lower Band Inner", color.new(vbLowerColor, 80), 1, editable = false)
- pVbLoMid = plot(showVB ? vbLoMid : na, "Lower Band Middle", color.new(vbLowerColor, 85), 1, editable = false)
- pVbLoOut = plot(showVB ? vbLoOut : na, "Lower Band Outer", color.new(vbLowerColor, 80), 1, editable = false)
- fill(pVbUpIn, pVbUpMid, color.new(vbUpperColor, 86), "Upper Volatility Zone")
- fill(pVbUpMid, pVbUpOut, color.new(vbUpperColor, 92), "Upper Volatility Outer Zone")
- fill(pVbLoIn, pVbLoMid, color.new(vbLowerColor, 86), "Lower Volatility Zone")
- fill(pVbLoMid, pVbLoOut, color.new(vbLowerColor, 92), "Lower Volatility Outer Zone")
- pBodyMid = plot(barstate.isfirst ? na : (open + close) / 2, "Body Middle", display = display.none, editable = false)
- pTrailUp = plot(showTrail and trailDir == 1 ? trailLine : na, "Bullish Trail", bullColor, 2, plot.style_linebr)
- pTrailDn = plot(showTrail and trailDir == -1 ? trailLine : na, "Bearish Trail", bearColor, 2, plot.style_linebr)
- fill(pBodyMid, pTrailUp, color.new(bullColor, 78), "Bullish Trail Fill")
- fill(pBodyMid, pTrailDn, color.new(bearColor, 78), "Bearish Trail Fill")
- color gaussCol = gaussBull ? bullColor : bearColor
- pGaussUp = plot(showGauss ? gaussUp : na, "Gauss Upper", color.new(gaussCol, 50), 1)
- pGaussMid = plot(showGauss ? gaussMid : na, "Gauss Ribbon", gaussCol, 2)
- pGaussLo = plot(showGauss ? gaussLo : na, "Gauss Lower", color.new(gaussCol, 50), 1)
- fill(pGaussUp, pGaussLo, color.new(gaussCol, 88), "Gauss Ribbon Fill")
- color waveCol = trade.dir == 1 ? bullColor : bearColor
- pWave382 = plot(waveVisible ? wave382 : na, "Retracement Wave 0.382", color.new(waveCol, 30), 1, plot.style_linebr)
- pWave618 = plot(waveVisible ? wave618 : na, "Retracement Wave 0.618", color.new(waveCol, 30), 1, plot.style_linebr)
- fill(pWave382, pWave618, color.new(waveCol, 85), "Retracement Wave Fill")
- color candleCol = trailDir == 1 ? bullColor : bearColor
- color candleWick = trendColorMode == "Bar Color + Wicks" ? candleCol : na
- plotcandle(showTrendColor ? open : na, showTrendColor ? high : na, showTrendColor ? low : na, showTrendColor ? close : na, title = "Trend Coloring", color = candleCol, wickcolor = candleWick, bordercolor = candleCol)
- plotshape(showTPLabel and longTPEvent, "Long Take Profit", shape.xcross, location.abovebar, tpMarkerColor, text = "TP", textcolor = labelTextColor, size = size.small)
- plotshape(showTPLabel and shortTPEvent, "Short Take Profit", shape.xcross, location.belowbar, tpMarkerColor, text = "TP", textcolor = labelTextColor, size = size.small)
- plotshape(autoSL and slFire and checkDir == 1, "Long Stop Loss", shape.xcross, location.belowbar, slLineColor, text = "SL", textcolor = labelTextColor, size = size.small)
- plotshape(autoSL and slFire and checkDir == -1, "Short Stop Loss", shape.xcross, location.abovebar, slLineColor, text = "SL", textcolor = labelTextColor, size = size.small)
- if buySignal
- label.new(bar_index, low, f_signalText(1, trade.rating, showStrength), yloc = yloc.belowbar, style = label.style_label_up, color = bullColor, textcolor = labelTextColor, size = labelSize, tooltip = "SFX Bullish Signal\nRating: " + f_stars(trade.rating) + f_levelDetails(trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, pricePattern))
- if sellSignal
- label.new(bar_index, high, f_signalText(-1, trade.rating, showStrength), yloc = yloc.abovebar, style = label.style_label_down, color = bearColor, textcolor = labelTextColor, size = labelSize, tooltip = "SFX Bearish Signal\nRating: " + f_stars(trade.rating) + f_levelDetails(trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, pricePattern))
- if showRatingLabels and ratingDelta != 0 and not newSignal
- string rTxt = (ratingDelta > 0 ? "β² " : "βΌ ") + str.tostring(trade.rating) + "β"
- label.new(bar_index, trade.dir == 1 ? low : high, rTxt, yloc = trade.dir == 1 ? yloc.belowbar : yloc.abovebar, style = trade.dir == 1 ? label.style_label_up : label.style_label_down, color = color.new(trade.dir == 1 ? bullColor : bearColor, 45), textcolor = labelTextColor, size = size.tiny)
- var array<line> rtLines = array.new<line>()
- var array<label> rtLabels = array.new<label>()
- var array<int> rtKinds = array.new<int>()
- bool rtEnabled = realtimeLines and tpSlMethod == "Key Levels"
- if newSignal
- for ln in rtLines
- line.delete(ln)
- for lb in rtLabels
- label.delete(lb)
- rtLines.clear()
- rtLabels.clear()
- rtKinds.clear()
- if rtEnabled
- for k = 0 to 3
- bool enabled = k == 0 ? (autoSL and not na(trade.sl)) : k == 1 ? tp1On : k == 2 ? tp2On : tp3On
- if enabled
- float lvl = k == 0 ? trade.sl : k == 1 ? trade.tp1 : k == 2 ? trade.tp2 : trade.tp3
- color lc = k == 0 ? slLineColor : tpLineColor
- rtLines.push(line.new(bar_index, lvl, bar_index + RT_EXTEND, lvl, color = lc, style = line.style_dashed, width = 1))
- rtLabels.push(label.new(bar_index + RT_EXTEND, lvl, f_rtText(k, lvl, false, pricePattern), style = label.style_label_left, color = color.new(color.black, 100), textcolor = lc, size = labelSize))
- rtKinds.push(k)
- if barstate.islast and rtLines.size() > 0
- for i = 0 to rtLines.size() - 1
- int k = rtKinds.get(i)
- float lvl = k == 0 ? trade.sl : k == 1 ? trade.tp1 : k == 2 ? trade.tp2 : trade.tp3
- bool done = k == 0 ? trade.slHit : k == 1 ? trade.hit1 : k == 2 ? trade.hit2 : trade.hit3
- line.set_x2(rtLines.get(i), bar_index + RT_EXTEND)
- label.set_x(rtLabels.get(i), bar_index + RT_EXTEND)
- label.set_text(rtLabels.get(i), f_rtText(k, lvl, done, pricePattern))
- plot(trade.dir != 0 ? trade.rating : na, "Signal Rating", display = display.data_window)
- plot(ratingDelta, "Rating Change", display = display.data_window)
- plot(buySignal ? 1 : 0, "Bullish Signal", display = display.data_window)
- plot(sellSignal ? 1 : 0, "Bearish Signal", display = display.data_window)
- plot(effSensitivity, "Active Sensitivity", display = display.data_window)
- string tblSize = f_size(tableSizeInput)
- color tblBg = color.new(#131722, 5)
- color tblCell = color.new(#1e222d, 0)
- color tblHead = color.new(#2a2e39, 0)
- color tblLine = color.new(#363a45, 0)
- var table ratingTable = na
- var table trendTable = na
- if showRatingDash and na(ratingTable)
- ratingTable := table.new(f_position(ratingDashPos), 2, 4, bgcolor = tblBg, frame_color = tblLine, frame_width = 1, border_color = tblLine, border_width = 1)
- if showTrendDash and na(trendTable)
- trendTable := table.new(f_position(trendDashPos), 2, 8, bgcolor = tblBg, frame_color = tblLine, frame_width = 1, border_color = tblLine, border_width = 1)
- if barstate.islast
- if not na(ratingTable)
- color dirCol = trade.dir == 1 ? bullColor : trade.dir == -1 ? bearColor : color.gray
- table.cell(ratingTable, 0, 0, "SFX Algo", text_color = labelTextColor, text_size = tblSize, bgcolor = dirCol)
- table.cell(ratingTable, 1, 0, "Signal Rating", text_color = labelTextColor, text_size = tblSize, bgcolor = dirCol)
- table.cell(ratingTable, 0, 1, "Signal", text_color = labelTextColor, text_size = tblSize, bgcolor = tblCell, text_halign = text.align_left)
- table.cell(ratingTable, 1, 1, trade.dir == 1 ? "Bullish" : trade.dir == -1 ? "Bearish" : "Neutral", text_color = labelTextColor, text_size = tblSize, bgcolor = color.new(dirCol, 35))
- table.cell(ratingTable, 0, 2, "Rating", text_color = labelTextColor, text_size = tblSize, bgcolor = tblCell, text_halign = text.align_left)
- table.cell(ratingTable, 1, 2, trade.dir != 0 ? f_stars(trade.rating) : "-", text_color = labelTextColor, text_size = tblSize, bgcolor = color.new(dirCol, 35))
- table.cell(ratingTable, 0, 3, "Sensitivity", text_color = labelTextColor, text_size = tblSize, bgcolor = tblCell, text_halign = text.align_left)
- table.cell(ratingTable, 1, 3, str.tostring(effSensitivity, "#") + (aiOptimizer ? " (AI)" : ""), text_color = labelTextColor, text_size = tblSize, bgcolor = color.new(dirCol, 35))
- if not na(trendTable)
- table.cell(trendTable, 0, 0, "Timeframe", text_color = labelTextColor, text_size = tblSize, bgcolor = tblHead)
- table.cell(trendTable, 1, 0, "SFX Sentiment", text_color = labelTextColor, text_size = tblSize, bgcolor = tblHead)
- array<string> tfNames = array.from("3 Minute", "15 Minute", "30 Minute", "1 Hour", "4 Hour", "1 Day", "1 Week")
- array<int> tfStates = array.from(mtf3S, mtf15S, mtf30S, mtf60S, mtf240S, mtfDS, mtfWS)
- for i = 0 to 6
- int st = tfStates.get(i)
- color stCol = st == 1 ? bullColor : st == -1 ? bearColor : color.gray
- table.cell(trendTable, 0, i + 1, tfNames.get(i), text_color = labelTextColor, text_size = tblSize, bgcolor = tblCell, text_halign = text.align_left)
- table.cell(trendTable, 1, i + 1, st == 1 ? "Bullish" : st == -1 ? "Bearish" : "Neutral", text_color = labelTextColor, text_size = tblSize, bgcolor = color.new(stCol, 25))
- float alertPrice = nz(realClose, close)
- if buySignal and alertBuy
- alert(webhookOn ? f_webhookJson("buy", "Bullish Signal", 1, alertPrice, trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, "") : f_plainMsg("Bullish Signal", alertPrice, f_levelDetails(trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, pricePattern), pricePattern), alert.freq_once_per_bar_close)
- if sellSignal and alertSell
- alert(webhookOn ? f_webhookJson("sell", "Bearish Signal", -1, alertPrice, trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, "") : f_plainMsg("Bearish Signal", alertPrice, f_levelDetails(trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, pricePattern), pricePattern), alert.freq_once_per_bar_close)
- if alertTP and tp1Event
- alert(f_tpAlert(1, checkDir, chkT1, tp1Retest and not tp1Fire, webhookOn, alertPrice, chkRate, chkT1, chkT2, chkT3, chkSL, pricePattern), alert.freq_once_per_bar_close)
- if alertTP and tp2Event
- alert(f_tpAlert(2, checkDir, chkT2, tp2Retest and not tp2Fire, webhookOn, alertPrice, chkRate, chkT1, chkT2, chkT3, chkSL, pricePattern), alert.freq_once_per_bar_close)
- if alertTP and tp3Event
- alert(f_tpAlert(3, checkDir, chkT3, tp3Retest and not tp3Fire, webhookOn, alertPrice, chkRate, chkT1, chkT2, chkT3, chkSL, pricePattern), alert.freq_once_per_bar_close)
- if alertSL and slFire
- string slEvt = "Stop Loss" + (checkDir == 1 ? " (Bullish)" : " (Bearish)")
- alert(webhookOn ? f_webhookJson("stop_loss", "Stop Loss", checkDir, alertPrice, chkRate, chkT1, chkT2, chkT3, chkSL, ',"sl_price":' + f_num(chkSL)) : f_plainMsg(slEvt, alertPrice, " | Level: " + f_fmt(chkSL, pricePattern), pricePattern), alert.freq_once_per_bar_close)
- if ratingUpgrade and alertUpgrade
- string upEvt = "Rating Upgrade (" + (trade.dir == 1 ? "Bullish" : "Bearish") + ")"
- alert(webhookOn ? f_webhookJson("rating_upgrade", upEvt, trade.dir, alertPrice, trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, ',"previous_rating":' + str.tostring(prevRating)) : f_plainMsg(upEvt, alertPrice, " | " + str.tostring(prevRating) + "β β " + str.tostring(trade.rating) + "β", pricePattern), alert.freq_once_per_bar_close)
- if ratingDowngrade and alertDowngrade
- string dnEvt = "Rating Downgrade (" + (trade.dir == 1 ? "Bullish" : "Bearish") + ")"
- alert(webhookOn ? f_webhookJson("rating_downgrade", dnEvt, trade.dir, alertPrice, trade.rating, trade.tp1, trade.tp2, trade.tp3, trade.sl, ',"previous_rating":' + str.tostring(prevRating)) : f_plainMsg(dnEvt, alertPrice, " | " + str.tostring(prevRating) + "β β " + str.tostring(trade.rating) + "β", pricePattern), alert.freq_once_per_bar_close)
Advertisement
Add Comment
Please, Sign In to add comment