Giter VIP home page Giter VIP logo

ezibpy's Introduction

ezIBpy: Pythonic Wrapper for IbPy

Python version PyPi version PyPi status Travis-CI build status Star this repo Follow me on twitter

ezIBpy is a Pythonic wrapper for the IbPy library by @blampe, that was developed to speed up the development of trading software that relies on Interactive Brokers for market data and order execution.

Changelog »


Version 1.12.67 now supports multiple/FA accounts!

  • Option to specify IB account upon connect. Alternatively, you can...
  • Get info using getAccount('DUXXXXXX'), getPositions('DUXXXXXX'), getPortfolio('DUXXXXXX'), or getOrders('DUXXXXXX')
  • Submit order to a specific account by specifing account=DUXXXXXX in createOrder(), placeOrder(), createBracketOrder(), createTrailingStopOrder(), createStopOrder(), and createTargetOrder() methods

NOTE

Starting with release 9.73, Interactive Brokers is officially supporting a new Python 3 API client. Although this is great news, I don't see ezIBpy becoming obsolete anytime soon since IB's API isn't Pythonic or or abstracted enough IMO. I do have plans to drop IbPy in favor of IB's official Python API, although I don't have a timetable for this transision.

If you're a developer and interested in helping converting ezIBpy to work with IB's Python API - please let me know :)


Code Examples

* Make sure you have the latest version of Interactive Brokers’ TWS or IB Gateway installed and running on the machine.

Market Data

*** YOU MUST HAVE ACTIVE MARKET DATA SUBSCRIPTION TO USE THESE METHODS ***

Order Execution

Other Stuff

Request Market Data:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()

# connect to IB (7496/7497 = TWS, 4001 = IBGateway)
ibConn.connect(clientId=100, host="localhost", port=4001)

# create some contracts using dedicated methods
stk_contract = ibConn.createStockContract("AAPL")
fut_contract = ibConn.createFuturesContract("ES", expiry="201606")
cont_fut_contract = ibConn.createContinuousFuturesContract("CL", "NYMEX")
csh_contract = ibConn.createCashContract("EUR", currency="USD")
opt_contract = ibConn.createOptionContract("AAPL", expiry="20160425", strike=105.0, otype="PUT")

# ...or using a contract tuple
oil_contract = ibConn.createContract(("CL", "FUT", "NYMEX", "USD", "201606", 0.0, ""))

# request market data for all created contracts
ibConn.requestMarketData()

# wait 30 seconds
time.sleep(30)

# cancel market data request & disconnect
ibConn.cancelMarketData()
ibConn.disconnect()

Request Market Depth:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# create a contract & request market depth
contract = ibConn.createCashContract("EUR", currency="USD")
ibConn.requestMarketDepth()

# wait 30 seconds
time.sleep(30)

# cancel market data request & disconnect
ibConn.cancelMarketData()
ibConn.disconnect()

Request Historical Data:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# create a contract
contract = ibConn.createStockContract("AAPL")

# request 30 days of 1 minute data and save it to ~/Desktop
ibConn.requestHistoricalData(resolution="1 min", lookback="2 D", csv_path='~/Desktop/')

# wait until stopped using Ctrl-c
try:
    while True:
        time.sleep(1)

except (KeyboardInterrupt, SystemExit):
    # cancel request & disconnect
    ibConn.cancelHistoricalData()
    ibConn.disconnect()

Submit an Order:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# create a contract
contract = ibConn.createFuturesContract("ES", exchange="GLOBEX", expiry="201609")

# create an order
order = ibConn.createOrder(quantity=1) # use price=X for LMT orders

# submit an order (returns order id)
orderId = ibConn.placeOrder(contract, order)

# to submit an order to a specific account (ie DUXXXXXX), use:
# orderId = ibConn.placeOrder(contract, order, account="DUXXXXXX")

# let order fill
time.sleep(1)

# see the positions
print("Positions")
print(ibConn.positions)

# disconnect
ibConn.disconnect()

Submit a Bracket Order:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# create a contract
contract = ibConn.createFuturesContract("ES", exchange="GLOBEX", expiry="201609")

