¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io
Date

Re: real-time level-i streaming for volume information - Am I getting all the volume

 

lists all tick types you can expect or request, Chris. Volume (#8) is a good overview of trade volume, but it only counts regular trades and does not include odd lots or any of a long list of "unreportable" trades.

You might find it helpful to also subscrive to "RT Volume" (#48) and "RT Trade Volume" (#77) as described in "RT Volume" includes "unreportable" trades while "RT Trade Volume" does not. Those two tick types return incremental volume numbers of recent trades.

´³¨¹°ù²µ±ð²Ô


Re: eroor 322 errorMsg "Error processing request.-'bW' : cause - Duplicate ticker id"

 

Well, somewhere in your program an API request is made with a duplicate requestId or tickerId. The error callback should give you the exact id at fault.

"reqId + counter" is a bad idea. You should have a function, such as nextRequestId(), that provides a new and unique Id every time the function is called. It is sufficient that the function simply returns the value of an incremented variable such as (pseudo language):

private integer _nextRestId = 10000000;
funtion integer nextRequestId()
{
??? return _nextRequestId++;
}


We found it helpful to start request Ids at a high number so that they cannot be confused with orderIds.? But "_nextRestId? = 1" will work just fine.

Now, every API request (not just reqMktData) gets a unique Id by a call to nextRequestId().

´³¨¹°ù²µ±ð²Ô


Re: eroor 322 errorMsg "Error processing request.-'bW' : cause - Duplicate ticker id"

 

On Thu, Jan 26, 2023 at 09:39 AM, Dmitry Shevkoplyas wrote:
multiple parallel for-each
sorry but i am not sure what you mean,?

I have??int counter = 1; outside the foreach loop

and I put a breakpoint at the end of foreach loop and ran it

I see in the debug each request of reqmktdata has a unique request id, unique strike and expire.

how? therefore is it possible that there is multiple foreach executions using the same variable?


Commodity Futures missing for Nickel/Zinc/Hogs/Propane etc.

 

Hello,

Can't find any commodity futures on Nickel/Zinc/Hogs/Propane etc.
Does IBKR not support any trading on these?

Thanks,
John


need help with stoploss of bracket order

 

Hello
?
We are trying to send a bracket order via API. We are encountering a problem with the stop loss part of the order. it doesn¡¯t seem to work properly and do not execute the stop order at the price we set.

We tried many different ways and objectives and all gave the same results ¨C no execution.

1.?What do we have to send in order to fix this problem? In order to execute the stop loss as intended.
2.?How does the stop loss order works? Is it triggered only by last trade price or can it be triggered by quotes as well? For example, we set the stop at 30. The price of the asset now is 20 bid ¨C 21 ask, last trade is still at 40. Should the stop order triggered? Or?wont triggered until last trade would be 30 or less?

?


Contract contract = new()

? ? ? ? ? ? {

? ? ? ? ? ? ? ? Symbol = closestContract.Symbol,

? ? ? ? ? ? ? ? SecType = closestContract.SecType,

? ? ? ? ? ? ? ? Exchange = closestContract.Exchange,

? ? ? ? ? ? ? ? Currency = closestContract.Currency,

? ? ? ? ? ? ? ? LastTradeDateOrContractMonth = closestContract.LastTradeDateOrContractMonth,

? ? ? ? ? ? ? ? LocalSymbol = closestContract.LocalSymbol,

? ? ? ? ? ? ? ? Strike = strike,

? ? ? ? ? ? ? ? Right = tickerType == Enumerators.Calls ? "C" : "P",

? ? ? ? ? ? ? ? Multiplier = closestContract.Multiplier,

? ? ? ? ? ? };

?

?

? ?{

? ? ? ? ? ? //TWS API

? ? ? ? ? ? //This will be our main or "parent" order

? ? ? ? ? ? Order parent = new Order();

? ? ? ? ? ? parent.OrderId = parentOrderId;

? ? ? ? ? ? parent.Action = action;

? ? ? ? ? ? parent.OrderType = "LMT";

? ? ? ? ? ? parent.TotalQuantity = quantity;

? ? ? ? ? ? parent.LmtPrice = limitPrice;

? ? ? ? ? ? parent.AuxPrice = stopLossPrice;

? ? ? ? ? ? parent.Tif = "GTC";

? ? ? ? ? ? //The parent and children orders will need this attribute set to false to prevent accidental executions.

? ? ? ? ? ? //The LAST CHILD will have it set to true,?

? ? ? ? ? ? parent.Transmit = false;

?

? ? ? ? ? ? Order takeProfit = new Order();

? ? ? ? ? ? takeProfit.OrderId = parent.OrderId + 1;

? ? ? ? ? ? takeProfit.Action = action.Equals("BUY") ? "SELL" : "BUY";

? ? ? ? ? ? takeProfit.OrderType = "LMT";

? ? ? ? ? ? takeProfit.TotalQuantity = quantity;

? ? ? ? ? ? takeProfit.LmtPrice = takeProfitLimitPrice;

? ? ? ? ? ? takeProfit.ParentId = parentOrderId;

? ? ? ? ? ? takeProfit.Transmit = false;

? ? ? ? ? ? takeProfit.Tif = "GTC";

?

? ? ? ? ? ? Order stopLoss = new Order();

? ? ? ? ? ? stopLoss.OrderId = parent.OrderId + 2;

? ? ? ? ? ? stopLoss.Action = action.Equals("BUY") ? "SELL" : "BUY";

? ? ? ? ? ? stopLoss.OrderType = "STP";?

? ? ? ? ? ? stopLoss.AuxPrice = stopLossPrice;

? ? ? ? ? ? stopLoss.TotalQuantity = quantity;

? ? ? ? ? ? stopLoss.ParentId = parentOrderId;?

? ? ? ? ? ? stopLoss.Transmit = true;

? ? ? ? ? ? stopLoss.Tif = "GTC";

?

? ? ? ? ? ? List<Order> bracketOrder = new List<Order>();

? ? ? ? ? ? bracketOrder.Add(parent);

? ? ? ? ? ? bracketOrder.Add(takeProfit);

? ? ? ? ? ? bracketOrder.Add(stopLoss);

? ? ? ? ? ? return bracketOrder;

? ? ? ? }

is there any issue with bracketorder ?


Re: eroor 322 errorMsg "Error processing request.-'bW' : cause - Duplicate ticker id"

 

Hi Liu,

The "counter" variable is initialized at a higher scope (not within the for-each loop).
This means that multiple parallel for-each executions are working against the same instance of that variable.
Depending on race conditions, this might lead to incorrect functioning of your logic.

Cheers,
Dmitry

On Thu, Jan 26, 2023 at 6:26 AM H Liu <liuhervey@...> wrote:
Hello

I am getting an duplicate ticker id error, however I already have a unique id for each request,

I have uploaded a screenshot of my snippet of code

when I comment out this code it works fine, I have tried commenting out contract.conid and using contract.tradingclass instead of contract.symbol but these did not solve the problem, the full message in debug shows?


? ? ? ? ? ? ? foreach (var strike in strikes)
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?foreach (var expire in expirations)
? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ?Contract contract = new Contract();

? ? ? ? ? ? ? ? ? ?contract.ConId = underlyingConId;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? contract.TradingClass = tradingClass;
? ? ? ? ? ? ? ? ? ? contract.Exchange = "SMART";
? ? ? ? ? ? ? ? ? ?contract.Currency = "USD";
? ? ? ? ? ? ? ? ? ?contract.SecType = "OPT";
? ? ? ? ? ? ? ? ? ?contract.Right = "CALL";
? ? ? ? ? ? ? ? ? ?contract.Multiplier = "100";

? ? ? ? ? ? ? ? ? ? contract.Strike = strike;
??
? ? ? ? ? ? ? ? ? ? ? ?contract.LastTradeDateOrContractMonth = expire;
? ? ? ? ? ? ? ? ? ? ? ?// Create a new TagValue List object (for API version 9.71)
? ? ? ? ? ? ? ? ? ? ? ?List<TagValue> mktDataOptions = new List<TagValue>();
? ? ? ? ? ? ? ? ? ?clientSocket.reqMarketDataType(3);
? ? ? ? ? ? ? ?clientSocket.reqMktData(reqId + counter, contract, "", false, false, mktDataOptions);?

? ? ? ? ? ? ? ? ? ? ? ?counter = counter + 1;
? ? ? ? ? ? ? ? ? ?}


eroor 322 errorMsg "Error processing request.-'bW' : cause - Duplicate ticker id"

 

Hello

I am getting an duplicate ticker id error, however I already have a unique id for each request,

I have uploaded a screenshot of my snippet of code

when I comment out this code it works fine, I have tried commenting out contract.conid and using contract.tradingclass instead of contract.symbol but these did not solve the problem, the full message in debug shows?


? ? ? ? ? ? ? foreach (var strike in strikes)
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?foreach (var expire in expirations)
? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ?Contract contract = new Contract();

? ? ? ? ? ? ? ? ? ?contract.ConId = underlyingConId;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? contract.TradingClass = tradingClass;
? ? ? ? ? ? ? ? ? ? contract.Exchange = "SMART";
? ? ? ? ? ? ? ? ? ?contract.Currency = "USD";
? ? ? ? ? ? ? ? ? ?contract.SecType = "OPT";
? ? ? ? ? ? ? ? ? ?contract.Right = "CALL";
? ? ? ? ? ? ? ? ? ?contract.Multiplier = "100";

? ? ? ? ? ? ? ? ? ? contract.Strike = strike;
??
? ? ? ? ? ? ? ? ? ? ? ?contract.LastTradeDateOrContractMonth = expire;
? ? ? ? ? ? ? ? ? ? ? ?// Create a new TagValue List object (for API version 9.71)
? ? ? ? ? ? ? ? ? ? ? ?List<TagValue> mktDataOptions = new List<TagValue>();
? ? ? ? ? ? ? ? ? ?clientSocket.reqMarketDataType(3);
? ? ? ? ? ? ? ?clientSocket.reqMktData(reqId + counter, contract, "", false, false, mktDataOptions);?

? ? ? ? ? ? ? ? ? ? ? ?counter = counter + 1;
? ? ? ? ? ? ? ? ? ?}


