declare lower;
# GLOBAL DEFINITIONS
DefineGlobalColor("TrendUp", CreateColor(0, 254, 30));
DefineGlobalColor("TrendDown", CreateColor(255, 3, 2));
input agg = AggregationPeriod.DAY;
input agg2 = AggregationPeriod.WEEK;
input agg3 = AggregationPeriod.MONTH;
input lengthCCI = 14;
input lengthATR = 4;
input AtrFactor = 0.7;
input DotSize = 3;
input n = 3;
input Factor = 1.3;
input Pd = 60;
input Lookback = 3;
def n1 = n + 1;
# AGGREGATION 1
def c = close(period = agg);
def h = high(period = agg);
def l = low(period = agg);
def pricedata = HL2(period = agg);
def ATRcci = Average(TrueRange(h, c, l), lengthATR) * AtrFactor;
def price = c + l + h;
def linDev = lindev(price, lengthCCI);
def CCI = if lindev == 0 then 0 else (price - Average(price, lengthCCI)) / linDev / 0.015;
def MT1 = if CCI > 0
then Max(MT1[1], pricedata - ATRcci)
else Min(MT1[1], pricedata + ATRcci);
plot MT1_Dot = if IsNaN(close) then Double.NaN else 1;
MT1_Dot.SetPaintingStrategy(PaintingStrategy.Points);
MT1_Dot.SetLineWeight(DotSize);
MT1_Dot.AssignValueColor(if c < MT1 then GlobalColor("TrendDown") else GlobalColor("TrendUp"));
#AddChartBubble(!IsNaN(close[n1]) and IsNaN(close[n]), 1, (agg/1000/60) + " min", Color.Yellow, yes);
# AGGREGATION 2
def c2 = close(period = agg2);
def h2 = high(period = agg2);
def l2 = low(period = agg2);
def pricedata2 = HL2(period = agg2);
def ATRcci2 = Average(TrueRange(h2, c2, l2), lengthATR) * AtrFactor;
def price2 = c2 + l2 + h2;
def linDev2 = lindev(price2, lengthCCI);
def CCI2 = if linDev2 == 0 then 0 else (price2 - Average(price2, lengthCCI)) / linDev2 / 0.015;
def MT2 = if CCI2 > 0
then Max(MT2[1], pricedata2 - ATRcci2)
else Min(MT2[1], pricedata2 + ATRcci2);
plot MT2_Dot = if IsNaN(close) then Double.NaN else 2;
MT2_Dot.SetPaintingStrategy(PaintingStrategy.Points);
MT2_Dot.SetLineWeight(DotSize);
MT2_Dot.AssignValueColor(if c2 < MT2 then GlobalColor("TrendDown") else GlobalColor("TrendUp"));
#AddChartBubble(!IsNaN(close[n1]) and IsNaN(close[n]), 2, (agg2/1000/60) + " min", Color.Yellow, yes);
addlabel(yes, "prev agg2", if c2[1] < MT2[1] then color.red else color.green);
# AGGREGATION 3
def c3 = close(period = agg3);
def h3 = high(period = agg3);
def l3 = low(period = agg3);
def pricedata3 = HL2(period = agg3);
def ATRcci3 = Average(TrueRange(h3, c3, l3), lengthATR) * AtrFactor;
def price3 = c3 + l3 + h3;
def linDev3 = lindev(price3, lengthCCI);
def CCI3 = if linDev3 == 0 then 0 else (price3 - Average(price3, lengthCCI)) / linDev3 / 0.015;
def MT3 = if CCI3 > 0
then Max(MT3[1], pricedata3 - ATRcci3)
else Min(MT3[1], pricedata3 + ATRcci3);
plot MT3_Dot = if IsNaN(close) then Double.NaN else 3;
MT3_Dot.SetPaintingStrategy(PaintingStrategy.Points);
MT3_Dot.SetLineWeight(DotSize);
MT3_Dot.AssignValueColor(if c3 < MT3 then GlobalColor("TrendDown") else GlobalColor("TrendUp"));
#AddChartBubble(!IsNaN(close[n1]) and IsNaN(close[n]), 3, (agg3/1000/60) + " min", Color.Yellow, yes);
# End Trend Magic MTF