Pattern Atlas : Geometric [AxeAlgo]Pattern Atlas : Geometric Patterns
WHAT THIS LIBRARY IS
This is a Pine Script v6 library of 17 classical chart pattern detectors — Head and Shoulders, Double/Triple Tops and Bottoms, triangles, wedges, flags, and the rest of the standard technical-analysis catalog built from swing highs and lows rather than single-candle shape. Unlike candlestick patterns, which read one to a handful of fixed bars, chart patterns span a variable, often large number of bars, so this library carries one small piece of state — a rolling history of confirmed swing pivots — that every pattern function reads from. Beyond that, the same philosophy as Library #1 applies: no plotting, no alerts, and no inputs in this script by design, since a library's job is to hand other scripts a clean, reusable, well-documented API, not to draw on a chart itself (Pine doesn't allow a library to plot anything anyway). If you're looking for a ready-to-use indicator built on top of this library, see the companion "Pattern Atlas : Geometric Indicator " script, which imports every function here and turns it into on-chart signals, measured-move price targets, a live scanner table, and alerts.
Chart pattern analysis is one of the foundational tools of classical technical analysis, going back to Edwards and Magee's original work and refined since by researchers like Thomas Bulkowski, whose statistical studies of pattern behavior are the closest thing this field has to an industry-standard reference. The patterns in this library follow that standard catalog, so anyone who already knows what a Head and Shoulders top or an Ascending Triangle looks like will recognize exactly what each function is checking for.
WHY A LIBRARY INSTEAD OF ONE MONOLITHIC INDICATOR
Splitting detection logic out as an importable library means:
- Any Pine coder building their own strategy, indicator, or screener can pull in exactly the pattern checks they need without copy-pasting swing-pivot and trendline math into every new script.
- The detection logic is tested and maintained in one place. When a threshold gets refined, everything importing this library benefits from the update by bumping one version number.
- It keeps the math separate from presentation — how a pattern gets drawn, colored, or alerted on is a completely separate decision from whether the pattern is actually present, and different users want different presentations.
HOW TO IMPORT AND USE IT
Add this line near the top of your script (adjust the version number to whatever the current published version is):
import AxeAlgo/Pattern_Atlas_Geometric/1 as geo
Unlike Library #1, most of the functions here need a shared pivot history to work from. Call trackPivots() exactly once per bar, then pass its result into every detect*() function that needs it:
pivots = geo.trackPivots()
match = geo.detectDoubleTopBottom(pivots)
if match.found
label.new(bar_index, high, match.patternName)
Four functions — detectSpike(), detectFlag(), detectPennant(), and detectIslandReversal() — read directly off recent price action instead of the shared pivot history, so they're called without a pivots argument: geo.detectSpike().
trackPivots() takes three optional parameters: leftBars and rightBars (how many less-extreme bars must surround a candidate swing point before it confirms as a pivot — higher values mean fewer, more significant pivots, at the cost of a longer confirmation lag), and maxPivots (how much pivot history to retain). All three have sensible defaults.
Every detect*() function returns the same structure, called ChartPatternMatch, so the calling pattern is identical no matter which of the 17 you use. It has nine fields:
- found — true if the pattern matched at the evaluated bar, false otherwise.
- patternName — the specific name of what matched (e.g. "Ascending Triangle"), na when not found.
- direction — "bullish" or "bearish".
- pivotBars — bar_index of each pivot the match was built from, in chronological order.
- pivotPrices — price of each pivot, in the same order as pivotBars.
- breakoutLevel — the support, resistance, or neckline level price broke through to confirm the pattern.
- necklineSlope — slope (price per bar) of the breakout line, na when the pattern's breakout level isn't a sloped line.
- barIndex — the bar_index the pattern completes (breaks out) on.
- description — a full sentence naming the pattern and the actual measured price levels that triggered it — genuinely useful for a tooltip or an alert message, not just a repeat of the pattern name.
Two additional exported functions turn that raw match into something more actionable, and both work on any ChartPatternMatch regardless of which detect*() function produced it:
- patternStrength(match) — a 0-100 score for how decisively the confirmation close broke through breakoutLevel, relative to the pattern's own price range. A breakout that clears the level by a meaningful fraction of the pattern's own size scores higher than a one-tick poke through it.
- patternTarget(match) — a classical measured-move price target, projecting the pattern's own height from the breakout point. Returns na for patterns without a reliable height to project from (V-Top/V-Bottom Spike, Island Reversal, Bump-and-Run Reversal).
Every detect*() function also exposes its own set of tunable threshold parameters — how flat a "flat top" has to be, how much two shoulders can differ and still count as equal, and so on — all with sensible defaults so you don't have to touch them unless you want to tighten or loosen a specific pattern's sensitivity for a particular instrument or timeframe.
THE 17 PATTERNS
Reversal patterns (7) — signal a potential change in the prevailing trend:
- Head and Shoulders / Inverse Head and Shoulders — detectHeadAndShoulders(). Three swing extremes with the middle one more extreme than the two roughly-equal outer ones, confirmed when price breaks the neckline connecting the two points between them.
- Double Top / Double Bottom — detectDoubleTopBottom(). Two roughly equal peaks (or troughs) with a retracement between them, confirmed when price breaks back through that retracement level.
- Triple Top / Triple Bottom — detectTripleTopBottom(). The same idea as a Double Top/Bottom with a third roughly-equal touch, confirmed on the break of the support or resistance formed between the touches.
- Rounding Top / Rounding Bottom — detectRoundingTopBottom(). A gradual, curved advance-and-rollover (or decline-and-recovery) between two similar edge levels. Approximate: read from three swing pivots rather than fitting a true curve.
- Diamond Top / Diamond Bottom — detectDiamondTopBottom(). Swing range that widens and then narrows again, confirmed on a break of the resulting support or resistance. Rare and approximate: read from three pivot pairs rather than a clean diamond outline.
- Broadening Formation — detectBroadeningTopBottom(). Diverging highs and lows forming an increasingly volatile range, confirmed on a break of either edge. Approximate: read from two pivot pairs rather than a hand-fitted diverging channel.
- V-Top / V-Bottom (Spike) — detectSpike(). A single sharp extreme with no rounding — a large move into the pivot and an equally large move away from it, both measured against the recent average bar range, within a handful of bars. Self-contained, no pivots argument needed.
Continuation patterns (8) — typically resolve in the direction of the move that preceded them:
- Ascending Triangle — detectTriangleAscending(). Flat resistance with rising support, confirmed on a break above resistance.
- Descending Triangle — detectTriangleDescending(). Flat support with falling resistance, confirmed on a break below support.
- Symmetrical Triangle — detectTriangleSymmetrical(). Converging highs and rising lows, confirmed (bullish or bearish) whichever side the price actually breaks.
- Rising Wedge / Falling Wedge — detectWedge(). Both trendlines slope the same direction and converge; breaks the opposite way from the slope, since the shared-direction move was already losing momentum.
- Bull Flag / Bear Flag — detectFlag(). A strong directional move (the pole), followed by a tight, roughly parallel pullback, confirmed on a break back out in the pole's direction. Self-contained, no pivots argument needed.
- Bull Pennant / Bear Pennant — detectPennant(). The same pole-and-consolidation structure as a Flag, but the consolidation narrows and converges rather than staying parallel. Self-contained, no pivots argument needed.
- Rectangle — detectRectangle(). Price boxed between flat support and flat resistance, confirmed on a break of either edge.
- Cup and Handle / Inverted Cup and Handle — detectCupAndHandle(). A rounded recovery (or decline) back to its starting rim, then a shallow pullback (the handle), confirmed on a break through the rim.
Structural / gap-based patterns (2):
- Bullish / Bearish Island Reversal — detectIslandReversal(). A bar (or small cluster) isolated by a gap on both sides, then abandoned by a gap the other way — an abrupt reversal. Self-contained, pure gap logic, no pivots argument needed.
- Bump-and-Run Reversal — detectBumpAndRun(). A lead-in trendline, then a "bump" phase accelerating well beyond it, then a "run" breaking back through the lead-in line. Approximate: the lead-in line is read from just two pivots rather than a hand-drawn trendline.
WHAT THIS LIBRARY DELIBERATELY DOES NOT DO
No plotting, no drawing, no alertcondition() calls, and no inputs — Pine doesn't allow any of those inside a library in the first place, since a library can never be added to a chart on its own. If you want signals, price targets, a scanner table, or alerts, import this library into your own script (or use the companion "Pattern Atlas : Chart Pattern Scanner " indicator, which does exactly that) rather than expecting this script to render anything by itself.
This library also does not evaluate multi-timeframe data, volume, or broader market structure — it's swing-pivot and trendline geometry only, on purpose, so its behavior is easy to reason about and easy to reuse as one building block among several.
Four of the seventeen patterns are explicitly noted above as approximate: Rounding Top/Bottom, Diamond Top/Bottom, Broadening Formation, and Bump-and-Run Reversal are read from a small, fixed number of swing pivots rather than fitting a true curve or hand-drawn trendline to the data. They will not catch every textbook-perfect example of these shapes, and they may occasionally flag a looser approximation of one. Treat them as a starting point for further chart review, not a final word.
PART OF A LARGER SERIES
This is Library #2 in the AxeAlgo Pattern Atlas — a planned set of Pine libraries splitting pattern detection by the method actually used to find each kind of pattern: candlestick shape (Library #1, already published), classical chart/geometric patterns (this library), harmonic patterns (Fibonacci-ratio XABCD structures), and market-structure concepts (order blocks, liquidity, Wyckoff-style events). Each library is independent and useful on its own; together they're meant to cover technical pattern analysis without forcing unrelated detection methods into the same function.
A NOTE ON REPAINTING
trackPivots() only confirms a swing pivot once rightBars bars have passed since it happened — the same confirmation lag ta.pivothigh()/ta.pivotlow() use, just written out as plain comparisons so it works safely inside a library's exported functions. That means a pivot never moves or disappears once confirmed; it just takes rightBars bars to become known, which is a normal and unavoidable part of swing-pivot detection, not a defect in this library. On the currently-forming bar, a pattern's found status can still change tick to tick as that bar's own high, low, and close move — that's inherent to reading live price action. If you're building persisted signals, drawings, alerts, or price targets on top of these functions (rather than a live "what's happening right now" readout), gate your usage on barstate.isconfirmed so a signal only fires once the bar it describes has actually closed, exactly like the companion scanner indicator does.
DISCLAIMER
This library is a technical analysis tool for identifying classical chart pattern shapes in historical and live price data. It does not predict future price movement, and a detected pattern — including any projected price target — is a description of past price action, not a signal guaranteed to repeat. Nothing in this script constitutes financial advice. Always combine pattern recognition with your own risk management and broader analysis before making any trading decision.
مكتبة