# submit a bracket order (entry=0 = MKT order)
order = ibConn.createBracketOrder(contract, quantity=1, entry=0, target=2200., stop=1900.)

# to submit bracket order to a specific account (ie DUXXXXXX), use:
# order = ibConn.createBracketOrder(contract, quantity=1, entry=0, target=2200., stop=1900., account="DUXXXXXX")

# let order fill
time.sleep(1)

# see the positions
print("Positions")
print(ibConn.positions)

# disconnect
ibConn.disconnect()

Submit a Bracket Order & Move Stop Manually:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# create a contract
contract = ibConn.createFuturesContract("ES", exchange="GLOBEX", expiry="201609")

# submit a bracket order (entry=0 = MKT order)
order = ibConn.createBracketOrder(contract, quantity=1, entry=0, target=2200., stop=1900.)

# let order fill
time.sleep(1)

# see the positions
print("Positions")
print(ibConn.positions)

# move the stop
order['stopOrderId'] = ibConn.modifyStopOrder(orderId=order['stopOrderId'],
            parentId=order['entryOrderId'], newStop=2000, quantity=-1)


# disconnect
ibConn.disconnect()

Submit a Bracket Order with a Trailing Stop:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# create a contract
contract = ibConn.createFuturesContract("ES", exchange="GLOBEX", expiry="201609")

# submit a bracket order (entry=0 = MKT order)
order = ibConn.createBracketOrder(contract, quantity=1, entry=0, target=2200., stop=1900.)

# let order fill
time.sleep(1)

# see the positions
print("Positions")
print(ibConn.positions)

# create a trailing stop that's triggered at 2190
symbol = ibConn.contractString(contract)

ibConn.createTriggerableTrailingStop(symbol, -1,
            triggerPrice  = 2190,
            trailAmount   = 10, # for trail using fixed amount
            # trailPercent  = 10, # for trail using percentage
            parentId      = order['entryOrderId'],
            stopOrderId   = order["stopOrderId"],
            ticksize      = 0.25 # see note
        )

# ticksize is needed to rounds the stop price to nearest allowed tick size,
# so you won't try to buy ES at 2200.128230 :)

# NOTE: the stop trigger/trailing is done by the software,
# so your script needs to keep running for this functionality to work

# disconnect
# ibConn.disconnect()

Submit a Combo Orders:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# create contracts for an bear call spread
contract_to_sell = ibConn.createOptionContract("AAPL", expiry=20161118, strike=105., otype="CALL")
contract_to_buy  = ibConn.createOptionContract("AAPL", expiry=20161118, strike=100., otype="CALL")

# create combo legs
leg1 = ibConn.createComboLeg(contract_to_sell, "SELL", ratio=1)
leg2 = ibConn.createComboLeg(contract_to_buy, "BUY", ratio=1)

# build a bag contract with these legs
contract = ibConn.createComboContract("AAPL", [leg1, leg2])

# create & place order (negative price means this is a credit spread)
order = ibConn.createOrder(quantity=1, price=-0.25)
orderId = ibConn.placeOrder(contract, order)

# let order fill
time.sleep(1)

# see the positions
print("Positions")
print(ibConn.positions)

# disconnect
ibConn.disconnect()

Custom Callback:

import ezibpy
import time

# define custom callback
def ibCallback(caller, msg, **kwargs):
    if caller == "handleOrders":
        order = ibConn.orders[msg.orderId]
        if order["status"] == "FILLED":
            print(">>> ORDER FILLED")

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# assign the custom callback
ibConn.ibCallback = ibCallback

# create a contract
contract = ibConn.createStockContract("AAPL")

# create & place order
order = ibConn.createOrder(quantity=100)
orderId = ibConn.placeOrder(contract, order)

# let order fill
time.sleep(1)

# see the positions
print("Positions")
print(ibConn.positions)

# disconnect
ibConn.disconnect()

* See This Gist for more examples.

Account Information:

import ezibpy
import time

# initialize ezIBpy
ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)

# available variables (auto-updating)
print("Market Data")
print(ibConn.marketData)

