Skip to content

Commit

Permalink
black format two files
Browse files Browse the repository at this point in the history
  • Loading branch information
letianzj committed Jun 16, 2024
1 parent 3cb7d86 commit 6b6eaf1
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 20 deletions.
4 changes: 3 additions & 1 deletion examples/download_historical_data_from_ib.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ def run(self) -> None:
# daily combine and remove duplicates
dfd = self.df.combine_first(dfd)
# ready for the next 30min
self.df = pd.DataFrame(columns=["Open", "High", "Low", "Close", "Volume"])
self.df = pd.DataFrame(
columns=["Open", "High", "Low", "Close", "Volume"]
)

dfd.sort_index(inplace=True)
dict_all[sym] = dfd
Expand Down
70 changes: 51 additions & 19 deletions quanttrader/brokerage/ib_brokerage.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ def __init__(
self.contract_detail_request_contract_dict: dict[int, Contract] = ( # type: ignore
{}
) # reqid ==> contract
self.contract_detail_request_symbol_dict: dict[int, str] = {} # reqid ==> symbol
self.contract_detail_request_symbol_dict: dict[int, str] = (
{}
) # reqid ==> symbol
self.sym_contract_dict: dict[str, Contract] = {} # type: ignore
self.contract_symbol_dict: dict[int, str] = {} # conId ==> symbol
self.market_data_subscription_dict: dict[int, str] = {} # reqId ==> sym
Expand All @@ -72,7 +74,9 @@ def __init__(
) # reqid ==> tick_event; to combine tickprice and ticksize
self.market_depth_subscription_dict: dict[int, str] = {}
self.market_depth_subscription_reverse_dict: dict[str, int] = {}
self.market_depth_tick_dict: dict[int, TickEvent] = {} # to combine tickprice and ticksize
self.market_depth_tick_dict: dict[int, TickEvent] = (
{}
) # to combine tickprice and ticksize
self.hist_data_request_dict: dict[int, str] = {}
self.order_dict: dict[int, OrderEvent] = {} # order id ==> order_event
self.account_summary_reqid = -1
Expand All @@ -81,7 +85,9 @@ def __init__(
self.clientid = 0
self.reqid = 0 # next/available reqid

def connect(self, host: str = "127.0.0.1", port: int = 7497, clientId: int = 0) -> None:
def connect(
self, host: str = "127.0.0.1", port: int = 7497, clientId: int = 0
) -> None:
"""
Connect to IB. Request open orders under clientid upon successful connection.
Expand Down Expand Up @@ -115,7 +121,9 @@ def disconnect(self) -> None:
self.api.disconnect()
_logger.info(f"disconnected {self.api.isConnected()}")

def _calculate_commission(self, full_symbol: str, fill_price: float, fill_size: int) -> float:
def _calculate_commission(
self, full_symbol: str, fill_price: float, fill_size: int
) -> float:
""""""
raise NotImplementedError("Implement this in your derived class")

Expand All @@ -139,7 +147,9 @@ def place_order(self, order_event: OrderEvent) -> None:

ib_contract = InteractiveBrokers.symbol_to_contract(order_event.full_symbol)
if not ib_contract:
_logger.error(f"Failed to find contract to place order {order_event.full_symbol}")
_logger.error(
f"Failed to find contract to place order {order_event.full_symbol}"
)
return

ib_order = InteractiveBrokers.order_to_ib_order(order_event)
Expand All @@ -156,7 +166,9 @@ def place_order(self, order_event: OrderEvent) -> None:
order_event.timestamp = datetime.now().strftime("%H:%M:%S.%f")
order_event.order_status = OrderStatus.ACKNOWLEDGED # acknowledged
self.order_dict[order_event.order_id] = order_event
_logger.info(f"Order acknowledged {order_event.order_id}, {order_event.full_symbol}")
_logger.info(
f"Order acknowledged {order_event.order_id}, {order_event.full_symbol}"
)
self.event_engine.put(copy(order_event))
self.api.placeOrder(order_event.order_id, ib_contract, ib_order)

Expand Down Expand Up @@ -454,7 +466,9 @@ def symbol_to_contract(symbol: str) -> Contract: # type: ignore
ib_contract.secType = symbol_fields[1] # OPT
ib_contract.lastTradeDateOrContractMonth = symbol_fields[2] # 20201016
ib_contract.strike = (
float(symbol_fields[3]) if "." in symbol_fields[3] else int(symbol_fields[3])
float(symbol_fields[3])
if "." in symbol_fields[3]
else int(symbol_fields[3])
) # 128.75
ib_contract.right = symbol_fields[4] # C
ib_contract.exchange = symbol_fields[5] # SMART
Expand All @@ -465,7 +479,9 @@ def symbol_to_contract(symbol: str) -> Contract: # type: ignore
ib_contract.secType = symbol_fields[1] # FOP
ib_contract.lastTradeDateOrContractMonth = symbol_fields[2] # 20200911
ib_contract.strike = (
float(symbol_fields[3]) if "." in symbol_fields[3] else int(symbol_fields[3])
float(symbol_fields[3])
if "." in symbol_fields[3]
else int(symbol_fields[3])
) # 128.75
ib_contract.right = symbol_fields[4] # C
ib_contract.multiplier = symbol_fields[5] # 50
Expand Down Expand Up @@ -811,7 +827,9 @@ def managedAccounts(self, accountsList: str) -> None:
self.broker.account = accountsList.split(",")[0]
self.reqAccountUpdates(True, self.broker.account)

def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str) -> None:
def accountSummary(
self, reqId: int, account: str, tag: str, value: str, currency: str
) -> None:
super().accountSummary(reqId, account, tag, value, currency)
msg = f"AccountSummary. ReqId: {reqId}, Account: {account}, Tag: {tag}, Value: {value}, Currency: {currency}"
_logger.info(msg)
Expand All @@ -821,7 +839,9 @@ def accountSummaryEnd(self, reqId: int) -> None:
super().accountSummaryEnd(reqId)
_logger.info(f"AccountSummaryEnd. ReqId: {reqId}")

def updateAccountValue(self, key: str, val: str, currency: str, accountName: str) -> None:
def updateAccountValue(
self, key: str, val: str, currency: str, accountName: str
) -> None:
"""
Just as with the TWS' Account Window, unless there is a position change this information is updated at a fixed interval of three minutes.
"""
Expand All @@ -844,7 +864,9 @@ def updateAccountValue(self, key: str, val: str, currency: str, accountName: str
self.broker.account_summary.closed_pnl = float(val)
elif key == "UnrealizedPnL" and currency == "USD":
self.broker.account_summary.open_pnl = float(val)
self.broker.event_engine.put(self.broker.account_summary) # assume alphabatic order
self.broker.event_engine.put(
self.broker.account_summary
) # assume alphabatic order

def updatePortfolio(
self,
Expand Down Expand Up @@ -1349,7 +1371,9 @@ def contractDetails(self, reqId: int, contractDetails: ContractDetails) -> None:
f"Contract Detail: {contractDetails.contract.symbol}, {contractDetails.contract.localSymbol}, {contractDetails.contract.primaryExchange}, {contractDetails.contract.exchange}, {contractDetails.contract.multiplier}"
)
if reqId in self.broker.contract_detail_request_contract_dict.keys():
self.broker.contract_detail_request_contract_dict[reqId] = contractDetails.contract
self.broker.contract_detail_request_contract_dict[reqId] = (
contractDetails.contract
)
self.broker.sym_contract_dict[
self.broker.contract_detail_request_symbol_dict[reqId]
] = contractDetails.contract
Expand Down Expand Up @@ -1488,17 +1512,23 @@ def execDetails(self, reqId: int, contract: Contract, execution: Execution) -> N
fill_event.order_id = execution.orderId
fill_event.fill_id = execution.execId
fill_event.fill_price = execution.price
fill_event.fill_size = execution.shares * (1 if execution.side == "BOT" else -1) # BOT SLD
fill_event.fill_time = datetime.strptime(execution.time, "%Y%m%d %H:%M:%S").strftime(
"%H:%M:%S.%f"
)
fill_event.fill_size = execution.shares * (
1 if execution.side == "BOT" else -1
) # BOT SLD
fill_event.fill_time = datetime.strptime(
execution.time, "%Y%m%d %H:%M:%S"
).strftime("%H:%M:%S.%f")
fill_event.exchange = (
contract.exchange if contract.primaryExchange == "" else contract.primaryExchange
contract.exchange
if contract.primaryExchange == ""
else contract.primaryExchange
)
fill_event.account = self.broker.account

if execution.orderId in self.broker.order_dict.keys():
fill_event.full_symbol = self.broker.order_dict[execution.orderId].full_symbol
fill_event.full_symbol = self.broker.order_dict[
execution.orderId
].full_symbol
fill_event.source = self.broker.order_dict[execution.orderId].source
else: # not placed by algo
fill_event.full_symbol = InteractiveBrokers.contract_to_symbol(contract)
Expand All @@ -1515,7 +1545,9 @@ def displayGroupList(self, reqId: int, groups: str) -> None:

def displayGroupUpdated(self, reqId: int, contractInfo: str) -> None:
super().displayGroupUpdated(reqId, contractInfo)
_logger.info(f"DisplayGroupUpdated. ReqId: {reqId}, ContractInfo: {contractInfo}")
_logger.info(
f"DisplayGroupUpdated. ReqId: {reqId}, ContractInfo: {contractInfo}"
)

def commissionReport(self, commissionReport: CommissionReport) -> None:
super().commissionReport(commissionReport)
Expand Down

0 comments on commit 6b6eaf1

Please sign in to comment.