مكتبة

Pattern Atlas : Candlestick [AxeAlgo]Pattern Atlas : Candlestick
WHAT THIS LIBRARY IS
This is a Pine Script v6 library of 23 candlestick pattern detectors — one exported function per pattern family, each doing pure open/high/low/close arithmetic against the current or a specified historical bar. There is no plotting, no alerts, and no inputs in this script by design: a library's job is to hand other scripts a clean, reusable, well-documented API, not to draw on a chart itself (Pine doesn't allow a library to plot anything anyway). If you're looking for a ready-to-use indicator built on top of this library, see the companion "Pattern Atlas : Candlestick Scanner " script, which imports every function here and turns it into on-chart signals, a live scanner table, and alerts.(will be published soon)
Candlestick reading is one of the oldest and most widely taught tools in technical analysis, going back to Steve Nison's work bringing Japanese candlestick charting to Western traders. The patterns in this library follow that standard catalog (cross-checked against TA-Lib's CDL* function list, the closest thing to an industry-standard reference), so anyone who already knows what a Morning Star or a Bullish Engulfing bar looks like will recognize exactly what each function is checking for.
WHY A LIBRARY INSTEAD OF ONE MONOLITHIC INDICATOR
Splitting detection logic out as an importable library means:
- Any Pine coder building their own strategy, indicator, or screener can pull in exactly the pattern checks they need without copy-pasting candlestick math into every new script.
- The detection logic is tested and maintained in one place. When a threshold gets refined, everything importing this library benefits from the update by bumping one version number.
- It keeps the math separate from presentation — how a pattern gets drawn, colored, or alerted on is a completely separate decision from whether the pattern is actually present, and different users want different presentations.
HOW TO IMPORT AND USE IT
Add this line near the top of your script (adjust the version number to whatever the current published version is):
import AxeAlgo/PatternCandlestick/1 as cdl
Then call any function directly. Every function returns the same structure, called CandleMatch, so the calling pattern is identical no matter which of the 23 you use:
match = cdl.detectDoji()
if match.found
label.new(bar_index, low, match.patternName)
CandleMatch has six fields:
- found — true if the pattern matched at the evaluated bar, false otherwise.
- patternName — the specific name of what matched (e.g. "Hanging Man"), na when not found.
- direction — "bullish", "bearish", or "neutral".
- barIndex — the bar_index the pattern completes on.
- barsUsed — how many bars the pattern spans (1, 2, 3, or 5 for the one continuation pattern that needs a 5-bar read).
- description — a full sentence naming the pattern and the actual measured values that triggered it (body size as a percent of range, wick-to-body multiples, or the specific price levels involved, depending on the pattern) — genuinely useful for a tooltip or an alert message, not just a repeat of the pattern name.
Every function also accepts an optional offset parameter (default 0, meaning the current/most recent bar) if you want to check a pattern further back in history, plus its own set of tunable threshold parameters — how strict the "small body" or "long wick" cutoffs are — all exposed with sensible defaults so you don't have to touch them unless you want to tighten or loosen a specific pattern's sensitivity for a particular instrument.
THE 23 PATTERNS
Single-bar patterns (9) — each reads one candle's own open/high/low/close shape:
- Doji — detectDoji(). Body is negligible relative to the bar's range; open and close land almost on top of each other. Neutral.
- Long-Legged Doji — detectLongLeggedDoji(). A doji with long wicks on both sides — both directions were pushed and rejected in the same bar. Neutral.
- Dragonfly Doji — detectDragonflyDoji(). A doji with a long lower wick and almost no upper wick — buyers rejected the lows. Bullish.
- Gravestone Doji — detectGravestoneDoji(). A doji with a long upper wick and almost no lower wick — sellers rejected the highs. Bearish.
- Hammer / Hanging Man — detectHammerHangingMan(). Small body, long lower wick, negligible upper wick — the same shape read two ways depending on the prior trend: a Hammer after a decline (bullish), a Hanging Man after an advance (bearish). The function infers the prior trend automatically from a lookback window, or you can supply your own trend context.
- Inverted Hammer / Shooting Star — detectInvertedHammerShootingStar(). The mirror shape (long upper wick, negligible lower wick), same trend-dependent split: Inverted Hammer after a decline (bullish), Shooting Star after an advance (bearish).
- Marubozu — detectMarubozu(). A full-bodied candle with negligible wicks on either side — one side was in complete control from open to close. Direction follows the body color.
- Spinning Top — detectSpinningTop(). Small body with real wicks on both sides, roughly balanced — pushes both up and down failed. Neutral.
- Belt Hold — detectBeltHold(). Opens at (or almost at) one extreme with almost no wick on the opening side, then closes strongly the other way — one side controlled the entire session from the opening bell.
Two-bar patterns (6) — each compares the current bar against the one before it:
- Engulfing — detectEngulfing(). The current bar's body fully covers the prior bar's opposite-colored body.
- Harami — detectHarami(). The current bar's body sits fully inside the prior bar's opposite-colored body — the inverse of Engulfing, read as the move stalling.
- Harami Cross — detectHaramiCross(). A Harami where the contained bar is also a doji — a stronger version of the stall.
- Piercing Line / Dark Cloud Cover — detectPiercingDarkCloud(). The current bar opens beyond the prior bar's extreme and closes back past its midpoint — Piercing Line is the bullish version after a decline, Dark Cloud Cover the bearish version after an advance.
- Tweezer Top / Bottom — detectTweezer(). Two consecutive bars sharing a near-identical high (Tweezer Top, bearish) or low (Tweezer Bottom, bullish) — the level held on both attempts.
- Kicker — detectKicker(). A gap between two opposite-colored bars with zero overlap between their bodies — an abrupt, no-transition reversal in sentiment.
Three-bar-and-longer patterns (8) — each reads a short sequence of bars together:
- Morning Star / Evening Star — detectStar(). A large bar, a small bar gapped away from it, then a third bar closing back past the midpoint of the first — the classic three-bar reversal, bullish (Morning) at the bottom or bearish (Evening) at the top.
- Morning Doji Star / Evening Doji Star — detectDojiStar(). The same structure as the Star pattern above, but the middle bar is specifically a doji — a stronger version of the signal.
- Three White Soldiers / Three Black Crows — detectThreeSoldiersCrows(). Three consecutive same-direction bars, each opening inside the prior body and closing beyond the prior close — steady, sustained buying or selling.
- Three Inside Up / Down — detectThreeInside(). A Harami followed by a third bar closing beyond the first bar's open, confirming the stall seen in the Harami actually turned into a reversal.
- Three Outside Up / Down — detectThreeOutside(). An Engulfing followed by a third bar extending the same move, confirming the reversal.
- Abandoned Baby — detectAbandonedBaby(). A Doji Star with a genuine price gap (not just a wick gap) on both sides of the middle bar — a rare, high-conviction reversal.
- Rising / Falling Three Methods — detectThreeMethods(). A strong trend bar, three small counter-trend bars fully contained inside its range, then a bar resuming the original direction beyond the first bar's close — the trend paused without reversing. This is the one pattern spanning 5 bars rather than 1-3.
- Stick Sandwich — detectStickSandwich(). Two bearish bars with matching closes sandwiching one bullish bar in between — sellers failed to push the close any lower on the second attempt.
WHAT THIS LIBRARY DELIBERATELY DOES NOT DO
No plotting, no drawing, no alertcondition() calls, and no inputs — Pine doesn't allow any of those inside a library in the first place, since a library can never be added to a chart on its own. If you want signals, a scanner table, or alerts, import this library into your own script (or use the companion "Pattern Atlas : Candlestick Scanner " indicator, which does exactly that) rather than expecting this script to render anything by itself.
This library also does not evaluate multi-timeframe data, volume, or broader market structure — it's candlestick shape and price-only, on purpose, so its behavior is easy to reason about and easy to reuse as one building block among several.
PART OF A LARGER SERIES
This is Library #1 in the AxeAlgo Pattern Atlas — a planned set of Pine libraries splitting pattern detection by the method actually used to find each kind of pattern: candlestick shape (this library), classical chart/geometric patterns (trendline-based structures like triangles, head and shoulders, flags), harmonic patterns (Fibonacci-ratio XABCD structures), and market-structure concepts (order blocks, liquidity, Wyckoff-style events). Each library is independent and useful on its own; together they're meant to cover technical pattern analysis without forcing unrelated detection methods into the same function.
A NOTE ON REPAINTING
Every function here evaluates whatever bar you point it at (the current bar by default, via the offset parameter) using that bar's own open/high/low/close. On the currently-forming bar, those values are still changing tick to tick — that's inherent to reading live price action, not a defect in this library. If you're building persisted signals, drawings, or alerts on top of these functions (rather than a live "what's happening right now" readout), gate your usage on barstate.isconfirmed so a signal only fires once the bar it describes has actually closed, exactly like the companion scanner indicator does.
DISCLAIMER
This library is a technical analysis tool for identifying classical candlestick shapes in historical and live price data. It does not predict future price movement, and a detected pattern is a description of past price action, not a signal guaranteed to repeat. Nothing in this script constitutes financial advice. Always combine pattern recognition with your own risk management and broader analysis before making any trading decision.
مكتبة

