Indicateur

Trade ManagementTrade Management
Trade Management is a visual planning and position-management tool designed to help traders structure, size, and monitor both long and short trades directly on the chart.
It combines entry planning, stop-loss placement, profit targets, position sizing, partial exits, and progressive profit protection within a single dashboard.
Main features
- LONG and SHORT trade plans
- Automatic, manual-price, or percentage-based stop-loss
- Automatic stop placement based on confirmed pivots and ATR
- Fixed risk-multiple or market-structure targets
- Two profit targets: TP1 and TP2
- Optional ideal-entry level based on recent price structure
- Position sizing based on:
- Capital allocation
- Maximum account risk at the stop
- Fixed quantity
- Configurable TP1/TP2 position allocation
- Support for stocks and other instruments
- Automatic or manually defined point value
- Progressive stop management
- Live and historical tracking modes
- Customizable dashboard position, text size, and projected levels
Trade-plan construction
The indicator calculates the initial risk from the distance between the entry price and the stop-loss.
In AUTOMATIC stop mode, the stop is placed beyond a confirmed structural pivot with an ATR-based buffer. A minimum ATR distance prevents the initial stop from being placed excessively close to the entry.
Alternatively, traders can define an exact stop price or use a percentage distance from entry.
Profit targets can be calculated using fixed multiples of the initial risk, expressed in R , or derived from historical support and resistance levels that satisfy the selected minimum reward-to-risk requirement.
Position sizing
Three sizing methods are available:
- CAPITAL ALLOCATION % allocates a selected percentage of account capital to the position.
- STOP RISK % calculates the quantity according to the maximum theoretical account loss at the initial stop.
- FIXED QUANTITY uses a manually entered number of shares, units, or lots.
For stocks, quantities are rounded down to whole shares. Other instruments can use a configurable point value and quantity increment.
The position can also be divided between TP1 and TP2 using several predefined allocation ratios.
Progressive protection
When TP1 is reached, the tracked stop moves to the entry price, creating a break-even reference for the remaining position.
A separate profit-protection trigger can move the tracked stop beyond entry by a configurable fraction of the initial risk. This helps visualize how much profit would theoretically be protected if the corresponding broker order were adjusted.
The indicator does not modify broker orders automatically.
Tracking modes
LIVE mode freezes the complete trade plan when tracking is armed. It can either treat the position as already open or wait for the entry price to be crossed. Once frozen, new pivots and ATR changes do not modify the original plan.
HISTORICAL mode begins monitoring from the selected date and assumes entry when the configured price is touched. When several levels are reached within the same candle, the exact event order cannot always be determined from OHLC data. The dashboard identifies these situations as intrabar uncertainty, and stop-loss events receive priority when conflicting levels are touched on the same bar.
Dashboard and chart levels
The chart displays the planned entry, optional ideal entry, tracked stop-loss, TP1, TP2, profit-protection trigger, and protected-stop level.
The dashboard summarizes:
- Entry and initial stop
- Position quantity
- Capital allocated
- Initial monetary and percentage risk
- TP1 and TP2 allocations
- Estimated target profit
- Weighted reward-to-risk ratio
- Current tracked stop
- Remaining position
- Theoretical profit or loss
- Trade status
- Suggested next management action
Important limitations
This indicator is a planning and monitoring aid, not an automated trading system. It does not place orders, confirm broker executions, or generate autonomous trade recommendations.
LIVE tracking is reset when an input or timeframe is changed, or when the script is reloaded. Calculations assume executions at the displayed levels and exclude commissions, taxes, slippage, spreads, currency conversion, liquidity constraints, and other execution differences.
Always verify contract specifications, point values, quantities, and orders directly with your broker.
For educational and informational purposes only. This indicator does not constitute financial advice.
DL INVEST - Laurent. Indicateur

Indicateur

Indicateur

Sector Rotation - Leadership Persistence [Dots3Red]🔄 SECTOR ROTATION - LEADERSHIP PERSISTENCE
At any given time, some sectors are leading and others are lagging behind — traders call this rotation. This tool draws all eleven US sectors on one chart, normalized from the same starting point, so leadership and lag are visible at a glance instead of pieced together from eleven separate tabs.
✨ WHY THIS MATTERS
This script adds a question that few answer: once a sector takes the lead, how long does that lead typically last before another sector overtakes it? And right now, given how long the current leader has already held the top spot, what are the odds it's still leading a bit further down the road?
📊 Avg Leadership: 14 bars (n=8)
📊 Leader Persists: 58% (n=8)
That's measured directly from this chart's own rotation history — not a general rule about how sectors "should" behave.
⚙️ HOW IT WORKS
🔄 Eleven sectors, one normalized view — all eleven SPDR Select Sector ETFs (Technology, Financials, Energy, Health Care, Industrials, Discretionary, Staples, Utilities, Materials, Real Estate, Communication Services) are plotted as cumulative percentage return from a common anchor point. Every line starts at zero and diverges from there, so the spread between the best and worst performer is the actual visual story.
⚓ Anchor options — Week, Month, or Quarter. All lines reset to zero at the start of each new period. Month is the standard window for rotation analysis, since it's long enough to show a real trend without being so long that early leadership becomes irrelevant.
👑 Leadership tracking — the sector with the highest normalized return at any moment is the current leader, marked with a star in both the end-of-chart label and the dashboard legend. Every time leadership changes hands, the duration the previous leader held the top spot is recorded, building a running average across every changeover this chart has produced.
🎯 Persistence grading — separately, each new leader is checked again a set number of bars later: is it still leading? The running percentage is a direct, honest answer to "once a sector takes over, how often does that lead actually hold up," specific to this chart's own history.
📋 Ranked dashboard legend — all eleven sectors, sorted by current performance, with each one's actual line color and live return percentage. This solves a real limitation of on-chart labels at the far right edge, which can get compressed or pushed off-screen depending on how the chart is sized — the dashboard legend is always fully readable regardless of zoom or pane width.
🧭 HOW TO USE
1️⃣ Read the spread, not just the top line. A wide gap between the leader and the rest signals strong rotation conviction; a tight cluster near zero signals an indecisive, rotation-less market.
2️⃣ Check "Led Since" alongside "Avg Leadership." If the current leader has already held the top spot longer than the historical average changeover duration, that's context worth noting — not a signal to act on, but a useful piece of the picture.
3️⃣ Use the persistence percentage to calibrate expectations, not to predict. "58% (n=8)" is a real but still-developing sample; treat it with more confidence once the changeover count grows.
4️⃣ Use the ranked legend as a quick market-breadth check. Seeing whether the top of the ranking is dominated by cyclical sectors (Discretionary, Industrials, Financials) versus defensive ones (Staples, Utilities, Real Estate) is itself a useful read on broad market risk appetite.
5️⃣ Match the anchor to your own time horizon. Week for a fast, tactical view; Month for the standard rotation window; Quarter for a slower, more structural read on which sectors have been dominant over a longer stretch.
🛠️ SETTINGS
⚓ Anchoring
• Rotation Anchor — Week / Month / Quarter
• Leadership Check Window — how many bars ahead a new leader is graded for persistence
🖥️ Dashboard
• Show/hide, position — current leader, leadership duration, average leadership length, persistence odds, changeover count, and the full ranked sector legend
📝 NOTES
This tool covers the eleven US SPDR Select Sector ETFs specifically — it does not cover international markets or custom sector groupings. Leadership and persistence statistics accumulate from when the indicator is added to the chart and become more meaningful as more changeovers occur; early on, expect small sample sizes.
⚠️ DISCLAIMER
This is an analytical and visualization tool. It does not generate trade signals and does not constitute financial advice. Historical leadership duration and persistence rates do not guarantee how sector rotation will behave going forward. Indicateur

Position Size CalculatorPosition Size Calculator
Computes quantity, position value, and risk-reward directly on the chart, checked against multiple stop-loss methods simultaneously. No manual calculation, no spreadsheet.
How it works
Enter account size and risk per trade. For each stop-loss method enabled, the table displays shares to buy or sell, capital required and percentage of account, recalculated on every tick.
Up to four stop definitions can be compared side by side:
1) Current Day Low/High: calculated from the current session
2) Previous Day Low/High: calculated from the prior session
3) Fixed Price: a manually set stop
4) Fixed %: a stop set as a distance from entry
Comparing columns shows how tightening or widening a stop changes position size for the same risk amount.
Features
1) Live table, recalculates every tick
2) Risk mode: percent of account or fixed currency amount
3) Long and short supported; stop logic adjusts automatically by direction
4) Optional target price adds R:R per stop column
5) Fixed Price and Fixed % toggle independently
6) Quantities floored to whole shares
7) Table position, text size, colors and borders are configurable
Setup
1) Enter account value, select risk mode (percent or fixed amount), and set the risk value.
2) Select Long or Short. Optionally enable a target price to compute R:R.
3) Enable Fixed Stop Price and/or Fixed Stop % as needed. Current Day and Previous Day stops calculate automatically.
4) Read the table: each active column shows stop price, quantity, position size, percent of account, and R:R (if a target is set).
An info banner above the table shows live entry price, direction, and target for reference.
Notes
- Entry price is always the live price. This is a real-time sizing tool, not a backtesting tool.
- Current Day and Previous Day stops require the chart timeframe to be Daily or lower. A warning appears in the banner if the timeframe is coarser.
- Quantity shows "n/a" when a stop is on the wrong side of entry for the selected direction, or when risk-per-share cannot be computed.
Disclaimer
This tool performs position-sizing calculations only. It does not predict price movement, generate trade signals, or constitute financial advice. Perform independent due diligence before entering any trade. Indicateur

EMA 50x200 Cross Trend Barometer The 50/200 moving-average cross is one of the most-watched signals in markets:
the "golden cross" and the "death cross." Trend Barometer turns that classic into
a clean, at-a-glance read on the prevailing regime, the way a barometer reads the
pressure before the storm.
When the fast average (50) sits above the slow one (200), the market is in a
risk-on regime and the chart glows fair-weather green (☀). When it slips below,
conditions turn risk-off and the chart shifts to storm red (⛈). One look tells you
which side of the trend you're standing on.
WHAT IT SHOWS
• Regime-coloured EMA 50 and EMA 200, with a shaded gap between them
• A soft background tint for the current regime (risk-on / risk-off)
• Golden-cross ▲ and death-cross ▼ markers on the exact flip bar
• A compact weather panel: current regime, bars held in it, and the last cross
• Alerts on every regime flip
MAKE IT YOURS
Switch between EMA and SMA, set your own fast/slow lengths (50/200 by default),
and recolour everything to match your chart.
HONEST BY DESIGN
This is a regime lens, not a buy/sell system. A barometer reports the conditions;
it doesn't place your trades. The 50/200 cross is trend-following context: great for
reading the prevailing regime and filtering out noise, but it lags turns and is not
an entry trigger on its own. Use it to frame your bias and manage risk alongside
your own analysis.
NO REPAINTING
Some indicators quietly rewrite their own past: you look back and see a signal at a
perfect spot that simply wasn't there when the bar formed. That flatters them in
hindsight. This one can't do that. It only ever reads the current and earlier bars,
never the future (no request.security, no forward references), so a cross printed
two years ago sits exactly where it printed at the time.
One caveat, true of every indicator: the newest bar is still forming, so the colour
can flicker while it's live. A cross is only final once that bar closes. Indicateur

Indicateur

Portfolio Open Risk and Position Heat Tracker - India [SMC]WHAT THIS DOES
Position sizing tells you how much to buy on one trade. It says nothing about what happens when you are holding eight of them at once.
This tracks all your open positions together. Pick up to twenty symbols, give each one a quantity, an entry and a stop, and it prices what you are carrying: what you lose if every stop fills, which sectors that loss is concentrated in, and how much room is left before you reach the total loss you are willing to take.
TWO NUMBERS THAT ARE NOT THE SAME
Most risk calculators quietly conflate these. They answer different questions and both are worth knowing.
OPEN LOSS
what you give back from today's price down to your stops. Money currently on the table.
LOSS VS COST
what you lose measured from your entries. On a position whose stop has been trailed above cost this is zero, no matter how much open loss it still carries. A trader running trailed stops can be carrying a large open loss and no loss at all against cost. One number says exposed, the other says protected. Both are true, so the dashboard prints both.
The sample position in WIPRO shows it: stop at 172 against a 170 entry. Real open loss, zero loss against cost.
THE ARITHMETIC
Open loss = Qty x (Last - Stop)
Loss vs cost = Qty x max(0, Entry - Stop)
P&L = Qty x (Last - Entry)
Deployed = sum of Qty x Last
Room left = Max total open loss - Open loss
A position trading below its stop is counted as zero open loss and flagged "past stop", because that loss is already realised. Counting it again would flatter the total.
YOUR LIMIT, NOT MINE
You set the maximum total open loss in rupees. The default of thirty thousand is six percent of the default capital, being six trades at one percent each. That is a common starting point, not a rule from this script. Set it to what you actually run.
The bar fills toward your number. Room left translates whatever remains into a rough count of further trades at your standard risk per trade.
SECTOR CLUSTERING
Open loss is grouped by sector, taken automatically from exchange data. This exists because five positions in one sector is not five independent risks.
Total risk can look comfortable while sitting almost entirely in one group. In the sample portfolio three of five positions are Technology Services and carry half the open loss. The headline number never shows that. The sector block does.
THE POSITION TABLE
Rows sort by open loss, heaviest first, so the position you would feel most is not buried at the bottom. Note that this ordering is not P&L ordering. A stock up five percent with a trailed stop can sit last, because it has the least left on the table.
Entry, stop and last are reference prices and are shown muted. P&L and open loss are the numbers you act on and stay at full strength. A stop above cost is shown in the up colour, which is a fact about the position, not a view on the trade.
GETTING STARTED
The first five rows arrive filled with sample positions so the dashboard shows something useful before you type anything. Replace them with your own. A row counts once it has a symbol, a quantity and a stop. Entry is optional, though without it P&L and loss vs cost cannot be worked out.
Pine cannot add input rows on demand, so all twenty exist from the start and empty ones are ignored.
WHAT THIS DOES NOT DO
It does not know your real broker positions, so what you type is what it believes. It does not tell you whether any position is worth holding, whether your stops are sensible, or whether you are too concentrated. It measures. The judgement stays with you.
LIMITATIONS
Long positions only. Figures exclude brokerage, exchange and statutory charges, taxes, slippage, partial fills, and gap risk. Gap risk matters most here: if several positions gap below their stops at once, the total loss will exceed every figure shown, and no dashboard can prevent that. Open loss assumes each stop fills at its exact price. Treat it as a floor. Prices are daily closes for each symbol and update while the session is open. Positions whose symbol cannot be priced are excluded from every total and
flagged.
Educational and decision-support only. Not investment advice, and not a recommendation to buy or sell any security. Indicateur

