10.25 ib api 自定义魔改日记

1、通过ibapi 下 EClient 和 EWrapper 创建新SimpleClient()类,其中EClient负责 connet()链接tws 发送req____ 请求,EWrapper负责 处理服务器发回的数据 利用回调函数处理。

2、实例  请求 EUR USD 历史数据

(1)定义 contract (人话:就是告诉服务器 我要EURUSD的历史数据)

from ibapi.client import EClient, Contract
contract = Contract()
contract.symbol = "EUR"
contract.secType = "CASH"
contract.currency = "USD"
contract.exchange = "IDEALPRO"
contract = Contract()
contract.symbol = "ES"
contract.secType = "FUT"
contract.exchange = "GLOBEX"
contract.currency = "USD"
contract.lastTradeDateOrContractMonth = "201903"

(2)展示代码

### SimpleClient 是上个文章中新定义的类 下面要魔改以下回调函数
from SC import SimpleClient
import datetime
client = SimpleClient('127.0.0.1', 7497, 0)
### 设置请求时间(人话:就是咱们得告诉服务器 我需要什么时间段的历史数据)
queryTime = (datetime.datetime.today() - datetime.timedelta(days=180)).strftime("%Y%m%d %H:%M:%S")
### 发送请求
client.reqHistoricalData(4102, contract, queryTime,"1 M", "1 day", "MIDPOINT", 1, 1, False, [])

(3)魔改回调函数

import pandas as pd
from datetime import datetime
from threading import Thread
import time
import sys 
from ibapi.client import EClient, Contract
from ibapi.order import Order
from ibapi.wrapper import EWrapper
from ibapi.utils import iswrapper


class SimpleClient(EWrapper, EClient):
    ''' Serves as the client and the wrapper '''

    def __init__(self, addr, port, client_id):
        '''省略一些上篇代码里有的代码 只展示修改的地方'''
        self.historical_data = []
        self.historical_data_pandas = pd.DataFrame()
########################  下面两个函数是用来修改回调函数  ######################## 
    @iswrapper
    def historicalData(self, reqId:int, bar):
        self.historical_data.append([bar.date,bar.open,bar.high,bar.low,
bar.close,bar.volume])
        print("HistoricalData. ReqId:", reqId, "BarData.", bar)


########################  bar类内容一些说明  ######################## 
        """ returns the requested historical data bars

        reqId - the request's identifier
        date  - the bar's date and time (either as a yyyymmss hh:mm:ssformatted
             string or as system time according to the request)
        open  - the bar's open point
        high  - the bar's high point
        low   - the bar's low point
        close - the bar's closing point
        volume - the bar's traded volume if available
        count - the number of trades during the bar's timespan (only available
            for TRADES).
        WAP -   the bar's Weighted Average Price
        hasGaps  -indicates if the data has gaps or not. """   

    @iswrapper
    def historicalDataEnd(self, reqId: int, start: str, end: str):
        super().historicalDataEnd(reqId, start, end)
        print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
        self.historical_data_pandas = pd.DataFrame(self.historical_data,columns=['date','open','high','low','close','volume'])

(4)结果展示

10.25 ib api 自定义魔改日记_第1张图片

10.25 ib api 自定义魔改日记_第2张图片

10.25 ib api 自定义魔改日记_第3张图片

2、接下来的计划 可以从盈透服务器下载历史数据了,也可以同步实时数据流,同时完成下单功能。

3、利用历史数据 对智能体进行训练 先用 金融人工智能一书 9.8章中 提到的 FQL智能体对历史数据进行训练

10.25 ib api 自定义魔改日记_第4张图片

def reqHistoricalData(self, reqId:TickerId , contract:Contract, endDateTime:str,
                          durationStr:str, barSizeSetting:str, whatToShow:str,
                          useRTH:int, formatDate:int, keepUpToDate:bool, chartOptions:TagValueList):
        """Requests contracts' historical data. When requesting historical data, a
        finishing time and date is required along with a duration string. The
        resulting bars will be returned in EWrapper.historicalData()

        reqId:TickerId - The id of the request. Must be a unique value. When the
            market data returns, it whatToShowill be identified by this tag. This is also
            used when canceling the market data.
        contract:Contract - This object contains a description of the contract for which
            market data is being requested.
        endDateTime:str - Defines a query end date and time at any point during the past 6 mos.
            Valid values include any date/time within the past six months in the format:
            yyyymmdd HH:mm:ss ttt

            where "ttt" is the optional time zone.
        durationStr:str - Set the query duration up to one week, using a time unit
            of seconds, days or weeks. Valid values include any integer followed by a space
            and then S (seconds), D (days) or W (week). If no unit is specified, seconds is used.
        barSizeSetting:str - Specifies the size of the bars that will be returned (within IB/TWS listimits).
            Valid values include:
            1 sec
            5 secs
            15 secs
            30 secs
            1 min
            2 mins
            3 mins
            5 mins
            15 mins
            30 mins
            1 hour
            1 day
        whatToShow:str - Determines the nature of data beinging extracted. Valid values include:

            TRADES
            MIDPOINT
            BID
            ASK
            BID_ASK
            HISTORICAL_VOLATILITY
            OPTION_IMPLIED_VOLATILITY
        useRTH:int - Determines whether to return all data available during the requested time span,
            or only data that falls within regular trading hours. Valid values include:

            0 - all data is returned even where the market in question was outside of its
            regular trading hours.
            1 - only data within the regular trading hours is returned, even if the
            requested time span falls partially or completely outside of the RTH.
        formatDate: int - Determines the date format applied to returned bars. validd values include:

            1 - dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd
            2 - dates are returned as a long integer specifying the number of seconds since
                1/1/1970 GMT.
        chartOptions:TagValueList - For internal use only. Use default value XYZ. """

### ibapi 文档网址 TWS API v9.72: Trader Workstation API

### basic contract 网址 https://interactivebrokers.github.io/tws-api/basic_contracts.html

你可能感兴趣的:(python,pandas,金融,算法)