Beispiel #1
0
 class Character(models.Model):
     n = models.IntegerField()
     m = models.CharField()
     word = models.ReferenceField(Word)
Beispiel #2
0
 class Person(models.Model):
     name = models.Attribute()
     friend = models.ReferenceField('Person')
Beispiel #3
0
class Order(models.Model):
    OS_NONE, OS_NEW, OS_CANCELED, OS_FILLED, OS_CLOSING, OS_CLOSED, OS_REJECTED = range(
        7)
    account = models.ReferenceField('Account')
    local_id = models.Attribute()
    sys_id = models.Attribute(default='')
    strategy_code = models.Attribute(default='')
    instrument = models.ReferenceField(Instrument)
    is_long = models.BooleanField(indexed=False)
    is_open = models.BooleanField(indexed=True)
    order_time = models.DateTimeField()
    price = models.FloatField(indexed=False)
    volume = models.FloatField(indexed=False)
    status = models.IntegerField(default=OS_NONE)
    orig_order = models.ReferenceField('Order', related_name='close_orders')
    stop_profit_offset = models.FloatField(indexed=False, default=0.0)  # 止赢偏离值
    stoploss = models.FloatField(indexed=False, default=0.0)  # 止损价
    stopprofit = models.FloatField(indexed=False, default=0.0)  # 止赢价

    def __repr__(self):
        return u'<Order: {0.id}({0.instrument}:{0.opened_volume})>'.format(
            self)

    def is_closed(self):
        return self.status == Order.OS_CLOSED

    @property
    def currency(self):
        return self.instrument.quoted_currency

    @property
    def can_close(self):
        return self.status == Order.OS_FILLED

    @property
    def can_cancel(self):
        if self.status in (Order.OS_NONE, Order.OS_NEW):
            return True
        elif self.status == Order.OS_FILLED:
            if abs(self.filled_volume) < abs(self.volume):
                return True
        return False

    @property
    def trades(self):
        return Trade.objects.filter(order_id=self.id).order('trade_time')

    @property
    def filled_volume(self):
        return sum([trade.volume for trade in self.trades])

    @property
    def closed_volume(self):
        return sum([trade.closed_volume for trade in self.trades])

    @property
    def opened_volume(self):
        """ 剩余开仓量 """
        return sum([trade.opened_volume for trade in self.trades])

    @property
    def opened_amount(self):
        return sum([trade.opened_amount for trade in self.trades])

    @property
    def commission(self):
        return sum([trade.commission for trade in self.trades])

    @property
    def real_profit(self):
        return sum([trade.profit for trade in self.trades])

    @property
    def trade_amt(self):
        return sum([trade.amount for trade in self.trades])

    @property
    def avg_fill_price(self):
        if self.filled_volume:
            if self.instrument.indirect_quotation:
                return self.filled_volume * self.instrument.multiplier / self.trade_amt
            else:
                return self.trade_amt / (self.filled_volume *
                                         self.instrument.multiplier)
        return None

    @property
    def cur_price(self):
        return current_price(self.instrument.secid, self.opened_volume > 0)

    @property
    def strategy(self):
        return STRATEGIES.get(self.strategy_code)

    def delete(self, *args, **kwargs):
        for t in self.trades:
            t.delete()
        super(Order, self).delete(*args, **kwargs)

    def update_index_value(self, att, value):
        assert att in ('status', 'is_open', 'local_id', 'sys_id')
        pipeline = self.db.pipeline()
        # remove from old index
        indkey = self._index_key_for_attr_val(att, getattr(self, att))
        pipeline.srem(indkey, self.id)
        pipeline.srem(self.key()['_indices'], indkey)
        # add to new index
        # in version 0.1.4 there is a bug in self._add_to_index(att, value, pipeline):
        #      the val paramter doesnot work, it's ignored.
        # so i have to hardcode it as following
        t, index = self._index_key_for(att, value)
        if t == 'attribute':
            pipeline.sadd(index, self.id)
            pipeline.sadd(self.key()['_indices'], index)
        elif t == 'list':
            for i in index:
                pipeline.sadd(i, self.id)
                pipeline.sadd(self.key()['_indices'], i)
        elif t == 'sortedset':
            zindex, index = index
            pipeline.sadd(index, self.id)
            pipeline.sadd(self.key()['_indices'], index)
            descriptor = self.attributes[att]
            score = descriptor.typecast_for_storage(value)
            pipeline.zadd(zindex, self.id, score)
            pipeline.sadd(self.key()['_zindices'], zindex)
        # set db value
        pipeline.hset(self.key(), att, value)
        pipeline.execute()
        # set instance value
        setattr(self, att, value)

    def update_status(self, value):
        value = int(value)
        assert 0 <= value < 7
        logger.debug('update order {2} status from {0} to {1}'.format(
            getattr(self, 'status'), value, self.sys_id))
        self.update_index_value('status', value)

    def change_to_open_order(self):
        self.update_index_value('is_open', 1)

    def update_local_id(self, value):
        value = str(value)
        self.update_index_value('local_id', value)

    def update_sys_id(self, value):
        value = str(value)
        self.update_index_value('sys_id', value)

    def update_float_value(self, att, value):
        assert att in ('stoploss', 'stopprofit', 'stop_profit_offset',
                       'volume')
        value = float(value)
        self.db.hset(self.key(), att, value)
        setattr(self, att, value)

    def update_stopprice(self, stoploss=None, stopprofit=None):
        if stoploss is not None:
            self.update_float_value('stoploss', stoploss)
        if stopprofit is not None:
            self.update_float_value('stopprofit', stopprofit)

    def update_stop_profit_offset(self, value):
        self.update_float_value('stop_profit_offset', value)

    def margin(self, cur_price=None):
        cur_price = cur_price or self.cur_price
        return self.instrument.calc_margin(cur_price, self.opened_volume)

    def float_profit(self, cur_price=None):
        cur_price = cur_price or self.cur_price
        profit = self.instrument.amount(
            cur_price, self.opened_volume) - self.opened_amount
        if self.instrument.indirect_quotation:
            profit *= -1
        return profit

    def on_new(self, orderid, instid, direction, price, volume, exectime):
        instrument = Instrument.objects.filter(secid=instid).first()
        #assert self.is_open is not None
        self.sys_id = orderid
        self.instrument = instrument
        self.is_long = direction
        self.price = float(price)
        self.volume = float(volume)
        self.order_time = exectime
        self.status = Order.OS_NEW
        assert self.is_valid(), self.errors
        self.save()

    def on_trade(self, price, volume, tradetime, execid):
        assert self.is_open is not None
        # check duplicate trade
        if Trade.objects.filter(exec_id=execid):
            logger.debug(u'EXECID {0} 已经存在!'.format(execid))
            return False
        if not self.is_long:
            volume = -volume
        t = Trade(order=self)
        t.on_trade(price, volume, tradetime, execid, self.is_open)
        self.update_status(Order.OS_FILLED)
        logger.info(u'<策略{0}>成交回报: {1}{2}仓 合约={3} 价格={4} 数量={5}'.format(
            self.strategy_code,
            u'开' if self.is_open else u'平',
            u'多' if self.is_long == self.is_open else u'空',
            self.instrument.name,
            price,
            volume,
        ))
        return t

    def set_stopprice(self, price, offset_loss=0.0, offset_profit=0.0):
        # 静态止赢价
        if offset_profit and not self.stopprofit:
            if self.is_long:
                stopprofit = price + offset_profit
            else:
                stopprofit = price - offset_profit
            self.update_stopprice(stopprofit=stopprofit)
            logger.debug('Order {0} set stop profit price to {1}'.format(
                self.sys_id, self.stopprofit))
        # 浮动止损价
        if offset_loss:
            if self.is_long:
                stoploss = price - offset_loss
                if self.stoploss and stoploss <= self.stoploss:
                    return
            else:
                stoploss = price + offset_loss
                if self.stoploss and stoploss >= self.stoploss:
                    return
            self.update_stopprice(stoploss)
            logger.debug('Order {0} set stop loss price to {1}'.format(
                self.sys_id, self.stoploss))

    def on_close(self, trade):
        trade.on_close()
        if abs(self.orig_order.closed_volume) >= abs(
                self.orig_order.filled_volume):
            self.orig_order.update_status(Order.OS_CLOSED)
            logger.debug(u'订单{0}已全部平仓'.format(self.orig_order.sys_id))
        if (abs(self.closed_volume) >= abs(self.volume)) or (abs(
                self.closed_volume) >= abs(self.orig_order.filled_volume)):
            self.update_status(Order.OS_CLOSED)
            logger.debug(u'订单{0}已全部平仓'.format(self.sys_id))
