Индикатор

Индикатор

Индикатор

Индикатор

Trailing Drawdown Line Futures PropFirmsSee the exact price where your trailing drawdown gets hit — before it happens.
Built for futures prop-firm traders (Apex, Topstep, MyFundedFutures, Tradeify, BluSky and similar). Enter your firm's trailing DD size, your buffer at entry and your contract count, then click your entry point on the chart. The indicator draws your liquidation line — the price where the account would breach the trailing max drawdown — and ratchets it the way the firm actually does: it trails the implied equity peak at the FULL drawdown distance, and if you enter below your prior peak the line starts closer but does not move until price beats that peak.
Features
• Works on any futures symbol automatically — the contract's point value is read from the symbol (ES, NQ, MNQ, MES, GC, CL, ZB, …). Non-USD contracts (e.g. FDAX) display in their quote currency.
• Three trailing models: Intraday (trails every new high/low — real-time-trailing firms), Bar close, and End of day (EOD-trailing firms; needs an intraday or 1D chart).
• Live buffer readout — dollars and points left before the line — in a dark info table and an on-chart label.
• Breach is latched: once the line is touched the status stays BREACHED, because a trailing max-DD hit is terminal, not a temporary state. On historical bars the intraday model errs toward flagging (the path inside a bar is unknowable) — confirm on a lower timeframe.
• Lock support: enter the price where your firm freezes the DD (breakeven lock), or let the script derive it from your start balance + equity at entry. Status flips to LOCKED.
• Exit time: set it when you close the trade — the line and buffer freeze, because real DD levels stop moving while you're flat.
• Two alert conditions: buffer below warning level, and line touched.
How to use: add to chart → click your entry point → set contracts, firm DD size and buffer at entry (from your firm dashboard) → pick the trailing model that matches your firm → optionally create the two alerts. Re-anchor for every new trade.
Honest limitations: models ONE fixed-size position on THIS symbol. Scaling in/out or holding other instruments changes your real equity path and is not modeled. Anchor on a low timeframe (1–5 min) for precision. Educational risk-visualization tool — always confirm your firm's exact drawdown rule on their own site. Индикатор

Prop Firm Risk Guard I EonMetrics Prop Firm Risk Guard
Prop Firm Risk Guard is a risk dashboard and position size calculator for prop firm challenge and funded-account traders. It keeps the numbers that decide whether your account survives — the Daily Loss Limit, the Max Drawdown floor and the size of your next trade — on one screen, derived from one shared account state.
Stated plainly up front: TradingView cannot see your broker account. Your balance and today's P&L are MANUAL inputs — you type them in, the script does the limit math and the sizing math. Entry, Stop and Take Profit are also yours: the script never calculates or suggests any of them, it only draws the levels you decided on and does the arithmetic. The only live, price-driven element is the Entry/SL/TP lines and their cross alerts. No signals, no trade suggestions.
🔶 WHY ONE SCRIPT
A challenge usually fails through one compounding mistake: a trade sized without checking how much of today's loss allowance is actually left, so a routine stop-out becomes a daily breach. That check only works when the daily limit, the drawdown floor and the position size are computed from the same account state at the same moment — which is why they are one dashboard instead of separate tools you would have to cross-reference by hand. The last sizing row makes the link explicit: it compares one full stop-out against your remaining daily room and turns red BEFORE the trade if it doesn't fit.
🔶 WHAT IT DOES
Daily Loss Limit — enter your firm's daily loss % and its basis (starting or current balance). Today's P&L is a NET number, wins offset losses. Because firms word this rule two ways, both models are supported: Floor (the day has a fixed equity floor, so intraday profit adds room before it — the common model) and Hard Cap (the allowed loss is fixed, profit does not extend it). The table shows the remaining allowance in money and a status ladder: OK → CAUTION (50% used) → DANGER (80%) → BREACHED.
Max Drawdown — Static (floor fixed below the starting balance) or Trailing (floor follows the equity high-water mark). Shows the floor as an actual money level and the buffer above it, with the same status ladder.
Position sizing — risk per trade as % of balance or a fixed amount, planned entry (or live price) and stop. Returns the size in units, the forex conversion to 100k lots and the notional value. A Contract Multiplier input keeps the math correct on futures (e.g. ES = 50, GC = 100) as well as stocks, crypto and forex.
Take Profit (optional) — add your own TP price to see the R:R ratio and the money gain if it hits, using the same calculated size. If the TP sits on the wrong side of entry for your direction, the cell flags it instead of showing a meaningless ratio.
Entry / SL / TP lines — your levels drawn on the chart, with three alert conditions that fire when price crosses any of them.
🔶 HOW TO USE
1. Settings → Account: starting balance, current balance; high-water mark for trailing-drawdown firms (0 = auto).
2. Prop Firm Rules: copy the exact numbers and models from your firm's dashboard.
3. During the session, keep Today's P&L updated — the daily section only knows what you tell it.
4. Before a trade: set risk, entry and stop; read the size; make sure the last row is not red.
5. Optional: add a TP for R:R, and set alerts on the three price-cross conditions.
🔶 SETTINGS
Account (balances, high-water mark) · Prop Firm Rules (daily loss % + basis + Floor/Hard Cap, max drawdown % + Static/Trailing, profit target) · Today's P&L · Position Sizing (risk mode, entry/stop/TP, contract multiplier, lines toggle) · Table (position, text size).
This tool does the arithmetic of your firm's rules and your own trade plan. It does not know your account, does not predict anything and does not tell you what to trade.
Part of the EonMetrics toolset.
Индикатор

