Esempio n. 1
0
    def createContract(self,
                       secType,
                       symbol,
                       exchange,
                       expiry=None,
                       currency=None):
        """
        Create new IB Contract
        :param secType: Contract sector type: STK, OPT, FUT, IND, FOP, CASH,BAG, NEWS
        :param expiry: The expiration date. Use the format YYYYMM.
        :param symbol: This is the symbol of the underlying asset.
        :param exchange: The order destination, such as Smart.
        """
        ibcontract = IBcontract()
        ibcontract.secType = secType

        if expiry:
            ibcontract.expiry = expiry
        if currency:
            ibcontract.currency = currency

        ibcontract.symbol = symbol
        ibcontract.exchange = exchange

        return ibcontract
Esempio n. 2
0
def main():
    """
    This simple example returns historical data
    """

    callback = IBWrapper()
    client = IBclient(callback)

    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry = "202009"
    ibcontract.symbol = "GE"
    ibcontract.exchange = "GLOBEX"

    # ibcontract.secType = "STK"
    # ibcontract.exchange = "SMART"
    # ibcontract.symbol = "MMM"
    # ibcontract.currency = "USD"

    end_dt = datetime.datetime(2016, 8, 3)
    ans = client.get_IB_historical_data(ibcontract,
                                        durationStr='5 d',
                                        barSizeSetting='5 mins',
                                        end_dt=end_dt)
    return ans
Esempio n. 3
0
def dbcontract_to_ibcontract(dbcontract):
    symbol = str(dbcontract.sym)
    localSym = str(dbcontract.local_sym)
    if str(dbcontract.secType) == 'CASH':
        symbol = str(dbcontract.sym) + str(dbcontract.cur)

    if str(dbcontract.secType) == 'FUT':
        year = str(dbcontract.contractMonth)[0:4]
        mon = str(dbcontract.contractMonth)[4:6]
        addSym = ''
        print symbol, year, int(mon)

        if int(mon) == 1:
            addSym = 'F'
            print addSym
        if int(mon) == 2:
            addSym = 'G'
        if int(mon) == 3:
            addSym = 'H'
        if int(mon) == 4:
            addSym = 'J'
        if int(mon) == 5:
            addSym = 'K'
        if int(mon) == 6:
            addSym = 'M'
        if int(mon) == 7:
            addSym = 'N'
        if int(mon) == 8:
            addSym = 'Q'
        if int(mon) == 9:
            addSym = 'U'
        if int(mon) == 10:
            addSym = 'V'
        if int(mon) == 11:
            addSym = 'X'
        if int(mon) == 12:
            addSym = 'Z'
        addSym += year[3:4]
        print addSym
        localSym += addSym
    print 'Found', localSym
    contract = Contract()
    contract.symbol = str(symbol)
    contract.secType = str(dbcontract.secType)
    contract.exchange = str(dbcontract.exch)
    contract.primaryExchange = str(dbcontract.exch)
    contract.currency = str(dbcontract.cur)
    contract.expiry = str(dbcontract.expiry)
    #contract.strike= # Strike Price
    contract.localSymbol = localSym
    return contract
Esempio n. 4
0
 def createContract(self, secType, symbol, exchange, expiry=None, currency=None ):
     """
     Create new IB Contract
     :param secType: Contract sector type: STK, OPT, FUT, IND, FOP, CASH,BAG, NEWS
     :param expiry: The expiration date. Use the format YYYYMM.
     :param symbol: This is the symbol of the underlying asset.
     :param exchange: The order destination, such as Smart.
     """
     ibcontract = IBcontract()
     ibcontract.secType = secType
     
     if expiry:
         ibcontract.expiry = expiry
     if currency:
         ibcontract.currency = currency
         
     ibcontract.symbol = symbol
     ibcontract.exchange = exchange
     
     return ibcontract
