What is Algomojo – Smart Order Execution Module for Amibroker Based Trading Systems?

Smart Order Module brings a 100% end-to-end automated trading solution for Amibroker users to automate their trading ideas with a simple plug-and-play module. Traders have to connect their trading system along with smart order execution to make their system trading life easier.

Supported Brokers

Angel Broking, Aliceblue, Firstock, Fyers, Tradejini, Upstox, Zebu

Smart order execution looks into the position book before taking any trading decisions.

Signal and PositionInterpretation
Buy Signal (Long Entry) and No Open PositionBuy x1 times of Quantity
Sell Signal (Long Exit) and No Open Position Do Nothing
Sell Signal (Long Exit) and Positive Open Position (Prev Long Signal Continues)Sell x1 times of Quantity
Short Signal (Short Entry) and No Open PositionSell x1 times of Quantity
Cover Signal (Short Exit) and No Open PositionDo Nothing
Cover Signal (Short Exit) and Negative Open Position (Prev Short Signal Continues)Buy x1 times of Quantity
Buy and Cover Signal and No Open PositionBuy x1 times of Quantity
Buy and Cover Signal and Negative Open Position (Prev Short Signal Continues) Buy x2 times of Quantity
Short and Sell Signal and No Open Position Sell x1 times of Quantity
Short and Sell Signal and Positive Open Position (Prev Long Signal Continues) Sell x2 times of Quantity

AFL Code provided for the brokers : Angel Broking, Aliceblue, Tradejini, Zebu

How to use the smart order module?

1)Apply your trading system on a new blank chart

2)Save the Smart Order Module to any folder of your choice

3)drag and drop the Smart order Module on top of the trading system

4)Configure Smart order Module parameters

5)Enable the Algo Mode and Start 100% Smart Automation.

Smart Order Module for Angel Broking Users (Parameter Controls)

Smart Order Module – Amibroker AFL Code for AngelOne users

// Developer: Algomojo
// Date: 24-Dec-2021
// Website: algomojo.com

_SECTION_BEGIN("Angel Broking - Broker Controls");

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";
Entrydelay = Param("Entry Delay",0,0,1,1);
Exitdelay = Param("Exit Delay",0,0,1,1);
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";

AlgoBuy = lastvalue(Ref(Buy,-Entrydelay));
AlgoSell = lastvalue(Ref(Sell,-Exitdelay));
AlgoShort = lastvalue(Ref(Short,-Entrydelay));
AlgoCover = lastvalue(Ref(Cover,-Exitdelay));



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);
}
}



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" ); 
}



Newquantity = Null;
	//Execution Module

