コード例 #1
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
コード例 #2
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
コード例 #3
0
 def __init__(self):
     self.xq = easytrader.use('xq')
     self.xq.prepare('config/xq3.json')
     self.xq.set_attr("portfolio_code", "ZH776826")
     self.logger = get_logger(HISTORY_OPERATION_XQ)
     self.db_xq = MongoDB(XUEQIU_DB_NAME)
     # self.db_ib = MongoDB(IB_DB_NAME)
     self.last_trade_time = get_trade_date_series("US")
     self.trade_time = get_date_now("US")
     self.callback = IBWrapper()
     self.ibcontract = IBcontract()
     self.ibcontract.secType = "STK"
     self.ibcontract.exchange = "SMART"
     self.ibcontract.currency = "USD"
     self.client = IBclient(self.callback)
     self.position_ib = PorfolioPosition(IB_DB_NAME, IB_POSITION)
コード例 #4
0
ファイル: orders_methods.py プロジェクト: OZ-T/voltrad1
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)
コード例 #5
0
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 = "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
コード例 #6
0
ファイル: orders_methods.py プロジェクト: OZ-T/voltrad1
def list_spread_prices_before_trade(symbol, expiry, query):
    """
    List option spread prices before trade
    """
    query1 = query.split(",")
    client, log_order = init_func()
    underl = {}

    for idx, x in enumerate(query1):
        underl[idx] = RequestOptionData(
            symbol,
            get_contract_details(symbol)["secType"],
            expiry,
            float(x[1:]),
            x[:1],
            get_contract_details(symbol)["multiplier"],
            get_contract_details(symbol)["exchange"],
            get_contract_details(symbol)["currency"],
            idx,
            comboLegs=None)
    action1 = {0: "BUY", 1: "SELL"}
    list_results = client.getOptionsChain(underl)
    legs = []
    log_order.info("Number of requests [%d]" % (len(list_results)))
    for reqId, request in list_results.items():
        log_order.info(
            "Requestid [%d]: Option[%s] Results [%d]" %
            (reqId, str(request.get_in_data()), len(request.optionsChain)))
        for opt1 in request.optionsChain:
            leg1 = sy.ComboLeg()
            leg1.conId = opt1['conId']
            leg1.ratio = get_order_defaults()["ratio"]
            leg1.action = action1[reqId]
            leg1.exchange = opt1['exchange']
            legs.append(leg1)

    ibcontract = IBcontract()
    ibcontract.comboLegs = sy.ComboLegList(legs)
    ibcontract.symbol = symbol
    ibcontract.secType = "BAG"  # BAG is the security type for COMBO order
    ibcontract.exchange = get_contract_details(symbol)["exchange"]
    ibcontract.currency = get_contract_details(symbol)["currency"]

    ctrt = {}
    ctrt[100] = RequestOptionData(symbol,
                                  get_contract_details(symbol)["secType"],
                                  expiry,
                                  float(x[1:]),
                                  x[:1],
                                  get_contract_details(symbol)["multiplier"],
                                  get_contract_details(symbol)["exchange"],
                                  get_contract_details(symbol)["currency"],
                                  100,
                                  comboLegs=None,
                                  contract=ibcontract)
    ctrt_prc = client.getMktData(ctrt)
    log_order.info("[%s]" % (str(ctrt_prc)))
    df1 = pd.DataFrame()
    #for id, req1 in ctrt_prc.iteritems():
    #    subset_dic = {k: req1.get_in_data()[k] for k in ('secType','symbol','comboLegsDescrip')}
    #    subset_dic2 = {k: req1.get_out_data()[id][k] for k in ('bidPrice', 'bidSize', 'askPrice', 'askSize') }
    #    dict1 = subset_dic.copy()
    #    dict1.update(subset_dic2)
    #    temp=pd.DataFrame.from_dict(dict1, orient='index').transpose()
    #    df1=df1.append(temp)

    row1 = 0
    for reqId, request in ctrt_prc.items():
        row1 += 1
        dict1 = request.get_in_data().copy()
        if reqId in request.get_out_data():
            dict1.update(request.get_out_data()[reqId])
        for key in dict1.keys():
            df1.loc[row1, key] = dict1[key]

    df1 = df1.set_index(['secType', 'symbol', 'comboLegsDescrip'], drop=True)

    columns = [
        'bidPrice', 'bidSize', 'askPrice', 'askSize', '', 'modelDelta',
        'modelImpliedVol', 'lastUndPrice', 'modelGamma', 'closePrice'
    ]
    cols = [val for val in columns if val in df1.columns]
    print(df1[cols])

    end_func(client=client)
コード例 #7
0
ファイル: orders_methods.py プロジェクト: OZ-T/voltrad1
def place_or_modif_spread_order(expiry, symbol, right, strike_l, strike_s,
                                orderType, quantity, lmtPrice, orderId):
    """
    Place new option spread order or modify existing order orderType="LMT"
    Put orderId <= 0 if new order
    """
    """
    Modification of an open order through the API can be achieved by the same client which placed the original order.
    In the case of orders placed manually in TWS, the order can be modified by the client with ID 0.

    To modify an order, simply call the IBApi.EClient.placeOrder function again with the same parameters used to place
    the original order, except for the changed parameter. This includes the IBApi.Order.OrderId, which must match the
    IBApi.Order.OrderId of the original. It is not generally recommended to try to change order parameters other than
    the order price and order size. To change other parameters, it might be preferable to cancel the original order
    and place a new order.
    """
    # http://interactivebrokers.github.io/tws-api/modifying_orders.html#gsc.tab=0

    if orderId <= 0:
        orderId = None
    client, log_order = init_func()
    log_order.info("placing order ")
    underl = {
        1001:
        RequestOptionData(symbol,
                          get_contract_details(symbol)["secType"], expiry,
                          strike_l, right,
                          get_contract_details(symbol)["multiplier"],
                          get_contract_details(symbol)["exchange"],
                          get_contract_details(symbol)["currency"], 1001),
        1002:
        RequestOptionData(symbol,
                          get_contract_details(symbol)["secType"], expiry,
                          strike_s, right,
                          get_contract_details(symbol)["multiplier"],
                          get_contract_details(symbol)["exchange"],
                          get_contract_details(symbol)["currency"], 1002)
    }
    action1 = {1001: "BUY", 1002: "SELL"}
    list_results = client.getOptionsChain(underl)
    legs = []
    log_order.info("Number of requests [%d]" % (len(list_results)))
    for reqId, request in list_results.items():
        log_order.info(
            "Requestid [%d]: Option[%s] Results [%d]" %
            (reqId, str(request.get_in_data()), len(request.optionsChain)))
        for opt1 in request.optionsChain:
            leg1 = sy.ComboLeg()
            leg1.conId = opt1['conId']
            leg1.ratio = get_order_defaults()["ratio"]
            leg1.action = action1[reqId]
            leg1.exchange = opt1['exchange']
            legs.append(leg1)
    #sy.Contract.comboLegs
    ibcontract = IBcontract()
    ibcontract.comboLegs = sy.ComboLegList(legs)
    ibcontract.symbol = symbol
    ibcontract.secType = "BAG"  # BAG is the security type for COMBO order
    ibcontract.exchange = get_contract_details(symbol)["exchange"]
    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)