我想使用 contractDetails(( 中的值从函数 tickPrice(( 中获取值。
为此,我尝试将结果从 contractDetails(( 传递给 tickPrice(( 的参数,但是当我尝试在 contractDetails(( 函数中设置参数时,我收到一个错误,指出变量未定义。
这是我到目前为止的代码:
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *
import pandas as pd
from threading import Timer
class TestApp(EWrapper, EClient):
def __init__(self):
EWrapper.__init__(self)
EClient.__init__(self, self)
def error(self, reqId, errorCode, errorString):
print("Error: ", reqId, " ", errorCode, " ", errorString)
def nextValidId(self, orderId):
self.start()
def contractDetails(self, reqId, contractDetails):
contract.lastTradeDateOrContractMonth = contractDetails.realExpirationDate
contract.strike = contractDetails.contract.strike
contract.right = contractDetails.contract.right
def tickPrice(self, reqId, tickType, price, attrib):
if tickType == 4 and reqId == 1:
print(price)
def contractDetailsEnd(self, reqId):
print("ncontractDetails Endn")
self.stop()
def start(self):
contract = Contract()
contract.symbol = 'AAPL'
contract.secType = 'OPT'
contract.currency = 'USD'
contract.exchange = 'SMART'
contract.multiplier = '100'
contract.lastTradeDateOrContractMonth = '20200619'
contract.strike = '180'
contract.right = 'C'
self.reqContractDetails(1, contract)
self.reqMktData(1, contract, '101', False, False, [])
def stop(self):
self.done=True
self.disconnect()
print('disconnect')
def main():
print('start')
app = TestApp()
app.nextOrderId = 0
app.connect('127.0.0.1',7497,108)
#Timer(4, app.stop).start()
app.run()
print('finish')
if __name__ == "__main__":
main()
错误:
contract.lastTradeDateOrContractMonth = contractDetails.realExpirationDate
NameError: name 'contract' is not defined
我无法设置剩余的 3 个变量:
contract.lastTradeDateOrContractMonth = contractDetails.realExpirationDate
contract.strike = contractDetails.contract.strike
contract.right = contractDetails.contract.right
结果来自 contractDetails((。
这将允许我遍历所有参数。
在定义对象之前设置contract
对象的字段。看起来您希望contract
成为实例变量,因此我将以下代码添加到__init__
方法中:
def __init__(self):
EWrapper.__init__(self)
EClient.__init__(self, self)
self.contract = None
然后在其余方法中将contract
替换为self.contract
。