{"id":142,"date":"2021-01-17T22:38:02","date_gmt":"2021-01-17T22:38:02","guid":{"rendered":"https:\/\/algomojo.com\/blog\/?p=142"},"modified":"2023-09-13T06:37:49","modified_gmt":"2023-09-13T06:37:49","slug":"amibroker-execution-module-hedged-index-futures-for-directional-trading-in-algomojo-platform","status":"publish","type":"post","link":"https:\/\/algomojo.com\/blog\/amibroker-execution-module-hedged-index-futures-for-directional-trading-in-algomojo-platform\/","title":{"rendered":"Amibroker Execution Module \u2013 Hedged Index Futures for Directional Trading in Algomojo Platform"},"content":{"rendered":"\n<p>This tutorial focus on how to automate your positional buy and sell signal ideas with Hedged Index Futures to reduce your trading margin significantly.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/i1.wp.com\/www.marketcalls.in\/wp-content\/uploads\/2021\/01\/image-26-1024x555.png?resize=1024%2C555&amp;ssl=1\" alt=\"\"\/><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Trading Signal in Spot\/Futures<\/strong><\/td><td><strong>Orders to be Placed<\/strong><\/td><\/tr><tr><td>Buy Signal<\/td><td>Long Futures and Long OTM Put Options<\/td><\/tr><tr><td>Sell Signal<\/td><td>Short Futures and Exit OTM Put Options<\/td><\/tr><tr><td>Short Signal<\/td><td>Short Futures and Long OTM Call Options<\/td><\/tr><tr><td>Cover Signal<\/td><td>Long Futures and Exit OTM Call Options<\/td><\/tr><tr><td>Buy and Cover Signal<\/td><td>2 times of Long Futures, Long OTM Put Options and Exit OTM Call Options<\/td><\/tr><tr><td>Short and Cover Signal<\/td><td>2 times of Short Futures, Long OTM Call Options, and Exit OTM Put Options<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>Bringing Smartness in Execution<\/strong><\/p>\n\n\n\n<p>While Placing Orders to the System it checks the Position Book and Executes Trades smartly. Always hedge is executed first to get an effective margin and if no positions are there in the open positions then the system will not take reverse trade.<\/p>\n\n\n\n<p>In case if you are new to the option execution module then kindly kickstart with the basic tutorial on&nbsp;<a href=\"https:\/\/algomojo.com\/blog\/sending-option-orders-and-exiting-option-orders-in-algomojo-platform-using-amibroker\/\">Sending Option Orders from Amibroker using Algomojo Platform<\/a><\/p>\n\n\n\n<p><strong>Supported Brokers<\/strong>&nbsp;: Aliceblue, Tradejini, Zebu<br><strong>Supported Trading Instruments&nbsp;<\/strong>: Index Futures (Nifty, Bank Nifty, Finnifty) with Long Options as a Hedge<\/p>\n\n\n\n<p><strong>To Build this module we need 3 components<\/strong><\/p>\n\n\n\n<p>1)Trading System with Buy\/Sell\/Short\/Cover Signals<br>2)Header Option Execution Module that needs to be placed inside the&nbsp;<strong>Amibroker\\Formulas\\Include<\/strong>&nbsp;folder<br>3)Main Option Execution Module that needs to be drag and dropped over the Trading System<\/p>\n\n\n\n<p>1)<strong>Building your Trading System<\/strong><\/p>\n\n\n\n<p>Apply the Trading System with your Buy\/Sell\/Short\/Cover variables on the charts.<\/p>\n\n\n\n<p>Here is the sample EMA Crossover Trading System with Buy,Sell,Short,Cover variables.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-javascript\">\/\/Candle Plot and Axis\nSetChartOptions(0,chartShowArrows|chartShowDates);\n_N(Title = StrFormat(&quot;{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}&quot;, O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));\nPlot( C, &quot;Close&quot;, ParamColor(&quot;Color&quot;, colorDefault ), styleNoTitle | ParamStyle(&quot;Style&quot;) | GetPriceStyle() ); \n\n\/\/Controls\nlen1 = Param(&quot;Length1&quot;,20,1,100,1);\nlen2 = Param(&quot;Length2&quot;,50,1,100,1);\n\n\/\/Plot Functions\nPlot(EMA(Close,len1),&quot;EMA1&quot;,colorGreen, styleLine | styleThick);\nPlot(EMA(Close,len2),&quot;EMA2&quot;,coloryellow, styleLine | styleThick);\n\n\n\/\/Trading Rules\nBuy = Cross(EMA(Close,len1), EMA(Close,len2)); \/\/Positive EMA Crossover\nSell = Cross(EMA(Close,len2), EMA(Close,len1)); \/\/Negative EMA Crossover\n\n\/\/Stop and Reverse\n\nShort = Sell;\nCover = Buy;\n\n\/* Plot Buy and Sell Signal Arrows *\/\nPlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);\nPlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);\nPlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);\nPlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);\nPlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);\nPlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote\"><p><em><strong>Note: <\/strong>Buy\/Sell\/Short\/Cover parameters are mandatory without that execution will not happen properly<\/em><\/p><\/blockquote>\n\n\n\n<p>If in case your trading system supports only Buy and Sell and you don\u2019t want to use short and cover variables, in that case, use the below-mentioned logic where initialize short and cover variables to zero.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-javascript\">Buy = your buy trading logic ;\nSell = your sell trading logic ;\n\nshort =0;\ncover =0;<\/code><\/pre>\n\n\n\n<p><strong>2)Header Include Option Execution Module<\/strong><\/p>\n\n\n\n<p>Copy the Header Execution Module to Amibroker\\Formulas\\include folder. Save the AFL under the name&nbsp;<strong>algomojohedgedfutures.afl<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-javascript\">\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/Multi Broker Amibroker Hedged Futures Execution Module\n\/\/Coded by Algomojo\n\/\/Date : 10\/12\/2020\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\/\/Use this code only for Single Legged Long Only Options and Exiting Long Only Options\n\n\n_SECTION_BEGIN(&quot;Algomojo Hedged Futures- Include Module&quot;);\n\n\nuid = ParamStr(&quot;Client ID&quot;,&quot;TS2499&quot;);\nuser_apikey = ParamStr(&quot;user_apikey&quot;,&quot;86cbef19e7e61ccee91e497690d5814e&quot;); \/\/Enter your API key here\napi_secret = ParamStr(&quot;api_secret&quot;,&quot;4a94db82ea4fa140afaa2f039efffd18&quot;); \/\/Enter your API secret key here\ns_prdt_ali = &quot;BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML&quot;;\nexch = &quot;NFO&quot;; \/\/Exchange\nRet = &quot;DAY&quot;; \/\/Retention\nprctyp = ParamList(&quot;prctyp&quot;,&quot;MKT|L|SL|SL-M&quot;,0);\nPcode = ParamList(&quot;Pcode&quot;,&quot;NRML|CO|MIS&quot;,2);\nPrice = ParamList(&quot;Price&quot;,&quot;0&quot;);\nTrigPrice = ParamList(&quot;TrigPrice&quot;,&quot;0&quot;);\nAMO = &quot;NO&quot;; \/\/AMO Order\n\nstgy_name = ParamStr(&quot;Strategy Name&quot;, &quot;Options&quot;);\nbroker = ParamStr(&quot;Broker&quot;,&quot;ab&quot;); \/\/Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich\nver = ParamStr(&quot;API Version&quot;,&quot;1.0&quot;);\nfpath = ParamStr(&quot;Symbol Filepath&quot;, &quot;C:\\\\Program Files (x86)\\\\AmiBroker\\\\Formulas\\\\Algomojo\\\\&quot;);\ntimer = 1; \/\/3 seconds for providing delay after placing order\n\nRequestTimedRefresh(1,False);\n\n\nfunction futuresorder(Tsym,orderqty,transactiontype)\n{\n\t\n    algomojo=CreateObject(&quot;AMAMIBRIDGE.Main&quot;);\n    api_data =&quot;{\\&quot;stgy_name\\&quot;:\\&quot;&quot;+stgy_name+&quot;\\&quot;,\\&quot;s_prdt_ali\\&quot;:\\&quot;&quot;+s_prdt_ali+&quot;\\&quot;,\\&quot;Tsym\\&quot;:\\&quot;&quot;+Tsym+&quot;\\&quot;,\\&quot;exch\\&quot;:\\&quot;&quot;+exch+&quot;\\&quot;,\\&quot;Ttranstype\\&quot;:\\&quot;&quot;+transactiontype+&quot;\\&quot;,\\&quot;Ret\\&quot;:\\&quot;&quot;+Ret+&quot;\\&quot;,\\&quot;prctyp\\&quot;:\\&quot;&quot;+prctyp+&quot;\\&quot;,\\&quot;qty\\&quot;:\\&quot;&quot;+orderqty+&quot;\\&quot;,\\&quot;discqty\\&quot;:\\&quot;&quot;+&quot;0&quot;+&quot;\\&quot;,\\&quot;MktPro\\&quot;:\\&quot;&quot;+&quot;NA&quot;+&quot;\\&quot;,\\&quot;Price\\&quot;:\\&quot;&quot;+&quot;0&quot;+&quot;\\&quot;,\\&quot;TrigPrice\\&quot;:\\&quot;&quot;+&quot;0&quot;+&quot;\\&quot;,\\&quot;Pcode\\&quot;:\\&quot;&quot;+Pcode+&quot;\\&quot;,\\&quot;AMO\\&quot;:\\&quot;&quot;+AMO+&quot;\\&quot;}&quot;;\n    _TRACE(&quot;&quot;);\n    _TRACE(&quot;API Request&quot;+api_data);\n    resp=algomojo.AMDispatcher(user_apikey, api_secret,&quot;PlaceOrder&quot;,api_data,broker,ver);\n    Say( &quot;Buy Order Placed&quot; ); \n    return resp;\n}\n\n\nfunction NetOpenPositions(Tsym)\n{\nflag = 0;\n\nalgomojo=CreateObject(&quot;AMAMIBRIDGE.Main&quot;);\napi_data =&quot;{\\&quot;uid\\&quot;:\\&quot;&quot;+uid+&quot;\\&quot;,\\&quot;actid\\&quot;:\\&quot;&quot;+uid+&quot;\\&quot;,\\&quot;type\\&quot;:\\&quot;&quot;+&quot;NET&quot;+&quot;\\&quot;,\\&quot;s_prdt_ali\\&quot;:\\&quot;&quot;+s_prdt_ali+&quot;\\&quot;}&quot;;\nresp=algomojo.AMDispatcher(user_apikey, api_secret,&quot;PositionBook&quot;,api_data,broker,ver);\n_TRACE(&quot;Position Book Response : &quot; +resp);\nposNetqty =0;\n\nfor( item = 0; ( sym = StrExtract( resp, item,&#039;{&#039; )) != &quot;&quot;; item++ )\n{\n\n\nif(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) \/\/Matches the symbol and \/\/Matches the Order Type\n{\n\nflag = 1; \/\/turn on the flag\n\nfor( jitem = 0; ( posdetails = StrExtract( sym, jitem,&#039;,&#039; )) != &quot;&quot;; jitem++ )\n{\n\n if(Strfind(posdetails,&quot;Tsym&quot;))\n  {\n   posdetails = StrExtract(posdetails,1,&#039;:&#039;);\n   possym = StrTrim(posdetails,&quot;\\&quot;&quot;);\n    _TRACE(&quot;\\nSymbol : &quot;+possym);\n  }\n\n  if(Strfind(posdetails,&quot;Netqty&quot;))\n  {\n   posdetails = StrExtract(posdetails,1,&#039;:&#039;);\n   posNetqty = StrToNum(StrTrim(posdetails,&quot;\\&quot;&quot;));\n   _TRACE(&quot;\\nNetQty : &quot;+posNetqty);\n  }\n  if(Strfind(posdetails,&quot;unrealisedprofitloss&quot;))\n  {\n\tposdetails = StrExtract(posdetails,1,&#039;:&#039;);\n\tposupnl = StrTrim(posdetails,&quot;\\&quot;&quot;);\n    _TRACE(&quot;\\nUnRealized PNL : &quot;+posupnl);\n  }\n  if(Strfind(posdetails,&quot;realisedprofitloss&quot;))\n  {\n    posdetails = StrExtract(posdetails,1,&#039;:&#039;);\n\tposrpnl = StrToNum(StrTrim(posdetails,&quot;\\&quot;&quot;));\n    _TRACE(&quot;\\n Realized PNL : &quot;+posrpnl);\n  }\n \n  if(Strfind(posdetails,&quot;MtoM&quot;))\n  {\n    posdetails = StrExtract(posdetails,1,&#039;:&#039;);\n\tposmtm = StrToNum(StrTrim(posdetails,&quot;\\&quot;&quot;));\n    _TRACE(&quot;\\nMTM PNL : &quot;+posmtm);\n  }\n\n} \/\/end of for loop\n}\n\n}\/\/end of for loop\n\n\nif(flag==0)\n{\n_TRACE(&quot;\\nTrading Symbol Not Found&quot;);\n\/\/posNetqty =0;\n_TRACE(&quot;\\nNetQty : &quot;+posNetqty);\n}\n\nreturn posNetqty;\n\n\n}\/\/end of Net Open Positions\n\n\n\n\nfunction getnestorderno(response)\n{\n\nNOrdNo = &quot;&quot;;\n\n\nif(StrFind(response,&quot;NOrdNo&quot;)) \/\/Matches the orderstatus\n{\nNOrdNo = StrTrim( response, &quot;{\\&quot;NOrdNo\\&quot;:&quot; );\nNOrdNo = StrTrim( NOrdNo, &quot;\\&quot;,\\&quot;stat\\&quot;:\\&quot;Ok\\&quot;}&quot; );\n}\n\nreturn NOrdNo;\n}\n\nfunction getorderhistory(orderno)\n{\n\nalgomojo=CreateObject(&quot;AMAMIBRIDGE.Main&quot;);\napi_data = &quot;{\\&quot;uid\\&quot;:\\&quot;&quot;+uid+&quot;\\&quot;,\\&quot;NOrdNo\\&quot;:\\&quot;&quot;+orderno+&quot;\\&quot;,\\&quot;s_prdt_ali\\&quot;:\\&quot;&quot;+s_prdt_ali+&quot;\\&quot;}&quot;;\nresp=algomojo.AMDispatcher(user_apikey, api_secret,&quot;OrderHistory&quot;,api_data,broker,ver);\n\nreturn resp;\n\n\n}\n\n\nfunction getsymbol(orderno)\n{\n\nordresp = getorderhistory(orderno);\n\ndata = &quot;&quot;;\nTrsym=&quot;&quot;;\n\nfor( item = 0; ( sym = StrExtract( ordresp, item,&#039;{&#039; )) != &quot;&quot;; item++ )\n{\n\nsym = StrTrim(sym,&quot; &quot;); \/\/Trim Whitespaces\n\n\n\n\nif(StrFind(sym,&quot;complete&quot;) OR StrFind(sym,&quot;rejected&quot;)) \/\/Matches the orderstatus\n{\n\nflag = 1; \/\/turn on the flag\n\ndata = sym;\n\nfor( jitem = 0; ( ohistory = StrExtract( data, jitem,&#039;,&#039; )) != &quot;&quot;; jitem++ )\n{\n\nif(Strfind(ohistory,&quot;Trsym&quot;))\n  {\n   Trsym = StrExtract(ohistory,1,&#039;:&#039;);\n   Trsym = StrTrim(Trsym,&quot;\\&quot;&quot;);\n   \n  }\n\n}\n\n}\n\n}\n\nreturn Trsym;\n\n}\n\nfunction getorderstatus(orderno)\n{\norderstatus=&quot;&quot;;\nordresp = getorderhistory(orderno);\n\ndata = &quot;&quot;;\n\nfor( item = 0; ( sym = StrExtract( ordresp, item,&#039;{&#039; )) != &quot;&quot;; item++ )\n{\n\nsym = StrTrim(sym,&quot; &quot;); \/\/Trim Whitespaces\n\n\nif(StrFind(sym,&quot;complete&quot;) OR StrFind(sym,&quot;rejected&quot;)) \/\/Matches the orderstatus\n{\n\nflag = 1; \/\/turn on the flag\n\ndata = sym;\n\nfor( jitem = 0; ( ohistory = StrExtract( data, jitem,&#039;,&#039; )) != &quot;&quot;; jitem++ )\n{\n\nif(Strfind(ohistory,&quot;Status&quot;))\n  {\n   orderstatus = StrExtract(ohistory,1,&#039;:&#039;);\n   orderstatus = StrTrim(orderstatus,&quot;\\&quot;&quot;);\n   \n  }\n\n}\n\n}\n\n}\n\nreturn orderstatus;\n}\/\/end function\n\n\nfunction gettoken(symbol)\n{\nstoken=&quot;&quot;;\nalgomojo=CreateObject(&quot;AMAMIBRIDGE.Main&quot;);\napi_data = &quot;{\\&quot;s\\&quot;:\\&quot;&quot;+symbol+&quot;\\&quot;}&quot;;\nresp=algomojo.AMDispatcher(user_apikey, api_secret,&quot;fetchsymbol&quot;,api_data,broker,ver);\n\nfor( item = 0; ( sym = StrExtract( resp, item,&#039;{&#039; )) != &quot;&quot;; item++ )\n{\n\nsym = StrTrim(sym,&quot; &quot;); \/\/Trim Whitespaces\n\ndata = sym;\n\nfor( jitem = 0; ( ofetch = StrExtract( data, jitem,&#039;,&#039; )) != &quot;&quot;; jitem++ )\n{\n\nif(Strfind(ofetch,&quot;symbol_token&quot;))\n  {\n   stoken = StrExtract(ofetch,1,&#039;:&#039;);\n   stoken = StrTrim(stoken,&quot;\\&quot;&quot;);\n   \n  }\n\n}\n\n}\nreturn stoken;\n}\n\nfunction writetofile(filepath,ordno,symbol,ostatus)\n{\n    result =0;\n\tif(ostatus==&quot;complete&quot; OR ostatus==&quot;rejected&quot;)\n\t{\n    fh = fopen( filepath, &quot;w&quot;); \/\/Filepath of csv file with symbols\n\tif(fh)\n    {\n\t\t\n\t\tfputs(ordno + &quot;,&quot;, fh);\n\t\tfputs(symbol + &quot;,&quot;, fh);\n\t\tfputs(ostatus+&quot;,&quot;, fh);\n\t\tfclose(fh);\n\t\tresult =1;\n    } \n    }\n    \n    return result; \n}\n\n\n\nfunction placeoptionorder(spot_sym,expiry_dt,strike_int,qty,Ttranstype,opt,off,leg)\n{\n\nalgomojo=CreateObject(&quot;AMAMIBRIDGE.Main&quot;);\napi_data = &quot;{\\&quot;strg_name\\&quot;:\\&quot;&quot;+stgy_name+&quot;\\&quot;,\\&quot;spot_sym\\&quot;:\\&quot;&quot;+spot_sym+&quot;\\&quot;,\\&quot;expiry_dt\\&quot;:\\&quot;&quot;+expiry_dt+&quot;\\&quot;,\\&quot;opt_type\\&quot;:\\&quot;&quot;+opt+&quot;\\&quot;,\\&quot;Ttranstype\\&quot;:\\&quot;&quot;+Ttranstype+&quot;\\&quot;,\\&quot;prctyp\\&quot;:\\&quot;&quot;+prctyp+&quot;\\&quot;,\\&quot;qty\\&quot;:\\&quot;&quot;+qty+&quot;\\&quot;,\\&quot;Price\\&quot;:\\&quot;&quot;+Price+&quot;\\&quot;,\\&quot;TrigPrice\\&quot;:\\&quot;&quot;+TrigPrice+&quot;\\&quot;,\\&quot;Pcode\\&quot;:\\&quot;&quot;+Pcode+&quot;\\&quot;,\\&quot;strike_int\\&quot;:\\&quot;&quot;+strike_int+&quot;\\&quot;,\\&quot;offset\\&quot;:\\&quot;&quot;+off+&quot;\\&quot;}&quot;;\nresp=algomojo.AMDispatcher(user_apikey, api_secret,&quot;PlaceFOOptionsOrder&quot;,api_data,broker,ver);\n_TRACE(&quot;\\n&quot;+api_data);\n\/\/Get Nest Order Number\nnestorderno = getnestorderno(resp);\n_TRACE(&quot;\\nNest Order No : &quot;+nestorderno);\n\ntradetime=GetPerformanceCounter()\/1000; \n\nwhile ((GetPerformanceCounter()\/1000 - tradetime) &lt; timer)\n{            \n\n\/\/Get Trading Symbol\nTsym = getsymbol(nestorderno);\n}\n_TRACE(&quot;\\nTrading Symbol : &quot;+Tsym);\n\n\/\/Get Order Status\norderstatus = getorderstatus(nestorderno);\n_TRACE(&quot;\\nOrder Status : &quot;+orderstatus);\n\/\/Get Token Number\n\/\/token = gettoken(Tsym);\n\/\/_TRACE(&quot;\\nSymbol Token : &quot;+token);\nif(opt==&quot;CE&quot;)\n{\npath = fpath+leg+&quot;AlgomojoCE.csv&quot;;\n}\nif(opt==&quot;PE&quot;)\n{\npath = fpath+leg+&quot;AlgomojoPE.csv&quot;;\n}\n\nwritestatus = writetofile(path,nestorderno,Tsym,orderstatus);\n_TRACEF(WriteIf(writestatus,&quot;\\nWriting to File - Success&quot;,&quot;\\nWriting to File - Failure&quot;));\n\/\/resp = resp+&quot;\\nNest Order No : &quot;+nestorderno+&quot;\\nTrading Symbol : &quot;+Tsym+&quot;\\nOrder Status : &quot;+orderstatus+&quot;\\nSymbol Token : &quot;+token;\nreturn Tsym;\n\n}\n\n\nfunction getquantity(Tsym)\n{\n\nalgomojo=CreateObject(&quot;AMAMIBRIDGE.Main&quot;);\napi_data =&quot;{\\&quot;uid\\&quot;:\\&quot;&quot;+uid+&quot;\\&quot;,\\&quot;actid\\&quot;:\\&quot;&quot;+uid+&quot;\\&quot;,\\&quot;type\\&quot;:\\&quot;&quot;+&quot;NET&quot;+&quot;\\&quot;,\\&quot;s_prdt_ali\\&quot;:\\&quot;&quot;+s_prdt_ali+&quot;\\&quot;}&quot;;\nresp=algomojo.AMDispatcher(user_apikey, api_secret,&quot;PositionBook&quot;,api_data,broker,ver);\n\n\/\/Initialization\nflag = 0;\npossym = &quot;&quot;;\nposNetqty =0;\n\n\nfor( item = 0; ( sym = StrExtract( resp, item,&#039;{&#039; )) != &quot;&quot;; item++ )\n{\n\nsym = StrTrim(sym,&quot; &quot;);\nTsym = StrTrim(Tsym,&quot; &quot;);\n\nif(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) \/\/Matches the symbol and \/\/Matches the Order Type\n{\n\nflag = 1; \/\/turn on the flag\n\ndata = sym;\n\n_TRACE(&quot; Position Book  : &quot; +data);\n\nfor( jitem = 0; ( posdetails = StrExtract( data, jitem,&#039;,&#039; )) != &quot;&quot;; jitem++ )\n{\n\n  if(Strfind(posdetails,&quot;Netqty&quot;))\n  {\n   posdetails = StrExtract(posdetails,1,&#039;:&#039;);\n   posNetqty = StrToNum(StrTrim(posdetails,&quot;\\&quot;&quot;));\n   _TRACE(&quot;\\nNetQty : &quot;+posNetqty);\n  }\n  \n\n} \/\/end of for loop\n}\n\n}\/\/end of for loop\n\nif(flag==0)\n{\n_TRACE(&quot;\\nTrading Symbol Not Found&quot;);\n}\n\nreturn posNetqty;\n\n}\n\n\nfunction squareoffoptions(opt,Ttranstype,leg)\n{\n\nttype=&quot;&quot;;\n\nif(Ttranstype==&quot;B&quot;)\n{\n\nttype = &quot;S&quot;;\n\n}\n\nif(Ttranstype==&quot;S&quot;)\n{\n\nttype = &quot;B&quot;;\n\n}\n\n\nordno = &quot;&quot;;\nSymbol = &quot;&quot;;\nostatus =&quot;&quot;;\n\n\tif(opt==&quot;CE&quot;)\n\t{\n\tfpath = fpath+leg+&quot;AlgomojoCE.csv&quot;;\n\t}\n\tif(opt==&quot;PE&quot;)\n\t{\n\tfpath = fpath+leg+&quot;AlgomojoPE.csv&quot;;\n\t}\n\t\n\tfh = fopen(fpath, &quot;r&quot;); \n\tif(fh)\n\t{\n\t\t\n\t\tread = fgets(fh);\n\t\tordno = StrTrim(StrExtract(read,0),&quot; &quot;);\n\t\tSymbol = StrTrim(StrExtract(read,1),&quot; &quot;);\n\t\tostatus = StrTrim(StrExtract(read,2),&quot; &quot;);\n\t\t\t\t\t\n\t\tfclose(fh);\n\t}\n\t\n\texitqty = getquantity(Symbol);\n\t_TRACE(&quot;Net Quantity in the OrderBook for the Symbol : &quot;+Symbol+&quot; is : &quot;+exitqty);\n\t\n\tif(ostatus==&quot;complete&quot; AND exitqty!=0)\n\t{\n\talgomojo=CreateObject(&quot;AMAMIBRIDGE.Main&quot;);\n\tapi_data = &quot;{\\&quot;strg_name\\&quot;:\\&quot;&quot;+stgy_name+&quot;\\&quot;,\\&quot;s_prdt_ali\\&quot;:\\&quot;&quot;+s_prdt_ali+&quot;\\&quot;,\\&quot;Tsym\\&quot;:\\&quot;&quot;+Symbol+&quot;\\&quot;,\\&quot;exch\\&quot;:\\&quot;&quot;+&quot;NFO&quot;+&quot;\\&quot;,\\&quot;Ttranstype\\&quot;:\\&quot;&quot;+ttype+&quot;\\&quot;,\\&quot;Ret\\&quot;:\\&quot;&quot;+&quot;DAY&quot;+&quot;\\&quot;,\\&quot;prctyp\\&quot;:\\&quot;&quot;+prctyp+&quot;\\&quot;,\\&quot;qty\\&quot;:\\&quot;&quot;+exitqty+&quot;\\&quot;,\\&quot;discqty\\&quot;:\\&quot;&quot;+&quot;0&quot;+&quot;\\&quot;,\\&quot;MktPro\\&quot;:\\&quot;&quot;+&quot;NA&quot;+&quot;\\&quot;,\\&quot;Price\\&quot;:\\&quot;&quot;+&quot;0&quot;+&quot;\\&quot;,\\&quot;TrigPrice\\&quot;:\\&quot;&quot;+&quot;0&quot;+&quot;\\&quot;,\\&quot;Pcode\\&quot;:\\&quot;&quot;+Pcode+&quot;\\&quot;,\\&quot;AMO\\&quot;:\\&quot;&quot;+&quot;NO&quot;+&quot;\\&quot;}&quot;;\n\tresp=algomojo.AMDispatcher(user_apikey, api_secret,&quot;PlaceOrder&quot;,api_data,broker,ver);\n\t\/\/Get Nest Order Number\n\tnestorderno = getnestorderno(resp);\n\t_TRACE(&quot;\\nNest Order No : &quot;+nestorderno);\n\n\ttradetime=GetPerformanceCounter()\/1000; \n\n\twhile ((GetPerformanceCounter()\/1000 - tradetime) &lt; timer)\n\t{            \n\n\t\/\/Get Trading Symbol\n\tTsym = getsymbol(nestorderno);\n\t}\n\t_TRACE(&quot;\\nTrading Symbol : &quot;+Tsym);\n\n\t\/\/Get Order Status\n\torderstatus = getorderstatus(nestorderno);\n\t_TRACE(&quot;\\nOrder Status : &quot;+orderstatus);\n\t\n\t}\n\telse\n\t{\n\t\n\tresp = &quot;Not Squared Off. Either No Open Position Exist or Prev Signal Status Not in Completed State&quot;;\n\t\n\t}\n\t\n\treturn resp;\n}\n\n\n_SECTION_END();\n<\/code><\/pre>\n\n\n\n<p><strong>3)Main Option Execution Module<\/strong><\/p>\n\n\n\n<p>Copy the Main Execution Module to Amibroker\\Formulas\\Algomojo Platform. Save the AFL under the name&nbsp;<strong>Algomojo Hedged Futures Module to Save Margin.afl<\/strong><\/p>\n\n\n\n<p>Now drag and Drop the Module on top of your Charting with Buy\/Sell Trading System<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-javascript\">\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/Multi Broker Amibroker Option Execution Module\n\/\/Coded by Algomojo Developers\n\/\/Date : 30\/12\/2020\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include &lt; algomojohedgedfutures.afl &gt;\n\n\/\/Note : First Trade in Pure Long\/Short Strategy is always manual.\n\n_SECTION_BEGIN(&quot;Hedged Index Futures - Main Module&quot;);\n\n\/\/ Send orders even if Amibroker is minimized or Chart is not active\nRequestTimedRefresh(1, False); \n\n\/\/Initialization\n\n\n\n\nspot_sym = ParamStr(&quot;spot_sym&quot;,&quot;NIFTY&quot;); \/\/Enter the symbol name here\nstrike_int = ParamStr(&quot;strike_int&quot;,&quot;50&quot;);\nlotsize = Param(&quot;Symbol Lot Size&quot;,75,1,50000);\n\n\/\/Leg 2 is enabled by default\nleg2symbol = ParamStr(&quot;Futures Symbol&quot;,&quot;NIFTY28JAN21FUT&quot;);\nleg2qty = Param(&quot;Futures Lot Size&quot;,1)*lotsize;\n\n\/\/Option Buying Leg for Reduced Margin\n\/\/Leg 1 is optional for Hedging Purpose\nleg1 = ParamToggle(&quot;Hedge&quot;,&quot;Disable|Enable&quot;); \/\/Enable the Hedge\nleg1expiry_dt = ParamStr(&quot;Leg 1 expiry_dt&quot;, &quot;21JAN21&quot;); \/\/Always prefer using weekly expiry so reduce your margin exposure\nleg1qty = Param(&quot;Leg 1 Lot Size&quot;,1)*lotsize;\nleg1Ttranstype = ParamStr(&quot;Leg 1 Transaction Type&quot;,&quot;B&quot;);\n\/\/leg1opt_type = ParamList(&quot;Leg 1 Option Type&quot;,&quot;CE|PE&quot;,0);\nleg1offset = Param(&quot;Leg 1 Offset&quot;,10); \/\/need to handle positive offset for long call option and negative offset for long put option\n\n\n\n\n\n\n\ntradedelay = Param(&quot;Trade Delay&quot;,0);\nEnableAlgo = ParamList(&quot;Algo Mode&quot;,&quot;Disable|Enable&quot;,0); \/\/ Algo Mode\n\n\n\n\/\/Configure Trade Execution Delay\n\n\nAlgoBuy = lastvalue(Ref(Buy,-tradedelay));\nAlgoSell = lastvalue(Ref(Sell,-tradedelay));\nAlgoShort = lastvalue(Ref(Short,-tradedelay));\nAlgoCover = lastvalue(Ref(Cover,-tradedelay));\n\n\/\/Static Varibales for Order Protection\n\nstatic_name_ = Name()+GetChartID()+interval(2)+stgy_name;\nstatic_name_algo = Name()+GetChartID()+interval(2)+stgy_name+&quot;algostatus&quot;;\n\/\/StaticVarSet(static_name_algo, -1); \n\n\n\/\/Algo Dashboard\n\nGfxSelectFont( &quot;BOOK ANTIQUA&quot;, 14, 100 );\nGfxSetBkMode( 1 );\nif(EnableAlgo == &quot;Enable&quot;)\n{\nAlgoStatus = &quot;Algo Enabled&quot;;\nGfxSetTextColor( colorGreen ); \nGfxTextOut( &quot;Algostatus : &quot;+AlgoStatus , 20, 40); \nif(Nz(StaticVarGet(static_name_algo),0)!=1)\n{\n_TRACE(&quot;Algo Status : Enabled&quot;);\nStaticVarSet(static_name_algo, 1);\n}\n}\nif(EnableAlgo == &quot;Disable&quot;)\n{\nAlgoStatus = &quot;Algo Disabled&quot;;\nGfxSetTextColor( colorRed ); \nGfxTextOut( &quot;Algostatus : &quot;+AlgoStatus , 20, 40); \nif(Nz(StaticVarGet(static_name_algo),0)!=0)\n{\n_TRACE(&quot;Algo Status : Disabled&quot;);\nStaticVarSet(static_name_algo, 0);\n}\n}\nif(EnableAlgo == &quot;LongOnly&quot;)\n{\nAlgoStatus = &quot;Long Only&quot;;\nGfxSetTextColor( colorYellow ); \nGfxTextOut( &quot;Algostatus : &quot;+AlgoStatus , 20, 40); \nif(Nz(StaticVarGet(static_name_algo),0)!=2)\n{\n_TRACE(&quot;Algo Status : Long Only&quot;);\nStaticVarSet(static_name_algo, 2);\n}\n}\nif(EnableAlgo == &quot;ShortOnly&quot;)\n{\nAlgoStatus = &quot;Short Only&quot;;\nGfxSetTextColor( colorYellow ); \nGfxTextOut( &quot;Algostatus : &quot;+AlgoStatus , 20, 40); \nif(Nz(StaticVarGet(static_name_algo),0)!=3)\n{\n_TRACE(&quot;Algo Status : Short Only&quot;);\nStaticVarSet(static_name_algo, 3);\n}\n}\n\n\/\/Execution Module\n\nif(EnableAlgo != &quot;Disable&quot;)\n    {\n        lasttime = StrFormat(&quot;%0.f&quot;,LastValue(BarIndex()));\n        \n        SetChartBkColor(colorDarkGrey);\n        if(EnableAlgo == &quot;Enable&quot;)\n        {   \n            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+&quot;buyCoverAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;buyCoverAlgo_barvalue&quot;) != lasttime )\n            {\n            \/\/ Buying Put Option as Hedge + Long Futures + Exiting Call Option\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name() +&quot;  Signal : Buy and Cover Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n            \n\t\t\t\tif(leg1)\n\t\t\t\t{\n                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,&quot;PE&quot;,-1*leg1offset,1);\n\t\t\t\t_TRACEF(&quot;\\nLong Put Hedge Executed Symbol :&quot;+orderresponse);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nNo Open Positions&quot;);\n\t\t\t\t}\n\t\t\t\telse if(NetOpenPositions(leg2symbol) == -leg2qty)\n\t\t\t\t{\n\t\t\t\tNewQty = 2*leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = 2*leg2qty;\n\t\t\t\t_TRACE(&quot;\\nReversal signal will be taken with 2 times of Trading Quantity&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tenterlongresponse = futuresorder(leg2symbol,NewQty,&quot;B&quot;);\n\t\t\t\t_TRACEF(&quot;\\nLong Futures Response :&quot;+enterlongresponse);\n\t\t\t\t\n\t\t\t\t\/\/Exit Call Option \n\t\t\t\tif(leg1)\n\t\t\t\t{\n\t\t\t\tsqoff1status = squareoffoptions(&quot;CE&quot;,&quot;S&quot;,1);\n\t\t\t\t_TRACE(&quot;Leg 1 Call Exit Response :&quot;+sqoff1status);\n\t\t\t\t}\n\t\t\t\t\n                StaticVarSetText(static_name_+&quot;buyCoverAlgo_barvalue&quot;,lasttime);  \n                StaticVarSet(static_name_+&quot;buyCoverAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n        \n            }\n            else if ((AlgoBuy != True OR AlgoCover != True))\n            {   \n                StaticVarSet(static_name_+&quot;buyCoverAlgo&quot;,0);\n            }\n            \n            if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+&quot;buyAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;buyAlgo_barvalue&quot;) != lasttime)\n            {\n            \/\/ Buy Long Put Option as Hedge + Long Futures\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name() +&quot;  Signal : Buy Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n                \n                if(leg1)\n                {\n                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,&quot;PE&quot;,-1*leg1offset,1);\n\t\t\t\t_TRACEF(&quot;\\nLong Put Hedge Executed Symbol :&quot;+orderresponse);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tenterlongresponse = futuresorder(leg2symbol,NewQty,&quot;B&quot;);\n\t\t\t\t_TRACEF(&quot;\\nLong Futures Response :&quot;+enterlongresponse);\n\t\t\t\t\n                StaticVarSetText(static_name_+&quot;buyAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;buyAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if (AlgoBuy != True)\n            {   \n                StaticVarSet(static_name_+&quot;buyAlgo&quot;,0);\n                \n            }\n            if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+&quot;sellAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;sellAlgo_barvalue&quot;) != lasttime)\n            {     \n            \/\/ Short Futures + Exit Put Options\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : Sell Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n                \n                if(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = 0;\n\t\t\t\t_TRACE(&quot;\\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded&quot;);\n\t\t\t\t}\n\t\t\t\telse if(NetOpenPositions(leg2symbol) == leg2qty)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tenterlongresponse = futuresorder(leg2symbol,NewQty,&quot;S&quot;);\n\t\t\t\t_TRACEF(&quot;\\nShort Futures Response :&quot;+enterlongresponse);\n\t\t\t\tif(leg1)\n\t\t\t\t{\n\t\t\t\tsqoff1status = squareoffoptions(&quot;PE&quot;,&quot;S&quot;,1);\n\t\t\t\t_TRACE(&quot;Leg 1 Put Exit Response :&quot;+sqoff1status);\n                }\n                \n                \n                StaticVarSetText(static_name_+&quot;sellAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;sellAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if (AlgoSell != True )\n            {   \n                StaticVarSet(static_name_+&quot;sellAlgo&quot;,0);\n            }\n            if (AlgoShort==True AND AlgoSell==True AND  StaticVarGet(static_name_+&quot;ShortSellAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;ShortSellAlgo_barvalue&quot;) != lasttime)\n            {\n            \/\/ Long Call Options + Short Futures and Exit Long Put Options\n            \n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : Short and Sell Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n            \n                if(leg1)\n\t\t\t\t{\n                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,&quot;CE&quot;,leg1offset,1);\n\t\t\t\t_TRACEF(&quot;\\nLong Call Hedge Executed Symbol :&quot;+orderresponse);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nNo Open Positions&quot;);\n\t\t\t\t}\n\t\t\t\telse if(NetOpenPositions(leg2symbol) == leg2qty)\n\t\t\t\t{\n\t\t\t\tNewQty = 2*leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = 2*leg2qty;\n\t\t\t\t_TRACE(&quot;\\nReversal signal will be taken with 2 times of Trading Quantity&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tenterlongresponse = futuresorder(leg2symbol,NewQty,&quot;S&quot;);\n\t\t\t\t_TRACEF(&quot;\\nShort Futures Response :&quot;+enterlongresponse);\n\t\t\t\t\n\t\t\t\t\/\/Exit Put Option \n\t\t\t\tif(leg1)\n\t\t\t\t{\n\t\t\t\tsqoff1status = squareoffoptions(&quot;PE&quot;,&quot;S&quot;,1);\n\t\t\t\t_TRACE(&quot;Leg 1 Put Exit Response :&quot;+sqoff1status);\n\t\t\t\t}\n\t\t\t\t\n                StaticVarSetText(static_name_+&quot;ShortsellAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;ShortSellAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if ((AlgoShort != True OR AlgoSell != True))\n            {   \n                StaticVarSet(static_name_+&quot;ShortSellAlgo&quot;,0);\n            }\n                \n            if (AlgoShort==True  AND  AlgoSell != True AND StaticVarGet(static_name_+&quot;ShortAlgo&quot;)==0 AND  StaticVarGetText(static_name_+&quot;ShortAlgo_barvalue&quot;) != lasttime)\n            {\n            \/\/ Buy Long Call as Hedge + Short Futures\n            \n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : Short Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n            \n               if(leg1)\n\t\t\t\t{\n                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,&quot;CE&quot;,leg1offset,1);\n\t\t\t\t_TRACEF(&quot;\\nLong Call Hedge Executed Symbol :&quot;+orderresponse);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tenterlongresponse = futuresorder(leg2symbol,NewQty,&quot;S&quot;);\n\t\t\t\t_TRACEF(&quot;\\nShort Futures Response :&quot;+enterlongresponse);\n\t\t\t\t\n                StaticVarSetText(static_name_+&quot;ShortAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;ShortAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if (AlgoShort != True )\n            {   \n                StaticVarSet(static_name_+&quot;ShortAlgo&quot;,0);\n            }\n            if (AlgoCover==true AND AlgoBuy != True AND StaticVarGet(static_name_+&quot;CoverAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;CoverAlgo_barvalue&quot;) != lasttime)\n            {\n            \/\/ Buy the Futures + Exit Call Option\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : Cover Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = 0;\n\t\t\t\t_TRACE(&quot;\\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded&quot;);\n\t\t\t\t}\n\t\t\t\telse if(NetOpenPositions(leg2symbol) == -leg2qty)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n                enterlongresponse = futuresorder(leg2symbol,NewQty,&quot;B&quot;);\n\t\t\t\t_TRACEF(&quot;\\nLong Futures Response :&quot;+enterlongresponse);\n\t\t\t\tif(leg1)\n\t\t\t\t{\n\t\t\t\tsqoff1status = squareoffoptions(&quot;CE&quot;,&quot;S&quot;,1);\n\t\t\t\t_TRACE(&quot;Leg 1 Call Exit Response :&quot;+sqoff1status);\n                }\n                StaticVarSetText(static_name_+&quot;CoverAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;CoverAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if (AlgoCover != True )\n            {   \n                StaticVarSet(static_name_+&quot;CoverAlgo&quot;,0);\n            }\n        }\n        \n        \n        \n        else if(EnableAlgo == &quot;LongOnly&quot;)\n        {\n            \n            if (AlgoBuy==True AND StaticVarGet(static_name_+&quot;buyAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;buyAlgo_barvalue&quot;) != lasttime)\n            {  \n            \/\/  Buy Put Option as Hedge and Long Futures\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : Buy Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n\t\t\t\t\n                if(leg1)\n\t\t\t\t{\n                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,&quot;PE&quot;,-1*leg1offset,1);\n\t\t\t\t_TRACEF(&quot;\\nLong Put Hedge Executed Symbol :&quot;+orderresponse);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tenterlongresponse = futuresorder(leg2symbol,NewQty,&quot;B&quot;);\n\t\t\t\t_TRACEF(&quot;\\nLong Futures Response :&quot;+enterlongresponse);\n                StaticVarSetText(static_name_+&quot;buyAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;buyAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if (AlgoBuy != True)\n            {   \n                StaticVarSet(static_name_+&quot;buyAlgo&quot;,0);\n            }\n            if (AlgoSell==true AND StaticVarGet(static_name_+&quot;sellAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;sellAlgo_barvalue&quot;) != lasttime)\n            {  \n            \/\/ Short Futures and Exit Put Option\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : Sell Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n                \n                if(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = 0;\n\t\t\t\t_TRACE(&quot;\\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded&quot;);\n\t\t\t\t}\n\t\t\t\telse if(NetOpenPositions(leg2symbol) == leg2qty)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n                \n                enterlongresponse = futuresorder(leg2symbol,NewQty,&quot;S&quot;);\n\t\t\t\t_TRACEF(&quot;\\nShort Futures Response :&quot;+enterlongresponse);\n\t\t\t\tif(leg1)\n\t\t\t\t{\n\t\t\t\tsqoff1status = squareoffoptions(&quot;PE&quot;,&quot;S&quot;,1);\n\t\t\t\t_TRACE(&quot;Leg 1 Put Exit Response :&quot;+sqoff1status);\n                }\n                \n                \n                StaticVarSetText(static_name_+&quot;sellAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;sellAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if (AlgoSell != True )\n            {   \n                StaticVarSet(static_name_+&quot;sellAlgo&quot;,0);\n            }\n        }\n        else if(EnableAlgo == &quot;ShortOnly&quot;)\n        {\n            if (AlgoShort==True AND StaticVarGet(static_name_+&quot;ShortAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;ShortAlgo_barvalue&quot;) != lasttime)\n            {\n            \/\/ Long Call Option and Short Futures\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : ShortSignal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n                \n                \n                if(leg1)\n\t\t\t\t{\n                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,&quot;CE&quot;,leg1offset,1);\n\t\t\t\t_TRACEF(&quot;\\nLong Call Hedge Executed Symbol :&quot;+orderresponse);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tenterlongresponse = futuresorder(leg2symbol,NewQty,&quot;S&quot;);\n\t\t\t\t_TRACEF(&quot;\\nShort Futures Response :&quot;+enterlongresponse);\n                \n                \n                StaticVarSetText(static_name_+&quot;ShortAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;ShortAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                _TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;AlgoStatus : &quot;+ EnableAlgo +&quot;Chart Symbol : &quot;+ Name() +&quot;  Trading Symbol : &quot;+  Tsym +&quot;  Quantity : &quot;+ qty +&quot;  Signal : Short Signal  TimeFrame : &quot;+ Interval(2)+&quot;  Response : &quot;+ resp +&quot;  ChardId : &quot;+ GetChartID() + &quot; Latest Price : &quot;+LastValue(C));\n            }\n            else if (AlgoShort != True )\n            {   \n                StaticVarSet(static_name_+&quot;ShortAlgo&quot;,0);\n            }\n            if (AlgoCover==true AND StaticVarGet(static_name_+&quot;CoverAlgo&quot;)==0 AND StaticVarGetText(static_name_+&quot;CoverAlgo_barvalue&quot;) != lasttime)\n            {\n            \/\/ Long Futures and Exit Call Option\n\t\t\t\t_TRACE(&quot;Strategy : &quot;+ stgy_name +&quot;Chart Symbol : &quot;+ Name()  +&quot;  Signal : Cover Signal  TimeFrame : &quot;+ Interval(2)+&quot;  ChardId : &quot;+ GetChartID());\n                \n                if(NetOpenPositions(leg2symbol) == 0)\n\t\t\t\t{\n\t\t\t\tNewQty = 0;\n\t\t\t\t_TRACE(&quot;\\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded&quot;);\n\t\t\t\t}\n\t\t\t\telse if(NetOpenPositions(leg2symbol) == -leg2qty)\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\tNewQty = leg2qty;\n\t\t\t\t_TRACE(&quot;\\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists&quot;);\n\t\t\t\t_TRACE(&quot;\\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.&quot;);\n\t\t\t\t}\n\t\t\t\t\n                enterlongresponse = futuresorder(leg2symbol,NewQty,&quot;B&quot;);\n\t\t\t\t_TRACEF(&quot;\\nLong Futures Response :&quot;+enterlongresponse);\n\t\t\t\tif(leg1)\n\t\t\t\t{\n\t\t\t\tsqoff1status = squareoffoptions(&quot;CE&quot;,&quot;S&quot;,1);\n\t\t\t\t_TRACE(&quot;Leg 1 Call Exit Response :&quot;+sqoff1status);\n                }\n                \n                StaticVarSetText(static_name_+&quot;CoverAlgo_barvalue&quot;,lasttime); \n                StaticVarSet(static_name_+&quot;CoverAlgo&quot;,1); \/\/Algo Order was triggered, no more order on this bar\n                \n            }\n            else if (AlgoCover != True)\n            {   \n                StaticVarSet(static_name_+&quot;CoverAlgo&quot;,0);\n            }\n        }\n        \n    }\/\/end main if\n\n    \n_SECTION_END();\n<\/code><\/pre>\n\n\n\n<p>4)Now right-click over the charts and set the Client ID, user_apikey, api_secretkey,broker and set the required quantity<\/p>\n\n\n\n<p>5)Ensure the&nbsp;<strong>Symbol File Path Exists<\/strong>. This is the path where the executed symbols CE and PE Options will get saved in a CSV file for later squareoff.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Ensure while entering the Option Expiry Format. Login to Algomojo Terminal and check out the weekly and monthly option format and enter the expiry date accordingly.<\/p><p>For Aliceblue account holders Monthly Option Symbol Format: NIFTY21JAN14500CE<\/p><p>Hence the Expiry Date needs to be entered as 21JAN<\/p><p>For Aliceblue Account holders weekly Option Symbol Format: NIFTY2111414500CE<\/p><p>Hence the Expiry Date needs to be entered as 21114<\/p><p>For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY28JAN2114500CE<\/p><p>Hence the Expiry Date needs to be entered as 28JAN21<\/p><p>For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY14JAN2114500CE<\/p><p>Hence the Expiry Date needs to be entered as 14JAN21<\/p><\/blockquote>\n\n\n\n<p>1AlgomojoCE.csv and 1AlgomojoPE.csv will be saved whenever the hedged option traders are executed and files will be saved only if the execution status is in&nbsp;<strong>complete&nbsp;or in rejected<\/strong>&nbsp;mode.<\/p>\n\n\n\n<p>6)Enable the Hedge Option, Enter the Futures Symbol, Enter the Option Hedging Expiry, Lot Size, Transaction Type and Offset (To Select OTM\/ATM. Keep the value as zero for ATM Option selection)<\/p>\n\n\n\n<p>7)Ensure Log Window is open to capture the Trace Logs<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/i0.wp.com\/www.marketcalls.in\/wp-content\/uploads\/2021\/01\/image-25.png?resize=460%2C816&amp;ssl=1\" alt=\"\"\/><\/figure>\n\n\n\n<p>8)Bingo Now you can Send Hedged Orders from Amibroker by connecting any of your Buy\/Sell Trading System. To Send ATM\/ITM\/OTM Option Orders, adjust the offset parameters from the Properties section.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial focus on how to automate your positional buy and sell signal ideas with Hedged Index Futures to reduce your trading margin significantly.<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"default","ast-global-header-display":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":""},"categories":[6,15],"tags":[36,13,7,44],"_links":{"self":[{"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/posts\/142"}],"collection":[{"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/comments?post=142"}],"version-history":[{"count":6,"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/posts\/142\/revisions"}],"predecessor-version":[{"id":651,"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/posts\/142\/revisions\/651"}],"wp:attachment":[{"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/media?parent=142"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/categories?post=142"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/algomojo.com\/blog\/wp-json\/wp\/v2\/tags?post=142"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}