Beispiel #1
0
class GameModel(models.Model):
    desk = models.Attribute()
    game_time = models.DateTimeField(auto_now_add=True)
    all_bet = models.IntegerField(default=0)
    all_paid = models.IntegerField(default=0)
    game_result = models.ListField(int)
    bank_cards = models.ListField(int)
    player_cards = models.ListField(int)
Beispiel #2
0
        class Exam(models.Model):
            score = models.IntegerField()
            total_score = models.IntegerField()

            def percent(self):
                return int((float(self.score) / self.total_score) * 100)

            class Meta:
                indices = ('percent', )
Beispiel #3
0
class Stock(models.Model):
    sc_code = models.IntegerField(required=True)
    sc_name = models.Attribute(required=True)
    created_at = models.DateTimeField(auto_now_add=True)
    sc_open = models.FloatField()
    sc_high = models.FloatField()
    sc_low = models.FloatField()
    sc_close = models.FloatField()
    sc_prevclose = models.FloatField()
    sc_volume = models.IntegerField()
Beispiel #4
0
class Role(db.Model):
    uuid = db.Attribute(indexed=False)
    name = db.Attribute(required=True)
    description = db.Attribute(indexed=False)
    created_at = db.DateTimeField()
    updated_at = db.DateTimeField()
    permission = db.IntegerField(required=True)

    def __repr__(self):
        return "<{}-{:04X}>".format(self.name, self.permission)

    def __str__(self):
        return self.__repr__()

    def __unicode__(self):
        return self.__repr__()

    def to_json(self, user):
        rst = self.attributes_dict
        rst["created_at"] = format_datetime(self.created_at)
        rst["updated_at"] = format_datetime(self.updated_at)
        rst["created_by"] = user.id
        rst["updated_by"] = user.id
        rst["id"] = self.id
        return rst
Beispiel #5
0
class Images(db.Model):
    post_id = db.IntegerField(required=True)
    status = db.Attribute(required=True, default="active")
    image_name = db.Attribute(indexed=False)
    height = db.IntegerField(indexed=False)
    width = db.IntegerField(indexed=False)
    url = db.Attribute(indexed=False)
    delete_url = db.Attribute()
    local_path = db.Attribute(indexed=False)

    def to_json(self):
        return {
            "id": self.id, "post_id": self.post_id,
            "image_name": self.image_name,
            "url": self.url, "local_path": self.local_path
        }
class Link(r_models.Model):
    """Model that represents a shortened URL."""

    short_url = r_models.Attribute(unique=True)
    url = r_models.Attribute(required=True)
    date_submitted = r_models.DateTimeField(auto_now_add=True)
    usage_count = r_models.IntegerField(default=0, indexed=True)
    is_custom = r_models.BooleanField()

    def __unicode__(self):
        return '%s : %s' % (self.url, self.short_url)

    def save(self, *args, **kwargs):
        if hasattr(self, 'id'):
            super(self.__class__, self).save(*args, **kwargs)
            return

        if self.is_custom:
            pass
        else:
            self.short_url = utils.get_short_url()

        while True:
            existing_link = self.__class__.objects.filter(
                short_url=self.short_url)
            if existing_link:
                if self.is_custom:
                    raise ValueError('Custom url already exists')
                else:
                    self.short_url = utils.get_short
            else:
                break
        super(self.__class__, self).save(*args, **kwargs)
class LogEntry(rmodels.Model):
    num = rmodels.IntegerField()
    time = rmodels.FloatField()
    date = rmodels.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Search index update statistic'
        verbose_name_plural = 'Search index update statistic'
        db = default_connection
Beispiel #8
0
class DomainInfo(re_models.Model):
    name = re_models.Attribute(required=True)
    created_at = re_models.DateTimeField(auto_now_add=True)
    res_code = re_models.IntegerField(default=0)
    alert = re_models.BooleanField(default=False)
    new_msg = re_models.BooleanField(default=True)
    address = re_models.ListField(str)
    no_ip = re_models.ListField(str)
    info = re_models.Attribute()
