Ejemplo n.º 1
0
 class _Security(MyXmlObject):
     # Id бумаги
     secid = IntegerField('@secid')
     # Внутренний код рынка
     market = IntegerField('market')
     # Код инструмента
     seccode = StringField('seccode')
     # Максимум купить (лотов)
     max_buy = IntegerField('maxbuy')
     # Максимум продать (лотов)
     max_sell = IntegerField('maxsell')
Ejemplo n.º 2
0
class Quote(Entity):
    """
    Глубина рынка по инструменту.
    """
    ROOT_NAME = 'quote'
    id = secid = IntegerField('@secid')
    # Идентификатор режима торгов по умолчанию
    board = StringField('board')
    # Код инструмента
    seccode = StringField('seccode')
    # Цена
    price = FloatField('price')
    # Источник котировки (маркетмейкер)
    source = StringField('source')
    # Доходность облигаций
    yld = IntegerField('yield')
    # Количество бумаг к покупке
    buy = IntegerField('buy')
    # Количество бумаг к продаже
    sell = IntegerField('sell')
Ejemplo n.º 3
0
class DetailVariable(XmlObject):
    ROOT_NAME = '_'
    function = StringField('@function')

    def get_name(self):
        return self.node.tag

    def set_name(self, value):
        self.node.tag = value

    name = property(get_name, set_name)
Ejemplo n.º 4
0
class Instance(IdNode, OrderedXmlObject):
    ROOT_NAME = 'instance'
    ORDER = ('id', 'src')

    src = StringField('@src')

    def __eq__(self, other):
        return self.src == other.src and self.id == other.id

    def __hash__(self):
        return hash((self.src, self.id))
Ejemplo n.º 5
0
class Text(XmlObject):
    """
    <text>                     <!----------- Exactly one. Will be present wherever text can be defined. Contains a sequential list of string elements to be concatenated to form the text body.-->
        <xpath function="">   <!------------ 0 or More. An xpath function whose result is a string. References a data model if used in a context where one exists. -->
            <variable name=""/> <!------------ 0 or More. Variable for the localized string. Variable elements can support any child elements that <body> can. -->
        </xpath>
        <locale id="">         <!------------ 0 or More. A localized string. id can be referenced here or as a child-->
            <id/>              <!------------ At Most One. The id of the localized string (if not provided as an attribute -->
            <argument key=""/> <!------------ 0 or More. Arguments for the localized string. Key is optional. Arguments can support any child elements that <body> can. -->
        </locale>
    </text>
    """

    ROOT_NAME = 'text'

    xpath = NodeField('xpath', Xpath)
    xpath_function = StringField('xpath/@function')

    locale = NodeField('locale', Locale)
    locale_id = StringField('locale/@id')
Ejemplo n.º 6
0
class MarketOrderAbility(MyXmlObject):
    """
    Возможность рыночных заявок.
    """
    ROOT_NAME = 'marketord'
    # Id бумаги
    secid = IntegerField('@secid')
    # Код бумаги
    seccode = StringField('@seccode')
    # Флаг доступности
    permitted = SimpleBooleanField('@permit', 'yes', 'no')
Ejemplo n.º 7
0
class Entry(XmlObject):
    ROOT_NAME = 'entry'

    form = StringField('form')
    command = NodeField('command', Command)
    instances = NodeListField('instance', Instance)

    datums = NodeListField('session/datum', SessionDatum)

    stack = NodeField('stack', Stack)

    assertions = NodeListField('assertions/assert', Assertion)
Ejemplo n.º 8
0
class AbstractResource(XmlObject):

    LOCATION_TEMPLATE = 'resource/location[@authority="%s"]'

    local = StringField(LOCATION_TEMPLATE % 'local', required=True)
    remote = StringField(LOCATION_TEMPLATE % 'remote', required=True)

    version = IntegerField('resource/@version')
    id = StringField('resource/@id')

    def __init__(self,
                 id=None,
                 version=None,
                 local=None,
                 remote=None,
                 **kwargs):
        super(AbstractResource, self).__init__(**kwargs)
        self.id = id
        self.version = version
        self.local = local
        self.remote = remote