print("Market Depth")
print(ibConn.marketDepthData)

print("Account Information")
print(ibConn.account)

print("Positions")
print(ibConn.positions)

print("Portfolio")
print(ibConn.portfolio)

print("Contracts")
print(ibConn.contracts)

print("Orders (by TickId)")
print(ibConn.orders)

print("Orders (by Symbol)")
print(ibConn.symbol_orders)

# subscribe to account/position updates
ibConn.requestPositionUpdates(subscribe=False)
ibConn.requestAccountUpdates(subscribe=False)

# disconnect
ibConn.disconnect()

Logging:

ezIBpy logs via the standard Python logging facilities under the logger name ezibpy at the level of ERROR by default.

You can change the log level:

import logging
import ezibpy

# after ezibpy is imported, we can silence error logging
logging.getLogger('ezibpy').setLevel(logging.CRITICAL)

# initialize with new logging configration
ibConn = ezibpy.ezIBpy()
...

Or log to a file:

import logging
import ezibpy

# after ezibpy is imported, we can change the logging handler to file
logger = logging.getLogger('ezibpy')
logger.addHandler(logging.FileHandler('path/to/ezibpy.log'))
logger.setLevel(logging.INFO)
logger.propagate = False # do not also log to stderr

# initialize with new logging configration
ibConn = ezibpy.ezIBpy()
...

Installation

Install ezIBpy using pip:

$ pip install ezibpy --upgrade --no-cache-dir

Requirements

  • Python >=3.4
  • Pandas (tested to work with >=0.23.0)
  • dateutil (tested to with with >=2.5.1)
  • IbPy2 (tested to work with >=0.8.0)
  • Latest Interactive Brokers’ TWS or IB Gateway installed and running on the machine

To-Do:

In regards to Options, ezIBpy currently supports market data retrieval and order execution.

If you want to add more functionality (such as news retreival, etc) be my guest and please submit a pull request.

Legal Stuff

ezIBpy is licensed under the Apache License, Version 2.0. A copy of which is included in LICENSE.txt. ezIBpy is not a product of Interactive Brokers, nor is it affiliated with Interactive Brokers.

P.S.

I'm very interested in your experience with ezIBpy. Please drop me an note with any feedback you have.

Ran Aroussi

ezibpy's People

Contributors

jkleint avatar ranaroussi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ezibpy's Issues

Delete all order

hi
thank for your library
this is too easy use
i have a ask i need a function for delete all orders in broket order (with a example for this work ) so
i need a function for cancel all order in account. i dont need use special order id

No exchange information in contracts

using ezIBpy (1.12.44).
codes below:

ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=4001)
print(ibConn.contracts[1].m_exchange)

there are positions in my account. it seems ezibpy created contracts based upon my positions. However, the created contracts did not have the exchange information. This caused issues later to place the orders.

Hardcoded formatDate forces TZ to UTC on forex historical data requests

With formatDate hardcoded to "2", historical data requests for forex pairs return in UTC, no matter if you have TZ set in end_datetime. Hardcoding this to "1" will throw this error:

ValueError: invalid literal for int() with base 10: '20170221 19:39:00'

Therefore, attached is a patch which retains the default functionality while allowing the user to avoid forcing all output data to UTC, if desired. Note: there might be a better way to accomplish the same. I'm not a python programmer.

If you're unconvinced of this bug, pull a day of historical data for USD.NOK with 1 min candles and see the start time for the day as 22:15:00 instead of 17:15:00, as defined for IDEAL PRO.

ezibpy_ezibpy_py.patch.txt

Stop Order

Is there a way to place a stop order or trailing stop order without a parent order id? I put my orders in a loop until a limit order is filled, and i cancel all previous orders. It would be difficult to get the parent id.

Futures Contract String

There are a few issues with the formula contractString for futures. on line 1480 you have localSymbol = contract.m_localSymbol.

