Exemple #1
0
 def makeContract(self, symbol):
     c = Contract()
     c.m_symbol = symbol
     c.m_secType = "STK"
     c.m_currency = "USD"
     c.m_exchange = "SMART"
     return c
Exemple #2
0
def makeStkContract(symbol, cur = 'USD'):
    contract = Contract()
    contract.m_symbol = symbol
    contract.m_secType = 'STK'
    contract.m_exchange = 'SMART'
    contract.m_currency = cur
    return contract
Exemple #3
0
def addfutur(ticker, exchg, expiry):
    c = Contract()
    c.m_symbol = ticker
    c.m_secType = 'FUT'
    c.m_exchange = exchg
    c.m_expiry = expiry
    addcontract(c, "Fut(" + exchg + ", " + expiry + ")")
Exemple #4
0
 def reqMktData(self):
     contract = Contract() #
     contract.m_symbol = 'AUD'
     contract.m_currency = 'USD'
     contract.m_secType = 'CASH'
     contract.m_exchange = 'IDEALPRO'
     self.connection.reqMktData(1, contract, '', False)
Exemple #5
0
 def create_option_ticker(self, ticker, currency='USD', exchange='SMART'):
     c = Contract()
     c.m_secType = 'OPT'
     c.m_localSymbol = ticker
     c.m_currency = currency
     c.m_exchange = exchange
     return c
    def subscribe_to_market_data(self,
                                 symbol,
                                 sec_type='STK',
                                 exchange='SMART',
                                 currency='USD'):
        if symbol in self.symbol_to_ticker_id:
            # Already subscribed to market data
            return

        contract = Contract()
        contract.m_symbol = symbol
        contract.m_secType = symbol_to_sec_type[symbol]
        contract.m_exchange = symbol_to_exchange[symbol]
        contract.m_currency = currency
        ticker_id = self.next_ticker_id

        self.symbol_to_ticker_id[symbol] = ticker_id
        self.ticker_id_to_symbol[ticker_id] = symbol

        # INDEX tickers cannot be requested with market data. The data can,
        # however, be requested with realtimeBars. This change will make
        # sure we can request data from INDEX tickers like SPX, VIX, etc.
        if contract.m_secType == 'IND':
            self.reqRealTimeBars(ticker_id, contract, 60, 'TRADES', True)
        else:
            tick_list = "233"  # RTVolume, return tick_type == 48
            self.reqMktData(ticker_id, contract, tick_list, False)
            sleep(11)
Exemple #7
0
 def inner():
     con.reqAccountUpdates(1, '')
     qqqq = Contract()
     qqqq.m_symbol = 'QQQQ'
     qqqq.m_secType = 'STK'
     qqqq.m_exchange = 'SMART'
     con.reqMktData(1, qqqq, '', False)
Exemple #8
0
 def start(self):
     """Start the connection and read the realtime bars for the specified 
     tickers.
     """
     # connection and handler
     self.connection = ibConnection(
                                    host=self.host, 
                                    port=self.port, 
                                    clientId=self.client_id)
     
     # registration
     self.connection.register( self.ticker_updated, message.RealtimeBar )
     
     # connect
     self.connection.connect()
     
     for inx,stock in enumerate(self.stocks):
         print "Requesting:\t%d = %s" % (inx,stock)
         # create the contract
         contract = Contract()
         contract.m_symbol = stock
         contract.m_secType = 'STK'
         contract.m_exchange = self.exchange
         contract.m_currency = 'USD'
         self.connection.reqRealTimeBars(inx, contract, 5, 'TRADES', False)
Exemple #9
0
def makeStkContract(contractTuple):
    newContract = Contract()
    newContract.m_symbol = contractTuple[0]
    newContract.m_secType = contractTuple[1]
    newContract.m_exchange = contractTuple[2]
    newContract.m_currency = contractTuple[3]
    return newContract
Exemple #10
0
def addstock(ticker, exchg, cur = None):
    c = Contract()
    c.m_symbol = ticker
    c.m_secType = 'STK'
    c.m_exchange = exchg
    if cur != None:
        c.m_currency = cur
    addcontract(c, "Stock(" + exchg + ")")
def createContract(symbol, secType='STK', exchange='SMART', currency='USD'):
    """ contract factory function """
    contract = Contract()
    contract.m_symbol = symbol
    contract.m_secType = secType
    contract.m_exchange = exchange
    contract.m_currency = currency
    return contract	
def build_qqq_msg(symbol_id):
    print i
    qqq = Contract()  
    qqq.m_symbol = i  
    qqq.m_secType = ibsecType 
    qqq.m_exchange = ibexchange
    qqq.m_currency = cashcurr
    return qqq
def createContract(symbol):
    ''' create contract object '''
    c = Contract()
    c.m_symbol = symbol
    c.m_secType= "STK"
    c.m_exchange = "SMART"
    c.m_currency = "USD"
    
    return c
Exemple #14
0
	def addindex(self, ticker, exchg):
		c = Contract()
		c.m_symbol = ticker
		c.m_secType = 'IND'
		c.m_exchange = exchg
		cid = self.registercontract(c)
		if not self.isActiveContract(cid):
			self.activateContract(cid)		
		return(cid)
def makeStkContract(contractTuple):
    newContract = Contract()
    newContract.m_symbol = contractTuple[0]
    newContract.m_secType = contractTuple[1]
    newContract.m_exchange = contractTuple[2]
    newContract.m_currency = contractTuple[3]
   
    print 'Contract Values:%s,%s,%s,%s:' % contractTuple
    return newContract
 def request_data(self):
     for ticker_id, instrument in self.instruments.items():
         contract = Contract()
         contract.m_symbol = instrument['symbol']
         contract.m_currency = instrument['currency']
         contract.m_secType = instrument['secType']
         contract.m_exchange = instrument['exchange']
         self.contracts[instrument['symbol']] = contract
         self.connection.reqMktData(ticker_id, contract, '', False)
def createContract(symbol,secType='STK',exchange='SMART',currency='USD'):
    ''' create contract object '''
    c = Contract()
    c.m_symbol = symbol
    c.m_secType= secType
    c.m_exchange = exchange
    c.m_currency = currency
    
    return c
def createContract(symbol, secType="STK", exchange="SMART", currency="USD"):
    """ contract factory function """
    contract = Contract()
    contract.m_symbol = symbol
    contract.m_secType = secType
    contract.m_exchange = exchange
    contract.m_currency = currency

    return contract
Exemple #19
0
 def createContract(self, symbol, secType="STK",
                    exchange="SMART", currency="USD"):
     """Create and store a contact from the given symbol"""
     c = Contract()
     c.m_symbol = symbol
     c.m_secType = secType
     c.m_exchange = exchange
     c.m_currency = currency
     return c
Exemple #20
0
	def addfuture(self, ticker, exchg, expiry):
		c = Contract()
		c.m_symbol = ticker
		c.m_secType = 'FUT'
		c.m_exchange = exchg
		c.m_expiry = expiry
		cid = self.registercontract(c)
		if not self.isActiveContract(cid):
			self.activateContract(cid)		
		return(cid)
 def contract(self):
     symbol = self.symbolName.text()
     security = self.secType.currentText()
     exchange = self.exchangeName.currentText()
     contract = Contract()
     contract.m_symbol = str(symbol)
     contract.m_secType = str(security)
     contract.m_exchange = str(exchange)
     contract.m_currency = 'USD'
     return contract
Exemple #22
0
 def addSymbol(self, symbol, secType="STK", exchange="SMART"):
     """Create and store a contact from the given symbol"""
     c = Contract()
     c.m_symbol = symbol
     c.m_secType = secType
     c.m_exchange = exchange
     c.m_currency = self.currency
     self._contracts[symbol] = self._next_valid_id, c
     self._next_valid_id += 1
     return self._next_valid_id - 1
