def send_notification(self, notify_type, notification_trap, notification_args): agent_host = self.config['snmp']['transport']['listen_address'] agent_port = self.config['snmp']['transport']['listen_port'] community = self.config['snmp']['auth']['version2']['community'] # Initialize Notification Originator notifier = ntforg.NotificationOriginator() # Build Tarp Argument List varbinds = [] for varName, val in notification_args.items(): varbinds.append((ntforg.MibVariable(*varName), val)) # Send Notification error = notifier.sendNotification(ntforg.CommunityData(community), ntforg.UdpTransportTarget((agent_host, agent_port)), notify_type, ntforg.MibVariable(*notification_trap), *varbinds) # Check if Notification was successfully sent if error: self.fail('Notification not sent: %s' % error) log.debug("Sent Trap: %s:%d %r" % (agent_host, agent_port, notification_trap)) # stupid hack for race condition time.sleep(1)
def request(self, params): params_str = urllib.urlencode(params) unquote_str = urllib.unquote(params_str) url = self.trade_prefix + '?' + unquote_str r = self.s.post(url) log.debug('raw response: {}'.format(r.text)) return r.content
def slice_list(step=None, num=None, data_list=None): if not ((step is None) & (num is None)): if num is not None: step = math.ceil(len(data_list) / num) return [data_list[i:i + step] for i in range(0, len(data_list), step)] else: log.debug("step和num不能同时为空") return False
def unlockscreen(self): unlock_params = dict( password=self.account_config['trdpwd'], mainAccount=self.account_config['inputaccount'], ftype='bsn') log.debug('unlock params: %s' % unlock_params) unlock_resp = self.s.post(self.config['unlock'], params=unlock_params) log.debug('unlock resp: %s' % unlock_resp.text)
def cancel_entrust(self, entrust_no, stock_code): """撤单 :param entrust_no: 委托单号 :param stock_code: 股票代码""" need_info = self.__get_trade_need_info(stock_code) cancel_params = dict( self.config['cancel_entrust'], orderSno=entrust_no, secuid=need_info['stock_account']) cancel_response = self.s.post( self.config['trade_api'], params=cancel_params) log.debug('cancel trust: %s' % cancel_response.text) return cancel_response.json()
def post_login_data(self, verify_code): password = urllib.unquote(self.account_config['password']) login_params = dict(self.config['login'], mac_addr=order.get_mac(), account_content=self.account_config['account'], password=password, validateCode=verify_code) login_response = self.s.post(self.config['login_api'], params=login_params) log.debug('login response: %s' % login_response.text) if login_response.text.find('上次登陆') != -1: return True, None return False, login_response.text
def request(self, params): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko' } item = params.pop('ram') params['ram'] = item params_str = urllib.urlencode(params) unquote_str = urllib.unquote(params_str) log.debug('request params: %s' % unquote_str) b64params = base64.b64encode(unquote_str.encode()).decode() r = self.s.get('{prefix}/?{b64params}'.format(prefix=self.trade_prefix, b64params=b64params), headers=headers) return r.content
def post_login_data(self, verify_code): login_params = dict( self.config['login'], mac=order.get_mac(), clientip='', inputaccount=self.account_config['inputaccount'], trdpwd=self.account_config['trdpwd'], checkword=verify_code) log.debug('login params: %s' % login_params) login_response = self.s.post( self.config['login_api'], params=login_params) log.debug('login response: %s' % login_response.text) if login_response.text.find('success') != -1: return True, None return False, login_response.text
def cancel_entrusts(self, entrust_no): """ @Contact: Emptyset <*****@*****.**> 批量撤单 @param entrust_no: string类型 委托单号,用逗号隔开 e.g:"8000,8001,8002" @return 返回格式是list,比如一个22个单子的批量撤单 e.g.: [{"success":15, "failed":0},{"success":7, "failed":0}] """ import time list_entrust_no = entrust_no.split(",") # 一次批量撤单不能超过15个 list_entrust_no = slice_list(step=15, data_list=list_entrust_no) result = list() for item in list_entrust_no: if item[-1] == "": num = len(item) - 1 else: num = len(item) cancel_data = { "ajaxFlag": "stock_batch_cancel", "num": num, "orderSno": ",".join(item) } while True: try: cancel_response = self.s.post( "https://www.chinastock.com.cn/trade/AjaxServlet", data=cancel_data, timeout=1) if cancel_response.status_code == 200: cancel_response_json = cancel_response.json() # 如果出现“系统超时请重新登录”之类的错误信息,直接返回False if "result_type" in cancel_response_json and "result_type" == 'error': return False result.append(cancel_response_json) break else: log.debug('{}'.format(cancel_response)) except Exception as e: log.debug('{}'.format(e)) time.sleep(0.2) return result
def __check_login_status(self, verify_code): # 设置登录所需参数 params = dict(userName=self.account_config['userName'], trdpwd=self.account_config['trdpwd'], trdpwdEns=self.account_config['trdpwd'], servicePwd=self.account_config['servicePwd'], macaddr=self.__mac, lipInfo=self.__ip, vcode=verify_code) params.update(self.config['login']) log.debug('login params: %s' % params) login_api_response = self.s.post(self.config['login_api'], params) if login_api_response.text.find('欢迎您') != -1: return True, None return False, login_api_response.text
def __tradefund(self, stock_code, other): # 检查是否已经掉线 if not self.heart_thread.is_alive(): check_data = self.get_balance() if type(check_data) == dict: return check_data need_info = self.__get_trade_need_info(stock_code) trade_params = dict( other, stockCode=stock_code, market=need_info['exchange_type'], secuid=need_info['stock_account']) trade_response = self.s.post( self.config['trade_api'], params=trade_params) log.debug('trade response: %s' % trade_response.text) return trade_response.json()
def __handle_recognize_code(self): """获取并识别返回的验证码 :return:失败返回 False 成功返回 验证码""" # 获取验证码 verify_code_response = self.s.get(self.config['verify_code_api']) # 保存验证码 image_path = tempfile.mktemp() with open(image_path, 'wb') as f: f.write(bytes(verify_code_response.content)) verify_code = order.recognize_verify_code(image_path, broker='gf') log.debug('verify code detect result: %s' % verify_code) os.remove(image_path) ht_verify_code_length = 5 if len(verify_code) != ht_verify_code_length: return False return verify_code
def __handle_recognize_code(self): """获取并识别返回的验证码 :return:失败返回 False 成功返回 验证码""" # 获取验证码 verify_code_response = self.s.get(self.config['verify_code_api']) # 保存验证码 image_path = os.path.join(tempfile.gettempdir(), 'vcode_%d' % os.getpid()) with open(image_path, 'wb') as f: f.write(verify_code_response.content) verify_code = order.recognize_verify_code(image_path) log.debug('verify code detect result: %s' % verify_code) os.remove(image_path) ht_verify_code_length = 4 if len(verify_code) != ht_verify_code_length: return False return verify_code
def handle_recognize_code(self): """获取并识别返回的验证码 :return:失败返回 False 成功返回 验证码""" # 获取验证码 verify_code_response = self.s.get(self.config['verify_code_api'], params=dict( randomStamp=random.random())) # 保存验证码 image_path = os.path.join(os.getcwd(), 'vcode') with open(image_path, 'wb') as f: f.write(verify_code_response.content) verify_code = order.recognize_verify_code(image_path, 'yh') log.debug('verify code detect result: %s' % verify_code) ht_verify_code_length = 4 if len(verify_code) != ht_verify_code_length: return False return verify_code
def __set_trade_need_info(self): """设置交易所需的一些基本参数 """ account_params = dict(self.config['accountinfo']) params_str = urllib.urlencode(account_params) unquote_str = urllib.unquote(params_str) url = self.trade_prefix + '?' + unquote_str r = self.s.get(url) log.debug('get account info: {}'.format(r.text)) jslist = r.text.split(';') jsholder = jslist[HOLDER_POS] jsholder = re.findall(r'\[(.*)\]', jsholder) jsholder = eval(jsholder[0]) if len(jsholder) < 3: self.holdername.append(jsholder[0]) self.holdername.append(jsholder[1]) return self.holdername.append(jsholder[1]) self.holdername.append(jsholder[2])
def __get_trade_info(self): """ 请求页面获取交易所需的 uid 和 password """ trade_info_response = self.s.get(self.config['trade_info_page']) # 查找登录信息 search_result = re.search(r'var data = "([/=\w\+]+)"', trade_info_response.text) if not search_result: return False need_data_index = 0 need_data = search_result.groups()[need_data_index] bytes_data = base64.b64decode(need_data) log.debug('trade info bytes data: ', bytes_data) try: str_data = bytes_data.decode('gbk') except UnicodeDecodeError: str_data = bytes_data.decode('gb2312', errors='ignore') log.debug('trade info: %s' % str_data) json_data = json.loads(str_data) return json_data
def get_ipo_limit(self, stock_code): """ 查询新股申购额度申购上限 :param stock_code: 申购代码!!! :return: high_amount(最高申购股数) enable_amount(申购额度) last_price(发行价) """ need_info = self.__get_trade_need_info(stock_code) params = dict( self.config['ipo_enable_amount'], CSRF_Token='undefined', timestamp=random.random(), stock_account=need_info['stock_account'], # '沪深帐号' exchange_type=need_info['exchange_type'], # '沪市1 深市2' entrust_prop=0, stock_code=stock_code) data = self.do(params) if 'error_no' in data.keys() and data['error_no'] != "0": log.debug('查询错误: %s' % (data['error_info'])) return None return dict(high_amount=float(data['high_amount']), enable_amount=data['enable_amount'], last_price=float(data['last_price']))
def __set_trade_need_info(self, json_data): """设置交易所需的一些基本参数 :param json_data:登录成功返回的json数据 """ for account_info in json_data['item']: if account_info['stock_account'].startswith( 'A') or account_info['stock_account'].startswith('B'): # 沪 A 股东代码以 A 开头,同时需要是数字,沪 B 帐号以 C 开头,机构账户以B开头 if account_info['exchange_type'].isdigit(): self.__sh_exchange_type = account_info['exchange_type'] self.__sh_stock_account = account_info['stock_account'] log.debug('sh_A stock account %s' % self.__sh_stock_account) # 深 A 股东代码以 0 开头,深 B 股东代码以 2 开头 elif account_info['stock_account'].startswith('0'): self.__sz_exchange_type = account_info['exchange_type'] self.__sz_stock_account = account_info['stock_account'] log.debug('sz_A stock account %s' % self.__sz_stock_account) self.__fund_account = json_data['fund_account'] self.__client_risklevel = json_data['branch_no'] self.__op_station = json_data['op_station'] self.__trdpwd = json_data['trdpwd'] self.__uid = json_data['uid'] self.__branch_no = json_data['branch_no']
def login(self, throw=False): """ 登录 :param throw: :return: """ self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0', 'Host': 'xueqiu.com', 'Pragma': 'no-cache', 'Connection': 'keep-alive', 'Accept': '*/*', 'Accept-Encoding': 'gzip,deflate,sdch', 'Cache-Conrol': 'no-cache', 'Referer': 'http://xueqiu.com/P/ZH003694', 'X-Requested-With': 'XMLHttpRequest', 'Accept-Language': 'zh-CN,zh;q=0.8' } login_status, result = self.post_login_data() if login_status == False and throw: raise NotLoginError(result) log.debug('login status: %s' % result) return login_status
def format_response_data(self, data): bytes_str = base64.b64decode(data) gbk_str = bytes_str.decode('gbk') log.debug('response data before format: %s' % gbk_str) filter_empty_list = gbk_str.replace('[]', 'null') filter_return = filter_empty_list.replace('\n', '') log.debug('response data: %s' % filter_return) response_data = json.loads(filter_return) if response_data[ 'cssweb_code'] == 'error' or response_data['item'] is None: return response_data return_data = self.format_response_data_type(response_data['item']) log.debug('response data: %s' % return_data) return return_data
def __trade(self, stock_code, price=0, amount=0, volume=0, entrust_bs='buy'): """ 调仓 :param stock_code: :param price: :param amount: :param volume: :param entrust_bs: :return: """ stock = self.__search_stock_info(stock_code) balance = self.get_balance()[0] if stock == None: raise TraderError(u"没有查询要操作的股票信息") if not volume: volume = int(float(price) * amount) # 可能要取整数 if balance['current_balance'] < volume and entrust_bs == 'buy': raise TraderError(u"没有足够的现金进行操作") if stock['flag'] != 1: raise TraderError(u"未上市、停牌、涨跌停、退市的股票无法操作。") if volume == 0: raise TraderError(u"操作金额不能为零") # 计算调仓调仓份额 weight = volume / balance['asset_balance'] * 100 weight = round(weight, 2) # 获取原有仓位信息 position_list = self.__get_position() # 调整后的持仓 is_have = False for position in position_list: if position['stock_id'] == stock['stock_id']: is_have = True position['proactive'] = True old_weight = position['weight'] if entrust_bs == 'buy': position['weight'] = weight + old_weight else: if weight > old_weight: raise TraderError(u"操作数量大于实际可卖出数量") else: position['weight'] = old_weight - weight if not is_have: if entrust_bs == 'buy': position_list.append({ "code": stock['code'], "name": stock['name'], "enName": stock['enName'], "hasexist": stock['hasexist'], "flag": stock['flag'], "type": stock['type'], "current": stock['current'], "chg": stock['chg'], "percent": str(stock['percent']), "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'], "weight": weight, "url": "/S/" + stock['code'], "proactive": True, "price": str(stock['current']) }) else: raise TraderError(u"没有持有要卖出的股票") if entrust_bs == 'buy': cash = (balance['current_balance'] - volume) / balance['asset_balance'] * 100 else: cash = (balance['current_balance'] + volume) / balance['asset_balance'] * 100 cash = round(cash, 2) log.debug("weight:%f, cash:%f" % (weight, cash)) data = { "cash": cash, "holdings": str(json.dumps(position_list)), "cube_symbol": str(self.account_config['portfolio_code']), 'segment': 1, 'comment': "" } data = (urllib.urlencode(data)) self.headers['Referer'] = self.config['referer'] % self.account_config[ 'portfolio_code'] try: rebalance_res = self.requests.session().post( self.config['rebalance_url'], headers=self.headers, cookies=self.cookies, params=data) except Exception as e: log.warn('调仓失败: %s ' % e) return else: log.debug('调仓 %s%s: %d' % (entrust_bs, stock['name'], rebalance_res.status_code)) rebalance_status = json.loads(rebalance_res.text) if 'error_description' in rebalance_status.keys( ) and rebalance_res.status_code != 200: log.error('调仓错误: %s' % (rebalance_status['error_description'])) return [{ 'error_no': rebalance_status['error_code'], 'error_info': rebalance_status['error_description'] }] else: return [{ 'entrust_no': rebalance_status['id'], 'init_date': self.__time_strftime(rebalance_status['created_at']), 'batch_no': '委托批号', 'report_no': '申报号', 'seat_no': '席位编号', 'entrust_time': self.__time_strftime(rebalance_status['updated_at']), 'entrust_price': price, 'entrust_amount': amount, 'stock_code': stock_code, 'entrust_bs': '买入', 'entrust_type': '雪球虚拟委托', 'entrust_status': '-' }]
def _trap_receiver_callback(self, trap): self.traps.append(trap) log.debug("Recevied Trap: %r" % (trap))