Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, 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. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Visualizing Intraday PNL with Amibroker AFL

5 min read

Intraday traders often rely on quick decision-making supported by robust analytics. Tracking intraday profit and loss (PNL) in real-time can provide traders with essential insight into how their strategy is performing during the trading day. In this blog post, we will discuss an Amibroker AFL (AmiBroker Formula Language) code that visualizes intraday PNL while running a simple moving average crossover strategy as a prototype. The strategy itself can be replaced or enhanced as needed—our main focus is on the techniques used to visualize intraday equity changes and PNL.

Key Features of This Prototype

  • Uses a basic EMA crossover strategy as a placeholder.
  • Computes intraday PNL by comparing current equity to the day’s starting equity.
  • Plots intraday PNL as a colored area chart (green when positive, red when negative).
  • Allows user-defined parameters and times (signal start time, end time, and square-off time).
  • Can be extended or modified to reflect your own strategy logic.

Amibroker AFL Code with Intraday PNL Dashboard

//Rajandran R - Creator of OpenAlgo
//website - openalgo.in / marketcalls.in
//Intraday PNL Visualizer - Trading Module v1.0
//Date - 10/12/2024

_SECTION_BEGIN("Intraday Strategy with MTM Stoploss and Target");

//Initial Parameters

SetOption( "InitialEquity", 400000);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",1);
SetOption("CommissionAmount",0.02);
SetOption("AccountMargin",10);
SetOption("RefreshWhenCompleted",True);

//Position Sizing

SetPositionSize(1*RoundLotSize,spsShares);



//Parameters

MALength1 = param("MALength1",10,1,5,1);
MALength2 = param("MALength2",20,1,5,1);

starttime =  ParamTime("Signal Start Time", "09:30");
endtime =  ParamTime("Signal End Time", "15:00");
squareofftime = ParamTime("Squareoff Time", "15:15");

// Calculate EMAs
EMA1 = EMA(C, MALength1);
EMA2 = EMA(C, MALength2);


// Plot EMA1 and EMA2
Plot(EMA1, "EMA " + MALength1, colorBlue, styleThick);
Plot(EMA2, "EMA " + MALength2, colorRed, styleThick);


//Buy-Sell Logic

Buy = Cross(ema( C, MALength1 ),ema( C, MALength2 )) AND TimeNum()>=starttime AND TimeNum()<=endtime ;
Sell =Cross( ema( C, MALength2 ), ema( C, MALength1 )) OR TimeNum()>=squareofftime;

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

Short = Cross( ema( C, MALength2 ), ema( C, MALength1 )) AND TimeNum()>=starttime AND TimeNum()<=endtime ;
Cover = Cross(ema( C, MALength1 ),ema( C, MALength2 )) OR TimeNum()>=squareofftime;

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


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



//start = ParamDate( "Start Date", "2024-01-01" );
//end=ParamDate( "End Date", "2024-12-31" );
//e=Equity(1,3,start,end); //Calculates for the Date Specific Quotes

e = Equity();

//Plot(e, "Equity", colorYellow, styleArea);

newday = Day() != Ref(Day(),-1);


daystartequity = ValueWhen(newday,e); //Start of the day take the equity value as reference

intradaypnl = e - daystartequity; //Todays aka intraday PNL




_SECTION_END();


_SECTION_BEGIN("Candlestick Charts with Date & Time Axis");

//Enable the Date & Time Axis
SetChartOptions(0, chartShowArrows | chartShowDates);

//Plotting Candlestick charts
Plot(Close,"Candle",colorDefault,styleCandle);


_SECTION_END();




_SECTION_BEGIN("Trading Dashboard");


dashboard = ParamToggle("Trading Dashboard","Show|Hide",1);

// Parameter for UpColor
UpColor = ParamColor("UpColor", colorGreen);

// Parameter for DownColor
DownColor = ParamColor("DownColor", colorRed);

buycontinue = Flip(Buy,Sell);
shortcontinue =Flip(Short,Cover);



if(dashboard)
{

//Show Dashboard

//Setting the font and font size
GfxSelectFont("BOOK ANTIQUA",14);

//set the background mode
GfxSetBkMode(1); //Transparent mode

//Set the Text Color
GfxSetTextColor(colorWhite);

dashboardcolor = IIf(buycontinue,upcolor, IIf(shortcontinue, downcolor, colorGrey40));

GfxSelectSolidBrush(SelectedValue(dashboardcolor));

GfxSelectPen(colorWhite);

width = Status("pxwidth");
height = Status("pxheight");

x1 = 5;
y1 = height-200;

x2 = 400;
y2 = height-50;


//Draw the rectangle
GfxRectangle( x1, y1 , x2, y2);

//Draw the text inside the rectage
GfxTextOut("Intraday - Trading System",x1+20,y1+20);


//Get the Trading Signal Status - "Buy Signal" or "Short Signal"

sigstatus = WriteIf(buycontinue, "Buy Signal", WriteIf(shortcontinue, "Short Signal", "No Signal"));

GfxTextOut(sigstatus,x1+20,y1+50);

pnl =IIf(buycontinue,Close - BuyPrice, IIf(shortcontinue, ShortPrice - Close, Null));



//Accepts only string -> PNL is array
GfxTextOut("Profit/Loss : "+Prec(SelectedValue(pnl),2),x1+20,y1+80);

GfxTextOut("Intraday PNL : "+Prec(SelectedValue(intradaypnl),2),x1+20,y1+110);



}


_SECTION_END();


_SECTION_BEGIN("Trading Signals");

/* Plot Buy and Sell Signal Arrows */
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);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);



_SECTION_END();


_SECTION_BEGIN("Top Dashboard");

