Python demjson.encode() Examples

The following are code examples for showing how to use demjson.encode(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cms-grafana-builder   Author: sunny0826   File: aliyun_rds.py    Apache License 2.0 6 votes vote down vote up
def GenerateRdsDashboard(self, rds_list, line_template, panels_template, metric_list):
        dashboard_lines = []
        for index, metric in enumerate(metric_list):
            panels_lines = []
            for i, rds in enumerate(rds_list):
                template = readj2(line_template)
                panels_lines.append(
                    self.line_template(template=template, line_name=rds['name'], line_id=rds['id'], ycol="Average",
                                       metric=metric['field'], project="acs_rds_dashboard"))
            template = readj2(panels_template)
            dashboard_lines.append(
                self.panels_template(index=index, template=template, title=metric['name'], format=metric['format'],
                                     targets=demjson.encode(panels_lines)))
        dashboard_template = readj2("dashboard.json.j2")
        resultjson = dashboard_template.render(panels_card=demjson.encode(dashboard_lines), title="RDS监控", tag="RDS")
        # print(resultjson)
        return {'cms-{0}.json'.format(self.product): resultjson} 
Example 2
Project: cms-grafana-builder   Author: sunny0826   File: aliyun_eip.py    Apache License 2.0 6 votes vote down vote up
def GenerateEipDashboard(self, epi_list, line_template, panels_template, metric_list):
        dashboard_lines = []
        for index, metric in enumerate(metric_list):
            panels_lines = []
            for i, eip in enumerate(epi_list):
                template = readj2(line_template)
                panels_lines.append(self.line_template(template=template, line_name=eip['name'], line_id=eip['id'],
                                                       ycol=metric['ycol'], metric=metric['field'], period=60,
                                                       project="acs_vpc_eip"))
            template = readj2(panels_template)
            dashboard_lines.append(
                self.panels_template(index=index, template=template, title=metric['name'], format=metric['format'],
                                     redline=metric['redline'], targets=demjson.encode(panels_lines)))
        dashboard_template = readj2("dashboard.json.j2")
        resultjson = dashboard_template.render(panels_card=demjson.encode(dashboard_lines), title="EIP监控",
                                               tag="EIP")
        # print(resultjson)
        return {'cms-{0}.json'.format(self.product): resultjson} 
Example 3
Project: cms-grafana-builder   Author: sunny0826   File: aliyun_redis.py    Apache License 2.0 6 votes vote down vote up
def GenerateRedisDashboard(self, redis_list, line_template, panels_template, metric_list):
        dashboard_lines = []
        for index, metric in enumerate(metric_list):
            panels_lines = []
            for i, redis in enumerate(redis_list):
                template = readj2(line_template)
                panels_lines.append(
                    self.line_template(template=template, line_name=redis['name'], line_id=redis['id'], ycol="Average",
                                       metric=metric['field'], project="acs_kvstore"))
            template = readj2(panels_template)
            dashboard_lines.append(
                self.panels_template(index=index, template=template, title=metric['name'], format=metric['format'],
                                     redline=metric['redline'], targets=demjson.encode(panels_lines)))
        dashboard_template = readj2("dashboard.json.j2")
        resultjson = dashboard_template.render(panels_card=demjson.encode(dashboard_lines), title="redis资源监控",
                                               tag="Redis")
        # print(resultjson)
        return {'cms-{0}.json'.format(self.product): resultjson} 
Example 4
Project: cms-grafana-builder   Author: sunny0826   File: aliyun_ecs.py    Apache License 2.0 6 votes vote down vote up
def GenerateEcsDashboard(self, ecs_list, line_template, panels_template, metric_list):
        dashboard_lines = []
        for index, metric in enumerate(metric_list):
            panels_lines = []
            for i, ecs in enumerate(ecs_list):
                template = readj2(line_template)
                panels_lines.append(
                    self.line_template(template=template, line_name=ecs['name'], line_id=ecs['id'], ycol="Average",
                                       period=60, metric=metric['field'], project="acs_ecs_dashboard"))
            template = readj2(panels_template)
            dashboard_lines.append(
                self.panels_template(index=index, template=template, title=metric['name'], format=metric['format'],
                                     redline=metric['redline'], targets=demjson.encode(panels_lines)))
        dashboard_template = readj2("dashboard.json.j2")
        resultjson = dashboard_template.render(panels_card=demjson.encode(dashboard_lines), title="ECS资源监控",
                                               tag="ECS")
        # print(resultjson)
        return {'cms-{0}.json'.format(self.product): resultjson} 
Example 5
Project: CTPOrderService   Author: lllzzz   File: OrderRealClose.py    Mozilla Public License 2.0 6 votes vote down vote up
def __doSend(self, total, price):
        self.trytimes -= 1
        orderID = self.getOrderID()

        sendData = {
            'action': 'trade',
            'appKey': int(self.appKey),
            'orderID': int(orderID),
            'iid': self.iid,
            'type': self.ORDER_TYPE_FAK,
            'price': int(price),
            'total': int(total),
            'isBuy': int(self.isBuy),
            'isOpen': 0,
        }
        self.sender.publish(self.sendOrderCh, JSON.encode(sendData))
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderRealClose[sendOrder]', sendData) 
Example 6
Project: CTPOrderService   Author: lllzzz   File: OrderRealClose.py    Mozilla Public License 2.0 6 votes vote down vote up
def __sendIOC(self, total):
        orderID = self.getOrderID()

        sendData = {
            'action': 'trade',
            'appKey': int(self.appKey),
            'orderID': int(orderID),
            'iid': self.iid,
            'type': self.ORDER_TYPE_IOC,
            'price': 0,
            'total': int(total),
            'isBuy': int(self.isBuy),
            'isOpen': 0,
        }
        self.sender.publish(self.sendOrderCh, JSON.encode(sendData))
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderRealClose[sendIOC]', sendData) 
Example 7
Project: cms-grafana-builder   Author: sunny0826   File: aliyun_slb.py    Apache License 2.0 5 votes vote down vote up
def GenerateSlbDashboard(self, slb_list, card_template, panels_template, metric, thresholds, title):
        template = readj2(card_template)
        panels_cards = []
        for i, slb in enumerate(slb_list):
            panels_cards.append(self._card_template(index=i, template=template, slb_id=slb["id"], slb_name=slb["name"],
                                                    metric=metric, project="acs_slb_dashboard",
                                                    thresholds=thresholds))
        template = readj2(panels_template)
        resultjson = template.render(panels_card=demjson.encode(panels_cards), title=title, tag="SLB")
        # print(resultjson)
        # writej2('{0}/{1}.json'.format(self.check_dir(), metric), resultjson)
        # writej2("slb/" + metric + ".json", resultjson)
        return {'cms-{0}.json'.format(metric): resultjson} 
Example 8
Project: CF-Cannon   Author: LevyHsu   File: attack.py    GNU General Public License v3.0 5 votes vote down vote up
def attack():
    attackinfo = demjson.decode(request.form['attackinfo'])
    status = Bypass.getstatus()
    if status['Satus'] == 'STOP':
        threading.Thread(target=Bypass.goAttack, args=(attackinfo['T'],attackinfo['url'],attackinfo['path'],attackinfo['charset'],attackinfo['is_protected_by_cf'],attackinfo['threadCount'],attackinfo['peerCount'],attackinfo['keywords'])).start()
        return demjson.encode({'status': 'success'}),json
    else:
        return demjson.encode({'status': 'failed'}),json 
Example 9
Project: CF-Cannon   Author: LevyHsu   File: attack.py    GNU General Public License v3.0 5 votes vote down vote up
def status():
    return demjson.encode(Bypass.getstatus()),json 
Example 10
Project: fb-crawler   Author: Ardenhong   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def write_json_file(path,file_name,data):
    fo = open(path+file_name+'.json', 'w')
    fo.write(demjson.encode(data)) 
Example 11
Project: Siarobo   Author: siyanew   File: bot.py    MIT License 5 votes vote down vote up
def save_config():
    file = open(join(WD, "config.json"), "w")
    file.write(demjson.encode(config))
    file.close() 
Example 12
Project: CTPOrderService   Author: lllzzz   File: Base.py    Mozilla Public License 2.0 5 votes vote down vote up
def error(self, data):
        self.endOrder(self.iid)
        self.sender.publish(self.sendOrderRspCh, JSON.encode({'mid': self.mid, 'successVol': self.successVol}))
        # self.toDB()
        self.service.stop() 
Example 13
Project: CTPOrderService   Author: lllzzz   File: OrderRealClose.py    Mozilla Public License 2.0 5 votes vote down vote up
def process(self, channel, data):
        if channel != self.tradeRspCh: return
        if data['err'] > 0:
            self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderRealClose[error]', data)
            self.error(data['err'])
            return

    	data = data['data']
        if self.orderID != data['orderID']: return
        data['volWaiting'] = self.total
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderRealClose[process]', data)

        isOver = False
        type = data['type']
        if type == 'traded':
            vol = data['successVol']
            self.successVol += vol
            # 更新持仓
            if self.isBuy:
                self.sellVol(self.iid, vol, False)
            else:
                self.buyVol(self.iid, vol, False)

            # 判断是否结束
            self.total -= vol
            if self.total == 0:
                isOver = True

        if type == 'canceled':
            if self.trytimes == 0:
                self.__sendIOC(self.total)
            else:
                price = data['price']
                price = price + self.minTick if self.isBuy else price - self.minTick
                self.__doSend(self.total, price)

        if isOver:
            self.endOrder(self.iid)
            self.sender.publish(self.sendOrderRspCh, JSON.encode({'mid': self.mid, 'successVol': self.successVol}))
            self.toDB()
            self.service.stop() 
Example 14
Project: CTPOrderService   Author: lllzzz   File: OrderRealOpen.py    Mozilla Public License 2.0 5 votes vote down vote up
def process(self, channel, data):
        if channel != self.tradeRspCh: return
        if data['err'] > 0:
            self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderRealOpen[error]', data)
            self.error(data['err'])
            return

        data = data['data']
        if self.orderID != data['orderID']: return
        data['volWaiting'] = self.total
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderRealOpen[process]', data)

        isOver = False
        type = data['type']
        if type == 'traded':
            vol = data['successVol']
            self.successVol += vol
            # 更新持仓
            if self.isBuy:
                self.buyVol(self.iid, vol, True)
            else:
                self.sellVol(self.iid, vol, True)

            # 判断是否结束
            self.total -= vol
            if self.total == 0:
                isOver = True

        elif type == 'canceled':
            vol = data['cancelVol']
            self.total -= vol
            if self.total == 0:
                isOver = True

        if isOver:
            self.endOrder(self.iid)
            self.sender.publish(self.sendOrderRspCh, JSON.encode({'mid': self.mid, 'successVol': self.successVol}))
            self.toDB()
            self.service.stop() 
Example 15
Project: CTPOrderService   Author: lllzzz   File: OrderForecast.py    Mozilla Public License 2.0 5 votes vote down vote up
def __sendOrder(self):

        self.mid   = self.req['mid']
        self.cancelRange = int(self.req['cancelRange'])
        self.minTick = int(C.get('min_tick', self.req['iid']))
        self.cancelPriceH = int(self.req['cancelPriceH'])
        self.cancelPriceL = int(self.req['cancelPriceL'])
        self.cancelTime = self.req['cancelTime']
        self.cancelTime = datetime.datetime.strptime(self.cancelTime, '%Y%m%d_%H:%M:%S')
        self.checkCancelKey = 'price'

        self.iid   = self.req['iid']
        self.price = self.req['price']
        self.isBuy = self.req['isBuy']
        self.isOpen = self.req['isOpen']
        self.total = self.req['total']
        self.totalOri = self.total
        self.type = 0

        if not self.isOpen:
            if self.isBuy:
                self.checkCancelKey = 'ask1'
            else:
                self.checkCancelKey = 'bid1'

        self.startOrder(self.iid)

        orderID = self.getOrderID()
        sendData = {
            'action': 'trade',
            'appKey': int(self.appKey),
            'orderID': int(orderID),
            'iid': self.iid,
            'type': self.ORDER_TYPE_NORMAL,
            'price': int(self.price),
            'total': int(self.total),
            'isBuy': int(self.isBuy),
            'isOpen': int(self.isOpen),
        }
        self.sender.publish(self.sendOrderCh, JSON.encode(sendData))
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderForecast[sendOrder]', sendData) 
Example 16
Project: CTPOrderService   Author: lllzzz   File: OrderForecast.py    Mozilla Public License 2.0 5 votes vote down vote up
def __cancel(self, total):
        if self.isCanceled: return
        self.isCanceled = True
        sendData = {
            'action': 'cancel',
            'appKey': int(self.appKey),
            'orderID': int(self.orderID),
        }
        self.sender.publish(self.sendOrderCh, JSON.encode(sendData))
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderForecast[cancel]', sendData) 
Example 17
Project: CTPOrderService   Author: lllzzz   File: OrderIOCClose.py    Mozilla Public License 2.0 5 votes vote down vote up
def process(self, channel, data):
        if channel != self.tradeRspCh: return
        if data['err'] > 0:
            self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderIOCClose[error]', data)
            self.error(data['err'])
            return

        data = data['data']
        if self.orderID != data['orderID']: return
        data['volWaiting'] = self.total
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderIOCClose[process]', data)

        isOver = False
        type = data['type']
        if type == 'traded':
            vol = data['successVol']
            self.successVol += vol
            # 更新持仓
            if self.isBuy:
                self.sellVol(self.iid, vol, False)
            else:
                self.buyVol(self.iid, vol, False)

            # 判断是否结束
            self.total -= vol
            if self.total == 0:
                isOver = True

        if isOver:
            self.endOrder(self.iid)
            self.sender.publish(self.sendOrderRspCh, JSON.encode({'mid': self.mid, 'successVol': self.successVol}))
            self.toDB()
            self.service.stop() 
Example 18
Project: CTPOrderService   Author: lllzzz   File: OrderIOCClose.py    Mozilla Public License 2.0 5 votes vote down vote up
def __sendOrder(self):

        self.mid   = self.req['mid']
        self.iid   = self.req['iid']
        self.price = 0
        self.isBuy = self.req['isBuy']
        self.isOpen = 0
        self.total = self.req['total']
        self.totalOri = self.total
        self.type = 3
        orderID = self.getOrderID()

        sendData = {
            'action': 'trade',
            'appKey': int(self.appKey),
            'orderID': int(orderID),
            'iid': self.iid,
            'type': self.ORDER_TYPE_IOC,
            'price': 0,
            'total': int(self.total),
            'isBuy': int(self.isBuy),
            'isOpen': 0,
        }
        self.startOrder(self.iid)
        self.sender.publish(self.sendOrderCh, JSON.encode(sendData))
        self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderIOCClose[sendOrder]', sendData) 
Example 19
Project: vxTrader   Author: vex1023   File: xqTrader.py    MIT License 4 votes vote down vote up
def cancel(self, order_no=0):

        portfolio = self.portfolio

        comment = '撤单\n 来自vxTrader'

        stock_infos = self._worker.imap(
            self._get_stock_info,
            portfolio.loc[portfolio.index != 'cash'].index
        )

        holdings = []
        for stock in stock_infos:
            holding = {
                "code": stock['code'],
                "flag": stock['flag'],
                "type": stock['type'],
                "stock_id": stock['stock_id'],
                "ind_id": stock['ind_id'],
                "ind_name": stock['ind_name'],
                "ind_color": stock['ind_color'],
                "textname": stock['name'],
                "segment_name": stock['ind_name'],
                # 注意此处雪球接受的是持仓百分比,例如:30.33
                "weight": round(portfolio.loc[stock['code'].lower(), 'weight'] * 100, 2),
                "proactive": True,
                "price": str(stock['current'])
            }

            holdings.append(holding)

        params = {
            # 注意此处雪球接受的是持仓百分比,例如:30.33
            'cash': round(portfolio.loc['cash', 'weight'] * 100, 2),
            'holdings': str(json.encode(holdings)),
            'cube_symbol': self.portfolio_code,
            'segment': 1,
            'comment': comment
        }

        self.client.headers.update(
            referer='https://xueqiu.com/p/update?action=holdings&symbol=%s' % self.portfolio_code)
        logger.debug(self.client.session.headers)

        try:
            r = self.client.post(url='https://xueqiu.com/cubes/rebalancing/create.json', params=params)
            r.raise_for_status()
        except Exception as err:
            logger.warning('order failed: %s' % err)
            raise TraderAPIError(str(err))

        logger.debug('order success:%s %s' % (holdings, r.json()))
        return r.json()['id'] 
Example 20
Project: CTPOrderService   Author: lllzzz   File: OrderForecast.py    Mozilla Public License 2.0 4 votes vote down vote up
def process(self, channel, data):

        if channel == self.tickCh:

            if self.__checkTime(data):
                self.__cancel(self.total)

            if self.startCheckCancel:
                if abs(self.price - data[self.checkCancelKey]) > self.cancelRange * self.minTick:
                    self.__cancel(self.total)
            else:
                if data['price'] >= self.cancelPriceH or data['price'] <= self.cancelPriceL:
                    self.startCheckCancel = True
                    self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderForecast[tick]', data)
            return

        if channel == self.tradeRspCh:
            if data['err'] > 0:
                self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderForecast[error]', data)
                self.error(data['err'])
                return

            data = data['data']
            if self.orderID != data['orderID']: return
            data['volWaiting'] = self.total
            self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderForecast[process]', data)

            isOver = False
            type = data['type']

            if type == 'traded':
                vol = data['successVol']
                self.successVol += vol
                # 更新持仓
                if self.isOpen:
                    if self.isBuy:
                        self.buyVol(self.iid, vol, True)
                    else:
                        self.sellVol(self.iid, vol, True)
                else:
                    if self.isBuy:
                        self.sellVol(self.iid, vol, False)
                    else:
                        self.buyVol(self.iid, vol, False)

                # 判断是否结束
                self.total -= vol
                if self.total == 0:
                    isOver = True

            if type == 'canceled':
                vol = data['cancelVol']
                self.total -= vol
                if self.total == 0:
                    isOver = True

        if isOver:
            self.endOrder(self.iid)
            self.sender.publish(self.sendOrderRspCh, JSON.encode({'mid': self.mid, 'successVol': self.successVol}))
            self.toDB()
            self.service.stop()