if(EnableAlgo != "Disable")
    {
        lasttime = StrFormat("%0.f",LastValue(BarIndex()));
        
        SetChartBkColor(colorDarkGrey);
        if(EnableAlgo == "Enable")
        {   
            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
            {
            // reverse Long Entry 
				OpenPos = NetOpenPositions();
                if(OpenPos==0)
                {
                //If no open position send only x1 times of quantity
                Newquantity = quantity;
                _TRACE("No Open Positions Exist and Hence x1 times quantity will be punched");
                }
                else if(OpenPos == -quantity)
                {
                //if already short positions are running send x2 times of quantity
                Newquantity = 2*quantity;
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                }
                else
                {
                Newquantity = 2*quantity;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                
                }
                
                PlaceOrder("BUY",Newquantity);
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos == quantity)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("SELL",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != quantity)
                {
                PlaceOrder("SELL",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos==0)
                {
                //If no open position send only x1 times of quantity
                Newquantity = quantity;
                _TRACE("No Open Positions Exist and Hence x1 times quantity will be punched");
                }
                else if(OpenPos == quantity)
                {
                //if already short positions are running send x2 times of quantity
                Newquantity = 2*quantity;
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                }
                else
                {
                Newquantity = 2*quantity;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                
                }
                PlaceOrder("SELL",Newquantity);
                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
				OpenPos = NetOpenPositions();
				if(OpenPos == -quantity)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("BUY",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != -quantity)
                {
                PlaceOrder("BUY",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == quantity)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("SELL",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != quantity)
                {
                PlaceOrder("SELL",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == -quantity)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("BUY",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != -quantity)
                {
                PlaceOrder("BUY",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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","");
            }
        }
        
    }
    
  

SmartOrder Module for Aliceblue, Tradejini, Zebu users

// Developer: Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo)
// Date: 24-Dec-2021
// Website: algomojo.com / marketcalls.in

_SECTION_BEGIN("Nest Broker - Broker Controls");

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

broker = Paramlist("Broker","ab|tj|zb");  //ab - aliceblue, tj - tradejini, zb - zebu
ver = ParamStr("API Version ","1.0");
clnt_id = ParamStr("Client ID","xxxxxx"); //Enter your trading client ID
user_apikey = ParamStr("user_apikey","xxxxxx"); //Enter your API key here
api_secretkey = ParamStr("api_secretkey","xxxxxx"); //Enter your API secret key here

_SECTION_END();

_SECTION_BEGIN("Nest Broker - Order Controls");

s_prdt_ali = "BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML"; //Product Alias
Tsym = ParamStr("Trading Symbol","RELIANCE-EQ"); //Symbol Name
exch = ParamList("Exchange","NFO|NSE|BSE|CDS|MCX|NCDEX|BFO|MCXSXFO|MCXSX",1); //Exchange
Ret = "DAY"; //Retention
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0); // Pricetype
Pcode = ParamList("Product code","NRML|BO|CNC|CO|MIS",4); // Product Code
qty = Param("Quantity",1,0,100000,1); // Quantity
AMO = "NO"; //AMO Order


Entrydelay = Param("Entry Delay",0,0,1); // 0 - Execution with No Delay after a signal, 1- Execution at the end of the candle
Exitdelay = Param("Exit Delay",0,0,1);

strg_name = ParamStr("Strategy Name","Test Strategy Chart"); // Strategy Name
EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode
resp = "";


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

//Configure Trade Execution Delay


AlgoBuy = lastvalue(Ref(Buy,-Entrydelay));
AlgoSell = lastvalue(Ref(Sell,-Exitdelay));
AlgoShort = lastvalue(Ref(Short,-Entrydelay));
AlgoCover = lastvalue(Ref(Cover,-Exitdelay));




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);
}
}


function GetPositionsBook()
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+clnt_id+"\",\"actid\":\""+clnt_id+"\",\"type\":\""+"NET"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secretkey,"PositionBook",api_data,broker,ver);
_TRACE("Position Book Response : " +resp);
return resp;
}

function NetOpenPositions()
{
flag = 0;

resp = GetPositionsBook();
posNetqty =0;

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


if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //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,"Tsym"))
  {
   posdetails = StrExtract(posdetails,1,':');
   possym = StrTrim(posdetails,"\"");
    _TRACE("\nSymbol : "+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;


}//end of Net Open Positions

function PlaceOrder(TransType,orderqty) {

//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data
api_data ="{\"strg_name\":\""+strg_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+""+TransType+""+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+"MKT"+"\",\"qty\":\""+orderqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";

_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data,broker,ver);

_TRACE("API Response : "+resp);

_TRACE("Strategy Name : "+strg_name+"  AlgoStatus : "+ EnableAlgo);
_TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"Trading Interval : "+Interval(2)+"  Chard Id : "+ GetChartID());

Say( "Order Placed" ); 

return resp;

}

NewQty = Null;
	//Execution Module

