Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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

Stoploss, Multi Target, and Trailing Stoploss Module – Amibroker AFL Code V2.0

14 min read

After Intraday V2.0 Amibroker Module – a readymade drag and drop module to convert any trading strategy into the intraday trading system with alerts, stop loss, target feature with intraday controls many users demanded a plug-n-play aka another drag and drop module to convert any trading strategy coded in Amibroker with Buy,Sell, Short,Cover into Multi Targets (Target1, Target2), Stoploss and Trailing Stoploss Module. Code Supports Automated Execution using PlaceSmartOrder and Split Facility controls.

Features of the Module

  • Module with Stoploss and Two Target Management (T1-Partial Exit and T2- Complete Exit)
  • Drag and Drop on Any of your simple trading strategies rest Amibroker module will take care of.
  • Dashboard which shows the current target1, target2, stoploss and trailingstoploss levels.
  • Easy to Integrate Automated Trading Modules and Algotrading platforms like Algomojo.

Steps to use the module

1)Download the AFL Code and Store it as trademanagement.afl under any of the Amibroker Formulas Folder.

2)Ensure your strategy has Buy,sell,short,cover parameters. Apply your trading system on a blank chart and drag and drop the trademanagement.afl on top of your trading system

3)if your strategy doesn’t has short and cover variables use short =0; and cover = 0; in your code before dragging and dropping

4)Use the code only on Top of the trading strategy with plain vanilla buy,sell,short,cover variables defined.

5)Avoid giving any trade delay in your strategy as it is already handled inside the module

Warning :
AFL Code is not back testable for Multi Targets as sigscalein
or sigscaleout is not implemented Module. AFL module is built for Algotraders who want to automate their trading system

Stoploss, Multi Target, and Trailing Stoploss Module – Amibroker AFL Code

//Stoploss and Target Module - Readymade Module (Drag and Drop on top of your trading strategy)
//Built in Target1, Target2, Stoploss and Trailing Stoploss Based Exit (Touch based Exit)
//Regular Exit(Close of Candle/Touch of the level)
//Supported Brokers : All Algomojo Supported Brokers for Trade Automation

//Warning : Use the Module only on top of a trading strategy with proper buy, sell,short,cover variables defined
//Avoid giving any delay in your strategy as it is already handles inside the module
//Warning Code is not backtestable for Multi Targets as sigscalein/sigscaleout is not implemented
//Module is built for Algotraders who want to automate their trading system
//Code Supports Automated Execution using PlaceSmartOrder and Split Facility controls.

//Coded by Rajandran R - Founder - Marketcalls / Co-Founder - Algomojo
//Coded on 22nd Feb 2023
//Website - www.marketcalls.in / www.algomojo.com
//Version - 2.0

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();


_SECTION_BEGIN("Stoploss, Multi Target and Trailing Stoploss Module");

//Remove Excessive Signals
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);


TickSz = Param("Tick Size",0.05);
mode = ParamList("Stop and Target Mode","Points|Percentage");
stops = Param("Stoploss",50,0.05,1000,0.05);
target1 = Param("Target 1",100,0.05,1000,0.05);
target2 = Param("Target 2",100,0.05,1000,0.05);
tsl = Param("Trailing Stop",100,0.05,1000,0.05);

Quantity = Param("Entry Quantity",1000,1,10000,1);
target1exit = Param("Target 1 Exit(qty)",500,1,10000,1);
target2exit = Paramstr("Target 2 Exit(qty)","FULL"); //Dummy control mostly information purpose only

//Initializing the Open Position
openposition = 0; 

//Signal Executes on Close of the Candle
SignalDelay = Param("Signal Delay",1,0,10,1);

Buy = Ref(Buy,-SignalDelay);
iSell = Ref(Sell,-SignalDelay);

SetTradeDelays(0,0,0,0); //No Trade Delays provided
BuyPrice = ValueWhen(Buy,Open);

Buytsllevel = Null;