MGC order(s) not accepted by IB.

 

Hi All,

I don't remember this happening before, but MGC Comex Micro Gold just flipped from Feb to Apr.

I have a BUY (1) STPLMT ENTRY with a STP loss attached.
MGC 202304 Current price 1966.30
(1) BUY STPLMT Entry? Aux 1953.80 Lim 1953.80
(1) SELL STP Stop Aux 1930.10

IB? keeps saying " Text= Stop trigger price is too low" for the STPLMT Entry Order.

I'm about 13 points lower.? Is this realistic, or am I doing something wrong?

So I then raise the Trigger to 1960.00 and the Limit to 1950.00 and get
MsgType??? ExecutionReport
SendingTime??? 20230126-00:06:41
ClientOrderID??? 1003596985.0
ExecID??? 81374.1674691601.5
OrderReference??? LONG 1d MS 01-19-23 Entry
ExecType??? Canceled
ExecTransType??? Status
ExecRestatementReason??? 5
OrdStatus??? Canceled
Symbol??? MGC
TWSTickerExchange??? COMEX
OrderQty??? 1
AuxPrice??? 1960
LmtPrice??? 1950
StopPrice??? 1960
LastShares??? 0
LastPx??? 0.00
CumQty??? 0
LeavesQty??? 0
AvgPx??? 0
Side??? Buy
OrderID??? 00a6f69d.00013dde.63d0bd85.0001
Account??? U6645952
SecurityType??? FUT
MaturityMonthYear??? 202304
MaturityDate??? 20230426

