def parse_response_content(self, response_content):
     response = super(DelayBriefsResponse, self).parse_response_content(response_content)
     if 'is_success' in response:
         self._is_success = response['is_success']
     if self.data and isinstance(self.data, list):
         df = pd.DataFrame(self.data)
         field_mapping = {item: string_utils.camel_to_underline(item) for item in df.columns}
         self.briefs = df.rename(columns=field_mapping)
 def _parse_segment(segment, sub_value):
     for segment_key, segment_value in sub_value.items():
         if segment_value is None:
             continue
         if segment_key in ACCOUNT_FIELD_MAPPINGS:
             sub_tag = ACCOUNT_FIELD_MAPPINGS[segment_key]
         else:
             sub_tag = camel_to_underline(segment_key)
         setattr(segment, sub_tag, segment_value)
    def parse_response_content(self, response_content):
        response = super(AssetsResponse,
                         self).parse_response_content(response_content)
        if 'is_success' in response:
            self._is_success = response['is_success']

        if self.data:
            data_json = json.loads(self.data)
            if 'items' in data_json:
                for item in data_json['items']:
                    account = item['account']
                    asset = PortfolioAccount(account)
                    summary = asset.summary

                    for key, value in item.items():
                        if value is None:
                            continue
                        tag = ACCOUNT_FIELD_MAPPINGS[
                            key] if key in ACCOUNT_FIELD_MAPPINGS else camel_to_underline(
                                key)
                        if hasattr(summary, tag):
                            setattr(summary, tag, value)
                        elif 'market_values' == tag:
                            if isinstance(value, dict):
                                for sub_key, sub_value in value.items():
                                    currency = sub_key
                                    market_value = asset.market_value(
                                        currency=currency)
                                    self._parse_market_value(
                                        market_value, sub_value)
                            elif isinstance(value, list):
                                for sub_value in value:
                                    currency = sub_value.get('currency')
                                    if not currency:
                                        continue
                                    market_value = asset.market_value(
                                        currency=currency)
                                    self._parse_market_value(
                                        market_value, sub_value)
                        elif 'segments' == tag and value:
                            if isinstance(value, dict):
                                for sub_key, sub_value in value.items():
                                    segment_name = sub_key
                                    segment = asset.segment(
                                        segment_name=segment_name)
                                    self._parse_segment(segment, sub_value)
                            elif isinstance(value, list):
                                for sub_value in value:
                                    segment_name = sub_value.get('category')
                                    if not segment_name:
                                        continue
                                    segment = asset.segment(
                                        segment_name=segment_name)
                                    self._parse_segment(segment, sub_value)

                    self.assets.append(asset)
 def _parse_market_value(market_value, sub_value):
     for mv_key, mv_value in sub_value.items():
         if mv_value is None:
             continue
         if mv_key in ACCOUNT_FIELD_MAPPINGS:
             sub_tag = ACCOUNT_FIELD_MAPPINGS[mv_key]
         else:
             sub_tag = camel_to_underline(mv_key)
         if hasattr(market_value, sub_tag):
             setattr(market_value, sub_tag, mv_value)
Esempio n. 5
0
 def parse_response_content(self, response_content):
     response = super(OptionChainsResponse, self).parse_response_content(response_content)
     if 'is_success' in response:
         self._is_success = response['is_success']
     if self.data and isinstance(self.data, list):
         chain_data = []
         for item in self.data:
             symbol = item.get('symbol')
             expiry = item.get('expiry')
             items = item.get('items')
             if symbol and items:
                 for chain_item in items:
                     for call_put_item in chain_item.values():
                         item_values = {'symbol': symbol, 'expiry': expiry}
                         for key, value in call_put_item.items():
                             if value is None:
                                 continue
                             if key == 'right':
                                 value = value.upper()
                             item_values[CHAIN_FIELD_MAPPINGS.get(key, string_utils.camel_to_underline(key))] = value
                         chain_data.append(item_values)
         self.chain = pd.DataFrame(chain_data)