There are two problems here:

  1. some exchanges use a different syntax for m_localSymbol for example DAX which trades on DTB details['m_localSymbol'] = 'FDAX JUN 19'. Or the Dow Jones (YM trading on ECBOT) has details['m_localSymbol'] = 'YM JUN 19'. On line 1503 you have the code exp = localSymbol[2:3] + self.localSymbolExpiry[localSymbol][:4]. Thus the first term (localSymbol[2:3]) in the DAX would be "A" and in "YM" would be " " (for which you have a backup).

  2. for symbols that have more than 2-character symbols, for example, RTY, localSymbol = "RTYM9" again the term localSymbol[2:3] is inappropriate here.

As this is so important for futures, this is what I would recommend:

From what I can tell details['m_contractMonth'] seems to be very reliable, slicing [-2:] would give you the best chance to get the correct letter code for expiry. If that's empty, then I would look to localSymbol, first checking for spaces. If there is no space use localSymbol[-2:-1]. If there are spaces, I would try to parse it 'localSymbol.split()[1]' and then use that to lookup against 3-letter month codes.

Unfortunately, if you want to standardize to using the expiry letter codes (which IS the correct choice), using m_expiry will sometimes lead you astray because the expiry date does not always happen in the month of coded expiration, for example, July gasoline m_expiry is 6/28. Many of the single month contracts have this problem. So mixing expiration day and expiration month can be confusing.

move target order?

For bracket orders,there is a function to move the stop order. Can we move the other target order?

Interacting Live with IBKR

How do you interact with this? I can run a python script no problem. But I cannot seem to find a way to then manually type in requests or cancel requests like for fundamental data, live ticks.

IE. At times I want to manually intervene, and make the script focus on other stocks. In terminal, it does not allow for inputs while running. If I run in Visual Code, and try to type something in the 'Debug Console' Most of the time I just get the variable is not defined.

What am I missing here?

The combo details for leg '1' are invalid.

combo example not working using valid options
contract_to_sell = ibConn.createOptionContract("AAPL", expiry=20170519, strike=140., otype="CALL")
contract_to_buy = ibConn.createOptionContract("AAPL", expiry=20170519, strike=135., otype="CALL")