Ejemplo n.º 9
0
 class _ValuePart(MyXmlObject):
     # Регистр учёта
     register = StringField('@register')
     # Входящая денежная позиция
     open_balance = FloatField('open_balance')
     # Потрачено на покупки
     bought = FloatField('bought')
     # Выручка от продаж
     sold = FloatField('sold')
     # Исполнено
     settled = FloatField('settled')
     # Текущая денежная позиция
     balance = FloatField('balance')
Ejemplo n.º 10
0
class SessionDatum(IdNode, OrderedXmlObject):
    ROOT_NAME = 'datum'
    ORDER = (
        'id',
        'nodeset',
        'value',
        'function',
        'detail_select',
        'detail_confirm',
        'detail_persistent',
        'detail_inline',
        'autoselect',
    )

    nodeset = XPathField('@nodeset')
    value = StringField('@value')
    function = XPathField('@function')
    detail_select = StringField('@detail-select')
    detail_confirm = StringField('@detail-confirm')
    detail_persistent = StringField('@detail-persistent')
    detail_inline = StringField('@detail-inline')
    autoselect = SimpleBooleanField('@autoselect', true="true", false="false")
Ejemplo n.º 11
0
class Entry(OrderedXmlObject, XmlObject):
    ROOT_NAME = 'entry'
    ORDER = ('form', 'command', 'instance', 'datums')

    form = StringField('form')
    command = NodeField('command', Command)
    instances = NodeListField('instance', Instance)

    datums = NodeListField('session/datum', SessionDatum)
    queries = NodeListField('session/query', RemoteRequestQuery)
    session_children = NodeListField('session/*', _wrap_session_datums)
    all_datums = NodeListField(
        'session/*[self::datum or self::instance-datum]', _wrap_session_datums)

    stack = NodeField('stack', Stack)

    assertions = NodeListField('assertions/assert', Assertion)

    def require_instances(self, instances=(), instance_ids=()):
        used = {(instance.id, instance.src) for instance in self.instances}
        for instance in instances:
            if 'remote' in instance.src:
                continue
            if (instance.id, instance.src) not in used:
                self.instances.append(
                    # it's important to make a copy,
                    # since these can't be reused
                    Instance(id=instance.id, src=instance.src))
                # make sure the first instance gets inserted
                # right after the command
                # once you "suggest" a placement to eulxml,
                # it'll follow your lead and place the rest of them there too
                if len(self.instances) == 1:
                    instance_node = self.node.find('instance')
                    command_node = self.node.find('command')
                    self.node.remove(instance_node)
                    self.node.insert(
                        self.node.index(command_node) + 1, instance_node)
        covered_ids = {instance_id for instance_id, _ in used}
        for instance_id in instance_ids:
            if instance_id not in covered_ids:
                raise UnknownInstanceError(
                    "Instance reference not recognized: {} in XPath \"{}\""
                    # to get xpath context to show in this error message
                    # make instance_id a unicode subclass with an xpath property
                    .format(instance_id, getattr(instance_id, 'xpath', "(XPath Unknown)")))

        sorted_instances = sorted(self.instances,
                                  key=lambda instance: instance.id)
        if sorted_instances != self.instances:
            self.instances = sorted_instances