XZ_SD_AlertsLibrary "XZ_SD_Alerts"
XZ S&D Alerts v1. Notification-only support library for already-committed XZ Supply & Demand engine events. It owns alert filtering, Horizon admission, message formatting, aggregation and alert() dispatch. It never creates or reinterprets S&D lifecycle events.
route(base_message, event, enabled, source_scope, zone_scope, supply_events, demand_events, zone_confirmed, wick_test, partial_consumption, swing_promoted, zone_consumed, zone_horizon, horizon_timezone, reference_time, ticker)
Appends one already-committed engine event to an aggregated alert message when all notification filters admit it.
Parameters:
base_message (string)
event (AlertEvent)
enabled (bool)
source_scope (string)
zone_scope (string)
supply_events (bool)
demand_events (bool)
zone_confirmed (bool)
wick_test (bool)
partial_consumption (bool)
swing_promoted (bool)
zone_consumed (bool)
zone_horizon (string)
horizon_timezone (string)
reference_time (int)
ticker (string)
dispatch(message)
Dispatches one aggregated message. Empty messages do nothing.
Parameters:
message (string)
AlertEvent
Fields:
event_type (series string)
side (series string)
source_context (series string)
source_timeframe (series string)
confirmation_time (series int)
outer_boundary (series float)
original_inner_boundary (series float)
event_price (series float)
penetration_pct (series float)
event_sequence (series int)
pivot_class (series string)
swing_family (series string)
lifecycle_state (series string)
pathway (series string) مكتبة

ReadableTimeframeAlertsFixes the "what timeframe is this?" problem.
Pine's timeframe.period gives you raw values like "60", "240", "1D", "3M" — accurate, but not something a normal user can read at a glance. If your alert says "Zone formed on 360," most people have no idea that 360 means the 6-hour timeframe.
This library converts that raw string into a proper readable label: "60" becomes "1 Hour", "240" becomes "4 Hours", "1D" becomes "Daily", "3M" becomes "3 Months", and so on — covering minutes, hours, days, weeks, months, seconds, and ticks.
I built this after running into the exact issue in my own — a user kept seeing numbers like 360 in their alerts and couldn't tell what timeframe it referred to. This library is what fixed it, and I'm sharing it so anyone facing the same confusion can drop it into their own script.
Usage:
import AfnanTAjuddin/ReadableTimeframeAlerts/1 as tf
alert("Zone formed on " + tf.f_tf_label(timeframe.period))
One line, and your alert messages, labels, or tables show a timeframe users actually understand instead of a raw number.
Found an edge case it doesn't handle correctly? Drop a comment and I'll take a look. مكتبة