Exemple #23
0
    def subscribe(self, subscribeReq):
        """订阅行情"""
        # 订阅行情
        self.tickerId += 1
        
        contract = Contract()
        contract.m_symbol = str(subscribeReq.symbol)
        contract.m_exchange = exchangeMap.get(subscribeReq.exchange, '')
        contract.m_secType = productClassMap.get(subscribeReq.productClass, '')
        contract.m_currency = currencyMap.get(subscribeReq.currency, '')
        contract.m_expiry = subscribeReq.expiry
        contract.m_strike = subscribeReq.strikePrice
        contract.m_right = optionTypeMap.get(subscribeReq.optionType, '')
        
        # 考虑设计为针对期货用代码_到期日的方式来代替单纯的代码
        if contract.m_secType == 'FUT' and not subscribeReq.expiry:
            # 期货 如果没有设置过期时间, 默认设置为下个月
            dt_obj = datetime.now()
            days = calendar.monthrange(dt_obj.year, dt_obj.month)[1]
            nextMonth = dt_obj + timedelta(days=(days - dt_obj.day + 1))
            contract.m_expiry = nextMonth.strftime('%Y%m')

        self.connection.reqMktData(self.tickerId, contract, '', False)
        
        # 获取合约详细信息
        self.connection.reqContractDetails(self.tickerId, contract)
        
        # 创建Tick对象并保存到字典中
        tick = VtTickData()
        tick.symbol = subscribeReq.symbol
        tick.exchange = subscribeReq.exchange
        tick.vtSymbol = '.'.join([tick.symbol, tick.exchange])
        tick.gatewayName = self.gatewayName
        tick.__setattr__('m_secType', productClassMap.get(subscribeReq.productClass, ''))
        self.tickDict[self.tickerId] = tick
Exemple #24
0
	def addstock(self, ticker, exchg, cur):
		#print ticker  + "  " + exchg  + "  " + cur
		c = Contract()
		c.m_symbol = ticker
		c.m_secType = 'STK'
		c.m_exchange = exchg
		c.m_currency = cur
		cid = self.registercontract(c)
		if not self.isActiveContract(cid):
			self.activateContract(cid)		
		return(cid)
Exemple #25
0
def newContract(symbol, secType, optType="", strike=0, expiry=""):
    contract = Contract()
    contract.m_symbol = symbol
    contract.m_secType = secType
    contract.m_exchange = "SMART"
    contract.m_primaryExchange = "SMART"
    contract.m_currency = "USD"
    contract.m_expiry = expiry  # dateString
    contract.m_strike = float(strike)
    contract.m_multiplier = 100
    contract.m_right = optType
    return contract
Exemple #26
0
 def download_contracts(self):
     contract = Contract()
     contract.m_exchange     = "SMART"
     contract.m_secType      = "OPT"
     contract.m_currency     = "USD"
     contract.m_symbol       = self._ticker
     self._con.reqContractDetails(1, contract)
     self._wait = True  
     i = 0
     while self._wait and i < 90:
         i += 1 ; print i,
         time.sleep(1)   
     print ''   
Exemple #27
0
    def __init__(self, name):
        
        c = Contract()
        c.m_symbol = name
        c.m_secType = "STK"

        # ib-tws server connection
        con = Pyro.core.getProxyForURI("PYRONAME://serverInterface")

        # get the first contract of the list comming from the details
        contract = con.reqContractDetails(c)[0].m_summary

        IBContract.__init__(self, contract)
Exemple #28
0
 def makeContract(self, symbol, **kwds):
     contract = Contract()
     kwds["symbol"] = symbol
     attrs = [k for k in dir(contract) if k.startswith("m_")]
     for attr in attrs:
         kwd = attr[2:]
         if kwd in kwds:
             setattr(contract, attr, kwds[kwd])
     ## set these even if they're already set
     contract.m_secType = kwds.get("secType", "STK")
     contract.m_exchange = kwds.get("exchange", "SMART")
     contract.m_currency = kwds.get("currency", "USD")
     return contract
Exemple #29
0
 def sendOrder(self, orderReq):
     """发单"""
     # 增加报单号1,最后再次进行查询
     # 这里双重设计的目的是为了防止某些情况下,连续发单时,nextOrderId的回调推送速度慢导致没有更新
     self.orderId += 1
     
     # 创建合约对象
     contract = Contract()
     contract.m_symbol = str(orderReq.symbol)
     contract.m_exchange = exchangeMap.get(orderReq.exchange, '')
     contract.m_secType = productClassMap.get(orderReq.productClass, '')
     contract.m_currency = currencyMap.get(orderReq.currency, '')
     
     contract.m_expiry = orderReq.expiry
     contract.m_strike = orderReq.strikePrice
     contract.m_right = optionTypeMap.get(orderReq.optionType, '')
     
     # 创建委托对象
     order = Order()
     order.m_orderId = self.orderId
     order.m_clientId = self.clientId
     
     order.m_action = directionMap.get(orderReq.direction, '')
     order.m_lmtPrice = orderReq.price
     order.m_totalQuantity = orderReq.volume
     order.m_orderType = priceTypeMap.get(orderReq.priceType, '')
     
     # 发送委托
     self.connection.placeOrder(self.orderId, contract, order)
     
     # 查询下一个有效编号
     self.connection.reqIds(1)
Exemple #30
0
 def create_contract(self, symbol, secType, exchange, currency,
                     right = None, strike = None, expiry = None,
                     multiplier = None, tradingClass = None):
     contract = Contract()
     contract.m_symbol = symbol
     contract.m_secType = secType
     contract.m_exchange = exchange
     contract.m_currency = currency
     contract.m_right = right
     contract.m_strike = strike
     contract.m_expiry = expiry
     contract.m_multiplier = multiplier
     contract.m_tradingClass = tradingClass
     return contract
# ------------create contract legs
# for simplicity, I just set each leg to buy 1 share
legs = []

for conId in contractIds:
    leg = ComboLeg()
    leg.m_conId = conId
    leg.m_ratio = 1
    leg.m_action = "BUY"
    leg.m_exchange = "SMART"

    legs.append(leg)

#-------- create a contract with required legs
contract = Contract()

contract.m_symbol = "USD"
contract.m_secType = "BAG"
contract.m_exchange = "SMART"
contract.m_currency = "USD"
contract.m_comboLegs = legs

#----- create and place order
print('Placing order')
order = createOrder(orderId, shares=1)  # create order

tws.placeOrder(orderId, contract, order)  # place order

sleep(1)  # wait before disconnecting
Exemple #32
0
def contract_to_dict(contract):
    """Convert an IBPy Contract object to a dict containing any non-default values."""
    default = Contract()
    return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)}
Exemple #33
0
def new_option_contract(symbol,
                        exchange,
                        expiry=None,
                        strike_price=None,
                        trading_class=None,
                        multiplier=100,
                        currency='USD',
                        is_expired=False):
    ''' Make a new option contract. Options, like futures, also require an expiration date plus a strike and a multiplier.
    The function is implemented according to http://interactivebrokers.github.io/tws-api/basic_contracts.html
    Args:
        symbol: string of a symbol or local symbol for the contract
        exchange: string of exchange name
        is_local_symbol: a True/False flag
        expiry: string; expiry month, e.g. '201610'
        tradingClass: string
    Returns:
        a new future contract object
    Raises:
        None
    '''

    contract = Contract()
    contract.m_symbol = symbol
    contract.m_secType = 'OPT'
    contract.m_exchange = exchange
    contract.m_expiry = expiry
    contract.m_strike = strike_price
    contract.m_right = "C"
    contract.m_multiplier = multiplier
    contract.m_currency = currency
    # It is not unusual to find many option contracts with an
    # almost identical description (i.e. underlying symbol, strike, last trading date, multiplier, etc.).
    # Adding more details such as the trading class will help:
    contract.m_tradingClass = trading_class

    if is_expired:
        contract.m_includeExpired = True

    return contract
Exemple #34
0
from ib.opt import Connection
from ib.ext.Contract import Contract
import time
import csv

Equity = Contract()
Equity.m_secType = 'Stk'
Equity.m_exchange = 'Smart'
Equity.m_currency = 'USD'

EquityList = ['XOM', 'JNJ', 'BRK B', 'JPM','GE','T','WFC','BAC','PG','CVX','VZ','PFE','MRK','HD','C','KO','DIS','V','UNH','PEP','PM','IBM','MO','SLB','ORCL','MMM','MDT','MA','WMT','MCD','ABBV','BMY','BA','HON','CVS','SPY']
PriceList = []
PriceData = csv.writer(open('/home/ori/price.csv','wb'))

def print_message_from_ib(msg):
    print(msg)
    

def savepx(msg):
    if msg.field == 4:
        PriceList.insert(msg.tickerId,msg.price)