??????????????????????
Text??? Limit Price should be better or equal to trigger price.
??????????????????????

TransactTime??? 20230126-00:06:41
OrderReceiptTime??? 20230126-00:06:41
BrokerExpireTime??? 20230630-22:00:00
OrderType??? StopLimit
TradingClass??? MGC
ServerId??? 224
DdeId??? 87066
TimeInForce??? GTC
ContractID??? 493857816
Currency??? USD
Exchange??? COMEX
IgnoreRth??? 1
OptionAcct??? c
6531??? 13/0/-2264651
WorkingIndicator??? N
OutsideRTH??? 1
TriggerMethod??? 7
IBLocalSymbol??? MGCJ3
ClrIntent??? IB
OrigOrderReceiptTime??? 20230126-00:06:41

What am I missing?

Thanks, as always,
Be Well,
Lou Dudka


IB order callback for cancelled order shows empty orderRef

 

Hi All,

I got some strange behavior while connecting to a simulated account. I'm writing code to make my app robust to crashing intra-day. I'm wondering if what I'm seeing is what I should expect, or possibly a bug in either the IBAPI or my code. I'm using the C++ API.

I placed a Market order through the client api and immediately cancelled it by calling reqGlobalCancel() function. (within 205 ms based on logs). The orderRef string in order was set to a structured string containing a UUID and some app specific info. The order in short was as follows:
- OrderType: MKT
- orderRef: [set to a string]
- Ticker: AMD
- Size: 100
- Side: SELL

It seems like the original order was filled completely , and cancellation was rejected, as observed in the audit trail that I got from a TWS connected to the same account.

When I disconnect, restart my app and called reqCompletedOrders(), instead of the order I had sent, I go the following order:
Ticker: AMD
OrderType: LMT
lmtPrice: 0
NOTE: Order sent was a market order.
Request ID: 0 [Not the request ID of the original order]
permId : same as original Order
orderRef: "" [Empty string received, not the string that had been set in the original order]

The orderState structure shows the state: Cancelled with CompletedStatus: FIlled Quantity 100.

Note also that when I got the callback for the fill for this order after disconnecting, restarting and reconnecting, the fill had the correct orderRef on it.

I was wondering if anyone had any explanation for why we are not getting a completed order callback with the correct orderRef and request id and why the price instruction changed from MKT to LMT?
I am attaching the audit Trail as a html file. Logs from TWS and the logs generated by my application are given below for your information.

Logs of callback received:

[2023-01-25 02:58:50.765] [info]?Completed order: IB_ORDER:?[orderId=0, clientId=0, permId=586137032, action=SELL, totalQuantity=0,?orderType=LMT, lmtPrice=0, auxPrice=0, tif=DAY, activeStartTime=, activeStopTime=, ocaGroup=, ocaType=3,?orderRef=,?transmit=1, parentId=0, blockOrder=0, sweepToFill=0, displaySize=2147483647, triggerMethod=-1, outsideRth=0, hidden=0, goodAfterTime=,

[2023-01-25 02:58:50.865] [info]?Execution Details: req_id: 522, Asset: AMD, Execution_details: IB Execution: [execId=0000e0d5.641f4ec2.01.01, time=20230125 02:19:38, acctNumber=DU810247, exchange=NYSE, side=SLD, shares=100, price=74.45, permId=586137032, clientId=0, orderId=518, liquidation=0, cumQty=100, avgPrice=74.45,?orderRef=714a5eeb-96b9-419f-8286-4f8dcc146563|base|USEQT:000000004266|4391||, evRule=, evMultiplier=0, modelCode=, lastLiquidity=2]
TWS Logs:

2023-01-25 02:19:38.234 [ES] INFO [AWT-EventQueue-0] - cdebug: TRADER | WARNING | Completed time is not set on order | id=586137032 mod=1 liq=false sym=AMD side=SELL qty=0 tif=DAY orderType=MKT lmtPrice=1.7976931348623157E308 stopPrice=1.7976931348623157E308 offsetAmt=0.01 originator=Socket orderRef=714a5eeb-96b9-419f-8286-4f8dcc146563|base|USEQT:000000004266|4391|| ruleGroup=[] state=jfix.FixOrderState$Filled acct=DU810247. faParams=null cum=100 conid=4391 exch=SMART compExch=AMEX best=NYSE goodTil=ExpireDateTime [null] secType=STK ddeId=518 avpx=74.45 cumFill=100 unallocatedQuantity=NaN preserveDeactivate=false state=jfix.FixOrderState$Filled chameleonParams=null adjustedAttribs=None 1.7976931348623157E308 1.7976931348623157E308 1.7976931348623157E308 1.7976931348623157E308 Attributes: AutoRouted=false BlockOrder=false PostToAts=2147483647 CrossQuantity=2147483647 OrderRef=714a5eeb-96b9-419f-8286-4f8dcc146563|base|USEQT:000000004266|4391|| MinCompeteSize=100 TwoSidedCrossOrderId=null Hidden=false VolatilityType=null ReferenceContractExchange=null RecentSubmitModifyTime=20230124-20:49:38 TriggerMethod=Default ReceiptTime=20230124-20:49:37 IsOrderInTransitionalState=false ContinuousUpdate=false NoDarkPools=false SweepToFill=false PeggedChangeAmount=1.7976931348623157E308 RoutingStrategyAttribute=null DarkPoolOnly=false DeltaNeutralAuxPrice=1.7976931348623157E308 AutoCancelParent=false FacilitationPct=2147483647 AdvancedErrorOverride=null ReferenceContractId=2147483647 BlotterPreConfiguredOrder=false OptionAcctAttrib=c SoftDollars= OptOutSmartRouting=false MinimumQuantity=2147483647 DeltaNeutralOrderType=None CompeteAgainstBestOffset=0.02 HasCoTradingMatchingSize=false Clearing=/IB StockRangeUpper=1.7976931348623157E308 ReferenceChangeAmount=1.7976931348623157E308 MarketCapPrice=1.7976931348623157E308 OrderCreationTime=20230124-20:49:37 TouchedTrigger=75.27 NotHeld=false StockRefPrice=1.7976931348623157E308 RelativeDiscretionary=false GuardRailsOrderTypeStatus=1 Delta=1.7976931348623157E308 AcceptLargeSize=false DisplaySize=2147483647 AllOrNone=false Volatility=1.7976931348623157E308 ReferencePriceType=null StartingPrice=1.7976931348623157E308 TrailingUnit=null StockRangeLower=1.7976931348623157E308 OutsideRth=false AlgoAttribts: null CompletedAttribs:
2023-01-25 02:19:38.247 [ES] INFO [JTS-CCPDispatcherS2-39] - Created JTS-ExecCommissionSave-247
2023-01-25 02:19:38.254 [ES] INFO [AWT-EventQueue-0] - EXEC Sorting now main model 406335480
2023-01-25 02:19:38.439 [ES] INFO [JTS-ChartOrderProcessor-35] - cdebug: TRADER | WARNING | Neither original order receipt time nor recent submit modify time attributes are set on order | id=586137032 mod=1 liq=false sym=AMD side=SELL qty=0 tif=DAY orderType=LMT lmtPrice=1.7976931348623157E308 stopPrice=1.7976931348623157E308 offsetAmt=0.01 originator=Socket orderRef=null ruleGroup=[] state=jfix.FixOrderState$CancelConfirmed acct=DU810247. faParams=null cum=0 conid=4391 exch=SMART compExch=AMEX best=null goodTil=ExpireDateTime [null] secType=STK ddeId=518 avpx=74.45 cumFill=0 unallocatedQuantity=NaN preserveDeactivate=false state=jfix.FixOrderState$CancelConfirmed chameleonParams=null adjustedAttribs=None 1.7976931348623157E308 1.7976931348623157E308 1.7976931348623157E308 1.7976931348623157E308 Attributes: AutoCancelDate=null HasCoTradingMatchingSize=false Clearing=null/null CompletedOrderStatus:FILLED OrderQtyInStatusAttrib=0 CompletedOrderTime=20230124-20:49:38 MarketCapPrice=1.7976931348623157E308 AlgoAttribts: null CompletedAttribs:
2023-01-25 02:19:38.443 [ES] INFO [AWT-EventQueue-0] - cdebug: TRADER | WARNING | Neither original order receipt time nor recent submit modify time attributes are set on order | id=586137032 mod=1 liq=false sym=AMD side=SELL qty=0 tif=DAY orderType=LMT lmtPrice=1.7976931348623157E308 stopPrice=1.7976931348623157E308 offsetAmt=0.01 originator=Socket orderRef=null ruleGroup=[] state=jfix.FixOrderState$CancelConfirmed acct=DU810247. faParams=null cum=0 conid=4391 exch=SMART compExch=AMEX best=null goodTil=ExpireDateTime [null] secType=STK ddeId=518 avpx=74.45 cumFill=0 unallocatedQuantity=NaN preserveDeactivate=false state=jfix.FixOrderState$CancelConfirmed chameleonParams=null adjustedAttribs=None 1.7976931348623157E308 1.7976931348623157E308 1.7976931348623157E308 1.7976931348623157E308 Attributes: AutoCancelDate=null HasCoTradingMatchingSize=false Clearing=null/null CompletedOrderStatus:FILLED OrderQtyInStatusAttrib=0 CompletedOrderTime=20230124-20:49:38 MarketCapPrice=1.7976931348623157E308 AlgoAttribts: null CompletedAttribs:
2023-01-25 02:19:38.752 [ES] INFO [AWT-EventQueue-0] - EXEC Sorting now main model 406335480
Has anyone seen this behaviour before? Is this expected?

Thanks for your help.


reqPnlSingle shows unset Pnls for closed position

 

Hi,

I have been using the TWS API (Python implementation) recently to create a custom trade report of my daily trades, and this has been working quite ok so far. Today however I am receiving some unexpected results with unset values for all PnLs (daily, unrealized, and realized).

This is what has been logged for the trades/pnl in question:

19:00:08:679:Thread-2:logAnswer:ANSWER pnlSingle {'reqId': 112, 'pos': Decimal('0'), 'dailyPnL': 1.7976931348623157e+308, 'unrealizedPnL': 1.7976931348623157e+308, 'realizedPnL': 1.7976931348623157e+308, 'value': 0.0}

For a closed position I would expect only the unrealizedPnL to be unset, and the dailyPnL and realizedPnL to be set. This has been the case so far from what I can tell.

Any idea why I am getting this result today? Is it because I created the report later than usual (6-7pm PST)?

Thank you!

?Simon


Re: MOO / MOC / Time Conditional Orders

 

1) For API, check??Scroll down, examples are given for MOO / LOO / MOC / LOC. For TWS, from an order entry window, the order type pull down offers MKT, LMT, MOC, LOC and other choices; the TIF pull down offers DAY, OPG (opening) and other choices.