Trade Wzrd - Library Alert String UtilsTrade Wzrd - Library Alert String Utils
WHAT IT IS
Open-source Pine library that builds comma-separated webhook alert strings for automated order commands. Import name: TradeWzrdAlerts.
This is an educational protocol helper for strategy and indicator authors. It is not a signal service and does not place broker orders by itself.
WHY IT EXISTS (ORIGINALITY)
Most automation scripts hand-concatenate alert text. That causes dialect drift, missing parameters, and broken multi-command messages. This library is a single export surface for the full command set used with webhook-style automation:
Market: BUY, SELL
Pending: BUYLIMIT, SELLLIMIT, BUYSTOP, SELLSTOP
Futures-style: BRACKET, REMOVE_SL, REMOVE_TP
Manage: MODIFY, BREAKEVEN
Close: CLOSE, CLOSEALL, LAYER_CLOSE
Cancel: CANCEL
It also provides zero-config PRICE helpers so you can pass exact strategy stop and take-profit prices (no manual pip math), plus a multi() joiner for semicolon-separated command chains.
HOW IT WORKS
1) Each command function returns one string: COMMAND,SYMBOL
2) Optional parameters are omitted when unset (na or empty string). Legitimate zero values such as OFFSET=0 are still emitted when you pass them.
3) COMMENT text is sanitized so commas and semicolons cannot break multi-command grammar.
4) Invalid required fields (empty symbol, pending without PRICE, MODIFY with neither SL nor TP) return an empty string. Callers should not fire alerts on empty strings.
5) Zero-config helpers (buyPrice, sellPrice, bracketPrice, modifySlPrice, breakEvenPrice, closePercent) force TPSLTYPE=PRICE and format prices with mintick precision.
HOW TO USE
1) Publish or open this library, then import it in your script (replace username and version as shown on the library page):
import USERNAME/TradeWzrdAlerts/1 as TW
2) Build a message, for example:
msg = TW.buy("EURUSD", vol=0.01, sl=100, tp=200, tpslType="PIPS")
3) Pass msg into strategy.entry / strategy.exit alert_message, or call alert(msg) when length(msg) > 0
4) Create a TradingView alert with message:
{{strategy.order.alert_message}}
or use Any alert() function call when using alert()
5) Point the alert webhook field at whatever endpoint you already use
DEFAULTS AND RULES
- Symbol is pass-through (not force-uppercased)
- Ticket is an optional string parameter
- TPSLTYPE is only written when you provide it (except zero-config PRICE helpers)
- multi(a,b,...) joins non-empty segments with semicolons
LIMITATIONS
- Library only builds text. Execution quality depends on your webhook receiver and broker
- Pending-order automation support depends on your backend and platform
- Past results and example strings do not predict live performance
- Not intended as financial advice
No external links are required to understand or use this library.
مكتبة