Индикатор

Индикатор

Индикатор

LWTG MITS Strategy**Title:** LWTG MITS Strategy
**Description:**
LWTG MITS (Multi-Indicator Trading System) is a rules-based mean-reversion and trend-following scoring engine designed for micro futures trading on prop firm accounts. It evaluates nine independent market conditions simultaneously and only enters a trade when a configurable minimum number of those conditions align — creating a high-confluence filter that reduces noise and improves signal quality.
**How the scoring system works**
Each bar, the script evaluates nine confluence factors across both long and short directions. Each factor that aligns with the potential trade direction adds one point to the score. A trade signal fires only when the score meets or exceeds the minimum threshold set in the inputs. The nine factors are:
1. **EMA Alignment** — Price relationship to short and long exponential moving averages confirms the directional bias
2. **VWAP Position** — Price position relative to the Volume Weighted Average Price filters entries against the intraday mean
3. **Momentum** — A custom momentum calculation confirms the strength of the current directional move
4. **Volume Confirmation** — Current bar volume relative to a rolling average confirms institutional participation
5. **Candlestick Pattern** — Engulfing and reversal patterns at key levels add a price action confirmation layer
6. **Volatility Filter** — ATR-based volatility measurement ensures entries occur in tradeable market conditions, not during dead zones
7. **RSI Filter** — Relative Strength Index prevents entries in overbought or oversold extremes where mean-reversion risk is highest
8. **ADX Filter** — Average Directional Index confirms sufficient trend strength before entry
9. **Market Regime** — A composite regime score (-6 to +6) derived from multiple timeframe analysis gates entries against the broader market direction. Counter-regime trades are blocked entirely
**Additional filters**
Beyond the nine confluence factors, the system includes:
- **Session time filter** — restricts trading to configurable intraday windows, avoiding low-liquidity periods
- **EOD cutoff** — automatically stops new entries before the end of the regular trading session
- **Session loss policy** — after a configurable number of consecutive losses, the system pauses entries for the remainder of the session
- **Daily loss limit** — blocks all new entries when cumulative session realized P&L drops below a configurable threshold
- **Trade direction control** — configurable to Long Only, Short Only, or Both
**Instruments**
Optimized and validated for micro futures: MES (Micro S&P 500), MNQ (Micro Nasdaq-100), M2K (Micro Russell 2000), and MGC (Micro Gold Futures). Each instrument has independently optimized default parameters.
**How to use this script**
This is the strategy version (v3.x). It uses TradingView's built-in strategy engine, which means it fires alerts on bar close and powers the built-in paper trading panel and strategy tester. It is designed to run alongside the companion indicator version (LWTG MITS Indicator) on the same chart.
Add the script to your chart, select the appropriate preset for your instrument in the inputs, and configure your minimum confluence score. The diagnostic panel on the chart displays real-time scoring, regime status, filter states, and session P&L.
Alert message format is JSON and is designed to integrate with automated order execution systems via webhook.
For full setup documentation, visit the companion GitHub repository linked in the author profile.
**Important:** This script is provided for educational purposes. All trading involves risk. Past performance does not guarantee future results. Always validate any trading system thoroughly before deploying with real capital.
Стратегия