2) In my opinion, Time in force (TIF) / order type is a bit inconsistent at IBKR.? For the open, you specify TIF - see above link MOO / LOO documentation. For the close, you specify order type, MOC / LOC.? For the close, I use TIF=Day (other TIFs may work).?

2a) "will the order show anywhere" - at least in aggregate, the order will appear for US destinations.? The opening and closing auction orders and imbalances are broadcast by both NYSE and NASDAQ, at least in aggregate. For details, see??and??. For NYSE and NASDAQ, there are cutoff times for the auction.? So, the NYSE and NASDAQ orders do not sit on IB servers, but are sent to the destinations before the time cutoffs. If you are referring to other order destinations, dig around their websites for details.


Re: MOO / MOC / Time Conditional Orders

 

Hello , as far as I know , time conditionned orders are only available for LMT orders


Le?mar. 24 janv. 2023 ¨¤?06:21, John <serorjb@...> a ¨¦crit?:
Hello,

Few questions on timed orders please:

  1. MOC/MOO orders () Market On Close,
    do not appear in TWS, no matter what underlier I select, the option is just not in the drop down menu?

  2. Assuming I use the API, and I successfully submit a time conditional order, either using?, or simply MOO/MOC,
    will the order show anywhere on the market or the order book? or will it sit hidden with the IB server until the time comes, and then be sent to the market?

Thanks,
Jonathan



--



MOO / MOC / Time Conditional Orders

 

Hello,

Few questions on timed orders please:

  1. MOC/MOO orders () Market On Close,
    do not appear in TWS, no matter what underlier I select, the option is just not in the drop down menu?

  2. Assuming I use the API, and I successfully submit a time conditional order, either using?, or simply MOO/MOC,
    will the order show anywhere on the market or the order book? or will it sit hidden with the IB server until the time comes, and then be sent to the market?

Thanks,
Jonathan


real-time level-i streaming for volume information - Am I getting all the volume

 

¿ªÔÆÌåÓý

Hi,

I have set-up streaming for level-i data (multiple symbols) by using the following construct :


....? ? m_pClient->reqMktData(j, ContractSamples::USStockAtSmart_NEW(i), "", false, false, TagValueListSPtr());? ? ?....

The data comes back ok and I am capturing volume data as follows :??

....? ? if (field == 8) {
????? my_ts_data.the_array[7][my_symbol_rev_map] = size * 100;? ? // from tickSize callback... (field and size are from callback argument list)
??? }
....

Are their other field and areas that contain volume that I may be missing? Thank you.

Best,
? Chris






Is it possible to create bracket order with hotkeys using TWS?

 

Hi,
can we create hotkeys to send bracket orders in TWS?
i found attach bracket orders in hotkeys but there is no customize tab.
Thanks


Re: Option stoploss order depending on underlying price

 

Hi,
I am not sure if I could fix it. Apparently with the following code, TWS is showing right TakeProfit(TRAIL order) and StopLoss (Price Condition) order. Shall check tomorrow when market opens and update. Thanks Dave and Bart for support.

Regards,
Souvik

# Adjustable bracket order. STP order adjusted to TRAIL
? ? def adjusted_trailing_stop_price_condition_order(self, underlying:Instrument, opt_instr:Instrument, direction: Direction,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity, isMore:bool, stopLossPrice,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? trailTriggerPrice, trailStopPrice, trailAmt):
? ? ? ? parent = Order()
? ? ? ? parent.orderId = IDGen.next_id()
? ? ? ? parent.action = "BUY" if direction is Direction.LONG else "SELL"
? ? ? ? parent.orderType = "MKT"
? ? ? ? parent.totalQuantity = quantity
? ? ? ? parent.eTradeOnly = ''
? ? ? ? parent.firmQuoteOnly = ''
? ? ? ? parent.transmit = False

? ? ? ? takeProfit = Order()
? ? ? ? takeProfit.orderId = IDGen.next_id()
? ? ? ? takeProfit.action = "SELL" if direction is Direction.LONG else "BUY"
? ? ? ? takeProfit.orderType = "TRAIL"
? ? ? ? takeProfit.totalQuantity = quantity
? ? ? ? takeProfit.triggerPrice = trailTriggerPrice
? ? ? ? #takeProfit.trailingPercent = 0
? ? ? ? takeProfit.auxPrice = trailAmt
? ? ? ? takeProfit.trailStopPrice = trailStopPrice
? ? ? ? takeProfit.parentId = parent.orderId
? ? ? ? takeProfit.eTradeOnly = ''
? ? ? ? takeProfit.firmQuoteOnly = ''
? ? ? ? takeProfit.transmit = False

? ? ? ? stopLoss = Order()
? ? ? ? stopLoss.orderId = IDGen.next_id()
? ? ? ? stopLoss.action = "SELL" if direction is Direction.LONG else "BUY"
? ? ? ? stopLoss.orderType = "MKT"
? ? ? ? stopLoss.conditions.append(
? ? ? ? ? ? self.price_condition(PriceCondition.TriggerMethodEnum.Default,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? underlying.contract_id,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? switcher_ib_exchange.get(underlying.exchange),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLossPrice, #Underlying price e.g. 42300
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? isMore, # If its more than 42300
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? False))
? ? ? ? stopLoss.totalQuantity = quantity
? ? ? ? stopLoss.parentId = parent.orderId
? ? ? ? stopLoss.eTradeOnly = ''
? ? ? ? stopLoss.firmQuoteOnly = ''
? ? ? ? stopLoss.transmit = True

