Exemple #1
0
def set_device_fence():
    """设置设备的围栏参数
    """
    user = g.user
    device_id = request.values.get('device_id')
    data = {}
    for k, v in request.args.items():
        data[k] = v

    fence = model.Fence.get_or_new(device_id=device_id)
    object_assign(fence, data)
    if fence.type not in FenceType.ALL:
        return ErrorReturn(ErrorDefs.ParameterInvalid).response
    fence.index = int(fence.index)
    fence.enable = int(fence.enable)
    fence.cx = float(fence.cx)
    fence.cy = float(fence.cy)
    fence.radius = int(fence.radius)
    fence.x1 = float(fence.x1)
    fence.y1 = float(fence.y1)
    fence.x2 = float(fence.x2)
    fence.y2 = float(fence.y2)
    fence.alarm_type = int(fence.alarm_type)

    device = model.Device.get(device_id=device_id)
    main = instance.serviceManager.get('main')
    # 发送设置围栏命令
    cmd = ''
    cc = main.getCommandController(device.device_type)
    if fence.type == FenceType.CIRCLE:
        cmd = cc.setCircleFence(fence.cx, fence.cy, fence.radius, fence.inout)
    if cmd:
        main.sendCommand(device_id, cmd)
    fence.save()
    return CR().response
Exemple #2
0
 def get(cls, **kwargs):
     obj = cls()
     coll = get_database()[cls.__name__]
     data = coll.find_one(kwargs)
     if data:
         object_assign(obj, data)
         return obj
     return None
Exemple #3
0
 def get(cls, id):
     obj = cls()
     coll = database[obj.__collection__]
     data = coll.find_one({'_id': ObjectId(id)})
     if data:
         object_assign(obj, data)
         return obj
     return None
def init_product_list():
    content = YamlConfigParser('./product-list.yaml').props.get('product_list')

    for profile in content:
        product = model.Product.get_or_new(sku=profile['sku'])
        # product = model.Product()
        object_assign(product, profile)
        product.update_time = timestamp_current()
        product.save()
Exemple #5
0
 def __init__(self, level=DEBUG, **kwargs):
     Model.__init__(self)
     self.strategy_id = ''
     self.code = ''
     self.issue_time = datetime.datetime.now()
     self.level = level
     self.title = ''
     self.message = ''
     object_assign(self, kwargs, True)
Exemple #6
0
def get_last_position():
    """查询设备最近的位置信息
    """
    user = g.user
    device_id = request.values.get('device_id')
    data = _get_last_position(device_id)
    pos = model.Position()
    object_assign(pos, data)
    # return CR(result=pos.__dict__).response
    return CR(result=data).response
Exemple #7
0
def update_wxsystem_info():
    """更新微信系统信息 , 一个微信账户可能在多台主机登录"""
    user = g.user
    props = request.values.to_dict()
    wxsys = model.WxSystemInfo.get_or_new(user_id=user.id)
    object_assign(wxsys, props)
    wxsys.open_id = g.auth.open_id
    wxsys.save()

    return CR().response
Exemple #8
0
 def find(cls, **kwargs):
     clsname = cls.__name__
     coll = get_database()[clsname]
     rs = coll.find(kwargs)
     result = []
     for r in list(rs):
         obj = cls()
         object_assign(obj, r)
         result.append(obj)
     return result
Exemple #9
0
 def from_dict(self, data):
     object_assign(self, data)
     self.location_ext.from_dict(data)
     data.update(self.simple_info.dict())
     data.update({
         'voltage': self.voltage,
         'gsm': self.gsm,
         'alarm': self.alarm,
         'lang': self.lang
     })
Exemple #10
0
    def setConfig(self, **kwargs):
        """设置配置参数
          如果提供 'file' ,则从配置文件读取,其它参数覆盖已存在的配置项目
          setConfig(broker_id='999',user_id='778261',...)

        """
        if kwargs.has_key('file'):
            pass
        object_assign(self.conf, kwargs)
        return self
Exemple #11
0
 def from_dict(self, data):
     self.location.from_dict(data)
     object_assign(self, data)
     self.location_ext.from_dict(data)
     self.simple_info.from_dict(data)
     self.voltage = data.get('voltage', VoltageValue.EMPTY.value)
     self.gsm = data.get('gsm', GSMSignalValue.EMPTY.value)
     self.alarm = data.get('alarm', AlarmType.OK.value)
     self.lang = data.get('lang', LanguageValue.CHINESE)
     self.miles = data.get('miles', 0)
Exemple #12
0
def update_wxuser_info():
    """更新微信用户信息"""
    user = g.user

    wxuser = model.WxUser.get_or_new(user_id=user.id)
    props = request.values.to_dict()
    object_assign(wxuser, props)
    wxuser.user_id = user.id
    wxuser.open_id = g.auth.open_id
    wxuser.save()
    return CR().response
Exemple #13
0
def token_decode(token):
    auth = None
    try:
        data = base64.b64decode(token)
        data = json.loads(data)
        return data
        auth = AuthToken()
        object_assign(auth, data)

    except:
        instance.getLogger().warn('Request Token is invalid. Token: {}'.format(
            str(token)))
    return auth