if(mode=="Points")
{
BuyStop = BuyPrice - stops;
BuyTarget1 = BuyPrice + target1;
BuyTarget2 = BuyPrice + target2;
Buytsllevel = BuyPrice - tsl;
}


if(mode=="Percentage")
{
BuyStop1 = (100-stops)/100*BuyPrice; 
BuyTarget1 = (100+target1)/100*BuyPrice;
BuyTarget2 = (100+target2)/100*BuyPrice;
Buytsllevel1 = (100-tsl)/100*high; 

//Round it of to nearest Tick Size
BuyStop = TickSz * round(Buystop1/TickSz);
BuyTarget1 = TickSz * round(BuyTarget1/TickSz);
BuyTarget2 = TickSz * round(BuyTarget2/TickSz);
Buytsllevel = TickSz * round(Buytsllevel1/TickSz);

}

buytslarray = Null;
//if buytrailstop >0 -> long trades are running
buytrailstop = 0; 
bt1flag = 0;
bt1hit = False;
bt2hit = False;


for(i=0;i<BarCount;i++)
{
	//Identifying Very First Buy
	if(Buy[i] AND buytrailstop == 0)
	{
	//Calculate the trailstop
	
	buytrailstop = Buytsllevel[i];
	
	openposition[i] = Quantity; //fullposition
	}
	//else 
	//{
	//Buy[i] = false; //Removing Excessive Buy
	//}
	//if buy signal continues at the same time if the trailstop hits
	if(buytrailstop>0 AND Low[i] < buytrailstop)
	{
	
	Sell[i] = True;
	SellPrice[i] = buytrailstop;
	buytrailstop = 0;  // reset the flag to zero -> so that it can take fresh buy signal
	openposition[i] =0;
	bt1flag = 0;
	
	}
    //if buy signal continues at the same time if the Target1 hits
	if(buytrailstop>0 AND high[i] > BuyTarget1[i] AND bt1flag==0 )
	{
	
	bt1hit[i] = True;
	openposition[i] = Quantity - target1exit;
	bt1flag = 1; //enabling target1 hit flag - to avoid multiple target 1 hits
	
	}
	//if buy signal continues at the same time if the Target2 hits
	if(buytrailstop>0 AND high[i] > BuyTarget2[i])
	{
	
	bt2hit[i] = True;
	openposition[i] = 0;
	bt1flag = 0; //enabling target1 hit flag
	Sell[i] = True;
	SellPrice[i] = BuyTarget2[i];
	buytrailstop = 0; 
	}
	
	if(buytrailstop>0 AND low[i] < Buystop[i])
	{
	
	
	openposition[i] = 0;
	bt1flag = 0; //reset target1 hit flag
	Sell[i] = True;
	SellPrice[i] = Buystop[i];
	buytrailstop = 0; 
	}
	
	
	// if buy signal continues -> upgrade my stoploss
	if(buytrailstop>0 AND !Buy[i] AND !Sell[i] AND !bt1hit[i])
	{
	
	
	if(mode=="Percentage")
	{
	buytrailstop = Max( Buytsllevel[i],buytrailstop); //Trailing to the newer stoploss
	}
	if(mode=="Points")
	{
	buytrailstop = Max( High[i]-tsl,buytrailstop); //Trailing to the newer stoploss
	}
	openposition[i] = openposition[i-1]; //previous open position continues
	buytslarray[i] = buytrailstop;
	}
	
	

} //end of for loop




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

buycontinue = Flip(Buy,Sell);


//Plot Stops and Targets, TrailingStops - only if the trade is continuing

Plot(IIf(buycontinue OR Sell, BuyStop,Null),"BuyStops",colorRed,styleDashed | styleThick);
Plot(IIf(buycontinue OR Sell, Buytarget1,Null),"BuyTarget1",colorGreen,styleDashed | styleThick);
Plot(IIf(buycontinue OR Sell, Buytarget2,Null),"BuyTarget2",colordarkGreen,styleDashed | styleThick);
Plot(IIf(buycontinue OR Sell, buytslarray,Null),"BuyTSL",colorYellow,styleDashed | styleThick);