Beispiel #4
0
 class User(models.Model):
     name = models.CharField()
     address = models.ReferenceField('Address')
Beispiel #5
0
 class Person(models.Model):
     name = models.Attribute(required=True)
     manager = models.ReferenceField('Person', related_name='underlings')
     department = models.ReferenceField(Department)
Beispiel #6
0
class Instrument(models.Model):
    """
    >>> i = Instrument(secid='XX1505', name='XX 2015/05', symbol='XX-1505', quoted_currency='USD', multiplier=10.0)
    >>> print i
    XX-1505
    """
    secid = models.Attribute(required=True)
    name = models.Attribute(required=True)
    symbol = models.Attribute(required=True)
    exchangeid = models.Attribute()
    product = models.ReferenceField('Product')
    quoted_currency = models.Attribute(required=True, indexed=False)
    indirect_quotation = models.BooleanField(indexed=False)
    ndigits = models.IntegerField(indexed=False, default=2)
    multiplier = models.FloatField(indexed=False)
    open_commission_rate = models.FloatField(indexed=False, default=0)
    close_commission_rate = models.FloatField(indexed=False, default=0)
    tick_size = models.FloatField(indexed=False)
    tick_value = models.FloatField(indexed=False)
    min_order_volume = models.FloatField(indexed=False, default=1.0)
    max_order_volume = models.FloatField(indexed=False, default=99999999.0)
    effective_date = models.DateField(indexed=False)
    expire_date = models.DateField(indexed=False)
    is_trading = models.BooleanField()
    long_margin_ratio = models.FloatField(indexed=False)
    short_margin_ratio = models.FloatField(indexed=False)
    volume = models.FloatField(indexed=False)

    def __repr__(self):
        return self.symbol

    def amount(self, price, volume):
        if not price:
            return 0.0
        if self.indirect_quotation:
            return volume * self.multiplier / price
        else:
            return volume * self.multiplier * price

    def calc_margin(self, price, volume, direction=None):
        if direction:
            return abs(self.amount(price, volume) * self.long_margin_ratio)
        else:
            return abs(self.amount(price, volume) * self.short_margin_ratio)

    def amount2volume(self, amt, price):
        if not price:
            return 0.0
        if self.indirect_quotation:
            return amt * price / self.multiplier
        else:
            return amt / price / self.multiplier

    def margin2volume(self, margin, price, direction=None):
        if direction:
            amt = margin / self.long_margin_ratio
        else:
            amt = margin / self.short_margin_ratio
        return self.amount2volume(amt, price)

    def calc_commission(self, price, volume, is_open):
        if is_open:
            if self.open_commission_rate is None:
                self.open_commission_rate = 0.000025
            commission = abs(self.amount(price,
                                         volume)) * self.open_commission_rate
        else:
            if self.close_commission_rate is None:
                self.close_commission_rate = 0.000025
            commission = abs(self.amount(price,
                                         volume)) * self.close_commission_rate
        ndigits = self.ndigits or 2
        return round(commission, ndigits)

    @classmethod
    def symbol2id(cls, symbol):
        instance = cls.objects.filter(symbol=symbol).first()
        if instance:
            return instance.secid

    @classmethod
    def from_id(cls, secid):
        return cls.objects.filter(secid=secid).first()

    @classmethod
    def all_ids(cls):
        return [obj.secid for obj in cls.objects.all()]

    def deadline(self):
        if self.exchangeid in ('DCE', 'CZCE'):  # 大连/郑州
            d = self.expire_date.replace(day=1) - datetime.date.resolution
            while d.weekday() >= 5:  # weekend
                d = d - datetime.date.resolution
            t = datetime.time(14, 0)
        elif self.exchangeid == 'SHFE':  # 上期
            d = self.expire_date - datetime.timedelta(3)
            t = datetime.time(14, 0)
        elif self.exchangeid == 'CFFEX':  # 中金所
            d = self.expire_date
            t = datetime.time(14, 55)
        else:
            d = self.expire_date
            t = datetime.time(23, 59)
        return datetime.datetime.combine(d, t)