if(EnableAlgo != "Disable")
    {
        lasttime = StrFormat("%0.f",LastValue(BarIndex()));
        
        SetChartBkColor(colorDarkGrey);
        if(EnableAlgo == "Enable")
        {   
            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
            {
            // reverse Long Entry 
				OpenPos = NetOpenPositions();
                if(OpenPos==0)
                {
                //If no open position send only x1 times of qty
                NewQty = qty;
                _TRACE("No Open Positions Exist and Hence x1 times qty will be punched");
                }
                else if(OpenPos == -qty)
                {
                //if already short positions are running send x2 times of qty
                NewQty = 2*qty;
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                }
                else
                {
                NewQty = 2*qty;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                
                }
                
                PlaceOrder("B",NewQty);
                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("B",qty);
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos == qty)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",qty);
                }
                else if(OpenPos != 0 AND OpenPos != qty)
                {
                PlaceOrder("S",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos==0)
                {
                //If no open position send only x1 times of qty
                NewQty = qty;
                _TRACE("No Open Positions Exist and Hence x1 times qty will be punched");
                }
                else if(OpenPos == qty)
                {
                //if already short positions are running send x2 times of qty
                NewQty = 2*qty;
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                }
                else
                {
                NewQty = 2*qty;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                
                }
                PlaceOrder("S",NewQty);
                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("S",qty);
                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
				OpenPos = NetOpenPositions();
				if(OpenPos == -qty)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",qty);
                }
                else if(OpenPos != 0 AND OpenPos != -qty)
                {
                PlaceOrder("B",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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("B",qty);
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == qty)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",qty);
                }
                else if(OpenPos != 0 AND OpenPos != qty)
                {
                PlaceOrder("S",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                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("S",qty);
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == -qty)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",qty);
                }
                else if(OpenPos != 0 AND OpenPos != -qty)
                {
                PlaceOrder("B",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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","");
            }
        }
        
    }
    
  


_SECTION_END();

SmartOrder Module for Firstock, Tradejini(Cube)



// Developer: Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo)
// Date: 24-Dec-2021
// Website: algomojo.com / marketcalls.in

_SECTION_BEGIN("Kambala - Broker Controls");

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

uid = ParamStr("uid","xxxx"); //Enter your API key here
broker = Paramlist("Broker","fs|tc"); //Broker Short Code - fs - firstock , tc - Tradejini (Cube)
ver = ParamStr("API Version","1.0");
api_key = ParamStr("user_apikey","xxxxxxxxx"); //Enter your API key here
api_secret = ParamStr("api_secret","xxxxxxxxx"); //Enter your API secret key here


_SECTION_END();

_SECTION_BEGIN("Kambala - Order Controls");

tsym = ParamStr("Trading Symbol","RELIANCE-EQ");
exch = ParamList("Exchange","NSE|NFO|BSE|MCX",0); 
qty = Param("Quatity",1,1,100000,1);

prc = "0";
prd = Paramlist("Product","C|M|I",1); //Enter your API key here
prctyp = ParamList("Product Type","MKT|MKT|SL-LMT|SL-MKT|DS|2L|3L",0);
ret = "Day";
remarks = "Algomojo";
ordersource ="API";
strg_name = ParamStr("Strategy Name", "Firstock Strategy");


Entrydelay = Param("Entry Delay",0,0,1); // 0 - Execution with No Delay after a signal, 1- Execution at the end of the candle
Exitdelay = Param("Exit Delay",0,0,1);

EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode

resp="";


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

//Configure Trade Execution Delay


AlgoBuy = lastvalue(Ref(Buy,-Entrydelay));
AlgoSell = lastvalue(Ref(Sell,-Exitdelay));
AlgoShort = lastvalue(Ref(Short,-Entrydelay));
AlgoCover = lastvalue(Ref(Cover,-Exitdelay));



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);
}
}

