Automated Buy Returning Sell

Hi everyone,
I apologize if I'm overlooking something simple. I've been trying to teach myself coding/amibroker from online videos, this forum, and books but unfortunately that can only get you so far when you don't have someone to talk to.

I'm currently just trying to confirm that I've set up my amibroker to InteractiveBrokers code correctly. My current buy commands are "buy if close is greater than 0, sell if close is greater than 0 but on the next bar" the command works fine for MOST ETF's but on some it returns a sell before it returns a buy function. I've tested it on 10 etf's but can't find a reason why it works for most but not all (it successfully bought CORN, XLY XLK, NIB, SOXX, UNG, SSO, TAN, FXI, SPY, QQQ but it is returning a sell command for WEAT, VIXY, TLT and XOP). I also am receiving "Error 19. COM method/function PlaceOrder call failed. COM error: HRESULT = 8002000a (Ln: 446, Col. 69)" whenever my short command is initiated. I've checked and the short/cover commands for IB should be the exact same as the buy/sell commands. If anyone can offer any insight at all I would be massively in your debt, I have attached the entirety of my code to be safe however the chart and backtesting sections are most likely irrelevant.
I am currently trying to trade at the open and/or close on daily bars in eastern standard time.

_SECTION_BEGIN("New Chart");

//To live trade turn on scanner and set time frame to 1 bar
//Strategy set 1

SetOption("WarningLevel",True);
barcolor = ((IIf(C>O,colorGreen,colorRed)));
SetBarFillColor(barcolor);
Plot( C, "Price", barcolor, styleCandle );

GfxSelectFont( "Tahoma", 11, 110 );
GfxSetBkMode( 1 );
GfxSetTextColor( colorWhite );
SetChartOptions(0,chartShowArrows|chartShowDates);
//SetBarsRequired(sbrAll,sbrAll);

GraphXSpace=10;
dec = (2/10)+1;
Title = EncodeColor(55)+ Title = Name() + " " + EncodeColor(32) + Date() +
" " + EncodeColor(5) + "{{INTERVAL}} " +
EncodeColor(55)+ " Open = "+ EncodeColor(52)+ WriteVal(O,dec) +
EncodeColor(55)+ " High = "+ EncodeColor(5) + WriteVal(H,dec) +
EncodeColor(55)+ " Low = "+ EncodeColor(32)+ WriteVal(L,dec) +
EncodeColor(55)+ " Close = "+ EncodeColor(7)+ WriteVal(C,dec)+
EncodeColor(55)+ " Volume = "+ EncodeColor(11)+ WriteVal(V,1)+
EncodeColor(55)+ " ROC = "+ EncodeColor(colorOrange)+ WriteVal(SelectedValue( ROC( C, 1 ) ));

_SECTION_END();

//################################### Below Section is only for Intraday Timing Condition #############################

_SECTION_BEGIN("Intraday Timing Condition");

Intra = ParamToggle("Intraday Mode On/Off","OFF|ON",0);

FirstTradeTime = ParamTime( "Start Time", "09:15" ); // Earliest time to take a trade
LastTradeTime = ParamTime( "End Time", "15:00" ); // Latest time to take new trades
ExitAllPositionsTime = ParamTime( "Exit Time", "15:10" ); // Exit all trades

if (Intra)
{

Entrytimecondition = (Now(format=4) >= FirstTradeTime AND Now(format=4) <= LastTradeTime );

Exittimecondition = Cross(Now(format=4),ExitAllPositionsTime);

}
else
{

Entrytimecondition = True;

Exittimecondition = false;
}

dn = Day();
newday = dn != Ref( dn, -1 );
bar=BarsSince(newday);

_SECTION_END();

//################################### Below Section is for Trading Strategy #############################

//IBController 1.3.8 READ ME

_SECTION_BEGIN("Trade Setting");
delay = Param("Trade Delay (Number of candle Delay)",1,0,10,1);
sambarexit = ParamToggle("Same Bar Entry and Exit","OFF|ON",0);

ct = Now(format=4) ;
opentime = 093015 ;
closetime = 155945 ;
starttime = 093000 ;
endtime = 160000 ;
_buy = 0 ;
_sell = 0 ;
_short = 0;
_cover = 0;

_buy = Close > 0 AND ct > closetime AND ct < endtime ;

_sell = Close > 0 AND ct > closetime AND ct < endtime ;

_short = Close > 0 AND ct > starttime AND ct < opentime ;

_cover = Close> 0 AND ct > starttime AND ct < opentime ;

_buy = Ref(_buy,-delay);
_sell = Ref(_sell,-delay);
_short = Ref(_short,-delay);
_cover = Ref(_cover,-delay);

PlotShapes(_buy*shapeStar,colorYellow);
Filter=1;
AddColumn(_buy,"_buy");

dir = ParamList("Trade Direction Long/Short/Both","Long_Only|Short_Only|Both",2);

_SECTION_END();

_SECTION_BEGIN("Take Profit and StopLoss Setting");

Type=ParamToggle("Point or Percent","Percent|Point",0);
BT = Param("Take Profit ",0.5,0.05,1000,0.05);
SL = Param("Stop Loss ",0.5,0.05,1000,0.05);

_SECTION_END();

//############################## Variable Initialization so we can use these variable name inside the For loop #########################

_SECTION_BEGIN("Variable Initialization");

Buy = Sell = Short = Cover = Null;

LongFlag = 0;
ShortFlag = 0;
Target = 0;
_BuyPrice = 0;
ShortTarget = 0;
_shortprice = 0;
buytarget= 0;
shorttarget= 0;
t= 0;
st= 0;
bsl= 0;
ssl= 0;
bp= 0;
sp=0;
buysl = 0;
shortsl=0;
Starget= 0;
sstoploss = 0;
LF=0;
SF=0;
EntryBar = 0;
BI = BarIndex();

