def create_ExecutionFilter(self): filter = ExecutionFilter() filter.clientId = 999 filter.acctCode = self.account yesterday = datetime.datetime.now() - datetime.timedelta(1) filter.time = yesterday.strftime('%Y%m%d-18:00:00') return filter
def do_sync(): if len(self.get_open_orders()) > 0: logging.info("开始同步订单的执行详情") req = Request.new_request() exec_filter = ExecutionFilter() exec_filter.clientId = self.cli.cli.clientId self.cli.cli.reqExecutions(req.req_id, exec_filter)
def _download_account_details(self): exec_filter = ExecutionFilter() exec_filter.clientId = self.client_id self.reqExecutions(self.next_request_id, exec_filter) self.reqManagedAccts() while self.managed_accounts is None: sleep(_poll_frequency) for account in self.managed_accounts: self.reqAccountUpdates(subscribe=True, acctCode=account) while self.accounts_download_complete is False: sleep(_poll_frequency)
def get_executions_and_commissions(self, reqId=DEFAULT_EXEC_TICKER, execution_filter=ExecutionFilter()): """ Returns a list of all executions done today with commission data """ ## store somewhere execution_queue = finishableQueue( self.init_requested_execution_data(reqId)) ## We can change ExecutionFilter to subset different orders ## note this will also pull in commissions but we would use get_executions_with_commissions self.reqExecutions(reqId, execution_filter) ## Run until we get a terimination or get bored waiting MAX_WAIT_SECONDS = 10 exec_list = list_of_execInformation( execution_queue.get(timeout=MAX_WAIT_SECONDS)) while self.wrapper.is_error(): print(self.get_error()) if execution_queue.timed_out(): print( "Exceeded maximum wait for wrapper to confirm finished whilst getting exec / commissions" ) ## Commissions will arrive seperately. We get all of them, but will only use those relevant for us commissions = self._all_commissions() ## glue them together, create a dict, remove duplicates all_data = exec_list.blended_dict(commissions) return all_data
def orderOperations_req(self, contract: Contract, order: Order): # Requesting the next valid id # The parameter is always ignored. self.reqIds(-1) # Requesting all open orders self.reqAllOpenOrders() # Taking over orders to be submitted via TWS self.reqAutoOpenOrders(True) # Requesting this API client's orders self.reqOpenOrders() # Placing/modifying an order - remember to ALWAYS increment the # nextValidId after placing an order so it can be used for the next one! # Note if there are multiple clients connected to an account, the # order ID must also be greater than all order IDs returned for orders # to orderStatus and openOrder to this client. self.simplePlaceOid = self.nextOrderId() self.placeOrder(self.simplePlaceOid, contract, order) # Request the day's executions self.reqExecutions(10001, ExecutionFilter()) # Requesting completed orders self.reqCompletedOrders(False)
def tickPrice(self, reqId, tickType, price, attrib): #68 denotes the tickType of lastPrice if tickType == 68: self.prices.append(price), self.times.append(time.time() - self.current_time) self.reqPositions() self.reqIds(-1) self.run_strategy(self.prices, self.contract) self.reqExecutions(self.reqExecutionId, ExecutionFilter()) self.reqExecutionId += 1
def connect(self, host: str, port: int, clientid: int, account: str): """ Connect to TWS. """ if self.status: return self.clientid = clientid self.account = account self.client.connect(host, port, clientid) self.thread.start() self.client.reqCurrentTime() if self.clientid == 0: self.client.reqAutoOpenOrders(True) self.reqid += 1 executionFilter = ExecutionFilter() self.client.reqExecutions(self.reqid, executionFilter) self.client.reqOpenOrders() self.client.reqPositions()
def reqExecutions(self) -> None: super().reqExecutions(self.nextReqId, ExecutionFilter()) self.nextReqId += 1
def commission_report(acctCode, time): class TestApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) self.executed_orders = pd.DataFrame(columns=[ 'ticker', 'time', 'shares', 'action', 'price', 'marketValue', 'RealizedPNL', 'commission' ]) self.val = 0 self.val2 = 0 def error(self, reqId: TickerId, errorCode: int, errorString: str): if reqId > -1: print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ", errorString) def execDetails(self, reqId, contract, execution): super().execDetails(reqId, contract, execution) self.executed_orders.loc[self.val, [ 'ticker', 'time', 'shares', 'action', 'price', 'marketValue' ]] = [ contract.symbol, pd.to_datetime(execution.time), execution.shares, execution.side, execution.price, execution.shares * execution.price ] self.val = self.val + 1 def commissionReport(self, commissionReport): super().commissionReport(commissionReport) self.executed_orders.loc[self.val2, ['RealizedPNL', 'commission']] = [ float( commissionReport.realizedPNL), float(commissionReport.commission) ] self.val2 = self.val2 + 1 def execDetailsEnd(self, reqId): super().execDetailsEnd(reqId) self.disconnect() app = TestApp() app.connect('127.0.0.1', 7497, 0) execution_filter = ExecutionFilter() execution_filter.acctCode = acctCode execution_filter.time = time app.reqExecutions(0, execution_filter) sleep(sleeptime) df = app.executed_orders app.run() sleep(sleeptime) df.set_index('time', inplace=True) df.sort_index(inplace=True) df['RealizedPNL'][df['RealizedPNL'] > 1000000] = 'OPEN' return df
def main_run(self): self.reqAllOpenOrders() self.reqExecutions(self.next_valid_id(), ExecutionFilter())