results in:
[ERROR] ezibpy: [#321] Error validating request:-'bj' : cause - The combo details for leg '1' are invalid. - conid, ratio, side: 0, 1,
1

Delete Position

hi
thank for your library
this is too easy use
i have a ask i need a function for delete a position (with a example for this work ) so
i need a function for get position with id until use for delete this position any time i want

ValueError: Account not found in account list

1.12.67 was working fine, error with 1.12.68:

When I place an a basic market order I get the following error:

>>> tws.placeOrder(contract, tws.createOrder(1))
1550304349
ERROR:ibpy:Exception in message dispatch.  Handler 'handleServerEvents' for 'orderStatus'
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/ib/opt/dispatcher.py", line 44, in __call__
    results.append(listener(message))
  File "/usr/local/lib/python3.7/site-packages/ezibpy/ezibpy.py", line 332, in handleServerEvents
    self.handleOrders(msg)
  File "/usr/local/lib/python3.7/site-packages/ezibpy/ezibpy.py", line 762, in handleOrders
    positions = self.getPositions(order['account'])
  File "/usr/local/lib/python3.7/site-packages/ezibpy/ezibpy.py", line 616, in getPositions
    raise ValueError("Account %s not found in account list" % account)
ValueError: Account  not found in account list
ERROR:ibpy:Exception in message dispatch.  Handler 'handleServerEvents' for 'orderStatus'
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/ib/opt/dispatcher.py", line 44, in __call__
    results.append(listener(message))
  File "/usr/local/lib/python3.7/site-packages/ezibpy/ezibpy.py", line 332, in handleServerEvents
    self.handleOrders(msg)
  File "/usr/local/lib/python3.7/site-packages/ezibpy/ezibpy.py", line 762, in handleOrders
    positions = self.getPositions(order['account'])
  File "/usr/local/lib/python3.7/site-packages/ezibpy/ezibpy.py", line 616, in getPositions
    raise ValueError("Account %s not found in account list" % account)
ValueError: Account  not found in account list

Using TWS I can see that the order completes successfully. Also when I type tws.getPositions() I get my positions back as normal.

[#162] Historical Market Data Service error message:No historical market data for EUR/CASH@FXSUBPIP Last 1d

error retrieving FX cash historical data (i.e. EUR.USD).
Interactive Brokers does not disseminate TRADES data for cash FX. You need to use a different value for whatToShow than the default.

solution:

def requestHistoricalData(...):
    self.ibConn.reqHistoricalData(
                tickerId       = tickerId,
                contract       = contract,
                endDateTime    = end_datetime,
                durationStr    = lookback,
                barSizeSetting = resolution,
                whatToShow     = data, <<<<<
                useRTH         = int(rth),
                formatDate     = int(format_date)
            )

if contract.m_secType in ['CASH', 'CFD'], then override whatToShow=="MIDPOINT" or "BID" or "ASK", instead of "TRADES"

order type and destination

Hello,

I'm trying to figure out if it is possible to set the order type and the order destination explicitly when sending an order.

Line 1375 in ezibpy.py defines the params for the order but I'm not sure those two items are available to be modified.

Thanks

[ERROR] ezibpy: [#321] Error validating request:-'bp' : cause - Invalid account code '0'.

hi i get this error
my code is

        ibConn.requestAccountUpdates(subscribe=True)
        ibConn.requestPositionUpdates(subscribe=True)
        Time. sleep (30)
        
   
        account_data_response=ibConn.account


        ibConn.requestAccountUpdates(subscribe=False)
        ibConn.requestPositionUpdates(subscribe=False)
        # disconnect

how can i do for remove this error
my version is 1.12.67
so thanks for support

Bracket order - Parent is GTC Profit & Stop are DAY

Hey Ran,

i've been using ezIBPY and are loving how it simplifies IBPY programming.
Not sure if i am missing something but when i submit a bracket order - the parent order is set for "GTC" but the child orders are submitted as "DAY" , how can i have child orders set for GTC aswell ?

Bracket Order for stock - target order Id doesn't work

Ran,
i am trying to create a bracket order for TSLA but i think the orderID's aren't incrementing correctly. I get a reply from TWS but order ID's are 1 , 2 & 3. So i am guessing that i am not creating orders with ID's that start at 504. I would expect that my order id's should be 504,505 & 506. Is this correct? Any assistance on using this component of ezibpy would be much appreciated.

Below is the code i used and the results i get back.

import ezibpy
import time

initialize ezIBpy

ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=7496)

create a contract

contract = ibConn.createStockContract("TSLA")

submit a bracket order (entry=0 = MKT order)

order=ibConn.createBracketOrder(contract,quantity=1,entry=0,target=210,stop=190,targetType=None,trailingStop=None,group=None,tif="DAY",fillorkill=False,iceberg=False,rth=False,stop_limit=False)

orderId = ibConn.placeOrder(contract,order,orderId=504)

let order fill

time.sleep(5)

see the positions

print("Positions")
print(ibConn.positions)
print(orderId)
print(order)

disconnect

ibConn.disconnect()
The output I get seems that my OrderId’s aren’t working correctly.

Server Version: 76
TWS Time at connection:20161016 14:24:49 Australian Eastern Standard Time (Victoria)
Positions
{}
504
{'targetOrderId': 2, 'entryOrderId': 1, 'stopOrderId': 3, 'group': 'bracket_1476588290'}

Process finished with exit code 0

I think the order Id’s are incrementing but the orderId isn’t using my 504 above.

    # main order
    enteyOrder = self.createOrder(quantity, price=entry, transmit=False,
        tif=tif, fillorkill=fillorkill, iceberg=iceberg, rth=rth)
    entryOrderId = self.placeOrder(contract, enteyOrder)

    # target
    targetOrderId = 0
    if target > 0:
        targetOrder = self.createTargetOrder(-quantity,
            parentId  = entryOrderId,
            target    = target,
            transmit  = False if stop > 0 else True,
            orderType = targetType,
            group     = group,
            rth       = rth

        )
        targetOrderId = self.placeOrder(contract, targetOrder, self.orderId+1)

example history.py runs with errors

I'm running the history.py example with
contract = ibConn.createStockContract("AAPL", exchange="NYSE")
or
contract = ibConn.createFuturesContract(symbol="FDAX", exchange="DTB", currency="EUR", expiry="201709")

I don't get any data, I just get the following errors:

Server Version: 76
TWS Time at connection:20170907 14:37:29 CET
2017-09-07 14:37:30,379 [ERROR] ezibpy: [#2107] HMDS data farm connection is inactive but should be available upon demand.ushmds.us
2017-09-07 14:37:30,380 [ERROR] ezibpy: [#2107] HMDS data farm connection is inactive but should be available upon demand.ilhmds
2017-09-07 14:37:30,380 [ERROR] ezibpy: [#2107] HMDS data farm connection is inactive but should be available upon demand.euhmds
2017-09-07 14:37:30,380 [ERROR] ezibpy: [#2107] HMDS data farm connection is inactive but should be available upon demand.ushmds
2017-09-07 14:37:31,383 [ERROR] ezibpy: [#321] Error validating request:-'a0' : cause - Invalid account code '0'.
2017-09-07 14:37:31,385 [ERROR] ezibpy: [#321] Error validating request:-'bm' : cause - Please enter exchange

I'm connecting to an advisor account.

Endless loop on connection

I've also been able to put it into an endless loop of trying to connect and erroring out. Any thoughts on what I can send you to help resolve?

from Queue import Queue, Empty ModuleNotFoundError: No module named 'Queue' getting following error

File "optionsdata.py", line 21, in
import ezibpy
File "/Users/mark/work/rss/options/lib/python3.7/site-packages/ezibpy/init.py", line 26, in
from ezibpy.ezibpy import ezIBpy
File "/lib/python3.7/site-packages/ezibpy/ezibpy.py", line 31, in
from ib.opt import Connection
/lib/python3.7/site-packages/ib/opt/init.py", line 30, in
from ib.opt.connection import Connection
lib/python3.7/site-packages/ib/opt/connection.py", line 20, in
from ib.opt.dispatcher import Dispatcher
lib/python3.7/site-packages/ib/opt/dispatcher.py", line 8, in
from Queue import Queue, Empty
ModuleNotFoundError: No module named 'Queue'

[#2139] Real paper-trading has not been acknowledged yet.

I'm quite confused, can't find this message anywhere,but it seems to come from ezibpy?

2020-05-22 10:58:40,239 [ERROR] ezibpy: [#2139] Real paper-trading has not been acknowledged yet.

Using a paper trading connection through IB Gateway and the message appears when calling an order...
The connection itself works (using the "original" ib api) and I have clicked the "blabla this is paper trading only" message in the ib gateway.

thx in advance!

Add primaryExchange parameter

Greetings,

It would be nice to be able to specify not only the "exchange parameter", but also the "primaryExchange" in the case of an ambiguous tickets

Best regards

Market Data not subscribed

This might be a newbie question, but I have been reading the docs for IB API and couldn't find my answer.

I am trying to run the following code from the example provided:

stk_contract = ibConn.createStockContract("AAPL")

fut_contract = ibConn.createFuturesContract("ES", expiry="201606")
csh_contract = ibConn.createCashContract("EUR", currency="USD")
opt_contract = ibConn.createOptionContract("AAPL", expiry="20160425", strike=105.0, otype="PUT")

And when running this command:

ibConn.requestMarketData() # This gives me an error

With the following message:

2018-05-17 07:48:29,469 [ERROR] ezibpy: [#354] Requested market data is not subscribed.Delayed market data is available.Error&NYSE/STK/Top

This is simulated trading currently, and I found in the docs that I have to run a command to subscribe to market data type.

# ibConn.reqMarketDataType(3) # This is what the docs say to request delayed market data?

Interactive Brokers Doc for this: https://interactivebrokers.github.io/tws-api/market_data_type.html

Is there a similar command for ezibpy? Or do I need to contact IB for delayed market data?

I appreciate any help!

Simple TypeError fixes.

Hello Ran,

Uncovered these two TypeErrors in your ezibpy.py module. Not deal breakers obviously.
Just digging into qtpylib API.

File "/Users/KJ/Programming/Python/qtpylib/env/lib/python3.4/site-
packages/ezibpy/ezibpy.py", line 157, in log_msg
if hasattr("contract", logmsg):
TypeError: hasattr(): attribute name must be string

ezibpy.py
line 157:
#if hasattr("contract", logmsg):
if hasattr("contract", str(logmsg)):

and

line 312:
#self.log_msg("server", msg)
self.log_msg("server", str(msg))

Thanks
KJ

history.py example is not working

First, thanks for the excellent work with qtpy and ezibpy.

I see following error with the supplied history.py example. It works fine for futures though
<error id=1, errorCode=321, errorMsg=Error validating request:-'yd' : cause - HMDS Expired Contract Violation:contract can not expire.>

portfolio (ibConn.portfolio) has no currency

Hi,
Do you think that it is possible to get the currency of each investments/positions ?
Currently neither portfolio dict nor positions, are showing the currency in which investments are made.
It makes it hard to calculate a P&L in a given currencies.

i have added this bit of code in the method handlePosition in class ezIBpy():

    self._positions[msg.account][contractString] = {
        "symbol":        contractString,
        **"currency": str(contract_tuple[3]),**
        "position":      int(msg.pos),
        "avgCost":       float(msg.avgCost),
        "account":       msg.account
    }

and in handlePortolio:
self._portfolios[msg.accountName][contractString] = {
"symbol": contractString,
"position": int(msg.position),
"currency": str(contract_tuple[3]),
"marketPrice": float(msg.marketPrice),
"marketValue": float(msg.marketValue),
"averageCost": float(msg.averageCost),
"unrealizedPNL": float(msg.unrealizedPNL),
"realizedPNL": float(msg.realizedPNL),
"totalPNL": float(msg.realizedPNL) + float(msg.unrealizedPNL),
"account": msg.accountName
}

and it seems to work

Thanks
Best

I refer to these 2 dict/json:
ibConn.portfolio
ibConn.positions

Custom callback on requestHistoricalData()

Is there a callback once this function finishes running, i'm downloading in batches of 50 and i would like to know when the last symbol is downloaded so i can start the next batch.

Bracket orders for combo legs

Hi Ran,

thank you for writing this great module! It makes interaction with IB much easier.
As I am focused towards automating placing option spread combos, I have encountered the following issue: Combining your two examples from Readme file on placing an option combo and a bracket order, I get the following:

`import ezibpy
import time

ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=100, host="localhost", port=7496)

contract_to_buy = ibConn.createOptionContract("AAPL", expiry=20191101, strike=250, otype="CALL")
contract_to_sell = ibConn.createOptionContract("AAPL", expiry=20191101, strike=252.5, otype="CALL")

leg1 = ibConn.createComboLeg(contract_to_buy , "SELL", ratio=1)
leg2 = ibConn.createComboLeg(contract_to_sell , "BUY", ratio=1)
contract = ibConn.createComboContract("AAPL", [leg1, leg2])

order = ibConn.createBracketOrder(contract,
quantity = 1,
entry = 0.02,
target = 0.05,
stop = 0.01)
`

Missing or invalid NonGuaranteed value. REL+MKT, LMT+MKT, and REL+LMT order of two legs can only be set as non-guaranteed.

I have configured my API setting in IB TWS to allow Non-guaranteed execution, but the error remains. Looking through your source code, I also havent been able to locate the variable corresponding to this setting.

Any idea how to solve this?

Account information example

The example code outputs with the following error.

My account contains 1 futures contract, 1 share of AAPL.
There is also a pending order for AAPL LMT at 10.00 however, the code snippet doesn't seem to be capturing that at all in the Orders (by TickId) or Orders (by Symbol)

18-Apr-17 12:41:35 ERROR     Exception in message dispatch.  Handler 'handleServerEvents' for 'openOrder'
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\ib\opt\dispatcher.py", line 44, in __call__
    results.append(listener(message))
  File "C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\ezibpy\ezibpy.py", line 267, in handleServerEvents
    self.handleOrders(msg)
  File "C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\ezibpy\ezibpy.py", line 585, in handleOrders
    "time": datetime.fromtimestamp(int(self.time))
OSError: [Errno 22] Invalid argument
18-Apr-17 12:41:35 ERROR     Exception in message dispatch.  Handler 'handleServerEvents' for 'orderStatus'
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\ib\opt\dispatcher.py", line 44, in __call__
    results.append(listener(message))
  File "C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\ezibpy\ezibpy.py", line 267, in handleServerEvents
    self.handleOrders(msg)
  File "C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\ezibpy\ezibpy.py", line 550, in handleOrders
    contractString = self.contractString(msg.contract)
AttributeError: 'OrderStatus' object has no attribute 'contract'

Server Version: 76
TWS Time at connection:20170418 12:41:34 EST
Market Data
{0: ask asksize bid bidsize last lastsize
datetime
0 0 0 0 0 0 0}
Market Depth
{0: ask asksize bid bidsize
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0}
Account Information
{'AvailableFunds': 996222.14, 'AvailableFunds-C': -635.85, 'AvailableFunds-S': 996857.99, 'BuyingPower': 3987830.64, 'CashBalance': 999794.0, 'DayTradesRemaining': -1.0, 'InitMarginReq': 3712.95, 'MaintMarginReq': 2977.43, 'NetLiquidation': 999935.09}
Positions
{'ESU2017_FUT': {'symbol': 'ESU2017_FUT', 'position': 1, 'avgCost': 116564.54, 'account': 'xxx'}, 'AAPL': {'symbol': 'AAPL', 'position': 1, 'avgCost': 141.71345725, 'account': 'xxx'}}
Portfolio
{'AAPL': {'symbol': 'AAPL', 'position': 1, 'marketPrice': 141.33599855, 'marketValue': 141.34, 'averageCost': 141.71345725, 'unrealizedPNL': -0.38, 'realizedPNL': 0.0, 'account': 'xxx'}, 'ESU2017_FUT': {'symbol': 'ESU2017_FUT', 'position': 1, 'marketPrice': 2330.00024415, 'marketValue': 116500.01, 'averageCost': 116564.54, 'unrealizedPNL': -64.53, 'realizedPNL': 0.0, 'account': 'xxx'}}
Contracts
{1: <ib.ext.Contract.Contract object at 0x0000000007F10A20>}
Orders (by TickId)
{}
Orders (by Symbol)
{}

Place Order for a specify order

How do I set the order to be placed to a specific account?

I have 2 accounts under the same TWS login. (Taxable and Retirement/IRA A/c)
The code below does not have an Account# to be sent as parameter. Need help!

stk_contract = ibConn.createStockContract("SDS")

# create an order
order = ibConn.createOrder(quantity=1000, price =39.13) 

# submit an order (returns order id)
orderId = ibConn.placeOrder(stk_contract, order)

How to get hostorics of trade

HI,
Is it possible to pull trades history for a certain period?
Would help reconciliation/P&L/risk data.

Thanks

Best

Logging issue

When I have logging enabled and I connect to the gateway, it doesn't print out the contract name properly

2017-04-15 12:22:05,742 [INFO] ezibpy: [CONNECTION TO IB ESTABLISHED]
2017-04-15 12:22:05,749 [INFO] ezibpy: [POSITION]: <position account=xxx, contract=<ib.ext.Contract.Contract object at 0x0000000008129F60>, pos=33, avgCost=21.13030305>

historicaldata

I am very new to this and I tried with

ibConn = ezibpy.ezIBpy()
ibConn.connect(clientId=4, host="localhost", port=7496)
contract1 = ibConn.createStockContract("BAC")
ibConn.requestHistoricalData(resolution = "5 mins", lookback ="2 D", csv_path = '~/Desktop/5mindata/')

then i got

2016-12-13 00:46:44,667 [ERROR] ezibpy: [#321] Error validating request:-'bh' : cause - Please enter exchange

sometimes after this msg pop up i still can get the data in csv file but sometime it doesn't work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.