Beispiel #9
0
class PlayerModel(models.Model):
    playerId = models.Attribute()
    player_phone = models.Attribute(required=True)
    player_name = models.Attribute(required=True)
    player_password = models.Attribute()
    last_login = models.DateTimeField()
    player_points = models.Counter()
    player_vip = models.IntegerField(default=0)
    player_desk = models.Attribute()
Beispiel #10
0
class Comment(db.Model):
    # 评论者的用户名
    author_name = db.Attribute()
    # 评论者的邮箱,如果没有设置头像会根据这个信息从gravatar获取头像
    author_email = db.Attribute()
    # 评论者的URL,评论者头像或者名字会跳转到改URL
    author_url = db.Attribute()
    # 评论者的IP
    ip = db.Attribute()
    # 评论者User Agent信息,通常包括浏览器版本、引擎、设备等信息
    agent = db.Attribute()
    # 这条评论被【赞】的次数,该属性导入意义不大,会在被喜欢之后重新统计
    likes = db.IntegerField()
    # 对这条评论点了【举报】的次数
    reports = db.IntegerField()
    # 评论发表时间。
    created_at = db.DateTimeField()
    # 评论状态。
    status = db.IntegerField()
Beispiel #11
0
class UserInterface(models.Model):
    ''''''

    id = models.IntegerField(required=True, unique=True)
    user = models.Attribute(required=True, unique=True)
    pwd = models.Attribute()
    description = models.Attribute()
    email = models.Attribute()
    avatar = models.Attribute()
    last_login = models.DateTimeField(auto_now=True)
Beispiel #12
0
class Category(db.Model):
    name = db.Attribute(required=True)
    super = db.IntegerField()

    def to_json(self):
        jsn = {
            "id": self.id,
            "name": self.name
        }
        if self.super:
            jsn['super'] = self.super
        return jsn
Beispiel #13
0
class AccessToken(models.Model):
    """
    Model to store, in redis (via redisco) all tokens and their status
    """
    uid = models.Attribute(required=True, indexed=True, unique=True)
    login = models.Attribute(required=True, indexed=True)
    token = models.Attribute(required=True, indexed=True)
    backend = models.Attribute(required=True, indexed=True)
    status = models.IntegerField(required=True, indexed=True, default=200)
    last_use = models.DateTimeField(auto_now_add=True, auto_now=True)
    last_message = models.Attribute()

    def __unicode__(self):
        return str(self)

    def __str__(self):
        return self.uid

    def save(self):
        is_new = self.is_new()
        result = super(AccessToken, self).save()
        if result == True and is_new:
            self.release()
        return result

    def is_valid(self):
        """
        Overrive the default method to save the uid, which is unique (by
        concatenating backend and token)
        """
        self.uid = '%s:%s:%s' % (self.backend, self.login, self.token)
        return super(AccessToken, self).is_valid()

    def lock(self):
        """
        Set the token as currently used
        """
        return connection.srem(AVAILABLE_LIST_KEY, self.uid)

    def release(self):
        """
        Set the token as not currently used
        """
        return connection.sadd(AVAILABLE_LIST_KEY, self.uid)

    def set_status(self, code, message):
        """
        Set a new status and message for this token
        """
        self.status = code
        self.last_message = message
        self.save()
Beispiel #14
0
class Chairman(models.Model):
    id = models.Attribute(unique=True)
    # pk = models.Attribute(unique=True)
    title = models.Attribute()
    name = models.Attribute()
    href = models.Attribute()
    img = models.Attribute()
    num = models.IntegerField()
    desc = models.Attribute()
    type = models.Attribute()
    avatar = models.Attribute()

    object_name = 'chairman'

    def __init__(self, *args, **kwargs):
        super(Chairman, self).__init__(**kwargs)
        if 'ele' in kwargs:
            ele = json.loads(kwargs['ele'])
            self.id = ele['_id']
            self.title = ele['_title']
            self.name = ele['_name']
            self.href = ele['_href']
            self.num = ele['_num']
            self.img = ele['_img']
            self.desc = ele['_desc']
            self.type = ele['_type']
            self.avatar = ele['_avatar']

    def set_id(self, id):
        self.pk = id
        self.id = id

    def set_num(self, num):
        if '万' in num:
            self.num = int(
                round(
                    float(
                        num.replace('万', '').replace('\r', '').replace(
                            '\n', '')) * 10000))
        else:
            self.num = int(num)

    def __unicode__(self):
        return json.dumps(self,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)