Ejemplo n.º 12
0
class GraphTemplate(Template):
    # TODO: Is there a way to specify a default/static value for form?
    form = StringField('@form', choices=['graph'])
    graph = NodeField('graph', Graph)

    @classmethod
    def build(cls,
              form,
              graph,
              locale_config=None,
              locale_series_config=None,
              locale_annotation=None):
        return cls(
            form=form,
            graph=Graph(
                type=graph.graph_type,
                series=[
                    Series(
                        nodeset=s.data_path,
                        x_function=s.x_function,
                        y_function=s.y_function,
                        radius_function=s.radius_function,
                        configuration=ConfigurationGroup(configs=([
                            # TODO: It might be worth wrapping
                            #       these values in quotes (as appropriate)
                            #       to prevent the user from having to
                            #       figure out why their unquoted colors
                            #       aren't working.
                            ConfigurationItem(id=k, xpath_function=v)
                            for k, v in s.config.items()
                        ] + [
                            ConfigurationItem(
                                id=k, locale_id=locale_series_config(index, k))
                            for k, v in sorted(
                                s.locale_specific_config.items())
                        ]))) for index, s in enumerate(graph.series)
                ],
                configuration=ConfigurationGroup(configs=([
                    ConfigurationItem(id=k, xpath_function=v)
                    for k, v in graph.config.items()
                ] + [
                    ConfigurationItem(id=k, locale_id=locale_config(k))
                    for k, v in graph.locale_specific_config.items()
                ])),
                annotations=[
                    Annotation(x=Text(xpath_function=a.x),
                               y=Text(xpath_function=a.y),
                               text=Text(locale_id=locale_annotation(i)))
                    for i, a in enumerate(graph.annotations)
                ]))
Ejemplo n.º 13
0
class Entry(OrderedXmlObject):
    ROOT_NAME = 'entry'
    ROOT_NAMESPACES = NS
    ROOT_NS = NS['atom']
    ORDER = ('category_term', 'title', 'id', 'updated', 'content',
             'properties')

    category_term = StringField('atom:category/@term')
    title = StringField('atom:title')
    id = EntryIdField('atom:id')
    updated = UTCDateTimeField('atom:updated')
    content = StringField('atom:content')
    properties = NodeListField('apps:property', EntryProperty)

    def __init__(self, node=None, context=None, **kwargs):
        if node is None:
            if 'category_term' not in kwargs:
                kwargs['category_term'] = 'filter'
            if 'title' not in kwargs:
                kwargs['title'] = 'Mail Filter'
            if 'content' not in kwargs:
                kwargs['content'] = ''
        super(Entry, self).__init__(node, context, **kwargs)
Ejemplo n.º 14
0
class ClientLimitsForts(Entity):
    """
    Лимиты клиента на срочном рынке.
    """
    ROOT_NAME = 'clientlimits'
    # Идентификатор клиента
    id = client = StringField('@client')
    # стоимостной лимит открытых позиций (СЛОП срочн.рынок ММВБ)
    cbplimit = FloatField('cbplimit')
    # стоимостная оценка текущих чистых позиций (СОЧП срочн. рынок ММВБ)
    cbplused = FloatField('cbplused')
    # СОЧП с учетом активных заявок (срочный рынок ММВБ)
    cbplplanned = FloatField('cbplplanned')
    # Вар. маржа срочного рынка ММВБ
    fob_varmargin = FloatField('fob_varmargin')
    # Обеспеченность срочного портфеля (FORTS)
    coverage = FloatField('coverage')
    # Коэффициент ликвидности(FORTS)
    liquidity_c = FloatField('liquidity_c')
    # Доход(FORTS)
    profit = FloatField('profit')
    # Деньги текущие
    money_current = FloatField('money_current')
    # Деньги заблокированные
    money_reserve = FloatField('money_reserve')
    # Деньги свободные
    money_free = FloatField('money_free')
    # Премии по опционам(FORTS)
    options_premium = FloatField('options_premium')
    # Биржевой сбор(FORTS)
    exchange_fee = FloatField('exchange_fee')
    # Вар. маржа текущая (FORTS)
    forts_varmargin = FloatField('forts_varmargin')
    # Операционная маржа
    varmargin = FloatField('varmargin')
    # Перечисленная в пром.клиринге вариационная маржа(FORTS)
    pclmargin = FloatField('pclmargin')
    # Вар. маржа по опционам(FORTS)
    options_vm = FloatField('options_vm')
    # Лимит на покупку спот
    spot_buy_limit = FloatField('spot_buy_limit')
    # Лимит на покупку спот использованный
    used_spot_buy_limit = FloatField('used_spot_buy_limit')
    # Залоги текущие
    collat_current = FloatField('collat_current')
    # Залоги заблокированные
    collat_blocked = FloatField('collat_blocked')
    # Залоги свободные
    collat_free = FloatField('collat_free')
