Re: TWS: Your connection was lost. Would you like to re-login? Re-login Exit Application
Did you manage to solve this? I have the same problem. Even if I close TWS and do the login every day sometimes at night the Re-Login window pops up and my trading systems stop until I wake up and I click re-login. Extremely tired of this improvvise behaviour as I am losing money and opportunities.
|
How to print / return size of position for a given contract
I am trying to print the quantity of a stock (or other financial asset) held. I have defined a stock contract under nextValidId and have defined position as follows:
def nextValidId(self, orderId: int):
super().nextValidId(orderId)
self.nextorderId = orderId
print('The next valid order id is: ', self.nextorderId)
self.stock_contract = Contract()
self.stock_contract.symbol = "APPL"
self.stock_contract.secType = "STK"
self.stock_contract.exchange = "SMART"
self.stock_contract.currency = "USD"
app.reqMktData(508, self.stock_contract, "", False, False, [])
app.reqPositions()
def position(self, account, contract, position, avgCost):
super().position(account, contract, position, avgCost)
print(contract, position)
if contract == 'stock_contract':
self.quantity_held = position
if contract == app.stock_contract:
self.quantity_held = position
I then request positions and try to print the result as follows:
app.reqPositions()
print("Apple held: " + str(app.quantity_held))
app.reqPositions() prints the contract and position, but I want to get the quantity held as part of my string statement. I am getting "Apple held: 0" but this is wrong.
|
Re: checking and reconnnecting python script after tws shutdown (or auto-restart)
I don't use python, but if I get a disconnect (isConnected = false, or any of the other connection error codes) I execute a "disconnection" method, a 1 minute pause, and then a full "reconnection" method.?
|
Re: reqPositions avgCost prices muliplier?
I did not see your post until I hit send on mine, Glenn.
"Position" is a generic concept that needs to work across a wide range of different instruments and, therefore, needs to be independent of instrument specifics. Internally, the two values that completely describe the financial aspects of a position (independent of instrument type) are the number of units in the position and the average cost for each unit. Those are the two values that IBKR tracks and reports to your client via reqPositions. For some instruments (such as stocks) "cost per unit" is identical to "price quotation per unit" but for others (such as futures contracts) it is not. But those differences are irrelevant for the concept of "position" and are better handled with the instrument specific multiplier (along with other specifics such as MinSize and MinTick) within the instruments' contract objects.
The portfolio window in TWS is designed to provide meaningful information for human traders. So they display an "average price" (that should probably be called the? "average quotation price"). For all instruments TWS determines the "average price" by dividing "average cost" by the multiplier for the instrument. The TWS window also shows other information the human trader wants to see such as the "last [quotation] price", the resulting "market value" and the P&L. But those were TWS GUI design decisions that are independent from the internal concept of "Position" and derived from several internally tracked values.
I just made an ESH2 trade to make sure that is correct:
- The unit is specified as "$50 x S&P 500 Index". so that is the "cost" or "value" for one contract
- The ES contract price quotation is "U.S. dollars and cents per index point"
- The price quotation for the trade was $4,566 plus a commission of $2.10. Therefore, the cost for that trade was 50 * $4,566 + $2.10 = $228,302.10
- That is what reqPositions correctly reports as the average cost of the position (since I have only that one contract in the position)
- For the convenience of human traders, TWS shows the "average [quotation] price" for the position as $4,566.05 which is $228,302.10 / 50 = $4,566.042 rounded up to two decimal places.
If your trading logic makes decision based on the human centric instrument specific "price quotation" (and as I said before that is perfectly fine) you simply perform the same division TWS does to get the "average price quotation" from the "average cost" for the position.
Alternatively, you could multiply incoming "price quotations" by the instrument specific multiplier and make decision based on "cost" and "value" with the advantage that more of your code would be independent of those human centric concepts of "price quotation".
´³¨¹°ù²µ±ð²Ô
toggle quoted message
Show quoted text
On Thu, Jan 20, 2022 at 10:53 AM, Glenn wrote:
While I understand (and agree) that "positions" are potentially the result of a series of trades, there is a discrepancy between what IB shows as price for the position and what it reports through reqPositions. For futures contract, it reports dollar values instead of price. I believe it reports 'Market Value' (as shown on TWS) divided by number of contracts instead of the Average Price (as shown on TWS). Market Value divided by number of shares for stocks would yield an accurate value for price. Options also likely use the contract multiplier to report average price. The discrepancy comes with futures where the contract multiplier not consistent across contracts.
|
checking and reconnnecting python script after tws shutdown (or auto-restart)
Hi there,
I am a newbie struggling with the reconnection of my python script after tws auto restarts (or manual restart for that matter). I know similar questions have been asked before and I am trying to follow this advice?to use connectionClosed callback but cant really seem to get it working.?
my callback function:
def connectionClosed(self): print('connection lost') while self.isConnected() is False: print('trying reconnection') self.connect('127.0.0.1', 7497, 123) time.sleep(30) return
But it doesn't work. apparently the following error AttributeError: 'NoneType' object has no attribute 'settimeout' occurs at line self.connect('127.0.0.1', 7497, 123) .
Quite desperate to get it working. Any help would be extremely appreciated!
?
|
Re: reqPositions API returns nothnig
Crow,
Today, reqContractDetails() is returning no data for me at all - was working yesterday and before.? Tried all sorts of debugging to no avail - wonder if someone else is having the same issue.? Did your problem resolve?
|
Re: reqPositions avgCost prices muliplier?
It sounds like you equate the cost of purchasing the futures contract with the price quotation for the contract. That is where the disconnect is. So let's take the GC you mentioned in your initial post as an example and let me tighten my terminology a little.
The contract specification says that the "contract unit" is "100 troy ounces of gold" and that the "price quotation" is "U.S. dollars and cents per troy ounce". So let's do the math (with GCG2 price quotations as of right now):
- The last "price quotation" for GCG2 is $1,841
- That means the value of one GCG2 contract is 100 troy ounces * 1,841$/troy ounce = $184,100
- When you now purchase n of those contracts, your account must show that you hold a position of n contracts with an average cost of $184,100 each (ignoring commissions)
This is no different than holding stock positions, just that the numeric value for a stock "price quotation" is identical to the value/cost for one unit of stock.
So if your algorithm is built around the concept of "contract price quotations" (and there is nothing wrong with that) you determine the "average price quotation" for a position of GCG2 contracts in your account by dividing the "average cost" of the position by 100 (the number per contract, aka the multiplier).
´³¨¹°ù²µ±ð²Ô.
toggle quoted message
Show quoted text
On Thu, Jan 20, 2022 at 06:43 AM, Jenzi wrote:
As you can see in my first post not the average cost of my position is returned, but the underlying contract value (contract size, i.e. multiplier * price).
|
Re: reqPositions avgCost prices muliplier?
While I understand (and agree) that "positions" are potentially the result of a series of trades, there is a discrepancy between what IB shows as price for the position and what it reports through reqPositions. For futures contract, it reports dollar values instead of price. I believe it reports 'Market Value' (as shown on TWS) divided by number of contracts instead of the Average Price (as shown on TWS). Market Value divided by number of shares for stocks would yield an accurate value for price. Options also likely use the contract multiplier to report average price. The discrepancy comes with futures where the contract multiplier not consistent across contracts.
|
Re: Fix Pegged order type?
I have seen it when I have used a Adjustable Trail Stop Order - So usually when I submit a bracket order, I adjust my stop order such that after the price moves a certain amount in my direction, I want to adjust the stop to start trailing. When the trigger price for the adjustable stop order is reached, I see in TWS that my original stop order has changed to a Fix Pegged Order Type. So basically I think its used to implement a Trail Stop order.
Other than this, I myself have not found documentation for this specific order type in their doc.
|
Re: reqPositions avgCost prices muliplier?
The purpose of reqPositions is to give you the quantity and the average cost for each position in your account. Seemingly, it does exactly that for stocks, options, etc., but not for Futures. As you can see in my first post not the average cost of my position is returned, but the underlying contract value (contract size, i.e. multiplier * price). With that i can either break down the contract value to the price or monitor my executions to calculate the average position price for myself (requires much more effort).
|
reqPositions API returns nothnig
I have been using the reqPositions API for a long time, but it seems to have stopped working today.
From the IB Gateway, I see this message with logging turned on:
[AWT-EventQueue-0] - Positions were not received for accounts: ***
Anyone else seeing this issue?
|
Does anyone know what this order type means? I haven¡¯t been able to find any info in any of IB¡¯s user guides/help docs.
|
Re: Multiple Algos on Linked Accounts
Hi Glenn. Thats pretty much what I am looking for! I guess I can simply use linked accounts and trade different strategies!
Thanks everyone for all your inputs!
|
Re: reqPositions avgCost prices muliplier?
Not sure I agree. Prices are related to executions, not to positions.
The current "position" is the end-point of possibly a long series of trades (buy, sell, different prices, different quantities) and each would have incurred a cost of qty[i] * multiplier * price[i]. The two items that completely describe the outcome of the series are the current quantity and the average cost per unit.
You can find prices for each trade in objects that are reported back to you right after the execution of trades. You can also request historical execution details if you did not record them. More detail at
´³¨¹°ù²µ±ð²Ô
On Wed, Jan 19, 2022 at 02:26 PM, Jenzi wrote:
toggle quoted message
Show quoted text
They definitely should provide the option to obtain that in reqPositions. Looks like i'll have to set up the calculations too.
|
Re: reqPositions avgCost prices muliplier?
Thanks for the answer. Just tested, reqExecutions(avgPrice) and there they are transmitting the executed price. They definitely should provide the option to obtain that in reqPositions. Looks like i'll have to set up the calculations too.
|
Re: Multiple Algos on Linked Accounts
I presently have 5 linked accounts at IB that share one data subscription and can be accessed by one username log-in. Positions in each account are independent, so it would be possible to hold both a long position in one account and a short position in a second account. I can access all of them through one API connection at the same time. I simply need to specify the account when submitting orders.
|
Re: reqPositions avgCost prices muliplier?
For whatever reason, in reqPositions, IB provides the $$ value of futures contracts, not the executed price. I do the math myself after getting the value, but I'd be delighted to learn if IB provides the correct values in another function....
|
Re: Multiple Algos on Linked Accounts
Yup, log-in is definitely usernames ¡ª I use a password manager so honestly didn¡¯t notice. Sorry.
JG¡¯s response was definitely clear and helpful.
Good luck with your trading.
|
Re: Multiple Algos on Linked Accounts
Hi J G, Yes, the whole conversation is all over the place. And yes, I have the same setup as you, but not sure whether its going to work or not. I guess I will just have to try it!
Gilbert, you can't login to TWS with "account numbers". You need usernames. I just tried logging in with account number and didnt work. Unless you have a totally different setup!
Thanks.
|
reqPositions avgCost prices muliplier?
Hello Everyone, i am using Python API and TWS 981.3. When i send reqPositions, i receive avgCost prices with a multiplier. Print Statement:  API Log: 19:53:48:206 -> ---K61-3-DUxx-415176828-GC-FUT-20220224-0.0--100--USD-GCG2-GC-1-181272.42- 19:53:48:206 -> ---O61-3-DUxx-269459887-EUR-FUT-20220314-0.0--125000--USD-6EH2-6E-4-142469.97- 19:53:48:207 -> ---P61-3-DUxx-495918908-GBX-FUT-20220308-0.0--1000--EUR-FGBX MAR 22-FGBX-0-0.0- 19:53:48:207 -> ---M61-3-DUxx-498287810-TN-FUT-20220322-0.0--1000--USD-TN?? MAR 22-TN-0-0.0- 19:53:48:207 -> ---M61-3-DUxx-498287815-ZB-FUT-20220322-0.0--1000--USD-ZB?? MAR 22-ZB-0-0.0- 19:53:48:207 -> ---P61-3-DUxx-495918902-GBL-FUT-20220308-0.0--1000--EUR-FGBL MAR 22-FGBL-0-0.0- 19:53:48:207 -> ---M61-3-DUxx-498287821-UB-FUT-20220322-0.0--1000--USD-UB?? MAR 22-UB-0-0.0- 19:53:48:207 -> ---J61-3-DUxx-461318816-ES-FUT-20220318-0.0--50--USD-ESH2-ES-1-230358.35- 19:53:48:207 -> ---F61-3-DUxx-256019295-CL-FUT-20220222-0.0--1000--USD-CLH2-CL-0-0.0- In the API Log you can see the multiplier. For GC it is 181272.42 / 100 = 1812.7242 (correct price) For EUR it is 142469.97 / 125000 = 1.1397 (correct price) Why is that? What am i missing? Thank you.
|