def main():
    conn = Connection.create(port=7496,clientId=999)
    conn.registerAll(print_message_from_ib)
    conn.connect()
    count = 0
    for ticker in EquityList:
        Equity.m_symbol = ticker
        conn.register(savepx,'TickPrice')# move this out of loop, just do it once
        conn.reqMktData(count,Equity,225,True)#true snapshot
    def get_eod_options(
            self,
            contract_=Contract(),
            eod_or_bod=True,  # EOD or BOD options? 
            whatToShow_='MIDPOINT',
            endDateTime_=datetime.datetime.now(),
            numOfWeeks_=1,
            sameContract_=False):
        """
        The method returns EOD (3 min before close) and BOD data for options. It uses a different handler
        
        Contract: Specifies the contract we are querying. ib.ext.Contract 
        eod_or_bod: end of the day or beginning of the day. Boolean
        whatToShow: TRADE, MIDPOINT, BID, ASK, BID_ASK. From IB, string.
        endDateTime_: The last datetime that you would like to be queried. string in the right format
        numOfWeeks_: number of weekes we are iterating over. int
        sameContract_: For storage purposes, if it is indeed the same contract then get_conId would return the same id
        """
        # First step is to define a dictionary whill will be populated by IB API
        con = ibConnection(port=4001, clientId=998)
        #con.registerAll(self.watcher)
        #con.register(self.my_hist_data_handler, message.historicalData)
        #con.register(self.my_hist_option_eod_handler, message.historicalData)
        if eod_or_bod:
            con.register(self.my_hist_option_eod_handler,
                         message.historicalData)
        else:
            con.register(self.my_hist_option_bod_handler,
                         message.historicalData)
        # Setting up the connection
        con.connect()

        # First we should clean up the temporary dataframe of ours
        if not self.hist_data.empty:
            self.hist_data.drop(range(self.hist_data.shape[0]), inplace=True)

        # Putting the request in
        weekEnd = endDateTime_
        for i in xrange(numOfWeeks_):
            con.reqHistoricalData(
                tickerId=i,
                contract=contract_,
                endDateTime=weekEnd.strftime("%Y%m%d %H:%M:%S %Z"),
                durationStr='1 W',
                barSizeSetting='3 mins',
                whatToShow=whatToShow_,
                useRTH=0,
                formatDate=1)
            sleep(2)
            print ' - Iteration %s Completed - ' % i
            weekEnd = weekEnd - datetime.timedelta(days=7)

        # Sleep
        sleep(1)
        # Canceling the request
        con.cancelHistoricalData(tickerId=1)
        # Adding One Thing Before Storing The Contract
        self.hist_data['whatToShow'] = whatToShow_
        self.hist_data['Ticker'] = contract_.m_symbol
        self.hist_data.date = pd.to_datetime(self.hist_data.date)
        # Storing The Data
        conId = self.get_conId(sameContract=sameContract_)
        self.store_historical_data(contract_, conId)
        # Disconnecting
        print('Disconnected', con.disconnect())
Exemple #36
0
        cnx.commit()

    Flag = 1
    logger.debug('Flag set to %s', Flag)
    print(Flag)
    return (Flag)

while Flag == 0:
    logger.debug('Flag set to %s', Flag)
    conn = Connection.create(port=4002, clientId=999)
    conn.connect()
    logger.debug('Connecting to Server')
    time.sleep(1)
    conn.register(
        reply_handler, 'HistoricalData'
    )  #By registering "HistoricalData" --the Method name only --we can eliminate all the open order garbage
    logger.debug('Registered HistoricalData Reply Handler')
    time.sleep(1)
    qqq = Contract()
    qqq.m_symbol = Table
    qqq.m_secType = 'STK'
    qqq.m_exchange = 'SMART:ARCA'
    qqq.m_currency = 'USD'
    logger.debug('Requesting historical data')
    conn.reqHistoricalData(1, qqq, '', '1 D', '1 day', 'TRADES', 0, 1)
    logger.debug('Returned from Reply Handler')
    time.sleep(1)  #give IB time to send us messages
    logger.debug('Disconnecting from Server')
    conn.disconnect()

logger.debug('Finished Daily OHLC %s', Table)
Exemple #37
0
        self._reqId += 1


def makeOptContract(sym, exp, strike, right):
    """ exp should be in (year/month/day) """
    newOptContract = Contract()
    newOptContract.m_symbol = sym
    newOptContract.m_secType = 'OPT'
    newOptContract.m_expiry = exp
    newOptContract.m_strike = strike
    newOptContract.m_right = right
    newOptContract.m_multiplier = 100
    newOptContract.m_exchange = 'SMART'
    newOptContract.m_primaryExch = 'SMART'
    newOptContract.m_currency = 'USD'
    return newOptContract


if __name__ == '__main__':
    dl = Downloader()
    c = Contract()
    c.m_symbol = 'SPY'
    c.m_secType = 'STK'
    c.m_exchange = 'SMART'
    c.m_currency = 'USD'

    #c = makeOptContract('SPY', '20190219', 270, 'CALL')

    dl.requestData(c)
    sleep(3)
    print('Price - field 4: ', dl.field4price)
Exemple #38
0
 def __init__(self):
     self.m_summary = Contract()
     self.m_minTick = 0
     self.m_underConId = 0
Exemple #39
0
conn.register(reply_handler, 'Position')
conn.register(reply_handler_Orders, 'OpenOrder')
conn.register(reply_handler_Status, 'OrderStatus')
conn.register(reply_handler_Status, 'OrderStatus')
conn.register(reply_handler_Data, 'HistoricalData')
#conn.register(reply_handler_contract, 'Contract')
logger.debug('Requesting Positions')
conn.reqPositions()  # will find the order if it was filled
logger.debug('Finished Positions')
time.sleep(1)
logger.debug('Requesting Open Orders')
conn.reqAllOpenOrders()  # will find the order if it's open
time.sleep(1)
logger.debug('Finished Open Orders')

qqq = Contract()
qqq.m_symbol = CCY1
qqq.m_secType = 'CASH'
qqq.m_exchange = 'IDEALPRO'
qqq.m_currency = CCY2
logger.debug('Requesting historical data')
conn.reqHistoricalData(1, qqq, '', '60 S', '5 mins', 'Midpoint', 1, 1)
logger.debug('Returned from Reply Handler')
#qqq = Contract()
#qqq.m_symbol = 'EUR'
#qqq.m_secType = 'CASH'
#qqq.m_exchange = 'IDEALPRO'
#qqq.m_currency = 'USD'
#conn.reqHistoricalData(1, qqq, '', '60 S', '1 min', 'Midpoint', 1, 2)
##conn.reqContractDetails(1)  #TWS returns two messages  OrderStatus and Openorder  only for submitted orders or partial fills
#time.sleep(1)
Exemple #40
0
        cnx.commit()

        global Flag
        Flag = 1
        logger.debug('Flag set to 1')


while Flag == 0:
    conn = Connection.create(port=4002, clientId=999)
    conn.connect()
    logger.debug('Connecting to Server')
    time.sleep(1)
    conn.register(
        reply_handler, 'HistoricalData'
    )  #By registering "HistoricalData" --the Method name only --we can eliminate all the open order garbage
    logger.debug('Registered HistoricalData Reply Handler')
    #conn.registerall(reply_handler)
    time.sleep(1)

    qqq = Contract()
    qqq.m_symbol = 'GBP'
    qqq.m_secType = 'CASH'
    qqq.m_exchange = 'IDEALPRO'
    qqq.m_currency = 'NZD'
    logger.debug('Requesting historical data')
    conn.reqHistoricalData(1, qqq, '', '1 D', '1 day', 'Midpoint', 1, 2)
    logger.debug('Returned from Reply Handler')
    time.sleep(1)  #give IB time to send us messages
    logger.debug('Disconnecting from Server')
    conn.disconnect()
logger.debug('Finished GBPNZD Daily OHLC')
Exemple #41
0
        cnx.commit()

        global Flag
        Flag = 1
        logger.debug('Flag set to 1')


while Flag == 0:
    conn = Connection.create(port=4002, clientId=999)
    conn.connect()
    logger.debug('Connecting to Server')
    time.sleep(1)
    conn.register(
        reply_handler, 'HistoricalData'
    )  #By registering "HistoricalData" --the Method name only --we can eliminate all the open order garbage
    logger.debug('Registered HistoricalData Reply Handler')
    #conn.registerall(reply_handler)
    time.sleep(1)

    qqq = Contract()
    qqq.m_symbol = 'USD'
    qqq.m_secType = 'CASH'
    qqq.m_exchange = 'IDEALPRO'
    qqq.m_currency = 'ZAR'
    logger.debug('Requesting historical data')
    conn.reqHistoricalData(1, qqq, '', '1 D', '1 day', 'Midpoint', 1, 2)
    logger.debug('Returned from Reply Handler')
    time.sleep(1)  #give IB time to send us messages
    logger.debug('Disconnecting from Server')
    conn.disconnect()
