AFL for EMA Crossover, firing through Pi Bridge

I am using Amibroker and Pi. Have started using the Pi bridge, want some help in coding this on AFL along with the bit to fire orders directly from the AFL whever the condition is met.

code this for NIFTY

Buy-when 5 ema closes above 200 ema (Cover short and long) means exit short position and take long position.

Sell-when 5 ema closes below 200 ema (cover long and short) means exit long position and take short position.

Where ever client Id is there replace with your Id.

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

Buy= Cross(EMA(Close,5),EMA(Close,200));
Sell= Cross(EMA(Close,200),EMA(Close,5));

Short= Cross(EMA(Close,200),EMA(Close,5));
Cover= Cross(EMA(Close,5),EMA(Close,200));

//============================================================================================================================PlugIn============================================================================================//

brd=Null;
if(IsNull(brd))
{
  brd = CreateStaticObject("pibridge.Bridge");

}

if(!brd.GetConnectionStatus()) brd.Reconnect();

ClientID_String = ParamStr("ClientID", "ClientID");
Trading_Symbol = ParamStr("Contract","NIFTY15MARFUT");
Quantity = Param("Lots/Quantity",1, 1, 10, 1 ,1);

currTimestamp = LastValue( TimeNum() );
LastTimestamp = Nz( StaticVarGet("LastBarTimestamp_"+Name()+"_" +GetChartID()) );
if ( currTimestamp !=  LastTimestamp  )
{

    StaticVarSet( "LastBarTimestamp_"+Name()+"_" +GetChartID(), currTimestamp );    
 
    if( LastValue( Ref(Buy,-1) ))
    {   brd.PlaceOrder("NFO", Trading_Symbol, Trading_Symbol,"Strategy A", 1, Quantity, Quantity, LastValue(Close), 0, "LIMIT", "NRML", "ClientID_String","DAY");
        PopupWindow("Time: " + Now() + "\n\n\n\n Price: " + LastValue(Close),"Strategy A:  Buy    " + Trading_Symbol, 7200, 640*mtRandom(), 480*mtRandom());
        PlaySound("C:\\Windows\\Media\\tada.wav");    
    }

if( LastValue( Ref(Sell,-1) ))
    { brd.PlaceOrder("NFO", Trading_Symbol, Trading_Symbol,"Strategy A", 2, Quantity, Quantity, LastValue(Close), 0, "LIMIT", "NRML", "ClientID_String","DAY");
      PopupWindow("Time: " + Now() + "\n\n\n\n Price: " + LastValue(Close-My_Order_Price_Error),"Strategy A:  Sell    " + Trading_Symbol, 7200, 640*mtRandom(), 480*mtRandom());
      PlaySound("C:\\Windows\\Media\\tada.wav");
    }

    if( LastValue( Ref(Short,-1) ) )
    { brd.PlaceOrder("NFO", Trading_Symbol, Trading_Symbol,"Strategy A", 2, Quantity, Quantity, LastValue(Close), 0, "LIMIT", "NRML", "ClientID_String","DAY");
      PopupWindow("Time: " + Now() + "\n\n\n\n Price: " + LastValue(Close),"Strategy A:  Short    " + Trading_Symbol, 7200, 640*mtRandom(), 480*mtRandom());
      PlaySound("C:\\Windows\\Media\\tada.wav");
    }

    if( LastValue( Ref(Cover,-1) ) )
    {   brd.PlaceOrder("NFO", Trading_Symbol, Trading_Symbol,"Strategy A", 1, Quantity, Quantity, LastValue(Close), 0, "LIMIT", "NRML", "ClientID_String","DAY");
          PopupWindow("Time: " + Now() + "\n\n\n\n Price: " + LastValue(Close+My_Order_Price_Error),"Strategy A:  Cover    " + Trading_Symbol, 7200, 640*mtRandom(), 480*mtRandom());
       PlaySound("C:\\Windows\\Media\\tada.wav");    
    }

}
_SECTION_BEGIN("PiPluginMini");
GfxSetBkMode(0);SetChartOptions (0,chartShowDates|chartShowArrows,chartGridMiddle,0,0,10);SetChartBkColor( ParamColor("Chart BackGround Color", colorBlack ) ) ;SetBarFillColor( IIf( C > O, colorLime, IIf(C <= O,colorRed,colorBlack ) ));Plot(Close,"Close",IIf( C > O, colorLime, IIf(C <= O,colorRed,colorBlack ) ),styleCandle|styleNoTitle);
BarN = ValueWhen(DateNum()!= Ref(DateNum(),-1),BarIndex());BarNo = IIf(IsEmpty(BarN),BarIndex()+1,BarIndex()-BarN+1);Bvalue = LastValue(ValueWhen(BarNo==1,C),1);PrvC = IIf(IsEmpty(TimeFrameGetPrice("C",inDaily,-1)),ValueWhen(BarNo==1,O),TimeFrameGetPrice("C",inDaily,-1));Buy=Sell=Short=Cover=0;pxw = Status("pxwidth");pxh = Status("pxheight");
GfxSelectFont( "Lucida Fax", 16, 700, False );GfxSetTextColor( colorGold );GfxGradientRect( 1, 1, pxw, 30, colorGrey50, colorDarkGrey);GfxTextOut( "AMIBROKER - PIBRIDGE ", (pxw/2)-120, 4 );GfxTextOut( Name(), 5, 4 );GfxTextOut( Date(), PXW-250, 4 );GfxSelectFont( "Lucida Fax", 24, 700, False );GfxSetTextColor( colorOrange  );
GfxTextOut( "LTP:"+" "+WriteVal(LastValue(C,1),1.2), (PXW/2)-80, 60 );GfxSelectFont( "Lucida Fax", 11, 700, False );GfxSetTextColor( colorWhite  );GfxTextOut( "Op :"+WriteVal(Open,1.2)+"   Hi :"+WriteVal(High,1.2)+"   Lo :"+WriteVal(Low,1.2)+"   Cl :"+WriteVal(Close,1.2)+"   Chg :"+WriteVal(((Close-PrvC)/PrvC)*100,1.2)+"%", 3, 35);
PClientId = ParamStr("ZeroDha ClientId","AB1234");PLogic = ParamStr("Enter Ur Strategy Name","MYLOGIC");PExch = ParamList("Select Stock Exchange","NSE,NFO,MCX,BSE,BFO,CDS",0);PSymbol = StrLeft(StrFormat(Name()),10);PTrdSymbol1 = ParamStr("Enter Trd Symbol Here","ACC-EQ");PTrdSymbol = StrToUpper(PTrdSymbol1);PProdType = ParamList("Select Product Type","MIS,NRML,CNC",0);
POrdType = ParamList("Select Order Type","L,MKT",0);PTrdValue = Param("Investment For Equity?",10000,1000,2500000,500);PLotNo = Param("No of Lots to Trade in Futures?",1,1,25,1);PlotSize = Param("Enter lot Size Per lot?",250,1,5000,1);if(PExch == "NSE" OR PExch =="BSE") PQty = ceil(PTrdValue/BValue);else PQty = PlotNo;if(PExch == "NSE" OR PExch =="BSE") PLQty = PQty;else PLQty = PLotSize;
if (StrRight(PTrdSymbol,3)== "FUT")Tsym="Trade Symbol";else if (StrRight(PTrdSymbol,2)== "EQ")Tsym="Trade Symbol";else Tsym="No Symbol";GfxSelectFont( "Lucida Fax", 16, 700, False );GfxSetTextColor( colorWhite );if (StrLeft(PTrdSymbol,3)!= StrLeft(PSymbol,3) AND Tsym=="Trade Symbol"){GfxTextOut("Trade Symbol in Parameter Window" ,(pxw/2)-190,pxh/2);GfxTextOut("Does not Match with the Ticker" ,(pxw/2)-165,(pxh/2)+20);}
else if ( Tsym=="No Symbol"){GfxTextOut("Enter Correct Trade Symbol in Parameter Window" ,(pxw/2)-260,pxh/2);}
//---Your Buy/Sell/Short/Cover Logic/Strategy Starts Here---\\
//Below is the Sample Buy/short Condition Replace it with Your Own---\\