function PlaceOrder(Action,orderqty)
{
	
    algomojo=CreateObject("AMAMIBRIDGE.Main");
    api_data ="{\"strg_name\":\""+strg_name+"\",\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"exch\":\""+exch+"\",\"tsym\":\""+tsym+"\",\"qty\":\""+orderqty+"\",\"prc\":\""+prc+"\",\"prd\":\""+prd+"\",\"trantype\":\""+Action+"\",\"prctyp\":\""+prctyp+"\",\"ret\":\""+ret+"\",\"remarks\":\""+remarks+"\",\"ordersource\":\""+ordersource+"\"}";
    
    _TRACE("API Request"+api_data);
    resp=algomojo.AMDispatcher(api_key, api_secret,"PlaceOrder",api_data,broker,ver);
    _TRACE("API Response : "+resp);
    _TRACE("Strategy Name : "+strg_name+"  AlgoStatus : "+ EnableAlgo);
    _TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  tsym +"  qty : "+ orderqty +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID() + " LTP : "+LastValue(C));
	Say( "Order Placed" ); 
}

function GetPositionsBook()
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\"}";
_TRACE("PositionBook Request :"+api_data);
resp=algomojo.AMDispatcher(api_key, api_secret,"PositionBook",api_data,broker,ver);
_TRACE("PositionBook Response :"+resp);
return resp;
}

function NetOpenPositions()
{


//Initialization
flag = 0;

resp = GetPositionsBook();

possym = "";
posNetqty =0;


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

sym = StrTrim(sym," ");
Tsym = StrTrim(Tsym," ");

if(Strfind(sym,Tsym) AND StrFind(sym,"\"prd\":\""+prd+"\"")) //Matches the symbol and //Matches the Order Type
{

flag = 1; //turn on the flag

data = sym;

_TRACE(" Position Book  : " +data);

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

  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");
}

return posNetqty;

}

NewQty = Null;

if(EnableAlgo != "Disable")
    {
        lasttime = StrFormat("%0.f",LastValue(BarIndex()));
        
        SetChartBkColor(colorDarkGrey);
        if(EnableAlgo == "Enable")
        {   
            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
            {
            // reverse Long Entry 
				OpenPos = NetOpenPositions();
                if(OpenPos==0)
                {
                //If no open position send only x1 times of qty
                NewQty = qty;
                _TRACE("No Open Positions Exist and Hence x1 times qty will be punched");
                }
                else if(OpenPos == -qty)
                {
                //if already short positions are running send x2 times of qty
                NewQty = 2*qty;
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                }
                else
                {
                NewQty = 2*qty;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                
                }
                
                PlaceOrder("B",NewQty);
                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("B",qty);
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos == qty)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",qty);
                }
                else if(OpenPos != 0 AND OpenPos != qty)
                {
                PlaceOrder("S",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos==0)
                {
                //If no open position send only x1 times of qty
                NewQty = qty;
                _TRACE("No Open Positions Exist and Hence x1 times qty will be punched");
                }
                else if(OpenPos == qty)
                {
                //if already short positions are running send x2 times of qty
                NewQty = 2*qty;
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                }
                else
                {
                NewQty = 2*qty;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                
                }
                PlaceOrder("S",NewQty);
                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("S",qty);
                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
				OpenPos = NetOpenPositions();
				if(OpenPos == -qty)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",qty);
                }
                else if(OpenPos != 0 AND OpenPos != -qty)
                {
                PlaceOrder("B",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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("B",qty);
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == qty)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",qty);
                }
                else if(OpenPos != 0 AND OpenPos != qty)
                {
                PlaceOrder("S",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                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("S",qty);
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == -qty)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",qty);
                }
                else if(OpenPos != 0 AND OpenPos != -qty)
                {
                PlaceOrder("B",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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","");
            }
        }
        
    }
    
    
_SECTION_END();

SmartOrder Module for Fyers Users

// Developer: Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo)
// Date: 24-Dec-2021
// Website: algomojo.com / marketcalls.in