Ejemplo n.º 15
0
class Trade(Entity):
    """
    Сделка по инструменту на рынке (внешняя).
    """
    ROOT_NAME = 'trade'
    secid = IntegerField('@secid')
    # Наименование борда
    board = StringField('board')
    # Код инструмента
    seccode = StringField('seccode')
    # Биржевой номер сделки
    id = trade_no = IntegerField('tradeno')
    # Время сделки
    time = DateTimeField('time', TIME_FORMAT)
    # Цена сделки
    price = FloatField('price')
    # Объём в лотах
    quantity = IntegerField('quantity')
    # Покупка (B) / Продажа (S)
    buysell = StringField('buysell', choices=('B', 'S'))
    open_interest = IntegerField('openinterest')
    # Период торгов (O - открытие, N - торги, С - закрытие)
    trade_period = StringField('period',
                               choices=('O', 'N', 'C', 'F', 'B', 'T', 'L'))
Ejemplo n.º 16
0
class Suite(XmlObject):
    ROOT_NAME = 'suite'

    version = IntegerField('@version')

    xform_resources = NodeListField('xform', XFormResource)
    locale_resources = NodeListField('locale', LocaleResource)
    media_resources = NodeListField('locale', MediaResource)

    details = NodeListField('detail', Detail)
    entries = NodeListField('entry', Entry)
    menus = NodeListField('menu', Menu)

    fixtures = NodeListField('fixture', Fixture)
    descriptor = StringField('@descriptor')
Ejemplo n.º 17
0
class QueryPrompt(DisplayNode):
    ROOT_NAME = 'prompt'

    key = StringField('@key')
    appearance = StringField('@appearance', required=False)
    receive = StringField('@receive', required=False)
    hidden = BooleanField('@hidden', required=False)
    input_ = StringField('@input', required=False)
    default_value = StringField('@default', required=False)
    allow_blank_value = BooleanField('@allow_blank_value', required=False)
    exclude = StringField('@exclude', required=False)
    required = StringField('@required', required=False)

    itemset = NodeField('itemset', Itemset)
Ejemplo n.º 18
0
class Suite(OrderedXmlObject):
    ROOT_NAME = 'suite'
    ORDER = ('version', 'descriptor')

    version = IntegerField('@version')
    descriptor = StringField('@descriptor')

    xform_resources = NodeListField('xform', XFormResource)
    locale_resources = NodeListField('locale', LocaleResource)
    media_resources = NodeListField('locale', MediaResource)

    details = NodeListField('detail', Detail)
    entries = NodeListField('entry', Entry)
    menus = NodeListField('menu', Menu)
    remote_requests = NodeListField('remote-request', RemoteRequest)

    fixtures = NodeListField('fixture', Fixture)
Ejemplo n.º 19
0
 class _ValuePart(MyXmlObject):
     # Входящая позиция, штук
     register = StringField('@register')
     # Входящая позиция, штук
     open_balance = IntegerField('open_balance')
     # Куплено, штук
     bought = IntegerField('bought')
     # Продано, штук
     sold = IntegerField('sold')
     # Исполнено
     settled = IntegerField('settled')
     # Текущая позиция, штук
     balance = IntegerField('balance')
     # Заявлено купить, штук
     buying = IntegerField('buying')
     # Заявлено продать, штук
     selling = IntegerField('selling')
Ejemplo n.º 20
0
class StopLoss(StopOrder):
    """Стоп лосс оредер"""
    # Использование кредита
    use_credit = SimpleBooleanField('stoploss/@usecredit', 'yes', 'no')
    # Цена активации
    activation_price = FloatField('stoploss/activationprice')
    # Рыночное исполнение
    bymarket = ItemField('bymarket')
    # Защитное время удержания цены
    # (когда цены на рынке лишь кратковременно достигают уровня цены активации,
    # и вскоре возвращаются обратно)
    guard_time = DateTimeField('stoploss/guardtime', TIME_FORMAT)
    # Примечание
    broker_ref = StringField('stoploss/brokerref')
    # Количество лотов
    quantity = IntegerField('stoploss/quantity')
    # Цена исполнения (отменяет bymarket)
    price = FloatField('stoploss/orderprice')