Exemple #14
0
    def spawn(cls, data):
        """根据mongo查询的数据集合返回类实例"""

        # 单个对象
        if isinstance(data, dict):
            obj = cls()
            object_assign(obj, data)
            return obj
        # 集合
        rs = []
        for r in data:
            obj = cls()
            object_assign(obj, data)
            rs.append(obj)
        return rs
Exemple #15
0
def get_cargo_address_list():
    """查询本人创建的共享设备信息
        支持 共享设备编号查询 或 设备编号查询
        如果共享记录未创建则创建,并返回
    """
    user = g.user
    address_list = model.CargoAddress.collection().find({
        'user_id': user.id
    }).sort('order', pymongo.ASCENDING)
    result = []
    for address in list(address_list):
        object = model.CargoAddress()
        object_assign(object, address)
        result.append(object.dict())
    return CR(result=result).response
Exemple #16
0
def update_cargo_address():
    """
    """
    user = g.user
    id = request.values.get('id')
    is_default = request.values.get('is_default', 0, type=int)
    order = request.values.get('order', 0, type=int)
    props = request.values.to_dict()
    address = model.CargoAddress.get(_id=ObjectId(id))
    if not address:
        return ErrorReturn(ErrorDefs.ObjectNotExist, u'请求对象不存在').response
    object_assign(address, props)
    address.is_default = is_default
    address.user_id = user.id
    address.update_time = timestamp_current()
    address.save()
    return CR(result=address.id).response
Exemple #17
0
def getPosition(conn_id):
    """查询指定 代码或者指定策略的持仓记录"""
    conn = model.ConnectionUrl.get(id=conn_id)
    url = conn.td_api_url + '/ctp/position/list'
    result = []
    try:
        res = requests.get(url, timeout=3)
        values = res.json().get('result', [])
        for _ in values:
            if not _.get('InstrumentID'):
                continue
            pos = Position()
            object_assign(pos, _)
            result.append(pos)
    except:
        traceback.print_exc()
    return result
Exemple #18
0
def getTradeRecords(conn_id):
    conn = model.ConnectionUrl.get(id=conn_id)
    url = conn.td_api_url + '/ctp/trade/list'

    result = []
    try:
        res = requests.get(url, timeout=3)
        values = res.json().get('result', [])

        for _ in values:
            tr = TradeReturn()
            object_assign(tr, _)
            tr.normalize()

            result.append(tr)
    except:
        traceback.print_exc()
    return result
Exemple #19
0
def parse(data):
    if isinstance(data, str):
        data = json.loads(data)

    method = data.get('method')
    if not method:
        return None
    CLS = MessageClsDict.get(method)
    if not CLS:
        return None
    msg = CLS()
    try:
        object_assign(msg, data)
        if data.has_key('params'):
            object_assign(msg, data['params'])
    except:
        return None
    return msg
Exemple #20
0
def getOrders(conn_id):
    """查询委托信息,状态包括: 未成、部分成、全成、错误
        strategy_id 作为 委托的 orign source  字段
    """
    conn = model.ConnectionUrl.get(id=conn_id)
    url = conn.td_api_url + '/ctp/order/list'

    orders = []
    try:
        res = requests.get(url, timeout=3)
        values = res.json().get('result', [])

        for _ in values:
            if not _.get('InstrumentID'):
                continue
            order = OrderRecord()
            object_assign(order, _)
            order.normalize()
            orders.append(order)
    except:
        traceback.print_exc()
    return orders
Exemple #21
0
def report_device_status():
    '''上报设备状态'''
    from dateutil.parser import parse

    from mantis.fundamental.utils.useful import object_assign
    import time
    dev_type = request.values.get('dev_type', type=int)
    dev_id = request.values.get('dev_id', '')
    time = request.values.get('time', 0)
    ver = request.values.get('ver', '')
    detail = request.values.get('detail', '')

    start = request.values.get('start', 0)
    elapsed = request.values.get('elapsed', '')

    if time:
        time = datetime.datetime.fromtimestamp(float(time))
    else:
        time = None

    # 支持任意多的状态参数输入
    fields = request.values.to_dict()

    fields.update(
        dict(name='',
             type=dev_type,
             id=dev_id,
             time=time,
             ip=request.remote_addr.split(':')[-1],
             os='',
             ver='',
             sys_time=datetime.datetime.now(),
             detail=detail))

    _ = model.DeviceBaseStatus()
    object_assign(_, fields, add_new=True)
    _.save()

    return CR().response
