# AlphaTrend - ThinkScript Not PRO
# Original: KivancOzbilgic (TradingView)
# Converted by CANDO13579 | Oct 2025
input coeff = 1.0; # Multiplier
input AP = 14; # Common Period (integer constant)
input src = close; # Source
input showSignals = yes; # Show Signals?
input noVolumeData = no; # Use RSI Instead of MFI?
def TR = TrueRange(high, close, low);
def ATR = Average(TR, AP);
def hlc3 = (high + low + close) / 3;
def upT = low - ATR * coeff;
def downT = high + ATR * coeff;
# Compute RSI and MFI separately (avoid dynamic length parameter)
def rsiVal = RSI(price = src, length = AP);
def mfiVal = MoneyFlow(high, low, close, AP);
# Choose which metric to use (TOS-safe)
def calcCond = if noVolumeData then rsiVal >= 50 else mfiVal >= 50;
# Recursive AlphaTrend logic
rec AlphaTrend =
if BarNumber() == 1 then downT
else if calcCond then
if upT < AlphaTrend[1] then AlphaTrend[1] else upT
else
if downT > AlphaTrend[1] then AlphaTrend[1] else downT;
plot Line1 = AlphaTrend;
Line1.SetDefaultColor(Color.CYAN);
Line1.SetLineWeight(2);
def AlphaTrend2 = AlphaTrend[2];
plot Line2 = AlphaTrend2;
Line2.SetDefaultColor(Color.DARK_RED);
Line2.SetLineWeight(2);
# Determine up/down trends
def upCondition = AlphaTrend > AlphaTrend[2] or AlphaTrend[1] > AlphaTrend[3];
def downCondition = AlphaTrend < AlphaTrend[2] or AlphaTrend[1] < AlphaTrend[3];
# Cloud plots (required to use plots for AddCloud)
plot CloudUpPlot = if upCondition then Line1 else Double.NaN;
CloudUpPlot.HideTitle();
CloudUpPlot.SetPaintingStrategy(PaintingStrategy.LINE);
plot CloudDownPlot = if downCondition then Line1 else Double.NaN;
CloudDownPlot.HideTitle();
CloudDownPlot.SetPaintingStrategy(PaintingStrategy.LINE);
AddCloud(CloudUpPlot, Line2, Color.GREEN, Color.GREEN);
AddCloud(CloudDownPlot, Line2, Color.RED, Color.RED);
# Buy/Sell signals
def buySignal = AlphaTrend crosses above AlphaTrend2;
def sellSignal = AlphaTrend crosses below AlphaTrend2;
rec K1 = if BarNumber() == 1 then 99999 else if buySignal then 0 else K1[1] + 1;
rec K2 = if BarNumber() == 1 then 99999 else if sellSignal then 0 else K2[1] + 1;
rec O1 = if BarNumber() == 1 then 99999 else if buySignal[1] then 0 else O1[1] + 1;
rec O2 = if BarNumber() == 1 then 99999 else if sellSignal[1] then 0 else O2[1] + 1;
def validBuy = buySignal and showSignals and (O1 > K2);
def validSell = sellSignal and showSignals and (O2 > K1);
plot BuyDot = if validBuy then AlphaTrend2 * 0.9999 else Double.NaN;
BuyDot.SetPaintingStrategy(PaintingStrategy.POINTS);
BuyDot.SetDefaultColor(Color.BLUE);
BuyDot.SetLineWeight(3);
plot SellDot = if validSell then AlphaTrend2 * 1.0001 else Double.NaN;
SellDot.SetPaintingStrategy(PaintingStrategy.POINTS);
SellDot.SetDefaultColor(Color.DARK_RED);
SellDot.SetLineWeight(3);
AssignPriceColor(
if upCondition then Color.GREEN
else if downCondition then Color.RED
else Color.CURRENT
);