Esempio n. 5
0
    def getPortfolio(self):
        '''
	Returns list of triplets of current (contract, position in number of shares/contracts, market value of position)
	'''
        portfolioList = []
        # setup call back variables
        self.callback.accountEnd = False
        #self.callback.portfolioContract = None
        #self.callback.portfolioPosition = None
        #self.callback.portfolioSecMarketValue = None

        self.tws.reqAccountUpdates(1, self.accountNumber)
        while (not self.callback.accountEnd):
            self.callback.portfolioContract = None
            self.callback.portfolioPosition = None
            self.callback.portfolioSecMarketValue = None
            max_wait = datetime.timedelta(seconds=60) + datetime.datetime.now()
            while (self.callback.portfolioPosition is None
                   or self.callback.portfolioContract is None
                   or self.callback.portfolioSecMarketValue is None):
                if datetime.datetime.now() > max_wait:
                    break
            if self.callback.portfolioPosition is not None and self.callback.portfolioContract is not None and self.callback.portfolioSecMarketValue is not None:
                myContract = Contract()
                myContract.exchange = "SMART"
                myContract.currency = "USD"
                myContract.symbol = self.callback.portfolioContractSymbol
                myContract.conId = self.callback.portfolioContractConId
                myContract.secType = self.callback.portfolioContractSecType
                myContract.strike = self.callback.portfolioContractStrike
                myContract.expiry = self.callback.portfolioContractExpiry
                myContract.right = self.callback.portfolioContractRight
                myPosition = self.callback.portfolioPosition
                mySecMarketValue = self.callback.portfolioSecMarketValue
                portfolioList.append(
                    (myContract, myPosition, mySecMarketValue))

        self.tws.reqAccountUpdates(0, self.accountNumber)
        return portfolioList
Esempio n. 6
0
def place_plain_order(expiry, symbol, right, strike, orderType, quantity,
                      lmtPrice, orderId):
    """
    Place a sinlge option order orderType="LMT"
    """
    if orderId <= 0:
        orderId = None

    client, log_order = init_func()
    log_order.info("placing order ")
    ibcontract = IBcontract()
    ibcontract.secType = get_contract_details(symbol)["secType"]
    ibcontract.expiry = expiry
    ibcontract.symbol = symbol
    ibcontract.exchange = get_contract_details(symbol)["exchange"]
    ibcontract.right = right
    ibcontract.strike = strike
    ibcontract.multiplier = get_contract_details(symbol)["multiplier"]
    ibcontract.currency = get_contract_details(symbol)["currency"]

    iborder = IBOrder()
    iborder.action = bs_resolve(quantity)
    iborder.lmtPrice = lmtPrice
    iborder.orderType = orderType
    iborder.totalQuantity = abs(quantity)
    iborder.tif = get_order_defaults()["tif"]
    iborder.transmit = get_order_defaults()["transmit"]

    order_structure = client.place_new_IB_order(ibcontract,
                                                iborder,
                                                orderid=orderId)
    df1 = pd.DataFrame()
    for idx, x in order_structure.items():
        temp = pd.DataFrame.from_dict(x, orient='index').transpose()
        df1 = df1.append(temp)
    if not df1.empty:
        df1 = df1.set_index(['orderid'], drop=True)
    print(df1)
    end_func(client=client)
Esempio n. 7
0
def create_contract(security):
    if security.split('.')[0]=='FUT':
        contract = Contract()
        contract.symbol = security.split('.')[1]
        contract.secType = 'FUT'
        contract.exchange = 'GLOBEX'
        contract.currency = security.split('.')[2]
        contract.expiry= security.split('.')[3]
        contract.primaryExchange='GLOBEX'
    elif security.split('.')[0]=='CASH':
        contract = Contract()
        contract.symbol = security.split('.')[1]
        contract.secType = 'CASH'
        contract.exchange = 'IDEALPRO'
        contract.currency = security.split('.')[2]
        contract.primaryExchange='IDEALPRO'
    elif security.split('.')[0]=='STK':
        contract = Contract()
        contract.symbol = security.split('.')[1]
        contract.secType = 'STK'
        contract.exchange = 'SMART'
        contract.currency = 'USD'
        contract.primaryExchange='SMART'
    return contract