LWTG MITS Indicator**Title:** LWTG MITS Indicator
**Description:**
LWTG MITS (Multi-Indicator Trading System) is a rules-based mean-reversion and trend-following scoring engine designed for micro futures trading on prop firm accounts. It evaluates nine independent market conditions simultaneously and only enters a trade when a configurable minimum number of those conditions align — creating a high-confluence filter that reduces noise and improves signal quality.
**How the scoring system works**
Each bar, the script evaluates nine confluence factors across both long and short directions. Each factor that aligns with the potential trade direction adds one point to the score. A trade signal fires only when the score meets or exceeds the minimum threshold set in the inputs. The nine factors are:
1. **EMA Alignment** — Price relationship to short and long exponential moving averages confirms the directional bias
2. **VWAP Position** — Price position relative to the Volume Weighted Average Price filters entries against the intraday mean
3. **Momentum** — A custom momentum calculation confirms the strength of the current directional move
4. **Volume Confirmation** — Current bar volume relative to a rolling average confirms institutional participation
5. **Candlestick Pattern** — Engulfing and reversal patterns at key levels add a price action confirmation layer
6. **Volatility Filter** — ATR-based volatility measurement ensures entries occur in tradeable market conditions, not during dead zones
7. **RSI Filter** — Relative Strength Index prevents entries in overbought or oversold extremes where mean-reversion risk is highest
8. **ADX Filter** — Average Directional Index confirms sufficient trend strength before entry
9. **Market Regime** — A composite regime score (-6 to +6) derived from multiple timeframe analysis gates entries against the broader market direction. Counter-regime trades are blocked entirely
**Additional filters**
Beyond the nine confluence factors, the system includes:
- **Session time filter** — restricts trading to configurable intraday windows, avoiding low-liquidity periods
- **EOD cutoff** — automatically stops new entries before the end of the regular trading session
- **Session loss policy** — after a configurable number of consecutive losses, the system pauses entries for the remainder of the session
- **Daily loss limit** — blocks all new entries when cumulative session realized P&L drops below a configurable threshold
- **Trade direction control** — configurable to Long Only, Short Only, or Both
**Instruments**
Optimized and validated for micro futures: MES (Micro S&P 500), MNQ (Micro Nasdaq-100), M2K (Micro Russell 2000), and MGC (Micro Gold Futures). Each instrument has independently optimized default parameters.
**How to use this script**
This is the indicator version (v4.x). Unlike the strategy version, this script uses Pine Script's alert() function to fire signals intrabar — before the bar closes. This results in earlier signal detection and tighter entry prices compared to bar-close execution.
This script is the live execution path for automated trading. It fires two alerts per chart: one for order execution via webhook to an automated broker integration, and one for trade logging to a Google Apps Script backend. It is designed to run alongside the companion strategy version (LWTG MITS Strategy) on the same chart — the strategy version handles paper trading and backtesting while this indicator handles live execution.
Add the script to your chart, select the appropriate preset for your instrument, and configure your minimum confluence score. The diagnostic panel displays real-time scoring, regime status, filter states, session P&L, and daily loss limit gate status.
Alert message format is JSON and integrates with automated order execution systems via webhook. Full webhook payload specification and GAS logging integration are documented in the companion GitHub repository.
For full setup documentation, visit the companion GitHub repository linked in the author profile.
**Important:** This script is provided for educational purposes. All trading involves risk. Past performance does not guarantee future results. Always validate any trading system thoroughly before deploying with real capital. Индикатор

Индикатор

Индикатор

Индикатор

