当前位置: 首页>>代码示例>>Python>>正文


Python EPosixClientSocket.reqHistoricalData方法代码示例

本文整理汇总了Python中swigibpy.EPosixClientSocket.reqHistoricalData方法的典型用法代码示例。如果您正苦于以下问题:Python EPosixClientSocket.reqHistoricalData方法的具体用法?Python EPosixClientSocket.reqHistoricalData怎么用?Python EPosixClientSocket.reqHistoricalData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在swigibpy.EPosixClientSocket的用法示例。


在下文中一共展示了EPosixClientSocket.reqHistoricalData方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Contract

# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import reqHistoricalData [as 别名]
# Simple contract for DELL
dell = Contract()
dell.exchange = "SMART"
dell.symbol = "DELL"
dell.secType = "STK"
dell.currency = "USD"
today = datetime.today()

print "Requesting historical data for %s" % dell.symbol

# Request some historical data. 
tws.reqHistoricalData(
        1,                                          #tickerId, 
        dell,                                       #contract, 
        today.strftime("%Y%m%d %H:%M:%S %Z"),       #endDateTime, 
        "1 W",                                      #durationStr, 
        "1 day",                                    #barSizeSetting, 
        "TRADES",                                   #whatToShow, 
        0,                                          #useRTH, 
        1                                           #formatDate
    )


print "\n====================================================================="
print " History requested, waiting for TWS responses"
print "=====================================================================\n"
    
    
print "******************* Press ENTER to quit when done *******************\n"
raw_input()

print "\nDisconnecting..."
开发者ID:ashokez,项目名称:swigibpy,代码行数:34,代码来源:historicaldata.py

示例2: RuntimeError

# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import reqHistoricalData [as 别名]
# Connect to tws running on localhost
if not tws.eConnect("", 7496, 42):
    raise RuntimeError('Failed to connect to TWS')

today = datetime.today()

for index, row in contractlist.iterrows():
    print 'Index:', index, ', Sym:', row['sym']
    #self.reqMktData(index, create_contract(row['sym']), '233', False)
    # Request some historical data.
    tws.reqHistoricalData(
        index,                                        # tickerId,
        create_contract(row['sym']),                                   # contract,
        today.strftime("%Y%m%d %H:%M:%S %Z"),       # endDateTime,
        "1 W",                                      # durationStr,
        "1 day",                                    # barSizeSetting,
        "TRADES",                                   # whatToShow,
        useRTH,                                          # useRTH,
        1,                                          # formatDate
        None                                        # chartOptions
    )

print("\n====================================================================")
print(" History requested, waiting %ds for TWS responses" % WAIT_TIME)
print("====================================================================\n")


try:
    callback.got_history.wait(timeout=WAIT_TIME)
    print symbols
except KeyboardInterrupt:
开发者ID:border,项目名称:quantway,代码行数:33,代码来源:kv_scan.py

示例3: error

# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import reqHistoricalData [as 别名]
    def error(self, id, errCode, errString):
        global clientid
        global tws
        global connection_state
        global pacing
        global last_time
        global cooldowntime

        s = "IB[{}]: {}".format(errCode, errString)
        if id > -1:
            s += " (ID: {})".format(id)
        logging.debug(s)

        if errCode == ErrorCode.clientid_in_use:
            logging.info("Client ID {} in use, reconnecting ...".format(clientid))
            clientid += 1
            tws = EPosixClientSocket(self)
            tws.eConnect("", 7496, clientid)
        elif errCode == ErrorCode.md_connection_ok:
            logging.info("IB[{}]: {}".format(errCode, errString))
            api_started.set()
        # TODO: use a better string here!
        elif errCode == ErrorCode.historical_data_error and "Historical data request pacing violation" in errString:
            logging.info("Historical data pacing violation: retrying last batch and start using pacing between data requests...")
            logging.info(errString)
            if not pacing:
                pacing = 10
            dt = prev_last_time.strftime("%Y%m%d %H:%M:%S")
            logging.info("Cooling down for {} seconds...".format(cooldowntime))
            sleep(cooldowntime)
            cooldowntime += 15 #  sometimes we just need to cool down for a longer time
            tws.reqHistoricalData(0, contract, dt, duration, barsize, datatype, rth_only, 1)
        elif errCode == ErrorCode.historical_data_error and "invalid step" in errString:
            logging.info("IB[{}]: {}".format(errCode, errString))
            historical_data_received.set()
        elif errCode == ErrorCode.historical_data_error and "HMDS query returned no data" in errString:
            logging.info("IB[{}]: {}".format(errCode, errString))
            historical_data_received.set()
        elif (errCode == ErrorCode.historical_data_error and "Trader Workstation exited" in errString) or \
                errCode == ErrorCode.cannot_connect_to_tws:
            logging.info("IB[{}]: {}".format(errCode, errString))
            tws.exited = True
            historical_data_received.set()
        # requesting historical data from period too long time ago
        elif errCode == ErrorCode.error_validating_request and "Historical data queries on this contract requesting any data earlier than" in errString:
            dt = prev_last_time.strftime(dt_format)
            logging.info("IB cannot provide data from period ending {}, it's too far back in the history.".format(dt))
            historical_data_received.set()
        elif errCode == ErrorCode.error_validating_request:
            s = "IB[{}]: {}".format(errCode, errString)
            if id > -1:
                s += " (ID: {})".format(id)
            logging.fatal(s)
            historical_data_received.set()
        elif errCode == ErrorCode.connection_lost:
            # TODO: some logic to retry after connection has been momentarily lost, and eventually give up...
            logging.info("Connection lost, saving data end aborting...")
            if not output_file:
                sys.exit(ExitCode.error_can_continue)
            historical_data_received.set()
        elif errCode == ErrorCode.no_security_def_found:
            logging.info("IB[{}]: {}".format(errCode, errString))
            if not output_file:
                sys.exit(ExitCode.error_can_continue)
            historical_data_received.set()
        else:
            s = "IB[{}]: {}".format(errCode, errString)
            if id > -1:
                s += " (ID: {})".format(id)
            logging.info(s)