? ? ? ? bracketOrder = [parent, takeProfit, stopLoss]

? ? ? ? contract = Contract()
? ? ? ? contract.localSymbol = opt_instr.symbol ?#local symbol signifies all right, strike and expiry. #TBD as of now keeping the symbol similar to IBKR
? ? ? ? contract.secType = switcher_ib_instr_type.get(opt_instr.type)
? ? ? ? contract.currency = switcher_ib_currency.get(opt_instr.currency)
? ? ? ? contract.exchange = switcher_ib_exchange.get(opt_instr.exchange)

? ? ? ? for o in bracketOrder:
? ? ? ? ? ? ? ? ? ? ? ? self.ibkr_app.placeOrder(o.orderId, contract, o)


Re: Option stoploss order depending on underlying price

 

Dave,
That was really a great help. I did look at the price condition and seems a good fit for the purpose. I could code and test the price conditioned stop loss order. It worked like a charm. But couldnt test the trailing adjusted profit order since the market got closed :(

Configuration as follow -
- Parent order is MKT
- Stop loss order is also MKT with pricecondition of underlying? (Checked and this works great)
- Above stop loss order is adjusted to be TRAIL on arriving at a trailing price of the strike? (This I couldnt test)

Need guidance on the TRAIL part to suggest if this works.
Thanks in advance.

Regards,
Souvik
? ? def price_condition(self,triggerMethod:int, contractId:int, exchange:str, price:float,
? ? ? ? ? ? ? ? ? ? ? ? isMore:bool, isConjunction:bool):
? ?
? ? ? ? #! [price_condition]
? ? ? ? #Conditions have to be created via the OrderCondition.create
? ? ? ? priceCondition = order_condition.Create(OrderCondition.Price)
? ? ? ? #When this contract...
? ? ? ? priceCondition.conId = contractId
? ? ? ? #traded on this exchange
? ? ? ? priceCondition.exchange = exchange
? ? ? ? #has a price above/below
? ? ? ? priceCondition.isMore = isMore
? ? ? ? priceCondition.triggerMethod = triggerMethod
? ? ? ? #this quantity
? ? ? ? priceCondition.price = price
? ? ? ? #AND | OR next condition (will be ignored if no more conditions are added)
? ? ? ? priceCondition.isConjunctionConnection = isConjunction
? ? ? ? #! [price_condition]
? ? ? ? return priceCondition


?# Adjustable bracket order. STP order adjusted to TRAIL
? ? def adjusted_trailing_stop_price_condition_order(self, underlying:Instrument, opt_instr:Instrument, direction: Direction,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity, isMore:bool, stopLossPrice,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? trailTriggerPrice, trailStopPrice, trailAmt):
? ? ? ? parent = Order()
? ? ? ? parent.orderId = IDGen.next_id()
? ? ? ? parent.action = "BUY" if direction is Direction.LONG else "SELL"
? ? ? ? parent.orderType = "MKT"
? ? ? ? parent.totalQuantity = quantity
? ? ? ? parent.eTradeOnly = ''
? ? ? ? parent.firmQuoteOnly = ''
? ? ? ? parent.transmit = False

? ? ? ? #Attached order is a conventional MKT order
? ? ? ? stopLoss = Order()
? ? ? ? stopLoss.orderId = IDGen.next_id()
? ? ? ? stopLoss.action = "SELL" if direction is Direction.LONG else "BUY"
? ? ? ? stopLoss.orderType = "MKT"
? ? ? ? stopLoss.conditions.append(
? ? ? ? ? ? self.price_condition(PriceCondition.TriggerMethodEnum.Default,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? underlying.contract_id,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? switcher_ib_exchange.get(underlying.exchange),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLossPrice, #Underlying price e.g. 42300
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? isMore, ?# If its more than 42300
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? False))

? ? ? ? #Additional Fields for adjusted order
? ? ? ?
? ? ? ? #When trigger price is penetrated
? ? ? ? stopLoss.triggerPrice = trailTriggerPrice ?# e.g. 365
? ? ? ? #The STP order will be turned into a TRAIL order
? ? ? ? stopLoss.adjustedOrderType = "TRAIL"
? ? ? ? #With a stop price of...
? ? ? ? stopLoss.adjustedStopPrice = trailStopPrice # e.g. 360
? ? ? ? #trailing by and amount (0) or a percent (1)...
? ? ? ? stopLoss.adjustableTrailingUnit = 0
? ? ? ? #of...
? ? ? ? stopLoss.adjustedTrailingAmount = trailAmt # e.g. 5
? ? ? ? stopLoss.totalQuantity = quantity
? ? ? ?
? ? ? ? stopLoss.parentId = parent.orderId
? ? ? ? stopLoss.eTradeOnly = ''
? ? ? ? stopLoss.firmQuoteOnly = ''
? ? ? ? stopLoss.transmit = True

? ? ? ? bracketOrder = [parent, stopLoss]

? ? ? ? contract = Contract()
? ? ? ? contract.localSymbol = opt_instr.symbol ?#local symbol signifies all right, strike and expiry. #TBD as of now keeping the symbol similar to IBKR
? ? ? ? contract.secType = switcher_ib_instr_type.get(opt_instr.type)
? ? ? ? contract.currency = switcher_ib_currency.get(opt_instr.currency)
? ? ? ? contract.exchange = switcher_ib_exchange.get(opt_instr.exchange)

? ? ? ? for o in bracketOrder:
? ? ? ? ? ? self.ibkr_app.placeOrder(o.orderId, contract, o)


Re: Option stoploss order depending on underlying price

 

Bart,
I cant agree more since the options highly fluctuate due to greeks.
However, the strategy I am building is for scalping and and am looking at keeping the position at very short time frame. Short profit and short stoploss. Will revisit the strategy once again after I deploy on paper account. Thanks for the suggestion.

Regards,
Souvik


Re: Option stoploss order depending on underlying price

 

¿ªÔÆÌåÓý

Though I haven¡¯t used it for your specific application, I would be looking at Price Conditioning:

?

Price conditioning allows conditioning of an order on the price of any (unrelated) contract by using the PriceCondition.conId parameter.? You would create an order for (say) a market sell of the option, with an attached price condition object watching the price of the underlying.? When the underlying breaks the specified price, the order will become active.

?

Dave

?

?

From: [email protected] <[email protected]> On Behalf Of Bart D
Sent: Thursday, 19 January 2023 10:28 AM
To: [email protected]; souvik.trader via groups.io <souvik.trader@...>
Subject: Re: [TWS API] Option stoploss order depending on underlying price

?

I believe if you do a bracket order then all is based on pricing of the contract that you buy, ie. the option, and that you can't have some order components based on the price of the contract and others based on the price of the underlying contract.

However I don't see the rationale for placing a stoploss based on the price of the underlying: for the same underlying price, the option price will highly fluctuate based on DTE and IV. Seems more logical to base it on option price itself which directly sets your loss.

On Jan 18, 2023 at 4:33 AM -0800, souvik.trader via groups.io <souvik.trader@...>, wrote:

Hi,
I am developing an option buying strategy and right now, I am monitoring the underlying to get a signal for long(Call buy) or short(Put buy)
Upon signal, the strategy picks the ATM strike and place a MKT order with adjusted trailing stop order. Present code is pasted below.
With this, more or less I am keeping a fixed stoploss whereas profit is indefinite.

Now, I will require to change the logic such that,
The stoploss will be dependent on a particular price of underlying and not price of option. Say for example:

At 9:30 AM
Underlying price: 42300
ATM Call strike 42300 price : 340
I need to place a market order for 42300 Call strike and at the same time place a stop loss order if underlying touches 42100
The complexity here is that the stoploss is monitored for underlying contract whereas the stoploss order itself is for Option contract.

Are there any such combo order possible ? If not, then I will have to place the stoploss order separately by monitoring the underlying price
Requesting experts advice.

Cheers,
Souvik

?

# Adjustable bracket order. STP order adjusted to TRAIL

?

? ? def adjusted_trailing_stop_order(self,

instr:Instrument,

direction: Direction,

?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity,

stopLossPrice,

?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? trailTriggerPrice,

trailStopPrice,

trailAmt):

?

? ? ? ? parent = Order()

?

? ? ? ? parent.orderId = IDGen.next_id()

?

? ? ? ? parent.action = "BUY"

if direction is Direction.LONG

else "SELL"

?

? ? ? ? parent.orderType = "MKT"

# Let say market price is. 340

?

? ? ? ? parent.totalQuantity = quantity

?

? ? ? ? parent.eTradeOnly = ''

?

? ? ? ? parent.firmQuoteOnly = ''

?

? ? ? ? parent.transmit = False

?



? ? ? ? #Attached order is a conventional STP order

?

? ? ? ? stopLoss = Order()

?

? ? ? ? stopLoss.orderId = IDGen.next_id()

?

? ? ? ? stopLoss.action = "SELL"

if direction is Direction.LONG

else "BUY"

?

? ? ? ? stopLoss.orderType = "STP"

?

? ? ? ? stopLoss.auxPrice = stopLossPrice ?# e.g. 320

?

? ? ? ? print("=========>STP stopLossPrice:{}".format(stopLossPrice))

?

? ? ? ? stopLoss.totalQuantity = quantity

?

? ? ? ?

?

? ? ? ? #Additional Fields for adjusted order

?

? ? ? ?

?

? ? ? ? #When trigger price is penetrated

?

? ? ? ? stopLoss.triggerPrice = trailTriggerPrice ?# e.g. 365

?

? ? ? ? #The STP order will be turned into a TRAIL order

?

? ? ? ? stopLoss.adjustedOrderType = "TRAIL"

?

? ? ? ? #With a stop price of...

?

? ? ? ? stopLoss.adjustedStopPrice = trailStopPrice

# e.g. 360

?

? ? ? ? #trailing by and amount (0) or a percent (1)...

?

? ? ? ? stopLoss.adjustableTrailingUnit = 0

?

? ? ? ? #of...

?

? ? ? ? stopLoss.adjustedTrailingAmount = trailAmt

# e.g. 5

?

? ? ? ?

?

? ? ? ? stopLoss.parentId = parent.orderId

?

? ? ? ? stopLoss.eTradeOnly = ''

?

? ? ? ? stopLoss.firmQuoteOnly = ''

?

? ? ? ? stopLoss.transmit = True

?



? ? ? ? bracketOrder = [parent, stopLoss]

?



? ? ? ? contract = Contract()

?

? ? ? ? contract.localSymbol = instr.symbol ?#local symbol signifies all right, strike and expiry

?

? ? ? ? contract.secType = switcher_ib_instr_type.get(instr.type)

?

? ? ? ? contract.currency = switcher_ib_currency.get(instr.currency)

?

? ? ? ? contract.exchange = switcher_ib_exchange.get(instr.exchange)

?



? ? ? ? print("=========>ParentOrderId:{}, action:{},

quantity:{}, stopLossPrice:{}".format(

?

? ? ? ? ? ? parent.orderId, direction, quantity, stopLossPrice))