Risk/Reward Visualizer - Trade Management [Dots3Red]🎯 RISK/REWARD VISUALIZER — POSITION SIZER & OUTCOME TRACKER
A risk/reward calculator answers one question and then forgets it existed. Click three prices on your chart — entry, stop, target — and this tool draws the zones, sizes the position from your account risk, and shows the ratio plainly. But it also remembers. Every plan you set is tracked to its actual outcome, building a real record of how your own planning has played out over time.
✨ WHY THIS MATTERS
This script treats every set of levels you draw as a real plan worth remembering — not just a static suggestion.
📊 Plans Resolved: 14W / 6L Hit Rate: 70% Total R: +9.2R
That's not a backtest of a strategy. It's a running record of the actual entry/stop/target combinations you personally set on this chart and what genuinely happened to each one afterward.
⚙️ HOW IT WORKS
🖱️ Click-to-place levels — Entry, Stop Loss, and Target are set by clicking directly on the chart rather than typing numbers into a settings box. Direction is detected automatically: if your stop sits below entry, it's read as long; above entry, short.
💰 Position sizing from account risk — enter your account size and how much of it you're willing to risk per trade (as a percentage), and the script calculates exactly how large a position keeps that risk fixed regardless of how wide your stop is. The result is rounded to whatever step size fits your instrument — whole shares, or fractional units for crypto.
📏 Risk and reward zones — the space between entry and stop is shaded as your risk; the space between entry and target as your reward. Seeing both zones side by side on the chart makes a lopsided plan (all risk, little reward) visually obvious in a way a bare number doesn't.
🧾 Plan tracking — every distinct entry/stop/target combination is treated as its own plan. When price later reaches either level, the plan resolves:
• Target hit — counted as a win, and the actual R multiple achieved is added to your running total
• Stop hit — counted as a loss (–1R)
• Same-bar ambiguity (a single bar's range touches both stop and target) always resolves as a loss — the conservative, honest call when intrabar order can't be known
• Neither hit within the tracking window — dropped from the record entirely, counted as neither a win nor a loss
Setting new levels automatically starts a new plan; the previous one, if still unresolved, is simply dropped from active tracking without being force-graded.
🔒 Non-repainting — all outcome grading happens strictly on confirmed bars.
🧭 HOW TO USE
1️⃣ Set your account size and risk % first , before placing levels — this is what turns a simple price plan into an actual position size you can act on.
2️⃣ Click Entry, then Stop, then Target on the chart. The dashboard updates immediately with direction, R:R ratio, position size, and dollar risk/reward.
3️⃣ Use the zones to sanity-check the plan visually before committing — a reward zone that looks tiny next to a wide risk zone is worth reconsidering even if the calculated ratio technically clears your minimum.
4️⃣ Check your plan history periodically , not just the current plan. A single setup can look great in isolation; the accumulated hit rate and total R tell you whether your actual level-picking has been working over time.
5️⃣ Adjust the tracking window to match your typical hold time — a scalper and a swing trader need very different values for how many bars a plan should be given before it's dropped as inconclusive.
🛠️ SETTINGS
🎯 Trade Levels — Entry, Stop Loss, Target — each set by clicking on the chart
💰 Account & Risk
• Account Size, Risk per Trade (%) — drive the position size calculation
• Position Size Rounding — match this to your instrument's minimum tradable increment
🎨 Visualization
• Risk/Reward Zones, Level Labels — toggle independently
• Max Bars to Track a Plan — how long an unresolved plan stays active before being dropped
🖥️ Dashboard — show/hide, position — direction, R:R ratio, position size, dollar risk/reward, and the full plan history in one place
📝 NOTES
Only one plan is actively tracked for outcome purposes at a time — setting new levels while a previous plan is still pending drops that previous plan from the record without grading it, rather than running two plans in parallel. This is a planning and tracking tool: it does not know your actual fills, slippage, or whether you genuinely took the trade — it measures what price did relative to the levels you set, not your live trading result.
⚠️ DISCLAIMER
This is an analytical and visualization tool. It does not generate trade signals, does not execute trades, and does not constitute financial advice. Historical plan outcomes do not guarantee how any future plan will resolve. Indicateur

[Kpt-Ahab] Savings Plan IND Savings Plan Indicator
This indicator simulates and documents a complete savings plan directly on the TradingView chart. Deposits, dividends, purchases, sales, and costs are processed through a shared savings-plan account, making the cash balance and cash flow transparent and traceable.
Features:
- Initial capital with first purchase
- Regular deposits with optional periodic increases
- Fractional or whole units
- Automatic use of available cash when the regular DCA budget is insufficient to purchase the minimum tradable quantity
- Chart warning when a DCA purchase cannot be executed
- Four manual or adaptive DIP-buy levels
- Automatic profiles: Defensive, Balanced, and Aggressive
- Manual or automatic profit taking with trailing and cash rebalancing
- Minimum price increase required between two TP sales
- Transactions at the confirmed bar close or at the bar open
- Dividend processing
- Transaction, broker, custody, and dividend costs
- TradingView alerts for DCA, DIP, and TP events
- Detailed purchase and sale labels
- Marking of the highest profit point and the largest portfolio drawdown
- Full statistics table or compact mobile view
- Tables, labels, and alert messages in English, German, or French
The statistics include, among other values, deposits, cash balance, units held, cost basis, market value, portfolio value, realized and unrealized results, total costs, drawdowns, cumulative return, and the annualized return (XIRR).
Mobile Table
A reduced mobile view can be enabled for smaller screens. It displays the most important portfolio, return, drawdown, cost, and transaction information using shorter labels and smaller text.
Transaction and Alert Notes
With "Confirmed close", signals are triggered only after the bar has been confirmed at its closing price. On daily charts, the exchange may already be closed by the time the signal becomes available.
With "Bar open", the evaluation is performed at the opening price of the new bar. The Auto model uses only confirmed data from the previous bar. The opening price of the new bar is not necessarily identical to the previous closing price, for example when a price gap occurs.
The indicator does not place real orders. Automatic settings and historical results do not guarantee future performance and do not constitute investment advice.
Indicateur

Indicateur

Global Macro RegimeThe Global Macro Regime is a top-down macro nowcasting and portfolio allocation tool that provides a consolidated view of the market-implied macro regime. It independently evaluates 30 key global markets across equities, fixed income, commodities, and currencies to determine the prevailing macro regime, which informs the model’s portfolio preferences and regime-specific exposures. It also features built-in alerts and an integrated backtester that enable investors to monitor regime changes and evaluate asset performance across different macro environments.
At its core, the model aggregates 30 independent cross-asset market signals to identify shifts in the market’s growth and inflation outlook. Rather than relying on backward-looking economic data, the model derives these signals in real time from evolving trends across global markets. By focusing on growth and inflation, the model captures two of the primary macroeconomic forces driving asset prices. The four possible combinations of growth and inflation define four distinct macro regimes, each of which tends to favor different portfolio preferences and exposures:
Goldilocks (Growth ↑, Inflation ↓): Improving growth with low/declining inflation.
Reflation (Growth ↑, Inflation ↑): Improving growth with high/rising inflation.
Inflation (Growth ↓, Inflation ↑): Deteriorating growth with high/rising inflation.
Deflation (Growth ↓, Inflation ↓): Deteriorating growth with low/declining inflation.
Goldilocks and Reflation represent Risk-On regimes, while Inflation and Deflation represent Risk-Off regimes. Each of the 30 selected markets is evaluated independently as either a growth or inflation signal. Markets signaling improving growth contribute to both Goldilocks and Reflation, while markets signaling deteriorating growth contribute to both Inflation and Deflation. Markets signaling high/rising inflation contribute to both Reflation and Inflation, while markets signaling low/declining inflation contribute to both Goldilocks and Deflation. The selected markets are grouped into equities (10), fixed income (10), commodities (6), and currencies (4):
Equities = S&P 500 Index (SPX), Russell 2000 Index (RUT), STOXX Europe 600 Index (SXXP), Nikkei 225 Index (NI225), Hang Seng Index (HSI), MSCI Emerging Markets Index Futures (MME), High Beta / Low Volatility Ratio (SPHB/SPLV), Cyclicals / Defensives Ratio (XLY/XLP), S&P 500 Volatility Index (VIX), and 3M Implied Correlation Index (COR3M).
Fixed Income = US 2Y Treasury Yield, US 10Y Treasury Yield, German 10Y Bund Yield, UK 10Y Gilt Yield, Japan 10Y JGB Yield, US 10Y Breakeven Inflation Rate, US CCC Distressed Index Option-Adjusted Spread, US High Yield Index Option-Adjusted Spread, US Investment Grade Corporate Index Option-Adjusted Spread, and US Bond Volatility Index (MOVE).
Commodities = Brent Crude Oil Futures (BRN), Agricultural Commodities (DBA), Industrial Metals (DBB), Copper Futures (HG), Silver / Gold Ratio (SI/GC), and CME Bitcoin Futures.
Currencies = US Dollar Index (DXY), Australian Dollar / US Dollar (AUDUSD), British Pound / US Dollar (GBPUSD), and Euro / US Dollar (EURUSD).
Each market signal is derived independently using either a volatility-adjusted moving-average crossover, a volatility-based adaptive trailing stop, or a combination of both. The signals are then aggregated and normalized into percentage scores representing each regime’s share of total signals, with optional smoothing over the specified signal length to reduce noise. The regime receiving the greatest confirmation across global markets is identified as the dominant macro regime and translated into portfolio preferences displayed in the regime preference table:
Goldilocks Preferences = Risk-On > Risk-Off, High Beta > Low Beta, Cyclicals > Defensives, International < US Equities, SMID Caps < Large Caps, Short Rates > Long Rates, Spreads > Treasuries, High Yield > Low Yield, Beta FX > US Dollar, Metals > Energy, and Bitcoin > Gold.
Reflation Preferences = Risk-On > Risk-Off, High Beta > Low Beta, Cyclicals > Defensives, International > US Equities, SMID Caps > Large Caps, Short Rates > Long Rates, Spreads > Treasuries, High Yield > Low Yield, Beta FX > US Dollar, Metals > Energy, and Bitcoin > Gold.
Inflation Preferences = Risk-On < Risk-Off, High Beta < Low Beta, Cyclicals < Defensives, International < US Equities, SMID Caps < Large Caps, Short Rates > Long Rates, Spreads < Treasuries, High Yield < Low Yield, Beta FX < US Dollar, Metals < Energy, and Bitcoin < Gold.
Deflation Preferences = Risk-On < Risk-Off, High Beta < Low Beta, Cyclicals < Defensives, International < US Equities, SMID Caps < Large Caps, Short Rates < Long Rates, Spreads < Treasuries, High Yield < Low Yield, Beta FX < US Dollar, Metals > Energy, and Bitcoin < Gold.
The model further translates these portfolio preferences into specific exposures across equities, fixed income, commodities, and currencies. The selected exposures have been systematically backtested across the four macro regimes, dating back as far as January 1996, to identify those exhibiting the strongest risk-adjusted performance and most consistent directionally aligned trending behavior within each asset class. The resulting exposure lists provide a more granular view of the model’s broader portfolio preferences based on historically observed relationships:
Goldilocks Exposures = Equity sectors include Communication Services (XLC), Technology (XLK), Financials (XLF), Industrials (XLI), Consumer Discretionary (XLY), Materials (XLB), and Real Estate (VNQ). Equity factors include S&P 500 (SPY), Nasdaq 100 (QQQ), High Beta (SPHB), Momentum (MTUM), Quality (QUAL), Growth (IWF), and Value (IWD). Fixed income includes High Yield Bonds (HYG), Investment Grade Bonds (LQD), and Convertible Bonds (CWB). Commodities include Bitcoin (BTC), Industrial Metals (DBB), Metal Producers (PICK), Gold (GLD), Gold Miners (GDX), Silver (SLV), Silver Miners (SIL), Copper (CPER), Copper Miners (COPX), Uranium (SRUUF), and Uranium Miners (URNM). Currencies include Australian Dollar (FXA), British Pound (FXB), and Euro (FXE).
Reflation Exposures = Equity sectors include Energy (XLE), Communication Services (XLC), Technology (XLK), Financials (XLF), Industrials (XLI), Consumer Discretionary (XLY), Materials (XLB), and Real Estate (VNQ). Equity factors include Global Equities (ACWI), International Equities (ACWX), S&P 500 (SPY), Nasdaq 100 (QQQ), Emerging Markets (EEM), High Beta (SPHB), Mid Caps (IWR), Small Caps (IWM), Momentum (MTUM), Quality (QUAL), Growth (IWF), Value (IWD), Equal Weight (RSP), Global Infrastructure (IGF), and International Real Estate (IFGL). Fixed income includes High Yield Bonds (HYG), Convertible Bonds (CWB), Private Credit (BIZD), and Emerging Market Bonds (EMB). Commodities include Bitcoin (BTC), Commodities (DBC), Industrial Metals (DBB), Metal Producers (PICK), Crude Oil (USO), Agriculture (DBA), Agriculture Producers (VEGI), Gold (GLD), Gold Miners (GDX), Silver (SLV), Silver Miners (SIL), Copper (CPER), Copper Miners (COPX), Uranium (SRUUF), and Uranium Miners (URNM). Currencies include Australian Dollar (FXA), Canadian Dollar (FXC), British Pound (FXB), and Euro (FXE).
Inflation Exposures = Equity sectors include Energy (XLE), Consumer Staples (XLP), Utilities (XLU), and Health Care (XLV). Equity factors include Low Volatility (SPLV). Fixed income includes 1-3 Month Treasury Bills (BIL). Commodities include Commodities (DBC), Crude Oil (USO), Agriculture (DBA), and Gold (GLD). Currencies include US Dollar (UUP).
Deflation Exposures = Equity sectors include Consumer Staples (XLP), Utilities (XLU), and Health Care (XLV). Equity factors include Low Volatility (SPLV) and High Dividend (SPHD). Fixed income includes 1-3 Year Treasuries (SHY), 7-10 Year Treasuries (IEF), 20+ Year Treasuries (TLT), US Aggregate Bonds (AGG), Mortgage-Backed Securities (MBB), and International Aggregate Bonds (BNDX). Commodities include Gold (GLD). Currencies include US Dollar (UUP) and Japanese Yen (FXY).
The model includes a built-in alert system that notifies investors in real time when the dominant macro regime changes and provides the corresponding exposures for the new regime. It also features an integrated backtesting engine that can be enabled in the menu to evaluate asset performance across the macro regimes. Users can assign an asset to each regime, with the backtest automatically rotating into the corresponding asset whenever that regime becomes dominant. If one or more assets are assigned, any unassigned regimes are treated as cash. If no assets are assigned, the chart ticker is assigned to Goldilocks and Reflation, while Inflation and Deflation are treated as cash. The backtest reports the following performance metrics:
CAGR = Compounded Annual Growth Rate.
Excess = CAGR in excess of buy-and-hold.
Sharpe = CAGR per unit of standard deviation.
Sortino = CAGR per unit of downside deviation.
Calmar = CAGR relative to maximum drawdown.
Max DD = Largest peak-to-trough decline in value.
Alpha (α) = Excess annualized risk-adjusted returns.
Win Rate = Ratio of profitable trades to total trades.
Profit Factor = Total gross profit per unit of losses.
Expectancy = Average expected return per trade.
Turnover = Average annualized change in exposure.
The indicator is designed with flexibility in mind, allowing users to select the backtest period, signal methodology, preferred trend type, volatility type, and the individual markets included in the regime calculation. Supported moving-average types include the Exponential Moving Average (EMA), Simple Moving Average (SMA), Wilder’s Moving Average (RMA), and Weighted Moving Average (WMA). Supported volatility types include the Average True Range (ATR), Standard Deviation (SD), and Mean Absolute Deviation (MAD). The table follows an intuitive color-coded logic that allows for quick performance comparison against buy-and-hold (B&H):
CAGR = Green indicates above 0%, while red indicates below 0%.
Excess = Green indicates above 0%, while red indicates below 0%.
Sharpe = Green indicates better than B&H, while red indicates worse.
Sortino = Green indicates better than B&H, while red indicates worse.
Calmar = Green indicates better than B&H, while red indicates worse.
Max DD = Green indicates better than B&H, while red indicates worse.
Alpha (α) = Green indicates above 0%, while red indicates below 0%.
Win Rate = Green indicates above 50%, while red indicates below 50%.
Profit Factor = Green indicates above 2, while red indicates below 1.
Expectancy = Green indicates above 0%, while red indicates below 0%.
In summary, the Global Macro Regime is a comprehensive market-based macro framework designed to identify the prevailing macro regime. By combining 30 independent cross-asset market signals, the model translates the dominant macro regime into portfolio preferences and regime-specific exposures based on historical relationships that may not persist under future market conditions as market dynamics and asset-specific characteristics evolve over time. Historical coverage also varies across the 30 selected markets, with regime signals prior to 2006 based on progressively fewer markets and therefore requiring more cautious interpretation. Indicateur

Yearly & January High/Low + Midpoints
Yearly & January High/Low + Midpoints
This indicator plots key reference levels for price analysis: the yearly high, low, and midpoint for two configurable years (default 2024 and 2025), plus the high, low, and midpoint of a specific month (default January) across three configurable years (default 2024, 2025, 2026).
What it calculates:
Yearly High/Low — the highest high and lowest low printed within each selected calendar year, tracked bar-by-bar as the year progresses.
Monthly High/Low — same logic, restricted to a single month you choose (defaults to January, but any month works via the settings).
Midpoint — (High + Low) / 2 for each range above, calculated live from the tracked data rather than a fixed number, so it updates automatically if a new extreme prints.
How it's built: the script reads year(time) and month(time) on each bar to detect which calendar year/month it's in, then maintains a running max/min for that period using persistent (var) variables. Once a year or month is fully in the past, its high/low is final; the current year's numbers will keep updating live until that year closes.
On the chart: all levels plot as horizontal reference lines (color-coded per year), and a summary table (position configurable) lays out every High/Low/Mid value in one clean grid so you don't have to trace individual lines across a busy chart.
Settings: Year 1, Year 2, Year 3 (for the month-only row), target month, and toggles to show/hide the yearly lines, monthly lines, midpoints, floating labels, and the table independently.
Best used on: the Daily (1D) timeframe, since yearly/monthly aggregation needs enough historical bars loaded to compute correctly — on very short intraday timeframes it may not have enough chart history loaded to reach back to 2024. Indicateur

MYND Risk-Based Position Size Calculator [v1.5]MYND Risk-Based Position Size Calculator
A standalone position-sizing calculator with 3 selectable risk philosophies - Fixed % Risk, Van Tharp R-Multiple/Expectancy, and Kelly Criterion - plus an optional Break-Even Trigger, a 3-tier Partial Profit-Taking Ladder, a Losing-Streak Survivability estimate, a Risk:Reward Ratio readout, live milestone status tags, a live P&L row, and a ladder allocation check.
WHAT IT DOES
Answers "given my account, my entry, my stop, and my chosen risk philosophy, how many shares/contracts should I actually put on" - a calculator, not another chart signal.
HOW IT WORKS
Fixed % Risk is the industry-standard baseline: position size = (Account Equity x Risk%) / Stop Distance. Van Tharp R-Multiple/Expectancy uses the same math but gates it on a positive Expectancy first, computed from your own supplied Win Rate / Average Win (R) / Average Loss (R) via Van Tharp's textbook formula. Kelly Criterion computes a dynamic risk% from your supplied Win Rate and Win/Loss Ratio using the classic f* = p - q/b formula, applied within the same stop-distance sizing formula (a disclosed practitioner adaptation, not a literal full-bankroll wager), with a Kelly Fraction Multiplier (Half-Kelly by default) on top.
This tool has NO access to your actual trade history - it is not a strategy backtester. The Van Tharp, Kelly, and Losing-Streak Survivability inputs are numbers you supply from your own trading record.
KEY FEATURES
A live dashboard showing every step of the calculation, including live status tags and P&L. A Max Position Size safety cap always applied on top of whichever mode's raw output. Up to 7 reference lines plotted directly on the chart, each with an optional price label. Full Total Control, Light/Dark/Custom theme plus a Colorblind-Safe Okabe-Ito palette, full tooltip coverage on every non-obvious setting, and Combo Alert Bundling.
HOW TO USE IT
Set your Account Equity, Direction, Entry Price, and Stop Method. For an actual open trade, set a fixed Entry Price so Live P&L and the tags mean something. Start with Fixed % Risk if you don't have reliable win-rate/R-multiple stats yet. Check the Risk:Reward Ratio and Ladder Allocation Check rows as quick sanity checks. Turn on the Partial Ladder if you scale out of positions, and the Break-Even Trigger if you follow a move-to-break-even habit.
SETTINGS WORTH TUNING FIRST
Account Equity + Risk % of Equity Per Trade. Max Position Size (% of Equity). Entry Price - fixed vs. 0/live close. Risk % Warning Threshold. Partial Ladder Tier R-Multiples/%. Milestone Status Lookback (bars) - increase for trades held longer than 100 bars.
ALERTS
11 individual alertcondition()s (Negative Expectancy Warning, No Kelly Edge Warning, Position Capped by Max Size, Zero Stop Distance Warning, High Risk % Warning, Ladder Over-Allocated Warning, Break-Even Trigger Reached, Take-Profit Target Reached, Partial Ladder Tier 1/2/3 Reached) plus 2 combo bundles (ALL Risk Warnings, ALL Trade Management Milestones).
This tool does not evaluate whether any trade is a good idea - every number is a mechanical consequence of the inputs you provide, and the Van Tharp/Kelly/Streak-Survivability inputs are only as good as your own supplied historical stats. This tool is provided for informational and educational purposes and does not constitute financial advice. Trading involves risk; past performance and historical patterns do not guarantee future results. Indicateur

Institutional Asset Quality Radar [BigBeluga]Institutional Asset Quality Radar is a high-performance multi-asset diagnostic tool designed to visualize the structural health and risk-adjusted performance of up to five assets simultaneously. By projecting institutional-grade metrics into a dynamic radar geometry, the indicator allows traders to compare the "DNA" of different symbols beyond simple price action.
The goal is to provide a multi-dimensional view of quality—identifying which assets are fundamentally robust and which are driven by high-risk volatility.
🔵 CONCEPTS
The indicator evaluates assets across five core pillars, each normalized to a 0–100 score.
The Radar (Spider) Chart represents these scores as a polygon; a larger, more symmetrical shape indicates a well-rounded, high-quality asset, while a "pinched" or narrow shape reveals specific structural weaknesses.
To ensure the UI remains clean, the radar uses a non-scaling overlay and an advanced rendering engine that manages drawings dynamically, preventing "ghosting" or chart clutter.
🔵 THE FIVE PILLARS OF ASSET QUALITY
At the core of the radar are five performance dimensions used by institutional fund managers to assess portfolio components.
Annual Return: Measures the raw growth of the asset over a 365-day period.
30d Stability: The inverse of short-term volatility. Higher scores mean smoother, more predictable price action.
Sharpe Ratio: Measures risk-adjusted return. It answers: "Is the profit worth the stress?"
1Y Stability: The inverse of long-term volatility, identifying assets with consistent structural integrity.
Max Drawdown: Evaluates the "pain factor" by measuring the largest peak-to-trough decline over the past year.
Each axis label is interactive —hovering over a label (e.g., "Max Drawdown") will reveal a ranked tooltip showing the specific performance values for all selected assets in that category.
🔵 THE INSTITUTIONAL DASHBOARD
Complementing the visual radar is a high-density Performance Dashboard that provides a granular breakdown of each asset's status.
Asset Classification: Automatically categorizes assets into PREMIUM (High efficiency), STABLE (Reliable), or SPECULATIVE (High risk) based on their aggregate score.
Real-Time Ranking: Hovering over the axis labels on the chart triggers tooltips that show a ranked list (1st to 5th place) for that specific metric.
Color-Coded Analytics: The table highlights returns, stability, and drawdown using color thresholds to immediately flag underperforming or high-risk assets.
🔵 FEATURES
Horizontal Offset Control
You can now shift the entire radar left or right using the "Horizontal Offset" input. This allows you to push the radar into the "future" (the empty space to the right of the current bar) to keep your candles unobstructed.
Long-Term Scale Smoothing
The radar now uses a 100-period ATR calculation for its vertical scaling. This ensures the radar shape remains stable and consistent even during sudden, short-term price spikes.
Optimized Rendering Engine
The tool now utilizes an array-based drawing management system. It clears and redrawn only on the most recent bar, ensuring maximum performance and a flicker-free experience.
Best-in-Axis Identification
Automatically identifies and labels the "Winner" of each category at the tip of the radar axes in real-time.
Centroid Labeling
Calculates the mathematical center of each asset's polygon to place ticker labels, ensuring they are always readable even when multiple assets overlap.
🔵 HOW TO USE
Identify Relative Strength: Look for assets with a large "reach" toward the Annual Return and Sharpe axes while maintaining a wide base in Stability.
Spot Risk Outliers: An asset with a high return but a very low Max Drawdown score is a "momentum trap" that may be prone to violent reversals.
Portfolio Rebalancing: Use the dashboard to monitor when a "Premium" asset begins to decay into "Speculative" territory as its Sharpe ratio drops or volatility expands.
Benchmark Comparison: Load a benchmark (like BTC or SPY) as Asset 1 to see how other altcoins or stocks perform relative to the market leader.
🔵 CONCLUSION
Institutional Asset Quality Radar transforms abstract financial data into a tangible geometric form. By visualizing the relationship between return, risk, and efficiency, the indicator helps traders move beyond "price-only" analysis and focus on assets with the highest structural integrity. Indicateur

Micro Futures Risk / Reward Calculator [V2]Because “eh, three contracts feels about right” is not a risk-management strategy.
The Micro Futures Risk / Reward Calculator is a visual position-sizing tool designed for traders who want to know exactly how many micro futures contracts they can trade before clicking Buy or Sell and suddenly discovering a new emotion.
Set your maximum dollar risk, then drag the red Stop Loss line to where your trade idea is officially wrong. The indicator automatically calculates:
- Stop distance in points and ticks
- Dollar risk per micro contract
- Maximum contracts, always rounded down
- Actual total dollar risk
When applying to different charts you must go to the top left corner on the chart where you see the name of the script, click the ... icon and click reset points
A green draggable Take Profit line also calculates your live risk-to-reward ratio. Trade direction is inferred automatically: a stop below the current price represents a long setup, while a stop above it represents a short setup.
The calculator uses TradingView’s built-in contract information, including `syminfo.pointvalue` and `syminfo.mintick`, so it can adapt across supported USD-denominated micro futures instead of pretending every instrument is MNQ.
Safety checks warn about invalid contract data, incorrectly positioned targets, zero-distance stops, unsupported symbols, and trades where even one contract would exceed the selected risk.
This is an indicator only. It does not place orders, generate entries, predict the market, contact your broker, or stop you from moving your stop because “it’ll probably come back.”
Built for one simple question:
“My stop belongs here, I’m willing to risk this much—how many micro contracts can I trade?”
For educational and risk-management purposes only. Always verify contract specifications and order details before trading. Indicateur

Black-Litterman Allocator [BackQuant]# Black-Litterman Allocator
IMPORTANT: Concept / Educational Implementation
Black-Litterman Allocator is a research and educational concept that implements a practical version of the Black-Litterman portfolio-allocation framework inside TradingView and Pine Script.
It is intended to demonstrate how equilibrium priors, covariance estimates, subjective investor views, view confidence, mean-variance optimization, portfolio constraints, volatility targeting and portfolio backtesting can be combined into one visual allocation model.
It should not be interpreted as an institutional-grade portfolio optimizer, automated investment product, portfolio recommendation, or guarantee that the resulting allocation is optimal.
The outputs depend heavily on:
The selected asset universe.
The chart timeframe.
The covariance lookback.
The quality and synchronization of TradingView price data.
The chosen prior-weight scheme.
Risk-aversion assumptions.
The investor views entered by the user.
The confidence attached to those views.
Portfolio constraints.
Volatility-target settings.
Transaction-cost assumptions.
The optional regime filter.
The default universe and default views are examples for demonstrating the framework. They are not investment recommendations.
The script is best treated as a portfolio-allocation laboratory : a way to study how changing assumptions about equilibrium, risk, correlations and expected returns can propagate through a Black-Litterman-style allocation process.
Overview
Black-Litterman Allocator is a 15-asset cross-asset portfolio model that starts with a neutral portfolio prior, reverse-engineers the expected returns implied by that prior, optionally incorporates up to five investor views, solves for a new posterior allocation, applies portfolio constraints and volatility targeting, and then simulates the resulting portfolio through time.
The model follows a broad sequence:
Collect return history for the selected 15-asset universe.
Estimate an annualized covariance matrix.
Stabilize that matrix using diagonal covariance shrinkage.
Construct a prior portfolio.
Estimate the market risk-aversion parameter.
Reverse-optimize the prior into implied equilibrium returns.
Convert investor views into the Black-Litterman P, Q and uncertainty structure.
Blend the prior with those views to obtain posterior expected returns.
Optionally calculate posterior covariance.
Solve a mean-variance portfolio from the posterior.
Apply availability, short-selling, gross exposure and position-size constraints.
Target a desired portfolio volatility.
Apply additional leverage and gross-exposure caps.
Rebalance periodically.
Track the resulting equity curve and portfolio statistics.
The script also provides detailed visualizations showing:
Prior versus final active weights.
Equilibrium versus posterior expected returns.
The impact of individual views.
Current gross and net exposure.
Portfolio volatility and scaling.
Turnover.
Portfolio equity versus a benchmark.
Drawdown and daily returns.
A broad set of performance and risk statistics.
Why Black-Litterman exists
Traditional mean-variance optimization has an important practical weakness.
The optimizer is extremely sensitive to expected-return estimates.
Suppose several assets have similar volatility and correlation characteristics, but one asset is assigned an expected return only slightly higher than the others.
A mathematical optimizer can interpret that small difference very aggressively and allocate an unrealistic amount of capital to that asset.
Small estimation errors in expected returns can therefore produce very large changes in portfolio weights.
This is one reason unconstrained mean-variance portfolios often produce allocations that appear unstable or unintuitive.
The Black-Litterman framework was developed by Fischer Black and Robert Litterman as a way of approaching the problem from the opposite direction.
Instead of beginning with a set of independently estimated expected returns, the framework begins with an equilibrium portfolio and asks:
What expected returns would make this portfolio mathematically optimal?
Those implied returns become the prior.
Investor views are then introduced as controlled deviations from that equilibrium rather than replacing the equilibrium assumptions entirely.
This creates a useful distinction:
Prior = what the portfolio implies before the investor expresses a view.
Views = where the investor believes equilibrium is wrong.
Posterior = the combined result after balancing both sources of information.
That is the central idea behind this indicator.
Important distinction: the prior in this script
In textbook Black-Litterman, the equilibrium portfolio is often represented using market-capitalization weights.
This script is intentionally more flexible.
It provides three different prior schemes:
Equal Weight.
Inverse Volatility.
Manual Weights.
For that reason, the word equilibrium should be interpreted carefully.
If Equal Weight or Inverse Volatility is selected, the prior is a user-selected equilibrium proxy , not necessarily the true global market portfolio.
If Manual Weights is selected and the user enters representative market-cap or benchmark weights, the prior can be made closer to the traditional Black-Litterman interpretation.
This flexibility is intentional because TradingView users may want to study Black-Litterman mechanics without first sourcing a complete set of institutional market-cap weights.
Asset universe
The allocator supports fifteen simultaneously selected assets.
The default universe is designed as a broad cross-asset example containing:
Cryptocurrency.
US equities.
International equities.
Precious metals.
Energy.
The US dollar.
Long-duration Treasury exposure.
The default list includes assets such as Bitcoin, Ethereum, Solana, major equity indices, gold, silver, oil, DXY and TLT.
Every symbol can be replaced by the user.
This allows the framework to be adapted to:
Global macro portfolios.
Equity-sector portfolios.
Cryptocurrency portfolios.
ETF portfolios.
Multi-asset portfolios.
However, all assets should represent actual price series .
Market-capitalization series, synthetic quantities or unrelated non-price data should not be inserted as if they were tradable asset prices, because the resulting returns would contaminate the covariance matrix and portfolio calculations.
Data availability protection
A multi-asset allocator has a specific problem when some assets have shorter histories than others.
Suppose fourteen assets have ten years of data but the fifteenth asset was only listed six months ago.
If missing values are simply converted into zeros, the new asset may appear to have:
Almost no volatility.
Artificially stable returns.
Artificial correlations.
This is especially dangerous when using inverse-volatility weighting, because an asset with incorrectly measured near-zero volatility could receive a very large prior allocation.
The script protects against this by maintaining a separate data-availability state for every asset.
An asset is only admitted into the active universe once it has accumulated at least one complete covariance lookback of valid price history.
Until then:
Its active mask remains disabled.
It receives no prior weight.
It receives no optimized weight.
Views referencing it are ignored.
The allocation table displays it as having no usable data.
This makes the universe dynamic.
A newly listed asset can eventually become active once enough genuine history has accumulated.
Return calculations
The allocator uses two forms of return data for different purposes.
Log returns
Log returns are used for covariance estimation:
Log Return = ln(Price / Previous Price)
These are stored in a rolling history matrix.
Simple returns
Simple returns are used when compounding the simulated portfolio:
Simple Return = Price / Previous Price - 1
This distinction is deliberate.
Log returns are convenient for statistical covariance calculations, while simple returns are appropriate for directly multiplying portfolio wealth through time.
Rolling return-history matrix
The script maintains a rolling matrix containing return history for all fifteen assets.
Each row represents a historical bar and each column represents one asset.
Once the requested covariance lookback has been collected, the matrix acts as the input for the covariance engine.
Rather than recalculating years of historical data from scratch on every bar, the script operates the history as a rolling buffer.
The full Black-Litterman calculation is also performed only on rebalance events rather than continuously.
This is important because:
Covariance estimation is computationally expensive.
Matrix multiplication is expensive.
Matrix inversion is expensive.
TradingView imposes execution limits.
The indicator therefore approximates how a real asset-allocation process is normally operated: weights remain relatively stable between scheduled portfolio reviews and are recomputed at discrete intervals.
Covariance matrix
The covariance matrix is one of the central inputs to the entire model.
For N assets, covariance produces an N × N matrix.
The diagonal contains the variance of each asset.
The off-diagonal entries contain covariance between pairs of assets.
Conceptually:
Positive covariance means two assets tend to move in the same direction.
Negative covariance means they tend to move in opposing directions.
Covariance near zero suggests weaker linear co-movement.
The portfolio does not consider the risk of each asset independently.
Instead, portfolio risk depends on:
Individual asset volatility.
Portfolio weights.
The covariance relationships between every pair of assets.
This is why diversification cannot be measured simply by counting positions.
Ten highly correlated assets may behave more like one large risk exposure than ten independent exposures.
Covariance Lookback
The Covariance Lookback controls how many bars are used to estimate the covariance matrix.
Shorter windows:
Adapt more quickly.
Reflect recent correlation changes.
Contain fewer observations.
Produce noisier covariance estimates.
Longer windows:
Provide more observations.
Create more statistically stable estimates.
Adapt more slowly when correlations change.
This parameter is particularly important when the number of assets is large relative to the number of observations.
With fifteen assets, an extremely short covariance window can create a poorly conditioned or nearly singular matrix.
That can make matrix inversion unstable and produce extreme portfolio weights.
Annualization
The covariance matrix is annualized using the Trading Days per Year input.
The script supports:
252 days.
365 days.
252 is generally appropriate for traditional financial markets operating primarily on weekdays.
365 may be more appropriate for a crypto-only daily portfolio.
Mixed universes require judgement because crypto trades continuously while many traditional markets do not.
The annualization setting affects:
Covariance.
Volatility.
Return statistics.
Risk-aversion estimates.
It should therefore be selected consistently with the universe and timeframe being studied.
Covariance shrinkage
Raw sample covariance matrices can be noisy.
This is particularly problematic when:
The lookback is short.
There are many assets.
Several assets are highly correlated.
Market relationships change rapidly.
The script applies a simple fixed-coefficient shrinkage toward a diagonal covariance target.
The diagonal variances are retained.
The off-diagonal covariance terms are multiplied by:
1 - Shrinkage
Therefore:
Shrinkage = 0
leaves the sample covariance relationships largely unchanged.
Shrinkage = 1
removes the off-diagonal covariance terms and effectively treats the assets as uncorrelated for optimization purposes.
Intermediate values partially reduce estimated correlations.
This is best described as Ledoit-Wolf-style diagonal shrinkage , not as a full automatic Ledoit-Wolf estimator.
A true Ledoit-Wolf implementation estimates an optimal shrinkage intensity statistically.
Here, the user directly controls the shrinkage coefficient.
Why shrinkage can help
Portfolio optimization involves matrix inversion.
If covariance estimates are noisy, the inverse matrix can amplify those errors dramatically.
Shrinkage intentionally sacrifices some estimated correlation detail in exchange for greater numerical stability.
A moderate amount of shrinkage can therefore:
Reduce unstable allocations.
Reduce sensitivity to short-term correlation noise.
Improve matrix conditioning.
Too much shrinkage can also remove genuine diversification information.
The parameter is a bias-versus-variance trade-off.
Safe matrix inversion
Black-Litterman requires several matrix inversions.
Matrices can become singular or nearly singular when:
Assets are highly correlated.
Lookbacks are too short.
Data is incomplete.
The script checks whether the matrix is square and sufficiently non-singular before using a standard inverse.
When necessary, it falls back to a pseudo-inverse.
This does not magically make poor data reliable, but it prevents a singular matrix from immediately destroying the calculation.
A pseudo-inverse should still be interpreted cautiously because the underlying portfolio problem may be poorly conditioned.
Prior portfolio
Before Black-Litterman can estimate equilibrium returns, it requires a prior portfolio.
Three schemes are provided.
Equal Weight
Every active asset receives an equal allocation:
Weight = 1 / Number of Active Assets
This is the simplest prior.
It expresses no preference based on:
Market capitalization.
Volatility.
Expected return.
Its strength is simplicity.
Its weakness is that it assumes every asset deserves the same capital allocation regardless of risk.
Inverse Volatility
Inverse Volatility gives greater prior weight to assets with lower historical volatility.
Conceptually:
Raw Weight ∝ 1 / Volatility
The weights are then normalized.
This produces a risk-oriented prior rather than a capital-oriented prior.
Lower-volatility assets receive more weight.
Higher-volatility assets receive less.
This can be useful for diversified macro portfolios, but it has an important implication:
the quietest asset may dominate the prior.
For example, a bond or currency exposure may receive much more prior weight than cryptocurrency simply because its realized volatility is lower.
This is not a bug.
It is the direct consequence of using inverse volatility as the prior definition.
Manual Weights
Manual mode allows the user to enter fifteen raw numbers corresponding to the fifteen selected assets.
The entries are normalized automatically.
This means the values do not need to sum to 100.
The user can enter:
Percentages.
Market capitalizations.
Benchmark weights.
Relative notional values.
Only their proportions matter.
If the intention is to approximate traditional Black-Litterman market equilibrium, Manual Weights can be used to supply actual or approximate market-cap weights.
Reverse optimization
Once the prior weights are known, the model derives the returns that would make those weights consistent with mean-variance equilibrium.
The implied equilibrium excess-return vector is:
Pi = Delta × Sigma × Wprior
where:
Pi = implied equilibrium excess returns.
Delta = risk-aversion coefficient.
Sigma = covariance matrix.
Wprior = prior portfolio weights.
This is called reverse optimization .
Normal portfolio optimization asks:
Given expected returns, what weights should I own?
Reverse optimization asks:
Given the portfolio weights, what expected returns would justify owning them?
That reversal is one of the key ideas behind Black-Litterman.
Why implied returns matter
Expected returns are difficult to estimate directly.
Historical averages are noisy.
Forecast models disagree.
Small errors can create enormous portfolio changes.
Black-Litterman instead begins from a portfolio that the user considers a reasonable neutral starting point.
The model then backs out the expected returns consistent with that portfolio.
These implied returns become the equilibrium prior against which investor opinions are expressed.
Risk aversion: Delta
Delta controls the relationship between expected return and risk.
Higher Delta means:
Greater assumed aversion to risk.
A larger equilibrium return requirement for a given covariance structure and prior.
Lower Delta implies less risk aversion.
The script provides:
Auto (Implied).
Manual.
Manual Delta
Manual mode allows the user to directly select the risk-aversion coefficient.
This is useful when:
A stable assumption is preferred.
The user is reproducing an external Black-Litterman study.
The portfolio prior is known but a particular Delta is desired.
Auto Delta
Auto mode estimates Delta from the current prior portfolio.
The script estimates:
Prior portfolio variance.
An annualized return estimate over the covariance horizon.
The selected risk-free rate.
It then forms an implied risk-aversion estimate from excess return relative to variance.
The value is constrained to a practical range to prevent extreme estimates from destabilizing the optimizer.
This Auto mode is a practical implementation choice for the concept.
It should not be interpreted as a uniquely correct market risk-aversion estimate.
Tau: uncertainty in the prior
Tau is one of the most important Black-Litterman parameters.
It scales uncertainty in the equilibrium prior.
Conceptually:
Prior Uncertainty = Tau × Sigma
A smaller Tau implies stronger confidence in the equilibrium-return prior.
A larger Tau gives the model more freedom to move away from the prior when investor views are introduced.
In practical terms:
Smaller Tau
Makes the prior harder to move.
Reduces the effect of views.
Larger Tau
Increases prior uncertainty.
Allows views to exert more influence.
Tau should not be interpreted in isolation.
Its effect interacts with:
The covariance matrix.
View confidence.
View direction.
The number of views.
Investor views
The script supports up to five simultaneous investor views.
Each view contains:
A view type.
Asset A.
Optional Asset B.
Expected return Q.
Confidence.
Each view can be:
Off.
Absolute.
Relative.
The expected-return input is interpreted as an annualized expected return or annualized relative return .
Absolute views
An absolute view expresses an opinion about one asset.
For example:
“Asset A will return 10% annually.”
In matrix notation, the corresponding row of the P matrix contains:
+1 for Asset A.
0 for all other assets.
Q then contains:
0.10
for a 10% annual view.
Relative views
A relative view expresses one asset relative to another.
For example:
“Asset A will outperform Asset B by 5% annually.”
The corresponding P row contains:
+1 for Asset A.
-1 for Asset B.
0 elsewhere.
Q becomes:
0.05
This does not necessarily mean Asset A itself must return +5%.
It means:
Expected Return A - Expected Return B = 5%
Relative views are one of the most useful features of Black-Litterman because investors are often more confident about relative relationships than exact absolute returns.
It may be easier to hold the view:
“Gold will outperform equities.”
than:
“Gold will return exactly 12.4%.”
P matrix
The P matrix describes which assets each investor view references.
Each row corresponds to one active view.
Each column corresponds to one of the fifteen assets.
An absolute view creates one non-zero exposure.
A relative view creates a long-versus-short pair.
P therefore translates a verbal market opinion into portfolio mathematics.
Q vector
Q contains the expected return associated with each view.
For absolute views:
Q = expected annual asset return.
For relative views:
Q = expected annual outperformance of A relative to B.
The relationship:
P × Returns = Q
defines what the investor believes.
View confidence
Black-Litterman does not require every opinion to be treated as equally reliable.
Each view therefore receives a confidence value.
Confidence controls its uncertainty.
The basic principle is:
Low confidence = large view uncertainty.
High confidence = small view uncertainty.
The script converts intuitive percentage confidence into an Omega uncertainty term using a confidence mapping related to the Idzorek-style approach to expressing subjective confidence. User-specified confidence was developed precisely to make the otherwise difficult view-uncertainty input more interpretable.
Omega
Omega represents uncertainty in the views.
For each active view, the script first measures the variance of the corresponding view portfolio using:
P × TauSigma × P'
It then scales that variance according to confidence:
Omega = ((1 - Confidence) / Confidence) × View Variance
This has intuitive behaviour.
High confidence
If confidence approaches 100%:
(1 - c) / c approaches zero.
Omega becomes small.
The view receives substantial influence.
Low confidence
If confidence approaches zero:
(1 - c) / c becomes very large.
Omega becomes large.
The view has little effect.
The script bounds confidence away from exactly zero and one for numerical stability.
Why confidence matters
Suppose two investors both believe Bitcoin will outperform gold by 10%.
Investor A has 90% confidence.
Investor B has 20% confidence.
Their view Q is identical.
But their portfolio allocations should not necessarily be identical.
The confidence parameter allows the same directional opinion to produce very different posterior tilts.
This is one of the most useful parts of Black-Litterman.
It separates:
What you believe.
How strongly you believe it.
View disagreement: Q - PΠ
The Views table displays:
Q - PΠ
This measures how far the investor view differs from the equilibrium prior.
Suppose equilibrium already implies that Asset A will outperform Asset B by 8%.
If the user enters a relative view of 9%, the disagreement is only 1%.
The posterior may therefore change only slightly.
If the user instead enters 20%, the disagreement with equilibrium is much larger.
The same confidence level will then produce a much larger posterior adjustment.
This quantity is extremely useful because it shows that the impact of a view depends not only on the view itself, but on how different it is from what the prior already expects.
Posterior expected returns
Once P, Q and Omega have been constructed, the script calculates the Black-Litterman posterior expected-return vector.
Conceptually:
Posterior = Prior + Confidence-Weighted Adjustment
The full adjustment depends on:
Tau.
Sigma.
P.
Q.
Omega.
The disagreement Q - PΠ.
The model therefore does not simply overwrite the expected return of the named asset.
The adjustment can propagate across the entire asset universe through covariance relationships.
This is a fundamental feature of Black-Litterman.
If two assets are strongly related, a view about one may alter the posterior expectation of the other even if that second asset was not explicitly named.
Why views propagate
Suppose the user enters a strong bullish view on one equity index.
If several other equity indices are highly correlated with it, the covariance matrix tells the model that those assets are economically related.
The posterior adjustment therefore does not exist in isolation.
This means:
Views influence related assets.
Portfolio effects depend on covariance.
The same view can produce different tilts under different correlation regimes.
That behaviour is intentional.
No active views
If no usable views are active:
Posterior expected returns remain equal to the equilibrium prior returns.
The allocation is then driven by:
The prior.
Covariance.
Risk aversion.
Portfolio constraints.
Volatility targeting.
This makes the script useful even without discretionary views.
It can be used to study how the prior portfolio behaves under the optimization and risk-management layers by itself.
Posterior covariance
The script can optionally include the Black-Litterman posterior covariance adjustment.
Investor views introduce uncertainty about expected returns.
The posterior covariance calculation incorporates additional uncertainty associated with combining the prior and the views.
When enabled, the optimizer uses this adjusted covariance matrix.
When disabled, optimization uses the original covariance estimate.
The practical effect is usually more subtle than changing the expected-return vector, but it can affect:
Position sizes.
Diversification.
Volatility estimates.
View-driven tilts.
Portfolio optimization
After calculating posterior expected returns, the script solves a mean-variance allocation.
The unconstrained portfolio is conceptually:
w* = (Delta × SigmaPosterior)^-1 × PiPosterior
This converts posterior return expectations and covariance into portfolio weights.
If:
There are no views.
The prior and covariance are internally consistent.
No constraints alter the result.
the solution tends toward the prior portfolio.
Views create deviations away from that starting point.
Why unconstrained weights can be extreme
Mean-variance optimization can produce very large positive or negative positions.
This happens because matrix inversion magnifies differences between:
Expected returns.
Volatility.
Correlations.
If two assets are highly correlated but have slightly different expected returns, the optimizer may create a large long position in one and a large short position in the other.
Mathematically this can be valid.
Practically it may be unusable.
The script therefore applies several layers of portfolio constraints after the raw solution.
Data mask
Assets without sufficient price history receive zero weight regardless of what the raw optimizer produces.
This prevents incomplete covariance columns from entering the live portfolio.
Long-only mode
When Allow Short Weights is disabled:
All negative optimizer weights are clipped to zero.
The remaining positive positions are then normalized.
This converts the portfolio into a long-only allocation.
The result is no longer the exact unconstrained analytical Black-Litterman solution.
That is expected.
Real portfolios frequently require constraints that alter the theoretical optimum.
Short-enabled mode
When shorting is enabled, negative posterior weights are permitted.
This allows:
Long-short portfolios.
Relative-value expressions.
Negative allocations to assets receiving sufficiently weak posterior expectations.
Gross exposure becomes especially important in this mode because a portfolio can have low net exposure while still carrying substantial absolute risk.
For example:
+150% long.
-50% short.
= 100% net exposure.
= 200% gross exposure.
Gross Exposure
The Gross Exposure input controls the target sum of absolute portfolio weights before volatility targeting.
Gross exposure is:
Gross = Sum of |Weight|
This differs from net exposure:
Net = Sum of Weight
For long-only portfolios, gross and net are normally similar.
For long-short portfolios, they can differ significantly.
Volatility targeting
After the portfolio has been normalized, the script estimates total portfolio volatility using:
Portfolio Variance = w' × Sigma × w
Portfolio Volatility = sqrt(Portfolio Variance)
This is a full covariance-aware portfolio volatility calculation.
It does not simply average asset volatility.
The model then calculates a volatility scaling factor:
Volatility Scale = Target Volatility / Estimated Portfolio Volatility
subject to minimum and maximum limits.
If estimated portfolio volatility is below target:
Exposure can increase.
If estimated volatility is above target:
Exposure is reduced.
Why portfolio volatility matters
Suppose two assets each have 20% volatility.
A 50/50 portfolio does not necessarily have 20% volatility.
If the assets are weakly correlated, portfolio volatility may be much lower.
If they are highly correlated, it may remain close to 20%.
Using:
sqrt(w'Σw)
allows the volatility target to account for diversification.
Target Volatility
Target Volatility defines the desired annualized risk level of the portfolio before later hard caps are considered.
Examples might conceptually include:
A lower target for a defensive multi-asset portfolio.
A higher target for a crypto-focused portfolio.
The setting is not automatically appropriate simply because the portfolio reaches it.
A volatility target does not account for:
Tail risk.
Liquidity.
Gap risk.
Regime changes.
Nonlinear derivatives.
It is one risk-control dimension.
Maximum volatility-target leverage
A very low-volatility portfolio can theoretically require enormous leverage to reach a high volatility target.
The Max Vol-Target Leverage setting prevents this.
For example, if the mathematical scaling factor is 6× but the maximum leverage is 3×:
The model uses no more than 3×.
This protects against explosive leverage during unusually quiet covariance estimates.
Maximum weight per asset
After volatility targeting, every individual position is subjected to a hard position-size cap.
This ordering is important.
If the position cap were applied before leverage scaling, the volatility scaler could simply increase the capped position again.
Applying the cap afterward ensures the final position magnitude cannot exceed the selected maximum.
For example:
Max Weight = 30%
means no individual position can remain above 30% after the volatility scaling stage.
Maximum gross exposure after volatility targeting
After individual caps are applied, the portfolio is also checked against a maximum total gross exposure.
If gross exposure exceeds that maximum, every position is scaled downward proportionally.
This provides a second portfolio-level safeguard.
The result is a hierarchy:
Generate raw Black-Litterman weights.
Apply long/short rules.
Normalize initial gross exposure.
Apply volatility targeting.
Cap individual positions.
Cap final gross exposure.
Why the target may not be reached
The volatility target is not guaranteed to be achieved exactly.
Suppose the model wants to increase portfolio exposure enough to reach 15% volatility.
If doing so would violate:
Maximum leverage.
Maximum asset weight.
Maximum gross exposure.
the constraints take priority.
The resulting portfolio may therefore have volatility below the requested target.
This is intentional.
Risk limits are allowed to override the target.
Rebalancing
The complete optimizer does not run on every bar.
The user selects a Rebalance Every N Bars interval.
For a daily chart:
Approximately 21 bars corresponds roughly to one trading month.
Longer rebalance intervals:
Reduce turnover.
Reduce computation.
Allow allocations to persist longer.
Shorter intervals:
React faster to new covariance and view conditions.
Increase turnover.
Increase computational load.
The covariance matrix and Black-Litterman solve run only on rebalance events.
Forced rebalances
Two events can trigger a solve outside the normal schedule:
The regime filter changes from CASH back to ACTIVE.
The number of assets with sufficient history changes.
This prevents the portfolio from waiting many bars before responding to a material change in state.
Regime filter
The script includes an optional regime filter based on the chart symbol.
The filter compares:
A fast EMA.
A slow EMA.
When the fast EMA is above the slow EMA:
Regime = ACTIVE
When the fast EMA is not above the slow EMA:
Regime = CASH
This filter applies to the chart symbol , not individually to the fifteen assets.
That distinction is important.
If the indicator is placed on SPX, the regime filter reflects SPX.
If it is placed on Bitcoin, it reflects Bitcoin.
The regime state therefore acts as a global risk-on/risk-off switch for the entire portfolio.
CASH regime
When the regime filter turns off:
The live asset weights are flattened to zero.
The strategy stops compounding asset returns while the regime remains inactive.
When the filter turns ACTIVE again:
A new Black-Litterman solve is forced immediately.
The user should therefore choose the chart symbol intentionally if the regime filter is enabled.
Regime filter limitation
A single chart-symbol EMA regime is an intentionally simple overlay on a much more sophisticated cross-asset model.
It should not be confused with a multi-asset economic-regime model.
It answers only:
Is the fast trend of the chart symbol above its slower trend?
The regime layer can have a very large impact on historical results.
Backtests with and without it are therefore testing materially different systems.
Transaction costs
The script calculates turnover on each committed rebalance:
Turnover = Sum of |New Weight - Previous Weight|
The selected transaction-fee rate is then applied to that turnover.
This is more realistic than assuming rebalancing is free.
However, the cost model remains simplified.
It does not separately model:
Bid-ask spread.
Slippage.
Market impact.
Short borrow fees.
Financing costs.
Taxes.
Different fee schedules by asset.
The fee input should therefore be treated as an approximate portfolio-level trading-cost assumption.
Important backtest implementation note
The current implementation charges transaction fees when a new active portfolio is committed during a rebalance.
The transition that flattens the portfolio when the regime filter enters CASH is not separately charged an explicit turnover fee in the current code.
Therefore, backtests using the regime filter may slightly understate transaction costs associated with risk-off exits.
This is one reason the script should be treated as a concept rather than a production execution simulator.
No-lookahead portfolio return handling
The portfolio return for the current bar is calculated using the weights that were already active before the current rebalance solve.
Only after that return has been calculated does a new set of weights become active.
This prevents the optimizer from using newly calculated current-bar weights to capture a return that occurred before those weights could have existed.
This ordering is essential for a meaningful historical simulation.
Prior versus posterior weight chart
One of the main visual components is the paired horizontal weight chart.
Each asset receives two bars:
Prior weight.
Final active portfolio weight.
The prior represents the selected equilibrium starting allocation.
The active portfolio reflects the portfolio after:
Views.
Optimization.
Short constraints.
Gross normalization.
Volatility targeting.
Position caps.
Final gross caps.
Therefore, the visible gap between the bars represents more than the mathematical Black-Litterman posterior alone.
It represents the complete practical allocation change from prior to final active book .
If the regime filter is currently in CASH, the live active weights may be zero.
This distinction is important when interpreting the chart.
Allocation table
The Allocation Table shows each of the fifteen assets with:
Prior Weight.
Post Weight.
Delta Weight.
Equilibrium Expected Return.
Posterior Expected Return.
Prior Weight
The allocation before investor views and final portfolio construction.
Post Weight
The current active portfolio weight after the complete optimization and risk-control process.
Delta Weight
The difference between the active weight and prior weight.
Positive values indicate the asset has been increased relative to the prior.
Negative values indicate it has been reduced.
Equilibrium E
The implied return derived through reverse optimization.
Posterior E
The expected return after the active investor views have been incorporated.
Comparing equilibrium and posterior expected return is often more informative than looking only at weights.
A return expectation can change substantially while the final weight changes only modestly because:
The asset is highly volatile.
It is highly correlated with another holding.
The maximum-weight constraint binds.
Portfolio volatility limits exposure.
Views table
The Views Table shows each active view and includes:
View description.
Q.
Confidence.
Omega.
Q - PΠ.
This allows the user to inspect not only what the view says, but how strongly it conflicts with equilibrium and how uncertain it is.
Two views with identical Q values may have very different portfolio effects if:
Confidence differs.
Covariance differs.
Equilibrium expectations differ.
Current Book table
The Current Book table provides a compact summary of the active portfolio.
It includes:
ACTIVE or CASH regime.
Prior scheme.
Number of active views.
Number of rebalances.
Gross exposure.
Net exposure.
Number of live assets.
Turnover.
Risk-aversion Delta.
Tau.
Estimated portfolio volatility.
Volatility scaling factor.
This table is useful for diagnosing why the allocator currently looks the way it does.
For example:
Large view changes but small weights
may be explained by a tight volatility target or maximum-weight constraint.
Large gross but low net
may indicate significant long-short exposure.
Few live assets
means part of the universe has not yet accumulated sufficient historical data.
Equity curve
The script maintains a simulated portfolio equity curve beginning from the selected Initial Capital.
Initial Capital affects only the scale of the equity curve.
It does not affect:
Weights.
Sharpe ratio.
Volatility.
Portfolio optimization.
The equity curve compounds the historical portfolio returns generated by the active weights.
The line changes colour according to whether equity increased or decreased from the previous bar.
Benchmark Buy & Hold
A benchmark equity curve can be displayed beside the portfolio.
Both curves begin from the same nominal capital.
The benchmark is also used in:
Beta.
Alpha.
The benchmark can be changed independently from the fifteen-asset universe.
For meaningful interpretation, the benchmark should be relevant to the portfolio being studied.
A broad global macro portfolio compared only with SPX is answering a different question from an equity portfolio compared with SPX.
Daily returns
The script can optionally plot the portfolio’s per-bar percentage return.
This is useful for visually inspecting:
Return clustering.
Large gains.
Large losses.
Regime-filter cash periods.
Because it shares the pane with the equity curve, it is generally best viewed separately.
Rolling drawdown
Drawdown is measured relative to the previous portfolio-equity peak:
Drawdown = (Current Equity - Peak Equity) / Peak Equity
The result is negative while the portfolio remains below its historical high.
The visual fill becomes stronger as drawdown deepens.
The Max DD for Scaling input affects only the visual intensity scale.
It does not limit portfolio losses or modify the allocation.
Performance metrics
The metrics table includes a broad range of return and risk statistics.
Net Profit
Percentage change in portfolio equity from initial capital.
Maximum Drawdown
Largest historical peak-to-trough decline in the simulated portfolio.
Win Rate
Percentage of non-zero portfolio-return bars that were positive.
Flat CASH bars are excluded from the win/loss count.
This prevents periods where the portfolio is deliberately inactive from automatically being classified as losing periods.
Annual Mean Return
Arithmetic average per-bar portfolio return multiplied by the selected annualization factor.
This is not identical to CAGR.
Annual Standard Deviation
Per-bar return standard deviation scaled by the square root of the annualization factor.
Variance
Square of annualized standard deviation.
Sharpe Ratio
Measures annualized excess mean return relative to total return volatility using the selected risk-free rate.
Sortino Ratio
Measures return relative to downside-return variability rather than total volatility.
Omega Ratio
Compares the aggregate positive portfolio returns with the magnitude of aggregate negative portfolio returns.
Gain-to-Pain
Compares net return with the aggregate magnitude of negative returns.
CAGR
Compound annual growth rate based on beginning equity, ending equity and elapsed calendar time.
Calmar Ratio
CAGR divided by absolute maximum drawdown.
Beta
Measures covariance of portfolio returns with benchmark returns relative to benchmark variance.
Alpha
Estimates annualized portfolio return in excess of the return implied by its benchmark Beta and selected risk-free rate.
Skewness
Measures asymmetry of the historical portfolio-return distribution.
Positive skew indicates a longer or heavier positive tail.
Negative skew indicates a more pronounced negative tail.
VaR 95th Percentile
The implementation reports the fifth percentile of historical portfolio returns.
It can be interpreted as the lower-tail return threshold associated with approximately the worst 5% of observations.
It is displayed as a return value rather than converting the loss into a positive number.
Conditional VaR
Conditional VaR averages the returns in the lowest 5% tail.
This provides information about the average severity of outcomes beyond the VaR threshold.
Historical VaR and Conditional VaR rely entirely on the observed backtest sample.
They should not be interpreted as guarantees about future tail losses.
Risk-free rate
The selected Risk-Free Rate influences:
Sharpe.
Alpha.
Auto risk-aversion estimation.
Changing it therefore affects both reported performance statistics and potentially the portfolio itself when Auto Delta is enabled.
Understanding prior versus posterior
The most important conceptual visualization in the script is the difference between the prior and posterior state.
Suppose the prior allocation is:
Asset A: 20%
Asset B: 20%
Asset C: 20%
Asset D: 20%
Asset E: 20%
Now suppose the investor enters:
Asset A will outperform Asset B by 8%, with high confidence.
Black-Litterman does not simply add 8% weight to A and remove 8% from B.
Instead, the model asks:
What did equilibrium already imply about A versus B?
How uncertain is the prior?
How confident is the investor?
What is the covariance of the A-minus-B view?
How are A and B related to the rest of the portfolio?
The resulting posterior return adjustment then passes through the optimizer.
The final weights are subsequently modified by the portfolio constraints.
This explains why Black-Litterman allocations can behave very differently from manually applying arbitrary portfolio tilts.
Example: low-confidence relative view
Suppose equilibrium implies:
Expected A return = 8%
Expected B return = 7%
The equilibrium difference is 1%.
The investor believes:
A will outperform B by 5%
but assigns only 20% confidence.
The view disagrees with equilibrium, but Omega is relatively large because confidence is low.
The posterior therefore moves toward the investor view without fully accepting it.
Example: high-confidence relative view
Using the same equilibrium assumptions, suppose confidence is increased to 90%.
Omega becomes much smaller.
The investor view therefore carries much greater influence.
The posterior A-minus-B expected-return spread moves much closer toward the stated view.
The final weights may then shift significantly, subject to risk and portfolio constraints.
Example: view already priced into equilibrium
Suppose the user believes A will outperform B by 5%.
But the equilibrium prior already implies approximately 5%.
Then:
Q - PΠ ≈ 0
There is little disagreement to resolve.
Even a high-confidence view may produce only a small posterior adjustment.
This is an important property of the model.
Black-Litterman does not reward the user simply for entering a strong opinion.
The opinion must differ from equilibrium before it meaningfully changes the posterior.
Absolute versus relative confidence
Absolute views generally require greater confidence in the expected return level itself.
Relative views can be easier to interpret because the user only needs an opinion about the spread between two assets.
For example:
“Equities will return 14%.”
is a stronger forecasting statement than:
“Equities will outperform bonds by 4%.”
Neither is inherently superior.
The model supports both because portfolio managers frequently express views in both forms.
Why the model is useful conceptually
The value of Black-Litterman is not that it discovers the future.
It provides a disciplined method for converting beliefs into portfolio changes.
Without a framework, an investor may say:
“I like gold.”
“I am bearish equities.”
“Bitcoin should outperform bonds.”
but those statements do not specify:
How much the portfolio should change.
How volatility should affect the position.
How correlated assets should respond.
How conviction should change the allocation.
Black-Litterman forces those opinions into a structured portfolio context.
That is what this indicator is intended to demonstrate.
Important implementation difference from institutional Black-Litterman
The script implements the core Black-Litterman mechanics, but several choices are intentionally simplified for TradingView.
These include:
A fixed maximum universe of fifteen assets.
Up to five investor views.
User-selected fixed covariance shrinkage rather than automatically estimated shrinkage intensity.
Equal-weight and inverse-volatility priors in addition to manual market-style priors.
A simplified Auto Delta estimate.
Discrete bar-based rebalancing.
Simplified transaction costs.
A single chart-symbol regime filter.
Historical covariance from TradingView price data.
These choices make the model practical and interpretable inside Pine Script.
They also mean that results should not be compared directly with a production institutional implementation without understanding the differences.
Mixed-market data considerations
Cross-asset portfolios introduce data-alignment problems.
Cryptocurrency trades continuously.
Equities, commodities and bonds have market sessions and holidays.
Different TradingView symbols may also come from different exchanges or data providers.
The covariance matrix assumes the return observations are meaningfully aligned.
Users should therefore be careful with:
Intraday mixed-asset universes.
Assets from incompatible sessions.
Symbols with limited historical coverage.
Synthetic or non-tradable price series.
Daily or broader timeframes are generally easier to interpret for a macro allocation concept.
Backtest limitations
Historical simulation is useful for understanding behaviour, but this should not be treated as proof of future performance.
The backtest does not model every real-world implementation issue.
Examples include:
Bid-ask spreads.
Market impact.
Execution latency.
Portfolio financing.
Borrow availability.
Short borrow costs.
Taxes.
Different trading sessions.
Rebalancing at exact executable prices.
Changes in instrument availability.
Survivorship effects in a manually selected universe.
The model also uses historical covariance as an estimate of future covariance.
Correlations can change abruptly during stress periods.
The most diversified-looking portfolio based on historical data can become much more concentrated in risk when formerly independent assets begin moving together.
No automatic investment views
The script does not create investor views for the user.
Q and confidence are deliberately manual.
This is important because Black-Litterman is a framework for combining beliefs with equilibrium.
It does not tell the investor what those beliefs should be.
Views could theoretically come from:
Macro analysis.
Valuation models.
Momentum models.
Fundamental research.
Quantitative forecasts.
Discretionary judgement.
The quality of the posterior cannot exceed the quality of the assumptions provided to it.
Parameter interaction
Black-Litterman parameters should not be tuned independently.
Several important interactions exist.
Tau + Confidence
Both influence how aggressively views move the posterior.
Higher prior uncertainty combined with high view confidence can create strong posterior changes.
Covariance Lookback + Shrinkage
A short noisy covariance window may require more shrinkage for stability.
A long sample may tolerate less.
Target Volatility + Leverage Caps
A high volatility target may have little effect if maximum leverage or gross exposure is restrictive.
Views + Max Weight
A strong posterior preference for one asset may never appear fully in the active portfolio if the asset cap is binding.
Shorts + Gross Exposure
Allowing shorts can materially increase gross exposure even when net exposure looks conservative.
Rebalance Frequency + Fees
Frequent optimization allows faster adaptation but increases turnover and assumed trading cost.
Prior selection
The choice of prior is not cosmetic.
It changes the equilibrium return vector itself.
The same investor views can therefore produce different posterior portfolios depending on whether the starting prior is:
Equal Weight.
Inverse Volatility.
Market-like Manual Weights.
Users studying the framework should therefore treat prior construction as one of the primary model assumptions.
Suggested research workflow
A useful way to study the indicator is:
Begin with no investor views.
Choose a prior.
Observe the implied equilibrium returns.
Inspect the covariance-driven allocation.
Add one low-confidence relative view.
Observe Q - PΠ.
Compare equilibrium and posterior returns.
Increase confidence gradually.
Observe how the posterior and weights respond.
Add a second view.
Experiment with Tau.
Enable and disable posterior covariance.
Compare long-only and short-enabled portfolios.
Change the volatility target.
Observe when position or gross caps become binding.
This is generally more informative than immediately entering five aggressive views and trying to interpret the final result.
Example research questions
The allocator can be used to study questions such as:
How much does a 70% confidence view move the portfolio compared with 30% confidence?
How does inverse-volatility equilibrium differ from equal-weight equilibrium?
How does covariance shrinkage change portfolio concentration?
How do relative views propagate into assets not explicitly named?
How much does volatility targeting alter the raw optimizer?
How often do hard position caps bind?
How different are equilibrium expected returns from posterior expected returns?
How much turnover is generated by monthly versus weekly rebalancing?
How does a regime filter alter drawdown and opportunity cost?
These are the types of questions the concept is designed to explore.
Input guide
Initial Capital
Controls the starting dollar value of the simulated equity curve.
It does not change portfolio weights.
Trading Days/Year
Controls annualization.
Use a value consistent with the universe being studied.
Target Volatility
Sets the desired annualized portfolio-volatility target before hard leverage and weight constraints.
Transaction Fees
Approximate fee charged per unit of rebalance turnover.
Rebalance Every N Bars
Controls how frequently the full covariance and Black-Litterman solve occurs.
Allow Short Weights
Allows negative optimized weights.
Max Weight per Asset
Hard cap on individual position magnitude after volatility targeting.
Gross Exposure
Target absolute exposure before volatility scaling.
Max Gross After Vol Target
Final portfolio-level ceiling on gross exposure.
Max Vol-Target Leverage
Maximum scaling multiplier permitted by volatility targeting.
Covariance Lookback
Historical window used for covariance estimation and minimum data availability.
Covariance Shrinkage
Reduces off-diagonal covariance estimates toward zero.
Tau
Controls uncertainty in the equilibrium prior.
Use Posterior Covariance
Allows view uncertainty to modify the covariance matrix used by the optimizer.
Risk Aversion
Selects automatically estimated or manually specified Delta.
Prior Weight Scheme
Selects Equal Weight, Inverse Volatility or Manual Weights.
Investor Views
Supports up to five annualized absolute or relative return views.
Confidence
Controls the uncertainty assigned to each view.
Start Date
Defines the beginning of simulated portfolio equity.
Historical data before the date may still be used to warm up covariance estimates.
Risk-Free Rate
Used in portfolio statistics and Auto Delta estimation.
Benchmark
Used for the buy-and-hold comparison, Alpha and Beta.
Regime Filter
Optional chart-symbol fast/slow EMA filter that moves the portfolio between ACTIVE and CASH.
Prior vs Posterior visualization
Displays the difference between the selected prior allocation and current final portfolio weights.
Strengths
Implements the central Black-Litterman prior-and-views framework directly in Pine.
Supports both absolute and relative investor views.
Allows confidence to directly control view uncertainty.
Uses a complete cross-asset covariance matrix.
Includes diagonal covariance shrinkage.
Supports dynamic asset-data availability.
Provides equal-weight, inverse-volatility and manual priors.
Supports long-only and long-short allocation.
Uses covariance-aware portfolio volatility targeting.
Includes individual and portfolio-level exposure constraints.
Accounts for rebalance turnover fees.
Provides extensive allocation, view and portfolio diagnostics.
Includes a visual prior-versus-final-weight comparison.
Includes portfolio equity, benchmark and risk statistics.
Limitations
This is a concept and educational implementation, not an institutional portfolio-management system.
Historical covariance is only an estimate of future relationships.
The 15-asset universe is fixed in size.
A maximum of five views can be entered.
The prior is only a true market-equilibrium proxy if the selected weights appropriately represent one.
Equal Weight and Inverse Volatility are practical prior substitutes rather than literal global market-cap equilibrium.
The shrinkage coefficient is user-selected rather than statistically estimated.
Auto Delta is a practical approximation.
Portfolio optimization remains sensitive to inputs.
Poor views can produce poor posterior estimates.
High-confidence incorrect views can materially damage the portfolio.
Volatility targeting does not protect against all forms of risk.
Historical volatility can underestimate future crisis volatility.
Hard constraints mean the final portfolio may differ substantially from the analytical unconstrained Black-Litterman optimum.
The final volatility target may not be reached when position, leverage or gross limits bind.
The regime filter is based only on the chart symbol.
The backtest uses simplified transaction costs.
Regime-driven exits to CASH are not separately charged an explicit turnover fee in the current implementation.
Mixed-market TradingView data can contain differing sessions and histories.
Backtested performance does not establish future performance.
Historical and theoretical context
The Black-Litterman framework was developed to address practical problems encountered when applying mean-variance optimization to global portfolios.
Its central contribution is not simply another optimization equation.
It is a different way of constructing expected returns.
Instead of requiring the investor to estimate every asset’s return independently, equilibrium returns provide a coherent starting point. Investor views then alter only the parts of that equilibrium where the investor has an opinion.
This structure can be summarized as:
Start neutral.
Reverse-engineer equilibrium.
State where you disagree.
State how strongly you disagree.
Let covariance propagate those beliefs.
Re-optimize the portfolio.
The original Black-Litterman work emphasized equilibrium as a neutral starting point and allowed investor opinions about absolute or relative performance to tilt that equilibrium according to confidence.
Later work on user-specified confidence made the view-uncertainty problem easier to interpret by expressing conviction in intuitive percentage terms rather than requiring users to manually specify an abstract uncertainty covariance for every view.
This indicator takes those principles and translates them into a practical TradingView research environment.
Summary
Black-Litterman Allocator is an experimental portfolio-allocation framework designed to demonstrate how equilibrium, investor beliefs and portfolio risk can be combined inside TradingView.
The model begins with fifteen selectable assets and estimates their annualized covariance structure using historical log returns. A user-controlled shrinkage process reduces noisy cross-asset covariance estimates, while assets without sufficient historical data are excluded until a complete covariance window becomes available.
The user then selects an Equal Weight, Inverse Volatility or Manual prior portfolio.
That prior is reverse-optimized into implied equilibrium expected returns:
Pi = Delta × Sigma × Prior Weights
Up to five absolute or relative investor views can then be introduced.
Each view specifies:
What the investor expects.
Which assets the view applies to.
How confident the investor is.
Confidence is translated into view uncertainty, allowing weak opinions to create small tilts and high-confidence opinions to exert greater influence.
The Black-Litterman posterior combines those views with equilibrium while accounting for covariance relationships across the entire portfolio.
The resulting posterior expected returns are converted into an optimized allocation, after which the script applies:
Data-availability rules.
Optional long-only constraints.
Gross-exposure normalization.
Portfolio volatility targeting.
Maximum leverage.
Maximum position sizes.
Maximum gross exposure.
The portfolio is then rebalanced through time, transaction costs are approximated, an optional chart-level regime filter can move the book into CASH, and the resulting historical equity curve is compared with a selectable benchmark.
Extensive tables show:
Prior and final weights.
Equilibrium and posterior returns.
View confidence and uncertainty.
View disagreement with equilibrium.
Gross and net exposure.
Portfolio volatility.
Turnover.
Performance and risk statistics.
The purpose of the script is not to claim that Black-Litterman can identify the optimal future portfolio.
Its purpose is to make the framework tangible.
It provides a way to explore how a neutral portfolio can be translated into implied expected returns, how subjective beliefs can be incorporated without completely discarding that prior, how confidence changes the strength of those beliefs, how covariance spreads their effects across the portfolio, and how practical constraints can transform a theoretical posterior into a more realistic active allocation.
Treat the indicator as a concept, a research tool, and a visual implementation of portfolio-allocation theory rather than as an automated investment recommendation.
Indicateur

TURKS - Tiered Unit Risk Kernel StrategyTURKS decides how much of a long position to hold. Exposure is a graded function of where the close sits against four moving averages (20/50/100/200), so it moves in rungs rather than switching on and off. That function is monotone in price, which means it inverts: every rung has exactly one price. The panel prints those prices before they are reached — a ladder of levels at which the position gets larger or smaller, readable today.
Long-only, 0 to 1, no shorting and no leverage.
📊 THE RESULT
Twelve symbols, shipped defaults, 4-hour charts, full available history. Commission $1.50 per order, slippage 0.01xATR per side, idle cash credited nothing. b&h is buy-and-hold over the identical bars, charged nothing at all. The comparison is deliberately rigged against the strategy.
CAGR MAX DRAWDOWN CAGR / maxDD
symbol sample TURKS b&h TURKS b&h TURKS b&h
SNDK 1.3y +1406.3% +1899.0% -37.2% -56.8% 37.82 33.43
ETH 9.5y +117.3% +71.9% -54.4% -94.1% 2.16 0.76
BTC 9.5y +70.0% +54.2% -62.3% -83.9% 1.12 0.65
ARM 2.7y +62.5% +72.9% -39.8% -55.8% 1.57 1.31
TSLA 15.9y +32.7% +41.7% -57.0% -74.9% 0.57 0.56
NVDA 22.4y +25.3% +36.4% -77.0% -85.2% 0.33 0.43
AMD 21.4y +20.2% +17.3% -69.3% -96.1% 0.29 0.18
AVGO 16.8y +16.9% +39.0% -36.9% -50.3% 0.46 0.78
MU 22.4y +9.3% +19.7% -81.4% -90.9% 0.11 0.22
GOLD 13.5y +7.2% +7.7% -20.0% -35.0% 0.36 0.22
SPY 20.4y +4.4% +9.1% -40.5% -56.7% 0.11 0.16
INTC 20.4y +2.2% +8.5% -73.3% -74.2% 0.03 0.11
CAGR / maxDD is the column that settles it — return earned per unit of drawdown suffered. On that measure TURKS wins on 7 of 12. It cut maximum drawdown on 12 of 12, and beat buy-and-hold on raw return on 3.
▸ ETH — 117.3% against 71.9%, at −54.4% drawdown against −94.1%. Nearly double the return on barely half the pain.
▸ BTC — 70.0% against 54.2%, at −62.3% against −83.9%.
▸ AMD — 20.2% against 17.3%, turning a −96.1% hole into −69.3% across 21.4 years.
These are assets that spent their entire sample inside a historic bull market, measured against a benchmark paying no commission and no slippage. Halving a drawdown is ordinary. Halving it and finishing ahead is not.
BTCUSD 4h at the shipped defaults. The ladder is the green and red boxes; the envelope is the pair of curves around the mean. Bottom left is the BOOK panel reading 70.0% against 54.2% buy-and-hold at −62.3% drawdown against −83.9%, on 58.0% average exposure. Right side is the live state: what the rule targets now, where the next rung sells, where it buys back.
MU, SPY, TSLA and INTC are in that table because they were chosen to be difficult, and they behave exactly as the mechanism predicts. The rule sells strength and holds cash: it pays when a price path is violent relative to its drift, and it costs when the drift is high and the path is smooth. On a broad index it is the wrong tool — SPY 9.1% becomes 4.4%, and that number is in the table rather than left out of it.
📖 HOW TO USE IT
1 — Set your costs before you read anything. Commission ($ per order) and Typical position size ($) are the only two numbers the cost model needs; every other cost figure is a rate derived from them. A flat $1.50 is 1.9bp on an $8,000 position and 7.5bp on a $2,000 one. Leave these wrong and the panel lies to you.
2 — Pick the instrument. Single names and crypto whose drawdowns are violent relative to their drift. The table above is the guide, including the four rows that say don't.
3 — Read the ladder, not the arrows. The SELL / BUY ENGINE block prints three live numbers:
▸ Sell next above — the price at which the next rung comes off
▸ Buy back below — the price at which it goes back on
▸ Rungs sold — how much the envelope has already taken off, e.g. 12 of 20
Both prices exist now, before the move. They are not marks that appeared after one.
4 — Read the dial. The THE RULE block prints Target weight, which is what the rule says you should be holding at this instant, and Dial c / f. The POSITION block prints what you actually hold, your entry, your open return, and the round-trip cost you are currently carrying — so the gap between intention and position is always visible.
5 — Size it with c and f, not by fighting the rungs. c scales the whole position down. f is the floor you keep while the rule is off; raising it walks the book continuously toward buy-and-hold. Both tooltips print the measured frontier — the whole curve of what each step costs in return and buys in drawdown, including the region where the rule loses to simply holding less.
6 — Verify on your own symbol before trusting any of this. The BOOK panel prints Sample, CAGR against b&h, Max drawdown against b&h, CAGR/maxDD, Sharpe, Exposure and Turnover for whatever chart you are on, net of your own cost settings. Change the symbol and the whole table above regenerates for your instrument in one bar.
7 — Alerts. alert() messages ship on; JSON webhook format is a checkbox away.
🪜 HOW THE EXPOSURE IS SET
Exposure Shape picks the weighting rule. Ensemble 20/50/100/200 (graded) is the default: a slice is sold as the close drops below one more mean, bought back the same way, flat only below all four. Graded (continuous) uses one mean with an ATR ramp. Binary gate (legacy) is the original all-or-nothing rule.
Risk dial c scales the entire position down. Risk dial f is how much you keep while the rule is off. These two are the real levers, and nothing about their trade-off is hidden behind a paywall or a marketing claim — the full measured frontier is printed in the settings dialog.
Quantise Steps rounds the target to N reachable weights and requires price to clear 75% of a step before acting, so orders do not fire every bar. Ramp Width (xATR) sets how far above the mean price must travel to earn full size.
✂️ THE NADARAYA-WATSON SELL ENGINE
A trend weight cuts into weakness by construction, so it sells low: 59% of every unit the dial sells goes out below its own average cost, at 12.4 round trips a year. That is the flaw this block exists to fix. It replaces or constrains the sell side with a Gaussian kernel-regression envelope that only sells into genuine extension.
Sell Engine Mode — Dial, NWE-gated (default) keeps the dial's targets but forbids cutting while price sits below the smoother; it may still add. NWE band only turns the dial's sells off entirely. Dial + NWE (both cut) lets either one sell. Dial only leaves the envelope drawn but inert.
Sell Rungs is how much leaves on each upper-band cross: 1/N of the position. Going from 3 to 10 halved turnover, cut the share sold below basis from 16.7% to 8.9%, and pulled out-of-sample drawdown from −32.6% to −18.3%. It ships at 20, one step further along the same gradient; 10 is the last value with a formal table behind it.
Band Multiplier (3.0) and Buy-back Multiplier (2.5) set the upper and lower halfwidths in mean-absolute-deviation units. The asymmetry is the point: buying back nearer the mean than you sold restores the position before price has fully round-tripped, which is what keeps the overlay from bleeding in a chop. Bandwidth h widens and slows the smoother; it ships at 5.
🔬 HOW THIS WAS BUILT
Nine candidate signal families were tested against a matched-exposure control across 140 markets and 8,793 sessions: moving-average and momentum structure, cross-sectional relative strength, short-horizon mean reversion, volatility-of-volatility and regime transitions, drawdown state, volume, range compression, multi-timeframe agreement, and calendar seasonality. Not one was positive both in and out of sample. All nine were deleted from the codebase rather than left in as decoration.
The cleanest demonstration: take the original engine's own weight path and fire it 60 trading days late — same trades, same sizes, same turnover, same average exposure, only the dates broken. It scores better late than on time. Block-shuffling the path also beats it. A rule whose dates carry information cannot survive having them destroyed, so that engine was removed and what remains is geometry.
The stretch-proportional alternative to fixed rungs was then built and measured across 44 configurations. None beat rungs = 10. The project's pre-registered five-clause acceptance test passed all 20 graded cells — but a constant weight of 1.0 also passes three of five clauses, exactly one cell of twenty reaches p < 0.05 uncorrected (the null expectation for twenty tests), that p fails Bonferroni, and the cells are 0.985-correlated. It was reported as a failed test.
Everything left in this script survived a process designed to kill it. What remains is a sizing rule with no forecast in it: it does not predict the retest, it tells you at a price you can read now exactly what happens when one arrives.
⚙️ COSTS, AND THE SETTINGS THAT DECIDE THEM
Initial capital 150,000; commission $1.50 cash per order; no pyramiding; orders processed on bar close. Sell Engine Mode Dial, NWE-gated, Exposure Shape Ensemble 20/50/100/200 (graded), c = 1.00, f = 0.00, Quantise Steps 3, Ramp 1.0 ATR, Trend Mean 200, Cash Yield 0.00%. Envelope: bandwidth 5, multiplier 3.0, buy-back 2.5, MAE window 499, Sell Rungs 20.
TradingView's strategy() slippage is denominated in ticks, and a tick is an absolute price — one tick cannot be simultaneously correct for a $20 stock and a $1,600 one, nor for the same stock at $0.21 and at $224. It is therefore left at 0, and a proportional Slippage (xATR per side) input, shipped at 0.01, charges the cost in-script where it scales with the instrument.
Cash Yield ships at 0.00%. The rule spends much of its life partly in cash, so any yield credited lands straight on the CAGR, and one constant cannot represent a twenty-year sample where real cash paid about 0.1% for eight years and about 5% for two. Every figure in the table above was measured with it at zero.
Exits are close-only by construction — no strategy.exit, no stop=, no limit= anywhere in the shipped path, and nothing resting at a broker. The printed ladder is the memoryless level; the live quantiser is hysteretic, so the executed switch can sit up to 0.75 steps from the printed one.
© CREDIT
The envelope is a port of "Nadaraya-Watson Envelope " by LuxAlgo (www.tradingview.com), published open-source under CC BY-NC-SA 4.0. The kernel, the MAE band construction and the crossover logic are theirs. This script is published under the same licence.
Only the non-repainting, one-sided causal branch was ported. LuxAlgo's script defaults to the repainting branch, which rebuilds its curve inside barstate.islast with a two-sided kernel, so the value at bar i averages bars on both sides of i — including bars that had not happened when i closed. That branch is deliberately absent here. The measured gap between the two is about 21% of the band halfwidth, which is why the repainting version's arrows look cleaner than any live rule can be. The sizing, the rung logic and the position accounting are new.
Stratégie

Swing Portfolio Trim Dashboard v1.5**Swing Portfolio Trim Dashboard**
A technical portfolio-ranking tool designed for swing traders who typically hold positions for roughly **1–3 months** and need a systematic way to decide which holdings to trim, exit, hold, or continue riding.
The indicator is designed for portfolios containing many positions and focuses entirely on **price action, momentum, trend strength, volatility-adjusted performance, and technical deterioration** rather than fundamentals.
### Technical Score
Every holding receives a **0–100 Technical Score** based on:
* **10-day raw momentum — 5%**
* **20-day raw momentum — 10%**
* **50-day raw momentum — 15%**
* **10-day volatility-adjusted momentum — 2.5%**
* **20-day volatility-adjusted momentum — 7.5%**
* **50-day volatility-adjusted momentum — 15%**
* **10/20/50 EMA trend structure — 20%**
* **ATR-normalized trend health — 25%**
Raw momentum captures absolute leadership, while volatility-adjusted momentum helps normalize comparisons between securities with very different volatility profiles.
This is particularly useful when comparing ordinary stocks, ETFs, and higher-volatility instruments within the same portfolio.
### Portfolio Relative Ranking
Momentum components are converted into **cross-sectional percentile ranks relative to the other securities in the portfolio**.
A stock ranking highly therefore means it is technically stronger than most of the alternatives currently held.
**Tech#** represents this overall ranking:
* **#1 = strongest holding**
* Higher numbers = progressively weaker holdings
### Multi-Horizon Momentum
The model uses three time horizons:
* **10D** — short-term acceleration/deceleration
* **20D** — current swing momentum
* **50D** — broader swing trend
The shorter 10-day horizon receives less weight to reduce sensitivity to temporary price noise.
### Volatility Normalization
The dashboard uses realized volatility and ATR so that securities with very different volatility characteristics can be compared more fairly.
For example, a +10% move in a low-volatility ETF may represent much stronger risk-adjusted momentum than the same +10% move in a highly volatile leveraged product.
### Trend Score
Trend strength is evaluated using:
* Price above EMA10
* Price above EMA20
* Price above EMA50
* EMA10 above EMA20
* EMA20 above EMA50
* Rising EMA20
* Rising EMA50
A **Trend score of 100** represents a very strong and well-structured swing trend.
### ATR20
**ATR20** measures the stock's distance from its 20-day EMA in ATR units:
`(Price - EMA20) / ATR(14)`
Examples:
* **+2.0** = price is 2 ATR above EMA20
* **+0.2** = slightly above EMA20
* **-0.5** = modestly below EMA20
* **-1.0** = meaningful technical damage
* **-2.0** = severe deterioration relative to normal volatility
Using ATR allows the model to distinguish normal volatility from genuinely abnormal price deterioration.
### Score Deterioration
The dashboard tracks how Technical Score changes over time.
**Δ5**
`Current Score - Score 5 trading days ago`
**Δ10**
`Current Score - Score 10 trading days ago`
Negative values indicate deterioration.
For example:
`Δ5 = -12`
means the Technical Score has fallen 12 points during the last five trading sessions.
### RankΔ5
**RankΔ5** measures how the security's portfolio ranking changed during the last five sessions.
Negative values mean the stock is being overtaken by other holdings.
This can help distinguish between:
* a stock whose own technical condition is breaking down, and
* a stock that remains healthy but is losing relative leadership.
### Action Engine
Each security receives an Action classification:
**EXIT**
Severe technical weakness with confirmed longer-term trend damage.
**TRIM**
Weak portfolio ranking combined with confirmed EMA/ATR deterioration.
**TRIM WATCH**
A weak holding approaching or beginning a technical breakdown.
**DETERIORATING**
Momentum or relative ranking is deteriorating, but the underlying price trend has not yet broken enough to justify an automatic trim.
**HOLD**
Technical condition remains acceptable.
**RECOVERING**
A historically weak holding whose technical score is improving materially.
**LEADER**
A top-ranked holding with strong trend structure.
### Trim Priority
Technical Score and Trim Priority are deliberately separate.
**Technical Score** answers:
> How strong is this holding today?
**Trim Priority** answers:
> If I need to reduce positions, which holding deserves attention first?
Trim Priority combines:
* **65% current technical weakness**
* **25% 5-day score deterioration**
* **10% 10-day score deterioration**
However, the dashboard does **not** blindly rank positions by this number.
The Action Engine takes priority.
Sell-eligible states are considered first:
**EXIT → TRIM → TRIM WATCH**
Trim Priority then helps rank securities within those groups.
This prevents an improving laggard from being sold before a genuinely broken position.
### Trim# vs Tech#
The dashboard contains two different rankings:
**Tech#**
Ranks holdings from technically strongest to weakest.
**Trim#**
Ranks holdings according to which positions should be reviewed first when reducing exposure.
These numbers may differ substantially because Trim# also considers deterioration, trend damage, and recovery.
### SPY / QQQ Comparison
The Diagnostics view also displays relative 20-day performance versus:
* SPY
* QQQ
These values are informational and currently **do not affect the Technical Score**, allowing securities from different sectors and asset exposures to compete primarily on their own technical characteristics.
### Portfolio Management Use
The dashboard is designed to answer a practical question:
> If I own 30–40 positions and need to remove 3–4 names, where should I look first?
Rather than manually reviewing every chart, the trader can begin with the highest-ranked **EXIT / TRIM / TRIM WATCH** candidates and then examine the underlying technical evidence.
The indicator is calculated from **daily data** and is intended primarily for decisions made after the daily close rather than intraday trading.
The portfolio ticker list can be edited directly from the indicator settings, allowing holdings to be added or removed without rewriting the Pine Script.
**This indicator is a technical decision-support and portfolio-ranking tool. It is not financial advice and should not be used as a standalone trading or risk-management system.**
Indicateur

ATR Swing Stop Loss (Long)ATR Swing Stop Loss (Long) — Documentation
Purpose: Plots a trailing stop-loss line for long swing positions in Indian equities, based on Average True Range (ATR) volatility rather than a fixed percentage or arbitrary support level.
Core Logic
ATR Calculation — Measures 14-period average true range (Wilder's smoothing), capturing the stock's typical daily volatility.
Stop Level — Highest High (14 bars) − (ATR × 3.0). Anchoring to the recent high (not just current price) keeps the stop from tightening prematurely during a pullback within an uptrend.
Ratcheting — The stop only moves up, never down, as price makes new highs. This locks in gains as the trade progresses.
Reset on Breach — If a candle closes below the trailing stop, it's treated as a stop-out. The calculation resets fresh from that point (as if starting a new trade), and the line briefly turns red.
Inputs
Input Default Description
ATR Length 14 Lookback period for ATR and highest-high calculation
ATR Multiplier 3.0 Controls stop distance — lower = tighter stop, higher = more room
Show Info Table On Displays ATR value, stop price, and risk % in top-right corner
Show Stop-Hit Markers On Plots an "SL" cross marker when price closes below the stop
Visual Output
Orange line — active trailing stop
Red line/marker — stop was just breached (exit signal)
Info table — current ATR, stop level, and % distance from close to stop (useful for position sizing/risk calc)
Alerts
One built-in alert condition: "Long ATR Stop Hit" — fires when price closes below the trailing stop. Set this up via TradingView's Alert panel to get notified without watching the chart.
Usage Notes
Designed for daily timeframe swing trades; can be used intraday but multiplier/length may need adjustment for lower timeframes.
Works best on trending stocks — in sideways/choppy names it may whipsaw more often near the 3× ATR threshold.
Long-only. Does not track entry price or position size — it's a volatility-based exit reference, not a full position manager.
Not signal generation — this indicator does not tell you when to enter, only where to consider exiting once you're long.
Suggested Workflow
Add to your stock's daily chart alongside your entry signal/strategy.
Enter long per your own setup.
Use the plotted stop as your live stop-loss reference — adjust broker SL order as the line ratchets up.
Exit (or tighten manually) when the "SL" marker appears or your alert fires.
Indicateur

TP/SL Toolkit [AxeAlgo]OVERVIEW
TP/SL Toolkit is a fast/slow EMA crossover strategy built around a modular take-profit and stop-loss engine. The crossover logic is intentionally simple — it exists mainly to give the exit engine something to trade — because the real purpose of this script is the exit engine itself: every take-profit, stop-loss, trailing-stop, break-even, time-based-exit and trend-filter calculation is written as a small, self-contained Pine Script function with no dependency on the rest of the script.
That means any of these functions can be copy-pasted directly into your own strategy and used as-is, without pulling in anything else from this script. This publication is written and commented with that specific audience in mind — Pine coders who want ready-made, tested exit logic rather than another closed black-box signal.
═══════════════════════════════════════════════════════════════════════
WHAT THE STRATEGY DOES
A fast EMA and a slow EMA are calculated from the chosen source price. When the fast EMA crosses above the slow EMA (a "Golden Cross"), the strategy opens a long and closes any open short. When the fast EMA crosses below the slow EMA (a "Death Cross"), it opens a short and closes any open long. This is one of the oldest and most widely known trend-following patterns in technical analysis — it performs best while a market is trending and is prone to whipsaws (false signals) in sideways, choppy conditions. An optional ADX-based trend filter (explained below) exists specifically to reduce that weakness.
Every trade can optionally carry a take-profit and a stop-loss, calculated one of four ways, selectable from a single input:
- Points mode places the exit a fixed number of ticks from entry. The distance is constant in price terms regardless of how far price has moved, and is converted from "points" to real price using the symbol's minimum tick, so the same input behaves sensibly on instruments with very different price scales.
- Percentage mode places the exit a fixed percentage of the entry price away, so the distance automatically scales with price and stays comparable across symbols trading at very different price levels.
- ATR mode places the exit a multiple of the Average True Range away from entry, so exits automatically widen during volatile conditions and tighten during quiet ones instead of staying fixed.
- Pivot mode sets the stop-loss at the most recently confirmed swing high or low (market structure) and derives the take-profit as a risk:reward multiple of that stop's distance, mirroring how many discretionary traders place stops beyond structure. Because a pivot only confirms a fixed number of bars after it actually forms, this mode is inherently a few bars delayed relative to the live swing point — a stop placed at "the last pivot" was already that many bars old at the moment the trade opened. This is disclosed here because it affects how the backtest results for Pivot mode should be interpreted.
On top of the static take-profit/stop-loss, two independent stop-management mechanisms are available and can be combined:
- A trailing stop that recalculates every bar to sit a fixed distance (points, percentage, or ATR multiple — same three distance types as above) behind the best price reached since entry, and can only tighten in the trade's favor, never loosen.
- A break-even stop that sits still until the trade has moved favorably by a chosen trigger distance, at which point it jumps once to entry price (plus an optional small offset) and stays there or better from then on, so the trade can no longer turn into a loss once triggered.
When both are enabled, the script keeps whichever of the two is currently more protective on any given bar. On the chart, the take-profit and stop-loss are drawn as shaded zones (boxes) stretching from the entry price to the current bar rather than as flat lines — the stop-loss zone changes color once the break-even stop actually triggers, so a trade that has become risk-free is visually distinct from one still risking a real loss.
An optional time-based exit force-closes a trade that is still open after a configurable number of bars, instead of waiting indefinitely for take-profit or stop-loss to be hit.
An optional ADX trend filter withholds new entries while ADX is below a configurable threshold (i.e., while the market isn't trending strongly), which is the standard way to reduce EMA-crossover whipsaws in range-bound conditions. The filter only gates new entries — an already-open trade still closes normally on an opposite crossover regardless of the filter's state.
A compact on-chart status table (optional, position configurable) shows the current trend direction, position, entry price, take-profit, stop-loss, computed risk:reward, and ADX reading, so the trade's state is readable at a glance instead of having to trace colored zones back to their exact values.
═══════════════════════════════════════════════════════════════════════
HOW TO USE IT
As a strategy: pick a TP/SL mode, optionally enable the trailing stop and/or break-even stop, optionally enable the ADX trend filter, and run it through the Strategy Tester like any other strategy. Every input has an in-editor tooltip explaining exactly which mode it applies to.
As a toolkit: each exit mechanism — points-based, percentage-based, ATR-based, and pivot-based TP/SL, the trailing-stop updater, the break-even-stop calculator, the two-stop combiner, the time-based-exit check, and the ADX trend-filter gate — is written as an independent function with no external state, documented inline with what it takes in and what it returns. Any one of them can be lifted into another script without needing the rest of this one.
═══════════════════════════════════════════════════════════════════════
ALERTS
Two alert conditions are provided — a bullish crossover ("buy") signal and a bearish crossover ("sell") signal — both gated by the same trend filter used for actual entries, so an alert only fires when the strategy would genuinely take that trade.
═══════════════════════════════════════════════════════════════════════
BACKTESTING NOTES & DISCLAIMER
This script is published primarily to demonstrate and share reusable exit-management code, not as a ready-to-trade signal service or a claim of profitability. The default strategy settings do not model commission or slippage and use a fixed starting capital with no margin restriction — before drawing any conclusion from the Strategy Tester's results, set the commission, slippage, initial capital, and position sizing to values that realistically match your own broker/exchange and account size. Backtested and simulated results have well-known limitations (including curve-fitting and lack of live-market friction) and do not guarantee similar performance going forward.
Nothing in this script or its description constitutes financial advice. Trading involves substantial risk of loss and is not suitable for everyone. Past performance — simulated or real — is not indicative of future results. Test thoroughly on a paper/demo account before considering any live use, and use position sizing appropriate to your own risk tolerance.
═══════════════════════════════════════════════════════════════════════
Stratégie

Indicateur
