python - 交互式经纪人 API 执行详细信息,我如何获得我获得的 Future 的入场价格?
问题描述
我想得到我实际购买的未来的价格。我越来越疯狂地试图让它发挥作用。我也想知道如何实时获得 PnL。当我尝试这样做时,更改值需要将近 5 分钟。这是我在这里使用的一些代码,它确实有效,但我无法获得执行细节。
进口时间
def read_positions(): # 读取所有账户仓位并返回 DataFrame 和信息
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import TickerId
import pandas as pd
import time
class ib_class(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.all_positions = pd.DataFrame([], columns=['Account', 'Symbol', 'Quantity', 'Average Cost', 'Sec Type'])
def error(self, reqId: TickerId, errorCode: int, errorString: str):
if reqId > -1:
print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ", errorString)
def position(self, account, contract, pos, avgCost):
index = str(account) + str(contract.symbol)
self.all_positions.loc[index] = account, contract.symbol, pos, avgCost, contract.secType
def positionEnd(self):
self.disconnect()
ib_api = ib_class()
ib_api.connect("127.0.0.1", 7496, 10)
ib_api.reqPositions()
current_positions = ib_api.all_positions
ib_api.run()
return current_positions
def read_navs(): # 读取所有账户的 NAV
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import TickerId
import pandas as pd
import time
class ib_class(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.all_accounts = pd.DataFrame([], columns=['reqId', 'Account', 'Tag', 'Value', 'Currency'])
def error(self, reqId: TickerId, errorCode: int, errorString: str):
if reqId > -1:
print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ", errorString)
def accountSummary(self, reqId, account, tag, value, currency):
#if tag == 'NetLiquidationByCurrency':
index = str(account)
self.all_accounts.loc[index] = reqId, account, tag, value, currency
def accountSummaryEnd(self, reqId: int):
self.disconnect()
def execDetails(self, reqId, contract, execution):
print('Order Executed: ', reqId, contract.symbol, contract.secType, contract.currency, execution.execId,
execution.orderId, execution.shares, execution.lastLiquidity)
ib_api = ib_class()
ib_api.connect("127.0.0.1", 7496, 10)
ib_api.reqAccountSummary(9001, "All", "$LEDGER")
current_nav = ib_api.all_accounts
ib_api.run()
return current_nav
而 True: time.sleep(0.1); 打印(读取位置())
解决方案
我记得这是一个新函数reqPnLSingle所以我写了这个来测试。
有一些奇怪的数据,但值似乎正确,并且不断更新。
我在代码中添加注释来解释。
import ibapi
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *
import pandas as pd
import collections
import time
class TestApp(EClient, EWrapper):
accts = []
orderId = 0
posns = collections.defaultdict(list)
start = time.time()
def __init__(self):
EClient.__init__(self, self)
def error(self, reqId:TickerId, errorCode:int, errorString:str):
if (reqId > -1):
# ignore many 2150 Invalid position trade derived value
if (errorCode == 2150): return
print("Error:", reqId, errorCode, errorString)
else :
print("Info: ", errorCode, errorString)
def managedAccounts(self, accountsList: str):
# the accounts are sent when a connection is made
# only needed to reqPosns for sub acct
self.accts = accountsList.split(",")# probably just 1
print("accts", self.accts)
def nextValidId(self, orderId:int):
# this is called when a connection is made
self.orderId = orderId
# to make sure the version is >= min 9.73.06, server > ~127?
print(ibapi.VERSION, self.serverVersion())
#use this as a signal to start making requests
self.reqPositions()
def position(self, account: str, contract: Contract, position: float, avgCost: float):
self.posns["account"].append(account)
self.posns["conId"].append(contract.conId)
self.posns["symbol"].append(contract.localSymbol)
self.posns["avgCost"].append(avgCost)
self.posns["posn"].append(position)
def positionEnd(self):
self.df = pd.DataFrame.from_dict(self.posns) #will make an automatic int index
if (self.df.empty):
self.disconnect()
return
# make req for each posn, use index for reqId
for index, row in self.df.iterrows():
self.reqPnLSingle(index, row.account, "", row.conId)
def pnlSingle(self, reqId: int, pos: int, dailyPnL: float, unrealizedPnL: float, realizedPnL: float, value: float):
row = self.df.iloc[reqId]
# all PnL's are maxint for me at night so I calc the right amount
print(row.symbol, "PnL", unrealizedPnL, "calc", value - row.avgCost * row.posn)
#just run for ~10 secs
if (time.time() - self.start > 10):
print(self.df)
self.disconnect()
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, 123)
app.run()
if __name__ == "__main__":
main()
推荐阅读
- apache-flink - 如何扩展/缩减正在运行的 Flink 集群?
- python - 有没有办法在 Tkinter 中显示 16 位图像?
- c# - 无法创建类型的常量值... + 跨上下文连接?
- python - 可以使 re.finditer() 从组中排除分隔符吗?
- c++ - 将集合的随机元素添加到列表中并将其从原始集合中删除
- python - DICOM 文件的医学图像质量问题
- java - 构造函数的自定义摆动组件问题
- django - 如何从查询集中创建一个 Select-Field 并在表单中实现它
- kubernetes - how to list the number of ready nodes in a cluster which don't have a taint
- ns2 - 如何计算数据包 AODV 的延迟