X0 = 10;
Y0 = 20;


//defining the procedures
procedure DrawData (Text, x1, y1, x2, y2, colorFrom, colorTo)
{
	GfxSetOverlayMode(0);
	GfxSelectFont("Verdana", 8.5, 700);
	GfxSetBkMode(1);
	GfxGradientRect(x1, y1, x2, y2, colorFrom, colorTo);
	GfxDrawText(Text, x1, y1, x2, y2, 32|1|4|16);
}


DrawData (Name(), X0, Y0, X0+150, Y0+20, colorGrey40, colorblack);
//DrawData (Date(), X0+155, Y0, X0+320, Y0+20, colorGrey40, colorblack);
DrawData ("Open : " + Open, X0+155, Y0, X0+320, Y0+20, colorGrey40, colorblack);
DrawData ("Close : " + Close, X0+325, Y0, X0+450, Y0+20, colorGrey40, colorblack);
DrawData ("High : " + High, X0+455, Y0, X0+580, Y0+20, colorGrey40, colorblack);
DrawData ("Low : " + Low, X0+585, Y0, X0+710, Y0+20, colorGrey40, colorblack);
//DrawData ("Timeframe : " + "5-Minute" , X0+845, Y0, X0+1050, Y0+20, colorGrey40, colorblack);
//DrawData ("Smooth Osc : " + RSI(14), X0+1055, Y0, X0+1225, Y0+20, colorGrey40, colorblack);


_SECTION_END();

SetOption():
This function is used to configure various environment settings. For instance:

  • SetOption("InitialEquity", 400000) sets the starting capital.
  • SetOption("FuturesMode", True) indicates that we are trading in futures mode.
  • SetOption("CommissionMode", 1) and SetOption("CommissionAmount", 0.02) define how commissions are calculated.

Equity():
The Equity() function calculates the equity curve based on the trading logic defined by Buy/Sell/Short/Cover signals. It helps us track how the strategy’s hypothetical capital grows or shrinks over time.

Intraday PNL Calculation:
With Equity() calculated, we determine the intraday PNL as:

newday = Day() != Ref(Day(), -1);      // True when a new day starts
daystartequity = ValueWhen(newday, e); // Captures the equity at start of day
intradaypnl = e - daystartequity;      // Current equity minus day's start equity

Intraday PNL Visualizer – Amibroker AFL Code

//Rajandran R - Creator of OpenAlgo
//website - openalgo.in / marketcalls.in
//Intraday PNL Visualizer - Trading Module v1.0
//Date - 10/12/2024

_SECTION_BEGIN("Intraday Strategy with MTM Stoploss and Target");

//Initial Parameters

SetOption( "InitialEquity", 400000);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",1);
SetOption("CommissionAmount",0.02);
SetOption("AccountMargin",10);
SetOption("RefreshWhenCompleted",True);

//Position Sizing

SetPositionSize(1*RoundLotSize,spsShares);



//Parameters

MALength1 = param("MALength1",10,1,5,1);
MALength2 = param("MALength2",20,1,5,1);

starttime =  ParamTime("Signal Start Time", "09:30");
endtime =  ParamTime("Signal End Time", "15:00");
squareofftime = ParamTime("Squareoff Time", "15:15");

// Calculate EMAs
EMA1 = EMA(C, MALength1);
EMA2 = EMA(C, MALength2);



//Buy-Sell Logic

Buy = Cross(ema( C, MALength1 ),ema( C, MALength2 )) AND TimeNum()>=starttime AND TimeNum()<=endtime ;
Sell =Cross( ema( C, MALength2 ), ema( C, MALength1 )) OR TimeNum()>=squareofftime;

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

Short = Cross( ema( C, MALength2 ), ema( C, MALength1 )) AND TimeNum()>=starttime AND TimeNum()<=endtime ;
Cover = Cross(ema( C, MALength1 ),ema( C, MALength2 )) OR TimeNum()>=squareofftime;

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


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



//start = ParamDate( "Start Date", "2024-01-01" );
//end=ParamDate( "End Date", "2024-12-31" );
//e=Equity(1,3,start,end); //Calculates for the Date Specific Quotes

e = Equity();

//Plot(e, "Equity", colorYellow, styleArea);

newday = Day() != Ref(Day(),-1);


daystartequity = ValueWhen(newday,e); //Start of the day take the equity value as reference

intradaypnl = e - daystartequity; //Todays aka intraday PNL

color = IIf(intradaypnl>0, colorGreen, colorRed);

Plot(intradaypnl, "Intraday PNL", color, styleThick | styleArea);


_SECTION_END();


This AFL code demonstrates a straightforward approach to visualizing your intraday PNL while executing a prototype trading strategy. The key takeaway is not the strategy itself—feel free to plug in your preferred signals, overlays, and filters—but rather the use of crucial AFL functions like Equity(), ValueWhen(), and ExRem() to manage signals and compute real-time intraday results.

You can further enhance this by:

  • Implementing your preferred entry and exit logic.
  • Adding more sophisticated risk management rules.
  • Incorporating advanced analytics like volatility filters or higher timeframe confirmations.

By understanding these building blocks, you open the door to creating more informed and data-driven intraday trading tactics in Amibroker.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, 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. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

CUSUM Filter Strategy in AmiBroker AFL: A Practical Implementation

Detecting meaningful shifts in price trends while filtering out market noise is a challenge many traders face. Inspired by Jakub Polec’s blog, which applies...
Rajandran R
2 min read

Fisher Transform – Amibroker AFL Code

The Fisher Transform is a technical analysis indicator developed by John F. Ehlers, designed to identify potential turning points in the price movements of...
Rajandran R
2 min read

Leave a Reply

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