logger.debug('Finished USDZAR Daily OHLC')
Exemple #42
0
def new_futures_contract(symbol,
                         exchange,
                         is_local_symbol,
                         expiry=None,
                         tradingClass=None,
                         currency='USD',
                         is_expired=False,
                         contract_id=0):
    ''' Make a new future contract
    The function is implemented according to http://interactivebrokers.github.io/tws-api/basic_contracts.html
    Args:
        symbol: string of a symbol or local symbol for the contract
        exchange: string of exchange name
        is_local_symbol: a True/False flag
        expiry: string; expiry month, e.g. '201610'
        tradingClass: string
    Returns:
        a new future contract object
    Raises:
        None
    '''

    if is_local_symbol is False:
        if expiry is None:
            print('new_futures_contract: get incorrect args.')
            return None

    contract = Contract()
    contract.m_secType = 'FUT'
    contract.m_exchange = exchange
    contract.m_currency = currency
    contract.m_conId = contract_id

    if is_local_symbol:
        contract.m_localSymbol = symbol  # e.g. 'VXV6', 'VXX6', 'VXZ6',
    else:
        contract.m_symbol = symbol
        contract.m_expiry = expiry

    if tradingClass is not None:
        contract.m_tradingClass = tradingClass

    if is_expired:
        contract.m_includeExpired = True

    return contract
