Real time trades aren't executing as in backtest

When using IBcontroller on real time data I was expecting on my algo when the stochs closed below a certain level and the other conditions where met a buy order would be executed. However, since the stochs move while price is fluctuating everytime that the stochs hit below the assigned level before the bar finishes closing a buy signal is sent causing inaccurate orders and multiple orders per bar. Heres the code:

Buy = MovingAvg>MovingAvgPrev AND k2<Lowest_stochs AND ATR(atrlen)<maxatr AND MA_filter> Ref(MA_filter, -1) AND O>C;
Sell = MovingAvg<MovingAvgPrev;



Buy = ExRem(Buy, Sell OR stop OR tp);
Sell = ExRem(Sell, Buy);

//Plot(MovingAvg, "MA", ColorChange, styleLine|styleThick);
PlotShapes( Buy * shapeUpArrow + Sell * shapeDownArrow, IIf( Buy, colorGreen, colorRed ) ); 
Plot(k2, "MA", colorWhite, styleLine|styleThick);

//for trading

if( LastValue( Buy ) )
{
  ibc = GetTradingInterface("IB");

  // check if we are connected OK
  if( ibc.IsConnected() )
  {
     // check if we do not have already open position on this stock
     if( ibc.GetPositionSize( "ESH1-GLOBEX-FUT" ) == 0 )
     {
        // transmit order
        ibc.PlaceOrder("ESH1-GLOBEX-FUT", "BUY", 1, "MKT", 0, 0, "GTC", True );

     }
  }
}



if( LastValue( stop OR tp OR Sell ) )
{
  ibc = GetTradingInterface("IB");

  // check if we are connected OK
  if( ibc.IsConnected() )
  {
     // check if we do not have already open position on this stock
     if( ibc.GetPositionSize( "ESH1-GLOBEX-FUT" ) >0 )
     {
        // transmit order
        ibc.PlaceOrder("ESH1-GLOBEX-FUT", "SELL", 1, "MKT", 0, 0, "GTC", True );

     }
  }
}

I thought doing somthing like Ref(k1, -1)<Lowest_stochs would work but it didnt and changed the algo. Also whenever a buy/sell signal gets sent multiple orders sometime get filled. I dont know why this is as I told it to only execute a trade if the current position size is 0 or if its a sell/tp/sl only execute if position size greater than 0. The only thing I could think of is maby because the execution speed is so fast so is there a way to have it wait one secound after the order is sent?

Thanks.

People on the TWS API forum (https://groups.io/g/twsapi) have been saying that they avoid use of positionSize because it's not updated fast enough to keep up with their code. Instead, they recommend using execInfo to check the order status. If there is an order, you should not send another one.

Of course, you will have to know the orderID of the order that you submitted, so you will have to set a persistent static variable to store the orderID after you submit an order.

You will also have to clear that static variable when you exit the position, so that you aren't checking the status of an old order that is no longer relevant.

Al Venosa and Herman van den Bergen wrote some terrific articles on the AB Knowledge Base, and you should read them also. They cover this topic in much more detail.

Additionally, you could be sending a stop loss order along with your entry order. You would want to store that orderID also, so that you can modify it on subsequent orders, e.g. to tighten the stop.

I hope this helps.

1 Like

Hi @flip, this post was helpful for me: Generic code snippet to trade with IB

Thank you both @Pinecone @PeterD for the helpful content It will truely help me. However, I feel as if my main question goes unanswered on how to I make it so buy signals are sent only at bar close?

Thanks.

Look at the link I posted. AMI needs to know that you sent an order. Currently the // for trading section does not do any checks to see that a order has been sent, whether it's been filled, etc. So it continually sends orders.

Another issue may be that you are not sufficiently using Ref().
Try putting your Buy/Sell signals within a Ref(...,-1);

This:

Buy = MovingAvg>MovingAvgPrev AND k2<Lowest_stochs AND ATR(atrlen)<maxatr AND MA_filter> Ref(MA_filter, -1) AND O>C; 

plots the signals correctly however when I do somthing like this where I reference the last array:

Buy = MovingAvg>MovingAvgPrev AND Ref(k2, -1)<Lowest_stochs AND ATR(atrlen)<maxatr AND MA_filter> Ref(MA_filter, -1) AND O>C;

barley anything gets plotted and it completely changes the algo I do not know why this is

Try

Buy = Ref(MovingAvg>MovingAvgPrev AND k2<Lowest_stochs AND ATR(atrlen)<maxatr AND MA_filter> Ref(MA_filter, -1) AND O>C,-1);
Sell = Ref(MovingAvg<MovingAvgPrev,-1);

But again, you will need to deal with your actual execution code.

For example this is with the ref:
with
This is without:
without without

Sorry I meant vice versa the first one is without and the second one is with the ref. I really do appreciate you trying to help me @Pinecone. So I just tried the code you sent me and I believe the signals do plot properly now however the backtest results are completely different and I think this is because on the backtest results it is a one bar delayed entry with the Ref however on the live autotrade version it will be the same as the other. does that sound accurate @Pinecone @Tomasz?

are you lagging your entries during backtest as well? (if so your entires will now be 2 bars lagged instead of one). Analysis Settings>Trades Settings>Bar Delay should now be 0 since you are now handling the delay in this script.

Use the open price as your entry price.

BuyPrice=O;
SellPrice=O;

Lastly, if it still looks bad, you likely had look ahead bias before. Your system will need to be reassessed/optimized or trashed.

Also, be aware that you have transmit set to true in the IB code. This will fire and send a trade to IB even during a backtest. Change transmit to False for now, or better yet get rid of the entire IB code section, it's got it's own issues.

Perfect thank you it works now although the results are slightly different. For SellPrice = O; will that also apply for ApplyStop(); functions or no?

Depends on how you have your applystop set up, look into SetOption("ActivateStopsImmediately", True); and ApplyStop();

@Pinecone Is there a way to reference the apply stops for IB for example:

if( LastValue( tp OR stop ) )
{
  ibc = GetTradingInterface("IB");

  // check if we are connected OK
  if( ibc.IsConnected() )
  {
     // check if we do not have already open position on this stock
     if( ibc.GetPositionSize( "ESH1-GLOBEX-FUT" ) >0 )
     {
        // transmit order
        ibc.PlaceOrder("ESH1-GLOBEX-FUT", "SELL", 1, "MKT", 0, 0, "GTC", True );

     }
  }
}

and say the apply stop = tp = ApplyStop(stopTypeProfit,stopModePoint, ATR(14)*mult);
If I reference it for the IB as if( LastValue( tp OR stop ) ) it doesn't work so it there a way to reference it or do you have to do something like:

exit = C >= Ref(LastValue(Buy)+ATR(14), -1) OR C <= Ref(LastValue(Buy)-ATR(14), -1)<=C;

For it to work with IB?

Thanks

@Pinecone I thought this would be better adressed in a new topic as I think it could be a popular question so I opened a new topic feel free to respound to it there

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.