Smart Button Trading Module – Trade Automation – Amibroker AFL Code

This Algomojo Button trading module provides 4 modes of the button to place orders with a single click directly from Amibroker using simple smart order controls.

Four Button Types

BE – Buy Entry Button – Enter longs for the selected quantity
BX – Buy Exit Button – Exit All Long Open Positions only if the Position is running long else do nothing
SE – Short Entry Button – Enter Shorts for the selected quantity
SX – Short Exit Button – Exit All Short Open Positions only if the Position is running shorts else do nothing

Supported Amibroker Version

Amibroker v6.22 or higher

Supported Broker – AngelOne

Automation Platform – Algomojo Trading Terminal

Smart Button Trading Module – Amibroker AFL Code

// Angel Broking - Smart Button Trading Module
// Developer: Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo)
// Date: 19-Apr-2022
// Website: algomojo.com / marketcalls.in

//BE - Buy Entry Button
//BX - Buy Exit Button - Exit All Long Open Positions only if the Position is running longs
//SE - Short Entry Button
//SX - Short Exit Button - Exit All Short Open Positions only if the Position is running shorts

_SECTION_BEGIN("Angel Broking - Broker Controls");

Version(6.22); //Gui Function Compatibility check

RequestTimedRefresh(1, False); 

broker =ParamStr("Broker","an"); //Broker Short Code - an- angel broking
ver = ParamStr("API Version ","1.0");
clnt_id = ParamStr("Client ID","xxxx"); //Enter your trading client ID
user_apikey = ParamStr("apikey","xxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secretkey = ParamStr("secretkey","xxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here

_SECTION_END();

_SECTION_BEGIN("Angel Broking - Order Controls");

stgy_name = ParamStr("Strategy Name", "Test Strategy");
variety = ParamList("Variety","NORMAL|STOPLOSS|AMO",0); 
tradingsymbol = ParamStr("Trading Symbol","RELIANCE-EQ");


exchange = ParamList("Exchange","NSE|NFO|BSE|MCX",0); 
ordertype = ParamList("Order Type","MARKET|LIMIT|STOPLOSS_LIMIT|STOPLOSS_MARKET",0);
producttype = ParamList("Product Type","DELIVERY|CARRYFORWARD|MARGIN|INTRADAY|AMO_MARGIN|AMO_DELIVERY|AMO_CARRYFORWARD",3);

price = "0"; 
triggerprice = "0"; 
quantity = Param("quanity",1,0,10000);

squareoff = "0"; 
stoploss = "0"; 
trailingStopLoss = "0"; 
disclosedquantity = "0"; 
duration = "DAY";




EnableAlgo = ParamList("AlgoStatus","Disable|Enable|LongOnly|ShortOnly",0);
resp = "";


static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";


function GetPositionsBook()
{
//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");

api_data = "{ }";
_TRACE("PositionBook API Request"+api_data);

//Sending The Broker Request for NetOpenPositions
resp=algomojo.AMDispatcher(user_apikey,api_secretkey,"Positions",api_data,broker,ver);
_TRACE("PositionBook API Response : "+resp);

return resp;

}

function NetOpenPositions()
{
flag = 0;

resp = GetPositionsBook();

posNetqty =0;

for( item = 1; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{



if(Strfind(sym,tradingsymbol) AND StrFind(sym,productType)) //Matches the symbol and //Matches the Order Type
{

flag = 1; //turn on the flag

for( jitem = 0; ( posdetails = StrExtract( sym, jitem,',' )) != ""; jitem++ )
{

 if(Strfind(posdetails,"tradingsymbol"))
  {
   posdetails = StrExtract(posdetails,1,':');
   possym = StrTrim(posdetails,"\"");
    _TRACE("\nTrading Symbol : "+possym);
  }

  if(Strfind(posdetails,"netqty"))
  {
   posdetails = StrExtract(posdetails,1,':');
   posNetqty = StrToNum(StrTrim(posdetails,"\""));
   _TRACE("\nNetQty : "+posNetqty);
  }
  

} //end of for loop
}

}//end of for loop


if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
 posNetqty =0;
_TRACE("\nNetQty : "+posNetqty);
}

return posNetqty;

}

//Buy and Sell Order Functions
function Placeorder(TransType,orderqty)
{
	
    algomojo=CreateObject("AMAMIBRIDGE.Main");
    symboltoken = "";
    api_data ="{\"stgy_name\": \""+stgy_name+"\",  \"variety\":\""+variety+"\",  \"tradingsymbol\":\""+tradingsymbol+"\",      \"symboltoken\":\""+symboltoken+"\",         \"transactiontype\":\""+TransType+"\",         \"exchange\":\""+exchange+"\",         \"ordertype\":\""+ordertype+"\",         \"producttype\":\""+producttype+"\",         \"duration\":\""+duration+"\",         \"price\":\""+price+"\",         \"squareoff\":\""+squareoff+"\",         \"stoploss\":\""+stoploss+"\",         \"quantity\":\""+orderqty+"\",         \"triggerprice\": \""+triggerprice+"\",  \"trailingStopLoss\": \""+trailingStopLoss+"\", \"disclosedquantity\":\""+disclosedquantity+"\" }";
   
    _TRACE("API Request"+api_data);
    resp=algomojo.AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data,broker,ver);
    _TRACE("API Response : "+resp);
    _TRACE("Strategy Name : "+stgy_name+"  AlgoStatus : "+ EnableAlgo);
    _TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  tradingsymbol +"  qty : "+ orderqty +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID() + " LTP : "+LastValue(C));
	Say( "Order Placed" ); 
}



_SECTION_BEGIN("Algo Dashboard");


static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";