Exemple #43
0
 def processMsg(self, msgId):
     """ generated source for method processMsg """
     if msgId == -1:
         return False
     if msgId == self.TICK_PRICE:
         version = self.readInt()
         tickerId = self.readInt()
         tickType = self.readInt()
         price = self.readDouble()
         size = 0
         if version >= 2:
             size = self.readInt()
         canAutoExecute = 0
         if version >= 3:
             canAutoExecute = self.readInt()
         self.eWrapper().tickPrice(tickerId, tickType, price,
                                   canAutoExecute)
         if version >= 2:
             #  not a tick
             sizeTickType = -1
             if tickType == 1:
                 #  BID
                 sizeTickType = 0
                 #  BID_SIZE
             elif tickType == 2:
                 #  ASK
                 sizeTickType = 3
                 #  ASK_SIZE
             elif tickType == 4:
                 #  LAST
                 sizeTickType = 5
                 #  LAST_SIZE
             if sizeTickType != -1:
                 self.eWrapper().tickSize(tickerId, sizeTickType, size)
     elif msgId == self.TICK_SIZE:
         version = self.readInt()
         tickerId = self.readInt()
         tickType = self.readInt()
         size = self.readInt()
         self.eWrapper().tickSize(tickerId, tickType, size)
     elif msgId == self.TICK_OPTION_COMPUTATION:
         version = self.readInt()
         tickerId = self.readInt()
         tickType = self.readInt()
         impliedVol = self.readDouble()
         if impliedVol < 0:  #  -1 is the "not yet computed" indicator
             impliedVol = Double.MAX_VALUE
         delta = self.readDouble()
         if abs(delta) > 1:  #  -2 is the "not yet computed" indicator
             delta = Double.MAX_VALUE
         optPrice = Double.MAX_VALUE
         pvDividend = Double.MAX_VALUE
         gamma = Double.MAX_VALUE
         vega = Double.MAX_VALUE
         theta = Double.MAX_VALUE
         undPrice = Double.MAX_VALUE
         if version >= 6 or (tickType == TickType.MODEL_OPTION):
             #  introduced in version == 5
             optPrice = self.readDouble()
             if optPrice < 0:  #  -1 is the "not yet computed" indicator
                 optPrice = Double.MAX_VALUE
             pvDividend = self.readDouble()
             if pvDividend < 0:  #  -1 is the "not yet computed" indicator
                 pvDividend = Double.MAX_VALUE
         if version >= 6:
             gamma = self.readDouble()
             if abs(gamma) > 1:  #  -2 is the "not yet computed" indicator
                 gamma = Double.MAX_VALUE
             vega = self.readDouble()
             if abs(vega) > 1:  #  -2 is the "not yet computed" indicator
                 vega = Double.MAX_VALUE
             theta = self.readDouble()
             if abs(theta) > 1:  #  -2 is the "not yet computed" indicator
                 theta = Double.MAX_VALUE
             undPrice = self.readDouble()
             if undPrice < 0:  #  -1 is the "not yet computed" indicator
                 undPrice = Double.MAX_VALUE
         self.eWrapper().tickOptionComputation(tickerId, tickType,
                                               impliedVol, delta, optPrice,
                                               pvDividend, gamma, vega,
                                               theta, undPrice)
     elif msgId == self.TICK_GENERIC:
         version = self.readInt()
         tickerId = self.readInt()
         tickType = self.readInt()
         value = self.readDouble()
         self.eWrapper().tickGeneric(tickerId, tickType, value)
     elif msgId == self.TICK_STRING:
         version = self.readInt()
         tickerId = self.readInt()
         tickType = self.readInt()
         value = self.readStr()
         self.eWrapper().tickString(tickerId, tickType, value)
     elif msgId == self.TICK_EFP:
         version = self.readInt()
         tickerId = self.readInt()
         tickType = self.readInt()
         basisPoints = self.readDouble()
         formattedBasisPoints = self.readStr()
         impliedFuturesPrice = self.readDouble()
         holdDays = self.readInt()
         futureExpiry = self.readStr()
         dividendImpact = self.readDouble()
         dividendsToExpiry = self.readDouble()
         self.eWrapper().tickEFP(tickerId, tickType, basisPoints,
                                 formattedBasisPoints, impliedFuturesPrice,
                                 holdDays, futureExpiry, dividendImpact,
                                 dividendsToExpiry)
     elif msgId == self.ORDER_STATUS:
         version = self.readInt()
         id = self.readInt()
         status = self.readStr()
         filled = self.readInt()
         remaining = self.readInt()
         avgFillPrice = self.readDouble()
         permId = 0
         if version >= 2:
             permId = self.readInt()
         parentId = 0
         if version >= 3:
             parentId = self.readInt()
         lastFillPrice = 0
         if version >= 4:
             lastFillPrice = self.readDouble()
         clientId = 0
         if version >= 5:
             clientId = self.readInt()
         whyHeld = None
         if version >= 6:
             whyHeld = self.readStr()
         self.eWrapper().orderStatus(id, status, filled, remaining,
                                     avgFillPrice, permId, parentId,
                                     lastFillPrice, clientId, whyHeld)
     elif msgId == self.ACCT_VALUE:
         version = self.readInt()
         key = self.readStr()
         val = self.readStr()
         cur = self.readStr()
         accountName = None
         if version >= 2:
             accountName = self.readStr()
         self.eWrapper().updateAccountValue(key, val, cur, accountName)
     elif msgId == self.PORTFOLIO_VALUE:
         version = self.readInt()
         contract = Contract()
         if version >= 6:
             contract.m_conId = self.readInt()
         contract.m_symbol = self.readStr()
         contract.m_secType = self.readStr()
         contract.m_expiry = self.readStr()
         contract.m_strike = self.readDouble()
         contract.m_right = self.readStr()
         if version >= 7:
             contract.m_multiplier = self.readStr()
             contract.m_primaryExch = self.readStr()
         contract.m_currency = self.readStr()
         if version >= 2:
             contract.m_localSymbol = self.readStr()
         position = self.readInt()
         marketPrice = self.readDouble()
         marketValue = self.readDouble()
         averageCost = 0.0
         unrealizedPNL = 0.0
         realizedPNL = 0.0
         if version >= 3:
             averageCost = self.readDouble()
             unrealizedPNL = self.readDouble()
             realizedPNL = self.readDouble()
         accountName = None
         if version >= 4:
             accountName = self.readStr()
         if version == 6 and self.m_parent.serverVersion() == 39:
             contract.m_primaryExch = self.readStr()
         self.eWrapper().updatePortfolio(contract, position, marketPrice,
                                         marketValue, averageCost,
                                         unrealizedPNL, realizedPNL,
                                         accountName)
     elif msgId == self.ACCT_UPDATE_TIME:
         version = self.readInt()
         timeStamp = self.readStr()
         self.eWrapper().updateAccountTime(timeStamp)
     elif msgId == self.ERR_MSG:
         version = self.readInt()
         if version < 2:
             msg = self.readStr()
             self.m_parent.error(msg)
         else:
             id = self.readInt()
             errorCode = self.readInt()
             errorMsg = self.readStr()
             self.m_parent.error(id, errorCode, errorMsg)
     elif msgId == self.OPEN_ORDER:
         #  read version
         version = self.readInt()
         #  read order id
         order = Order()
         order.m_orderId = self.readInt()
         #  read contract fields
         contract = Contract()
         if version >= 17:
             contract.m_conId = self.readInt()
         contract.m_symbol = self.readStr()
         contract.m_secType = self.readStr()
         contract.m_expiry = self.readStr()
         contract.m_strike = self.readDouble()
         contract.m_right = self.readStr()
         contract.m_exchange = self.readStr()
         contract.m_currency = self.readStr()
         if version >= 2:
             contract.m_localSymbol = self.readStr()
         #  read order fields
         order.m_action = self.readStr()
         order.m_totalQuantity = self.readInt()
         order.m_orderType = self.readStr()
         if version < 29:
             order.m_lmtPrice = self.readDouble()
         else:
             order.m_lmtPrice = self.readDoubleMax()
         if version < 30:
             order.m_auxPrice = self.readDouble()
         else:
             order.m_auxPrice = self.readDoubleMax()
         order.m_tif = self.readStr()
         order.m_ocaGroup = self.readStr()
         order.m_account = self.readStr()
         order.m_openClose = self.readStr()
         order.m_origin = self.readInt()
         order.m_orderRef = self.readStr()
         if version >= 3:
             order.m_clientId = self.readInt()
         if version >= 4:
             order.m_permId = self.readInt()
             if version < 18:
                 #  will never happen
                 #  order.m_ignoreRth =
                 self.readBoolFromInt()
             else:
                 order.m_outsideRth = self.readBoolFromInt()
             order.m_hidden = self.readInt() == 1
             order.m_discretionaryAmt = self.readDouble()
         if version >= 5:
             order.m_goodAfterTime = self.readStr()
         if version >= 6:
             #  skip deprecated sharesAllocation field
             self.readStr()
         if version >= 7:
             order.m_faGroup = self.readStr()
             order.m_faMethod = self.readStr()
             order.m_faPercentage = self.readStr()
             order.m_faProfile = self.readStr()
         if version >= 8:
             order.m_goodTillDate = self.readStr()
         if version >= 9:
             order.m_rule80A = self.readStr()
             order.m_percentOffset = self.readDoubleMax()
             order.m_settlingFirm = self.readStr()
             order.m_shortSaleSlot = self.readInt()
             order.m_designatedLocation = self.readStr()
             if self.m_parent.serverVersion() == 51:
                 self.readInt()  #  exemptCode
             elif version >= 23:
                 order.m_exemptCode = self.readInt()
             order.m_auctionStrategy = self.readInt()
             order.m_startingPrice = self.readDoubleMax()
             order.m_stockRefPrice = self.readDoubleMax()
             order.m_delta = self.readDoubleMax()
             order.m_stockRangeLower = self.readDoubleMax()
             order.m_stockRangeUpper = self.readDoubleMax()
             order.m_displaySize = self.readInt()
             if version < 18:
                 #  will never happen
                 #  order.m_rthOnly =
                 self.readBoolFromInt()
             order.m_blockOrder = self.readBoolFromInt()
             order.m_sweepToFill = self.readBoolFromInt()
             order.m_allOrNone = self.readBoolFromInt()
             order.m_minQty = self.readIntMax()
             order.m_ocaType = self.readInt()
             order.m_eTradeOnly = self.readBoolFromInt()
             order.m_firmQuoteOnly = self.readBoolFromInt()
             order.m_nbboPriceCap = self.readDoubleMax()
         if version >= 10:
             order.m_parentId = self.readInt()
             order.m_triggerMethod = self.readInt()
         if version >= 11:
             order.m_volatility = self.readDoubleMax()
             order.m_volatilityType = self.readInt()
             if version == 11:
                 receivedInt = self.readInt()
                 order.m_deltaNeutralOrderType = ("NONE" if
                                                  (receivedInt
                                                   == 0) else "MKT")
             else:
                 #  version 12 and up
                 order.m_deltaNeutralOrderType = self.readStr()
                 order.m_deltaNeutralAuxPrice = self.readDoubleMax()
                 if version >= 27 and not Util.StringIsEmpty(
                         order.m_deltaNeutralOrderType):
                     order.m_deltaNeutralConId = self.readInt()
                     order.m_deltaNeutralSettlingFirm = self.readStr()
                     order.m_deltaNeutralClearingAccount = self.readStr()
                     order.m_deltaNeutralClearingIntent = self.readStr()
             order.m_continuousUpdate = self.readInt()
             if self.m_parent.serverVersion() == 26:
                 order.m_stockRangeLower = self.readDouble()
                 order.m_stockRangeUpper = self.readDouble()
             order.m_referencePriceType = self.readInt()
         if version >= 13:
             order.m_trailStopPrice = self.readDoubleMax()
         if version >= 30:
             order.m_trailingPercent = self.readDoubleMax()
         if version >= 14:
             order.m_basisPoints = self.readDoubleMax()
             order.m_basisPointsType = self.readIntMax()
             contract.m_comboLegsDescrip = self.readStr()
         if version >= 29:
             comboLegsCount = self.readInt()
             if comboLegsCount > 0:
                 contract.m_comboLegs = []
                 i = 0
                 while i < comboLegsCount:
                     conId = self.readInt()
                     ratio = self.readInt()
                     action = self.readStr()
                     exchange = self.readStr()
                     openClose = self.readInt()
                     shortSaleSlot = self.readInt()
                     designatedLocation = self.readStr()
                     exemptCode = self.readInt()
                     comboLeg = ComboLeg(conId, ratio, action, exchange,
                                         openClose, shortSaleSlot,
                                         designatedLocation, exemptCode)
                     contract.m_comboLegs.append(comboLeg)
                     i += 1
             orderComboLegsCount = self.readInt()
             if orderComboLegsCount > 0:
                 order.m_orderComboLegs = []
                 i = 0
                 while i < orderComboLegsCount:
                     price = self.readDoubleMax()
                     orderComboLeg = OrderComboLeg(price)
                     order.m_orderComboLegs.append(orderComboLeg)
                     i += 1
         if version >= 26:
             smartComboRoutingParamsCount = self.readInt()
             if smartComboRoutingParamsCount > 0:
                 order.m_smartComboRoutingParams = []
                 i = 0
                 while i < smartComboRoutingParamsCount:
                     tagValue = TagValue()
                     tagValue.m_tag = self.readStr()
                     tagValue.m_value = self.readStr()
                     order.m_smartComboRoutingParams.append(tagValue)
                     i += 1
         if version >= 15:
             if version >= 20:
                 order.m_scaleInitLevelSize = self.readIntMax()
                 order.m_scaleSubsLevelSize = self.readIntMax()
             else:
                 #  int notSuppScaleNumComponents =
                 self.readIntMax()
                 order.m_scaleInitLevelSize = self.readIntMax()
             order.m_scalePriceIncrement = self.readDoubleMax()
         if version >= 28 and order.m_scalePriceIncrement > 0.0 and order.m_scalePriceIncrement != Double.MAX_VALUE:
             order.m_scalePriceAdjustValue = self.readDoubleMax()
             order.m_scalePriceAdjustInterval = self.readIntMax()
             order.m_scaleProfitOffset = self.readDoubleMax()
             order.m_scaleAutoReset = self.readBoolFromInt()
             order.m_scaleInitPosition = self.readIntMax()
             order.m_scaleInitFillQty = self.readIntMax()
             order.m_scaleRandomPercent = self.readBoolFromInt()
         if version >= 24:
             order.m_hedgeType = self.readStr()
             if not Util.StringIsEmpty(order.m_hedgeType):
                 order.m_hedgeParam = self.readStr()
         if version >= 25:
             order.m_optOutSmartRouting = self.readBoolFromInt()
         if version >= 19:
             order.m_clearingAccount = self.readStr()
             order.m_clearingIntent = self.readStr()
         if version >= 22:
             order.m_notHeld = self.readBoolFromInt()
         if version >= 20:
             if self.readBoolFromInt():
                 underComp = UnderComp()
                 underComp.m_conId = self.readInt()
                 underComp.m_delta = self.readDouble()
                 underComp.m_price = self.readDouble()
                 contract.m_underComp = underComp
         if version >= 21:
             order.m_algoStrategy = self.readStr()
             if not Util.StringIsEmpty(order.m_algoStrategy):
                 algoParamsCount = self.readInt()
                 if algoParamsCount > 0:
                     order.m_algoParams = []
                     i = 0
                     while i < algoParamsCount:
                         tagValue = TagValue()
                         tagValue.m_tag = self.readStr()
                         tagValue.m_value = self.readStr()
                         order.m_algoParams.append(tagValue)
                         i += 1
         orderState = OrderState()
         if version >= 16:
             order.m_whatIf = self.readBoolFromInt()
             orderState.m_status = self.readStr()
             orderState.m_initMargin = self.readStr()
             orderState.m_maintMargin = self.readStr()
             orderState.m_equityWithLoan = self.readStr()
             orderState.m_commission = self.readDoubleMax()
             orderState.m_minCommission = self.readDoubleMax()
             orderState.m_maxCommission = self.readDoubleMax()
             orderState.m_commissionCurrency = self.readStr()
             orderState.m_warningText = self.readStr()
         self.eWrapper().openOrder(order.m_orderId, contract, order,
                                   orderState)
     elif msgId == self.NEXT_VALID_ID:
         version = self.readInt()
         orderId = self.readInt()
         self.eWrapper().nextValidId(orderId)
     elif msgId == self.SCANNER_DATA:
         contract = ContractDetails()
         version = self.readInt()
         tickerId = self.readInt()
         numberOfElements = self.readInt()
         ctr = 0
         while ctr < numberOfElements:
             rank = self.readInt()
             if version >= 3:
                 contract.m_summary.m_conId = self.readInt()
             contract.m_summary.m_symbol = self.readStr()
             contract.m_summary.m_secType = self.readStr()
             contract.m_summary.m_expiry = self.readStr()
             contract.m_summary.m_strike = self.readDouble()
             contract.m_summary.m_right = self.readStr()
             contract.m_summary.m_exchange = self.readStr()
             contract.m_summary.m_currency = self.readStr()
             contract.m_summary.m_localSymbol = self.readStr()
             contract.m_marketName = self.readStr()
             contract.m_tradingClass = self.readStr()
             distance = self.readStr()
             benchmark = self.readStr()
             projection = self.readStr()
             legsStr = None
             if version >= 2:
                 legsStr = self.readStr()
             self.eWrapper().scannerData(tickerId, rank, contract, distance,
                                         benchmark, projection, legsStr)
             ctr += 1
         self.eWrapper().scannerDataEnd(tickerId)
     elif msgId == self.CONTRACT_DATA:
         version = self.readInt()
         reqId = -1
         if version >= 3:
             reqId = self.readInt()
         contract = ContractDetails()
         contract.m_summary.m_symbol = self.readStr()
         contract.m_summary.m_secType = self.readStr()
         contract.m_summary.m_expiry = self.readStr()
         contract.m_summary.m_strike = self.readDouble()
         contract.m_summary.m_right = self.readStr()
         contract.m_summary.m_exchange = self.readStr()
         contract.m_summary.m_currency = self.readStr()
         contract.m_summary.m_localSymbol = self.readStr()
         contract.m_marketName = self.readStr()
         contract.m_tradingClass = self.readStr()
         contract.m_summary.m_conId = self.readInt()
         contract.m_minTick = self.readDouble()
         contract.m_summary.m_multiplier = self.readStr()
         contract.m_orderTypes = self.readStr()
         contract.m_validExchanges = self.readStr()
         if version >= 2:
             contract.m_priceMagnifier = self.readInt()
         if version >= 4:
             contract.m_underConId = self.readInt()
         if version >= 5:
             contract.m_longName = self.readStr()
             contract.m_summary.m_primaryExch = self.readStr()
         if version >= 6:
             contract.m_contractMonth = self.readStr()
             contract.m_industry = self.readStr()
             contract.m_category = self.readStr()
             contract.m_subcategory = self.readStr()
             contract.m_timeZoneId = self.readStr()
             contract.m_tradingHours = self.readStr()
             contract.m_liquidHours = self.readStr()
         if version >= 8:
             contract.m_evRule = self.readStr()
             contract.m_evMultiplier = self.readDouble()
         if version >= 7:
             secIdListCount = self.readInt()
             if secIdListCount > 0:
                 contract.m_secIdList = []
                 i = 0
                 while i < secIdListCount:
                     tagValue = TagValue()
                     tagValue.m_tag = self.readStr()
                     tagValue.m_value = self.readStr()
                     contract.m_secIdList.append(tagValue)
                     i += 1
         self.eWrapper().contractDetails(reqId, contract)
     elif msgId == self.BOND_CONTRACT_DATA:
         version = self.readInt()
         reqId = -1
         if version >= 3:
             reqId = self.readInt()
         contract = ContractDetails()
         contract.m_summary.m_symbol = self.readStr()
         contract.m_summary.m_secType = self.readStr()
         contract.m_cusip = self.readStr()
         contract.m_coupon = self.readDouble()
         contract.m_maturity = self.readStr()
         contract.m_issueDate = self.readStr()
         contract.m_ratings = self.readStr()
         contract.m_bondType = self.readStr()
         contract.m_couponType = self.readStr()
         contract.m_convertible = self.readBoolFromInt()
         contract.m_callable = self.readBoolFromInt()
         contract.m_putable = self.readBoolFromInt()
         contract.m_descAppend = self.readStr()
         contract.m_summary.m_exchange = self.readStr()
         contract.m_summary.m_currency = self.readStr()
         contract.m_marketName = self.readStr()
         contract.m_tradingClass = self.readStr()
         contract.m_summary.m_conId = self.readInt()
         contract.m_minTick = self.readDouble()
         contract.m_orderTypes = self.readStr()
         contract.m_validExchanges = self.readStr()
         if version >= 2:
             contract.m_nextOptionDate = self.readStr()
             contract.m_nextOptionType = self.readStr()
             contract.m_nextOptionPartial = self.readBoolFromInt()
             contract.m_notes = self.readStr()
         if version >= 4:
             contract.m_longName = self.readStr()
         if version >= 6:
             contract.m_evRule = self.readStr()
             contract.m_evMultiplier = self.readDouble()
         if version >= 5:
             secIdListCount = self.readInt()
             if secIdListCount > 0:
                 contract.m_secIdList = []
                 i = 0
                 while i < secIdListCount:
                     tagValue = TagValue()
                     tagValue.m_tag = self.readStr()
                     tagValue.m_value = self.readStr()
                     contract.m_secIdList.append(tagValue)
                     i += 1
         self.eWrapper().bondContractDetails(reqId, contract)
     elif msgId == self.EXECUTION_DATA:
         version = self.readInt()
         reqId = -1
         if version >= 7:
             reqId = self.readInt()
         orderId = self.readInt()
         contract = Contract()
         #  read contract fields
         if version >= 5:
             contract.m_conId = self.readInt()
         contract.m_symbol = self.readStr()
         contract.m_secType = self.readStr()
         contract.m_expiry = self.readStr()
         contract.m_strike = self.readDouble()
         contract.m_right = self.readStr()
         if version >= 9:
             contract.m_multiplier = self.readStr()
         contract.m_exchange = self.readStr()
         contract.m_currency = self.readStr()
         contract.m_localSymbol = self.readStr()
         exec_ = Execution()
         exec_.m_orderId = orderId
         exec_.m_execId = self.readStr()
         exec_.m_time = self.readStr()
         exec_.m_acctNumber = self.readStr()
         exec_.m_exchange = self.readStr()
         exec_.m_side = self.readStr()
         exec_.m_shares = self.readInt()
         exec_.m_price = self.readDouble()
         if version >= 2:
             exec_.m_permId = self.readInt()
         if version >= 3:
             exec_.m_clientId = self.readInt()
         if version >= 4:
             exec_.m_liquidation = self.readInt()
         if version >= 6:
             exec_.m_cumQty = self.readInt()
             exec_.m_avgPrice = self.readDouble()
         if version >= 8:
             exec_.m_orderRef = self.readStr()
         if version >= 9:
             exec_.m_evRule = self.readStr()
             exec_.m_evMultiplier = self.readDouble()
         self.eWrapper().execDetails(reqId, contract, exec_)
     elif msgId == self.MARKET_DEPTH:
         version = self.readInt()
         id = self.readInt()
         position = self.readInt()
         operation = self.readInt()
         side = self.readInt()
         price = self.readDouble()
         size = self.readInt()
         self.eWrapper().updateMktDepth(id, position, operation, side,
                                        price, size)
     elif msgId == self.MARKET_DEPTH_L2:
         version = self.readInt()
         id = self.readInt()
         position = self.readInt()
         marketMaker = self.readStr()
         operation = self.readInt()
         side = self.readInt()
         price = self.readDouble()
         size = self.readInt()
         self.eWrapper().updateMktDepthL2(id, position, marketMaker,
                                          operation, side, price, size)
     elif msgId == self.NEWS_BULLETINS:
         version = self.readInt()
         newsMsgId = self.readInt()
         newsMsgType = self.readInt()
         newsMessage = self.readStr()
         originatingExch = self.readStr()
         self.eWrapper().updateNewsBulletin(newsMsgId, newsMsgType,
                                            newsMessage, originatingExch)
     elif msgId == self.MANAGED_ACCTS:
         version = self.readInt()
         accountsList = self.readStr()
         self.eWrapper().managedAccounts(accountsList)
     elif msgId == self.RECEIVE_FA:
         version = self.readInt()
         faDataType = self.readInt()
         xml = self.readStr()
         self.eWrapper().receiveFA(faDataType, xml)
     elif msgId == self.HISTORICAL_DATA:
         version = self.readInt()
         reqId = self.readInt()
         startDateStr = ""
         endDateStr = ""
         completedIndicator = "finished"
         if version >= 2:
             startDateStr = self.readStr()
             endDateStr = self.readStr()
             completedIndicator += "-" + startDateStr + "-" + endDateStr
         itemCount = self.readInt()
         ctr = 0
         while ctr < itemCount:
             date = self.readStr()
             open = self.readDouble()
             high = self.readDouble()
             low = self.readDouble()
             close = self.readDouble()
             volume = self.readInt()
             WAP = self.readDouble()
             hasGaps = self.readStr()
             barCount = -1
             if version >= 3:
                 barCount = self.readInt()
             self.eWrapper().historicalData(
                 reqId, date, open, high, low, close, volume, barCount, WAP,
                 Boolean.valueOf(hasGaps).booleanValue())
             ctr += 1
         #  send end of dataset marker
         self.eWrapper().historicalData(reqId, completedIndicator, -1, -1,
                                        -1, -1, -1, -1, -1, False)
     elif msgId == self.SCANNER_PARAMETERS:
         version = self.readInt()
         xml = self.readStr()
         self.eWrapper().scannerParameters(xml)
     elif msgId == self.CURRENT_TIME:
         # int version =
         self.readInt()
         time = self.readLong()
         self.eWrapper().currentTime(time)
     elif msgId == self.REAL_TIME_BARS:
         # int version =
         self.readInt()
         reqId = self.readInt()
         time = self.readLong()
         open = self.readDouble()
         high = self.readDouble()
         low = self.readDouble()
         close = self.readDouble()
         volume = self.readLong()
         wap = self.readDouble()
         count = self.readInt()
         self.eWrapper().realtimeBar(reqId, time, open, high, low, close,
                                     volume, wap, count)
     elif msgId == self.FUNDAMENTAL_DATA:
         # int version =
         self.readInt()
         reqId = self.readInt()
         data = self.readStr()
         self.eWrapper().fundamentalData(reqId, data)
     elif msgId == self.CONTRACT_DATA_END:
         # int version =
         self.readInt()
         reqId = self.readInt()
         self.eWrapper().contractDetailsEnd(reqId)
     elif msgId == self.OPEN_ORDER_END:
         # int version =
         self.readInt()
         self.eWrapper().openOrderEnd()
     elif msgId == self.ACCT_DOWNLOAD_END:
         # int version =
         self.readInt()
         accountName = self.readStr()
         self.eWrapper().accountDownloadEnd(accountName)
     elif msgId == self.EXECUTION_DATA_END:
         # int version =
         self.readInt()
         reqId = self.readInt()
         self.eWrapper().execDetailsEnd(reqId)
     elif msgId == self.DELTA_NEUTRAL_VALIDATION:
         # int version =
         self.readInt()
         reqId = self.readInt()
         underComp = UnderComp()
         underComp.m_conId = self.readInt()
         underComp.m_delta = self.readDouble()
         underComp.m_price = self.readDouble()
         self.eWrapper().deltaNeutralValidation(reqId, underComp)
     elif msgId == self.TICK_SNAPSHOT_END:
         # int version =
         self.readInt()
         reqId = self.readInt()
         self.eWrapper().tickSnapshotEnd(reqId)
     elif msgId == self.MARKET_DATA_TYPE:
         # int version =
         self.readInt()
         reqId = self.readInt()
         marketDataType = self.readInt()
         self.eWrapper().marketDataType(reqId, marketDataType)
     elif msgId == self.COMMISSION_REPORT:
         # int version =
         self.readInt()
         commissionReport = CommissionReport()
         commissionReport.m_execId = self.readStr()
         commissionReport.m_commission = self.readDouble()
         commissionReport.m_currency = self.readStr()
         commissionReport.m_realizedPNL = self.readDouble()
         commissionReport.m_yield = self.readDouble()
         commissionReport.m_yieldRedemptionDate = self.readInt()
         self.eWrapper().commissionReport(commissionReport)
     else:
         self.m_parent.error(EClientErrors.NO_VALID_ID,
                             EClientErrors.UNKNOWN_ID.code(),
                             EClientErrors.UNKNOWN_ID.msg())
         return False
     self.eWrapper().end_of_execution = True
     # print self.eWrapper().end_of_execution, msgId
     return True