Esempio n. 6
0
    def parse_response_content(self, response_content):
        response = super(PrimeAssetsResponse,
                         self).parse_response_content(response_content)
        if 'is_success' in response:
            self._is_success = response['is_success']

        if self.data:
            assets = PortfolioAccount(self.data.get('accountId'),
                                      self.data.get('updateTimestamp'))

            for segment_data in self.data.get('segments', list()):
                segment = Segment()
                for key, value in segment_data.items():
                    if key == 'currencyAssets':
                        currency_assets = camel_to_underline_obj(value)
                        [
                            segment.add_currency_asset(
                                CurrencyAsset.from_dict(i))
                            for i in currency_assets
                        ]
                    else:
                        setattr(segment, camel_to_underline(key), value)
                assets.add_segment(segment)
            self.assets = assets
    def on_message(self, headers, body):
        """
        Called by the STOMP connection when a MESSAGE frame is received.

        :param dict headers: a dictionary containing all headers sent by the server as key/value pairs.
        :param body: the frame's payload - the message body.
        """
        try:
            response_type = headers.get('ret-type')
            if response_type == str(ResponseType.GET_SUB_SYMBOLS_END.value):
                if self.subscribed_symbols:
                    data = json.loads(body)
                    limit = data.get('limit')
                    symbols = data.get('subscribedSymbols')
                    used = data.get('used')
                    symbol_focus_keys = data.get('symbolFocusKeys')
                    focus_keys = dict()
                    for sym, keys in symbol_focus_keys.items():
                        keys = set(
                            QUOTE_KEYS_MAPPINGS.get(key, camel_to_underline(
                                key)) for key in keys)
                        focus_keys[sym] = list(keys)
                    self.subscribed_symbols(symbols, focus_keys, limit, used)
            elif response_type == str(ResponseType.GET_QUOTE_CHANGE_END.value):
                if self.quote_changed:
                    data = json.loads(body)
                    hour_trading = False
                    if 'hourTradingLatestPrice' in data:
                        hour_trading = True
                    if 'symbol' in data:
                        symbol = data.pop('symbol', None)
                        offset = data.get('offset', 0)
                        items = []
                        # 期货行情推送的价格都乘了 10 的 offset 次方变成了整数, 需要除回去变为正常单位的价格
                        if offset:
                            for key, value in data.items():
                                if key == 'latestTime' or key == 'hourTradingLatestTime':
                                    continue
                                if key in QUOTE_KEYS_MAPPINGS:
                                    key = QUOTE_KEYS_MAPPINGS.get(key)
                                    if key in PRICE_FIELDS:
                                        value /= 10**offset
                                    elif key == 'minute':
                                        minute_item = dict()
                                        for m_key, m_value in value.items():
                                            if m_key in {'p', 'h', 'l'}:
                                                m_value /= 10**offset
                                            minute_item[m_key] = m_value
                                            value = minute_item
                                    items.append((key, value))
                                else:
                                    items.append(
                                        (camel_to_underline(key), value))
                        else:
                            for key, value in data.items():
                                if key == 'latestTime' or key == 'hourTradingLatestTime':
                                    continue
                                if key in QUOTE_KEYS_MAPPINGS:
                                    key = QUOTE_KEYS_MAPPINGS.get(key)
                                    items.append((key, value))
                                else:
                                    items.append(
                                        (camel_to_underline(key), value))
                        if items:
                            self.quote_changed(symbol, items, hour_trading)
            elif response_type == str(ResponseType.SUBSCRIBE_ASSET.value):
                if self.asset_changed:
                    data = json.loads(body)
                    if 'account' in data:
                        account = data.pop('account', None)
                        items = []
                        for key, value in data.items():
                            if key in ASSET_KEYS_MAPPINGS:
                                items.append(
                                    (ASSET_KEYS_MAPPINGS.get(key), value))
                            else:
                                items.append((camel_to_underline(key), value))
                        if items:
                            self.asset_changed(account, items)
            elif response_type == str(ResponseType.SUBSCRIBE_POSITION.value):
                if self.position_changed:
                    data = json.loads(body)
                    if 'account' in data:
                        account = data.pop('account', None)
                        items = []
                        for key, value in data.items():
                            if key in POSITION_KEYS_MAPPINGS:
                                items.append(
                                    (POSITION_KEYS_MAPPINGS.get(key), value))
                            else:
                                items.append((camel_to_underline(key), value))
                        if items:
                            self.position_changed(account, items)
            elif response_type == str(
                    ResponseType.SUBSCRIBE_ORDER_STATUS.value):
                if self.order_changed:
                    data = json.loads(body)
                    if 'account' in data:
                        account = data.pop('account', None)
                        items = []
                        for key, value in data.items():
                            if key in ORDER_KEYS_MAPPINGS:
                                if key == 'status':
                                    value = get_order_status(value)
                                    # 部分成交 (服务端推送 'Submitted' 状态)
                                    if value == OrderStatus.HELD and data.get(
                                            'filledQuantity'):
                                        value = OrderStatus.PARTIALLY_FILLED
                                items.append(
                                    (ORDER_KEYS_MAPPINGS.get(key), value))
                            else:
                                items.append((camel_to_underline(key), value))
                        if items:
                            self.order_changed(account, items)
            elif response_type == str(ResponseType.GET_SUBSCRIBE_END.value):
                if self.subscribe_callback:
                    self.subscribe_callback(headers.get('destination'),
                                            json.loads(body))
            elif response_type == str(
                    ResponseType.GET_CANCEL_SUBSCRIBE_END.value):
                if self.unsubscribe_callback:
                    self.unsubscribe_callback(headers.get('destination'),
                                              json.loads(body))
            elif response_type == str(ResponseType.ERROR_END.value):
                if self.error_callback:
                    self.error_callback(body)
        except Exception as e:
            logging.error(e, exc_info=True)