Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

Non Repainting – Trend Magic – Amibroker AFL code

2 min read

Nifty Futures Hourly Charts

 
Trend Magic is a positional trading system where the trade decision is based on the Commodity Channel Index supported by ATR Trailing stop loss. It will create more whipsaws in lower timeframes so it’s more than a positional trading system than an intraday trading system.

/* Done      by    Rajandran R */

/* Author of www.marketcalls.in  */



_SECTION_BEGIN("Trend Magic");

SetBarsRequired(100000,0);

GraphXSpace = 15;

SetChartOptions(0,chartShowArrows|chartShowDates);

SetChartBkColor(ParamColor("bkcolor",ColorRGB(0,0, 0)));

GfxSetBkMode(0); 

GfxSetOverlayMode(1);

SetBarFillColor(IIf(C>O,ParamColor("Candle UP Color", colorGreen),IIf(C<=O,ParamColor("Candle Down Color", colorRed),colorLightGrey)));

Plot(C,"\nPrice",IIf(C>O,ParamColor("Wick UP Color", colorDarkGreen),IIf(C<=O,ParamColor("Wick Down Color", colorDarkRed),colorLightGrey)),64,0,0,0,0);



//SetTradeDelays(1,1,1,1);

SetPositionSize(100,spsShares);





_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));



iCCI=Param("CCI Period",50,1,100,1);
Multiplier = Param("Multiplier",2,1,10,1);


Pd=Param("ATR Periods",5,1,10,1);

price = (O+H+L)/3;

iATR = ATR(Pd);
CCIvalue = CCIa(price,iCCI);

for (i = 0; i <iCCI+1; i++) {

      TrendUp[i] = Null;

      TrendDown[i] = Null;
}

TrendUp[BarCount-1]=Null;
TrendDown[BarCount-1]=Null;

for (i = iCCI+1; i <BarCount-1; i++) {

      TrendUp[i] = Null;

      TrendDown[i] = Null;

     

//       if (CCIvalue[i]>=0 && CCIvalue[i-1]<0) {
//		TrendUp[i-1]=TrendDown[i-1];
//		}

//       if (CCIvalue[i]<=0 && CCIvalue[i-1]>0) {
//		TrendDown[i-1]=TrendUp[i-1];
//		}	

	   if (CCIvalue[i] >= 0)
      {
         TrendUp[i] = (High[i]+Low[i])/2 - Multiplier*iATR[i];
         if (TrendUp[i] < TrendUp[i- 1])
            TrendUp[i] = TrendUp[i- 1];
      }
      else
      {
         if (CCIvalue[i] <= 0)
         {
            TrendDown[i] = (High[i]+Low[i])/2 + Multiplier*iATR[i];
            if (TrendDown[i] > TrendDown[i-1])
               TrendDown[i] = TrendDown[i-1];
         }
      }
	
} //end for loop



Plot(TrendUp,"Trend",colorGreen);

Plot(TrendDown,"Down",colorRed);


Buy = IsNull(TrendDown) AND !IsNull(TrendUP);
Sell = IsNull(TrendUp) AND !IsNull(TrendDown);

Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);
Short=Sell;
Cover=Buy;


BuyPrice=ValueWhen(Buy,C);
SellPrice=ValueWhen(Sell,C);
ShortPrice=ValueWhen(Short,C);
CoverPrice=ValueWhen(Cover,C);


Title = EncodeColor(colorWhite)+ "Trend Magic code from www.marketcalls.in" + " - " +  Name() + " - " + EncodeColor(colorRed)+ Interval(2) + EncodeColor(colorWhite) +
 "  - " + Date() +" - "+"\n" +EncodeColor(colorRed) +"Op-"+O+"  "+"Hi-"+H+"  "+"Lo-"+L+"  "+
"Cl-"+C+"  "+ "Vol= "+ WriteVal(V)+"\n"+ 
EncodeColor(colorLime)+
WriteIf (Buy , " GO LONG / Reverse Signal at "+C+"  ","")+
WriteIf (Sell , " EXIT LONG / Reverse Signal at "+C+"  ","")+"\n"+EncodeColor(colorYellow)+
WriteIf(Sell , "Total Profit/Loss for the Last Trade Rs."+(C-BuyPrice)+"","")+
WriteIf(Buy  , "Total Profit/Loss for the Last trade Rs."+(SellPrice-C)+"","");

PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);



_SECTION_END();



_SECTION_BEGIN("Time Left");

function GetSecondNum()

{

Time = Now( 4 );

Seconds = int( Time % 100 );

Minutes = int( Time / 100 % 100 );

Hours = int( Time / 10000 % 100 );

SecondNum = int( Hours * 60 * 60 + Minutes * 60 + Seconds );

return SecondNum;

}

RequestTimedRefresh( 1 );

TimeFrame = Interval();

SecNumber = GetSecondNum();

Newperiod = SecNumber % TimeFrame == 0;

SecsLeft = SecNumber - int( SecNumber / TimeFrame ) * TimeFrame;

SecsToGo = TimeFrame - SecsLeft;



x=Param("xposn",50,0,1000,1);

y=Param("yposn",380,0,1000,1);



GfxSelectSolidBrush( ColorRGB( 230, 230, 230 ) );

GfxSelectPen( ColorRGB( 230, 230, 230 ), 2 );

if ( NewPeriod )

{

GfxSelectSolidBrush( colorYellow );

GfxSelectPen( colorYellow, 2 );

Say( "New period" );

}

//GfxRoundRect( x+45, y+40, x-3, y-2, 0, 0 );

//GfxSetBkMode(1);

GfxSelectFont( "Arial", 14, 700, False );

GfxSetTextColor( colorRed );

GfxTextOut( "Time Left :"+SecsToGo+"", x, y );

_SECTION_END(); 
Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

[Webinar] Understanding and Mitigating Curve Fitting in System Trading

"Understanding and Mitigating Curve Fitting in System Trading"! This dynamic session aims to equip novice to intermediate traders, quantitative analysts, and financial engineers with...
Rajandran R
1 min read

P-Signal Strategy Long Only Strategy – Amibroker AFL Code

This tutorial provides an overview of the P-Signal reversal strategy, a quantitative trading strategy that utilizes statistical parameters and error functions to generate probabilistic...
Rajandran R
2 min read

