def _handle_request_exception(self, e, safe=True): if 1: if isinstance(e, RequestTimeoutException): return StrategyError(302, "timeout for request") elif isinstance(e, InvalidLoginStatus): return StrategyError( 300, "operation before login status, maybe connection is broke") elif isinstance(e, RequestCleanupAsDisconnect): return StrategyError(301, "request failed as disconnect") else: return BaseStrategy._new_500_error()
def init(self): err = StrategyError(100, "connect error") for name, strategy in [(u"trader", self.traderStrategy), (u"quote", self.quoteStrategy)]: if strategy is not None: try: err = strategy.init() if err.errorId == 0: logging.info(u"%s connection login succeed", name) else: logging.exception(u"%s connection failed.....", name) return err except Exception, e: logging.exception(u"login failed, e is %s", e) return StrategyError(100, "connect error")
def subscribe(self, symbol, notify_cb, bar_type=1, update_in_bar=False): err = StrategyError(0, "success") key = "%d_%d" % (bar_type, update_in_bar) if not self.listeners.has_key(symbol): self.listeners[symbol] = {} if key not in self.listeners[symbol]: self.listeners[symbol][key] = [] if notify_cb not in self.listeners[symbol][key]: self.listeners[symbol][key].append(notify_cb) if not self.ticks.has_key(symbol): self.ticks[symbol] = None current_bar_key = "%s_%d" % (symbol, bar_type) err = self.req_subscribe(TICK, symbol) self.current_sample_time[current_bar_key] = None self.concurrent_bars[current_bar_key] = None return err
def send_order(self, symbol=None, bs_flag=None, position_effect=None, price_type=None, price=None, volume=None, strategy=None, order_time=None, hedge_type=HEDGE_FLAG_HEDGE): if strategy is None: strategy = self.strategyConnectionInfo.strategyName order_info = StrategyOrder(userName=self.connectionInfo.userName, price=price, priceType=price_type, instrument=symbol, bsFlag=bs_flag, positionEffect=position_effect, strategyName=strategy, volume=volume, hedgeFlag=hedge_type, orderTime=order_time) result = None err = self._new_succeed_error() logging.info("Requested order info:%s", order_info.to_json()) try: self._check_login_status() request_info = self._build_request_info( self.DEFAULT_REQUEST_TIMEOUT, function_code.REQ_ST_ORDER) order_info.strategyClientID = os.getpid() # XXX 是不是这个? request_info.data = order_info.to_json() response_info = self.connClient.sync_rpc(request_info) data = response_info.data if response_info.is_success(): result = data logging.info("response order: %s", data) result = long(result) else: err = StrategyError().from_json(data) except Exception as e: logging.exception(e) err = self._handle_request_exception(e) return result, err
def req_position(self, strategy_id=None): result = None err = self._new_succeed_error() try: self._check_login_status() request_info = self._build_request_info( self.DEFAULT_REQUEST_TIMEOUT, function_code.REQ_ST_POTITIONDSTATICS) request_info.data = strategy_id response_info = self.connClient.sync_rpc(request_info) data = response_info.data if response_info.is_success(): result = utils_bean.json_load_bean_list(data, StrategyPosition) else: err = StrategyError().from_json(data) except Exception as e: logging.exception("%s", e) err = self._handle_request_exception(e) return result, err
def init(self): logging.debug( "connect to %s:%d for %s", self.connClient.host, self.connClient.port, "trader" if (AgentType_STRATEGY_TRADE == self.agentType) else "quote") err = self._new_succeed_error() if self.connClient.connect(): err = self.req_login() if err.errorId == 0: self.login = True if self.reConnectWorker is None: self.reConnectWorker = ThreadPoolExecutor(1) self.reConnectWorker.submit(self._reconnect) else: logging.warning(u"self.default_req_login() failed") else: err = StrategyError(100, "connect error") logging.warning(u"self.connClient.connect() failed") return err
def req_account_detail(self, trading_day=None): result = None err = self._new_succeed_error() try: self._check_login_status() request_info = self._build_request_info( self.DEFAULT_REQUEST_TIMEOUT, function_code.REQ_ST_ACCOUNTETAIL) request_info.data = trading_day response_info = self.connClient.sync_rpc(request_info) data = response_info.data if response_info.is_success(): result = utils_bean.json_load_bean_list( data, StrategyAccountDetail) else: err = StrategyError().from_json(data) except Exception as e: logging.exception("%s", e) err = self._handle_request_exception(e) return result, err
def req_login(self): if self.login: return StrategyError(0, "success") try: request_info = self._build_request_info( self.DEFAULT_REQUEST_TIMEOUT, function_code.STRATEGYLOGIN) data = self.connectionInfo.to_json() request_info.data = data response_info = self.connClient.sync_rpc(request_info) err = self._convert_2_strategy_error(response_info.protocolMessage) if err.errorId == 0: # 返回的sessionid保存下来给重连使用。 self.connectionInfo.sessionId = err.errorMsg logging.info(u"请求连接成功,err is %s", err.to_json()) err.errorMsg = "success" else: logging.exception(u"请求连接失败,err is %s", err.to_json()) return err except Exception as e: logging.exception("%s", e) return self._new_500_error()
def _new_succeed_error(cls): return StrategyError(error_id=0, error_msg=u"ok")
def _new_connection_error(cls): return StrategyError(error_id=400, error_msg=u"connection error for request")
def _new_500_error(cls): return StrategyError(error_id=500, error_msg=u"internal system error for request")
def _convert_2_strategy_error(cls, message): return StrategyError().from_json(message.body)
def _rpc_call(self, url, parameters, time_out=None): try: if time_out is None: time_out = self.timeOut error = StrategyError() data = None req_data = {} values = "appplt=web&%s&userName=%s&passWord=%s" % ( parameters, self.userName, self.passWord) for item in values.split("&"): key, val = item.split("=") req_data[key] = val req_data = urllib.urlencode(req_data) response = urllib2.urlopen("http://%s/quotehistory/v1/data/%s?%s" % (self.server, url, req_data), timeout=time_out) if response.code != 200: logging.warn("failed to get data as status:%d reason:%s" % (response.code, response.msg)) error.errorId = response.code error.errorMsg = "failed to get data as status:%d reason:%s" % ( response.code, response.msg) return error, data str_data = response.read() if len(str_data) == 0: logging.warn("failed to get data as response data is %s" % str_data) error.errorId = 200 error.errorMsg = "failed to get data as response data is %s" % str_data return error, data json_data = json.loads(str_data) if json_data["err"] != 0: error.errorId = int(json_data['errCode']) error.errorMsg = "failed to get data as error:%s" % json_data[ 'errCode'] return error, data error.errorId = 0 error.errorMsg = "success" if "data" not in json_data: error.errorId = 0 error.errorMsg = "no content" return error, data return error, json_data['data'] except Exception, e: logging.exception(e) return StrategyError(500, "internal error"), None