[EWT] MA Extension Risk Stats MA Extension Risk Stats helps traders objectively measure how extended a stock, index, or any instrument is relative to its own historical behavior from a moving average.
Instead of guessing whether price “looks high,” this indicator calculates the percentage distance of every historical bar from a configurable SMA or EMA and then displays the Maximum, Mean, and Median deviations in a clean, updating table. By comparing the current deviation against these historical benchmarks, you get clear, data-driven context for profit booking decisions.
Key Benefits
Objective Extension Measurement: See exactly where the current price stands in the instrument’s historical distribution of moves away from its moving average.
Better Profit Booking Decisions: Know whether the current extension is normal, moderate, high, or near the historical maximum — removing emotion from scaling out of positions.
Risk Context at a Glance: Color-coded risk levels (Low / Moderate / High / Very High) combined with concise guidance help you quickly decide whether to book partial profits (30-50%) or exit most/all of a position.
All-History Perspective: Unlike rolling-window tools, this indicator uses the entire available dataset on your chart, giving you a complete picture across different market regimes.
Fully Customizable: Choose SMA or EMA, any period length, and position the compact table anywhere on the chart. The table automatically adapts to your light or dark chart theme for excellent readability.
Practical Use Cases
Trend Following & Swing Trading: When price stretches far above its MA during a strong uptrend, use the stats to scale out systematically instead of hoping for more upside.
Mean Reversion Setups: Identify when price has extended unusually far below its MA and prepare for potential bounces with better risk awareness.
Position Management: Apply consistent rules such as “book 50% when current deviation exceeds 1.5× median” or “exit fully when approaching historical maximum.”
Multi-Timeframe Analysis: Run it on daily charts for swing trades and weekly charts for positional decisions using the same logic.
Whether you trade stocks, indices, forex, or crypto, MA Extension Risk Stats gives you a professional, repeatable framework to manage extension risk and improve profit-taking discipline. It is especially valuable for traders who want to move from subjective “it looks extended” decisions to quantifiable, historically grounded rules.
Add it to your chart, adjust the MA period to match your style, and start making more confident, data-backed decisions on when to lock in profits. Индикатор

Индикатор

Индикатор

Income ETF vs Benchmark ComparatorCompare the performance of income/covered call ETFs (JEPI, JEPQ, QYLD, QQQI, XYLD, SPYI) against their benchmark ETFs (SPY, QQQ) to determine if income strategies outperform buy-and-hold.
Features:
Total Returns: Year-by-year and period total returns (price appreciation + dividends, non-reinvested)
Dividend Yields: Annual dividend percentages for both income and benchmark ETFs
NAV Decay: Measures underperformance of income ETF vs benchmark
Dividend Extraction Analysis: Shows hypothetical benchmark returns if you extracted the same dividends by selling shares
Sharpe Ratios: Risk-adjusted returns for performance comparison
Predefined Pairs: Quick selection of common comparisons or custom symbol input
Customizable Display: Adjustable table position and font size
How to Use:
Select a comparison pair (e.g., "JEPI vs SPY") or choose "Custom" to compare any two symbols
Also put the ticker in analysis in the chart and 1D time frame
Review yearly performance, dividends, and risk metrics in the table
Ideal for investors evaluating whether income ETF strategies justify their NAV decay compared to traditional index investing. Индикатор