Beispiel #15
0
 class Character(models.Model):
     n = models.IntegerField()
     m = models.CharField()
     word = models.ReferenceField(Word)
Beispiel #16
0
 class Tweet(models.Model):
     status_id = models.IntegerField()
Beispiel #17
0
 class Person(models.Model):
     age = models.IntegerField()
Beispiel #18
0
        class Ninja(models.Model):
            age = models.IntegerField(required=True)

            def validate(self):
                if self.age >= 10:
                    self._errors.append(('age', 'must be below 10'))
Beispiel #19
0
        class Ninja(models.Model):
            def validator(field_name, age):
                if not age or age >= 10:
                    return ((field_name, 'must be below 10'), )

            age = models.IntegerField(required=True, validator=validator)
Beispiel #20
0
 class Character(models.Model):
     n = models.IntegerField()
     m = models.CharField()
Beispiel #21
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 #22
0
class CardModel(models.Model):
    card_suit = models.Attribute()
    card_rank = models.IntegerField()
Beispiel #23
0
 class User(models.Model):
     views = models.IntegerField(default=199)
     liked = models.BooleanField(default=True)
     disliked = models.BooleanField(default=False)
Beispiel #24
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)
Beispiel #25
0
class BetModel(models.Model):
    bank = models.IntegerField()
    player = models.IntegerField()
    tie = models.IntegerField()
    bankPair = models.IntegerField()
    playerPair = models.IntegerField()
Beispiel #26
0
class AdminModel(models.Model):
    admin_name = models.Attribute(required=True, unique=True)
    admin_password = models.Attribute()
    admin_grade = models.IntegerField()
Beispiel #27
0
class HandSelModel(models.Model):
    sender = models.Attribute()
    receiver = models.Attribute()
    points = models.IntegerField()
    date = models.DateTimeField(auto_now_add=True)
    success = models.BooleanField(default=False)
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 #29
0
class AccessToken(models.Model):
    """
    Model to store, in redis (via redisco) all tokens and their status
    """
    uid = models.Attribute(required=True, indexed=True, unique=True)
    login = models.Attribute(required=True, indexed=True)
    token = models.Attribute(required=True, indexed=True)
    backend = models.Attribute(required=True, indexed=True)
    status = models.IntegerField(required=True, indexed=True, default=200)
    last_use = models.DateTimeField()
    last_message = models.Attribute()
    suspended_until = models.DateTimeField()

    def __unicode__(self):
        return str(self)

    def __str__(self):
        return self.uid

    def save(self):
        is_new = self.is_new()
        self.last_use = datetime.utcnow()
        result = super(AccessToken, self).save()
        if result is True and is_new:
            self.release()
        return result

    def is_valid(self):
        """
        Override the default method to save the uid, which is unique (by
        concatenating backend and token)
        """
        self.uid = '%s:%s:%s' % (self.backend, self.login, self.token)
        return super(AccessToken, self).is_valid()

    def lock(self):
        """
        Set the token as currently used
        """
        return connection.srem(AVAILABLE_LIST_KEY, self.uid)

    def release(self):
        """
        Set the token as not currently used
        """
        return connection.sadd(AVAILABLE_LIST_KEY, self.uid)

    def set_status(self, code, message):
        """
        Set a new status and message for this token
        """
        self.status = code
        self.last_message = message
        self.save()

    def suspend(self, suspended_until=None, message=None):
        """
        Suspend the token until the given utc timestamp
        """
        if suspended_until:
            self.suspended_until = datetime.utcfromtimestamp(suspended_until)
        else:
            self.suspended_until = None
        self.last_message = message
        self.save()

        if suspended_until:
            # We make the `suspended_until` key auto expire
            key = self.key('suspended_until')
            connection.expire(key, round(suspended_until - now_timestamp()) + 1)
Beispiel #30
0
class Cloud(db.Model):
    name = db.IntegerField(required=True)
    upload_url = db.IntegerField(required=True)
    app_key = db.Attribute(required=False)
    app_secret = db.Attribute(required=False)
    extras = db.Attribute(indexed=False)