//StaticVarSet(static_name_algo, -1); 
GfxSelectFont( "BOOK ANTIQUA", 14, 100 );
GfxSetBkMode( 1 );
if(EnableAlgo == "Enable")
{
AlgoStatus = "Algo Enabled";
GfxSetTextColor( colorGreen ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=1)
{
_TRACE("Algo Status : Enabled");
StaticVarSet(static_name_algo, 1);
}
}
if(EnableAlgo == "Disable")
{
AlgoStatus = "Algo Disabled";
GfxSetTextColor( colorRed ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=0)
{
_TRACE("Algo Status : Disabled");
StaticVarSet(static_name_algo, 0);
}
}



_SECTION_END();

//Button Controls


btn1_name = "BE"; //BE- Buy Entry
btn2_name = "BX"; //BX - Buy Exit - close all the open positions
btn3_name = "SE"; //SE - Short Entry
btn4_name = "SX"; //SX - Short Exit - close all the open positions



function CreateGUI( ButtonName, x, y, width, Height ) {
	/// @link http://forum.amibroker.com/t/guibuttons-for-everyone/1716/4
	/// by beaver & fxshrat
	/// version 1.1
	global IDset;
	local id, event, clickeven;
	
	if( typeof( IDset ) == "undefined" ) IDset = 0; 

	//_TRACEF( "IDset before: %g", IDset );	
	GuiButton( ButtonName, ++IDset, x, y, width, height, 7 ); 
	//_TRACEF( "IDset after: %g", IDset );
	result = 1; //button creation is successful
	return result;
	
}


function HandleEvents()
{

	result = 0;
	id = GuiGetEvent( 0, 0 );// receiving button id
	event = GuiGetEvent( 0, 1 );// receiving notifyflag
	clickevent = event == 1;
	
	
	
	
	
	BE = id == 1 && clickevent;
	BX = id == 2 && clickevent;
	SE = id == 3 && clickevent;
	SX = id == 4 && clickevent;
	
	
	
	result = 0;
	
	if(EnableAlgo == "Enable")
	{
	
	if( BE AND StaticVarGet(Name()+GetChartID()+"BuyEntry")==0 ) 
	{
		_TRACE("BuyEntry is pressed");
		orderresponse = PlaceOrder("BUY",quantity);
		result = 1;
		StaticVarSet(Name()+GetChartID()+"BuyEntry",1); 
	}
	else
	{
		
		StaticVarSet(Name()+GetChartID()+"BuyEntry",0);
	}
	
	if( BX AND StaticVarGet(Name()+GetChartID()+"BuyExit")==0 ) 
	{
		_TRACE("BuyExit is pressed");
		if((qty=NetOpenPositions())>0) //if long positons are open
		{
		orderresponse = PlaceOrder("SELL",qty);
		result = 1;
		}
		else
		{
		_TRACE("No Long Positions Open");
		}
		
		StaticVarSet(Name()+GetChartID()+"BuyExit",1); 
	}
	else
	{
		
		StaticVarSet(Name()+GetChartID()+"BuyExit",0);
	}
	
	if( SE AND StaticVarGet(Name()+GetChartID()+"ShortEntry")==0 ) 
	{
		_TRACE("BShortEntry is pressed");
		orderresponse = PlaceOrder("SELL",quantity);
		result = 1;
		StaticVarSet(Name()+GetChartID()+"ShortEntry",1); 
	}
	else
	{
		
		StaticVarSet(Name()+GetChartID()+"ShortEntry",0);
	}
	

	
	if( SX AND StaticVarGet(Name()+GetChartID()+"ShortExit")==0 ) 
	{
		_TRACE("ShortExit is pressed");
		if((qty=NetOpenPositions())<0) //if short positons are open
		{
		orderresponse = PlaceOrder("BUY",abs(qty));
		result = 1;
		}
		else
		{
		_TRACE("No Short Positions Open");
		}
		
		StaticVarSet(Name()+GetChartID()+"ShortExit",1); 
	}
	else
	{
		
		StaticVarSet(Name()+GetChartID()+"ShortExit",0);
	}
	
	} 


return result;  //result = 1 - order is successfully placed, 0 - Algotrading is in disabled state or orders are not went through
	
}//end of function
	
	ButtonXOffset = Param("Button X-Offset",0,50,1000,50);
	ButtonYOffset = Param("Button Y-Offset",100,0,1000,50);
	
	BuyEntry = CreateGUI( btn1_name, ButtonXOffset, ButtonYOffset, 50, 50 );
	BuyExit = CreateGUI( btn2_name, ButtonXOffset+50, ButtonYOffset, 50, 50 );
	
	ShortEntry = CreateGUI( btn3_name, ButtonXOffset , ButtonYOffset+50, 50, 50 );
	ShortExit = CreateGUI( btn4_name, ButtonXOffset +50, ButtonYOffset+50, 50, 50 );

	
	
	handleevents();
	
	
	
	GuiSetColors( 1, 1, 2, colorGreen, colorBlack, colorGreen, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow ); 
	GuiSetColors( 2, 2, 2, colorred, colorBlack, colorRed, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow ); 


	GuiSetColors( 3, 3, 2, colorOrange, colorBlack, colorOrange, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow ); 
	GuiSetColors( 4, 4, 2, colorPaleGreen, colorBlack, colorPaleGreen, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow ); 

_SECTION_END();	
	
_SECTION_BEGIN("Plot Candles");	

SetChartOptions(0 , chartShowArrows | chartShowDates);
Plot(Close,"Candle", colorDefault, styleCandle);

_SECTION_END();

Leave a Reply

Your email address will not be published. Required fields are marked *