Exemple #22
0
def quoteTickRecv(message, ctx):
    """Tick进入,推送到不同的k线周期处理对象"""
    # print '== current thread: ',threading.current_thread().ident

    data = message
    data = json.loads(data)
    data['DateTime'] = datetime.datetime.strptime(data['DateTime'],
                                                  '%Y%m%d %H:%M:%S.%f')
    tick = TickData()
    object_assign(tick, data, add_new=True)
    tick.datetime = data['DateTime']

    # print 'symbol:',tick.InstrumentID, ' datetime:',tick.DateTime

    symbol = tick.InstrumentID
    ws = workerset_list.get(symbol)
    if not ws:
        ws = worker.BarWorkerSet(symbol, onBar).init()
        workerset_list[symbol] = ws

    if TickFilter().filter(tick):  # 是否有效时间段的tick
        ws.onTick(tick)
Exemple #23
0
def get_trade_contract_data(symbol):
    """查询合约 相关的全部信息,包括:高低限价,手续费,开仓平仓费用等等
    """
    from mantis.trade.objects import TradeContractData
    contract = get_contract_detail(symbol)
    market = get_depth_market_data(symbol)

    commission = get_contract_commission_rate(symbol)
    data = None
    if contract and market and commission:
        data = TradeContractData()

        object_assign(data,market.__dict__)
        object_assign(data,commission.__dict__)
        object_assign(data, contract.__dict__)
    return data
Exemple #24
0
 def assign(self, data):
     object_assign(self, data)
     return self
Exemple #25
0
 def assign(self, data):
     object_assign(self.price, data)
     object_assign(self, data)
     return self
Exemple #26
0
 def from_dict(self, data):
     object_assign(self, data)
Exemple #27
0
 def assign(self, data):
     object_assign(self, data)
Exemple #28
0
 def get_or_new(cls, **kwargs):
     obj = cls.get(**kwargs)
     if not obj:
         obj = cls()
         object_assign(obj, kwargs)
     return obj
Exemple #29
0
def quoteTickRecv(message, ctx):
    """Tick进入,推送到不同的k线周期处理对象"""
    # print '== current thread: ',threading.current_thread().ident

    data = message
    data = json.loads(data)

    # tick = TickData()
    # object_assign(tick, data, add_new=True)
    # 这个DateTime 是交易日YMD+ 当日HMS
    # 恶心的问题,在于非交易时间接收的tick的HMS居然也是错误的,shit,所以过滤是否有效tick要判断SaveTime字段了

    data['DateTime'] = datetime.datetime.strptime(data['DateTime'],
                                                  '%Y%m%d %H:%M:%S.%f')
    # data['SaveTime'] = datetime.datetime.strptime(data['SaveTime'], '%Y%m%d %H:%M:%S.%f')
    data['SaveTime'] = datetime.datetime.now()

    # 剔除 savetime 与 datetime 相距1分钟的tick
    a = data['DateTime'].replace(2019, 1, 1)
    b = data['SaveTime'].replace(2019, 1, 1)
    if abs(datetime_to_timestamp(a) - datetime_to_timestamp(b)) > 60:
        return

    a = data['DateTime']
    b = datetime.datetime.now()
    if a > b and (a - b).seconds > 120:
        # return
        pass

    symbol = data['InstrumentID']  # 合约名称
    prd_name = TickFix.get_product_code(symbol).upper()

    # where TradeData='2019-10-9'  order by SaveTime asc
    p = TickFix.Products.get(prd_name)
    if p:
        if TickFix.is_in_trading_time(
                data['DateTime'],
                p):  # and TickFix.is_in_trading_time( data['SaveTime'], p):
            rt = data['DateTime']
            # 夜盘时间
            if rt.time() >= datetime.time(
                    hour=21) and rt.time() <= datetime.time(
                        hour=23, minute=59, second=59,
                        microsecond=1000000 - 1):
                # 郑州以晚上21点开盘为交易日,其他交易所以隔日为交易日
                # 为保证夜盘时间在前,将非郑州的行情记录时间(21-00)算为交易日前一天晚间的记录,交易日跳跃多日的情况,夜间开盘日期会不准
                if p['exchange'] != 'ZCE':
                    rt = rt - datetime.timedelta(
                        days=1)  # 夜盘期间的tick日期记录为交易日的前一天

            data['RealTime'] = rt
            day = data['TradingDay']  # 20190917
            trade_date = datetime.datetime.strptime(day, '%Y%m%d')
            data['TradeDate'] = trade_date

            time = '20001010 ' + data['UpdateTime'] + '.' + str(
                data['UpdateMillisec'])
            trade_time = datetime.datetime.strptime(time, '%Y%m%d %H:%M:%S.%f')
            data['TradeTime'] = trade_time
        else:
            return
    else:
        return

    tick = TickData()
    object_assign(tick, data, add_new=True)
    tick.datetime = data['RealTime']

    # print 'symbol:',tick.InstrumentID, ' datetime:',tick.DateTime

    symbol = tick.InstrumentID
    ws = workerset_list.get(symbol)
    if not ws:
        ws = worker.BarWorkerSet(symbol, onBar).init()
        workerset_list[symbol] = ws

    # if TickFilter().filter(tick):  # 是否有效时间段的tick
    ws.onTick(tick)
Exemple #30
0
 def create(cls, **kwargs):
     obj = cls()
     object_assign(obj, kwargs)
     return obj