/* 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(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(IIf(bt1hit, shapeCircle, shapeNone),colorGreen, 0,H, Offset=25);



Short = Ref(Short,-SignalDelay);
iCover = Ref(Cover,-SignalDelay);


ShortPrice = ValueWhen(Short,Open);

Shorttsllevel = Null;

if(mode=="Points")
{
ShortStop = ShortPrice + stops;
ShortTarget1 = ShortPrice - target1;
ShortTarget2 = ShortPrice - target2;
Shorttsllevel = ShortPrice + tsl;
}


if(mode=="Percentage")
{
ShortStop1 = (100+stops)/100*ShortPrice; 
ShortTarget1 = (100-target1)/100*ShortPrice;
ShortTarget2 = (100-target2)/100*ShortPrice;
Shorttsllevel1 = (100+tsl)/100*Low; 

//Round it of to nearest Tick Size
ShortStop = TickSz * round(Shortstop1/TickSz);
ShortTarget1 = TickSz * round(ShortTarget1/TickSz);
ShortTarget2 = TickSz * round(ShortTarget2/TickSz);
Shorttsllevel = TickSz * round(Shorttsllevel1/TickSz);

}


Shorttslarray = Null;
//if Shorttrailstop >0 -> long trades are running
Shorttrailstop = 0; 
st1flag = 0;
st1hit = False;
st2hit = False;


for(i=0;i<BarCount;i++)
{
	//Identifying Very First Short
	if(Short[i] AND Shorttrailstop == 0)
	{
	//Calculate the trailstop
	
	Shorttrailstop = Shorttsllevel[i];
	
	openposition[i] = -1*Quantity; //fullposition
	}
	//else 
	//{
	//Short[i] = false; //Removing Excessive Short
	//}
	//if Short signal continues at the same time if the trailstop hits
	if(Shorttrailstop>0 AND high[i] > Shorttrailstop)
	{
	
	Cover[i] = True;
	CoverPrice[i] = Shorttrailstop;
	Shorttrailstop = 0;  // reset the flag to zero -> so that it can take fresh Short signal
	openposition[i] =0;
	st1flag = 0;
	
	}
    //if Short signal continues at the same time if the Target1 hits
	if(Shorttrailstop>0 AND low[i] < ShortTarget1[i] AND st1flag==0 )
	{
	
	st1hit[i] = True;
	openposition[i] = Quantity + target1exit;
	st1flag = 1; //enabling target1 hit flag - to avoid multiple target 1 hits
	
	}
	//if Short signal continues at the same time if the Target2 hits
	if(Shorttrailstop>0 AND low[i] < ShortTarget2[i])
	{
	
	st2hit[i] = True;
	openposition[i] = 0;
	st1flag = 0; //enabling target1 hit flag
	Cover[i] = True;
	CoverPrice[i] = ShortTarget2[i];
	Shorttrailstop = 0; 
	}
	
	if(Shorttrailstop>0 AND high[i] > Shortstop[i])
	{
	
	
	openposition[i] = 0;
	st1flag = 0; //reset target1 hit flag
	Cover[i] = True;
	CoverPrice[i] = Shortstop[i];
	Shorttrailstop = 0; 
	}
	
	
	// if Short signal continues -> upgrade my stoploss
	if(Shorttrailstop>0 AND !Short[i] AND !Cover[i] AND !st1hit[i])
	{
	
	if(mode=="Percentage")
	{
	Shorttrailstop = Min( Shorttsllevel[i],Shorttrailstop); //Trailing to the newer stoploss
	}
	if(mode=="Points")
	{
	Shorttrailstop = Min( Low[i]+tsl,Shorttrailstop); //Trailing to the newer stoploss
	}
	openposition[i] = openposition[i-1]; //previous open position continues
	Shorttslarray[i] = Shorttrailstop;
	}
	
	

} //end of for loop




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

Shortcontinue = Flip(Short,Cover);


//Plot Stops and Targets, TrailingStops - only if the trade is continuing

Plot(IIf(Shortcontinue OR Cover, ShortStop,Null),"ShortStops",colorViolet,styleDashed | styleThick);
Plot(IIf(Shortcontinue OR Cover, Shorttarget1,Null),"ShortTarget1",colorRed,styleDashed | styleThick);
Plot(IIf(Shortcontinue OR Cover, Shorttarget2,Null),"ShortTarget2",colorDarkRed,styleDashed | styleThick);
Plot(IIf(Shortcontinue OR Cover, Shorttslarray,Null),"ShortTSL",colorAqua,styleDashed | styleThick);

/* Plot Short and Cover Signal Arrows */

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(IIf(st1hit, shapeCircle, shapeNone),colorGreen, 0,H, Offset=25);

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