32 Replies to “Non Repainting – Trend Magic – Amibroker AFL code”

    1. @Tony Joseph

      Buddy it is non repainting only. Signal will form once the new bar forms. So it will create such kind of confusion on the daily charts. Its better to stick with hourly/2 hourly/ 4 hourly charts where you data is realtime. The code is designed for realtime trading. When it comes to EOD charts once the new bar opens it automatically access the previous bar and place the signal on the previous bar and not on the current bar.

      Hope you understand!

  1. Hello Rajendra ,

    I am please to visit your website,i want an help,I need to a good buy and sell indicator software which can give me on live data,please guide me.

    Thanks

  2. Dear Amibroker users and Mudraa family members,

    Can anyone here suggest how to setup alarm or any way for setting up alarms for buy/ sell signal in any stock. I mean to say, whenever any buy/ sell signal occurs in any stock, buy/ sell alarm must appear on display irrespective of any stock chart i am onto. Your suggestions are of great help for all users here. Thx

    from
    yuvraj

  3. Hi Rajendranji,

    even after downloading from the site it is not getting worked on my ami software. please help. it is a 2 kb file which getting downloaded every time.

  4. Dear Mr. Rajendra,

    I want to write AFL but not know how to do it.
    My condition is as follows:
    if EMA C 5 cross EMA Open 6 from bottom then Buy and all price is inorder like this

    Closing price
    EMA C 5
    EMA O 6
    EMA C 20
    EMA C 50
    EMA C 100

    Please help

  5. Dear Rajendran and well wishers, Thanks for all the good work. There are so many AFLs available, even on your blog you have “trend magic” and “super trend” indicator. which one would be better ?

    Stockmaniacs dot net website offers “super scalper” and “trend blaster” which mentions 80-90% accuracy and 300% returns, etc.

    Do you know of any link or has anyone compared the AFLs for the last 6 months to compare the results between the systems ? Maybe of someone good at AFL volunteers, we might have some concrete results etc.

    Just my curiosity. Thanks in advance.

    Raj

  6. hello mr rajendran, i would also like to know which system is better supertrend or trendmagic??

  7. Hi, The super trend EOD chart is not updated on EOD basis as mentioned.
    Can you please check…..it usually happen once in 3 or 4 days.
    A question: the trend magic indicator is the same as super trend or is it a different one?

    rgds,Deepak

    1. Deepak,

      Trend Magic is CCI based indicator and Supertrend is ATR based indicator. And for EOD charts iam coming with alternate update as iam facing some issues with datafeed.

  8. Dear Rajendran,

    I happened to come across your Supertrend indicator and find it very useful.
    Can you please add the alf to realtime scan and real time alert also for the same…

    Thanks and wish you great going,
    Mahesh.

  9. DEAR SIR,
    ANY BEST INDICATOR FOR STOCK MARKET EOD CHART AND INTRADAY BEST GOLD SILVER

  10. DAER RAJENDRA SIR CAN U PROVIDE ME WITH A PUSH BULLET WHICH MAY GIVE SINGNALS TO X NUMBER OF MACHINES FROM SINGLE SYATEM

  11. here is the mt4 version of halftrend
    //@version=4
    // Copyright (c) 2021-present, Alex Orekhov (everget)
    study(“HalfTrend”, overlay=true)

    amplitude = input(title=”Amplitude”, defval=2)
    channelDeviation = input(title=”Channel Deviation”, defval=2)
    showArrows = input(title=”Show Arrows”, defval=true)
    showChannels = input(title=”Show Channels”, defval=true)

    var int trend = 0
    var int nextTrend = 0
    var float maxLowPrice = nz(low[1], low)
    var float minHighPrice = nz(high[1], high)

    var float up = 0.0
    var float down = 0.0
    float atrHigh = 0.0
    float atrLow = 0.0
    float arrowUp = na
    float arrowDown = na

    atr2 = atr(100) / 2
    dev = channelDeviation * atr2

    highPrice = high[abs(highestbars(amplitude))]
    lowPrice = low[abs(lowestbars(amplitude))]
    highma = sma(high, amplitude)
    lowma = sma(low, amplitude)

    if nextTrend == 1
    maxLowPrice := max(lowPrice, maxLowPrice)

    if highma < maxLowPrice and close minHighPrice and close > nz(high[1], high)
    trend := 0
    nextTrend := 1
    maxLowPrice := lowPrice

    if trend == 0
    if not na(trend[1]) and trend[1] != 0
    up := na(down[1]) ? down : down[1]
    arrowUp := up – atr2
    else
    up := na(up[1]) ? maxLowPrice : max(maxLowPrice, up[1])
    atrHigh := up + dev
    atrLow := up – dev
    else
    if not na(trend[1]) and trend[1] != 1
    down := na(up[1]) ? up : up[1]
    arrowDown := down + atr2
    else
    down := na(down[1]) ? minHighPrice : min(minHighPrice, down[1])
    atrHigh := down + dev
    atrLow := down – dev

    ht = trend == 0 ? up : down

    var color buyColor = color.blue
    var color sellColor = color.red

    htColor = trend == 0 ? buyColor : sellColor
    htPlot = plot(ht, title=”HalfTrend”, linewidth=2, color=htColor)

    atrHighPlot = plot(showChannels ? atrHigh : na, title=”ATR High”, style=plot.style_circles, color=sellColor)
    atrLowPlot = plot(showChannels ? atrLow : na, title=”ATR Low”, style=plot.style_circles, color=buyColor)

    fill(htPlot, atrHighPlot, title=”ATR High Ribbon”, color=sellColor)
    fill(htPlot, atrLowPlot, title=”ATR Low Ribbon”, color=buyColor)

    buySignal = not na(arrowUp) and (trend == 0 and trend[1] == 1)
    sellSignal = not na(arrowDown) and (trend == 1 and trend[1] == 0)

    plotshape(showArrows and buySignal ? atrLow : na, title=”Arrow Up”, style=shape.triangleup, location=location.absolute, size=size.tiny, color=buyColor)
    plotshape(showArrows and sellSignal ? atrHigh : na, title=”Arrow Down”, style=shape.triangledown, location=location.absolute, size=size.tiny, color=sellColor)

    alertcondition(buySignal, title=”Alert: HalfTrend Buy”, message=”HalfTrend Buy”)
    alertcondition(sellSignal, title=”Alert: HalfTrend Sell”, message=”HalfTrend Sell”)

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More