Esempio n. 8
0
    def getPortfolio(self):
	'''
	Returns list of triplets of current (contract, position in number of shares/contracts, market value of position)
	'''
	portfolioList = []
	# setup call back variables 
	self.callback.accountEnd = False
	#self.callback.portfolioContract = None
	#self.callback.portfolioPosition = None
	#self.callback.portfolioSecMarketValue = None

	self.tws.reqAccountUpdates(1, self.accountNumber)
	while (not self.callback.accountEnd):
	    self.callback.portfolioContract = None
	    self.callback.portfolioPosition = None
	    self.callback.portfolioSecMarketValue = None
	    max_wait = datetime.timedelta(seconds=60) + datetime.datetime.now()
	    while (self.callback.portfolioPosition is None or self.callback.portfolioContract is None or self.callback.portfolioSecMarketValue is None):
	        if datetime.datetime.now() > max_wait:
	            break
	    if self.callback.portfolioPosition is not None and self.callback.portfolioContract is not None and self.callback.portfolioSecMarketValue is not None:
	        myContract = Contract()
	        myContract.exchange = "SMART"
	        myContract.currency = "USD"
	        myContract.symbol = self.callback.portfolioContractSymbol
	        myContract.conId = self.callback.portfolioContractConId
	        myContract.secType = self.callback.portfolioContractSecType
	        myContract.strike = self.callback.portfolioContractStrike
	        myContract.expiry = self.callback.portfolioContractExpiry
	        myContract.right = self.callback.portfolioContractRight
	        myPosition = self.callback.portfolioPosition
		mySecMarketValue = self.callback.portfolioSecMarketValue
	        portfolioList.append((myContract, myPosition, mySecMarketValue))

	self.tws.reqAccountUpdates(0, self.accountNumber)
	return portfolioList
Esempio n. 9
0
from sysIB.wrapper_v2 import IBWrapper, IBclient
from swigibpy import Contract as IBcontract

if __name__ == "__main__":
    """
    This simple example returns historical data 
    """
    callback = IBWrapper()
    client = IBclient(callback)

    ibcontract = IBcontract()
    ibcontract.secType = "STK"
    ibcontract.expiry = "201809"
    ibcontract.symbol = "GE"
    ibcontract.exchange = "GLOBEX"

    ans = client.get_IB_historical_data(ibcontract)
    print(ans)