_SECTION_BEGIN("Fyers - 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 = ParamStr("Broker","fy");
ver = ParamStr("API Version","1.0");
apikey = ParamStr("APIKey","xxxxxxxxxxxxxx");
apisecret = ParamStr("APIsecret","xxxxxxxxxxxxx");
client_id = ParamStr("Client ID","xxxxxxxxx");

_SECTION_END();

_SECTION_BEGIN("Fyers - Order Controls");

strg_name = ParamStr("Strategy Name","Amibroker Strategy");

exchange = ParamList("Exchange","NSE|BSE|MCX|CDS");
symbol = ParamStr("Symbol Name","RELIANCE-EQ");   
qty = Param("Quantity",1,1,10000,1);

type = ParamList("Order Type","MKT|LMT|SL-MKT|SL-LMT");

if(type=="MKT")
{
	type = 2;
	}
else if(type=="LMT")
{
	type = 1;
	}
else if(type=="SL-MKT")
{
	type = 3;
	}
else if(type=="SL-LMT")
{
	type = 4;
	}
	
			
symbol = exchange+":"+symbol;

productType = ParamList("Product Type","INTRADAY|CNC|MARGIN|BO|CO",0);
limitPrice = "0";
stopPrice = "0";
validity = "DAY";
disclosedQty = "0";
offlineOrder = "False";
stopLoss = "0";
takeProfit = "0";


Entrydelay = Param("Entry Delay",0,0,1); // 0 - Execution with No Delay after a signal, 1- Execution at the end of the candle
Exitdelay = Param("Exit Delay",0,0,1);
EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode


//Configure Trade Execution Delay


AlgoBuy = lastvalue(Ref(Buy,-Entrydelay));
AlgoSell = lastvalue(Ref(Sell,-Exitdelay));
AlgoShort = lastvalue(Ref(Short,-Entrydelay));
AlgoCover = lastvalue(Ref(Cover,-Exitdelay));



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


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);
}
}

//PlaceOrder Sends Market Order Returns response on Succesful PlaceOrder

function PlaceOrder(TransType,orderqty) {

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

if(TransType=="B")
	TransType = "1";
if(TransType=="S")
	TransType = "-1";

api_data = "{
            \"strg_name\": \""+strg_name+"\",
            \"symbol\":\""+symbol+"\",
            \"qty\":\""+orderqty+"\",
            \"type\":\""+type+"\",
            \"side\":\""+TransType+"\",
            \"productType\":\""+productType+"\",
            \"limitPrice\":\"0\",
            \"stopPrice\":\"0\",
            \"validity\": \"DAY\",
            \"disclosedQty\":\"0\",
            \"offlineOrder\": \"False\",
            \"stopLoss\":\"0\",
            \"takeProfit\":\"0\"
        }"; 

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

_TRACE("API Response : "+resp);

_TRACE("Strategy Name : "+strg_name+"  AlgoStatus : "+ EnableAlgo);
_TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  symbol +"Trading Interval : "+Interval(2)+"  Chard Id : "+ GetChartID());

Say( "Order Placed" ); 