_SECTION_END();

//Dashboard Controls.


_SECTION_BEGIN("Trading Dashboard");

strategy_name = ParamStr("Strategy Name","Simple Trading System");
fontsize = Param("Font Size",14,12,36,1);

GfxSelectFont("BOOK ANTIQUA", fontsize, 400);
GfxSetBkMode(1);  //Transparent Mode
GfxSetTextColor(colorWhite);

//build dyanmic dashboard colors based on the ongoing trades
color = IIf(buycontinue,colorGreen,IIf(shortcontinue,colorRed,colorGrey40));

GfxSelectPen(colorWhite);
GfxSelectSolidBrush(SelectedValue(color));

width = Status("pxchartwidth"); //output will be in terms of number of pixels
height = Status("pxchartheight");

//GfxRoundRect(20,height-150,320,height-30,15,15);

GfxGradientRect(20,height-150,320,height-30,SelectedValue(color),colorGrey40);

sigstatus = WriteIf(buycontinue,"Buy Signal",WriteIf(shortcontinue,"Short Signal","No Trade - Relax"));
PNL =  IIf(buycontinue,Close-buyprice,IIf(shortcontinue,ShortPrice-close,Null));
GfxTextOut(strategy_name,30,height-150);
GfxTextOut("Target1"+" : "+IIf(buycontinue,Buytarget1,IIf(shortcontinue,Shorttarget1,Null)),30,height-120);
GfxTextOut("Target2"+" : "+IIf(buycontinue,Buytarget2,IIf(shortcontinue,Shorttarget2,Null)),30,height-100);
GfxTextOut("Stop"+" : "+IIf(buycontinue,Buystop,IIf(shortcontinue,Shortstop,Null)),30,height-80);
//GfxTextOut("OpenPosition"+" : "+openposition,30,height-60);
GfxTextOut("TSL"+" : "+IIf(buycontinue,Buytslarray,IIf(shortcontinue,Shorttslarray,Null)),30,height-60);





_SECTION_END();

								
/*
Algomojo - Smart Order Trading Module with Split Order and Button Trading with Target Exit Controls
Created By : Rajandran R(Founder - Marketcalls / Co-Founder Algomojo )
Created on : 23 Feb 2023.
Website : www.marketcalls.in / www.algomojo.com
*/

_SECTION_BEGIN("Algomojo - Broker Controls");


// Send orders even if Amibroker is minimized or Chart is not active
RequestTimedRefresh(1, False); 

//Creating Input Controls for Setting Order Related Information

broker =Paramlist("Broker","an|ab|fs|fy|gc|pt|sm|tc|up|zb|ze",0);
ver = ParamStr("API Version ","v1");
apikey = ParamStr("apikey","xxxxxxxxxxxxxxxxxx"); //Enter your API key here
apisecret = ParamStr("secretkey","xxxxxxxxxxxxxxxxxx"); //Enter your API secret key here

_SECTION_END();

_SECTION_BEGIN("Algomojo - Order Controls");

strategy = ParamStr("Strategy Name", "Ami Strategy");

exchange = ParamList("Exchange","NSE|NFO|BSE|MCX",0); 
symbol = ParamStr("Trading Symbol","BHEL-EQ");
product = ParamList("Product","CNC|MIS|NRML",1);