class Comment(models.Model):
    comment_id = models.IntegerField(indexed=True)
    created_at = models.DateTimeField(auto_now_add=True, indexed=True)
    comment = models.Attribute(required=True, indexed=True)
    user = models.ReferenceField(User, indexed=True)
Beispiel #8
0
class Post(db.Model):
    title = db.Attribute(required=True)
    slug = db.Attribute(required=True)
    markdown = db.Attribute(indexed=False)
    content = db.Attribute(indexed=False)
    image = db.Attribute(indexed=False)
    featured = db.BooleanField()
    page = db.BooleanField()
    status = db.Attribute(required=True)
    language = db.Attribute(indexed=False)
    meta_title = db.Attribute(indexed=False)
    meta_description = db.Attribute(indexed=False)
    updated_at = db.DateTimeField(auto_now=True)
    updated_by = db.ReferenceField(User)
    published_at = db.DateTimeField()
    created_at = db.DateTimeField()
    created_by = db.ReferenceField(User)
    author = db.ReferenceField(User)
    publishedBy = db.ReferenceField(User)
    categories = db.ListField(Category)
    tags = db.ListField(Tag)

    # 相对于站点目录的路径,全小写
    path = db.Attribute(required=False, indexed=False)
    # 文档的完整路径, 全小写
    full_path = db.Attribute(required=False, indexed=False)
    # 文档的完整路径, 保留大小写
    raw_path = db.Attribute(required=False, indexed=False)
    # path的父目录路径
    parent_path = db.Attribute(required=False, indexed=False)
    # full_path的父目录路径
    parent_full_path = db.Attribute(required=False, indexed=False)
    # raw_path的父目录路径
    parent_raw_path = db.Attribute(required=False, indexed=False)
    # 文档类型,有folder/post/image/file四种
    type = db.Attribute(required=False, indexed=False)
    # 文档的时间,比如可作为文章的发表时间
    date = db.DateTimeField(auto_now=True)
    # 文档最后修改时间,评论文章也会导致m_date变动
    m_date = db.Attribute(required=False, indexed=False)
    # 文档的最后修改时间
    raw_date = db.Attribute(required=False, indexed=False)
    # 用户自定义的位置, 浮点数类型
    position = db.Attribute(required=False, indexed=False)
    # 文档的大小
    size = db.Attribute(required=False, indexed=False)
    # 内容类型,比如image/jpeg
    content_type = db.Attribute(required=False, indexed=False)
    visits = db.Attribute(required=False, indexed=False)
    # 在不改变文件路径的前提下,约等于访问IP数
    _visits = db.Attribute(required=False, indexed=False)
    # 文件后缀名,比如jpg txt
    ext = db.Attribute(required=False, indexed=False)
    # TableOfContens, HTML格式
    toc = db.Attribute(required=False, indexed=False)
    # 文章封面, 从内容中提取出来的第一张图片
    cover = db.Attribute(required=False, indexed=False)
    # 纯文本格式的正文,不包含metadata
    raw_content = db.Attribute(required=False, indexed=False)
    # 原始正文,包含metadata信息
    _content = db.Attribute(required=False, indexed=False)
    # post的扩展属性
    metadata = db.Attribute(required=False, indexed=False)
    # 自定义的url
    url_path = db.Attribute(required=False, indexed=False)
    # '/post/’+url_path 或 /+url_path,视情况而定
    url = db.Attribute(required=False, indexed=False)
    # 评论数
    comments_count = db.Attribute(required=False, indexed=False)
    # 恒等于1
    posts_count = db.Attribute(required=False, indexed=False)

    def __repr__(self):
        return "<Post: {post.id} Title: {post.title}>".format(post=self)

    def to_json(self):
        rtn = self.attributes_dict
        rtn["id"] = self.id
        rtn["date"] = format_now_datetime(self.published_at)
        rtn["updated_at"] = format_now_datetime(self.updated_at)
        rtn["updated_by"] = self.updated_by.id if self.updated_by else None
        rtn["published_at"] = format_now_datetime(self.published_at)
        rtn["created_at"] = format_now_datetime(self.created_at)
        rtn["created_by"] = self.created_by.id if self.created_by else None
        rtn["publishedBy"] = self.publishedBy.id if self.publishedBy else None
        rtn["categories"] = [cate.to_json() for cate in self.categories]
        rtn["tags"] = [tag.to_json() for tag in self.tags]
        rtn["author"] = self.author.to_json()
        return rtn