Exemple #44
0

def historical_data_handler(msg):
    # The response data callback function
    # print (msg.reqId, msg.date, msg.open, msg.close, msg.high, msg.low)
    print(msg)


if __name__ == '__main__':
    # Establish IB connection, make sure you have the correct port, clientId
    conn = ibConnection(host='127.0.0.1', port=7497, clientId=999)

    # Register the response callback function and type of data to be returned
    conn.register(historical_data_handler, message.historicalData)
    conn.registerAll(all_message_handler)
    conn.connect()

    # Establish a Contract object and the params for the request
    req = Contract()
    req.m_secType = "CFD"
    req.m_symbol = "IBDE30"
    req.m_currency = "EUR"
    req.m_exchange = "SMART"
    req.m_primaryExch = "SMART"
    endtime = strftime('%Y%m%d %H:%M:%S')
    conn.reqHistoricalData(1, req, endtime, "14 D", "1 min", "BID", 1, 1)

    # Make sure the connection don't get disconnected prior the response data return
    sleep(5)
    conn.disconnect()
Exemple #45
0
def makeOptContract(sym, exp, strike, right):
    """ exp should be in (year/month/day) """
    newOptContract = Contract()
    newOptContract.m_symbol = sym
    newOptContract.m_secType = 'OPT'
    newOptContract.m_expiry = exp
    newOptContract.m_strike = strike
    newOptContract.m_right = right
    newOptContract.m_multiplier = 100
    newOptContract.m_exchange = 'SMART'
    newOptContract.m_primaryExch = 'SMART'
    newOptContract.m_currency = 'USD'
    return newOptContract