pricetype = "MARKET";
//quantity = Param("Quantity",1,1,100000,1);
price = 0; 
disclosed_quantity = 0;
trigger_price = 0;
amo = "NO";
splitorder = ParamList("To Split Orders","NO|YES",0);
split_quantity = Param("Split Quantity",500,1,100000,1);

Entrydelay = Param("Entry Delay",0,0,1,1);
Exitdelay = Param("Exit Delay",0,0,1,1);
EnableButton = ParamList("Button Trading","Disable|Enable",0);
VoiceAlert = ParamList("Voice Alert","Disable|Enable",1);
EnableAlgo = ParamList("AlgoStatus","Disable|Enable|LongOnly|ShortOnly",0);
resp = "";

//Static Variables for Order protection

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

AlgoBuy = lastvalue(Ref(Buy,-Entrydelay));
AlgoSell = lastvalue(Ref(Sell,-Exitdelay));
AlgoShort = lastvalue(Ref(Short,-Entrydelay));
AlgoCover = lastvalue(Ref(Cover,-Exitdelay));
Algobt1target = lastvalue(bt1hit);
Algost1target = lastvalue(st1hit);
AlgoOpenPosition = LastValue(openposition);

printf("\nopenposition "+openposition);

//Algomojo Dashboard

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);
}
}
if(EnableAlgo == "LongOnly")
{
AlgoStatus = "Long Only";
GfxSetTextColor( colorYellow ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=2)
{
_TRACE("Algo Status : Long Only");
StaticVarSet(static_name_algo, 2);
}
}
if(EnableAlgo == "ShortOnly")
{
AlgoStatus = "Short Only";
GfxSetTextColor( colorYellow ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=3)
{
_TRACE("Algo Status : Short Only");
StaticVarSet(static_name_algo, 3);
}
}

//Button Trading Module

X0 = 20;
Y0 = 100;
X1 = 60;

LBClick = GetCursorMouseButtons() == 9;	// Click
MouseX  = Nz(GetCursorXPosition(1));		// 
MouseY  = Nz(GetCursorYPosition(1));		//

procedure DrawButton (Text, x1, y1, x2, y2, colorFrom, colorTo)
{
	GfxSetOverlayMode(0);
	GfxSelectFont("Verdana", 9, 700);
	GfxSetBkMode(1);
	GfxGradientRect(x1, y1, x2, y2, colorFrom, colorTo);
	GfxDrawText(Text, x1, y1, x2, y2, 32|1|4|16);
}
GfxSetTextColor(colorWhite);

//PlaceOrder Sends Market Order Returns response on Succesful PlaceOrder

function PlaceOrder(action,orderqty) {

//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data


api_data = "{ \"broker\": \""+broker+"\",
            \"strategy\":\""+strategy+"\",
            \"exchange\":\""+exchange+"\",
            \"symbol\":\""+symbol+"\",
            \"action\":\""+action+"\",
            \"product\":\""+product+"\",
            \"pricetype\":\""+pricetype+"\",
            \"quantity\":\""+orderqty+"\",
            \"price\":\""+price+"\",      
            \"disclosed_quantity\":\""+disclosed_quantity+"\",
            \"trigger_price\":\""+trigger_price+"\",
            \"amo\":\""+amo+"\",
            \"splitorder\":\""+splitorder+"\",
            \"split_quantity\":\""+split_quantity+"\"
          
        }"; 

_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceOrder",api_data,"am",ver);

_TRACE("API Response : "+resp);

if(VoiceAlert == "Enable")
	Say( "Order Placed" ); 

return resp;

}