//Using Loop to generate signals
for( i = 0; i < BarCount; i++ )
{
//#################### Long Positions ##################

//############### If we Enter in this Loop we will initiate the Buy Position ###########

if( _buy[ i ] AND LongFlag == 0 AND ShortFlag==0 AND (dir=="Long_Only" OR  dir=="Both") )
{
	 Buy[ i ] = 1;      //#########  Activate the Buy Signal for Current Bar  ############
	 
	 BuyPrice=o[i];   //####   Set the Buy Price so we can use this for backtest   #########
	 
	 _BuyPrice = o[i];  
	 
	 LongFlag = 1;   //####   If we are in long then we'll Enable Long Flag so we can avoid excessive entry signal Similer to Exrem Function in amibroker  #########
	 
	  
	 if(type)    //####   If Calcualtion Method is set to Point   #########
	{
		buytarget =  _BuyPrice[i] + BT ;
		buysl = _BuyPrice[i] - SL;
	}
	else   //####   If Calcualtion Method is set to Percent   #########
	{
		buytarget  = _BuyPrice[i] + (_BuyPrice[i]*(BT/100)) ; 
		buysl = _BuyPrice[i] - (_BuyPrice[i]*(SL/100));
	}
	
	EntryBar = BI[i];
}

//############### Buy Exit Position Condtion ###########

if(( LongFlag==1 AND High[i]>buytarget[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0) OR (LongFlag==1 AND High[i]>buytarget[i] AND  sambarexit[i]))         //############### Buy Exit From Take Profit ###########
{
	Sell[ i ] = 1;
	 
	SellPrice = Target[i];
	
	LongFlag = 0;  
}
 else
 if( (LongFlag==1 AND L[i] < buysl[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0) OR     (LongFlag==1 AND L[i] < buysl[i] AND  sambarexit[i]) )     //############### Buy Exit From Stoploss ###########
{
 
	Sell[ i ] = 1; 
	
	SellPrice[i] = buysl[i];
	
	LongFlag = 0; 
 
}
 else
 if((LongFlag==1 AND Exittimecondition[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0) OR (LongFlag==1 AND Exittimecondition[i] and  sambarexit[i])  )     //############### Buy Exit From Intraday Timing only if intraday mode is on ###########
{
 
	Sell[ i ] = 1;

	SellPrice[i] = Open[i];
	
	LongFlag = 0;		


}
 else
 if((LongFlag==1 AND _Sell[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0      )  OR (LongFlag==1 AND _Sell[i] AND  sambarexit[i]      ) )    //############### Buy Exit From _Sell Condition ###########
{
 
	Sell[ i ] = 1;

	SellPrice[i] = Open[i];
	
	LongFlag = 0;		


}

//#####################################################################################
//############################## Short Positions ###################################
//#####################################################################################

//############### If we Enter in this Loop we will initiate the Short Position ###########

if( _short[ i ] AND LongFlag == 0 AND ShortFlag==0  AND (dir=="Short_Only" OR  dir=="Both"))
{
	Short[ i ] = 1;      //#########  Activate the Short Signal for Current Bar  ############
	
	ShortPrice[i]=o[i];      //####   Set the Buy Price so we can use this for backtest   #########
	
	_ShortPrice = o[i];     
	
	ShortFlag = 1;       //####   If we are in Short then we'll Enable Short Flag so we can avoid excessive entry signal Similer to Exrem Function in amibroker  #########
	
	if(type)  					 //####   If Calculation Method is set to Point   #########
	{
		shorttarget =  _ShortPrice[i]  - BT ;
		
		Shortsl = _ShortPrice[i] +SL;
	}
	else   //####   If Calcualtion Method is set to Percent   #########
	{
		shorttarget  = _ShortPrice[i] - (_ShortPrice[i]*(BT/100)) ;   //########### Take Profit Calculation ##########
		
		Shortsl = _ShortPrice[i] + (_ShortPrice[i]*(SL/100));     //########### StopLoss Calculation ##########
	}
	
	EntryBar=BI[i];
}		 
if(( ShortFlag==1 AND High[i]>Shortsl[i] AND BI[i]>EntryBar[i] AND  sambarexit[i])      OR ( ShortFlag==1 AND High[i]>Shortsl[i] AND   sambarexit[i]==0)  )        //############### Short Exit From Stoploss ###########
{
	Cover[ i ] = 1;

	CoverPrice = Shortsl[i];
	
	ShortFlag = 0;  
}
else
if(( ShortFlag==1 AND L[i] < shorttarget[i]  AND BI[i]>EntryBar[i] AND  sambarexit[i] )OR ( ShortFlag==1 AND L[i] < shorttarget[i]   AND  sambarexit[i]==0 ))                //############### Short Exit From Take Profit ###########
{
	Cover[ i ] = 1; 
	
	coverPrice = shorttarget[i];
	
	ShortFlag = 0; 

}
else
if((ShortFlag==1 AND Exittimecondition[i]   AND BI[i]>EntryBar[i] AND  sambarexit[i] ) OR (ShortFlag==1 AND Exittimecondition[i]   AND  sambarexit[i]==0))                //############### Short Exit From Intraday Timing Condition, If intraday mode is on ###########
{

	Cover[ i ] = 1;

	COverPrice = Open[i];
	
	ShortFlag = 0;		

}
else
if((ShortFlag==1 AND _Cover[i]    AND BI[i]>EntryBar[i] AND  sambarexit[i] )    OR (ShortFlag==1 AND _Cover[i]    AND  sambarexit[i]==0))            //############### Short Exit From _Cover ###########
{

	Cover[ i ] = 1;

	COverPrice = Open[i];
	
	ShortFlag = 0;		

}

//#################### Storing All above Variable in new Array so we can use this value outside For Loop #############

bt[i] = buyTarget[i];
St[i] = ShortTarget[i];
bsl[i] = buysl[i];
ssl[i]= shortsl[i];
bp[i] = _buyprice[i];
sp[i]= _shortprice[i];
LF[i] = longflag[i];;
SF[i] =shortflag[i];

}

Buyflag = Flip(Buy,Sell);
Shortflag11 = Flip(Short,cover);

Plot(IIf(Buyflag,bt,Null),"Buy Take Profit",colorGreen,styleThick,Null,Null,0,0,2);
Plot(IIf(Shortflag11,st,Null),"Short Take Profit",colorGreen,styleThick,Null,Null,0,0,2);

Plot(IIf(Buyflag,bsl,Null),"Buy Stoploss",colorRed,styleThick,Null,Null,0,0,2);
Plot(IIf(Shortflag11,SSL,Null),"Short Stoploss",colorRed,styleThick,Null,Null,0,0,2);

Plot(IIf(Buyflag,BP,Null),"BuyPrice",colorWhite,styleThick,Null,Null,0,0,2);
Plot(IIf(Shortflag11,SP,Null),"ShortPrice",colorWhite,styleThick,Null,Null,0,0,2);

dist = 1.5*ATR(10);

for( i = 0; i < BarCount; i++ )
{
if( Buy[i] ) PlotText( "Buy @ " + BP[ i ], i, L[ i ]-dist[i], colorGreen );
if( Sell[i] ) PlotText( "Sell @ " + C[ i ], i, H[ i ]+dist[i], colorRed );

if( Cover[i] ) PlotText( "Cover @ " + C[ i ], i, L[ i ]-dist[i], colorGreen );
if( Short[i] ) PlotText( "Short @ " + SP[ i ], i, H[ i ]+dist[i], colorRed );
}

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( Sell , shapeDownArrow, shapeNone ), colorGreen , 0, H, Offset = -45 );

PlotShapes( IIf( Short, shapeSquare, shapeNone ), colorRed, 0, H, Offset = 40 );
PlotShapes( IIf( Short, shapeSquare, shapeNone ), colorOrange, 0, H, Offset = 50 );
PlotShapes( IIf( Short, shapeDownArrow, shapeNone ), colorWhite, 0, H, Offset = -45 );
PlotShapes( IIf( Cover , shapeUpArrow, shapeNone ), colorRed, 0, L, Offset = -45 );

_SECTION_END();

//######## Backtest Code ###########

_SECTION_BEGIN("BackTest Setting");

Initial_Equity = Param("Initial Equity",100000,100,10000000,1);

Equity_Percent = Param("Capital Allocation (Percent OF Equity)",80,0.05,100,0.05);

Max_Open_Position = Param("Max Open Position",4);

holdminbars = Param("Max Open Position",1);

SetOption("initialEquity",Initial_Equity);

SetPositionSize(Equity_Percent,spsPercentOfEquity);

setOption("MaxOpenPositions",Max_Open_Position);

setOption("holdminbars",holdminbars);

SetTradeDelays( 0, 0, 0, 0 );

_SECTION_END();

//########################### Automation Code ///////////

//######## Explorer Code ###########

_SECTION_BEGIN("Explorer");

Filter = (Buy OR Sell);
AddTextColumn(WriteIf(Buy,"Buy","Sell"),"Buy/Sell");

_SECTION_END();

//######## IB automation Code ###########

_SECTION_BEGIN("IB Setting");

ibc = GetTradingInterface("IB");
EnableTextOutput(0);
printf( "\nibc " + ibc +"\n");

//availableFunds = ibc.GetAccountValue("AvailableFunds"); // Need to test this function

Auto_trading = ParamToggle("Auto Trading","Auto Trading Off|Auto Trading On",1);
Symbol = Name();
QTY = StrToNum(""+(round(Param("Max Amount For Each Symbol",1000,1,100000,1) /bp ) ));
// round(Param("Max Amount For Each Symbol",1000,1,100000,1) /bp ) ;

Dop = ValueWhen(newday,O);

_SECTION_END();

_SECTION_BEGIN("IB Execution");

tn = Now(format=4);

VarName = Name()+GetChartID()+""+Dop;

if(LastValue(tn) != Nz(StaticVarGet("IBBuyOTime"+VarName)))
StaticVarSet("IBBuyO"+VarName,False);

if(LastValue(tn) != Nz(StaticVarGet("IBSellOTime"+VarName)))
StaticVarSet("IBSellO"+VarName,False);

if(LastValue(tn) != Nz(StaticVarGet("IBShortOTime"+VarName)))
StaticVarSet("IBShortO"+VarName,False);

if(LastValue(tn) != Nz(StaticVarGet("IBCoverOTime"+VarName)))
StaticVarSet("IBCoverO"+VarName,False);

if(LastValue(Sell) AND Nz(StaticVarGet("IBSellO"+VarName))==False)
{
_TRACE("Buy Exit , " + Name());
ibc.PlaceOrder(Symbol, "SELL", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBSellO"+VarName,True);
StaticVarSet("IBSellOTime"+VarName,LastValue(tn));
}

if(LastValue(Cover) AND Nz(StaticVarGet("IBCoverO"+VarName))==False)
{
_TRACE("Short Exit , " + Name());
ibc.PlaceOrder(Symbol, "BUY", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBCoverO"+VarName,True);
StaticVarSet("IBCoverOTime"+VarName,LastValue(tn));
}
if(LastValue(Buy) AND Nz(StaticVarGet("IBBuyO"+VarName))==False)
{
_TRACE("Buy Entry , " + Name());

ibc.PlaceOrder(Symbol, "BUY", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBBuyO"+VarName,True);
StaticVarSet("IBBuyOTime"+VarName,LastValue(tn));
}

if(LastValue(Short) AND Nz(StaticVarGet("IBShortO"+VarName))==False)
{
_TRACE("Short Entry , " + Name());
ibc.PlaceOrder(Symbol, "SELL", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBShortO"+VarName,True);
StaticVarSet("IBShortOTime"+VarName,LastValue(tn));
}

_SECTION_END();

When posting the formula, please make sure that you use Code Tags (using </> code button) as explained here: How to use this site.

Using code button

Code tags are required so formulas can be properly displayed and copied without errors.

_SECTION_BEGIN("New Chart");

//To live trade turn on scanner and set time frame to 1 bar
//Strategy set 1

SetOption("WarningLevel",True);
barcolor = ((IIf(C>O,colorGreen,colorRed)));
SetBarFillColor(barcolor);
Plot( C, "Price", barcolor, styleCandle );

GfxSelectFont( "Tahoma", 11, 110 );
GfxSetBkMode( 1 );
GfxSetTextColor( colorWhite );
SetChartOptions(0,chartShowArrows|chartShowDates);
//SetBarsRequired(sbrAll,sbrAll);

GraphXSpace=10;
dec = (2/10)+1;
Title = EncodeColor(55)+  Title = Name() + "     " + EncodeColor(32) + Date() +
"      " + EncodeColor(5) + "{{INTERVAL}}  " +
    EncodeColor(55)+ "     Open = "+ EncodeColor(52)+ WriteVal(O,dec) +
    EncodeColor(55)+ "     High = "+ EncodeColor(5) + WriteVal(H,dec) +
    EncodeColor(55)+ "      Low = "+ EncodeColor(32)+ WriteVal(L,dec) +
    EncodeColor(55)+ "    Close = "+ EncodeColor(7)+ WriteVal(C,dec)+
    EncodeColor(55)+ "    Volume = "+ EncodeColor(11)+ WriteVal(V,1)+
    EncodeColor(55)+ "    ROC = "+ EncodeColor(colorOrange)+ WriteVal(SelectedValue( ROC( C, 1 ) ));

_SECTION_END();


//################################### Below Section is only for Intraday Timing Condition #############################

_SECTION_BEGIN("Intraday Timing Condition");

Intra = ParamToggle("Intraday Mode On/Off","OFF|ON",0);

FirstTradeTime = ParamTime( "Start Time", "09:15" ); // Earliest time to take a trade
LastTradeTime = ParamTime( "End Time", "15:00" );  // Latest time to take new trades
ExitAllPositionsTime = ParamTime( "Exit Time", "15:10" );		// Exit all trades

if (Intra)
{

Entrytimecondition = (Now(format=4) >= FirstTradeTime AND Now(format=4) <= LastTradeTime );

Exittimecondition = Cross(Now(format=4),ExitAllPositionsTime);

}
else
{

Entrytimecondition = True;

Exittimecondition = false;
}



dn = Day();
newday = dn != Ref( dn, -1 );
bar=BarsSince(newday);

_SECTION_END();


//################################### Below Section is for Trading Strategy #############################




//https://www.amibroker.com/at/

_SECTION_BEGIN("Trade Setting");
delay = Param("Trade Delay (Number of candle Delay)",1,0,10,1);
sambarexit = ParamToggle("Same Bar Entry and Exit","OFF|ON",0);

ct = Now(format=4)	;
opentime = 093015 ;
closetime = 155945 ;
starttime = 093000 ;
endtime = 160000 ;
_buy = 0 ;
_sell = 0 ;
_short = 0;
_cover = 0;


//Strategy 1 good for 23 years
//1. Calculate the "typical price": (high+low+close) divided by three. Make a ten-day simple
//moving average of the typical price.
//2. Calculate a lower band by subtracting the 10-day ATR multiplied with 1.5 from the typical price.
//This is the lower band.
//3. Calculate the IBS: (close-low)/(high-low). 
//4. If the close is lower than the band in number 2, the IBS is below 0.2, and the ten day ADX is above 20, 
//then buy at the close. 
//5. Exit at the close when today's close is higher than yesterday's high.
//use TimeNum() > 155900 when live trading to restrict to close

if (Name () == "XLK")

{
ibs=(C-L)/(H-L)  ;

TypicalPrice = MA((High+Low+Close)/3,10);
LowerBand = TypicalPrice - (1.5*(ATR(10)));
ibs = (Close -Low)/(High-Low) ;


_buy = Close<lowerband AND ibs<0.2 AND ADX(10)>20 AND ct > closetime AND ct < endtime ;

_sell = Close>Ref(H,-1) AND ct > closetime AND ct < endtime ;
}

//Strategy 3 good for 23 years
//1. The 5-day Williams %R should be lower than -80.
//2. The five-day ADX must be higher than 40.
//3. If 1 and 2 are true, enter at the close. 
//4. Sell at the close when the high is higher than yesterday's close.

if (Name () == "SSO") //Strategy 3 good for 23 years
{

WR = ( ( HHV(H,5) - Close ) / ( HHV(H,5) - LLV(L,5) ) ) * -100 ; 

_buy= WR<-80 AND ADX(5)>40 AND ct > closetime AND ct < endtime ; 		
			
							
_sell= Close>Ref(H,-1) AND ct > closetime AND ct < endtime ; 

}

//Strategy 4 - good for 5 years
//1. The IBS must be lower than 0.2. 
//2. The two-day RSI must be lower than 10. 
//3. If 1 and 2 are true, enter at the close. 
//4. Sell at the close when the close is higher than yesterday's close. 

if (Name () == "XLK")
{
ibs=(C-L)/(H-L) ;


_buy= ibs<0.2 AND RSI(2)<10  AND ct > closetime AND ct < endtime  ;		
								
	
_sell= Close>Ref(C,-1)  AND ct > closetime AND ct < endtime ; 	
		
}

//Strategy 5 - good at 5 years
//1. The five-day ADX must be greater than 35. 
//2. The two-day RSI must be lower than 15. 
//3. If 1 and 2 are true, enter at the close. 
//4. Sell at the close when the close is higher than yesterday's close. 

if (Name () == "WEAT") //also triggers sell
{

_buy= RSI(2)<15 AND ADX(5)>35 AND ct > closetime AND ct < endtime ;

_sell= C>Ref(H,-1) AND ct > closetime AND ct < endtime ;		
				
}

//Strategy 8 - good for 23 years 
//1. When today's IBS is below 0.2, yesterday's IBS was also below 0.2, and today's five-day RSI 
//must be below 55.
//2. Buy at close if those three criteria in number 1 are true.
//3. Exit at the close when today's close is higher than yesterday's close
 
if (Name () == "FXI")

{
ibs=(C-L)/(H-L) ;

_buy= ibs < 0.2 AND Ref(ibs,-1) < 0.2 AND RSI(5) < 55 AND ct > closetime AND ct < endtime ;		

_sell = Close>ref(H,-1) AND ct > closetime AND ct < endtime ;				
						
}


//Strategy 12 - good for 5 years
//1. Today is Monday.
//2. The ten-day RSI must be above 60.
//3. Short at the close if 1 and 2 are true.
//4. Cover at the open the next day (Tuesday).

if (Name () == "NIB")
 
{

_short = dayOfWeek()==1 AND RSI(10) > 60 AND ct > closetime AND ct < endtime ;

_cover = Ref(_short ,-1)  AND ct < opentime AND ct > starttime;

}

//Strategy 15 - good for 23 years
//1. Today is the last trading day of the month.
//2. The S&P 500 needs to be above its 200-day moving average.  
//2. Go short TLT at the close.
//3. Cover on the close on the seventh trading day of the new month. 

if (Name () == "VIXY") 
{

Fremmed=Foreign("SPY","Close",fixup=1);

_short = Month() != Ref(Month(),1) AND fremmed>MA(fremmed,200) AND ct > closetime AND ct < endtime ;

bars = BarsSince(_short) == 6 ;			

_cover = bars AND ct > closetime AND ct < endtime ;
			
}

//Strategy 17 - good for 5 years
//1. Calculate the High minus Low each day. This is the daily range.
//2. If today has the lowest daily range of the last seven days and the 5-day ADX is higher than 40 
//(or in this ballpark), then go long at the close. 
//3. When the close is higher than yesterday's high, sell at the close. 

if (Name () == "CORN")
{

range1=(H-L) ;

_buy=  range1<Ref(LLV(range1, 6),-1) AND ADX(5)> 40 AND ct > closetime AND ct < endtime ;		

_sell = Close>ref(H,-1) AND ct > closetime AND ct < endtime ;		

}

//Strategy 18 - good for 23 years
//1. Today is the third lower low in a row. 
//2. Today is the third lower high in a row. 
//3. If 1 and 2 are true, go long at the close.
//4. Exit at tomorrow's close. 

if (Name () == "XLY")
{
ibs=(C-L)/(H-L) ;

_buy= Low<Ref(Low,-1) AND High<Ref(High,-1) AND Ref(Low,-1)<Ref(Low,-2) AND Ref(High,-1)<Ref(High,-2) AND Ref(Low,-2)<Ref(Low,-3) AND Ref(High,-2)<Ref(High,-3) AND ct > closetime AND ct < endtime ;


_sell = Close>ref(H,-1) AND ct > closetime AND ct < endtime ;

}

//Strategy 19 - good for 23 years
//1. Today is Monday. 
//2. Today's close is lower than yesterday's close. 
//3. Today's close must be lower than the close 22 days ago (about one month).
//4. If 1-3 are true, then buy the close.
//5. Sell on next day's close (Tuesday). 
 
if (Name () == "XOP") 
{

_buy=  DayOfWeek()==1 AND C<Ref(C,-1) AND Close<Ref(C,-22) AND ct > closetime AND ct < endtime ;

_sell= Ref(_buy,-1) AND ct > closetime AND ct < endtime ;

}

//Strategy 20 - good for 23 years
//1. Today is Monday in options expiration week (OPEX week). 
//2. Friday's (yesterday) 5-day RSI must be lower than 70. 
//3. If 1-2 are true, then buy the open.
//5. Sell on next day's close (Tuesday). 

if (Name () == "XLF") 
{

_buy=  DayOfWeek()==1 AND Day()>10 AND Day()<18 AND Ref(RSI(5),-1)<70  AND ct < opentime AND ct > starttime  ;

_sell= Ref(_buy,-1) AND ct > closetime AND ct < endtime ;

}

//Strategy 21 - good for 23 years
//1. Today's close must be lower than yesterday's. 
//2. The two-day RSI must be lower than 10.  
//3. VXN must close at a ten-day high. 
//4. If 1-3 are true, then but at the close.
//5. Sell at the close when today's close is higher than yesterday's high.  

if (Name () == "SOXX")
{

Fremmed=Foreign("^VXN","close",fixup=1);

_buy=   C<Ref(C,-1) AND RSI(2)<10 AND fremmed>Ref(HHV(fremmed,10), -1) AND ct > closetime AND ct < endtime ;

_sell= C>Ref(H,-1) AND ct > closetime AND ct < endtime ;

}

//Strategy 22 - good for 23 years
//1. The IBS must be below 0.5. 
//2. The five-day RSI must be below 25.  
//3. If 1-2 are true, then but at the close.
//5. Sell at the close tomorrow or the next trading day.   

if (Name () == "SSO")
{

ibs=(C-L)/(H-L) ;
_buy = ibs<0.5 AND RSI(5)<25 AND ct > closetime AND ct < endtime  ;

_sell = Ref(_buy,-1) AND ct > closetime AND ct < endtime ;

}

//Strategy 23 - good for 23 years

//1. Yesterday's IBS must be above 0.5 
//2. Today's IBS must be above 0.75.  
//3. Today's 5-day RSI must be above 70.
//4. Today's open must be higher than yesterday's close.
//5. It's not December.
//6. If 1-5 are true, then short at the close. 
//7. Cover when the close is lower than yesterday's close or when the IBS is lower than 0.2.    
 
if (Name () == "UNG")
{
ibs=(C-L)/(H-L) ;
_short= ibs> 0.75 AND Ref(ibs,-1)> 0.5 AND RSI(5)>70 AND O>Ref(C,-1) AND Month()!=12 AND ct > closetime AND ct < endtime ;


_cover=C<Ref(C,-1) OR ibs<0.2 AND ct > closetime AND ct < endtime ;

}

//Strategy 24 - good for 5 years
//1. Today is Monday.
//2. Calendar day is higher than 10th, but lower than 18th (option expiration week).
//3. The 5-day RSI of SPY/@ES was above 50 on the close of Friday (previous trading day).
//4. If 1-3 are true, then buy the open on Monday. 
//5. Sell at the close of Friday or after 5 trading days. 

if (Name () == "TLT") 
{

Fremmed=Foreign("SPY","close",fixup=1);
RSIfremmed=RSIa(fremmed,5);


_buy=  DayOfWeek()==1 AND Day()>10 AND Day()<18 AND  Ref(RSIfremmed,-1)>50  AND ct > opentime AND ct > starttime ;


_sell= DayOfWeek()==5  AND ct > closetime AND ct < endtime ;

}


//Strategy 26 - good for 5 years
//1. Today's close must be higher than today's open.
//2. The IBS must be higher than 0.6. 
//3. The 2-day RSI must be below 50.
//4. If 1 - 3 are true, buy the close (at 1730 German time/CET).
//5. Sell the open the next day (0900 German time/CET). 

if (Name () == "TAN")
{

ibs=(C-L)/(H-L)  ;

_buy= ibs> 0.6  AND RSI(2)<50 AND C>O AND ct > closetime AND ct < endtime ;

_sell= Ref(_buy,-1)  AND ct < opentime AND ct > starttime ;

}


//Strategy 29 - good for 5 years
//1. When TLT crosses above its 15-day moving average of its close, go long VNQ at the close.
//2. When TLT crosses below its 15-day moving average of its close, sell VNQ at the close.

if (Name () == "TAN")
{

Fremmed=Foreign("TLT","close",fixup=1);

_buy = Cross(fremmed,MA(fremmed,15))  AND ct > closetime AND ct < endtime ;

_sell = Cross(MA(fremmed,15),fremmed) AND ct > closetime AND ct < endtime ;

}

_buy = Ref(_buy,-delay);
_sell = Ref(_sell,-delay);
_short = Ref(_short,-delay);
_cover = Ref(_cover,-delay);

PlotShapes(_buy*shapeStar,colorYellow);
 Filter=1;
AddColumn(_buy,"_buy");



dir = ParamList("Trade Direction Long/Short/Both","Long_Only|Short_Only|Both",2);

_SECTION_END();

_SECTION_BEGIN("Take Profit and StopLoss Setting");

Type=ParamToggle("Point or Percent","Percent|Point",0);
BT = Param("Take Profit ",0.5,0.05,1000,0.05);
SL = Param("Stop Loss ",0.5,0.05,1000,0.05);

_SECTION_END();

//##############################  Variable Initialization  so we can use these variable name inside the For loop #########################

 _SECTION_BEGIN("Variable Initialization");

Buy = Sell = Short = Cover  = Null;

LongFlag =  0;
ShortFlag =  0;
Target = 0;
_BuyPrice = 0;
ShortTarget = 0; 
_shortprice = 0;
buytarget= 0;
shorttarget= 0;
t= 0;
st= 0;
bsl=  0;
ssl= 0;
bp=   0;
sp=0;
buysl = 0;
shortsl=0;
Starget=  0;
sstoploss = 0;
LF=0;
SF=0;
EntryBar = 0;
BI = BarIndex();

//Using Loop to generate signals
for( i = 0; i < BarCount; i++ )
{
//####################  Long Positions    ##################


 //############### If we Enter in this Loop we will initiate the Buy Position ###########
 
	if( _buy[ i ] AND LongFlag == 0 AND ShortFlag==0 AND (dir=="Long_Only" OR  dir=="Both") )
	{
		 Buy[ i ] = 1;      //#########  Activate the Buy Signal for Current Bar  ############
		 
		 BuyPrice=o[i];   //####   Set the Buy Price so we can use this for backtest   #########
		 
		 _BuyPrice = o[i];  
		 
		 LongFlag = 1;   //####   If we are in long then we'll Enable Long Flag so we can avoid excessive entry signal Similer to Exrem Function in amibroker  #########
		 
		  
		 if(type)    //####   If Calcualtion Method is set to Point   #########
		{
			buytarget =  _BuyPrice[i] + BT ;
			buysl = _BuyPrice[i] - SL;
		}
		else   //####   If Calcualtion Method is set to Percent   #########
		{
			buytarget  = _BuyPrice[i] + (_BuyPrice[i]*(BT/100)) ; 
			buysl = _BuyPrice[i] - (_BuyPrice[i]*(SL/100));
		}
		
		EntryBar = BI[i];
	}
		
 //############### Buy Exit Position Condtion ###########
 
 
	if(( LongFlag==1 AND High[i]>buytarget[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0) OR (LongFlag==1 AND High[i]>buytarget[i] AND  sambarexit[i]))         //############### Buy Exit From Take Profit ###########
	{
		Sell[ i ] = 1;
		 
		SellPrice = Target[i];
		
		LongFlag = 0;  
	}
	 else
	 if( (LongFlag==1 AND L[i] < buysl[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0) OR     (LongFlag==1 AND L[i] < buysl[i] AND  sambarexit[i]) )     //############### Buy Exit From Stoploss ###########
	{
	 
		Sell[ i ] = 1; 
		
		SellPrice[i] = buysl[i];
		
		LongFlag = 0; 
	 
	}
	 else
	 if((LongFlag==1 AND Exittimecondition[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0) OR (LongFlag==1 AND Exittimecondition[i] and  sambarexit[i])  )     //############### Buy Exit From Intraday Timing only if intraday mode is on ###########
	{
	 
		Sell[ i ] = 1;

		SellPrice[i] = Open[i];
		
		LongFlag = 0;		
	
	
	}
	 else
	 if((LongFlag==1 AND _Sell[i] AND BI[i]>EntryBar[i] AND  sambarexit[i]==0      )  OR (LongFlag==1 AND _Sell[i] AND  sambarexit[i]      ) )    //############### Buy Exit From _Sell Condition ###########
	{
	 
		Sell[ i ] = 1;

		SellPrice[i] = Open[i];
		
		LongFlag = 0;		
	
	
	}
//#####################################################################################		 
//##############################     Short Positions       ###################################
//#####################################################################################




//############### If we Enter in this Loop we will initiate the Short Position ########### 

	if( _short[ i ] AND LongFlag == 0 AND ShortFlag==0  AND (dir=="Short_Only" OR  dir=="Both"))
	{
		Short[ i ] = 1;      //#########  Activate the Short Signal for Current Bar  ############
		
		ShortPrice[i]=o[i];      //####   Set the Buy Price so we can use this for backtest   #########
		
		_ShortPrice = o[i];     
		
		ShortFlag = 1;       //####   If we are in Short then we'll Enable Short Flag so we can avoid excessive entry signal Similer to Exrem Function in amibroker  #########
		
		if(type)  					 //####   If Calculation Method is set to Point   #########
		{
			shorttarget =  _ShortPrice[i]  - BT ;
			
			Shortsl = _ShortPrice[i] +SL;
		}
		else   //####   If Calcualtion Method is set to Percent   #########
		{
			shorttarget  = _ShortPrice[i] - (_ShortPrice[i]*(BT/100)) ;   //########### Take Profit Calculation ##########
			
			Shortsl = _ShortPrice[i] + (_ShortPrice[i]*(SL/100));     //########### StopLoss Calculation ##########
		}
		
		EntryBar=BI[i];
	}		 
	if(( ShortFlag==1 AND High[i]>Shortsl[i] AND BI[i]>EntryBar[i] AND  sambarexit[i])      OR ( ShortFlag==1 AND High[i]>Shortsl[i] AND   sambarexit[i]==0)  )        //############### Short Exit From Stoploss ###########
	{
		Cover[ i ] = 1;

		CoverPrice = Shortsl[i];
		
		ShortFlag = 0;  
	}
	else
	if(( ShortFlag==1 AND L[i] < shorttarget[i]  AND BI[i]>EntryBar[i] AND  sambarexit[i] )OR ( ShortFlag==1 AND L[i] < shorttarget[i]   AND  sambarexit[i]==0 ))                //############### Short Exit From Take Profit ###########
	{
		Cover[ i ] = 1; 
		
		coverPrice = shorttarget[i];
		
		ShortFlag = 0; 
	
	}
	else
	if((ShortFlag==1 AND Exittimecondition[i]   AND BI[i]>EntryBar[i] AND  sambarexit[i] ) OR (ShortFlag==1 AND Exittimecondition[i]   AND  sambarexit[i]==0))                //############### Short Exit From Intraday Timing Condition, If intraday mode is on ###########
	{

		Cover[ i ] = 1;

		COverPrice = Open[i];
		
		ShortFlag = 0;		

	}
 	else
	if((ShortFlag==1 AND _Cover[i]    AND BI[i]>EntryBar[i] AND  sambarexit[i] )    OR (ShortFlag==1 AND _Cover[i]    AND  sambarexit[i]==0))            //############### Short Exit From _Cover ###########
	{

		Cover[ i ] = 1;

		COverPrice = Open[i];
		
		ShortFlag = 0;		

	}

//#################### Storing All above Variable in new Array so we can use this value outside For Loop #############


bt[i] = buyTarget[i];
St[i] = ShortTarget[i];
bsl[i] = buysl[i];
ssl[i]=   shortsl[i];
bp[i] = _buyprice[i];
sp[i]=   _shortprice[i];
LF[i] = longflag[i];;
SF[i] =shortflag[i];

}



Buyflag = Flip(Buy,Sell);
Shortflag11 = Flip(Short,cover);


Plot(IIf(Buyflag,bt,Null),"Buy Take Profit",colorGreen,styleThick,Null,Null,0,0,2);
Plot(IIf(Shortflag11,st,Null),"Short Take Profit",colorGreen,styleThick,Null,Null,0,0,2);

Plot(IIf(Buyflag,bsl,Null),"Buy Stoploss",colorRed,styleThick,Null,Null,0,0,2);
Plot(IIf(Shortflag11,SSL,Null),"Short Stoploss",colorRed,styleThick,Null,Null,0,0,2);

Plot(IIf(Buyflag,BP,Null),"BuyPrice",colorWhite,styleThick,Null,Null,0,0,2);
Plot(IIf(Shortflag11,SP,Null),"ShortPrice",colorWhite,styleThick,Null,Null,0,0,2);

dist = 1.5*ATR(10); 

for( i = 0; i < BarCount; i++ ) 
{ 
if( Buy[i] ) PlotText( "Buy @ " + BP[ i ], i, L[ i ]-dist[i], colorGreen ); 
if( Sell[i] ) PlotText( "Sell @ " + C[ i ], i, H[ i ]+dist[i], colorRed ); 

if( Cover[i] ) PlotText( "Cover @ " + C[ i ], i, L[ i ]-dist[i], colorGreen ); 
if( Short[i] ) PlotText( "Short @ " + SP[ i ], i, H[ i ]+dist[i], colorRed ); 
} 


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( Sell , shapeDownArrow, shapeNone ), colorGreen , 0, H, Offset = -45 );

PlotShapes( IIf( Short, shapeSquare, shapeNone ), colorRed, 0, H, Offset = 40 );
PlotShapes( IIf( Short, shapeSquare, shapeNone ), colorOrange, 0, H, Offset = 50 );
PlotShapes( IIf( Short, shapeDownArrow, shapeNone ), colorWhite, 0, H, Offset = -45 );
PlotShapes( IIf( Cover , shapeUpArrow, shapeNone ), colorRed, 0, L, Offset = -45 );


_SECTION_END();


 //######## Backtest  Code ###########

 _SECTION_BEGIN("BackTest Setting");


Initial_Equity = Param("Initial Equity",100000,100,10000000,1);

Equity_Percent =  Param("Capital Allocation (Percent OF Equity)",80,0.05,100,0.05);

Max_Open_Position =  Param("Max Open Position",4);

holdminbars   =  Param("Max Open Position",1);

SetOption("initialEquity",Initial_Equity);

SetPositionSize(Equity_Percent,spsPercentOfEquity);

setOption("MaxOpenPositions",Max_Open_Position);

setOption("holdminbars",holdminbars);

SetTradeDelays( 0, 0, 0, 0 ); 

_SECTION_END();


//########################### Automation Code ///////////


 //######## Explorer  Code ###########

 _SECTION_BEGIN("Explorer");

Filter = (Buy OR Sell);
AddTextColumn(WriteIf(Buy,"Buy","Sell"),"Buy/Sell");

_SECTION_END();

 //######## IB automation  Code ###########

 _SECTION_BEGIN("IB Setting");

ibc = GetTradingInterface("IB");
EnableTextOutput(0);
printf( "\nibc " + ibc +"\n");

//availableFunds = ibc.GetAccountValue("AvailableFunds");    // Need to test  this function 

 
Auto_trading = ParamToggle("Auto Trading","Auto Trading Off|Auto Trading On",1);
Symbol = Name();
QTY = StrToNum(""+(round(Param("Max Amount For Each Symbol",1000,1,100000,1) /bp ) ));
// round(Param("Max Amount For Each Symbol",1000,1,100000,1) /bp ) ;

Dop = ValueWhen(newday,O);

_SECTION_END();

_SECTION_BEGIN("IB Execution");

tn = Now(format=4);

VarName = Name()+GetChartID()+""+Dop;

if(LastValue(tn) != Nz(StaticVarGet("IBBuyOTime"+VarName)))
	StaticVarSet("IBBuyO"+VarName,False);
	
if(LastValue(tn) != Nz(StaticVarGet("IBSellOTime"+VarName)))
	StaticVarSet("IBSellO"+VarName,False);
	
if(LastValue(tn) != Nz(StaticVarGet("IBShortOTime"+VarName)))
	StaticVarSet("IBShortO"+VarName,False);
	
if(LastValue(tn) != Nz(StaticVarGet("IBCoverOTime"+VarName)))
	StaticVarSet("IBCoverO"+VarName,False);	



if(LastValue(Sell) AND Nz(StaticVarGet("IBSellO"+VarName))==False) 
{
_TRACE("Buy Exit , " + Name());
ibc.PlaceOrder(Symbol, "SELL", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBSellO"+VarName,True);
StaticVarSet("IBSellOTime"+VarName,LastValue(tn));
}

if(LastValue(Cover) AND Nz(StaticVarGet("IBCoverO"+VarName))==False) 
{
_TRACE("Short Exit , " + Name());
ibc.PlaceOrder(Symbol, "BUY", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBCoverO"+VarName,True);
StaticVarSet("IBCoverOTime"+VarName,LastValue(tn));
}
if(LastValue(Buy) AND Nz(StaticVarGet("IBBuyO"+VarName))==False) 
{
_TRACE("Buy Entry , " + Name());

ibc.PlaceOrder(Symbol, "BUY", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBBuyO"+VarName,True);
StaticVarSet("IBBuyOTime"+VarName,LastValue(tn));
}

if(LastValue(Short) AND Nz(StaticVarGet("IBShortO"+VarName))==False) 
{
_TRACE("Short Entry , " + Name());
ibc.PlaceOrder(Symbol, "SELL", QTY, "MKT", 0, 0, "DAY", Auto_trading );
StaticVarSet("IBShortO"+VarName,True);
StaticVarSet("IBShortOTime"+VarName,LastValue(tn));
}

_SECTION_END();

sorry about that I have posted the amended code now

8002000a is OLE error code meaning Out of present range. This is an error when you pass a value too large for the destination data type. Most likely one of parameters that you pass to PlaceOrder is too large.

To get better understanding of what is happening in your code and how functions work, use advice given here: How do I debug my formula?