return resp;

}

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(apikey, apisecret,"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,symbol) 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,"netQty"))
  {
   posdetails = StrExtract(posdetails,1,':');
   posNetqty = StrTrim(posdetails,"\""); //Trim if any extra white space
   posNetqty = StrToNum(posNetqty);
    _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;


}//end of Net Open Positions



_SECTION_END();


_SECTION_BEGIN("Live Algo Execution Module");


if(EnableAlgo != "Disable")
    {
        lasttime = StrFormat("%0.f",LastValue(BarIndex()));
        
        SetChartBkColor(colorDarkGrey);
        if(EnableAlgo == "Enable")
        {   
            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
            {
            // reverse Long Entry 
				OpenPos = NetOpenPositions();
                if(OpenPos==0)
                {
                //If no open position send only x1 times of qty
                NewQty = qty;
                _TRACE("No Open Positions Exist and Hence x1 times qty will be punched");
                }
                else if(OpenPos == -qty)
                {
                //if already short positions are running send x2 times of qty
                NewQty = 2*qty;
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                }
                else
                {
                NewQty = 2*qty;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                
                }
                
                PlaceOrder("B",NewQty);
                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("B",qty);
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos == qty)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",qty);
                }
                else if(OpenPos != 0 AND OpenPos != qty)
                {
                PlaceOrder("S",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos==0)
                {
                //If no open position send only x1 times of qty
                NewQty = qty;
                _TRACE("No Open Positions Exist and Hence x1 times qty will be punched");
                }
                else if(OpenPos == qty)
                {
                //if already short positions are running send x2 times of qty
                NewQty = 2*qty;
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                }
                else
                {
                NewQty = 2*qty;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times qty will be punched");
                
                }
                PlaceOrder("S",NewQty);
                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("S",qty);
                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
				OpenPos = NetOpenPositions();
				if(OpenPos == -qty)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",qty);
                }
                else if(OpenPos != 0 AND OpenPos != -qty)
                {
                PlaceOrder("B",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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("B",qty);
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == qty)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",qty);
                }
                else if(OpenPos != 0 AND OpenPos != qty)
                {
                PlaceOrder("S",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                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("S",qty);
                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
                OpenPos = NetOpenPositions();
				if(OpenPos == -qty)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",qty);
                }
                else if(OpenPos != 0 AND OpenPos != -qty)
                {
                PlaceOrder("B",qty);
                _TRACE("Mismatch in Qty : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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","");
            }
        }
        
    }
    



_SECTION_END();

SmartOrder Module for Upstox Users

// Developer: Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo)
// Date: 24-Dec-2021
// Website: algomojo.com / marketcalls.in

_SECTION_BEGIN("Upstox - 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 = ParamStr("Broker","up");
ver = ParamStr("API Version","1.0");
client_id = ParamStr("Client ID","xxxxx");
apikey = ParamStr("APIKey","xxxxxxxxxxxxxx");
apisecret = ParamStr("APIsecret","xxxxxxxxxxxxx");

_SECTION_END();

_SECTION_BEGIN("Upstox - Order Controls");

stgy_name = ParamStr("Strategy Name","Amibroker Strategy");
symbol = ParamStr("Symbol Name","RELIANCE");  
exchange = ParamList("Exchange","NSE_EQ|NSE_FO|NCD_FO|MCX_FO|BCD_FO|BSE_EQ");
 
quantity = Param("Quantity",1,1,10000,1);

order_type = ParamList("Order Type","MKT|LMT|SL-MKT|SL-LMT");


productType = ParamList("Product Type","MIS|CNC|NRML",0);
duration = "DAY";
MktPro = "NA";
price = "0";
disclosed_quantity = "0";
trigger_price = "0";
is_amo = "NO";

if(productType=="MIS")
{
product = "I";
}
if(productType=="CNC" OR productType=="NRML")
{
product = "D";
}


Entrydelay = Param("Entry Delay",0,0,1); // 0 - Execution with No Delay after a signal, 1- Execution at the end of the candle
Exitdelay = Param("Exit Delay",0,0,1);
EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode


//Configure Trade Execution Delay


AlgoBuy = lastvalue(Ref(Buy,-Entrydelay));
AlgoSell = lastvalue(Ref(Sell,-Exitdelay));
AlgoShort = lastvalue(Ref(Short,-Entrydelay));
AlgoCover = lastvalue(Ref(Cover,-Exitdelay));



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


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);
}
}

//PlaceOrder Sends Market Order Returns response on Succesful PlaceOrder

function PlaceOrder(TransType,orderqty) {

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



api_data = "{
            \"stgy_name\": \""+stgy_name+"\",
            \"symbol\":\""+symbol+"\",
            \"exchange\":\""+exchange+"\",
            \"transaction_type\":\""+TransType+"\",
            \"duration\":\""+duration+"\",
            \"order_type\":\""+order_type+"\",
            \"quantity\":\""+orderqty+"\",
            \"disclosed_quantity\":\""+disclosed_quantity+"\",
            \"MktPro\":\""+MktPro+"\",
            \"price\":\""+price+"\",
            \"trigger_price\":\""+trigger_price+"\",
            \"product\":\""+productType+"\",
            \"is_amo\":\""+is_amo+"\"
        }"; 

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