Exemple #46
0
    contract.m_secType = sec_type
    contract.m_exchange = exch
    contract.m_primaryExch = prim_exch
    contract.m_currency = curr
    return contract


def create_order(order_type, quantity, action):
    order = Order()
    order.m_orderType = order_type
    order.m_totalQuantity = quantity
    order.m_action = action
    return order


contract = Contract()
contract.symbol = "FISV"
contract.secType = "OPT"
contract.exchange = "SMART"
contract.currency = "USD"


class TestWrapper(wrapper.EWrapper):
    def historicalData(self, reqId: TickerId, date: str, open: float,
                       high: float, low: float, close: float, volume: int,
                       barCount: int, WAP: float, hasGaps: int):
        super().historicalData(reqId, date, open, high, low, close, volume,
                               barCount, WAP, hasGaps)
        print("HistoricalData. ", reqId, " Date:", date, "Open:", open,
              "High:", high, "Low:", low, "Close:", close, "Volume:", volume,
              barCount, "WAP:", WAP, "HasGaps:", hasGaps)
Exemple #47
0
        cnx.commit()

        global Flag
        Flag = 1
        logger.debug('Flag set to 1')


while Flag == 0:
    conn = Connection.create(port=4002, clientId=999)
    conn.connect()
    logger.debug('Connecting to Server')
    time.sleep(1)
    conn.register(
        reply_handler, 'HistoricalData'
    )  #By registering "HistoricalData" --the Method name only --we can eliminate all the open order garbage
    logger.debug('Registered HistoricalData Reply Handler')
    #conn.registerall(reply_handler)
    time.sleep(1)

    qqq = Contract()
    qqq.m_symbol = 'EUR'
    qqq.m_secType = 'CASH'
    qqq.m_exchange = 'IDEALPRO'
    qqq.m_currency = 'AUD'
    logger.debug('Requesting historical data')
    conn.reqHistoricalData(1, qqq, '', '1 D', '1 day', 'Midpoint', 1, 2)
    logger.debug('Returned from Reply Handler')
    time.sleep(1)  #give IB time to send us messages
    logger.debug('Disconnecting from Server')
    conn.disconnect()