Ejemplo n.º 21
0
class Suite(OrderedXmlObject):
    ROOT_NAME = 'suite'
    ORDER = ('version', 'descriptor')

    version = IntegerField('@version')
    descriptor = StringField('@descriptor')

    xform_resources = NodeListField('xform', XFormResource)
    # releases_xform_resources = NodeListField('xform-update-info', ReleaseInfoXFormResource)
    locale_resources = NodeListField('locale', LocaleResource)
    media_resources = NodeListField('locale', MediaResource)
    practice_user_restore_resources = NodeListField(
        'user-restore', PracticeUserRestoreResource)

    details = NodeListField('detail', Detail)
    entries = NodeListField('entry', Entry)
    menus = NodeListField('menu', Menu)
    endpoints = NodeListField('endpoint', SessionEndpoint)
    remote_requests = NodeListField('remote-request', RemoteRequest)

    fixtures = NodeListField('fixture', Fixture)
Ejemplo n.º 22
0
class ClientLimitsTPlus(Entity):
    """
    Максимальная покупка/продажа для Т+.
    """
    ROOT_NAME = 'max_buy_sell_tplus'
    # Идентификатор клиента
    id = client = StringField('@client')

    class _Security(MyXmlObject):
        # Id бумаги
        secid = IntegerField('@secid')
        # Внутренний код рынка
        market = IntegerField('market')
        # Код инструмента
        seccode = StringField('seccode')
        # Максимум купить (лотов)
        max_buy = IntegerField('maxbuy')
        # Максимум продать (лотов)
        max_sell = IntegerField('maxsell')

    securities = NodeListField('security', _Security)
Ejemplo n.º 23
0
class ClientTrade(Entity):
    """
    Клиентская сделка (т.е. успешно выполненная заявка).
    """
    ROOT_NAME = 'trade'
    # Id бумаги
    secid = IntegerField('secid')
    # Номер сделки на бирже
    id = trade_no = IntegerField('tradeno')
    # Номер заявки на бирже
    order_no = IntegerField('orderno')
    # Идентификатор борда
    board = StringField('board')
    # Код инструмента
    seccode = StringField('seccode')
    # Идентификатор клиента
    client = StringField('client')
    # B - покупка, S - продажа
    buysell = StringField('buysell', choices=('B', 'S'))
    # Время сделки
    time = DateTimeField('time', TIME_FORMAT)
    # Примечание
    broker_ref = StringField('brokerref')
    # Объем сделки
    value = FloatField('value')
    # Комиссия
    commission = FloatField('comission')
    # Цена
    price = FloatField('price')
    # Кол-во инструмента в сделках в штуках
    items = IntegerField('items')
    # Количество лотов
    quantity = IntegerField('quantity')
    # Доходность
    yld = IntegerField('yield')
    # НКД
    accrued_int = FloatField('accruedint')
    # тип сделки: ‘T’ – обычная ‘N’ – РПС ‘R’ – РЕПО ‘P’ – размещение
    trade_type = StringField('tradetype', choices=('T', 'N', 'R', 'P'))
    # Код поставки
    settle_code = StringField('settlecode')
    # Текущая позиция по инструменту
    current_position = IntegerField('currentpos')