开发者ID:azyr,项目名称:jtsdownloader,代码行数:72,代码来源:jtsdownloader.py

示例4: open

# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import reqHistoricalData [as 别名]
        filename = args.o
    else:
        filename = "{}_{}_{}.csv".format(contract_to_string(contract), barsize.replace(" ", ""), datatype)
    output_file = open(filename, 'w')


    s = "Receiving {} batches of historical data...".format(num_requests)
    if num_requests > 1 and pacing:
        s += " {} seconds remaining".format((num_requests - num_batches_received) * pacing)
    logging.info(s)
    prev_last_time = endtime

    if tws.exited:
        sys.exit(2)

    tws.reqHistoricalData(0, contract, endtime.strftime("%Y%m%d %H:%M:%S"), duration, barsize, datatype, rth_only, 1)
    historical_data_received.wait()


    if output_file.tell() > 0: #  file not empty
        logging.info("Reversing the output file...")

        output_file.close()

        with open(filename, 'r') as input_file:
            lines = input_file.readlines()

        lines.reverse()
        with open(filename, 'w') as output_file:
            for line in lines:
                output_file.write(line)
开发者ID:azyr,项目名称:jtsdownloader,代码行数:33,代码来源:jtsdownloader.py

示例5: Contract

# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import reqHistoricalData [as 别名]
# Connect to tws running on localhost
tws.eConnect("", 7496, 46, poll_interval=1)
accountNumber = ''
contract = Contract()
contract.exchange = "SMART"
contract.symbol = "TOT"
contract.secType = "STK"
#contract.right = "PUT"
contract.currency = "USD"
#contract.secType = 'OPT'
#contract.strike = 24
#contract.expiry = '20121116'
today = datetime.today()


#tws.reqAccountUpdates(1, accountNumber)
#tws.reqAccountUpdates(0, accountNumber)


callback.histTickerID = contract.symbol 
tws.reqHistoricalData(
        1,                                          #tickerId,
        contract,                                   #contract,
        datetime(2012, 11, 2, 23, 59, 59).strftime("%Y%m%d %H:%M:%S"),       #endDateTime,
        "2 D",                                      #durationStr,
        "1 min",                                    #barSizeSetting,
        "TRADES",                                   #whatToShow,
        0,                                          #useRTH,
        1                                           #formatDate
    )
开发者ID:ts468,项目名称:IBAlgoTrading,代码行数:32,代码来源:example_historicaldata.py

示例6: SwigIBClient

# 需要导入模块: from swigibpy import EPosixClientSocket [as 别名]
# 或者: from swigibpy.EPosixClientSocket import reqHistoricalData [as 别名]

#.........这里部分代码省略.........
        contract.secType = "STK"
        contract.currency = "USD"
        return contract

    def request_contract_details(self, contract):
        today = datetime.today()

        print("Requesting contract details...")

        # Perform the request
        self.tws.reqContractDetails(
            42,  # reqId,
            contract,  # contract,
        )

        print("\n====================================================================")
        print(" Contract details requested, waiting %ds for TWS responses" % WAIT_TIME)
        print("====================================================================\n")

        try:
            self.got_contract.wait(timeout=WAIT_TIME)
        except KeyboardInterrupt:
            pass
        finally:
            if not self.got_contract.is_set():
                print('Failed to get contract within %d seconds' % WAIT_TIME)

    def request_hist_data(self, contract):
        today = datetime.today()

        print("Requesting historical data for %s" % contract.symbol)

        # Request some historical data.
        self.tws.reqHistoricalData(
            2,  # tickerId,
            contract,  # contract,
            today.strftime("%Y%m%d %H:%M:%S %Z"),  # endDateTime,
            "1 W",  # durationStr,
            "1 day",  # barSizeSetting,
            "TRADES",  # whatToShow,
            0,  # useRTH,
            1  # formatDate
        )

        print("\n====================================================================")
        print(" History requested, waiting %ds for TWS responses" % WAIT_TIME)
        print(" History requested, waiting %ds for TWS responses" % WAIT_TIME)
        print("====================================================================\n")

        try:
            self.got_history.wait(timeout=WAIT_TIME)
        except KeyboardInterrupt:
            pass
        finally:
            if not self.got_history.is_set():
                print('Failed to get history within %d seconds' % WAIT_TIME)

    def subscribe_market_data(self, contract):
        pass

    def unsubscribe_market_data(self, contract):
        pass

    def place_order(self, contract):
        print('Waiting for valid order id')
        order_id = self.order_ids.get(timeout=WAIT_TIME)
开发者ID:alexcwyu,项目名称:python-trading,代码行数:70,代码来源:ib_demo.py


注:本文中的swigibpy.EPosixClientSocket.reqHistoricalData方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。