TradeStart = 100000;//Trade will start after 1000 am. Change as per Ur Requirement
TradeEnd = 143000;//Trade will not occur after 1430 pm. Change as per Ur Requirement

TradeTime = TimeNum()>= TradeStart AND TimeNum()<= 150000;

EMA1 = EMA(C,5);
EMA2 = EMA(C,200);

Buy = Cross(EMA1,EMA2) AND TradeTime == 1;
Short = Cross(EMA2,EMA1) AND TradeTime == 1;

Buy = ExRem(Buy,Short);
Short = ExRem(Short,Buy);

Sell = (Short OR TimeNum()==150000) AND Sum(Buy,BarNo) > 0;
Cover = (Buy OR TimeNum()==150000) AND Sum(Short,BarNo) > 0;

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

//---Your Buy/Sell/Short/Cover Logic/Strategy Ends Here---\\
ORder = IIf(Buy,1,IIf(Sell,2,IIf(Short,2,IIf(Cover,1,0))));BSCond = LastValue(ORder,1);PLmtPrice = LastValue(ValueWhen(BSCond >0,C),1);Checkone=StaticVarGetText("Check"+StrFormat(Name()));Checktwo = StrFormat(Name())+"-"+NumToStr((Cum(Buy)+Cum(Sell)+Cum(Short)+Cum(Cover)),1.0)+"-"+NumToStr(GetChartID(),1.0);if (BSCond >0 AND CheckOne != CheckTwo){brd = CreateStaticObject("pibridge.Bridge");brd.PlaceOrder (PExch, PTrdSymbol ,PSymbol,PLogic, BScond ,PQty,0, PLmtPrice, 0, POrdType, PProdType, PClientID,"Day");
StaticVarSetText("Check"+StrFormat(Name()),CheckTwo );}PlotShapes( Buy * shapeUpArrow + Sell * shapeDownArrow + Short * shapeDownArrow +  Cover * shapeUpArrow , IIf( Buy, colorGreen,IIf(Short,colorRed,IIf(Sell,colorOrange, IIf(Cover,colorPaleGreen,colorBlack))) ),0,IIf(Buy OR Cover ,L,IIf(Sell OR Short ,H,C)), Offset=-30 );dist = 1.5*ATR(60);for( i = 0; i < BarCount; i++ ) {if( Buy[i] ) PlotText( "Buy @ " + C[ i ], i-3, L[ i ]-dist[i], colorGreen ); if( Sell[i] ) PlotText( "Sell @ " + C[ i ], i-3, H[ i ]+dist[i], colorOrange); 
if( Short[i] ) PlotText( "Short @ " + C[ i ], i-3, H[ i ]+dist[i], colorRed );if( Cover[i] ) PlotText( "Cover @ " + C[ i ], i-3, L[ i ]-dist[i], colorPaleGreen ); }PLBox = ParamToggle("Display Profit/Loss Box?","Yes|No",1);if (PLBox==1 ){GfxSelectSolidBrush( colorBlack );GfxSelectPen( colorRed, 2);GfxRoundRect( 1, pxh-200, 330, pxh-20 , 7, 7 ) ;GfxRoundRect( 331, pxh-200, 520, pxh-80 , 7, 7 ) ;BuyVal  = IIf(Buy,C*PLQty,0);SellVal  = IIf(Sell,C*PLQty,0);ShortVal  = IIf(Short,C*PLQty,0);CoverVal  = IIf(Cover,C*PLQty,0);
BuyPLA = (C*Cum(Buy)*PLQty) - Cum(BuyVal);CoverPLA = (C*Cum(Cover)*PLQty) - Cum(CoverVal);ShortPLA = Cum(ShortVal) - (C*Cum(Short)*PLQty) ;SellPLA = Cum(SellVal) - (C*Cum(Sell)*PLQty) ;LongPLA = LastValue(BuyPLA+SellPLA,1);ShrtPLA = LastValue(ShortPLA+CoverPLA,1);BuyPLT = (C*Sum(Buy,BarNo)*PLQty) - Sum(BuyVal,BarNo);CoverPLT = (C*Sum(Cover,BarNo)*PLQty) - Sum(CoverVal,BarNo);ShortPLT = Sum(ShortVal,BarNo) - (C*Sum(Short,BarNo)*PLQty) ;SellPLT = Sum(SellVal,BarNo) - (C*Sum(Sell,BarNo)*PLQty) ;LongPLT = BuyPLT+SellPLT;
ShrtPLT = ShortPLT+CoverPLT;GfxSelectFont( "Lucida Fax", 12, 700, False );CDate = NumToStr(Day(),1.0) + "-" + NumToStr(Month(),1.0) + "-" + NumToStr(Year(),1.0);FDate = NumToStr(ValueWhen(BarIndex()==0,Day()),1.0) + "-" + NumToStr(ValueWhen(BarIndex()==0,Month()),1.0) + "-" + NumToStr(ValueWhen(BarIndex()==0,Year()),1.0);LDate = NumToStr(LastValue(Day()),1.0) + "-" + NumToStr(LastValue(Month()),1.0) + "-" + NumToStr(LastValue(Year()),1.0);GfxTextOut("Profit",30,pxh-190);GfxTextOut("Total Trades",331,pxh-190);
GfxTextOut("Gross P/L",331,pxh-150);GfxTextOut("Brkg+Chgs",331,pxh-130);GfxTextOut("Net P/L",331,pxh-110);Brkg=LastValue((Cum(Buyval)+Cum(Shortval))*0.0006,1);GfxTextOut(": "+WriteVal(LastValue(Cum(Buy)+Cum(Short),1.0),1),450,pxh-190);GfxTextOut(": "+WriteVal(LongPLA+ShrtPLA,1.0),450,pxh-150);GfxTextOut(": "+WriteVal(Brkg,1.0),450,pxh-130);GfxTextOut(": "+WriteVal(LongPLA+ShrtPLA-Brkg,1.0),450,pxh-110);GfxTextOut("&",45,pxh-170);GfxTextOut("Loss",30,pxh-150);GfxTextOut("Statement",5,pxh-130);GfxTextOut("Long P/L",5,pxh-100);
GfxTextOut("Short P/L",5,pxh-70);GfxTextOut("Total P/L",5,pxh-40);GfxTextOut("Daily P/L",120,pxh-190);GfxTextOut(CDate,120,pxh-150);GfxTextOut(WriteVal(LongPLT,1.0),140,pxh-100);GfxTextOut(WriteVal(ShrtPLT,1.0),140,pxh-70);GfxTextOut(WriteVal(LongPLT+ShrtPLT,1.0),140,pxh-40);GfxTextOut("P/L ALL",230,pxh-190);GfxTextOut(FDate,220,pxh-170);GfxTextOut("To",250,pxh-150);GfxTextOut(LDate,220,pxh-130);GfxTextOut(WriteVal(LongPLA,1.0),230,pxh-100);GfxTextOut(WriteVal(ShrtPLA,1.0),230,pxh-70);GfxTextOut(WriteVal(LongPLA+ShrtPLA,1.0),230,pxh-40);
GfxMoveTo( 104, pxh-170 ); GfxLineTo( 328, pxh-170);for( Col = 1; Col < 3; Col++ ) { GfxMoveTo( col*105, pxh-200); GfxLineTo( col*105, pxh-22 ); } for( i = 1; i < 4 ; i++ ) { GfxMoveTo( 0, i*30+(pxh-135) ); GfxLineTo( 328, i*30+(pxh-135));} }Alert=Buy OR Short OR Sell OR Cover ;AlertIf(ALERT,"SOUND C:\\Windows\\Media\\notify.wav", "Audio alert", 0 );Inst=ParamToggle("Hide Instructions","No|Yes",1);if (inst==1){GfxRoundRect( 1, 35, pxw-400, pxh-207 , 7, 7 ) ;
GfxDrawText("To Close This Instruction..Select 'Yes' in Parameter Window                                              Hi This is the Basic code  to fire Orders to Pi.                                                                    You Have to Set the variables Like Exchange,Trade Symbol,Qty,ProductType,OrderType As per Your Requirement/Strategey in Parameter Window.                                                  In Parameter window, type your Trade Symbol as Exactly as in Pi/Nest Ex: ACC-EQ, NIFTY15MARFUT etc..Else Order will NOT be fired to Pi.                                                    Most Important:if U have 2 OR More Chart in amibroker with same Chart ID (OR) Scanning Ur AFL for Many Symbols...Whatever U change/assign any values in Parameter window, It will be applied to all Symbols U are scanning OR All Opened chart..                                                                                                                                    Example:if U Typed Trade symbol as ACC-EQ in Parameter window...Then if any Signal generated on any symbol,..It 'll assign trade symbol as ACC-EQ to all Signal generated symbols...So U have only ACC-EQ orders with different price AND Qty..                             Pi bridge will NOT work if U Opened Amibroker First AND Pi Second..in that case Just Close AND Reopen Amibroker...                                                                                          Amibroker Has very Special feature Bar Replay...U can use that option to simulate live trading session to Check Ur Strategy AND firing of Orders to Pi..                                    This AFL Has Profit/Loss Table included...  No Backtest is Required..P/L can be seen On Chart",1,35,pxw-400,pxh,16);}
_SECTION_END();
1 Like