_TRACE("API Response : "+resp);

_TRACE("Strategy Name : "+stgy_name+"  AlgoStatus : "+ EnableAlgo);
_TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  symbol +"Trading Interval : "+Interval(2)+"  Chard Id : "+ GetChartID());
Say( "Order Placed" ); 
return resp;



}

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(apikey, apisecret,"Positions",api_data,broker,ver);
_TRACE("PositionBook API Response : "+resp);

return resp;

}



function NetOpenPositions()
{
flag = 0;


resp = GetPositionsBook();


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


if(Strfind(sym,symbol) AND StrFind(sym,product)) //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,"product"))
  {
   productmsg = StrExtract(posdetails,1,':');
   productmsg = StrTrim(productmsg,"\""); //Trim if any extra white space
   }
 

 if(productmsg == product AND Strfind(posdetails,"net_quantity"))
  {
   posNetqty = StrExtract(posdetails,1,':');
   posNetqty = StrTrim(posNetqty,"\""); //Trim if any extra white space
   posNetqty = StrToNum(posNetqty);
    _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;


}//end of Net Open Positions





_SECTION_BEGIN("Live Algo Execution Module");


if(EnableAlgo != "Disable")
    {
        lasttime = StrFormat("%0.f",LastValue(BarIndex()));
        
        SetChartBkColor(colorDarkGrey);
        if(EnableAlgo == "Enable")
        {   
            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
            {
            // reverse Long Entry 
				OpenPos = NetOpenPositions();
                if(OpenPos==0)
                {
                //If no open position send only x1 times of quantity
                Newquantity = quantity;
                _TRACE("No Open Positions Exist and Hence x1 times quantity will be punched");
                }
                else if(OpenPos == -quantity)
                {
                //if already short positions are running send x2 times of quantity
                Newquantity = 2*quantity;
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                }
                else
                {
                Newquantity = 2*quantity;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                
                }
                
                PlaceOrder("B",Newquantity);
                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("B",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 
				OpenPos = NetOpenPositions();
				if(OpenPos == quantity)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != quantity)
                {
                PlaceOrder("S",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                
                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 
				OpenPos = NetOpenPositions();
				if(OpenPos==0)
                {
                //If no open position send only x1 times of quantity
                Newquantity = quantity;
                _TRACE("No Open Positions Exist and Hence x1 times quantity will be punched");
                }
                else if(OpenPos == quantity)
                {
                //if already short positions are running send x2 times of quantity
                Newquantity = 2*quantity;
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                }
                else
                {
                Newquantity = 2*quantity;
                _TRACE("Warning Mismatch in Trading Positions and Check Manually and Take necessary Action");
                _TRACE("Open Positions Exist and Hence x2 times quantity will be punched");
                
                }
                PlaceOrder("S",Newquantity);
                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("S",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
				OpenPos = NetOpenPositions();
				if(OpenPos == -quantity)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != -quantity)
                {
                PlaceOrder("B",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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("B",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
                OpenPos = NetOpenPositions();
				if(OpenPos == quantity)
                {
                //If positive open positions are there only then exit the longs 
                PlaceOrder("S",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != quantity)
                {
                PlaceOrder("S",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Sell Order is Placed to Exit the Long Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
                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("S",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
                OpenPos = NetOpenPositions();
				if(OpenPos == -quantity)
                {
                //If negative open positions are there only then exit the shorts 
                PlaceOrder("B",quantity);
                }
                else if(OpenPos != 0 AND OpenPos != -quantity)
                {
                PlaceOrder("B",quantity);
                _TRACE("Mismatch in quantity : Exit Order is Placed. Kindly check the positions and take necssary action");
                }
                else
                {
                _TRACE("Warning : No Open Long Positions Exits and Hence No Cover Order is Placed to Exit the Short Position");
                _TRACE("Kindly check the positions and take necssary action");
                }
               
                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","");
            }
        }
        
    }
    



_SECTION_END();

Leave a Comment

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