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 #############################
_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();