Honest Trade PlannerHonest Trade Planner
On-chart position sizer & risk/reward planner. Place entry, stop, target — it sizes the trade so a single loss can't exceed your risk budget. Decision-support, not signals.
Honest Trader Toolkit — decision-support, not prediction. No signals, no forecasts, no win-rate claims. Just a correct read of what's actually on your chart.
The Honest Trade Planner turns a trade idea into a correctly sized order. You place your **entry**, **stop**, and (optionally) **target** on the chart; it shows you exactly how big to trade and precisely what you're risking — with the cross-asset math done right.
**What it does**
• Sizes a single trade from your **account size × risk %** and your **entry-to-stop distance**.
• Correct across **stocks, crypto, index, futures, and forex** — futures use the contract point value; forex reports both units and standard lots.
• Shows the full picture: **Risk $, Reward $, R:R ratio, position notional, and % of account** both risked and deployed.
• Optional **ATR-assisted stop** with an explicit Long/Short bias, so the distance math is never ambiguous.
• Draws a **risk zone** and a **reward zone** on the chart, plus a clean dashboard table.
**Honest by design**
• Position size is always rounded **DOWN** to your instrument's step — so your planned loss never sneaks past your risk budget. It will never round up to make a number look nicer.
• Money figures are shown in the symbol's **quote currency** (Pine can't read your broker, so account size is a manual input — convert if your account currency differs).
• On unsupported instruments or missing contract data it says **"verify contract specs"** rather than display a confidently wrong number.
• Bad inputs (zero account, entry = stop, target on the wrong side) **suppress** the nonsense output and tell you why. A low R:R is shown as information, never as a command to act.
**This tool does not predict anything and gives no buy or sell signals.** Every number is yours to act on or ignore — it only informs the decision you're already making.
**How to use**
1. Add it to any chart. You'll be prompted to click **Entry**, then **Stop** (both are draggable afterward). Set a **Target** in settings, or drag it, to get R:R.
2. Open settings → enter your **account size** and pick a **risk %** (0.25 / 0.5 / 1 / 2% or custom).
3. For fractional instruments (crypto, fractional shares) set the **Quantity step** (e.g. 0.001).
4. Read the dashboard. Drag entry/stop/target to plan different scenarios live.
**Limitations (so you know exactly what you're getting)**
• Pine cannot connect to your broker — account size and levels are manual inputs.
• Figures are in the symbol's quote currency.
• This is a planning and sizing tool, not financial advice. Always verify contract specifications for your instrument and broker before trading.
Open-source — read every line of the math yourself. Feedback welcome in the comments.
Индикатор

Lot Size Calculator KOANLot Size Calculator KOAN
Calculadora de tamaño de lote para operar CFDs de índices, pensada principalmente para el NAS100/US100. Muestra un panel fijo en el gráfico con el tamaño de lote exacto que debes operar para arriesgar solo el porcentaje o la cantidad de dinero que tú definas.
¿En qué instrumentos funciona?
Funciona en CFDs de índices cotizados en dólares (USD), siempre que configures correctamente el "Valor por punto por lote" según las especificaciones de tu bróker:
NAS100/US100 (Nasdaq 100)
US30 (Dow Jones)
SPX500/US500 (S&P 500)
US2000 (Russell 2000)
No está pensada para pares de forex tradicionales (EURUSD, GBPUSD…), ya que en forex el cálculo se hace en pips y el valor del pip depende del par; para eso existen calculadoras específicas de forex.
¿Cómo funciona?
El indicador calcula: Lot Size = Riesgo en $ / (Stop Loss en puntos × Valor por punto). Por ejemplo, con un balance de $2000, un riesgo del 1% ($20), un stop loss de 50 puntos y un valor de $1 por punto por lote, el resultado es un lote de 0.4. Así, si el precio toca tu stop loss, pierdes exactamente lo que habías decidido arriesgar, ni más ni menos.
Configuración:
Balance (USD): el capital total de tu cuenta. Es la base sobre la que se calcula el riesgo.
Modo de riesgo: elige cómo quieres definir tu riesgo por operación: como porcentaje del balance ("Porcentaje (%)") o como cantidad fija de dinero ("Dinero ($)"). El panel siempre muestra ambos valores, el que introduces y el que se calcula automáticamente.
Riesgo (%): porcentaje del balance que arriesgas por operación. Solo se usa si el modo es "Porcentaje (%)". Por defecto: 1%.
Riesgo ($): cantidad fija en dólares que arriesgas por operación. Solo se usa si el modo es "Dinero ($)".
Stop Loss (puntos): distancia de tu stop loss en puntos del índice. Ajústalo en cada operación según tu análisis.
Valor por punto por lote (USD): cuánto vale 1 punto de movimiento con 1 lote en tu bróker. En la mayoría de CFDs de NAS100 es $1, pero varía según el índice y el bróker. Revisa siempre las especificaciones del contrato (ver notas abajo).
Posición del panel: dónde se ancla el panel en pantalla (6 opciones: arriba/abajo, izquierda/centro/derecha). El panel es fijo: no se mueve al desplazar el gráfico ni al hacer zoom.
Color del panel: color de fondo del panel.
Color del texto: color del texto del panel.
Tamaño: tamaño del texto y del panel (Small, Medium, Large, XL).
Mostrar en el panel: casillas para elegir qué datos aparecen: Símbolo, Balance, Riesgo (%), Stop Loss, Valor por punto, Riesgo en $ y Lot Size. Desmarca lo que no quieras ver y el panel se compacta automáticamente.
Notas importantes sobre el "Valor por punto"
No todos los índices valen $1 por punto. El valor depende del tamaño de contrato de tu bróker. Ejemplo orientativo: en NAS100 suele ser $1 por punto por lote, pero algunos brókers manejan contratos de $10 o incluso $20 por punto, y en índices como el US30 o el SPX500 el tamaño de contrato también puede variar de un bróker a otro.
Cómo averiguar el valor en tu bróker: consulta las "especificaciones del contrato" del instrumento en tu plataforma (busca el dato "contract size" o "tamaño del contrato"). Otra forma práctica: abre una operación mínima en cuenta demo y observa cuántos dólares cambia tu P/L cuando el precio se mueve 1 punto; ese es el valor que debes introducir (escalado a 1 lote).
La definición de "punto" también puede variar entre brókers. Ante la duda, usa siempre el método de la cuenta demo descrito arriba.
Introduce el valor correcto en el campo "Valor por punto por lote (USD)" antes de confiar en el resultado. Si el valor es incorrecto, el tamaño de lote calculado también lo será.
El símbolo mostrado en el panel se detecta automáticamente del gráfico activo.
Este indicador es una herramienta de gestión de riesgo; no genera señales de compra o venta.
Verifica siempre los cálculos con tu bróker antes de operar con dinero real.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
ENGLISH VERSION
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Lot Size Calculator KOAN
Lot size calculator for trading index CFDs, designed primarily for the NAS100/US100. It displays a fixed panel on the chart showing the exact lot size you should trade to risk only the percentage or dollar amount you define.
Which instruments does it work on?
It works on USD-denominated index CFDs, as long as you correctly set the "Point value per lot" according to your broker's specifications:
NAS100/US100 (Nasdaq 100)
US30 (Dow Jones)
SPX500/US500 (S&P 500)
US2000 (Russell 2000)
It is not designed for traditional forex pairs (EURUSD, GBPUSD…), since forex calculations are done in pips and the pip value depends on the pair; there are dedicated forex calculators for that.
How does it work?
The indicator calculates: Lot Size = Risk in $ / (Stop Loss in points × Point value). For example, with a $2000 balance, 1% risk ($20), a 50-point stop loss and a point value of $1 per lot, the result is a lot size of 0.4. This way, if price hits your stop loss, you lose exactly what you decided to risk — no more, no less.
Settings:
Balance (USD): your total account capital. This is the base used to calculate your risk.
Risk mode: choose how you want to define your risk per trade: as a percentage of your balance ("Porcentaje (%)") or as a fixed dollar amount ("Dinero ($)"). The panel always displays both values — the one you enter and the one calculated automatically.
Risk (%): percentage of your balance risked per trade. Only used when the mode is set to percentage. Default: 1%.
Risk ($): fixed dollar amount risked per trade. Only used when the mode is set to money.
Stop Loss (points): your stop loss distance in index points. Adjust it on every trade according to your analysis.
Point value per lot (USD): how much 1 point of movement is worth with 1 lot at your broker. On most NAS100 CFDs it's $1, but it varies by index and broker. Always check your broker's contract specifications (see notes below).
Panel position: where the panel is anchored on screen (6 options: top/bottom, left/center/right). The panel is fixed — it doesn't move when you scroll or zoom the chart.
Panel color: background color of the panel.
Text color: color of the panel text.
Size: text and panel size (Small, Medium, Large, XL).
Show on panel: checkboxes to choose which data is displayed: Symbol, Balance, Risk (%), Stop Loss, Point value, Risk in $ and Lot Size. Untick what you don't want to see and the panel compacts automatically.
Important notes about "Point value"
Not all indices are worth $1 per point. The value depends on your broker's contract size. As a reference: on NAS100 it's usually $1 per point per lot, but some brokers use contracts of $10 or even $20 per point, and on indices like US30 or SPX500 the contract size can also vary from broker to broker.
How to find the value at your broker: check the instrument's "contract specifications" on your platform (look for "contract size"). A practical alternative: open a minimum-size trade on a demo account and watch how many dollars your P/L changes when price moves 1 point; that's the value you should enter (scaled to 1 lot).
The definition of a "point" can also vary between brokers. When in doubt, always use the demo account method described above.
Enter the correct value in the "Point value per lot (USD)" field before trusting the result. If the value is wrong, the calculated lot size will be wrong too.
The symbol shown on the panel is automatically detected from the active chart.
This indicator is a risk management tool; it does not generate buy or sell signals.
Always verify the calculations with your broker before trading real money. Индикатор

Индикатор

Optimal F by Ralph Vince. Position Sizing and Risk AnalysisEven a profitable strategy can produce weak results when position sizing is poorly calibrated. A position that is too small limits capital growth, while excessive exposure can turn an ordinary losing streak into a severe drawdown. MM: Optimal F analyzes the actual trade results of your strategy and identifies the historical risk level that produced the highest geometric capital growth.
The script implements the Optimal F concept developed by Ralph Vince. The method searches for the fraction of capital that maximizes the compounded result of the complete trade sequence, represented by Terminal Wealth Relative, or `G(f)`. Optimal F is not designed to maximize the profit of an individual trade. Its purpose is to optimize the long-term compounded growth of the entire system.
How the Script Works
The strategy must first be tested using a fixed position size of one contract or one unit of the traded instrument.
For every closed trade, the script calculates the financial result per contract. It then identifies the largest historical losing trade: Max Loss per Contract
Every trade is normalized relative to this loss: R = Profit per Contract / Max Loss per Contract
The script then tests values of `f` from 0.00 to 1.00 and calculates the following result for each value: G(f) = Π(1 + f × R)
A curve showing the relationship between `f` and `G(f)` is displayed on the chart.
The script reports four main values:
Best F — the value of `f` that produced the highest historical geometric growth.
Best G(f) — the maximum theoretical growth multiplier for the analyzed trade sequence.
Max Loss — the largest closed loss per contract.
Recommended Contracts — the calculated position size based on the current account equity.
The number of contracts is calculated using: Contracts = Equity × Selected F / Max Loss per Contract
Example:
Equity = 100,000
Selected F = 0.21
Max Loss per Contract = 9,775
Contracts = 100,000 × 0.21 / 9,775
Contracts = 2.15
For futures trading, the result is rounded down: 2 contracts
The table displays the value in the following format: 2 (2.15)
The first number is the whole-contract position size. The value in parentheses is the exact calculated position size before rounding.
What Optimal F Actually Means
A result such as: Best F = 0.21
does not mean that the strategy should enter a position using 21% of account equity as the nominal position value.
It means that the position size should be calculated so that a repetition of the largest historical loss per contract would represent approximately 21% of the current account equity.
For this reason, Optimal F cannot be replicated by simply setting:
Order size = 21% of equity
in the TradingView strategy settings.
The percentage of equity used as nominal position value and the percentage of equity exposed to the largest historical loss are different measurements.
Full F and Fractional F
Full Optimal F maximizes historical geometric growth, but it usually produces aggressive position sizing, large equity fluctuations, and deep drawdowns. It does not optimize equity-curve smoothness and does not impose a maximum drawdown limit.
Ralph Vince specifically discussed Half F, or 50% of the calculated Optimal F, as an attractive practical compromise. In his example, Half F reduced variability and expected drawdown by approximately half, although more trades were required to reach the same capital objective. He also noted that using a smaller fraction of Optimal F generally produces a smoother equity curve.
Example:
Best F = 0.21
Full F = 0.21
Half F = 0.105
Quarter F = 0.0525
Half F is calculated as:
Selected F = Best F × 0.50
This should not be treated as a universal rule. Half F is a more conservative starting point that can be compared with Full F and other fractional values.
How to Use the Script
1. Insert your own strategy code into the designated strategy section.
2. Disable: "Enable Optimal F Position Sizing"
In this mode, the strategy should be tested using one contract.
3. Verify that the following strategy properties are configured correctly:
Initial Capital
Commission
Slippage
Margin
These parameters directly affect trade results, the largest losing trade, and the calculated Optimal F.
4. Run the backtest and record:
Best F
Max Loss per Contract
Recommended Contracts
5. Select the fraction of Optimal F that you intend to apply:
Full F
Half F
Quarter F
A more conservative starting point is: Selected F = Best F × 0.50
6. Enter the selected value into: Optimal F
7. Enter the calculated maximum loss per contract into: Max Loss
8. Enable: "Enable Optimal F Position Sizing"
The strategy will now dynamically recalculate its position size before every new trade using the current account equity.
9. For futures trading, enable: Rounds contracts number
The calculated position size will be rounded down to a whole number of contracts. When the calculated size is below one contract, the strategy will continue trading one contract.
Important Limitations
Optimal F is calculated from historical trades. A future loss may exceed the largest loss observed in the backtest.
Full Optimal F often creates excessive exposure. Results should therefore be evaluated using more than Net Profit alone. Important metrics include:
Maximum Drawdown
Recovery Factor
Equity Curve Stability
Largest Losing Trade
Maximum Losing Streak
For a more objective evaluation, calculate Optimal F on one section of historical data and apply the fixed values to a separate out-of-sample period.
Insert your own strategy into MM: Optimal F, run the analysis using one contract, and determine the level of risk that is actually supported by the historical structure of your strategy’s profits and losses.
Стратегия

Индикатор
