AFL code for N-Bar and Trailing stop order placement in Interactive Brokers

Hi,
I have to place the following orders in my IB TWS:


StopLoss=Param("StopLoss",1.0,1,5,0.5);
ProfitTarget=Param("ProfitTarget",2.5,1,30,0.5);
TrailingStop=Param("TrailingStop",1.5,0.5,15,0.5);
NBarStop=Param("NBarStop",10,5,100,1);

ApplyStop(stopTypeLoss,stopModePercent,Stoploss);
ApplyStop(stopTypeProfit,stopModePercent,ProfitTarget);
ApplyStop(stopTypeTrailing,stopModePercent,TrailingStop);
ApplyStop(stopTypeNBar,stopModeBars,NBarStop);

I have looked at: IBController 1.3.8 READ ME but I do not see anything for N-Bar stop, yes there is one example for bracket order, but my strategy needs all four, and the first three-stop orders are in "Percent" of buy/sell price (how do I do that as well?).

Kindly let me know how to proceed to have an AFL code for the automatic placement of these four stop orders.

Thanks and regards

Hi @Ghanshyam_Singh,
ApplyStop is AFL code to simulate stops, not to execute them. That is, it doesn't magically send orders to IBKR.
First use Equity(1) (possibly with other arguments) to update buy/sell/short/cover arrays according to your ApplyStop() instructions. stopTypeNBar stops are not special. Second write code to send orders to TWS via IBController. This code should execute if and only if Buy/Sell/Short/Cover is true. For more details search this forum & the knowledge base e.g:

Really everything you need is here in this forum, in the kb or in the manual.
Cheers.

PS: please use code button to include AFL code.
code button amibroker forum 2

2 Likes

It has been said thousands of times, that ApplyStop is intended to simulate broker-provided orders during backtesting. For trading you just USE broker-provided order types. Once correct orders are placed are executed by the BROKER, not by the program. You place those exit orders when you enter the trade. For example for trailing stop in IB use "TRAIL" order type. For profit target you use "LMT" order. For stop loss you use "STP" order. For N-bar stop you use GAT (good after time).

Placing bracket orders with examples is given in the docs
http://www.amibroker.com/at/

2 Likes

Thanks a lot for your suggestion about GAT, yes, I am aware that ApplyStop is only for simulation within AB and not for placing the actual order in IB.

Best regards

Thank you, I will explore the links you have shared.....

Best regards

I tried using GAT for N-Bar stop, since it needs time in a specific format, do we have a way to convert N-Bar to the time format? Because there is a possibility that trade might continue for a couple of days and if there are holidays/weekends in between, that also must be accounted for.

Thanks and best regards

It is all in the manual
http://www.amibroker.com/f?DateTime

http://www.amibroker.com/f?DateTimeAdd

1 Like