Educational
High For Loop | MisinkoMasterThe High For Loop is a new Trend Following tool designed to give traders smooth and fast signals without being too complex, overfit or repainting.
It works by finding how many bars have a higher high than the current high, how many have a lower high, and scores it based on that. This provides users with easy and accurate signals, allowing for gaining a large edge in the market.
It is pretty simple but you can still play around with it pretty well and improve uppon your strategies.
For any backtests using strategies, I left many comments and tried to make it as easy as possible to backtest.
Enjoy G´s
Machine Learning : Neural Network Prediction -EasyNeuro-Machine Learning: Neural Network Prediction
— An indicator that learns and predicts price movements using a neural network —
Overview
The indicator “Machine Learning: Neural Network Prediction” uses price data from the chart and applies a three-layer Feedforward Neural Network (FNN) to estimate future price movements.
Key Features
Normally, training and inference with neural networks require advanced programming languages that support machine learning frameworks (such as TensorFlow or PyTorch) as well as high-performance hardware with GPUs. However, this indicator independently implements the neural network mechanism within TradingView’s Pine Script environment, enabling real-time training and prediction directly on the chart.
Since Pine Script does not support matrix operations, the backpropagation algorithm—necessary for neural network training—has been implemented entirely through scalar operations. This unique approach makes the creation of such a groundbreaking indicator possible.
Significance of Neural Networks
Neural networks are a core machine learning method, forming the foundation of today’s widely used generative AI systems, such as OpenAI’s GPT and Google’s Gemini. The feedforward neural network adopted in this indicator is the most classical architecture among neural networks. One key advantage of neural networks is their ability to perform nonlinear predictions.
All conventional indicators—such as moving averages and oscillators like RSI—are essentially linear predictors. Linear prediction inherently lags behind past price fluctuations. In contrast, nonlinear prediction makes it theoretically possible to dynamically anticipate future price movements based on past patterns. This offers a significant benefit for using neural networks as prediction tools among the multitude of available indicators.
Moreover, neural networks excel at pattern recognition. Since technical analysis is largely based on recognizing market patterns, this makes neural networks a highly compatible approach.
Structure of the Indicator
This indicator is based on a three-layer feedforward neural network (FNN). Every time a new candlestick forms, the model samples random past data and performs online learning using stochastic gradient descent (SGD).
SGD is known as a more versatile learning method compared to standard gradient descent, particularly effective for uncertain datasets like financial market price data. Considering Pine Script’s computational constraints, SGD is a practical choice since it can learn effectively from small amounts of data. Because online learning is performed with each new candlestick, the indicator becomes a little “smarter” over time.
Adjustable Parameters
Learning Rate
Specifies how much the network’s parameters are updated per training step. Values between 0.0001 and 0.001 are recommended. Too high causes divergence and unstable predictions, while too low prevents sufficient learning.
Iterations per Online Learning Step
Specifies how many training iterations occur with each new candlestick. More iterations improve accuracy but may cause timeouts if excessive.
Seed
Random seed for initializing parameters. Changing the seed may alter performance.
Architecture Settings
Number of nodes in input and hidden layers:
Increasing input layer nodes allows predictions based on longer historical periods. Increasing hidden layer nodes increases the network’s interpretive capacity, enabling more flexible nonlinear predictions. However, more nodes increase computational cost exponentially, risking timeouts and overfitting.
Hidden layer activation function (ReLU / Sigmoid / Tanh):
Sigmoid:
Classical function, outputs between 0–1, approximates a normal distribution.
Tanh:
Similar to Sigmoid but outputs between -1 and 1, centered around 0, often more accurate.
ReLU:
Simple function (outputs input if ≥ 0, else 0), efficient and widely effective.
Input Features (selectable and combinable)
RoC (Rate of Change):
Measures relative price change over a period. Useful for predicting movement direction.
RSI (Relative Strength Index):
Oscillator showing how much price has risen/fallen within a period. Widely used to anticipate direction and momentum.
Stdev (Standard Deviation, volatility):
Measures price variability. Useful for volatility prediction, though not directional.
Optionally, input data can be smoothed to stabilize predictions.
Other Parameters
Data Sampling Window:
Period from which random samples are drawn for SGD.
Prediction Smoothing Period:
Smooths predictions to reduce spikes, especially when RoC is used.
Prediction MA Period:
Moving average applied to smoothed predictions.
Visualization Features
The internal state of the neural network is displayed in a table at the upper-right of the chart:
Network architecture:
Displays the structure of input, hidden, and output layers.
Node activations:
Shows how input, hidden, and output node values dynamically change with market conditions.
This design allows traders to intuitively understand the inner workings of the neural network, which is often treated as a black box.
Glossary of Terms
Feature:
Input variables fed to the model (RoC/RSI/Stdev).
Node/Unit:
Smallest computational element in a layer.
Activation Function:
Nonlinear function applied to node outputs (ReLU/Sigmoid/Tanh).
MSE (Mean Squared Error):
Loss function using average squared errors.
Gradient Descent (GD/SGD):
Optimization method that gradually adjusts weights in the direction that reduces loss.
Online Learning:
Training method where the model updates sequentially with each new data point.
Master Arb Recipes – 3 Commas signal Bot integration Master Arb Recipes – 3 Commas signal Bot integration
Purpose
A systematic arbitrage/accumulation framework with pre-tuned “recipes” for BTC/ETH/XRP/SUI/SOL plus a fully manual mode. It automates signal generation for external execution bots (via alert() JSON), while showing on-chart panels for goals, active parameters, DCA position, and P&L/ROI/CAGR. Backtests simulate market orders with optional slippage and TradingView commissions.
Key ideas
Entries: Intrabar trigger when price drops by the recipe’s Entry drop % from the previous close.
Exits: Profit-taking when price rises by the recipe’s Exit rise % (optionally requiring price above average cost).
DCA accounting: Tracks running quantity, average cost, realized (cash) P&L, and unrealized (coin) P&L.
Capital planning: “ReqCap” column estimates capital = Entry $ × Allowed entries (UI only; does not affect orders).
Alerts (live only): Sends minimal Custom Signal JSON for enter_long / exit_long to your execution bot.
What’s included on chart
Top-Right: Strategy Goals Table
Describes the objective for each preset. Auto-filters by the chart’s base (optional).
Bottom-Left: Active Recipe Panel (with 3C UI column)
Shows the active preset (or custom) with: timeframe, Sell-Above-Cost state, Entry/Exit %, Exit-as-%-of-Entry, min bars between entries, once-per-bar gate, and 3Commas UI guidance for optional filters and per-order dollars.
Top-Left: DCA Panel
Current base quantity, average cost, and realized P&L.
Bottom-Right: P&L + ROI/CAGR Panel
Cash P&L (realized), Coin P&L (unrealized), Total P&L, ROI since first fill, and annualized CAGR. Displays denominators for both StartCap (strategy.initial_capital) and ReqCap (planning).
Presets
BTC: STH1_D, LTH1_6H, LTH2_D, LTH3_W, LTH4_6H
ETH: STH1_D, STH2_D, LTH1_D
XRP: STH1_D, STH2_6H, LTH1_6H, LTH2_1H
SUI: STH1_D, STH2_D, STH3_D
SOL: STH1_D, LTH1_D
Each preset sets Entry drop %, Exit rise %, default Entry $, Exit-as-%-of-Entry, Sell-Above-Cost flag, and a reference timeframe (display only). Custom mode lets you define these manually.
Inputs you’ll use
3Commas Custom Signal: secret, bot_uuid, max_lag_sec.
Start Window: Exact date/time + timezone to begin trading/signals.
Entry/Exit Parameters: Entry drop %, Exit rise %, Sell Above Avg Cost toggle, Exit as % of Entry.
Capital Planning: Allowed entries (for ReqCap), Entry $ override (panel only).
Execution/Sim: Simulated slippage %, once-per-bar gate, minimum bars between entries, TradingView commission.
Panels: Toggles + positions for each table.
Alert / Bot integration
Alerts fire only in realtime (barstate.isrealtime) on order submission.
Create one alert on this script using “Any alert() function call”.
Payload (Custom Signal style) includes:
secret, bot_uuid, max_lag, timestamp, trigger_price, tv_exchange, tv_instrument, action where action ∈ {enter_long, exit_long}.
Sizing: This script does not include per-order sizing in the JSON; size in your bot UI. The on-chart Entry $ / Exit $ values are for planning/backtest display.
3Commas optional filter mapping (shown in the panel’s “3C UI” column):
Entry filters:
Same order: set to –EntryDrop% (ON)
From average entry: set to –EntryDrop% (ON)
Exit filters:
If Sell Above Cost = ON → From average entry +ExitRise% (ON); Same order OFF
If Sell Above Cost = OFF → Same order +ExitRise% (ON); From average entry OFF
Per-order volume: Use your bot’s UI. Panel shows the dollars you planned (Entry $ and Exit $).
Backtest notes & limitations
Uses calc_on_every_tick=true and intrabar checks against the previous close for entry drops; historical behavior won’t perfectly match exchange microstructure.
process_orders_on_close=false; fills are simulated at bar prices with your slippage setting and TV commission.
Alerts and webhook timing depend on TradingView + broker/exchange latencies; use max_lag_sec accordingly.
Required Capital (ReqCap) is for planning only and does not reserve funds or constrain orders.
Recommended markets/timeframes
Crypto spot or futures charts that trade 24/7. Preset labels (D/6H/1H/W) are reference rhythms for volatility; the script runs on any timeframe but results will vary.
Change log (04092025)
Added 3C UI guidance column in Active Recipe panel (dynamic % per recipe).
Restored Goals (top-right) and P&L/ROI/CAGR (bottom-right with StartCap & ReqCap).
Minor UI clarifications; trading logic unchanged.
Disclaimer
This script is for research and education. It is not financial advice and makes no performance promises. Backtests are hypothetical and subject to substantial limitations. Markets involve risk; you can lose capital. Test on paper first and deploy at your own discretion. Licensed under the Mozilla Public License 2.0.
Artharjan High Volume Zones v2Artharjan High Volume Zones (AHVZ)
The Artharjan High Volume Zones (AHVZ) indicator is designed to identify, highlight, and track price zones formed during exceptionally high-volume bars. These levels often act as critical support and resistance zones, revealing where institutions or large players have shown significant interest.
By combining both short-term (ST) and long-term (LT) high-volume zones, the tool enables traders to align intraday activity with broader market structures.
Core Purpose
Markets often leave behind footprints in the form of high-volume bars. The AHVZ indicator captures these footprints and projects their influence forward, allowing traders to spot zones of liquidity, accumulation, or distribution where future price reactions are likely.
Key Features
🔹 Short-Term High Volume Zones (ST-ZoI)
Identifies the highest-volume bar within a short-term lookback period (default: 22 bars).
Draws and maintains:
Upper & Lower Bounds of the high-volume candle.
Midpoint Line (M-P) as the zone’s equilibrium.
Buffer Zones above and below for intraday flexibility (percentage-based).
Highlights these zones visually for quick intraday decision-making.
🔹 Long-Term High Volume Zones (LT-ZoI)
Scans for the highest-volume bar in a long-term lookback period (default: 252 bars).
Similar plotting structure as ST-ZoI: Upper, Lower, Midpoint, and Buffers.
Useful for identifying institutional footprints and multi-week/month accumulation zones.
🔹 Dynamic Buffering
Daily/Weekly/Monthly charts: Adds a fixed percentage buffer above and below high-volume zones.
Intraday charts: Uses price-range based buffers, scaling zones more adaptively to volatility.
🔹 Visual Customization
Independent color settings for ST and LT zones, mid-range lines, and buffers.
Adjustable plot thickness for clarity across different chart styles.
How It Helps
Intraday Traders
Use ST zones to pinpoint short-term supply/demand clusters.
Trade rejections or breakouts near these high-volume footprints.
Swing/Positional Traders
Align entries with LT zones to stay on the side of institutional flows.
Spot areas where price may stall, reverse, or consolidate.
General Market Structure Analysis
Understand where volume-backed conviction exists in the chart.
Avoid trading into hidden walls of liquidity by recognizing prior high-volume zones.
Closing Note
The Artharjan High Volume Zones indicator acts as a volume map of the market, giving traders a deeper sense of where meaningful battles between buyers and sellers took place. By combining short-term noise filtering with long-term structural awareness, it empowers traders to make more informed, disciplined decisions.
With Thanks,
Rrahul Desai @Artharjan
Clean Zone + SL/TP (Latest Only)📌 Description
Clean Zone + SL/TP (Latest Only) is an indicator designed to highlight the most recent supply or demand zone based on pivot highs/lows, and automatically plot entry, stop loss, and multiple take profit levels.
🔹 Automatic Direction Detection
The script can auto-detect trade direction (Long/Short) using pivot logic, or you can override manually.
🔹 Zone Drawing
Only the latest valid supply (red) or demand (green) zone is displayed.
Zones are extended to the right for a customizable number of bars.
🔹 Entry / SL / TP Levels
Entry, Stop Loss, and TP1/TP2/TP3 levels are plotted automatically.
Targets can be calculated either by zone size or by ATR-based multiples.
Risk/Reward ratios are fully adjustable.
🔹 Customizable Display
Toggle visibility for zones (box), entry/SL/TP lines, and price labels.
Labels show only on the latest bar for a clean chart look.
🎯 Use Case
This tool helps traders quickly identify the cleanest and most recent supply/demand setup and manage trades with predefined risk/reward targets. It’s especially useful for price action traders and those who prefer simple, uncluttered charts.
Artharjan NSE Sectors Relative Strength DashboardArtharjan NSE Sectors Relative Strength Dashboard
This script provides a comprehensive dashboard for analyzing the relative strength of NSE sectors compared to a benchmark index (default: NIFTY). It is designed to give traders and investors a consolidated snapshot of sector performance, momentum, and short-term trend strength — all in one visual table.
Core Purpose
The goal is to simplify sector rotation analysis by combining relative strength, rate of change, momentum, and trend classification into a sortable, color-coded dashboard. Instead of scanning multiple charts, users can rely on this single panel for quick decision-making.
Key Features
Benchmark Comparison
Every sector is measured against the benchmark index (default: NIFTY). This allows users to spot outperforming or underperforming sectors relative to the market.
Multiple Performance Metrics
LTP % Change: Last traded price percentage change from the prior close.
RS Score: Relative strength score over a user-defined lookback.
Momentum (ROC Difference): Convergence/divergence between two ROC values for added confirmation.
ROC1 / ROC2: Short- and medium-term rate-of-change measures.
Trend Classification Engine
Each sector is tagged as Ultra Bullish, Bullish Breakout, Strong/Moderate Bullish, Neutral, Moderate/Strong Bearish, Bearish Breakdown, or Ultra Bearish. This classification is based on sectoral price behavior and candlestick relationships.
Sorting & Customization
Users can sort the dashboard by any metric (e.g., RS Score, % Change, Momentum), in ascending or descending order, to highlight what matters most for their strategy.
Table Presentation
Adjustable text size, thickness, and positioning on the chart.
Optional color-coded cells for visual cues — green shades for strength, red shades for weakness, neutral shades for sideways trends.
“Last Updated” timestamp for clarity on when the snapshot was generated.
How It Helps
This tool reduces the noise of flipping through individual sector charts. Traders can identify sector leadership, monitor momentum shifts, and catch early signs of rotation without leaving a single chart window. It acts as both a macro lens (sector overview) and a micro tool (spotting exact strength/weakness transitions).
Closing Note
This dashboard was built with a simple goal: to bring clarity to complex sectoral movements. Use it as a guiding compass while respecting your broader trading or investing framework.
With Thanks,
Rrahul Desai
@Artharjan
Artharjan Heiken Ashi Super TrendArtharjan Heiken Ashi SuperTrend (AHAST)
The Artharjan Heiken Ashi SuperTrend (AHAST) indicator is a refined version of the classic SuperTrend tool, designed for traders who wish to blend trend-following logic with the smoothing effects of Heiken Ashi candles. This script not only highlights market trends but also introduces multi-timeframe filtering, visual cues, and alerts for sharper decision-making.
🔑 Key Features
Heiken Ashi Integration
Option to calculate trends using standard candles or Heiken Ashi candles.
Provides smoother visualization, reducing noise.
Flexible ATR Calculation
Choose between RMA (default) and SMA for ATR computation.
Option to switch between traditional ATR and Heiken Ashi-based ATR.
Customizable Inputs
ATR length, multiplier factor, trend colors, and higher-timeframe filters are all user-configurable.
Debug mode available for internal verification.
Visual Enhancements
Dynamic background highlighting to clearly distinguish bullish vs bearish phases.
Fill plots that emphasize ongoing trends.
Buy and Sell signal markers with optional on/off toggle.
Multi-Timeframe (MTF) Filter
Fetches higher timeframe (e.g., Weekly) Heiken Ashi values.
Detects bullish and bearish flips on higher timeframe trends.
Overlay highlights to align lower timeframe trades with broader market direction.
Alerts & Automation
Alerts available for:
Buy / Sell triggers
Direction changes
Higher timeframe bullish or bearish flips
Compatible with TradingView alerts for automated workflows.
⚙️ How It Works
Core Trend Logic
The script calculates the median price of Heiken Ashi highs and lows.
SuperTrend bands (up and dn) are adjusted using ATR.
A bullish or bearish state is determined based on price closing above or below these bands.
Signal Generation
Buy Signal: Trend flips from bearish (-1) to bullish (+1).
Sell Signal: Trend flips from bullish (+1) to bearish (-1).
Signals can be plotted as circles, labels, or both depending on configuration.
MTF SuperTrend
Parallel SuperTrend calculation on a higher timeframe (user-selected).
Detects bullish flip (HTF ↑) or bearish flip (HTF ↓).
Highlights the chart background with higher timeframe color filters when enabled.
Debug Mode
Turns on background shading to indicate whether Heiken Ashi or regular candles are in use.
Helps verify internal logic for advanced users.
🎨 Visualization Example
Green Highlight / Fill → Active bullish trend
Red Highlight / Fill → Active bearish trend
Light Blue / Gray Highlights → Higher timeframe bullish / bearish alignment
Buy / Sell Labels → Clear entry or exit cues, aligned with the trend
🚨 Practical Usage
Swing Traders: Use higher timeframe filters (e.g., Weekly) to align intraday signals with broader market direction.
Intraday Traders: Focus on Heiken Ashi smoothing to avoid whipsaws in volatile sessions.
Options Traders: Combine bullish/bearish flips with option strategies (e.g., Calls/Puts) to gain directional exposure.
✅ Final Thoughts
The Artharjan Heiken Ashi SuperTrend (AHAST) is not just another SuperTrend indicator—it’s a versatile trading companion. By merging classic ATR-based logic with Heiken Ashi smoothing and multi-timeframe confirmation, this tool equips traders with early signals, trend clarity, and strong alignment across timeframes.
Use it with discipline, combine it with your trading framework, and let it sharpen your edge in the markets.
With Thanks,
Rrahul Desai
@Artharjan
Artharjan Intraday Trading ZonesArtharjan Intraday Trading Zones (AITZ)
Overview
The AITZ indicator is designed to visually mark intraday trading zones on a chart by using the current day’s High (DH) and Low (DL) as reference points. It creates three distinct market zones:
Bullish Zone: Near the daily high, suggesting strength.
Bearish Zone: Near the daily low, suggesting weakness.
Neutral / No-Trade Zone: Between the bullish and bearish thresholds, where price movement is less directional.
These zones are highlighted with color-fills for quick visual identification, and the indicator automatically resets at the start of each new trading day.
Key Features
Daily Reference Levels: Automatically fetches Day High, Day Low, and uses them to calculate intraday zones.
Configurable Zone Depth: Traders can set the percentage distance from High/Low to define bullish and bearish zones.
Conditional Zone Coloring: Option to highlight zones only when price is actively trading inside them.
Dynamic Updates: Zone coloring adjusts in real time as the day progresses.
Customizable Appearance: Line thickness and zone colors can be adjusted to match chart preferences.
Inputs
Parameter Type Default Description
Level Thickness Integer 1 Thickness of all plotted levels (1–10).
(DH-DL)% below Day High Float 25 Distance from daily high (as % of DH–DL range) to define bullish threshold.
(DH-DL)% above Day Low Float 25 Distance from daily low (as % of DH–DL range) to define bearish threshold.
Plot Zone Colors (Conditional)? Boolean true If enabled, zones are colored only when price trades inside them. Otherwise, they remain visible regardless of price position.
Bullish Zone Color Color Teal (90% transparent) Fill color for bullish zone.
Neutral Zone Color Color Blue (90% transparent) Fill color for neutral/no-trade zone.
Bearish Zone Color Color Maroon (90% transparent) Fill color for bearish zone.
Core Calculations
Zones:
Bullish Zone = between DH and LTL
Bearish Zone = between DL and STL
Neutral Zone = between LTL and STL
Reset Behavior: At the start of each new daily session, old lines are deleted and fresh ones are drawn.
Usage Example
A trader sets:
(DH–DL)% below High = 20%
(DH–DL)% above Low = 20%
If today’s DH = 1000 and DL = 900 (Range = 100):
Bullish threshold = 1000 – (100 × 20%) = 980
Bearish threshold = 900 + (100 × 20%) = 920
Zones:
Bullish Zone: 980 → 1000
Neutral Zone: 920 → 980
Bearish Zone: 900 → 920
This creates clear trade zones for scalpers or intraday directional traders.
Practical Application
Trend Confirmation: If price sustains in the bullish zone, bias stays long.
Weakness Detection: Price falling into the bearish zone signals short opportunities.
Neutral Play: Avoid trades or expect sideways action inside the neutral zone.
Limitations
Works on instruments with clear daily highs/lows (equities, futures, FX).
May repaint levels intraday until the daily high/low is confirmed.
Zones depend on daily volatility—very narrow ranges may cause zones to overlap.
Price Grid (Base/Step/Levels)Price Grid (Base/Step/Levels) is a simple yet powerful tool for visual traders. It automatically draws a customizable grid of horizontal price levels on your chart.
You choose a base price, a grid step size, and the number of levels to display above and below. The indicator then plots evenly spaced lines around the base, helping you:
Spot round-number zones and psychological levels
Plan entries, exits, and stop-loss placements
Visualize support/resistance clusters
Build grid or ladder trading strategies
The base line is highlighted so you always know your anchor level, while the other levels are styled separately for clarity.
⚙️ Inputs
Base price → anchor level (set 0 to use current close price)
Grid step → distance between levels
Number of levels → lines drawn above & below base
Line style / width / colors → full customization
✅ Notes
Works on any market and timeframe
Automatically respects the symbol’s minimum tick size
Lightweight & non-repainting
Martingale Strategy Simulator [BackQuant]Martingale Strategy Simulator
Purpose
This indicator lets you study how a martingale-style position sizing rule interacts with a simple long or short trading signal. It computes an equity curve from bar-to-bar returns, adapts position size after losing streaks, caps exposure at a user limit, and summarizes risk with portfolio metrics. An optional Monte Carlo module projects possible future equity paths from your realized daily returns.
What a martingale is
A martingale sizing rule increases stake after losses and resets after a win. In its classical form from gambling, you double the bet after each loss so that a single win recovers all prior losses plus one unit of profit. In markets there is no fixed “even-money” payout and returns are multiplicative, so an exact recovery guarantee does not exist. The core idea is unchanged:
Lose one leg → increase next position size
Lose again → increase again
Win → reset to the base size
The expectation of your strategy still depends on the signal’s edge. Sizing does not create positive expectancy on its own. A martingale raises variance and tail risk by concentrating more capital as a losing streak develops.
What it plots
Equity – simulated portfolio equity including compounding
Buy & Hold – equity from holding the chart symbol for context
Optional helpers – last trade outcome, current streak length, current allocation fraction
Optional diagnostics – daily portfolio return, rolling drawdown, metrics table
Optional Monte Carlo probability cone – p5, p16, p50, p84, p95 aggregate bands
Model assumptions
Bar-close execution with no slippage or commissions
Shorting allowed and frictionless
No margin interest, borrow fees, or position limits
No intrabar moves or gaps within a bar (returns are close-to-close)
Sizing applies to equity fraction only and is capped by your setting
All results are hypothetical and for education only.
How the simulator applies it
1) Directional signal
You pick a simple directional rule that produces +1 for long or −1 for short each bar. Options include 100 HMA slope, RSI above or below 50, EMA or SMA crosses, CCI and other oscillators, ATR move, BB basis, and more. The stance is evaluated bar by bar. When the stance flips, the current trade ends and the next one starts.
2) Sizing after losses and wins
Position size is a fraction of equity:
Initial allocation – the starting fraction, for example 0.15 means 15 percent of equity
Increase after loss – multiply the next allocation by your factor after a losing leg, for example 2.00 to double
Reset after win – return to the initial allocation
Max allocation cap – hard ceiling to prevent runaway growth
At a high level the size after k consecutive losses is
alloc(k) = min( cap , base × factor^k ) .
In practice the simulator changes size only when a leg ends and its PnL is known.
3) Equity update
Let r_t = close_t / close_{t-1} − 1 be the symbol’s bar return, d_{t−1} ∈ {+1, −1} the prior bar stance, and a_{t−1} the prior bar allocation fraction. The simulator compounds:
eq_t = eq_{t−1} × (1 + a_{t−1} × d_{t−1} × r_t) .
This is bar-based and avoids intrabar lookahead. Costs, slippage, and borrowing costs are not modeled.
Why traders experiment with martingale sizing
Mean-reversion contexts – if the signal often snaps back after a string of losses, adding size near the tail of a move can pull the average entry closer to the turn
Behavioral or microstructure edges – some rules have modest edge but frequent small whipsaws; size escalation may shorten time-to-recovery when the edge manifests
Exploration and stress testing – studying the relationship between streaks, caps, and drawdowns is instructive even if you do not deploy martingale sizing live
Why martingale is dangerous
Martingale concentrates capital when the strategy is performing worst. The main risks are structural, not cosmetic:
Loss streaks are inevitable – even with a 55 percent win rate you should expect multi-loss runs. The probability of at least one k-loss streak in N trades rises quickly with N.
Size explodes geometrically – with factor 2.0 and base 10 percent, the sequence is 10, 20, 40, 80, 100 (capped) after five losses. Without a strict cap, required size becomes infeasible.
No fixed payout – in gambling, one win at even odds resets PnL. In markets, there is no guaranteed bounce nor fixed profit multiple. Trends can extend and gaps can skip levels.
Correlation of losses – losses cluster in trends and in volatility bursts. A martingale tends to be largest just when volatility is highest.
Margin and liquidity constraints – leverage limits, margin calls, position limits, and widening spreads can force liquidation before a mean reversion occurs.
Fat tails and regime shifts – assumptions of independent, Gaussian returns can understate tail risk. Structural breaks can keep the signal wrong for much longer than expected.
The simulator exposes these dynamics in the equity curve, Max Drawdown, VaR and CVaR, and via Monte Carlo sketches of forward uncertainty.
Interpreting losing streaks with numbers
A rough intuition: if your per-trade win probability is p and loss probability is q=1−p , the chance of a specific run of k consecutive losses is q^k . Over many trades, the chance that at least one k-loss run occurs grows with the number of opportunities. As a sanity check:
If p=0.55 , then q=0.45 . A 6-loss run has probability q^6 ≈ 0.008 on any six-trade window. Across hundreds of trades, a 6 to 8-loss run is not rare.
If your size factor is 1.5 and your base is 10 percent, after 8 losses the requested size is 10% × 1.5^8 ≈ 25.6% . With factor 2.0 it would try to be 10% × 2^8 = 256% but your cap will stop it. The equity curve will still wear the compounded drawdown from the sequence that led to the cap.
This is why the cap setting is central. It does not remove tail risk, but it prevents the sizing rule from demanding impossible positions
Note: The p and q math is illustrative. In live data the win rate and distribution can drift over time, so real streaks can be longer or shorter than the simple q^k intuition suggests..
Using the simulator productively
Parameter studies
Start with conservative settings. Increase one element at a time and watch how the equity, Max Drawdown, and CVaR respond.
Initial allocation – lower base reduces volatility and drawdowns across the board
Increase factor – set modestly above 1.0 if you want the effect at all; doubling is aggressive
Max cap – the most important brake; many users keep it between 20 and 50 percent
Signal selection
Keep sizing fixed and rotate signals to see how streak patterns differ. Trend-following signals tend to produce long wrong-way streaks in choppy ranges. Mean-reversion signals do the opposite. Martingale sizing interacts very differently with each.
Diagnostics to watch
Use the built-in metrics to quantify risk:
Max Drawdown – worst peak-to-trough equity loss
Sharpe and Sortino – volatility and downside-adjusted return
VaR 95 percent and CVaR – tail risk measures from the realized distribution
Alpha and Beta – relationship to your chosen benchmark
If you would like to check out the original performance metrics script with multiple assets with a better explanation on all metrics please see
Monte Carlo exploration
When enabled, the forecast draws many synthetic paths from your realized daily returns:
Choose a horizon and a number of runs
Review the bands: p5 to p95 for a wide risk envelope; p16 to p84 for a narrower range; p50 as the median path
Use the table to read the expected return over the horizon and the tail outcomes
Remember it is a sketch based on your recent distribution, not a predictor
Concrete examples
Example A: Modest martingale
Base 10 percent, factor 1.25, cap 40 percent, RSI>50 signal. You will see small escalations on 2 to 4 loss runs and frequent resets. The equity curve usually remains smooth unless the signal enters a prolonged wrong-way regime. Max DD may rise moderately versus fixed sizing.
Example B: Aggressive martingale
Base 15 percent, factor 2.0, cap 60 percent, EMA cross signal. The curve can look stellar during favorable regimes, then a single extended streak pushes allocation to the cap, and a few more losses drive deep drawdown. CVaR and Max DD jump sharply. This is a textbook case of high tail risk.
Strengths
Bar-by-bar, transparent computation of equity from stance and size
Explicit handling of wins, losses, streaks, and caps
Portable signal inputs so you can A–B test ideas quickly
Risk diagnostics and forward uncertainty visualization in one place
Example, Rolling Max Drawdown
Limitations and important notes
Martingale sizing can escalate drawdowns rapidly. The cap limits position size but not the possibility of extended adverse runs.
No commissions, slippage, margin interest, borrow costs, or liquidity limits are modeled.
Signals are evaluated on closes. Real execution and fills will differ.
Monte Carlo assumes independent draws from your recent return distribution. Markets often have serial correlation, fat tails, and regime changes.
All results are hypothetical. Use this as an educational tool, not a production risk engine.
Practical tips
Prefer gentle factors such as 1.1 to 1.3. Doubling is usually excessive outside of toy examples.
Keep a strict cap. Many users cap between 20 and 40 percent of equity per leg.
Stress test with different start dates and subperiods. Long flat or trending regimes are where martingale weaknesses appear.
Compare to an anti-martingale (increase after wins, cut after losses) to understand the other side of the trade-off.
If you deploy sizing live, add external guardrails such as a daily loss cut, volatility filters, and a global max drawdown stop.
Settings recap
Backtest start date and initial capital
Initial allocation, increase-after-loss factor, max allocation cap
Signal source selector
Trading days per year and risk-free rate
Benchmark symbol for Alpha and Beta
UI toggles for equity, buy and hold, labels, metrics, PnL, and drawdown
Monte Carlo controls for enable, runs, horizon, and result table
Final thoughts
A martingale is not a free lunch. It is a way to tilt capital allocation toward losing streaks. If the signal has a real edge and mean reversion is common, careful and capped escalation can reduce time-to-recovery. If the signal lacks edge or regimes shift, the same rule can magnify losses at the worst possible moment. This simulator makes those trade-offs visible so you can calibrate parameters, understand tail risk, and decide whether the approach belongs anywhere in your research workflow.
Live Market - Performance MonitorLive Market — Performance Monitor
Study material (no code) — step-by-step training guide for learners
________________________________________
1) What this tool is — short overview
This indicator is a live market performance monitor designed for learning. It scans price, volume and volatility, detects order blocks and trendline events, applies filters (volume & ATR), generates trade signals (BUY/SELL), creates simple TP/SL trade management, and renders a compact dashboard summarizing market state, risk and performance metrics.
Use it to learn how multi-factor signals are constructed, how Greeks-style sensitivity is replaced by volatility/ATR reasoning, and how a live dashboard helps monitor trade quality.
________________________________________
2) Quick start — how a learner uses it (step-by-step)
1. Add the indicator to a chart (any ticker / timeframe).
2. Open inputs and review the main groups: Order Block, Trendline, Signal Filters, Display.
3. Start with defaults (OB periods ≈ 7, ATR multiplier 0.5, volume threshold 1.2) and observe the dashboard on the last bar.
4. Walk the chart back in time (use the last-bar update behavior) and watch how signals, order blocks, trendlines, and the performance counters change.
5. Run the hands-on labs below to build intuition.
________________________________________
3) Main configurable inputs (what you can tweak)
• Order Block Relevant Periods (default ~7): number of consecutive candles used to define an order block.
• Min. Percent Move for Valid OB (threshold): minimum percent move required for a valid order block.
• Number of OB Channels: how many past order block lines to keep visible.
• Trendline Period (tl_period): pivot lookback for detecting highs/lows used to draw trendlines.
• Use Wicks for Trendlines: whether pivot uses wicks or body.
• Extension Bars: how far trendlines are projected forward.
• Use Volume Filter + Volume Threshold Multiplier (e.g., 1.2): requires volume to be greater than multiplier × average volume.
• Use ATR Filter + ATR Multiplier: require bar range > ATR × multiplier to filter noise.
• Show Targets / Table settings / Colors for visualization.
________________________________________
4) Core building blocks — what the script computes (plain language)
Price & trend:
• Spot / LTP: current close price.
• EMA 9 / 21 / 50: fast, medium, slow moving averages to define short/medium trend.
o trend_bullish: EMA9 > EMA21 > EMA50
o trend_bearish: EMA9 < EMA21 < EMA50
o trend_neutral: otherwise
Volatility & noise:
• ATR (14): average true range used for dynamic target and filter sizing.
• dynamic_zone = ATR × atr_multiplier: minimum bar range required for meaningful move.
• Annualized volatility: stdev of price changes × sqrt(252) × 100 — used to classify volatility (HIGH/MEDIUM/LOW).
Momentum & oscillators:
• RSI 14: overbought/oversold indicator (thresholds 70/30).
• MACD: EMA(12)-EMA(26) and a 9-period signal line; histogram used for momentum direction and strength.
• Momentum (ta.mom 10): raw momentum over 10 bars.
Mean reversion / band context:
• Bollinger Bands (20, 2σ): upper, mid, lower.
o price_position measures where price sits inside the band range as 0–100.
Volume metrics:
• avg_volume = SMA(volume, 20) and volume_spike = volume > avg_volume × volume_threshold
o volume_ratio = volume / avg_volume
Support & Resistance:
• support_level = lowest low over 20 bars
• resistance_level = highest high over 20 bars
• current_position = percent of price between support & resistance (0–100)
________________________________________
5) Order Block detection — concept & logic
What it tries to find: a bar (the base) followed by N candles in the opposite direction (a classical order block setup), with a minimum % move to qualify. The script records the high/low of the base candle, averages them, and plots those levels as OB channels.
How learners should think about it (conceptual):
1. An order block is a signature area where institutions (theory) left liquidity — often seen as a large bar followed by a sequence of directional candles.
2. This indicator uses a configurable number of subsequent candles to confirm that the pattern exists.
3. When found, it stores and displays the base candle’s high/low area so students can see how price later reacts to those zones.
Implementation note for learners: the tool keeps a limited history of OB lines (ob_channels). When new OBs exceed the count, the oldest lines are removed — good practice to avoid clutter.
________________________________________
6) Trendline detection — idea & interpretation
• The script finds pivot highs and lows using a symmetric lookback (tl_period and half that as right/left).
• It then computes a trendline slope from successive pivots and projects the line forward (extension_bars).
• Break detection: Resistance break = close crosses above the projected resistance line; Support break = close crosses below projected support.
Learning tip: trendlines here are computed from pivot points and time. Watch how changing tl_period (bigger = smoother, fewer pivots) alters the trendlines and break signals.
________________________________________
7) Signal generation & filters — step-by-step
1. Primary triggers:
o Bullish trigger: order block bullish OR resistance trendline break.
o Bearish trigger: bearish order block OR support trendline break.
2. Filters applied (both must pass unless disabled):
o Volume filter: volume must be > avg_volume × volume_threshold.
o ATR filter: bar range (high-low) must exceed ATR × atr_multiplier.
o Not in an existing trade: new trades only start if trade_active is false.
3. Trend confirmation:
o The primary trigger is only confirmed if trend is bullish/neutral for buys or bearish/neutral for sells (EMA alignment).
4. Result:
o When confirmed, a long or short trade is activated with TP/SL calculated from ATR multiples.
________________________________________
8) Trade management — what the tool does after a signal
• Entry management: the script marks a trade as trade_active and sets long_trade or short_trade flags.
• TP & SL rules:
o Long: TP = high + 2×ATR ; SL = low − 1×ATR
o Short: TP = low − 2×ATR ; SL = high + 1×ATR
• Monitoring & exit:
o A trade closes when price reaches TP or SL.
o When TP/SL hit, the indicator updates win_count and total_pnl using a very simple calculation (difference between TP/SL and previous close).
o Visual lines/labels are drawn for TP and updated as the trade runs.
Important learner notes:
• The script does not store a true entry price (it uses close in its P&L math), so PnL is an approximation — treat this as a learning proxy, not a position accounting system.
• There’s no sizing, slippage, or fee accounted — students must manually factor these when translating to real trades.
• This indicator is not a backtesting strategy; strategy.* functions would be needed for rigorous backtest results.
________________________________________
9) Signal strength & helper utilities
• Signal strength is a composite score (0–100) made up of four signals worth 25 points each:
1. RSI extreme (overbought/oversold) → 25
2. Volume spike → 25
3. MACD histogram magnitude increasing → 25
4. Trend existence (bull or bear) → 25
• Progress bars (text glyphs) are used to visually show RSI and signal strength on the table.
Learning point: composite scoring is a way to combine orthogonal signals — study how changing weights changes outcomes.
________________________________________
10) Dashboard — how to read each section (walkthrough)
The dashboard is split into sections; here's how to interpret them:
1. Market Overview
o LTP / Change%: immediate price & daily % change.
2. RSI & MACD
o RSI value plus progress bar (overbought 70 / oversold 30).
o MACD histogram sign indicates bullish/bearish momentum.
3. Volume Analysis
o Volume ratio (current / average) and whether there’s a spike.
4. Order Block Status
o Buy OB / Sell OB: the average base price of detected order blocks or “No Signal.”
5. Signal Status
o 🔼 BUY or 🔽 SELL if confirmed, or ⚪ WAIT.
o No-trade vs Active indicator summarizing market readiness.
6. Trend Analysis
o Trend direction (from EMAs), market sentiment score (composite), volatility level and band/position metrics.
7. Performance
o Win Rate = wins / signals (percentage)
o Total PnL = cumulative PnL (approximate)
o Bull / Bear Volume = accumulated volumes attributable to signals
8. Support & Resistance
o 20-bar highest/lowest — use as nearby reference points.
9. Risk & R:R
o Risk Level from ATR/price as a percent.
o R:R Ratio computed from TP/SL if a trade is active.
10. Signal Strength & Active Trade Status
• Numeric strength + progress bar and whether a trade is currently active with TP/SL display.
________________________________________
11) Alerts — what will notify you
The indicator includes pre-built alert triggers for:
• Bullish confirmed signal
• Bearish confirmed signal
• TP hit (long/short)
• SL hit (long/short)
• No-trade zone
• High signal strength (score > 75%)
Training use: enable alerts during a replay session to be notified when the indicator would have signalled.
________________________________________
12) Labs — hands-on exercises for learners (step-by-step)
Lab A — Order Block recognition
1. Pick a 15–30 minute timeframe on a liquid ticker.
2. Use default OB periods (7). Mark each time the dashboard shows a Buy/Sell OB.
3. Manually inspect the chart at the base candle and the following sequence — draw the OB zone by hand and watch later price reactions to it.
4. Repeat with OB periods 5 and 10; note stability vs noise.
Lab B — Trendline break confirmation
1. Increase trendline period (e.g., 20), watch trendlines form from pivots.
2. When a resistance break is flagged, compare with MACD & volume: was momentum aligned?
3. Note false breaks vs confirmed moves — change extension_bars to see projection effects.
Lab C — Filter sensitivity
1. Toggle Use Volume Filter off, and record the number and quality of signals in a 2-day window.
2. Re-enable volume filter and change threshold from 1.2 → 1.6; note how many low-quality signals are filtered out.
Lab D — Trade management simulation
1. For each signalled trade, record the time, close entry approximation, TP, SL, and eventual hit/miss.
2. Compute actual PnL if you had entered at the open of the next bar to compare with the script’s PnL math.
3. Tabulate win rate and average R:R.
Lab E — Performance review & improvement
1. Build a spreadsheet of signals over 30–90 periods with columns: Date, Signal type, Entry price (real), TP, SL, Exit, PnL, Notes.
2. Analyze which filters or indicators contributed most to winners vs losers and adjust weights.
________________________________________
13) Common pitfalls, assumptions & implementation notes (things to watch)
• P&L simplification: total_pnl uses close as a proxy entry price. Real entry/exit prices and slippage are not recorded — so PnL is approximate.
• No position sizing or money management: the script doesn’t compute position size from equity or risk percent.
• Signal confirmation logic: composite "signal_strength" is a simple 4×25 point scheme — explore different weights or additional signals.
• Order block detection nuance: the script defines the base candle and checks the subsequent sequence. Be sure to verify whether the intended candle direction (base being bullish vs bearish) aligns with academic/your trading definition — read the code carefully and test.
• Trendline slope over time: slope is computed using timestamps; small differences may make lines sensitive on very short timeframes — using bar_index differences is usually more stable.
• Not a true backtester: to evaluate performance statistically you must transform the logic into a strategy script that places hypothetical orders and records exact entry/exit prices.
________________________________________
14) Suggested improvements for advanced learners
• Record true entry price & timestamp for accurate PnL.
• Add position sizing: risk % per trade using SL distance and account size.
• Convert to strategy. (Pine Strategy)* to run formal backtests with equity curves, drawdowns, and metrics (Sharpe, Sortino).
• Log trades to an external spreadsheet (via alerts + webhook) for offline analysis.
• Add statistics: average win/loss, expectancy, max drawdown.
• Add additional filters: news time blackout, market session filters, multi-timeframe confirmation.
• Improve OB detection: combine wick/body, volume spike at base bar, and liquidity sweep detection.
________________________________________
15) Glossary — quick definitions
• ATR (Average True Range): measure of typical range; used to size targets and stops.
• EMA (Exponential Moving Average): trend smoothing giving more weight to recent prices.
• RSI (Relative Strength Index): momentum oscillator; >70 overbought, <30 oversold.
• MACD: momentum oscillator using difference of two EMAs.
• Bollinger Bands: volatility bands around SMA.
• Order Block: a base candle area with subsequent confirmation candles; a zone of institutional interest (learning model).
• Pivot High/Low: local turning point defined by candles on both sides.
• Signal Strength: combined score from multiple indicators.
• Win Rate: proportion of signals that hit TP vs total signals.
• R:R (Risk:Reward): ratio of potential reward (TP distance) to risk (entry to SL).
________________________________________
16) Limitations & assumptions (be explicit)
• This is an indicator for learning — not a trading robot or broker connection.
• No slippage, fees, commissions or tie-in to real orders are considered.
• The logic is heuristic (rule-of-thumb), not a guarantee of performance.
• Results are sensitive to timeframe, market liquidity, and parameter choices.
________________________________________
17) Practical classroom / study plan (4 sessions)
• Session 1 — Foundations: Understand EMAs, ATR, RSI, MACD, Bollinger Bands. Run the indicator and watch how these numbers change on a single day.
• Session 2 — Zones & Filters: Study order blocks and trendlines. Test volume & ATR filters and note changes in false signals.
• Session 3 — Simulated trading: Manually track 20 signals, compute real PnL and compare to the dashboard.
• Session 4 — Improvement plan: Propose changes (e.g., better PnL accounting, alternative OB rule) and test their impact.
________________________________________
18) Quick reference checklist for each signal
1. Was an order block or trendline break detected? (primary trigger)
2. Did volume meet threshold? (filter)
3. Did ATR filter (bar size) show a real move? (filter)
4. Was trend aligned (EMA 9/21/50)? (confirmation)
5. Signal confirmed → mark entry approximation, TP, SL.
6. Monitor dashboard (Signal Strength, Volatility, No-trade zone, R:R).
7. After exit, log real entry/exit, compute actual PnL, update spreadsheet.
________________________________________
19) Educational caveat & final note
This tool is built for training and analysis: it helps you see how common technical building blocks combine into trade ideas, but it is not a trading recommendation. Use it to develop judgment, to test hypotheses, and to design robust systems with proper backtesting and risk control before risking capital.
________________________________________
20) Disclaimer (must include)
Training & Educational Only — This material and the indicator are provided for educational purposes only. Nothing here is investment advice or a solicitation to buy or sell financial instruments. Past simulated or historical performance does not predict future results. Always perform full backtesting and risk management, and consider seeking advice from a qualified financial professional before trading with real capital.
________________________________________
Goldbach Time IndicatorA simple, time-only study that highlights “Goldbach minutes”—bars where any of three time transforms hit a curated integer set. It’s designed for timing research, session rhythm analysis, and building time-of-day confluence with your own strategy.
What it shows
Three time transforms (per bar, using your UTC offset):
Minute (Raw) → the current minute mm (yellow)
Min+Hr → mm + hh with a smart 60→00 rule & capped to 77 (lime)
Min−Hr → mm − hh (only if ≥ 0) (orange)
A minute is flagged when a transform equals a value in the script’s Goldbach set:
0, 3, 7, 11, 14, 17, 23, 29, 35, 41, 44, 47, 50, 53, 56, 59, 65, 71, 77
Background tint whenever there is ≥1 hit on the bar.
Goldbach Count histogram (0–3) showing how many of the three transforms hit.
Reference lines at common values (0, 11, 23, 35, 47, 59).
Live info table (bottom-right): current time (with offset), each transform’s value, and hit status.
Optional crosshair pane label showing time and “Goldbach: YES/NO”.
“00” guardrails (fewer false pings)
Zeros are plotted only when they’re time-valid:
1- Full hour: raw minute is 00
2- Equal pair: mm == hh > 0 so mm−hh = 0
3- Sum=60: mm + hh == 60 so Min+Hr becomes 00
Inputs
UTC Offset (−12…+14): shifts the evaluation clock.
Show Pane Label: on-chart crosshair label (optional).
Show All Plot Lines: plot everything (incl. tiny values 0–3) or, when OFF, show only “meaningful” hits (≥4) plus the strictly-validated 00 cases.
How to use it
Add as a separate pane (overlay=false).
Choose your UTC offset so the indicator matches your session clock.
Look for clusters (Goldbach Count 2–3) and compare with your own trade triggers, session opens, or news windows.
Treat this as timing confluence, not a buy/sell signal.
Notes
Purely time-derived (no price inputs). It doesn’t look ahead; values can update on the live bar as time advances.
The Min+Hr track can exceed 59; it’s capped at 77 to fit the set.
No alerts are included by design; pair it with your strategy’s alerts if needed.
Short description:
Highlights bars where mm, mm+hh, or mm−hh land in a curated “Goldbach” set, with strict 00 rules, UTC offset, count histogram, and a live info table—useful for time-of-day confluence research.
BTC Macro Composite Global liquidity Index -OffsetThis indicator is based on the thesis that Bitcoin price movements are heavily influenced by macro liquidity trends. It calculates a weighted composite index based on the following components:
• Global Liquidity (41%): Sum of central bank balance sheets (Fed , ECB , BoJ , and PBoC ), adjusted to USD.
• Investor Risk Appetite (22%): Derived from the Copper/Gold ratio, inverse VIX (as a risk-on signal), and the spread between High Yield and Investment Grade bonds (HY vs IG OAS).
• Gold Sensitivity (15–20%): Combines the XAUUSD price with BTC/Gold ratio to reflect the historical influence of gold on Bitcoin pricing.
Each component is normalized and then offset forward by 90 days to attempt predictive alignment with Bitcoin’s price.
The goal is to identify macro inflection points with high predictive value for BTC. It is not a trading signal generator but rather a macro trend context indicator.
❗ Important: This script should be used with caution. It does not account for geopolitical shocks, regulatory events, or internal BTC market structure (e.g., miner behavior, on-chain metrics).
💡 How to use:
• Use on the 1D timeframe.
• Look for divergences between BTC price and the macro index.
• Apply in confluence with other technical or fundamental frameworks.
🔍 Originality:
While similar components exist in macro dashboards, this script combines them uniquely using time-forward offsets and custom weighting specifically tailored for BTC behavior.
BTC(Sats Stacking) - CDC Action zone filterType: Indicator (Pine v6) • Category: Strategy Tools / DCA • Overlay: Yes
Overview
This indicator simulates fixed-amount Bitcoin DCA (dollar-cost averaging) and lets you apply a CDC Action Zone filter to only buy in specific market conditions. It plots EMA(12/26) lines with a shaded zone (green when fast > slow, red when slow > fast), shows buy markers on the chart when a DCA event actually executes, and displays a concise performance table.
The simulation tracks real invested capital (sum of your buys), not hypothetical equity injections, and reports PnL vs invested capital.
Key features
DCA frequency: Everyday, Every week, or Every month
CDC filter: Buy on all days, only when CDC is Green (trend-up above fast EMA), or only when Red (trend-down below fast EMA)
Execution price: Choose to buy at bar close or next bar open
Capital controls: Fixed DCA amount per event, optional max budget cap
Currency support: Portfolio currency label plus optional FX conversion (by symbol or manual rate)
Chart visuals: Buy markers on candles; EMA(12/26) lines with shaded “action zone”
Metrics table: Invested capital, buys executed, BTC accumulated, average price per BTC (quote), equity (portfolio), PnL% vs invested, and CAGR
How it works
CDC state:
Green = EMA(fast) > EMA(slow) and price ≥ EMA(fast)
Red = EMA(fast) < EMA(slow) and price < EMA(fast)
DCA trigger: Fires on new day/week/month boundaries (timeframe-agnostic).
Buy execution: When a DCA event occurs and passes the CDC filter and budget check, the script spends the fixed amount and adds the corresponding BTC at the chosen execution price.
Inputs (highlights)
Simulation
Symbol (blank = current chart), Buy at close/open, DCA amount, Max total invested
DCA Schedule
Everyday / Every week / Every month
CDC Action Zone
Filter mode (All / Green only / Red only), Price source, Fast/Slow EMA lengths (defaults 12/26)
Currency / Conversion
Portfolio currency label, Convert on/off, By symbol (e.g., OANDA:USDTHB) or Manual rate
Backtest Range
Optional start/end dates
Style
Show EMA lines and zone, colors and opacities, buy marker size and color
Display
Show qty/price labels on buys, show metrics table, number formatting
Metrics
Invested capital: Sum of all DCA spends in your portfolio currency
Equity (portfolio): BTC holdings marked to market and converted back if FX is enabled
PnL % vs invested: (Equity / Invested - 1) × 100
CAGR: Based on elapsed time from first in-range bar to the latest bar
Average price per BTC (quote): Spend in quote currency divided by BTC accumulated
Notes
This is an indicator, not a broker-connected strategy. It simulates buys and displays results without placing orders.
For more realistic fills, use Buy at next bar open.
If your portfolio currency differs from the symbol’s quote currency, enable Convert and supply a conversion symbol or manual rate.
EMA shading is purely visual; the filter logic uses the same EMA definitions.
Attribution & License
Inspired by the DCA idea and community simulations; CDC filtering implemented with standard EMA(12/26) logic.
License: MPL-2.0 (see code header).
Author: MiSuNoJo
Disclaimer
This tool is for research and education only and is not financial advice. Past performance does not guarantee future results. Use at your own risk.
ryantrad3s prev day high and lowThis indicator can help you find the Daily high and low a lot faster than what it usually does, having this indicator equipped will make it a lot more convenient for any trader that uses anything to do with Daily highs and lows. Hope this helps.
Market Spiralyst [Hapharmonic]Hello, traders and creators! 👋
Market Spiralyst: Let's change the way we look at analysis, shall we? I've got to admit, I scratched my head on this for weeks, Haha :). What you're seeing is an exploration of what's possible when code meets art on financial charts. I wanted to try blending art with trading, to do something new and break away from the same old boring perspectives. The goal was to create a visual experience that's not just analytical, but also relaxing and aesthetically pleasing.
This work is intended as a guide and a design example for all developers, born from the spirit of learning and a deep love for understanding the Pine Script™ language. I hope it inspires you as much as it challenged me!
🧐 Core Concept: How It Works
Spiralyst is built on two distinct but interconnected engines:
The Generative Art Engine: At its core, this indicator uses a wide range of mathematical formulas—from simple polygons to exotic curves like Torus Knots and Spirographs—to draw beautiful, intricate shapes directly onto your chart. This provides a unique and dynamic visual backdrop for your analysis.
The Market Pulse Engine: This is where analysis meets art. The engine takes real-time data from standard technical indicators (RSI and MACD in this version) and translates their states into a simple, powerful "Pulse Score." This score directly influences the appearance of the "Scatter Points" orbiting the main shape, turning the entire artwork into a living, breathing representation of market momentum.
🎨 Unleash Your Creativity! This Is Your Playground
We've included 25 preset shapes for you... but that's just the starting point !
The real magic happens when you start tweaking the settings yourself. A tiny adjustment can make a familiar shape come alive and transform in ways you never expected.
I'm genuinely excited to see what your imagination can conjure up! If you create a shape you're particularly proud of or one that looks completely unique, I would love to see it. Please feel free to share a screenshot in the comments below. I can't wait to see what you discover! :)
Here's the default shape to get you started:
The Dynamic Scatter Points: Reading the Pulse
This is where the magic happens! The small points scattered around the main shape are not just decorative; they are the visual representation of the Market Pulse Score.
The points have two forms:
A small asterisk (`*`): Represents a low or neutral market pulse.
A larger, more prominent circle (`o`): Represents a high, strong market pulse.
Here’s how to read them:
The indicator calculates the Pulse Strength as a percentage (from 0% to 100%) based on the total score from the active indicators (RSI and MACD). This percentage determines the ratio of circles to asterisks.
High Pulse Strength (e.g., 80-100%): Most of the scatter points will transform into large circles (`o`). This indicates that the underlying momentum is strong and It could be an uptrend. It's a visual cue that the market is gaining strength and might be worth paying closer attention to.
Low Pulse Strength (e.g., 0-20%): Most or all of the scatter points will remain as small asterisks (`*`). This suggests weak, neutral, or bearish momentum.
The key takeaway: The more circles you see, the stronger the bullish momentum is according to the active indicators. Watch the artwork "breathe" as the circles appear and disappear with the market's rhythm!
And don't worry about the shape you choose; the scatter points will intelligently adapt and always follow the outer boundary of whatever beautiful form you've selected.
How to Use
Getting started with Spiralyst is simple:
Choose Your Canvas: Start by going into the settings and picking a `Shape` and `Palette` from the "Shape Selection & Palette" group that you find visually appealing. This is your canvas.
Tune Your Engine: Go to the "Market Pulse Engine" settings. Here, you can enable or disable the RSI and MACD scoring engines. Want to see the pulse based only on RSI? Just uncheck the MACD box. You can also fine-tune the parameters for each indicator to match your trading style.
Read the Vibe: Observe the scatter points. Are they mostly small asterisks or are they transforming into large, vibrant circles? Use this visual feedback as a high-level gauge of market momentum.
Check the Dashboard: For a precise breakdown, look at the "Market Pulse Analysis" table on the top-right. It gives you the exact values, scores, and total strength percentage.
Explore & Experiment: Play with the different shapes and color palettes! The core analysis remains the same, but the visual experience can be completely different.
⚙️ Settings & Customization
Spiralyst is designed to be highly customizable.
Shape Selection & Palette: This is your main control panel. Choose from over 25 unique shapes, select a color palette, and adjust the line extension style ( `extend` ) or horizontal position ( `offsetXInput` ).
scatterLabelsInput: This setting controls the total number of points (both asterisks and circles) that orbit the main shape. Think of it as adjusting the density or visual granularity of the market pulse feedback.
The Market Pulse engine will always calculate its strength as a percentage (e.g., 75%). This percentage is then applied to the `scatterLabelsInput` number you've set to determine how many points transform into large circles.
Example: If the Pulse Strength is 75% and you set this to `100` , approximately 75 points will become circles. If you increase it to `200` , approximately 150 points will transform.
A higher number provides a more detailed, high-resolution view of the market pulse, while a lower number offers a cleaner, more minimalist look. Feel free to adjust this to your personal visual preference; the underlying analytical percentage remains the same.
Market Pulse Engine:
`⚙️ RSI Settings` & `⚙️ MACD Settings`: Each indicator has its own group.
Enable Scoring: Use the checkbox at the top of each group to include or exclude that indicator from the Pulse Score calculation. If you only want to use RSI, simply uncheck "Enable MACD Scoring."
Parameters: All standard parameters (Length, Source, Fast/Slow/Signal) are fully adjustable.
Individual Shape Parameters (01-25): Each of the 25+ shapes has its own dedicated group of settings, allowing you to fine-tune every aspect of its geometry, from the number of petals on a flower to the windings of a knot. Feel free to experiment!
For Developers & Pine Script™ Enthusiasts
If you are a developer and wish to add more indicators (e.g., Stochastic, CCI, ADX), you can easily do so by following the modular structure of the code. You would primarily need to:
Add a new `PulseIndicator` object for your new indicator in the `f_getMarketPulse()` function.
Add the logic for its scoring inside the `calculateScore()` method.
The `calculateTotals()` method and the dashboard table are designed to be dynamic and will automatically adapt to include your new indicator!
One of the core design philosophies behind Spiralyst is modularity and scalability . The Market Pulse engine was intentionally built using User-Defined Types (UDTs) and an array-based structure so that adding new indicators is incredibly simple and doesn't require rewriting the main logic.
If you want to add a new indicator to the scoring engine—let's use the Stochastic Oscillator as a detailed example—you only need to modify three small sections of the code. The rest of the script, including the adaptive dashboard, will update automatically.
Here’s your step-by-step guide:
#### Step 1: Add the User Inputs
First, you need to give users control over your new indicator. Find the `USER INTERFACE: INPUTS` section and add a new group for the Stochastic settings, right after the MACD group.
Create a new group name: `string GRP_STOCH = "⚙️ Stochastic Settings"`
Add the inputs: Create a boolean to enable/disable it, and then add the necessary parameters (`%K`, `%D`, `Smooth`). Use the `active` parameter to link them to the enable/disable checkbox.
// Add this code block right after the GRP_MACD and MACD inputs
string GRP_STOCH = "⚙️ Stochastic Settings"
bool stochEnabledInput = input.bool(true, "Enable Stochastic Scoring", group = GRP_STOCH)
int stochKInput = input.int(14, "%K Length", minval=1, group = GRP_STOCH, active = stochEnabledInput)
int stochDInput = input.int(3, "%D Smoothing", minval=1, group = GRP_STOCH, active = stochEnabledInput)
int stochSmoothInput = input.int(3, "Smooth", minval=1, group = GRP_STOCH, active = stochEnabledInput)
#### Step 2: Integrate into the Pulse Engine (The "Factory")
Next, go to the `f_getMarketPulse()` function. This function acts as a "factory" that builds and configures the entire market pulse object. You need to teach it how to build your new Stochastic indicator.
Update the function signature: Add the new `stochEnabledInput` boolean as a parameter.
Calculate the indicator: Add the `ta.stoch()` calculation.
Create a `PulseIndicator` object: Create a new object for the Stochastic, populating it with its name, parameters, calculated value, and whether it's enabled.
Add it to the array: Simply add your new `stochPulse` object to the `array.from()` list.
Here is the complete, updated `f_getMarketPulse()` function :
// Factory function to create and calculate the entire MarketPulse object.
f_getMarketPulse(bool rsiEnabled, bool macdEnabled, bool stochEnabled) =>
// 1. Calculate indicator values
float rsiVal = ta.rsi(rsiSourceInput, rsiLengthInput)
= ta.macd(close, macdFastInput, macdSlowInput, macdSignalInput)
float stochVal = ta.sma(ta.stoch(close, high, low, stochKInput), stochDInput) // We'll use the main line for scoring
// 2. Create individual PulseIndicator objects
PulseIndicator rsiPulse = PulseIndicator.new("RSI", str.tostring(rsiLengthInput), rsiVal, na, 0, rsiEnabled)
PulseIndicator macdPulse = PulseIndicator.new("MACD", str.format("{0},{1},{2}", macdFastInput, macdSlowInput, macdSignalInput), macdVal, signalVal, 0, macdEnabled)
PulseIndicator stochPulse = PulseIndicator.new("Stoch", str.format("{0},{1},{2}", stochKInput, stochDInput, stochSmoothInput), stochVal, na, 0, stochEnabled)
// 3. Calculate score for each
rsiPulse.calculateScore()
macdPulse.calculateScore()
stochPulse.calculateScore()
// 4. Add the new indicator to the array
array indicatorArray = array.from(rsiPulse, macdPulse, stochPulse)
MarketPulse pulse = MarketPulse.new(indicatorArray, 0, 0.0)
// 5. Calculate final totals
pulse.calculateTotals()
pulse
// Finally, update the function call in the main orchestration section:
MarketPulse marketPulse = f_getMarketPulse(rsiEnabledInput, macdEnabledInput, stochEnabledInput)
#### Step 3: Define the Scoring Logic
Now, you need to define how the Stochastic contributes to the score. Go to the `calculateScore()` method and add a new case to the `switch` statement for your indicator.
Here's a sample scoring logic for the Stochastic, which gives a strong bullish score in oversold conditions and a strong bearish score in overbought conditions.
Here is the complete, updated `calculateScore()` method :
// Method to calculate the score for this specific indicator.
method calculateScore(PulseIndicator this) =>
if not this.isEnabled
this.score := 0
else
this.score := switch this.name
"RSI" => this.value > 65 ? 2 : this.value > 50 ? 1 : this.value < 35 ? -2 : this.value < 50 ? -1 : 0
"MACD" => this.value > this.signalValue and this.value > 0 ? 2 : this.value > this.signalValue ? 1 : this.value < this.signalValue and this.value < 0 ? -2 : this.value < this.signalValue ? -1 : 0
"Stoch" => this.value > 80 ? -2 : this.value > 50 ? 1 : this.value < 20 ? 2 : this.value < 50 ? -1 : 0
=> 0
this
#### That's It!
You're done. You do not need to modify the dashboard table or the total score calculation.
Because the `MarketPulse` object holds its indicators in an array , the rest of the script is designed to be adaptive:
The `calculateTotals()` method automatically loops through every indicator in the array to sum the scores and calculate the final percentage.
The dashboard code loops through the `enabledIndicators` array to draw the table. Since your new Stochastic indicator is now part of that array, it will appear automatically when enabled!
---
Remember, this is your playground! I'm genuinely excited to see the unique shapes you discover. If you create something you're proud of, feel free to share it in the comments below.
Happy analyzing, and may your charts be both insightful and beautiful! 💛
JoseangelFX Trader Mecanico Vol 1🔥 Tired of emotional trading? Transform yourself in 7 days with a 100% mechanical system!
Hi, I'm José Ángel FX, the Mechanical Trader. Forget long, theoretical courses. Here I give you a proven method to master the indices in record time. No subjective analysis, no emotions, just clear rules that work.
This code is responsible for indicating a trading range for a 100% mechanical system.
🚀 What will you achieve with this system?
✅ Trade like a pro in 7 days: You don't need years of study.
✅ Objective and repeatable signals: Eliminate doubts forever.
✅ Backtesting: Concrete results of the strategy.
✅ Discipline of Steel: Psychotrading armored against fear and greed.
📢 "In a week with this system, you are no longer the same trader."
Investment: Profitability really has no value, you'll achieve it (remote assistance with management system installation included, for MT4, MT5, and TradingView).
Requirement: Obedience...
👉 Schedule your FREE diagnosis:
WhatsApp: wa.me/584122928262
Telegram: @tradermecanicoJAFX
t.me
SSMT [TakingProphets]OVERVIEW
SSMT (Sequential SMT) is an ICT-inspired divergence detection tool designed to help traders identify potential intermarket divergences using Quarterly Theory, a framework popularized within the ICT community by Trader Daye and FearingICT.
The indicator segments each trading day into structured time-based quarters and scans for Sequential SMT divergences across Daily, 90-minute, and Micro-session cycles — updating continuously in real time. This allows traders to visualize when institutional liquidity shifts are most likely, based on ICT’s time-of-day models.
Built on ICT’s Quarterly Theory
At the heart of SSMT is Quarterly Theory, a time-based framework used in ICT methodology. The model divides each trading day into four predictable phases, representing shifts between accumulation, manipulation, and distribution:
Daily Quarters (4 per day)
Q1: 18:00 – 00:00 ET
Q2: 00:00 – 06:00 ET
Q3: 06:00 – 12:00 ET
Q4: 12:00 – 18:00 ET
Additionally, the indicator refines timing with two further layers:
90-Minute Quarters → Splits Asia, London, New York AM, and New York PM into structured liquidity windows, helping intraday traders monitor session-specific SMTs.
Micro Quarters → Offers a granular breakdown of each session for scalpers who require precise entry timing.
By combining these cycles, SSMT provides a contextual framework for understanding when divergences may carry the highest institutional relevance.
How SSMT Detects SMT Divergences
Sequential SMT detection in SSMT works by comparing price behavior between your selected instrument and a correlated asset (default: CME_MINI:ES1!). It monitors current vs. previous highs and lows within the active quarter and identifies divergence patterns as they form:
Bullish SMT → Your instrument forms a higher low while the correlated asset does not.
Bearish SMT → Your instrument forms a lower high while the correlated asset does not.
Divergence lines and labels are plotted directly on your chart, and these drawings update dynamically in real time as new data comes in. Historical SMTs also persist beyond quarter boundaries for added confluence in your analysis.
Key Features
Three SMT Cycles in One Tool
-Daily Cycle → Track higher-timeframe divergences around key liquidity events.
-90-Minute Cycle → Ideal for timing intraday setups within major sessions.
-Micro Cycle → Provides highly detailed precision for scalpers trading engineered sweeps.
Per-Cycle Customization
-Toggle Daily, 90-Minute, and Micro SMT independently.
-Fully customize divergence line colors, styles, widths, and optional session boxes for clarity.
Smart Auto-Labeling
-Labels automatically display the correlated symbol (e.g., “SMT w/ES”).
-Divergence drawings persist historically for reference and context.
Instant Style Updates
-Any visual changes to colors, widths, or line styles are applied immediately across both active and historical SMT drawings.
Practical Use Cases
Scalpers → Spot Micro SMTs to refine entries with session-specific precision.
Intraday Traders → Track divergences across Asia, London, and New York sessions in real time.
Swing Traders → Combine Daily SMT divergences with HTF POIs for higher confluence.
ICT Traders → Built specifically around ICT teachings, this tool provides a clear, visual framework to apply Quarterly Theory and SMT models seamlessly.
Important Notes
SSMT is not a buy/sell signal generator. It is an analytical framework designed to help traders interpret ICT-based SMT concepts visually.
Always confirm divergences within your broader market narrative and risk management rules.
Prophet Model [TakingProphets]OVERVIEW
The Prophet Model is a structured, logic-driven indicator designed for traders who follow ICT (Inner Circle Trader) methodologies. It integrates multiple ICT concepts into a single, cohesive framework, giving traders a clear visual representation of institutional price delivery while minimizing chart clutter.
This tool does not provide buy/sell signals — instead, it enhances your workflow by automating the identification of key ICT-based criteria used to confirm high-probability trade setups.
WHAT THE INDICATOR DOES
The Prophet Model consolidates several advanced ICT concepts into a streamlined, real-time decision-support system:
Higher Timeframe PD Array Identification
-Automatically scans higher timeframes to locate unmitigated Fair Value Gaps (FVGs) and plots them on your lower timeframe charts, helping traders align with institutional price delivery.
Candle Range Theory (CRT) Validation
-Monitors higher timeframe candles to confirm directional bias using ICT’s Candle Range Theory, providing insight into delivery shifts without needing to change timeframes.
Liquidity Sweep Detection
-Identifies where price has taken buy-side or sell-side liquidity and highlights these zones visually to help traders anticipate potential reversals or continuations.
Change in State of Delivery (CISD)
-Detects moments of significant displacement that indicate structural shifts in price delivery, marking key opportunities for entry confirmation.
Enhanced Entry Precision (EPE)
-Automatically refines entry points by detecting overlapping internal FVGs within the displacement candle structure, improving execution accuracy.
Dynamic Risk Management Levels
-Plots Stop Loss (SL), Break-Even (BE), and Take Profit (TP) levels based on real structural movements — not fixed pip distances — giving traders clarity on risk exposure.
Real-Time Setup Checklist
-A built-in checklist confirms when all ICT-based confluence factors (HTF PDAs, CRT validation, liquidity sweep, CISD) align, helping traders maintain discipline.
HOW IT WORKS
Scan Higher Timeframes
-The indicator automatically identifies and marks institutional areas of interest like FVGs and PD Arrays from higher timeframes.
Confirm Market Bias
-Uses CRT analysis to validate directional conviction based on higher timeframe candle behavior.
Track Liquidity & Displacement
-Highlights liquidity sweeps and displacement candles, providing insight into when price is likely to expand, reverse, or redistribute.
Refine Entry Points
-Adjusts potential entry levels dynamically when internal imbalances overlap within CISD structures.
Visual Risk Management
-Automatically calculates realistic TP/SL levels based on the actual range of price delivery.
WHY ITS WORTH USING
Consolidates Multiple ICT Concepts
-Instead of relying on multiple scripts, the Prophet Model integrates FVGs, CRT, liquidity sweeps, and CISD detection into one cohesive tool.
Improves Efficiency
-Traders can analyze HTF and LTF confluence visually without switching charts or manually plotting levels.
Keeps Execution Disciplined
-The real-time checklist prevents overtrading by confirming only the setups that meet predefined ICT criteria.
Adaptable to Different Styles
-Whether you’re scalping, day trading, or swing trading, the model adapts to various timeframes and trading approaches.
IMPORTANT CONSIDERATIONS
This indicator is intended for traders with a working understanding of ICT methodology.
It does not generate standalone trading signals — users must incorporate narrative analysis and risk management.
Past performance of any ICT concept does not guarantee future results.
HTF Rejection Block [TakingProphets]Overview
The HTF Rejection Block indicator is designed to help traders identify and visualize Higher Timeframe Rejection Blocks—price zones where liquidity grabs often result in aggressive rejections. These areas can serve as high-probability decision points when combined with other ICT-based tools and concepts.
Unlike simple support/resistance markers, this indicator automates the detection of Rejection Blocks, maps them across up to four custom higher timeframes, and updates them in real time as price evolves. It provides traders with a structured framework for analyzing institutional price behavior without supplying direct buy/sell signals.
Concept & Background
The idea of Rejection Blocks was popularized by Powell, a respected educator within the ICT trading community. He highlighted how aggressive wicks—where price sweeps liquidity and sharply rejects—often reveal institutional activity and can hint at future directional bias.
This script builds upon that foundation by integrating several ICT-aligned concepts into a single, cohesive tool:
Liquidity Sweep Recognition → Identifies where price aggressively moves beyond a key level before snapping back.
Rejection Block Mapping → Highlights the candle bodies representing institutional rejection zones.
Multi-Timeframe Context → Lets you monitor rejection zones from higher timeframes while operating on your execution timeframe.
Equilibrium-Based Planning → Optional midpoint plotting offers a precise way to evaluate premium/discount within each block.
By combining these elements, the indicator makes it easier to see where liquidity events may influence price and how they relate to broader ICT-based setups.
How It Works
Detection Logic
A Rejection Block forms when price runs liquidity past a prior high/low but fails to hold and closes back inside the range.
These setups are detected automatically and marked as bullish or bearish zones.
Multi-Timeframe Analysis
Monitor up to four higher timeframes at once (e.g., 1H, 4H, 1D, 1W) while trading on your preferred execution timeframe.
Each block is clearly labeled and color-coded for visual clarity.
50% Equilibrium Levels
Optionally plot the midpoint of each rejection block, commonly used by ICT traders as a precision-based entry or target zone.
Auto-Mitigated Zones
When price fully trades through a rejection block, the zone is automatically removed to keep your chart clean.
Info Box for Context
An optional information panel displays the symbol, timeframe, and relevant data, helping you stay organized during active trading sessions.
Practical Usage
Select Higher Timeframes
Configure up to four HTFs based on your strategy (e.g., 1H, 4H, 1D, Weekly).
Identify Rejection Blocks
Watch for new blocks forming after liquidity sweeps beyond significant highs or lows.
Combine With Other ICT Concepts
Use alongside STDV, displacement, SMT divergence, or OTE retracements for confirmation and added confluence.
Plan Entry Zones
Leverage the 50% midpoint or body extremes of each block to build structured trade setups.
Why It’s Useful
This tool doesn’t generate trading signals or claim accuracy. Instead, it provides a visual framework for applying ICT’s Rejection Block methodology systematically across multiple timeframes.
Its value lies in helping traders:
Recognize where institutional activity may leave footprints.
Map key liquidity-based zones without manual marking.
Stay aligned with higher timeframe narratives while executing on lower timeframes.
The DTC fix7 Best Combined (New York Time Sessions)The DTC Bot – Weekly Results Recap 🚀
This week the bot came back with serious momentum! Here’s the breakdown of performance across pairs:
✅ AUDCHF: +$6,018.14
✅ NZDCHF: +$4,965.29
✅ AUDUSD: +$2,867.04
✅ NZDJPY: +$1,063.22
❌ NZDCAD: -$5,138.61
📊 Net Result: + $9,775.08
💡 Key Insight: Trading isn’t about one single trade or even one single week — it’s about probabilities over time. After a tough performance last week, this bounce shows how quickly the tide can turn in our favor.
The DTC Bot is designed to adapt across pairs, balance outcomes, and keep probabilities working for you.
⚡ Ready to get access?
The DTC Bot is now available as an invite-only strategy on TradingView:
$59/month subscription
$499/year (save big with the yearly plan!)