?



? ? ? ? for o

in bracketOrder:

?

? ? ? ? ? ? self.ibkr_app.placeOrder(o.orderId, contract, o)

?


Re: Option stoploss order depending on underlying price

 

¿ªÔÆÌåÓý

Though I haven¡¯t used it for your specific application, I would be looking at Price Conditioning:

?

Price conditioning allows conditioning of an order on the price of any (unrelated) contract by using the PriceCondition.conId parameter.? You would create an order for (say) a market sell of the option, with an attached price condition object watching the price of the underlying.? When the underlying breaks the specified price, the order will become active.

?

Dave

?

?

From: [email protected] <[email protected]> On Behalf Of Bart D
Sent: Thursday, 19 January 2023 10:28 AM
To: [email protected]; souvik.trader via groups.io <souvik.trader@...>
Subject: Re: [TWS API] Option stoploss order depending on underlying price

?

I believe if you do a bracket order then all is based on pricing of the contract that you buy, ie. the option, and that you can't have some order components based on the price of the contract and others based on the price of the underlying contract.

However I don't see the rationale for placing a stoploss based on the price of the underlying: for the same underlying price, the option price will highly fluctuate based on DTE and IV. Seems more logical to base it on option price itself which directly sets your loss.

On Jan 18, 2023 at 4:33 AM -0800, souvik.trader via groups.io <souvik.trader@...>, wrote:

Hi,
I am developing an option buying strategy and right now, I am monitoring the underlying to get a signal for long(Call buy) or short(Put buy)
Upon signal, the strategy picks the ATM strike and place a MKT order with adjusted trailing stop order. Present code is pasted below.
With this, more or less I am keeping a fixed stoploss whereas profit is indefinite.

Now, I will require to change the logic such that,
The stoploss will be dependent on a particular price of underlying and not price of option. Say for example:

At 9:30 AM
Underlying price: 42300
ATM Call strike 42300 price : 340
I need to place a market order for 42300 Call strike and at the same time place a stop loss order if underlying touches 42100
The complexity here is that the stoploss is monitored for underlying contract whereas the stoploss order itself is for Option contract.

Are there any such combo order possible ? If not, then I will have to place the stoploss order separately by monitoring the underlying price
Requesting experts advice.

Cheers,
Souvik

?

# Adjustable bracket order. STP order adjusted to TRAIL

?

? ? def adjusted_trailing_stop_order(self,

instr:Instrument,

direction: Direction,

?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity,

stopLossPrice,

?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? trailTriggerPrice,

trailStopPrice,

trailAmt):

?

? ? ? ? parent = Order()

?

? ? ? ? parent.orderId = IDGen.next_id()

?

? ? ? ? parent.action = "BUY"

if direction is Direction.LONG

else "SELL"

?

? ? ? ? parent.orderType = "MKT"

# Let say market price is. 340

?

? ? ? ? parent.totalQuantity = quantity

?

? ? ? ? parent.eTradeOnly = ''

?

? ? ? ? parent.firmQuoteOnly = ''

?

? ? ? ? parent.transmit = False

?



? ? ? ? #Attached order is a conventional STP order

?

? ? ? ? stopLoss = Order()

?

? ? ? ? stopLoss.orderId = IDGen.next_id()

?

? ? ? ? stopLoss.action = "SELL"

if direction is Direction.LONG

else "BUY"

?

? ? ? ? stopLoss.orderType = "STP"

?

? ? ? ? stopLoss.auxPrice = stopLossPrice ?# e.g. 320

?

? ? ? ? print("=========>STP stopLossPrice:{}".format(stopLossPrice))

?

? ? ? ? stopLoss.totalQuantity = quantity

?

? ? ? ?

?

? ? ? ? #Additional Fields for adjusted order

?

? ? ? ?

?

? ? ? ? #When trigger price is penetrated

?

? ? ? ? stopLoss.triggerPrice = trailTriggerPrice ?# e.g. 365

?

? ? ? ? #The STP order will be turned into a TRAIL order

?

? ? ? ? stopLoss.adjustedOrderType = "TRAIL"

?

? ? ? ? #With a stop price of...

?

? ? ? ? stopLoss.adjustedStopPrice = trailStopPrice

# e.g. 360

?

? ? ? ? #trailing by and amount (0) or a percent (1)...

?

? ? ? ? stopLoss.adjustableTrailingUnit = 0

?

? ? ? ? #of...

?

? ? ? ? stopLoss.adjustedTrailingAmount = trailAmt

# e.g. 5

?

? ? ? ?

?

? ? ? ? stopLoss.parentId = parent.orderId

?

? ? ? ? stopLoss.eTradeOnly = ''

?

? ? ? ? stopLoss.firmQuoteOnly = ''

?

? ? ? ? stopLoss.transmit = True

?



? ? ? ? bracketOrder = [parent, stopLoss]

?



? ? ? ? contract = Contract()

?

? ? ? ? contract.localSymbol = instr.symbol ?#local symbol signifies all right, strike and expiry

?

? ? ? ? contract.secType = switcher_ib_instr_type.get(instr.type)

?

? ? ? ? contract.currency = switcher_ib_currency.get(instr.currency)

?

? ? ? ? contract.exchange = switcher_ib_exchange.get(instr.exchange)

?



? ? ? ? print("=========>ParentOrderId:{}, action:{},

quantity:{}, stopLossPrice:{}".format(

?

? ? ? ? ? ? parent.orderId, direction, quantity, stopLossPrice))

?



? ? ? ? for o

in bracketOrder:

?

? ? ? ? ? ? self.ibkr_app.placeOrder(o.orderId, contract, o)

?