function PlaceSmartOrder(action,orderqty,position_size) {

//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data


api_data = "{ \"broker\": \""+broker+"\",
            \"strategy\":\""+strategy+"\",
            \"exchange\":\""+exchange+"\",
            \"symbol\":\""+symbol+"\",
            \"action\":\""+action+"\",
            \"product\":\""+product+"\",
            \"pricetype\":\""+pricetype+"\",
            \"quantity\":\""+orderqty+"\",
            \"price\":\""+price+"\",
            \"position_size\":\""+position_size+"\",            
            \"disclosed_quantity\":\""+disclosed_quantity+"\",
            \"trigger_price\":\""+trigger_price+"\",
            \"amo\":\""+amo+"\",
            \"splitorder\":\""+splitorder+"\",
            \"split_quantity\":\""+split_quantity+"\"
          
        }"; 

_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceSmartOrder",api_data,"am",ver);

_TRACE("API Response : "+resp);

if(VoiceAlert == "Enable")
	Say( "Order Placed" );

return resp;

}

function ExitOrder(action,position_size) {

//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data


api_data = "{ \"broker\": \""+broker+"\",
            \"strategy\":\""+strategy+"\",
            \"exchange\":\""+exchange+"\",
            \"symbol\":\""+symbol+"\",
            \"action\":\""+action+"\",
            \"product\":\""+product+"\",
            \"pricetype\":\""+pricetype+"\",
            \"quantity\":\""+"0"+"\",
            \"price\":\""+price+"\",
            \"position_size\":\""+position_size+"\",            
            \"disclosed_quantity\":\""+disclosed_quantity+"\",
            \"trigger_price\":\""+trigger_price+"\",
            \"amo\":\""+amo+"\",
            \"splitorder\":\""+splitorder+"\",
            \"split_quantity\":\""+split_quantity+"\"
          
        }"; 

_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceSmartOrder",api_data,"am",ver);

_TRACE("API Response : "+resp);

if(VoiceAlert == "Enable")
	Say( "Order Placed" );

return resp;

}

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

api_data = "{ \"broker\": \""+broker+"\" }";
_TRACE("Squareoff API Request"+api_data);

//Sending The Broker Request for NetOpenPositions
resp=algomojo.AMDispatcher(apikey, apisecret,"SquareOffAllPosition",api_data,"am",ver);
_TRACE("Squareoff API Response : "+resp);

if(VoiceAlert == "Enable")
	Say( "Order Placed" );
return resp;


}

//Execution Module