StocksDeveloperAlertsLibrary "StocksDeveloperAlerts"
AutoTrader Web alert builder by Stocks Developer — turn TradingView alerts into real broker orders across many accounts and brokers. Ready-made functions for single orders, options the easy way, 8 option structures (straddle/strangle/spreads/iron condor/iron fly), custom multi-leg, account or group targeting, and your own risk limits. No alert-text typing. stocksdeveloper.in
order(symbol, exchange, producttype, tradetype, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, optiontype, strike, expiry, spothint, usespot, onslicefailure, risk, extra)
Build an alert message for a single order (stock, futures or one option leg). This is the full builder; equity() and option() are shorter wrappers over it. Set exactly one of account/group and exactly one of lots/quantity. Add optiontype to make it an option order.
Parameters:
symbol (string) : (series string) Broker-independent symbol, e.g. "NIFTY", "BANKNIFTY", "SBIN". For options, pass the underlier (e.g. "NIFTY"), not a full contract.
exchange (string) : (series string) Exchange code, e.g. "NSE"/"BSE" for stocks, "NFO" for options and futures.
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
account (string) : (series string) Place in this single account. Set this OR group.
group (string) : (series string) Place in every live account in this group. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
optiontype (string) : (series string) CE for a call, PE for a put. Adding this makes it an option order.
strike (string) : (series string) ATM (default), ATM+1 / ATM-2, OTM / OTM2, ITM / ITM2, or an exact strike like "24500". Requires optiontype.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date like "10-JUL-2026". Requires optiontype.
spothint (string) : (series string) Advanced: a spot price to help option-strike selection.
usespot (bool) : (series bool) Advanced: use the spot hint for strike selection.
onslicefailure (string) : (series string) Advanced: continue (default), alert or retry, if a large order that was auto-split has a slice fail.
risk (string) : (series string) A risk block from risk() — for example risk=atw.risk(maxloss=5000).
extra (string) : (series string) Advanced: any extra "key=value" lines to pass through unchanged (one per line).
Returns: (series string) The ready-to-send alert message.
equity(symbol, exchange, producttype, tradetype, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, risk, extra)
Build an alert for a single stock or futures order (no option fields). Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) Broker-independent symbol, e.g. "SBIN".
exchange (string) : (series string) Exchange code, e.g. "NSE" or "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
option(symbol, exchange, producttype, tradetype, optiontype, strike, expiry, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, spothint, usespot, risk, extra)
Build an option order the easy way — give the underlier and pick the strike + expiry; no need to type the full option symbol. Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY", "BANKNIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
optiontype (string) : (series string) CE for a call, PE for a put.
strike (string) : (series string) ATM (default), ATM+1 / ATM-2, OTM / OTM2, ITM / ITM2, or an exact strike like "24500".
expiry (string) : (series string) weekly (default), next, monthly, or an exact date like "10-JUL-2026".
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
spothint (string) : (series string) Advanced: a spot price to help strike selection.
usespot (bool) : (series bool) Advanced: use the spot hint for strike selection.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
straddle(symbol, exchange, producttype, account, group, lots, quantity, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Straddle — buy (or sell) a call and a put at the money. direction "BUY" = long straddle, "SELL" = short straddle.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) builds the structure as named; SELL flips every leg.
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue, if one leg cannot be placed.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
strangle(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Strangle — buy (or sell) an out-of-the-money call and put, each 'width' strikes out. direction "BUY" = long strangle, "SELL" = short strangle.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) How far out of the money the legs sit, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bullCall(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bull call spread — buy a call at the money and sell a call 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bearPut(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bear put spread — buy a put at the money and sell a put 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bullPut(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bull put spread (credit) — sell a put at the money and buy a put 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bearCall(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bear call spread (credit) — sell a call at the money and buy a call 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
ironCondor(symbol, exchange, producttype, account, group, lots, quantity, width, wing, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Iron condor — sell a call and a put 'width' strikes out, and buy a call and a put 'width'+'wing' strikes out as protection. direction "BUY" builds this credit condor; "SELL" reverses it.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) How far out the sold legs sit, in strike steps (default 2).
wing (int) : (series int) Extra distance out to the protective legs, in strike steps (defaults to width).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
ironFly(symbol, exchange, producttype, account, group, lots, quantity, wing, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Iron fly — sell a call and a put at the money, and buy a call and a put 'wing' strikes out as protection. direction "BUY" builds this credit fly; "SELL" reverses it.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
wing (int) : (series int) How far out the protective legs sit, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
leg(optiontype, strike, tradetype, multiplier)
Build one option leg string for use with multiLeg(), e.g. atw.leg("CE", "ATM+2", "SELL", 2) -> "CE ATM+2 SELL x2".
Parameters:
optiontype (string) : (series string) CE for a call, PE for a put.
strike (string) : (series string) ATM, ATM+2, OTM2, ITM1, or an exact strike like "24500".
tradetype (string) : (series string) BUY or SELL for this leg.
multiplier (int) : (series int) Size multiplier for this leg (default 1).
Returns: (series string) The leg descriptor.
multiLeg(symbol, exchange, producttype, legs, account, group, lots, quantity, expiry, ordertype, price, onlegfailure, risk, extra)
Build an alert for a fully custom multi-leg order from a list of legs (1 to 10) made with leg(). Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
legs (array) : (array) The legs, e.g. array.from(atw.leg("PE","ATM-2","SELL"), atw.leg("PE","ATM-6","BUY")).
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
riskLimits(maxloss, forceexit, entrywindow, blockExpiry)
Build a risk-limits block to attach to any order via risk=. Example: risk=atw.riskLimits(maxloss=5000). These are your own limits; see the Alert Automation guide for exactly how each one behaves.
Parameters:
maxloss (float) : (series float) Maximum day loss for the account, in your account currency.
forceexit (string) : (series string) A square-off time as "HH:mm", e.g. "15:15".
entrywindow (string) : (series string) An allowed entry-time window "HH:mm-HH:mm", e.g. "09:30-14:30".
blockExpiry (bool) : (series bool) Block new entries on the instrument's expiry day.
Returns: (series string) The risk lines, ready to pass as risk=. مكتبة

مكتبة

StrategyWebhookJsonOverview
Open-source Pine library that builds JSON strings for strategy alert_message webhooks. Use it when a strategy should send structured trade signals to an external webhook receiver instead of plain alert text.
What it does
The library formats JSON payloads for three actions:
• open — new position (side, volume, stop loss, take profit, symbol, price)
• close — close by signal id
• modify — update stop loss and take profit for an existing signal id
Each payload includes secret, signalId, action, and symbol (from syminfo.ticker). Optional fields are omitted when not applicable. Strings are JSON-escaped.
Delivery modes (Mode enum)
• LocalOnly — returns an empty string (no JSON in alert_message)
• CloudOnly — returns JSON for webhook alerts
• Both — same as CloudOnly for alert_message output
How to use
1. Import the library into your strategy.
2. Call init(secret, mode) once and store the result in a var Config.
3. Pass the result of openMsg, closeMsg, or modifyMsg to strategy.entry, strategy.close, or strategy.exit via the alert_message parameter.
4. Create a strategy alert and set the webhook URL in TradingView alert settings (TradingView Plus or higher required for webhook URL field).
Example pattern
var cfg = init("YOUR_SECRET", Mode.CloudOnly)
strategy.entry("Long", strategy.long,
alert_message = openMsg(cfg, "Long", "buy", 0.1, sl, tp))
strategy.close("Long",
alert_message = closeMsg(cfg, "Long"))
Requirements
• Pine Script v6
• A strategy script (not an indicator)
• Webhook URL configured on the alert, not inside this library
Notes
signalId should be stable and unique per logical order so close and modify can target the correct open. The secret is included in the JSON body for authentication at the receiver. مكتبة

ZT_Webhook_LibCompanion library for the Alpha Flow Zone Trader (AFZT) invite-only indicator. Provides the AFZT webhook payload encoders — formats the AFZT|... pipe-delimited strings the Core script sends in its alert() messages on entry, breakeven, close, and S-event signals.
Exports:
• encode_entry_v1038 — entry-event payload (zone code, base type, confidence, touch count, zone age, entry & stop prices).
• encode_be_v1038 — breakeven-event payload.
• encode_close_v1038 / encode_close_v1041 / encode_close_v1043_v2 — close-event payloads with progressively richer telemetry (R-multiple, MFE/MAE, zone metadata, stop/BE/TP masks, ATR/risk/zone-width).
• encode_signal_v1 / encode_signal_v2 — S-Event signal payload with filter masks (v2 adds 4 upstream ML features: sweep flag, trend bias, HTF direction, liquidity distance).
All exports are pure string-formatting functions — no plots, no alerts, no state mutation. مكتبة

مكتبة

مكتبة

GBB_lib_webhookLibrary "GBB_lib_webhook"
buildPayload(action, comment)
buildPayload
@description Builds a JSON string containing standard OHLCV market data
and a custom action label, ready to be passed to alert().
Special characters in `action` and `comment` are automatically
escaped so the resulting JSON is always valid.
Parameters:
action (string) : (string) Signal label sent in the payload. Typical values:
"BUY", "SELL", "CLOSE". Any string is accepted.
comment (string) : (string) Optional free-text field (signal name, setup
description, etc.). Defaults to an empty string.
Returns: (string) A JSON object string with the fields: action, ticker,
exchange, interval, price, open, high, low, volume, time, comment.
buildPayloadFull(action, comment, qty, sl, tp, strategy)
buildPayloadFull
@description Builds an extended JSON string that includes all standard
OHLCV fields plus position-sizing and strategy metadata.
Numeric fields (qty, sl, tp) are serialised as JSON numbers
when provided, or as JSON null when omitted (na).
String fields are escaped to ensure valid JSON output.
Parameters:
action (string) : (string) Signal label. Typical values: "BUY", "SELL", "CLOSE".
comment (string) : (string) Optional free-text description. Defaults to "".
qty (float) : (float) Position size or quantity. Pass na to omit (serialised as null).
sl (float) : (float) Stop-loss price level. Pass na to omit (serialised as null).
tp (float) : (float) Take-profit price level. Pass na to omit (serialised as null).
strategy (string) : (string) Strategy identifier (e.g. "EMA_Cross"). Defaults to "".
Returns: (string) A JSON object string with the fields: action, ticker,
exchange, interval, price, open, high, low, volume, time, comment,
qty, sl, tp, strategy.
sendSignal(condition, action, comment)
sendSignal
@description Fires a TradingView alert containing a basic JSON payload
whenever `condition` is true. Alert frequency is set to
once_per_bar_close.
Parameters:
condition (bool) : (bool) Trigger condition.
action (string) : (string) Signal label.
comment (string) : (string) Optional description. Defaults to "".
Returns: void
sendSignalFull(condition, action, comment, qty, sl, tp, strategy)
sendSignalFull
@description Fires a TradingView alert containing an extended JSON payload
whenever `condition` is true. Alert frequency is set to
once_per_bar_close.
Parameters:
condition (bool) : (bool) Trigger condition.
action (string) : (string) Signal label.
comment (string) : (string) Optional description. Defaults to "".
qty (float) : (float) Position size. Pass na to omit. Defaults to na.
sl (float) : (float) Stop-loss price. Pass na to omit. Defaults to na.
tp (float) : (float) Take-profit price. Pass na to omit. Defaults to na.
strategy (string) : (string) Strategy name. Defaults to "".
Returns: void مكتبة

MaidongAlertLibraryLibrary "MaidongAlertLibrary"
Maidong Alert Library is a Pine Script library built to standardize alert formatting and dispatch across signals, order blocks, setups, and analysis modules.
Instead of building alert text separately inside each part of an indicator, this library centralizes message construction, time formatting, directional labeling, and frequency handling into one reusable component.
Core features:
- Supports `Signal`, `Setup`, `Analysis`, and `Order Block Signal`
- Supports `Bullish` and `Bearish` directional alerts
- Supports both compact and detailed alert output
- Supports timezone-aware timestamp formatting
- Supports common TradingView alert frequency modes
This library is useful when:
- Your script contains multiple modules that all need alerts
- You want a consistent alert format across your ecosystem
- You want to separate alert formatting from indicator logic
AlertSender(condition, alertSetting, alertName, alertType, detectionType, setupData, frequency, utcZone, moreInfo, message, o, h, l, c, entry, tp, sl, distal, proximal)
Parameters:
condition (bool)
alertSetting (string)
alertName (string)
alertType (string)
detectionType (string)
setupData (string)
frequency (string)
utcZone (string)
moreInfo (string)
message (string)
o (float)
h (float)
l (float)
c (float)
entry (float)
tp (float)
sl (float)
distal (float)
proximal (float) مكتبة

OrderTicketBuilderLibrary "OrderTicketBuilder"
Assembles broker order ticket payloads as JSON strings.
BuildTicket(licenseId, symbol, action, orderType, tradeType, size, price, tp, sl, risk, trailPrice, trailOffset)
BuildTicket assembles a JSON order ticket string for downstream execution.
Parameters:
licenseId (string) : License identifier
symbol (string) : Symbol to trade
action (string) : "MRKT" or "PENDING"
orderType (string) : "BUY" or "SELL"
tradeType (string) : "SPREAD" or "SINGLE"
size (float) : (Optional) Trade size
price (float) : (Optional) Price for pending orders
tp (float) : (Optional) Take profit
sl (float) : (Optional) Stop loss
risk (float) : (Optional) Percent risk if size unspecified
trailPrice (float) : (Optional) Trailing-stop trigger price
trailOffset (float) : (Optional) Trailing-stop offset
Returns: JSON order ticket string مكتبة

SimTradeIndicatorsLibrary "SimTradeIndicators"
SimTrade indicator library — exact parity with Python pipeline (TA-Lib + pandas_ta).
Each function replicates the formula used in base.py / signals.py so that
TradingView charts match the GPU hunt / validator / live engine outputs.
Formula sources:
TA-Lib → RSI, ATR, EMA, MACD, CCI, Stoch, WILLR, MFI, ADX, PSAR, OBV, BBANDS, AROON, PPO, AD
pandas_ta → SuperTrend, Vortex, Ichimoku, Donchian, HMA, TSI, CMF, EFI, CHOP, Heikin-Ashi
Manual → Keltner (EMA+ATR Wilder), TTM Squeeze, Chandelier Exit, VWAP reset, Pivot Points
Known intentional deviations (documented):
- Stoch trigger 11 uses Full %D (double-smoothed), not single %K
- OBV filter 206 uses windowed 800-bar OBV (GPU-aligned, not cumulative)
- Pivot Points use rolling window, not session-based (see pivot_pp notes)
- EMA has longer warmup in TA-Lib (~50 bars unstable period) vs TW (from bar 1); steady-state identical
smma(src, length)
SMMA / Wilder RMA. alpha = 1/length. Matches talib "RMA" used for ATR/RSI internally.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: RMA value
hma(src, length)
HMA (Hull Moving Average). HMA = WMA(2·WMA(N/2) − WMA(N), √N). Matches pandas_ta.hma.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: HMA value
dema(src, length)
DEMA (Double EMA) = 2·EMA − EMA(EMA). Matches talib.DEMA.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: DEMA value
tema(src, length)
TEMA (Triple EMA) = 3·EMA − 3·EMA² + EMA³. Matches talib.TEMA.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: TEMA value
atr_wilder(length)
ATR using Wilder RMA. Identical to talib.ATR and TW ta.atr.
Parameters:
length (simple int) : Period (default 14)
Returns: ATR value
atr_percentile_pct(length, lookback)
ATR percentile rank over a rolling window. Matches Python vol_filter 201.
Logic: for each bar count how many ATR values in are <= current ATR,
return that fraction as 0..100. Warmup bars (< lookback + length) return 50.0.
Parameters:
length (simple int) : ATR period / Wilder RMA (default 14). Matches params .
lookback (simple int) : Rolling window for percentile rank (default 30). Matches params .
Returns: Percentile rank 0..100 (pass filter when >= pct_min / params )
bbands(src, length, mult)
Bollinger Bands. Returns .
mid = SMA. Matches talib.BBANDS (matype=0 = SMA).
Parameters:
src (float) : Source series (typically close)
length (simple int) : Period (default 20)
mult (float) : Standard deviation multiplier (default 2.0)
Returns:
bb_pctb(src, length, mult)
Bollinger Bands %B = (close − lower) / (upper − lower).
Returns 0.5 during warmup (matches Python _nan50 fallback in base.bb_pctb).
Parameters:
src (float) : Source series
length (simple int) : Period (default 20)
mult (float) : Multiplier (default 2.0)
Returns: %B value
bb_width_x1000(src, length, mult)
BB bandwidth × 1000 / mid. Used by vol filter 202 (bb_width).
Parameters:
src (float) : Source series
length (simple int) : Period (default 20)
mult (float) : Multiplier (default 2.0)
Returns: (upper − lower) / |mid| × 1000
keltner(ema_period, atr_period, mult)
Keltner Channel. mid = EMA(close, ema_period), band = ATR(atr_period) Wilder RMA.
IMPORTANT: this is the TW-standard formula. NOT pandas_ta kc(mamode="ema") which uses EMA(TR).
That version produces ~40% narrower bands than TW. This library uses the correct RMA(ATR) band.
Parameters:
ema_period (simple int) : EMA period for midline (default 20)
atr_period (simple int) : ATR period for band width (default 10)
mult (float) : ATR multiplier (default 1.5)
Returns:
keltner_width_x1000(period, mult)
Keltner Channel bandwidth × 1000 / mid. Used by vol filter 204 (keltner_width).
Parameters:
period (simple int) : Period for both EMA and ATR (default 20)
mult (float) : ATR multiplier (default 1.5)
Returns: (upper − lower) / |mid| × 1000
choppiness(length)
Choppiness Index. CHOP = 100·log10(Σ ATR1 / (HH − LL)) / log10(N).
Matches pandas_ta.chop and TW built-in CHOP. Returns 50.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: CHOP value
rsi_val(src, length)
RSI using Wilder RMA. Identical to talib.RSI and TW ta.rsi.
Returns 50.0 during warmup (matches Python _nan50 fallback).
Parameters:
src (float) : Source series (typically close)
length (simple int) : Period (default 14)
Returns: RSI value
cci_val(length)
CCI = (typical − SMA(typical)) / (0.015 · mean_deviation). Matches talib.CCI.
Returns 0.0 during warmup (matches Python _nan0 fallback).
Parameters:
length (simple int) : Period (default 20)
Returns: CCI value
stoch_raw_k(k_period)
Stochastic raw %K (no smoothing). Matches base.stoch_k (talib slowk_period=1).
NOTE: TW ta.stoch default smooths %K with SMA(3). This is the unsmoothed fast %K.
Used by filter 103 (stoch_k_below).
Parameters:
k_period (simple int) : Lookback period (default 14)
Returns: Raw %K (50.0 during warmup)
stoch_full_d(k_period, d_period)
Full Stochastic %D = SMA(SMA(raw%K, d_period), d_period). Matches talib.STOCH output.
Used by trigger 11 (stoch_cross). NOT single-smoothed %K — lag is +2-3 bars vs TW default.
Parameters:
k_period (simple int) : Raw %K lookback (default 14)
d_period (simple int) : Smoothing applied twice (default 3)
Returns: Full Stochastic %D (50.0 during warmup)
williams_r(length)
Williams %R = −100 · (HH − close) / (HH − LL). Matches talib.WILLR.
Range: −100 to 0. Returns −50.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: Williams %R value
mfi_val(length)
MFI (Money Flow Index). Matches talib.MFI.
Returns 50.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: MFI value
macd_val(src, fast, slow, signal_period)
MACD. Returns . Identical to talib.MACD.
All NaN values replaced with 0.0 (matches Python _nan0).
Parameters:
src (float) : Source series
fast (simple int) : Fast EMA period (default 12)
slow (simple int) : Slow EMA period (default 26)
signal_period (simple int) : Signal EMA period (default 9)
Returns:
ppo_val(src, fast, slow)
PPO = (EMA(fast) − EMA(slow)) / EMA(slow) × 100. Matches talib.PPO.
Returns 0.0 during warmup.
Parameters:
src (float) : Source series
fast (simple int) : Fast period (default 12)
slow (simple int) : Slow period (default 26)
Returns: PPO value
tsi_val(src, long_period, short_period)
TSI (True Strength Index). Matches pandas_ta.tsi parameter order.
TSI = 100 · EMA(EMA(Δclose, slow), fast) / EMA(EMA(|Δclose|, slow), fast)
slow is the OUTER (first) smoothing, fast is the INNER (second). Same as TW.
Parameters:
src (float) : Source series
long_period (simple int) : Outer (slow) EMA period (default 25)
short_period (simple int) : Inner (fast) EMA period (default 13)
Returns: TSI value (0.0 during warmup)
adx_di(length)
ADX + DI lines. Returns . Matches talib.ADX/PLUS_DI/MINUS_DI.
Uses Wilder RMA (identical to TW ta.dmi / ta.adx).
Parameters:
length (simple int) : Period (default 14)
Returns: — 0.0 during warmup
supertrend_val(length, mult)
SuperTrend direction and value. Matches pandas_ta.supertrend (RMA ATR).
Returns : direction = 1 (bull) or −1 (bear).
Parameters:
length (simple int) : ATR period (default 10)
mult (float) : ATR multiplier (default 3.0)
Returns:
psar_val(start, inc, max_af)
Parabolic SAR. Returns . Matches talib.SAR.
direction = 1 if close > SAR (bull), −1 bear.
Parameters:
start (simple float) : Initial AF / step (default 0.02)
inc (simple float) : AF increment per bar (default 0.02)
max_af (simple float) : Maximum AF cap (default 0.2)
Returns:
aroon_val(length)
Aroon Up and Down. Returns . Matches talib.AROON.
ta.aroon does not exist in Pine v6 — computed manually:
Aroon Up = (length − bars since highest high over length+1 bars) / length × 100
Aroon Down = (length − bars since lowest low over length+1 bars) / length × 100
This is identical to talib.AROON and TradingView's built-in Aroon indicator.
Returns 50.0 during warmup (matches Python _nan50).
Parameters:
length (simple int) : Period (default 25)
Returns:
vortex_diff(length)
Vortex Indicator difference (VI+ − VI−). Matches base.vortex.
Positive = bullish regime, negative = bearish. Returns 0.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: VI+ minus VI−
linreg_slope(src, length)
Linear Regression Slope. Matches talib.LINEARREG_SLOPE exactly.
Computes OLS slope for x = 0..N-1 (oldest=0, newest=N-1).
Positive = uptrend, negative = downtrend. Returns 0.0 during warmup.
Parameters:
src (float) : Source series
length (simple int) : Period (default 20)
Returns: Slope value
obv_val()
OBV (On-Balance Volume). Cumulative. Matches talib.OBV.
Returns: Cumulative OBV
vwap_reset(reset_bars)
VWAP with periodic session reset. Matches base.vwap(reset_bars).
reset_bars=24 on H1 ≈ daily VWAP (crypto 24/7). reset_bars=6 on H4 ≈ daily.
reset_bars=0 uses TW built-in ta.vwap (session anchor).
Parameters:
reset_bars (simple int) : Bars per session (0 = TW session anchor, 24 = H1 daily, 6 = H4 daily)
Returns: VWAP value
cmf_val(length)
CMF (Chaikin Money Flow) = Σ(CLV·vol) / Σvol. Matches pandas_ta.cmf.
CLV = ((close − low) − (high − close)) / (high − low). Returns 0.0 during warmup.
Parameters:
length (simple int) : Period (default 20)
Returns: CMF value (−1 to 1)
ad_val()
Accumulation/Distribution Line. Matches talib.AD.
Returns: Cumulative A/D value
efi_val(length)
EFI (Elder Force Index). EFI = EMA((close − close ) · volume, length).
Matches pandas_ta.efi. Returns 0.0 during warmup.
Parameters:
length (simple int) : EMA period (default 13)
Returns: EFI value
ichimoku_val(tenkan_period, kijun_period, senkou_b_period)
Ichimoku lines. Returns .
Matches pandas_ta.ichimoku with CORRECTED column mapping (ISA, ISB, ITS, IKS, ICS).
senkou_a/b are plotted 26 bars AHEAD in TW — values here are for current bar alignment.
Parameters:
tenkan_period (simple int) : Tenkan-sen period (default 9)
kijun_period (simple int) : Kijun-sen period (default 26)
senkou_b_period (simple int) : Senkou B period (default 52)
Returns:
donchian_val(length)
Donchian Channel. Returns .
upper = highest(high, N), lower = lowest(low, N). Matches pandas_ta.donchian.
NOTE: lookback may differ ±1 bar from TA-Lib; consistent across all pipeline stages.
Trigger 37 (donchian_break) compares close > upper — use upper in Pine.
Parameters:
length (simple int) : Period (default 20)
Returns:
ttm_squeeze_val(bb_period, bb_mult, kc_period, kc_mult)
TTM Squeeze. Returns .
squeeze_on: BB inside KC (volatility compression).
momentum: ta.linreg(close − (donchian_mid + SMA) / 2, bb_period)
EXACT match with John Carter formula and base.ttm_squeeze after fix.
Parameters:
bb_period (simple int) : BB period (default 20)
bb_mult (float) : BB multiplier (default 2.0)
kc_period (simple int) : KC period — same for EMA midline and ATR band (default 20)
kc_mult (float) : KC ATR multiplier (default 1.5)
Returns:
chandelier_val(period, mult)
Chandelier Exit. Returns .
long_exit = highest(high, period) − mult · ATR(period)
short_exit = lowest(low, period) + mult · ATR(period)
Exact match with base.chandelier_exit. Both include current bar in rolling max/min.
Trigger 45 fires when close crosses long_exit or short_exit (up = bull, down = bear).
Parameters:
period (simple int) : Lookback and ATR period (default 22)
mult (float) : ATR multiplier (default 3.0)
Returns:
ha_close()
Heikin Ashi close. HA_close = (open + high + low + close) / 4. Matches pandas_ta.ha.
Returns: HA close value
ha_open()
Heikin Ashi open. HA_open = (HA_open + HA_close ) / 2.
Trigger 48 fires on HA candle color flip: HA_close vs HA_open.
Returns: HA open value
pivot_pp(period)
Rolling Pivot Point (floor method). Matches base.pivot_points.
pp = (max(high, period bars ago) + min(low, period bars ago) + close ) / 3
NOTE: Rolling window, NOT session-based. H1 default period=24 ≈ 1 day (crypto 24/7).
For H4 set period=6 (6 × 4h = 1 day). TW Pivot Points use session H/L/C — differs.
Parameters:
period (simple int) : Rolling lookback (default 24)
Returns: Pivot point value
pivot_r1_s1(period)
Rolling R1 and S1 levels. Matches base.pivot_points r1/s1.
r1 = 2·pp − lowest_low, s1 = 2·pp − highest_high
Parameters:
period (simple int) : Rolling lookback (default 24)
Returns: مكتبة

fpa_unified_libLibrary "fpa_unified_lib"
lineStyle(styleText)
Parameters:
styleText (string)
labelSize(sizeText)
Parameters:
sizeText (string)
normalizeSession(sessionInput, hideWeekends)
Parameters:
sessionInput (string)
hideWeekends (bool)
isSessionActive(sessionInput, timezoneInput)
Parameters:
sessionInput (string)
timezoneInput (string)
tfInRange(lowTf, highTf)
Parameters:
lowTf (string)
highTf (string)
parseTradingDayOpenMinutes(sessionInput)
Parameters:
sessionInput (string)
safeColor(c, transp)
Parameters:
c (color)
transp (int)
updateRay(lineRef, shouldShow, startBarIndex, yPrice, lineColor, lineWidth, lineStyleText, rightOffsetBars, lookbackBars)
Parameters:
lineRef (line)
shouldShow (bool)
startBarIndex (int)
yPrice (float)
lineColor (color)
lineWidth (int)
lineStyleText (string)
rightOffsetBars (int)
lookbackBars (int)
updateLabel(labelRef, shouldShow, yPrice, textValue, labelColor, rightOffsetBars, sizeText)
Parameters:
labelRef (label)
shouldShow (bool)
yPrice (float)
textValue (string)
labelColor (color)
rightOffsetBars (int)
sizeText (string)
trimLines(arr, limit)
Parameters:
arr (array)
limit (int)
trimLabels(arr, limit)
Parameters:
arr (array)
limit (int)
parseFloatList(textArea)
Parameters:
textArea (string) مكتبة

مكتبة

VoltRouter Webhook BuilderBuild TradingView alert webhook payloads for VoltRouter — a signal routing service that executes your TradingView strategy alerts directly at your broker. $0.07/signal, pay-as-you-go, no subscription required .
Supports: market, limit, stop, bracket (TP+SL), trailing stop, FLAT, and cancel-all.
How to use:
1. Sign up at voltrouter.com and connect your broker
2. Import this library in your strategy
3. Paste the output into a TradingView alert → Webhook URL field
Setup: voltrouter.com
import VoltRouterWebhook as vr
// In your strategy alert message field:
vr.market("MNQM26", "buy", 1, "ibkr", "my_strategy")
vr.bracket("MNQM26", "sell", 1, close + 10, close - 5)
vr.flat("MNQM26") مكتبة

Vantage_PickMyTrade_IntegrationVantage_PickMyTrade_Integration — Webhook integration library for Pine Script strategies routing orders through PickMyTrade.
─────────────────────────────────────────
WHAT IT DOES
Constructs and emits JSON webhook payloads in the PickMyTrade format. The library provides a strongly-typed Pine Script interface and emits the alert for you, so your strategy never has to hand-build JSON strings, remember exact field values, or track which fields are conditional.
─────────────────────────────────────────
WHAT IT PROVIDES
Strong types for every PickMyTrade enumeration — order actions (buy / sell / close), order types (market / limit / stop / stop-limit), and bracket-mode specification (price / dollar / percent). Using a typed enum catches typos at compile time.
High-level send functions covering the common order patterns — a stop entry with bracket (pre-placed at the exchange), a market or limit entry with bracket, targeted close by comment tag, a full-flatten for a symbol, and in-place SL/TP modification on an existing position. All share a single underlying builder that handles field ordering, conditional fields, and token-in-body authentication.
─────────────────────────────────────────
HOW TO USE
A complete example call is in the comment block at the top of the source file — import the library, copy the pattern, adjust to your strategy. Hover any exported type or function in the Pine Editor for per-parameter documentation. مكتبة

Vantage_TradersPostVantage_TradersPost — Webhook integration library for Pine Script strategies routing orders through TradersPost.
─────────────────────────────────────────
WHAT IT DOES
Constructs and emits JSON webhook payloads in the TradersPost format. The library provides a strongly-typed Pine Script interface and emits the alert for you, so your strategy never has to hand-build JSON strings, remember exact enum values, or track which fields are conditional.
─────────────────────────────────────────
WHAT IT PROVIDES
Strong types for every TradersPost enumeration — order actions, order types, quantity types, position sentiment, stop-loss types, time-in-force, and the options fields. Using a typed enum in your strategy catches typos at compile time instead of at trade time.
High-level send functions covering the common order patterns — a single-call bracket (entry + TP + SL), an advanced send with every TradersPost field exposed, a no-cancel variant, a sentiment-based position-management send, a cancel-all, and two-leg OTO and OCO helpers.
─────────────────────────────────────────
HOW TO USE
A complete example call is in the comment block at the top of the source file — import the library, copy the pattern, adjust to your strategy. Hover any exported type or function in the Pine Editor for per-parameter documentation.
─────────────────────────────────────────
Maintenance of this library was taken over at the request of adam_overton. مكتبة

AvwapLibLibrary "AvwapLib"
Shared functions: AVWAP, stage classification, position sizing,
swing detection, and risk helpers. Used by all strategy() scripts.
NOTE: rs_vs_spy() cannot live here (request.security() banned in
library exports) — each strategy implements it inline.
avwap(src, anchor_bar, max_lookback)
Anchored VWAP from a specific bar to current bar.
Uses loop approach with bounded max_lookback for robustness.
Parameters:
src (float) : Source price (typically hlc3)
anchor_bar (int) : Bar index of anchor point (from find_swing_high/low)
max_lookback (simple int) : Maximum bars to look back (cap for performance, default 500 ~2yr daily)
Returns: AVWAP value, or na if anchor invalid or out of range
avwap_slope(avwap_val, lookback)
AVWAP slope — rate of change over lookback period.
Parameters:
avwap_val (float) : AVWAP series
lookback (simple int) : Number of bars for slope calculation
Returns: Slope (positive = rising, negative = falling), or na
dcr()
Daily Closing Range — where price closed within the bar's range.
Returns: DCR as percentage (0 = closed at low, 100 = closed at high)
rvol(period)
Relative Volume — current bar volume vs historical average.
Uses volume offset to avoid including current bar in average.
Parameters:
period (simple int) : Lookback period for average calculation
Returns: RVOL ratio (>1 = above average)
is_stage2()
Stage 2 check (simplified Weinstein model).
Conditions: price > SMA50, SMA50 rising (vs 10 bars ago), price > SMA200.
Returns: true if all Stage 2 conditions met
calc_shares(entry, stop, risk_pct, equity)
Position size: shares = floor(equity * risk% / risk_per_share).
Parameters:
entry (float) : Entry price
stop (float) : Stop-loss price
risk_pct (float) : Risk as decimal (0.01 = 1%)
equity (float) : Account equity
Returns: Number of shares (integer), 0 if invalid
rr_valid(entry, stop, target, min_rr)
Validate risk/reward ratio meets minimum threshold.
Parameters:
entry (float) : Entry price
stop (float) : Stop-loss price
target (float) : Target price
min_rr (float) : Minimum required R:R (e.g., 2.0 for 1:2)
Returns: true if R:R >= min_rr
confirmed()
Returns true only on confirmed (closed) bars.
MUST gate every entry/exit signal to prevent repainting.
Returns: true if bar is confirmed
find_swing_high(strength)
Bar index of the most recent confirmed swing high.
Uses ta.pivothigh — confirmed 'strength' bars after the actual high.
Result persists (via var) until a new swing high is detected.
Parameters:
strength (simple int) : Number of bars required on each side to confirm pivot
Returns: Bar index of last swing high, or na if none found yet
find_swing_low(strength)
Bar index of the most recent confirmed swing low.
Uses ta.pivotlow — confirmed 'strength' bars after the actual low.
Result persists (via var) until a new swing low is detected.
Parameters:
strength (simple int) : Number of bars required on each side to confirm pivot
Returns: Bar index of last swing low, or na if none found yet مكتبة

مكتبة
