Unable to move past IB and Amibroker automated trading

requesting all experts/seniors/metors for guidance please.

since last 6 weeks, I have been unable to write a simple program which can buy/sell/short/cover for a simple crossover.

I tried learning as much as I could( as I didnt want to just come to forum as ask question), I visited user KB, past questions, did some google, looked into @Tomasz suggestions. I have some coding background( not an expert though), still I cant figure out where am i going wrong.
I finally referred http://www.amibroker.org/userkb/2007/07/14/preventing-repeat-orders-and-whipsaws/ to undestand situation, yet my issue not resolved.

main issue- while backtesting, when amibroker sends buy signal, it takes a while to get executed in TWS, in the meantime amibroker finds a sell signal, so my program end up selling 2 ( as getpositionsize doesnt give true data due to this lag)

I am using offline TWS 9.72 and IB Controller 1.3.8. pasted my code inline.
please help!!

SetChartOptions(0,chartShowArrows|chartShowDates);

_SECTION_BEGIN("EMA Cross");
RequestTimedRefresh( 1 ); 
ibc = GetTradingInterface("IB"); 
Buy =  Cross(EMA(Close,10),EMA(Close,20));
Sell = Cross(EMA(Close,20),EMA(Close,10));
OrderSize=1;

PrevTN = StaticVarGet("TimeNumber"); 
TN = LastValue(TimeNum()); 
NewBar = TN != PrevTN; 
StaticVarSet("TimeNumber",TN); 
BuyOrderID = StaticVarGetText("BuyOrderID"); 
SellOrderID = StaticVarGetText("SellOrderID"); 
BuyPending = ibc.IsOrderPending(BuyOrderID); 
SellPending = ibc.IsOrderPending(SellOrderID); 
if( NewBar ) 
{ 
   if( NOT BuyPending ) StaticVarSetText("BuyOrderID",""); 
   if( NOT SellPending ) StaticVarSetText("SellOrderID",""); 
   SetChartBkColor( colorWhite ); 
}
   if( LastValue(Buy) AND BuyOrderID=="") 
   { 
   _TRACE( " <<<<Buy trigger>>> | Check  current Position before any decision");	
   cPosSize=ibc.GetPositionSize(Name());  
   
   	if(cPosSize==0){
   	_TRACE( " <<<checked- NO position>>> | Initiate LONG --->>>");
   	 BuyOrderID= ibc.ModifyOrder( BuyOrderID, Name(), "Buy", OrderSize, "MKT", 0, 0, "Day", True);
   	 StaticVarSetText("BuyOrderID",BuyOrderID); 
   	 SetChartBkColor( colorBrightGreen ) ; 
		 }
   	else if(cPosSize==1){
   	 _TRACE( " <<<Checked- Has LONG position>>> | No Order required ********");	 
   	}
   	else if(cPosSize== -1){
   	 _TRACE( " <<<Checked - Has SHORT position>>> | Close Shorts & GO LONG +++++");
   	 BuyOrderID= ibc.ModifyOrder( BuyOrderID, Name(), "Buy", 2, "MKT", 0, 0, "Day", True); 
   	 //BuyOrderID= ibc.ModifyOrder( BuyOrderID, Name(), "Buy", OrderSize, "MKT", 0, 0, "Day", True); 
   	 StaticVarSetText("BuyOrderID",BuyOrderID); 
		 SetChartBkColor( colorBrightGreen ) ; 
   	}else if((cPosSize < -1) OR (cPosSize >1)){
   	_TRACE( " something wrong");
   	}
   } else if( LastValue(Sell) AND SellOrderID=="") 
   { 
   _TRACE( " <<<<Sell trigger>>> | Check  current Position before any decision");	
   cPosSize=ibc.GetPositionSize(Name());  
   
   	if(cPosSize==0){
   	_TRACE( " <<<checked- NO position>>> | Initiate Short <<---");
   	 SellOrderID= ibc.ModifyOrder( SellOrderID, Name(), "Sell", OrderSize, "MKT", 0, 0, "Day", True);
   	 StaticVarSetText("SellOrderID",SellOrderID); 
   	 SetChartBkColor( colorRed ) ; 
		 }
   	else if(cPosSize==1){
   	 _TRACE( " <<<Checked- Has LONG position>>> | Close LONG and Go Short -----");	 
   	 SellOrderID= ibc.ModifyOrder( SellOrderID, Name(), "sell", 2, "MKT", 0, 0, "Day", True); 
   	 StaticVarSetText("SellOrderID",SellOrderID); 
   	 //SellOrderID= ibc.ModifyOrder( SellOrderID, Name(), "sell", OrderSize, "MKT", 0, 0, "Day", True); 
		 SetChartBkColor( colorRed ) ; 
   	}
   	else if(cPosSize== -1){
   	 _TRACE( " <<<Checked - Has SHORT position>>> | No Order required ********");
   	 }else if((cPosSize < -1) OR (cPosSize >1)){
   	_TRACE( " something wrong");
   	}
   }

LastTWSMsg = ibc.getLastError( 0 ); 
BuyStatus = WriteIf( BuyOrderID != "", BuyOrderID+", Status: "+ibc.GetStatus( BuyORderID, True ),""); 
SellStatus= WriteIf( SellOrderID != "", SellOrderID+", Status: "+ibc.GetStatus( SellORderID, True ),""); 
LastBuyTime= Nz(StaticVarGet("LastBuyTime")); 
LastSellTime= Nz(StaticVarGet("LastSellTime")); 

SetChartOptions(0,chartShowArrows|chartShowDates);
Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, 
SelectedValue( ROC( C, 1 ) ) )+"  "+"\n"+ 
"Last TWS Error Msg: "+LastTWSMsg+"\n"+ 
"PrevTN: "+PrevTN+ "\n"+ 
"Current TN "+TN+ "\n"+ 
" BuyOrderID: "+BuyStatus+"\n"+ 
" SellOrderID: "+SellStatus+"\n"+ 
"TWS Position Size: "+NumToStr(ibc.GetPositionSize( Name() ),1.0,False); 
_SECTION_END();

/*********************************************************************/
_SECTION_BEGIN("Plotting of Buy/sell Arrows");
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
Plot(EMA(Close,10),"10-EMA",colorGreen,styleThick,styleDashed);
Plot(EMA(Close,20),"20-EMA",colorRed,styleLine);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorGreen, 0,L, Offset=-25); 
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
//PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorRed, 0,H, Offset=-25); 
//PlotShapes(IIf(Cover, shapeHollowUpArrow, shapeNone),colorGreen, 0,L, Offset=-35); 
PlotShapes(IIf(Sell, shapeHollowDownArrow, shapeNone),colorRed, 0,H, Offset=-35); 
PlotShapes(IIf(Sell, shapeStar, shapeNone),colorRed, 0, H, Offset=70);
_SECTION_END();


1 Like

Halo @rakeshjha

I have the same problem like you, How the update ?

(I want to make a new post, but apparently there is a post that is the same as my problem).

There are 3 crucial points that you formula must implement:

  • don't use GetPositionSize to get real-time pos size as the account data sent by TWS are DELAYED.
  • you should be tracking your position size YOURSELF using static variables
  • you should implement STATE machine that goes via fixed sequence of states when given events arrive:

https://www.google.com/search?q=state+machine

If you are unable to do that yourself, there are 3rd party programmers you can hire Third party services, blogs, courses, books, add-ons