logger.debug('Finished EURAUD Daily OHLC')
Exemple #48
0
conn.register(reply_handler, 'Position')
conn.register(reply_handler_Orders, 'OpenOrder')
conn.register(reply_handler_Status, 'OrderStatus')
conn.register(reply_handler2, 'HistoricalData')
#conn.register(reply_handler_contract, 'Contract')
logger.debug('Requesting Positions')
conn.reqPositions()  # will find the order if it was filled
logger.debug('Finished Positions')
time.sleep(1)
logger.debug('Requesting Open Orders')
conn.reqAllOpenOrders()  # will find the order if it's open
time.sleep(1)
logger.debug('Finished Open Orders')

qqq = Contract()
qqq.m_symbol = CCY1 + CCY2
qqq.m_localSymbol = CCY1 + CCY2 + datalink.monthcode + "7"
qqq.m_secType = 'FUT'
qqq.m_exchange = 'GLOBEX'
qqq.m_currency = 'USD'
qqq.m_expiry = datalink.exp_quarter
logger.debug('Requesting historical data')

conn.reqHistoricalData(1, qqq, '', '60 S', '5 mins', 'ASK', 0, 1)
logger.debug('Returned from HISTORICAL DATA')
#qqq = Contract()
#qqq.m_symbol = 'EUR'
#qqq.m_secType = 'CASH'
#qqq.m_exchange = 'IDEALPRO'
#qqq.m_currency = 'USD'
Exemple #49
0
 def reqMktData(self):
     contract = Contract() #
     contract.m_symbol = 'QQQQ'
     contract.m_secType = 'STK'
     contract.m_exchange = 'SMART'
     self.connection.reqMktData(1, contract, '', False)
Exemple #50
0
#csv_f = csv.reader(f)
#for row in csv_f:
#    print(row)

data = pd.read_csv('dow.csv')
print(data)
conn = Connection.create(port=4002, clientId=999)
conn.connect()
logger.debug('Connecting to Server')
time.sleep(1)
conn.register(
    reply_handler, 'HistoricalData'
)  #By registering "HistoricalData" --the Method name only --we can eliminate all the open order garbage
logger.debug('Registered HistoricalData Reply Handler')
#conn.registerall(reply_handler)
time.sleep(1)

qqq = Contract()
qqq.m_symbol = 'SPY'
#qqq.m_localSymbol = 'ES'+ datalink.monthcode + '8'
#qqq.ConId = 279555803
qqq.m_secType = 'STK'
qqq.m_exchange = 'SMART'  #NASDAQ defined as ISLAND by IB API
qqq.m_currency = 'USD'
logger.debug('Requesting historical data')
conn.reqHistoricalData(1, qqq, '', '1 D', '1 day', 'ASK', 0, 1)
logger.debug('Returned from Reply Handler')
time.sleep(1)  #give IB time to send us messages
logger.debug('Disconnecting from Server')
conn.disconnect()
logger.debug('Finished RSB dataframe')
Exemple #51
0
		if i not in s:
			s.append(i)
	s.insert(0,'Script, DateTime, Open, High, Low, Close, Volume, WAP, Count')
	for item in s:
		csvfile.write('%s \n' % item)
	csvfile.close()


tws = ibConnection()
tws.register(my_callback_handler, message.historicalData)
tws.connect()

symbol_id = 0
for i in new_symbolinput:
	print(i)
	c = Contract()
	c.m_symbol = i
	c.m_secType = "IND"
	c.m_exchange = "NSE"
	c.m_currency = "INR"
	number_of_days = 2600
	for day in range(0,number_of_days,2):
		time = datetime.now() - relativedelta(days=(2600 - day))
		endtime = time.strftime('%Y%m%d %H:%M:%S')
		#for reference http://www.inside-r.org/packages/cran/IBrokers/docs/reqHistoricalData
		#for data limitation https://www.interactivebrokers.com/en/software/api/apiguide/tables/historical_data_limitations.htm
		tws.reqHistoricalData(symbol_id,contract=c,endDateTime=endtime,
            durationStr='2 D',
            barSizeSetting='1 min',
            whatToShow='TRADES',
            useRTH=1,
Exemple #52
0
    def submitOrder(self, order):
        if order.isInitial():

            ibContract = Contract()
            ibOrder = Order()

            ibContract.m_symbol = order.getInstrument()


            ibContract.m_secType = self.__marketOptions['assetType']
            ibContract.m_currency = self.__marketOptions['currency']
            ibContract.m_exchange = self.__marketOptions['routing']

            ibOrder.m_totalQuantity = order.getInstrumentTraits().roundQuantity(order.getQuantity())
            if order.getAction() == (broker.Order.Action.BUY or broker.Order.Action.BUY_TO_COVER):
                ibOrder.m_action = 'BUY'
            elif order.getAction() == broker.Order.Action.SELL:
                ibOrder.m_action = 'SELL'
            elif order.getAction() == broker.Order.Action.SELL_SHORT:
                ibOrder.m_action = 'SELL'

            if order.getType() == broker.Order.Type.MARKET:                
                if order.getFillOnClose():
                    ibOrder.m_orderType = 'MOC'
                else:
                    ibOrder.m_orderType = 'MKT'
            elif order.getType() == broker.Order.Type.LIMIT:
                ibOrder.m_orderType = 'LMT'
                ibOrder.m_lmtPrice = order.getInstrumentTraits().roundPrice(order.getLimitPrice())
            elif order.getType() == broker.Order.Type.STOP:
                ibOrder.m_orderType = 'STP'
                ibOrder.m_auxPrice = order.getInstrumentTraits().roundPrice(order.getStopPrice())
            elif order.getType() == broker.Order.Type.STOP_LIMIT:
                ibOrder.m_orderType = 'STP LMT'
                ibOrder.m_lmtPrice = order.getInstrumentTraits().roundPrice(order.getLimitPrice())
                ibOrder.m_auxPrice = order.getInstrumentTraits().roundPrice(order.getStopPrice())

            

            if order.getAllOrNone() == True:
                ibOrder.m_allOrNone = 1
            else:
                ibOrder.m_allOrNone = 0


            if order.getGoodTillCanceled() == True:
                ibOrder.m_tif = 'GTC'
            else:
                ibOrder.m_tif = 'DAY'

            self.__ib.placeOrder(self.__nextOrderId, ibContract, ibOrder)

            order.setSubmitted(self.__nextOrderId, datetime.datetime.now())
            
            self.__nextOrderId += 1

            self._registerOrder(order)
            # Switch from INITIAL -> SUBMITTED
            # IMPORTANT: Do not emit an event for this switch because when using the position interface
            # the order is not yet mapped to the position and Position.onOrderUpdated will get called.
            order.switchState(broker.Order.State.SUBMITTED)
        else:
            raise Exception("The order was already processed")
Exemple #53
0
from ib.opt import ibConnection


def price_tick_handler(msg):
    """ function to handle price ticks """
    print(msg)


#--------------main script------------------
import ib
print('ibpy version:', ib.__version__)
tws = ibConnection()  # create connection object
tws.enableLogging()  # show debugging output from ibpy
tws.register(price_tick_handler, 'tickPrice')  # register handler
tws.connect()  # connect to API

#-------create contract and subscribe to data
c = Contract()
c.m_symbol = "SPY"
c.m_secType = "STK"
c.m_exchange = "SMART"
c.m_currency = "USD"

tws.reqMktData(1, c, "", False)  # request market data

#-------print data for a couple of seconds, then close
sleep(10)

print('All done')

tws.disconnect()
Exemple #54
0
 def _create_contract(symbol):
     contract = Contract()
     contract.m_symbol = symbol
     contract.m_secType = 'STK'
     return contract