Ejemplo n.º 24
0
class BaseOrder(Entity):
    """
    Базовый класс ордеров (обычных и стопов) с общими аттрибутами.
    """
    # идентификатор транзакции сервера Transaq
    id = IntegerField('@transactionid')
    # Биржевой номер заявки
    order_no = IntegerField('orderno')
    # идентификатор бумаги
    secid = IntegerField('secid')
    # Идентификатор борда
    board = StringField('board')
    # Код инструмента
    seccode = StringField('seccode')
    # Цена
    price = FloatField('price')
    # Время регистрации заявки биржей
    time = DateTimeField('time', TIME_FORMAT)
    # Идентификатор клиента
    client = StringField('client')
    # Cтатус заявки
    status = StringField('status')
    # Покупка (B) / Продажа (S)
    buysell = StringField('buysell', choices=('B', 'S'))
    # Дата экспирации (только для ФОРТС)
    exp_date = DateTimeField('expdate', TIME_FORMAT)
    # Примечание
    broker_ref = StringField('brokerref')
    # Время регистрации заявки сервером Transaq (только для условных заявок)
    accept_time = DateTimeField('accepttime', TIME_FORMAT)
    # До какого момента действительно
    valid_before = DateTimeField('validbefore', TIME_FORMAT)
    # Количество лотов
    quantity = IntegerField('quantity')
    # Время снятия заявки, 0 для активных
    withdraw_time = DateTimeField('withdrawtime', TIME_FORMAT)
    withdraw_time.mapper = NullableDateTimeMapper(TIME_FORMAT)
    # Сообщение биржи в случае отказа выставить заявку
    result = StringField('result')
Ejemplo n.º 25
0
class ConfigurationItem(Text):
    ROOT_NAME = "text"
    id = StringField("@id")
Ejemplo n.º 26
0
class Detail(OrderedXmlObject, IdNode):
    """
    <detail id="">
        <title><text/></title>
        <lookup action="" image="" name="">
            <extra key="" value = "" />
            <response key ="" />
        </lookup>
        <variables>
            <__ function=""/>
        </variables>
        <field sort="">
            <header form="" width=""><text/></header>
            <template form=""  width=""><text/></template>
        </field>
    </detail>
    """

    ROOT_NAME = 'detail'
    ORDER = ('title', 'lookup', 'details', 'fields')

    nodeset = StringField('@nodeset')
    print_template = StringField('@print-template')

    title = NodeField('title/text', Text)
    lookup = NodeField('lookup', Lookup)
    fields = NodeListField('field', Field)
    actions = NodeListField('action', Action)
    details = NodeListField('detail', "self")
    _variables = NodeField('variables', DetailVariableList)
    relevant = StringField('@relevant')

    def _init_variables(self):
        if self._variables is None:
            self._variables = DetailVariableList()

    def get_variables(self):
        self._init_variables()
        return self._variables.variables

    def set_variables(self, value):
        self._init_variables()
        self._variables.variables = value

    variables = property(get_variables, set_variables)

    def get_all_xpaths(self):
        result = set()

        if self.nodeset:
            result.add(self.nodeset)
        if self._variables:
            for variable in self.variables:
                result.add(variable.function)

        if self.actions:
            for action in self.actions:
                for frame in action.stack.frames:
                    result.add(frame.if_clause)
                    for datum in getattr(frame, 'datums', []):
                        result.add(datum.value)

        def _get_graph_config_xpaths(configuration):
            result = set()
            for config in configuration.configs:
                result.add(config.xpath_function)
            return result

        for field in self.fields:
            if field.template.form == 'graph':
                s = etree.tostring(field.template.node)
                template = load_xmlobject_from_string(s, xmlclass=GraphTemplate)
                result.update(_get_graph_config_xpaths(template.graph.configuration))
                for series in template.graph.series:
                    result.add(series.nodeset)
                    result.update(_get_graph_config_xpaths(series.configuration))
            else:
                result.add(field.header.text.xpath_function)
                result.add(field.template.text.xpath_function)

        for detail in self.details:
            result.update(detail.get_all_xpaths())
        result.discard(None)
        return result
Ejemplo n.º 27
0
class Response(XmlObject):
    ROOT_NAME = 'response'

    key = StringField("@key")
Ejemplo n.º 28
0
class Extra(XmlObject):
    ROOT_NAME = 'extra'

    key = StringField("@key")
    value = StringField("@value")
Ejemplo n.º 29
0
class Locale(XmlObject):
    ROOT_NAME = 'locale'
    id = StringField('@id')
    child_id = NodeField('id', Id)
    arguments = NodeListField('argument', LocaleArgument)
Ejemplo n.º 30
0
class AbstractTemplate(XmlObject):
    form = StringField('@form', choices=['image', 'phone', 'address'])
    width = IntegerField('@width')
    text = NodeField('text', Text)