我在一个函数中创建了一个变量conID
,我想在另一个函数中使用它。两个函数都在一个类中。
问题是在第二个函数中调用了第一个函数,因此self.reqSecDefOptParams
调用了第一个函数。之后,conID
接收到它的值。如果我试图在第二个函数中输出condID
,我不能,它说它的值仍然是None
。是否有一种方法可以首先调用第一个函数,然后在同一个函数中输出值?
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
string = str((contractDetails))
letter_list = string.split(",")
print(letter_list)
conID = letter_list[90] # the variable I need
第二个函数:
def start(self):
# using the variable again
self.reqSecDefOptParams(1, contract.symbol, "", "STK", conID)
更新:我得到一个错误连接到套接字。我能做什么?
错误:410167请求的市场数据未订阅。显示延迟的市场数据。错误:410090部分请求的市场数据未被订阅。与订阅无关的标记仍然是活动的。延迟的市场数据是可用的。apple纳斯达克。NMS/高级/reader线程中未处理的异常回溯(最近一次调用):文件"C:ProgrammingTWSsourcepythonclientibapireader.py",第34行,在运行data = self.conn.recvMsg()文件"C:ProgrammingTWSsourcepythonclientibapiconnection.py",第99行,在recvMsgbuf = self._recvAllMsg()文件"C:ProgrammingTWSsourcepythonclientibapiconnection.py",第119行,在_recvAllMsg但f = self.socket.recv(4096)OSError: [WinError 10038]尝试在非套接字上执行操作
进程结束,退出码0
你的最后一个问题有更多的信息,我点赞了,所以我可以找到它,但它消失了。我将修复这段代码,这样你就可以看到它是如何与API交互的。
至少有两种方法可以获得期权合约。第一种是只要求它们,但不填写所有参数,然后contractDetails将返回所有匹配的合同。第二种是询问所有的参数,但你不知道是否所有的合约都被交易了。
我把数字放在代码注释中,以便了解程序流程是如何工作的。
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import TickerId, SetOfFloat, SetOfString, MarketDataTypeEnum
from ibapi.contract import Contract, ContractDetails
from ibapi.ticktype import TickType
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
self.underlyingContract = None
self.opts = []
self.optParams = ()
self.greeks = []
def error(self, reqId:TickerId, errorCode:int, errorString:str):
print("Error: ", reqId, "", errorCode, "", errorString)
def nextValidId(self, orderId):
self.start() #1
def contractDetails(self, reqId:int, contractDetails:ContractDetails, ):
if contractDetails.contract.secType == "OPT":#2,3 (2 contracts, P+C)
self.opts.append(contractDetails.contract)
if contractDetails.contract.secType == "STK":#4
self.underlyingContract = contractDetails.contract
self.reqSecDefOptParams(3,self.underlyingContract.symbol,"","STK",
self.underlyingContract.conId)#5
def contractDetailsEnd(self, reqId):
print("ncontractDetails Endn")#3,4
def securityDefinitionOptionParameter(self, reqId:int, exchange:str,
underlyingConId:int, tradingClass:str, multiplier:str,
expirations:SetOfString, strikes:SetOfFloat):
#6
self.optParams = (exchange, underlyingConId, tradingClass, multiplier, expirations, strikes)
def securityDefinitionOptionParameterEnd(self, reqId:int):
print("SecurityDefinitionOptionParameterEnd. ReqId",reqId)
# make a contract out of params or just use contract from earlier
if len(self.opts) > 0:
self.reqMktData(4,self.opts[0],"",False,False,[])#7
def tickOptionComputation(self, reqId:TickerId, tickType:TickType,
impliedVol:float, delta:float, optPrice:float, pvDividend:float,
gamma:float, vega:float, theta:float, undPrice:float):
self.greeks.append([optPrice,delta,impliedVol,undPrice]) #8
# just stop after first callback but you could set a time or something else
# if you don't get data, the program won't end unless you ctrl-c or something
self.stop() #9
def start(self):
# get some option contracts, not all
opts = Contract()
opts.symbol = 'AAPL'
opts.secType = 'OPT'
opts.exchange = 'SMART'
opts.currency = 'USD'
opts.strike="140"
#opts.right="P" # ambiguous so as to get multiple contracts
opts.multiplier="100"
opts.lastTradeDateOrContractMonth = '20211015'
self.reqContractDetails(1, opts) #2
# get just underlying conId
underlying = Contract()
underlying.symbol = 'AAPL'
underlying.secType = 'STK'
underlying.exchange = 'SMART'
underlying.currency = 'USD'
self.reqContractDetails(2, underlying) #4
# in case you don't have data subscription
self.reqMarketDataType(MarketDataTypeEnum.DELAYED)
def stop(self):
self.disconnect() #10
app = TestApp()
app.connect("127.0.0.1", 7497, 123)
app.run() # starts a reader thread that will block until disconnect()
#11 after disconnect, program can continue
# I just do this so I can use spyder variable inspector but you could print
uc = app.underlyingContract
opts = app.opts
params = app.optParams
greeks = app.greeks
def func_a():
foo = 'bar'
func_b(foo)
def func_b(var):
print(var)
func_a()
或者,我不推荐这样做,你可以使用全局作用域来解决这个问题,像这样,
def func_a():
global foo
foo = 'bar'
func_b()
def func_b():
print(foo)
func_a()
你说两个函数都在一个类中,所以也许可以将变量声明为一个类变量:
class A:
def __init__(self):
self.foo = None
def func_a(self):
self.foo = "Hello"
def func_b(self):
if self.foo is not None:
print(self.foo)
你可以在init中声明这个变量函数,就像c/c++中的构造函数。
def __init__(self):
self.foo = init_value