if(EnableAlgo != "Disable")
	{
		lasttime = StrFormat("%0.f",LastValue(BarIndex()));
			
		SetChartBkColor(colorDarkGrey);
		if(EnableButton == "Enable")
		{
		DrawButton("BE", X0, Y0, X0+X1, Y0+50, colorGreen, colorGreen);
		CursorInBEButton = MouseX >= X0 AND MouseX <= X0+X1 AND MouseY >= Y0 AND MouseY <= Y0+50;
		BEButtonClick = CursorInBEButton AND LBClick;
		
		DrawButton("BX", X0+65, Y0, X0+X1+65, Y0+50, colorGreen, colorGreen);
		CursorInBXButton = MouseX >= X0+65 AND MouseX <= X0+X1+65 AND MouseY >= Y0 AND MouseY <= Y0+50;
		BxButtonClick = CursorInBXButton AND LBClick;
		
		DrawButton("SE", X0, Y0+55, X0+X1, Y0+105, colorRed, colorRed);
		CursorInSEButton = MouseX >= X0 AND MouseX <= X0+X1 AND MouseY >= Y0+55 AND MouseY <= Y0+105;
		SEButtonClick = CursorInSEButton AND LBClick;
		
		DrawButton("SX", X0+65, Y0+55, X0+X1+65, Y0+105, colorRed, colorRed);
		CursorInSXButton = MouseX >= X0+65 AND MouseX <= X0+X1+65 AND MouseY >= Y0+55 AND MouseY <= Y0+105;
		SXButtonClick = CursorInSXButton AND LBClick;
		
		DrawButton("SQUAREOFF", X0, Y0+110, X0+X1+65, Y0+155, colorRed, colorRed);
		CursorInCXButton = MouseX >= X0 AND MouseX <= X0+X1+65 AND MouseY >= Y0+110 AND MouseY <= Y0+155;
		CXButtonClick = CursorInCXButton AND LBClick;
		
			if( BEButtonClick AND StaticVarGet(Name()+GetChartID()+"BEAlgo")==0 ) 
			{
				PlaceOrder("BUY",quantity);
				StaticVarSet(Name()+GetChartID()+"BEAlgo",1); 
			}
			else
			{
				StaticVarSet(Name()+GetChartID()+"BEAlgo",0);
			}
				if( SEButtonClick AND StaticVarGet(Name()+GetChartID()+"SEAlgo")==0 ) 
			{
				PlaceOrder("SELL",quantity);
				StaticVarSet(Name()+GetChartID()+"SEAlgo",1); 
			}
			else
			{
				StaticVarSet(Name()+GetChartID()+"SEAlgo",0);
			}
			if( BXButtonClick AND StaticVarGet(Name()+GetChartID()+"BXAlgo")==0 ) 
			{
				ExitOrder("SELL",0);
				
				StaticVarSet(Name()+GetChartID()+"BXAlgo",1); 
			}
			else
			{
				StaticVarSet(Name()+GetChartID()+"BXAlgo",0);
			}
			if( SXButtonClick AND StaticVarGet(Name()+GetChartID()+"SXAlgo")==0 ) 
			{
				ExitOrder("BUY",0);
				StaticVarSet(Name()+GetChartID()+"SXAlgo",1); 
			}
			else
			{
				StaticVarSet(Name()+GetChartID()+"SXAlgo",0); 
			}
			
			if( CXButtonClick AND StaticVarGet(Name()+GetChartID()+"CXAlgo")==0 ) 
			{
				Squareoffall();
				StaticVarSet(Name()+GetChartID()+"CXAlgo",1); 
			}
			else
			{
				StaticVarSet(Name()+GetChartID()+"CXAlgo",0);
			}
			}//button trading ends
	if(EnableAlgo == "Enable")
        {   
        
			if (Algobt1target==True AND StaticVarGet(static_name_+"buytarget1hitAlgo")==0 AND StaticVarGetText(static_name_+"buytarget1hitAlgo_barvalue") != lasttime)
            {  
            
            //  Buy Target 1 Hit
				PlaceSmartOrder("SELL",Quantity,AlgoOpenPosition);
                
                StaticVarSetText(static_name_+"buytarget1hitAlgo_barvalue",lasttime);
                StaticVarSet(static_name_+"buytarget1hitAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            
            else if (Algobt1target !=True)
            {   
                StaticVarSet(static_name_+"buytarget1hitAlgo",0);
                StaticVarSetText(static_name_+"buytarget1hitAlgo_barvalue","");
            }
            
            if (Algost1target==True AND StaticVarGet(static_name_+"shorttarget1hitAlgo")==0 AND StaticVarGetText(static_name_+"shorttarget1hitAlgo_barvalue") != lasttime)
            {  
            
				PlaceSmartOrder("BUY",Quantity,AlgoOpenPosition);
				
                
                StaticVarSetText(static_name_+"shorttarget1hitAlgo_barvalue",lasttime);
                StaticVarSet(static_name_+"shorttarget1hitAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            
            else if (Algost1target != True)
            {   
                StaticVarSet(static_name_+"shorttarget1hitAlgo",0);
                StaticVarSetText(static_name_+"shorttarget1hitAlgo_barvalue","");
            }
            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
            {
                            
                PlaceSmartOrder("BUY",quantity,quantity);
                StaticVarSetText(static_name_+"buyCoverAlgo_barvalue",lasttime);  
                StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
                
        
            }
            else if ((AlgoBuy != True OR AlgoCover != True))
            {   
                StaticVarSet(static_name_+"buyCoverAlgo",0);
                StaticVarSetText(static_name_+"buyCoverAlgo_barvalue","");
            }
            
            if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
            {
            // Long Entry 
                PlaceOrder("BUY",quantity);
                StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoBuy != True)
            {   
                StaticVarSet(static_name_+"buyAlgo",0);
                StaticVarSetText(static_name_+"buyAlgo_barvalue","");
                
            }
            if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
            {     
            // Long Exit 
				ExitOrder("SELL",0);
                
                StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime);
                StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoSell != True )
            {   
                StaticVarSet(static_name_+"sellAlgo",0);
                StaticVarSetText(static_name_+"sellAlgo_barvalue","");
            }
            if (AlgoShort==True AND AlgoSell==True AND  StaticVarGet(static_name_+"ShortSellAlgo")==0 AND StaticVarGetText(static_name_+"ShortSellAlgo_barvalue") != lasttime)
            {
            // reverse Short Entry 
				PlaceSmartOrder("SELL",quantity,-1*quantity);
                StaticVarSetText(static_name_+"ShortsellAlgo_barvalue",lasttime);
                StaticVarSet(static_name_+"ShortSellAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if ((AlgoShort != True OR AlgoSell != True))
            {   
                StaticVarSet(static_name_+"ShortSellAlgo",0);
                StaticVarSetText(static_name_+"ShortsellAlgo_barvalue","");
            }
                
            if (AlgoShort==True  AND  AlgoSell != True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND  StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
            {
            // Short Entry
                PlaceOrder("SELL",quantity);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoShort != True )
            {   
                StaticVarSet(static_name_+"ShortAlgo",0);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue","");
            }
            if (AlgoCover==true AND AlgoBuy != True AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
            {
            // Short Exit
				ExitOrder("BUY",0);
               
                StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoCover != True )
            {   
                StaticVarSet(static_name_+"CoverAlgo",0);
                StaticVarSetText(static_name_+"CoverAlgo_barvalue","");
            }
        }
        
         else if(EnableAlgo == "LongOnly")
        {
            
            if (AlgoBuy==True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
            {  
            //  Long Entry
                PlaceOrder("BUY",quantity);
                StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime);
                StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoBuy != True)
            {   
                StaticVarSet(static_name_+"buyAlgo",0);
                StaticVarSetText(static_name_+"buyAlgo_barvalue","");
            }
            if (AlgoSell==true AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
            {  
            // Long Exit
                ExitOrder("SELL",0);
                StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime);
                StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoSell != True )
            {   
                StaticVarSet(static_name_+"sellAlgo",0);
                StaticVarSetText(static_name_+"sellAlgo_barvalue","");
            }
        }
        else if(EnableAlgo == "ShortOnly")
        {
            if (AlgoShort==True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
            {
            // Short Entry
                PlaceOrder("SELL",quantity);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoShort != True )
            {   
                StaticVarSet(static_name_+"ShortAlgo",0);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue","");
            }
            if (AlgoCover==true AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
            {
            // Short Exit
                ExitOrder("BUY",0);
               
                StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoCover != True)
            {   
                StaticVarSet(static_name_+"CoverAlgo",0);
                StaticVarSetText(static_name_+"CoverAlgo_barvalue","");
            }
        }
        
    }
    
Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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

Pivot Reversal Strategy – Tradingview Pinescript to Amibroker AFL…

Pivot Reversal Strategy is a popular in-built strategy in Tradingview Platform. Here I had attempted to convert the pinescript v5 to Amibroker AFL Code....
Rajandran R
3 min read

Interactive Brokers – Smart Order Chart Trading Module using…

The IB Controller is an interface designed to facilitate automatic trading with AmiBroker and Interactive Brokers (IB) TWS (Trader Workstation). It serves as a...
Rajandran R
8 min read

Introducing OpenAlgo V1.0: The Ultimate Open-Source Algorithmic Trading Framework…

OpenAlgo V1.0 is an open-source algorithmic trading platform to automate your trading strategies using Amibroker, Tradingview, Metatrader, Python etc. Designed with the modern trader...
Rajandran R
2 min read

One Reply to “Stoploss, Multi Target, and Trailing Stoploss Module – Amibroker…”

Leave a Reply

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