Esempio n. 10
0
    Note: If you are running this on the 'edemo' account it will probably give
    you back garbage

    Though the mechanics should still work

    This is because you see the orders that everyone demoing the account is
    trading!!!
    """

    callback = IBWrapper()
    client = IBclient(callback)

    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry = "201509"
    ibcontract.symbol = "GBL"
    ibcontract.exchange = "DTB"

    # Get contract details
    cdetails = client.get_contract_details(ibcontract)

    # In particular we want the expiry. You cannot just use
    # cdetails['expiry'][:6] to map back to the yyyymm expiry since certain
    # contracts expire the month before they should!

    print("Expiry is %s" % cdetails['expiry'])

    # Place the order, asking IB to tell us what the next order id is
    # Note limit price of zero
    orderid1 = client.place_new_IB_order(
from sysIB.wrapper_v3 import IBWrapper, IBclient
from swigibpy import Contract as IBcontract
 
if __name__=="__main__":

    """
    This simple example returns streaming price data
    """

    callback = IBWrapper()
    client=IBclient(callback)
    
    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry="201612"
    ibcontract.symbol="GE"
    ibcontract.exchange="GLOBEX"

    ans=client.get_IB_market_data(ibcontract)
    print "Bid size, Ask size; Bid price; Ask price"
    print ans
    
    """
    This simple example places an order, checks to see if it is active, and receives fill(s)
    
    Note: If you are running this on the 'edemo' account it will probably give you back garbage
    
    Though the mechanics should still work
    
    This is because you see the orders that everyone demoing the account is trading!!!
    """

    callback = IBWrapper()
    client=IBclient(callback)
    
    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry="201703"
    ibcontract.symbol="GBL"
    ibcontract.exchange="DTB"

    ## Get contract details
    cdetails=client.get_contract_details(ibcontract)
    
    ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm 
    ##    expiry since certain contracts expire the month before they should!
    
    print "Expiry is %s" % cdetails['expiry']

    ## Place the order, asking IB to tell us what the next order id is
    ## Note limit price of zero
    orderid1=client.place_new_IB_order(ibcontract, 10, 0.0, "MKT", orderid=None)
    
    """
    This simple example places an order, checks to see if it is active, and receives fill(s)
    
    Note: If you are running this on the 'edemo' account it will probably give you back garbage
    
    Though the mechanics should still work
    
    This is because you see the orders that everyone demoing the account is trading!!!
    """

    callback = IBWrapper()
    client = IBclient(callback)

    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry = "201703"
    ibcontract.symbol = "GBL"
    ibcontract.exchange = "DTB"

    ## Get contract details
    cdetails = client.get_contract_details(ibcontract)

    ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm
    ##    expiry since certain contracts expire the month before they should!

    print "Expiry is %s" % cdetails['expiry']

    ## Once you have the portfolio positions then you can use these expiries to map back

    (account_value, portfolio_data) = client.get_IB_account_data()
Esempio n. 14
0
from sysIB.wrapper_v2 import IBWrapper, IBclient
from swigibpy import Contract as IBcontract
 
if __name__=="__main__":

    """
    This simple example returns historical data 
    """

    callback = IBWrapper()
    client=IBclient(callback)
    
    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry="201809"
    ibcontract.symbol="GE"
    ibcontract.exchange="GLOBEX"

    ans=client.get_IB_historical_data(ibcontract)
    print ans
     
Esempio n. 15
0
from swigibpy import Contract as IBcontract

from sysIB.order_creation_wrapper import IBWrapper, IBclient

if __name__ == "__main__":
    """
    This simple example places an order, checks to see if it is active, and receives fill(s)
    Note: If you are running this on the 'edemo' account it will probably give you back garbage
    Though the mechanics should still work
    This is because you see the orders that everyone demoing the account is trading!!!
    """
    callback = IBWrapper()
    client = IBclient(callback)
    ibcontract = IBcontract()
    ibcontract.secType = "STK"
    ibcontract.expiry = "201603"
    ibcontract.symbol = "GOOG"
    ibcontract.exchange = "SMART"

    ## Get contract details
    cdetails = client.get_contract_details(ibcontract)
    ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm
    ##    expiry since certain contracts expire the month before they should!
    print("Expiry is %s" % cdetails['expiry'])
    print(client.get_managed_accounts())
    ## Place the order, asking IB to tell us what the next order id is
    ## Note limit price of zero
    orderid1 = client.place_new_IB_order(ibcontract, "DU271807", 10, 0.0, "MKT", orderid=None)
    print("")
    print("Placed market order, orderid is %d" % orderid1)
    ## And here is a limit order, unlikely ever to be filled
Esempio n. 16
0
                            format='%(asctime)s [%(levelname)s] %(message)s',
                            datefmt='%j-%H:%M:%S')
    else:
        logging.basicConfig(handlers=[logging.StreamHandler()],
                            level=logging.INFO,
                            format='%(asctime)s [%(levelname)s] %(message)s',
                            datefmt='%j-%H:%M:%S')

    logging.debug(args)

    if args.sym: contract.symbol = args.sym
    if args.exc: contract.exchange = args.exc
    if args.st: contract.secType = args.st
    if args.cur: contract.currency = args.cur
    if args.id: contract.conId = args.id
    if args.exp: contract.expiry = args.exp
    if args.pex: contract.primaryExchange = args.pex
    if args.str: contract.strike = args.str
    if args.rt: contract.right = args.rt
    if args.mult: contract.multiplier = args.mult

    barsize = args.p
    datatype = args.t
    rth_only = args.rth
    pacing = args.pacing
    num_requests = args.n
    zerobased = args.z

    if barsize == "1 day" or barsize == "1W" or barsize == "1M":
        dt_format = "%Y%m%d"
    else:
Esempio n. 17
0
from wrapper_v2 import IBWrapper, IBclient
from swigibpy import Contract as IBcontract
 
if __name__=="__main__":

    """
    This simple example returns historical data 
    """

    callback = IBWrapper()
    client=IBclient(callback, port=4002, clientid=999)
    
    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry="201612"
    ibcontract.symbol="ES"
    ibcontract.exchange="GLOBEX"

    ans=client.get_IB_historical_data(ibcontract, durationStr="2 D", barSizeSetting="5 mins")
    print ans
     
from sysIB.wrapper_v3 import IBWrapper, IBclient
from swigibpy import Contract as IBcontract
 
if __name__=="__main__":

    """
    This simple example returns streaming price data
    """

    callback = IBWrapper()
    client=IBclient(callback)
    
    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry="201406"
    ibcontract.symbol="GBL"
    ibcontract.exchange="DTB"

    ans=client.get_IB_snapshot_prices(ibcontract)
    print "Real time prices over seconds"
    print ans

    ans=client.get_IB_market_data(ibcontract)
    print "Bid size, Ask size; Bid price; Ask price"
    print ans
    
Esempio n. 19
0
    """
    This simple example places an order, checks to see if it is active, and receives fill(s)
    
    Note: If you are running this on the 'edemo' account it will probably give you back garbage
    
    Though the mechanics should still work
    
    This is because you see the orders that everyone demoing the account is trading!!!
    """

    callback = IBWrapper()
    client=IBclient(callback)
    
    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry="201509"
    ibcontract.symbol="GBL"
    ibcontract.exchange="DTB"

    ## Get contract details
    cdetails=client.get_contract_details(ibcontract)
    
    ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm 
    ##    expiry since certain contracts expire the month before they should!
    
    print "Expiry is %s" % cdetails['expiry']

    ## Place the order, asking IB to tell us what the next order id is
    ## Note limit price of zero
    orderid1=client.place_new_IB_order(ibcontract, 10, 0.0, "MKT", orderid=None)
    
Esempio n. 20
0
from sysIB.wrapper_v3 import IBWrapper, IBclient
from swigibpy import Contract as IBcontract

if __name__ == "__main__":
    """
    This simple example returns streaming price data
    """

    callback = IBWrapper()
    client = IBclient(callback)

    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry = "201812"
    ibcontract.symbol = "GE"
    ibcontract.exchange = "GLOBEX"

    ans = client.get_IB_market_data(ibcontract)
    print "Bid size, Ask size; Bid price; Ask price"
    print ans
Esempio n. 21
0
    args = parser.parse_args()

    if args.v:
        logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S')
    else:
        logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S')

    logging.debug(args)

    if args.sym: contract.symbol = args.sym
    if args.exc: contract.exchange = args.exc
    if args.st: contract.secType = args.st
    if args.cur: contract.currency = args.cur
    if args.id: contract.conId = args.id
    if args.exp: contract.expiry = args.exp
    if args.pex: contract.primaryExchange = args.pex
    if args.str: contract.strike = args.str
    if args.rt: contract.right = args.rt
    if args.mult: contract.multiplier = args.mult

    barsize = args.p
    datatype = args.t
    rth_only = args.rth
    pacing = args.pacing
    num_requests = args.n
    zerobased = args.z

    if barsize == "1 day" or barsize == "1W" or barsize == "1M":
        dt_format = "%Y%m%d"
    else:
Esempio n. 22
0
    """
    This simple example places an order, checks to see if it is active, and receives fill(s)
    
    Note: If you are running this on the 'edemo' account it will probably give you back garbage
    
    Though the mechanics should still work
    
    This is because you see the orders that everyone demoing the account is trading!!!
    """

    callback = IBWrapper()
    client = IBclient(callback)

    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry = "201406"
    ibcontract.symbol = "GBL"
    ibcontract.exchange = "DTB"

    ## Get contract details
    cdetails = client.get_contract_details(ibcontract)

    ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm
    ##    expiry since certain contracts expire the month before they should!

    print "Expiry is %s" % cdetails['expiry']

    ## Once you have the portfolio positions then you can use these expiries to map back

    positions = client.get_IB_positions()
Esempio n. 23
0
from sysIB.wrapper_v3 import IBWrapper, IBclient
from swigibpy import Contract as IBcontract
import time

if __name__ == "__main__":

    """
    This simple example returns streaming price data
    """

    callback = IBWrapper()
    client = IBclient(callback)

    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.expiry = "201712"
    ibcontract.symbol = "GE"
    ibcontract.exchange = "GLOBEX"

    ans = client.get_IB_market_data(ibcontract)

    WAIT_TIME = 5
    try:
        client.cb.got_sample.wait(timeout=WAIT_TIME)
    except KeyboardInterrupt:
        pass
    finally:
        if not callback.got_sample.is_set():
            print('Failed to get contract within %d seconds' % WAIT_TIME)

        print("\nDisconnecting...")