コード例 #1
0
ファイル: pdSql_common.py プロジェクト: allisnone/pytrade
def send_exit_mail(exit_code='002290',exit_state=1.0,exit_data={},exit_time=datetime.datetime.now(),
                   mail_to_list=None,count=0,clear=0,to_sql=None,period_count=20):
    """发送止损退出email告警"""
    exit_type = ""
    if exit_state==1:
        exit_type = "清仓 "
    elif exit_state==0.5:
        exit_type = "半仓 "
    else:
        pass
    stock_type = "个股风险"
    if exit_code in ['sh','cyb','999999','399006'] :
        stock_type = "系统风险"
    sub = '[%s] %s触发<%s>止损,累计触发count=%s, 时间: %s' % (stock_type,exit_code,exit_type,count, exit_time)
    content = '请确认已经止损!止损数据: \n %s' % exit_data
    if clear:
        sub = '[解除' + sub[1:]
        content = '当日止损后重返止损之上!止损数据: \n %s' % exit_data
    else:
        pass
    if count==1 or count%period_count==0:
        sm.send_mail(sub,content,mail_to_list)
        if to_sql:
            #type,symbol,subject,save_time
            data = [[stock_type,exit_type,exit_code,sub,exit_time]]
            to_sql.maillogs(data)
        else:
            pass
    else:
        pass
    return
コード例 #2
0
def order(
    browser,
    level_goumai='/html/body/div[5]/div[4]/div[2]/div/div/div[2]/div[5]/div[2]/table/tbody/tr[1]/td[7]/input'
):
    #获取是否可以购买
    try:
        level_goumai = browser.find_by_xpath(level_goumai)
        print level_goumai.value
        level_goumai.click()  #跳转到购买界面

        #点击同意公示期规则按钮
        links_found = browser.find_by_id('agree_fair_show_pay')
        links_found.click()

        #点击预定(加入购物车)
        links_found = browser.find_by_id('buy_btn')
        links_found.click()

        alert = browser.get_alert()
        print alert.text
        alert.accept()
        alert.dismiss()
        to_list = ''
        sub = u'已购买成功'
        content = u'已购买'
        sendEmail.send_mail(to_list, sub, content)
        raw_input(u"输入任何内容,回车继续!")

    except:
        print u'\u5df2\u88ab\u81ea\u5df1\u8ba2\u8d2d'  #已被自己订购
        time.sleep(30)
コード例 #3
0
ファイル: pdSql.py プロジェクト: taolaptop/pytrade
 def update_sql_position0(self, users={'36005':{'broker':'yh','json':'yh.json'},'38736':{'broker':'yh','json':'yh1.json'}}):
     sub = '持仓更异常'
     fail_check = []
     for account in list(users.keys()):
         #stock_sql.drop_table(table_name='myholding')
         try:
             broker = users[account]['broker']
             user_file = users[account]['json']
             position_df,balance = pdsqlc.get_position(broker, user_file)
             self.hold[account] =  position_df
             self.insert_table(data_frame=position_df,table_name='hold')
         except:
             fail_check.append(account)
         #self.insert_table(data_frame=position_df,table_name='balance')
         time.sleep(2)
     if fail_check:
         content = '%s 持仓表更新可能异常' % fail_check
         sm.send_mail(sub,content,mail_to_list=None)
         """再次尝试获取异常持仓"""
         for account in fail_check:
             #stock_sql.drop_table(table_name='myholding')
             try:
                 broker = users[account]['broker']
                 user_file = users[account]['json']
                 position_df,balance = pdsqlc.get_position(broker, user_file)
                 self.hold[account] =  position_df
                 self.insert_table(data_frame=position_df,table_name='hold')
             except:
                 pass
コード例 #4
0
ファイル: report.py プロジェクト: tedQB/easy-trading
def main(riqi):
    #returnAllFutureName = "replace INTO futures (futureName,riqi) VALUES('%s','%s')" % (
    #futureName, riqi)
    print(riqi)
    selectFutureName = "SELECT distinct futureName from futures WHERE riqi = '" + riqi + "'"
    #returnAllFutureName = 'SELECT * from futures'
    try:
        conn = connDB()
        cur = conn.cursor()
        count = cur.execute(selectFutureName)
        result = cur.fetchall()
        #遍历一条数据方式1
        for row in result:
            futureName = row[0]
            print('合约名称', futureName)
            generateMail(riqi, futureName)

        conn.commit()

    except Exception as e:
        print("通过主键读取一条记录:" + str(e))
        conn.rollback()
    finally:
        conn.close()

    print("需要发的邮件", mailArr)
    send_mail('测试邮件', mailArr)
コード例 #5
0
ファイル: pytrade_tdx.py プロジェクト: allisnone/pytrade
 def init_hwnd(self):
     self.__top_hwnd = findTopWindow(wantedClass='TdxW_MainFrame_Class')
     self.__button = {'refresh': 180, 'position': 145, 'deal': 112, 'withdrawal': 83, 'sell': 50, 'buy': 20}
     windows = dumpWindows(self.__top_hwnd)
     if self.debug: print('windows=',windows)
     temp_hwnd = 0
     temp_hwnd_guanlian=0
     p_hwnd=0
     self.p_acc_hwnd = 0
     self.acc_hwnd = 0
     self.new_stock_order_hwnd = 0
     find_guan_lian = False
     find_new_stock = False
     find_combobox = False
     for window in windows:
         child_hwnd, window_text, window_class = window
         if window_text=='买卖关联同一支股票':
             temp_hwnd_guanlian = child_hwnd
             print("find the hwnd: 买卖关联同一支股票, ",temp_hwnd_guanlian)
         if window_class == 'MHPToolBar' and window_text=='MainViewBar':
             self.p_acc_hwnd = child_hwnd
             print('parent_acc_combobox_hwnd=',self.p_acc_hwnd)
             p_p_acc_hwnd=getParentWindow(self.p_acc_hwnd)
             acc_windows = dumpWindows(self.p_acc_hwnd)   
             for window in acc_windows:
                 child_hwnd, window_text, window_class = window
                 if window_class == 'ComboBox':
                     self.acc_hwnd = child_hwnd
                     find_combobox = True
                     print('acc_combobox_hwnd=',self.acc_hwnd)
         if window_text=='一键申购':
             self.new_stock_order_hwnd = child_hwnd
             find_new_stock = True
         if find_guan_lian and find_new_stock and find_combobox:
             break
     else:
         pass  
         #raise Exception("Change saving type failed") 
                 
     if temp_hwnd_guanlian:
         p_hwnd=getParentWindow(temp_hwnd_guanlian) #买卖关联同一支股票的上一级句柄
         if self.debug: print('p_hwnd=',p_hwnd)
         p_hwnd_children = dumpWindow(p_hwnd)
         if self.debug: print('p_hwnd_children=',p_hwnd_children)
         p_p_hwnd=getParentWindow(p_hwnd) #股票交易第一级句柄
         p_p_hwnd_children = dumpWindow(p_p_hwnd)   #右侧操作区
         self.__menu_hwnds = dumpWindow(p_p_hwnd_children[0][0])
         if self.debug: print(self.__menu_hwnds)
         self.__buy_sell_hwnds = p_hwnd_children
         EXPECT_LEN = 68
         if len(self.__buy_sell_hwnds) != EXPECT_LEN:
             sm.send_mail(sub='无法获得通达信对买对卖界面的窗口句柄',content='子句柄数量为 %s,不等于期望数量:%s.也许软件亿升级。' %(len(self.__buy_sell_hwnds),EXPECT_LEN))
             tkinter.messagebox.showerror('错误', '无法获得通达信对买对卖界面的窗口句柄')
         else:
             pass
     else:
         sm.send_mail(sub='无法获得  买卖关联同一支股票 的窗口句柄',content='请点击  双向委托 按钮' )
         tkinter.messagebox.showerror('错误', '无法获得 "买卖关联同一支股票"的窗口句柄')
     return
コード例 #6
0
ファイル: pdSql_common.py プロジェクト: allisnone/pytrade
def quotation_monitor(codes,this_date_str,hour,minute):
    over_avrg_datas = qq.update_quotation_k_datas(codes,this_date_str,path='C:/work/temp_k/')
    if (hour==9 and minute>30) or (hour==10) or (hour==11 and minute<=59) or (hour>=13 and hour<15):
        if minute % mail_interval == 0:
            sub = '[%s:%:00]日内均线监测 ' %(hour,minute)
            content = '每%s分钟实时 均线监测数据如下:\n %s ' % (mail_interval,over_avrg_datas)
            sm.send_mail(sub,content,mail_to_list=None)
        else:
            pass
    return
コード例 #7
0
ファイル: archivePublish.py プロジェクト: ocswor/DeployiOSApp
 def doUploadDirect(self, ipaPath):
     if not ipaPath:
         with open('/%s/ipaPath' % CURRENT_SCRIPT_DIR, 'r+') as f:
             ipaPath = f.readline().strip('\n')
     if ipaPath:
         downURL = uploadIpaToPgyer(ipaPath)
         publish_instruction = getSendMailContent(downURL)
         sendEmail.send_mail('iOS 新版本发布', publish_instruction)
     else:
         print 'ipaPath is not exist'
コード例 #8
0
ファイル: job51.py プロジェクト: speakfly/findPractice
 def main(self):
     html = self.get_one_page(self.url)
     message = '<table border="1" cellpadding="10"><tr><td>职位</td><td>公司</td><td>地点</td><td>薪资</td></tr>'
     for item in self.parse_one_page(html):
         message1 = (
             '<tr><td><a href="%s">%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>'
             % (item['pos_url'], item['postion'], item['comp'],
                item['addr'], item['salary']))
         message = message + message1
     message = message + '</table>'
     sendEmail.send_mail(self.email, message, "html")
コード例 #9
0
ファイル: yhtrader.py プロジェクト: allisnone/easyquant
 def config_trade(self,stock_code,pre_holding_amount,trade_amount,trade_direct='B'):
     """定时买入某只股票
     :param stock_code: 股票代码
     :param buy_rate: 买出比例,默认全买
     :param set_time: datetime type, 买入时间
     :return trade_state: float type, -2 系统异常,-1 反向操作,0实质无成交,0.5部分成交,1按计划成交,2超额成交
     """
     trade_state = 0
     #print(self.position)
     pos_holding_amount = self.get_position_info(stock_code, info_column='股份余额')
     msg_content = ''
     if pos_holding_amount<0:
         log.debug('帐户空仓,无任何持仓股票')
         trade_state = -2
     else:
         if trade_direct=='B':
             if pos_holding_amount<pre_holding_amount:
                 msg_content = '原计划买入 %s %s股,实质卖出%s股' % (stock_code,trade_amount,(pre_holding_amount-pos_holding_amount))
                 trade_state = -1
             elif pos_holding_amount==pre_holding_amount:
                 msg_content = '原计划买入 %s %s股,实质无任何买入' % (stock_code,trade_amount)
                 trade_state = 0
             elif pos_holding_amount<(pre_holding_amount+trade_amount):
                 msg_content = '原计划买入 %s %s股,实质部分买入%s股' % (stock_code,trade_amount,(pos_holding_amount-pre_holding_amount))
                 trade_state = 0.5
             elif pos_holding_amount==(pre_holding_amount+trade_amount):
                 msg_content = '按原计划买入 %s %s股' % (stock_code,trade_amount)
                 trade_state = 1
             else:
                 msg_content = '原计划买入 %s %s股,实质超额买入,共买入%s股' % (stock_code,trade_amount,(pos_holding_amount-pre_holding_amount))
                 trade_state = 2
         elif trade_direct=='S':
             if pos_holding_amount>pre_holding_amount:
                 msg_content = '原计划卖出 %s %s股,实质买入%s股' % (stock_code,trade_amount,(pos_holding_amount-pre_holding_amount))
                 trade_state = -1
             elif pos_holding_amount==pre_holding_amount:
                 msg_content = '原计划卖出 %s %s股,实质无任何卖出' % (stock_code,trade_amount)
                 trade_state = 0
             elif pos_holding_amount>(pre_holding_amount-trade_amount):
                 msg_content = '原计划卖出 %s %s股,实质部分卖出%s股' % (stock_code,trade_amount,(pre_holding_amount-pos_holding_amount))
                 trade_state = 0.5
             elif pos_holding_amount==(pre_holding_amount-trade_amount):
                 msg_content = '按原计划卖出%s %s股' % (stock_code,trade_amount)
                 trade_state = 1
             else:
                 msg_content = '原计划卖出 %s %s股,实质超额卖出,共卖出%s股' % (stock_code,trade_amount,(pre_holding_amount-pos_holding_amount))
                 trade_state = 2
         else:
             trade_state = -2
     if msg_content:
         log.debug(msg_content)
         sub = '%s 交易结果确认' % stock_code
         sm.send_mail(sub,msg_content)
     return trade_state
コード例 #10
0
ファイル: apiTetst.py プロジェクト: cookie0131/qa
def send_log_file(work_path):
    """
    func:发送邮件,需要指定文件目录

    """
    for root, dirs, files in os.walk(work_path, followlinks=False):
        for fileName in files:
            if fileName.find("html") > -1:
                with open(work_path + "/" + fileName) as t:
                    text = t.read()
                files = [work_path + "/" + fileName]
                send_mail(server, fro, to, fileName[0:fileName.find('.')]+subject, text, files)
コード例 #11
0
ファイル: pytrade_tdx.py プロジェクト: taolaptop/pytrade
 def change_account(self, current_acc_id, current_box_id, position_dict={}):
     """
     双帐号切换: 默认先登录36005,再登录38736
     :param code: 股票代码
     :param current_acc_id: 当前账户id,int
     :param current_box_id: 当前账户切换的下拉菜单id, int
     :param position_dict: 持仓, dict
     :return: 0-未成交, 正整数是买入的数量, 负整数是卖出的数量
     """
     #index_map = {'36005':0,'38736':1}
     exchange_id = -1
     if self.p_acc_hwnd and self.acc_hwnd:
         valid_combobox_id = get_valid_combobo_ids(self.p_acc_hwnd,
                                                   self.acc_hwnd)
         if self.debug: print('valid_combobox_id=', valid_combobox_id)
         len_id = len(valid_combobox_id)
         if len_id > 2:
             pass
             if self.debug: print('超过三个账户切换,未实现')
         elif len_id == 2:
             if current_box_id == 0 and current_acc_id == '36005':
                 exchange_id = select_combobox(self.p_acc_hwnd,
                                               self.acc_hwnd,
                                               index_id=1)
                 #target_acc_id,target_box_id = self.get_acc_combobox_id(position_dict)
                 if self.debug:
                     print('从%s账户切换成功到:%s ' % (current_acc_id, '38736'))
                 time.sleep(1)
             elif current_box_id == 1 and current_acc_id == '38736':
                 exchange_id = select_combobox(self.p_acc_hwnd,
                                               self.acc_hwnd,
                                               index_id=0)
                 #target_acc_id,target_box_id = self.get_acc_combobox_id(position_dict)
                 if self.debug:
                     print('从%s账户切换成功到:%s ' % (current_acc_id, '36005'))
                 time.sleep(1)
             else:
                 if self.debug: print('账户切换异常,请检查')
         elif len_id == 1:
             pass
             if self.debug: print('仅有一个登录账户,无需切换')
         else:
             pass
             if self.debug: print('无任何登录账户,无需切换')
     else:
         sm.send_mail(sub='无法获得通达信帐户切换下来菜单的窗口句柄',
                      content='下来菜单的父窗口句柄 =%s,下来菜单的窗口句柄= %s.也许软件亿升级。' %
                      (self.p_acc_hwnd, self.acc_hwnd))
     return exchange_id
コード例 #12
0
ファイル: main.py プロジェクト: ywang412/homework-arch-4
def logic(d_in):
    data = json.loads(d_in)
    print data.keys()
    with open('conf.py') as f:
        content = f.read()
        info_l = eval(content.split('=')[1])
        # [['MemUsage', '>', 1900, '*****@*****.**'], ['LoadAvg', '>', 1.0, '*****@*****.**']]
    for info in info_l:
        key, op, va, mail = info
        expression = str(data[key]) + op + str(va)
        print expression
        mail_to = [mail]
        if eval(str(data[key]) + op + str(va)):
            sub_mail = 'Monitor Alarm'
            con_mail = '%s %s %s' % (key, op, va)
            sendEmail.send_mail(mail_to, sub_mail, con_mail)
    return "FF got the data"
コード例 #13
0
ファイル: pytrade_tdx.py プロジェクト: taolaptop/pytrade
 def getMoney(self):
     """获取可用资金
     """
     code = '999999'
     setEditText(self.__buy_sell_hwnds[24][0], code)  # 测试时获得资金情况
     time.sleep(0.2)
     if self.debug: print('money_hwnd=', self.__buy_sell_hwnds[12][0])
     money = getWindowText(self.__buy_sell_hwnds[12][0]).strip()
     #setEditText(self.__buy_sell_hwnds[24][0], '')  # 测试时获得资金情况
     time.sleep(0.2)
     #print('money_str=',money)
     try:
         money = float(money)
     except:
         money = 0.0
         sm.send_mail(sub='获取可用资金失败', content='检查验证是否软件异常')
     if self.debug: print('可用资金=', money)
     return money
コード例 #14
0
ファイル: pytrade_tdx.py プロジェクト: allisnone/pytrade
 def getMoney(self):
     """获取可用资金
     """
     code = '999999'
     setEditText(self.__buy_sell_hwnds[24][0], code)  # 测试时获得资金情况
     time.sleep(0.2)
     if self.debug: print('money_hwnd=',self.__buy_sell_hwnds[12][0])
     money = getWindowText(self.__buy_sell_hwnds[12][0]).strip()
     #setEditText(self.__buy_sell_hwnds[24][0], '')  # 测试时获得资金情况
     time.sleep(0.2)
     #print('money_str=',money)
     try:
         money=float(money)
     except:
         money=0.0
         sm.send_mail(sub='获取可用资金失败',content='检查验证是否软件异常' )
     if self.debug: print('可用资金=',money)
     return money
コード例 #15
0
ファイル: archivePublish.py プロジェクト: ocswor/DeployiOSApp
    def work(self):

        if self.direct_upload:
            self.doUploadDirect(self.direct_upload)
        elif (self.direct_sendEmail):
            downURL = self.direct_sendEmail
            publish_instruction = self.getSendMailContent(downURL)
            sendEmail.send_mail('iOS 新版本发布', publish_instruction)
        else:
            os.chdir(self.project_workdir)
            self.cleanArchiveFile()
            self.checkoutCode()
            self.buildWorkspace(self.workspace)
            path = self.exportArchive()
            if path:
                downURL = self.uploadIpaToPgyer(path)
                # downURL = 'DownUrl is:https://qiniu-storage.pgyer.com/n883'
                publish_instruction = self.getSendMailContent(downURL)
                sendEmail.send_mail('iOS 新版本发布', publish_instruction)
コード例 #16
0
ファイル: pytrade_tdx.py プロジェクト: taolaptop/pytrade
 def trade_confirm(self, code, trade_num, pos_chg={}):
     """
 确认成交并email通知
     :param code: 股票代码, char type  (getPosition)
     :param trade_num: 计划成交数量, int type (getPosition)
     :return pos_chg, 持仓变化,dict type
     """
     if trade_num == 0:  # no trade
         return
     if not pos_chg or code not in list(pos_chg.keys()):
         if self.debug: print('请手动确认股票  %s交易是否成功 !', code)
         pass
     else:
         actual_trade_num = pos_chg[code]
         if actual_trade_num == 0:
             sm.send_mail(sub='计划成交%s, 股票%s无任何成交' % (trade_num, code),
                          content='请人工检查验证!')
         else:
             if (trade_num > 0 and actual_trade_num > 0) or (
                     trade_num < 0 and actual_trade_num < 0):
                 remain_num = actual_trade_num - actual_trade_num
                 if remain_num == 0:
                     sm.send_mail(sub='[股票%s全部成交]计划成交%s, 还有%s未成交' %
                                  (code, trade_num, remain_num),
                                  content='请人工检查验证!')
                 else:
                     sm.send_mail(sub='[股票%s部分成交]计划成交%s, 还有%s未成交' %
                                  (code, trade_num, remain_num),
                                  content='请人工检查验证!')
             elif (trade_num > 0 and actual_trade_num < 0):
                 sm.send_mail(sub='[股票%s交易逻辑混乱]原计划买入%s股, 结果<卖出>%s股' %
                              (code, trade_num, actual_trade_num),
                              content='请人工检查验证!')
             elif (trade_num < 0 and actual_trade_num > 0):
                 sm.send_mail(sub='[股票%s交易逻辑混乱]原计划<卖出>%s股, 结果买入%s股' %
                              (code, trade_num, actual_trade_num),
                              content='请人工检查验证!')
             else:
                 pass
     return
コード例 #17
0
ファイル: pytrade_tdx.py プロジェクト: allisnone/pytrade
 def change_account(self,current_acc_id,current_box_id,position_dict={}):
     """
     双帐号切换: 默认先登录36005,再登录38736
     :param code: 股票代码
     :param current_acc_id: 当前账户id,int
     :param current_box_id: 当前账户切换的下拉菜单id, int
     :param position_dict: 持仓, dict
     :return: 0-未成交, 正整数是买入的数量, 负整数是卖出的数量
     """
     #index_map = {'36005':0,'38736':1}
     exchange_id = -1
     if self.p_acc_hwnd and self.acc_hwnd:
         valid_combobox_id = get_valid_combobo_ids(self.p_acc_hwnd, self.acc_hwnd)
         if self.debug: print('valid_combobox_id=',valid_combobox_id)
         len_id = len(valid_combobox_id)
         if len_id>2:
             pass
             if self.debug: print('超过三个账户切换,未实现')
         elif len_id==2:
             if current_box_id==0 and current_acc_id=='36005':
                 exchange_id = select_combobox(self.p_acc_hwnd ,self.acc_hwnd,index_id=1)
                 #target_acc_id,target_box_id = self.get_acc_combobox_id(position_dict)
                 if self.debug: print('从%s账户切换成功到:%s ' % (current_acc_id,'38736'))
                 time.sleep(1)
             elif current_box_id==1 and current_acc_id=='38736':
                 exchange_id = select_combobox(self.p_acc_hwnd ,self.acc_hwnd,index_id=0)
                 #target_acc_id,target_box_id = self.get_acc_combobox_id(position_dict)
                 if self.debug: print('从%s账户切换成功到:%s ' % (current_acc_id,'36005'))
                 time.sleep(1)
             else:
                 if self.debug: print('账户切换异常,请检查')
         elif len_id==1:
             pass
             if self.debug: print('仅有一个登录账户,无需切换')
         else:
             pass
             if self.debug: print('无任何登录账户,无需切换')
     else:
         sm.send_mail(sub='无法获得通达信帐户切换下来菜单的窗口句柄',content='下来菜单的父窗口句柄 =%s,下来菜单的窗口句柄= %s.也许软件亿升级。' %(self.p_acc_hwnd,self.acc_hwnd))
     return exchange_id
コード例 #18
0
def mysqldb_connect_and_test(ip, user, passwd, port):
    print("连接mysql数据库{0}中,请稍后....".format(ip))
    try:
        conn = pymysql.connect(host=ip,
                               user=user,
                               passwd=passwd,
                               port=int(port),
                               charset='utf8',
                               connect_timeout=3)
        print("连接成功,执行测试语句中...")
        with conn.cursor() as cur:
            sql = 'select 1 from dual'
            a = str(cur.execute(sql))
            print("successful! 进一步确认数据库服务正常。执行结果-->a: {0}".format(a))
    except Exception:
        print("发生异常,数据库连接失败,服务器ip:{0}".format(ip), Exception)
        send_mail(
            "*****@*****.**", ["*****@*****.**"], [], "警告:mysql数据库服务不可用!!!",
            "【邮件内容】:\n \t\tpython检测到mysql数据库异常,服务器为{0},请紧急处理!!!".format(host),
            "")
    else:
        print("连接成功:{0}\n".format(ip))
コード例 #19
0
ファイル: pytrade_tdx.py プロジェクト: allisnone/pytrade
 def getRealtimeQuotation(self,code='300431'):
     """获取可用资金
     """
     #code = '999999'
     setEditText(self.__buy_sell_hwnds[24][0], code)  # 测试时获得资金情况
     time.sleep(0.2)
     if self.debug: print('money_hwnd=',self.__buy_sell_hwnds[12][0])
     #money = getWindowText(self.__buy_sell_hwnds[12][0]).strip()
     #setEditText(self.__buy_sell_hwnds[24][0], '')  # 测试时获得资金情况
     buy1 = getWindowText(self.__buy_sell_hwnds[25][0]).strip()
     sell1 = getWindowText(self.__buy_sell_hwnds[1][0]).strip()
     print('buy1=',buy1)
     print('sell1=',sell1)
     time.sleep(0.2)
     #print('money_str=',money)
     try:
         money=float(money)
     except:
         money=0.0
         sm.send_mail(sub='获取可用资金失败',content='检查验证是否软件异常' )
     if self.debug: print('可用资金=',money)
     return money
コード例 #20
0
ファイル: pytrade_tdx.py プロジェクト: taolaptop/pytrade
 def getRealtimeQuotation(self, code='300431'):
     """获取可用资金
     """
     #code = '999999'
     setEditText(self.__buy_sell_hwnds[24][0], code)  # 测试时获得资金情况
     time.sleep(0.2)
     if self.debug: print('money_hwnd=', self.__buy_sell_hwnds[12][0])
     #money = getWindowText(self.__buy_sell_hwnds[12][0]).strip()
     #setEditText(self.__buy_sell_hwnds[24][0], '')  # 测试时获得资金情况
     buy1 = getWindowText(self.__buy_sell_hwnds[25][0]).strip()
     sell1 = getWindowText(self.__buy_sell_hwnds[1][0]).strip()
     print('buy1=', buy1)
     print('sell1=', sell1)
     time.sleep(0.2)
     #print('money_str=',money)
     try:
         money = float(money)
     except:
         money = 0.0
         sm.send_mail(sub='获取可用资金失败', content='检查验证是否软件异常')
     if self.debug: print('可用资金=', money)
     return money
コード例 #21
0
ファイル: pytrade_tdx.py プロジェクト: allisnone/pytrade
 def trade_confirm(self,code, trade_num, pos_chg={}):
     if not pos_chg or code not in list(pos_chg.keys()):
         if self.debug: print('请手动确认股票  %s交易是否成功 !', code)
         pass
     else:
         actual_trade_num = pos_chg[code]
         if actual_trade_num==0:
             sm.send_mail(sub='计划成交%s, 股票%s无任何成交' %(trade_num,code),content='请人工检查验证!' )
         else:
             if (trade_num>0 and actual_trade_num>0) or (trade_num<0 and actual_trade_num<0):
                 remain_num = actual_trade_num - actual_trade_num
                 if  remain_num==0:
                     sm.send_mail(sub='[股票%s全部成交]计划成交%s, 还有%s未成交' %(code, trade_num, remain_num),content='请人工检查验证!' )
                 else:
                     sm.send_mail(sub='[股票%s部分成交]计划成交%s, 还有%s未成交' %(code, trade_num, remain_num),content='请人工检查验证!' )
             elif (trade_num>0 and actual_trade_num<0):
                 sm.send_mail(sub='[股票%s交易逻辑混乱]原计划买入%s股, 结果<卖出>%s股' %(code, trade_num, actual_trade_num),content='请人工检查验证!' )
             elif (trade_num<0 and actual_trade_num>0):
                 sm.send_mail(sub='[股票%s交易逻辑混乱]原计划<卖出>%s股, 结果买入%s股' %(code, trade_num, actual_trade_num),content='请人工检查验证!' )
             else:
                 pass
     return
コード例 #22
0
ファイル: pdSql_common.py プロジェクト: allisnone/pytrade
def get_HO_dapan(dapan_codes=[],ho_rate=0.0026, stock_sql=None):
    """
    找出高开的大盘股,并触发email
    """
    codes = ['600029', '600018', '000776', '600016', '600606', '601668', '600050', '601688', '600030', 
                    '600104', '601377', '601633', '600585', '601186', '600036', '002450', '000538', '601818', 
                    '601898', '002304', '601628', '600276', '601800', '002027', '600000', '601318', '601088', 
                    '601601', '000001', '601988', '601390', '600015', '002673', '600547', '600340', '601238', 
                    '601006', '000783', '001979', '601857', '000768', '601766', '600518', '600011', '000166', 
                    '002024', '000002', '600519', '600048', '600383', '300498', '600028', '600999', '002142', 
                    '601018', '600887', '601336', '600958', '002252', '601328', '002594', '601398', '600115', 
                    '000063', '601618', '601727', '000895', '601985', '300104', '600900', '601989', '600019',
                    '601899', '600663', '600690', '000333', '600649', '600795', '002415', '000725', '601211', 
                    '000625', '000651', '601169', '601111', '601788', '002736', '601009', '601669', '600837', 
                    '601939', '603993', '601288', '601166', '000858', '601998', '600705']
    if dapan_codes:
        codes = dapan_codes
    ho_codes = []
    if stock_sql:
        codes = stock_sql.get_dapan(table='dapan_gu')
    this_datas = qq.get_qq_quotations_df(codes)
    if this_datas.empty:
        return ho_codes
    ho_datas = this_datas[(this_datas['open']>=(1 + ho_rate) * this_datas['close0'])]
    if ho_datas.empty:
        return ho_codes
    else:
        ho_codes = ho_datas['code'].values.tolist()
        ho_datas['ho_chg'] = (ho_datas['open']/ho_datas['close0'] - 1)*100.0
        mail_columns = ['code','name','ho_chg','PE','increase_rate','open','high','low','close', 'PB', 'total_market','datetime']
        ho_datas = ho_datas.sort_values(axis=0, by='ho_chg', ascending=False)
        ho_datas = ho_datas[mail_columns]
        sub = '[大盘股机会] 大盘股高开比率:%s%%, 今日高开大盘股有: %s' % (round(len(ho_codes),2)/len(codes)*100,ho_codes)
        content = '高开大盘股: \n %s' % ho_datas
        sm.send_mail(sub,content,mail_to_list=None)
        return list(set(ho_codes))
コード例 #23
0
ファイル: alert.py プロジェクト: valdupin/Admin_systeme
def alert(process, ram, disque):

    #--------------------------------------------------------------------------------------------
    #Dans cette fonction, on va vérifier si les arguments passer dans la fonction
    #   - process
    #   - ram
    #   - disque
    #   - absence
    #ne sont pas supérieur à 100, si ils sont supérieur on envoi un mail
    #avec le fonction send_mail()
    #--------------------------------------------------------------------------------------------

    if process > 99:
        sendEmail.send_mail(
            "Processeur", "Error : capacitee maximale du processeur atteinte.")

    if ram > 99:
        sendEmail.send_mail(
            "Ram", "Error : capacitee maximale de la memoire vive atteinte.")

    if disque > 99:
        sendEmail.send_mail(
            "Disque", "Error : capacitee maximale du disque dur atteint.")
コード例 #24
0
ファイル: pdSql.py プロジェクト: taolaptop/pytrade
 def update_sql_index(self, index_list=['sh','sz','zxb','cyb','hs300','sh50'],force_update=False):
     index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
                      'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
     FIX_FACTOR = 1.0
     scz_code_str='399001'
     zxb_code_str='399005'
     chy_code_str='399006'
     shz ='999999'
     shz_50 = '000016'
     hs_300 = '000300'
     zx_300 ='399008'
     sz_300 ='399007'
     d_format='%Y/%m/%d'
     last_date_str = tt.get_last_trade_date(date_format=d_format)
     latest_date_str = tt.get_latest_trade_date(date_format=d_format)
     print('last_date_str=',last_date_str)
     print('latest_date_str=',latest_date_str)
     #next_date_str = tt.get_next_trade_date(date_format=d_format)
     #print(next_date_str)
     try:
         quotation_index_df = qq.get_qq_quotations(['sh','sz','zxb','cyb','hs300','sh50'], ['code','date','open','high','low','close','volume','amount'])
         #quotation_index_df = ts.get_index()
     except:
         sleep(3)
         quotation_index_df = qq.get_qq_quotations(['sh','sz','zxb','cyb','hs300','sh50'], ['code','date','open','high','low','close','volume','amount'])
     #quotation_index_df[['open','high','low','close']]=quotation_index_df[['open','high','low','close']].round(2)
     #quotation_index_df['amount'] = quotation_index_df['amount']*(10**8)
     #quotation_index_df['date'] = latest_date_str
     quotation_index_df['factor'] = 1.0
     #print(quotation_index_df)
     need_to_send_mail = []
     sub = ''
     #table_update_times = self.get_table_update_time()
     for index_name in index_list:
         yh_symbol = index_symbol_maps[index_name]
         yh_file_name = YH_SOURCE_DATA_DIR+symbol+'.'+file_type
         #yh_index_df = get_yh_raw_hist_df(code_str=symbol)
         yh_index_df = pd.read_csv(yh_file_name)
         yh_index_df['factor'] = FIX_FACTOR
         try:
             date_data = self.query_data(table=index_name,fields='date',condition="date>='%s'" % last_date_str)
             data_len = len(date_data)
             #this_table_update_time = table_update_times[index_name]
             #print('this_table_update_time=', this_table_update_time)
             if len(date_data)==0: #no update more than two day
                 """需要手动下载银河客户端数据"""
                 print('Need to manual update %s index from YH APP! Please make suere you have sync up YH data' % index_name)
                 need_to_send_mail.append(index_name)
                 sub = '多于两天没有更新指数数据库'
                 self.drop_table(table_name=index_name)
                 self.insert_table(data_frame=yh_index_df,table_name=index_name)
             elif len(date_data) == 1: # update by last date
                 """只需要更新当天数据"""
                 self.update_sql_index_today(index_name,latest_date_str,quotation_index_df,index_symbol_maps)
                 pass
             elif len(date_data) == 2: #update to  latest date
                 """要更新盘中获取的当天数据"""
                 print(' %s index updated to %s.' % (index_name,latest_date_str))
                 if force_update:
                     print(' force update %s index' % index_name)
                     self.delete_data(table_name=index_name,condition="date='%s'" % latest_date_str)
                     self.update_sql_index_today(index_name,latest_date_str,quotation_index_df,index_symbol_maps)
                     pass
                 else:
                     pass
             else:
                 pass
         #print(date_data)
         except:
             sub = '数据表不存在'
             need_to_send_mail.append(index_name)
             print('Table %s not exist.'% index_name)
             try:
                 self.drop_table(table_name=yh_index_df)
             except:
                 pass
             self.insert_table(data_frame=yh_index_df,table_name=index_name,is_index=False)
             print('Created the table %s.' % index_name)
     if need_to_send_mail:
         content = '%s 数据表更新可能异常' % need_to_send_mail
         sm.send_mail(sub,content,mail_to_list=None)
コード例 #25
0
ファイル: pdSql.py プロジェクト: taolaptop/pytrade
 def update_one_stock(self, symbol,force_update=False):
     index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
                      'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
     FIX_FACTOR = 1.0
     d_format='%Y/%m/%d'
     last_date_str = tt.get_last_trade_date(date_format=d_format)
     latest_date_str = tt.get_latest_trade_date(date_format=d_format)
     print('last_date_str=',last_date_str)
     print('latest_date_str=',latest_date_str)
     next_date_str = tt.get_next_trade_date(date_format=d_format)
     #print(next_date_str)
     quotation_date = ''
     try:
         quotation_index_df = qq.get_qq_quotations([symbol], ['code','date','open','high','low','close','volume','amount'])
         quotation_date = quotation_index_df.iloc[0]['date']
         #quotation_index_df = ts.get_index()
     except:
         sleep(3)
         quotation_index_df = qq.get_qq_quotations([symbol], ['code','date','open','high','low','close','volume','amount'])
         quotation_date = quotation_index_df.iloc[0]['date']
     print('quotation_date=',quotation_date)
     print(quotation_index_df)
     quotation_index_df['factor'] = 1.0
     quotation_index_df = quotation_index_df[['date','open','high','low','close','volume','amount','factor']]
     #quotation_index_df.iloc[0]['volume'] = 0
     #quotation_index_df.iloc[0]['amount'] = 0
     print(quotation_index_df)
     #print(quotation_index_df)
     need_to_send_mail = []
     sub = ''
     index_name = symbol
     #table_update_times = self.get_table_update_time()
     if quotation_date:
         yh_symbol = symbol
         if symbol in index_symbol_maps.keys():
             yh_symbol = index_symbol_maps[index_name]
         yh_file_name = YH_SOURCE_DATA_DIR+symbol+'.'+file_type
         #yh_index_df = get_yh_raw_hist_df(code_str=symbol)
         yh_index_df = pd.read_csv(yh_file_name)
         yh_index_df['factor'] = FIX_FACTOR
         yh_last_date = yh_index_df.tail(1).iloc[0]['date']
         print('yh_last_date=',yh_last_date)
         print( yh_index_df)#.head(len(yh_index_df)-1))
         if True:
             #date_data = self.query_data(table=index_name,fields='date',condition="date>='%s'" % last_date_str)
             #data_len = len(date_data)
             #this_table_update_time = table_update_times[index_name]
             #print('this_table_update_time=', this_table_update_time)
             if yh_last_date<last_date_str: #no update more than two day
                 """需要手动下载银河客户端数据"""
                 print('Need to manual update %s index from YH APP! Please make suere you have sync up YH data' % index_name)
                 need_to_send_mail.append(index_name)
                 sub = '多于两天没有更新指数数据库'
                 content = '%s 数据表更新可能异常' % need_to_send_mail
                 sm.send_mail(sub,content,mail_to_list=None)
             elif yh_last_date==last_date_str: # update by last date
                 """只需要更新当天数据"""
                 yh_index_df = yh_index_df.append(quotation_index_df, ignore_index=True)
                 print(yh_index_df)
                 pass
             else:# yh_last_date>latest_date_str: #update to  latest date
                 """YH已经更新到今天,要更新盘中获取的当天数据"""
                 print(' %s index updated to %s; not need to update' % (index_name,latest_date_str))
                 if force_update:
                     print(' force update %s index' % index_name)
                     yh_index_df0 = yh_index_df.head(len(yh_index_df)-1)
                     print(yh_index_df0)
                     yh_index_df = yh_index_df0.append(quotation_index_df, ignore_index=True)
                     print(yh_index_df)
                 else:
                     pass
             yh_index_df = yh_index_df.set_index('date')
             dir='C:/hist/day/data/'
             file_name = dir+ '%s.csv' % index_name
             try:
                 os.remove(file_name)
                 print('Delete and update the csv file')
             except:
                 pass
             yh_index_df.to_csv(file_name ,encoding='utf-8')
     return yh_index_df
コード例 #26
0
def buy():
    with Browser('firefox') as browser:
        # Visit URL
        url = "http://xy2.cbg.163.com/"
        browser.visit(url)
        #time.sleep(10)
        button = browser.find_by_id('link_105')
        button.click()
        #time.sleep(10)
        button = browser.find_by_id('server_18齐云灵脉')
        button.click()

        #点击登陆 需要手动输入用户名 密码 验证码
        #time.sleep(30)
        # raw_input_name = raw_input("username: "******"password: "******"image_validate: ")
        # browser.find_by_id('urs').fill(raw_input_name)
        # browser.find_by_id('password').fill(raw_input_password)
        # browser.find_by_id('image_validate').fill(image_validate)
        # links_found = browser.find_by_tag('a')[9]
        # links_found.click()

        #点击进入
        time.sleep(30)
        links_found = browser.find_by_text('进入')
        links_found.click()

        #输入将军登陆界面
        #time.sleep(30)<input class="text" name="otp" id="otp" type="password">
        # jiangjun_validate = raw_input("jiangjun_validate: ")
        # browser.find_by_id('otp').fill(jiangjun_validate)
        # links_found = browser.find_by_value('确定')
        # links_found.click()

        #点击公示期物品
        # time.sleep(10)
        # links_found = browser.find_by_id('banner_fairshow_a')
        # links_found.click()

        #点击召唤兽

        # browser.fill('TPL_username', username.decode('utf8'))

        # links_found = browser.find_by_text('跨服购买')
        # links_found.click()

        while True:
            #循环页面
            try:
                time.sleep(10)
                browser.visit(
                    'http://xy2.cbg.163.com/cgi-bin/equipquery.py?act=show_overall_search_pet'
                )
                browser.reload()
                browser.find_by_id("js_search_pet_name").first.fill(
                    "孟极".decode('utf8'))
                browser.find_by_id("txt_price_max").first.fill(
                    "2600".decode('utf8'))
                browser.find_by_text('义之金叶神').click()
                browser.find_by_text('信之土叶神').click()
                browser.find_by_text('分花拂柳').click()
                browser.find_by_text('4年以上可移民服').click()
                browser.find_by_name('skill_logic').last.click()
                browser.find_by_id('btn_equip_search').click()
                time.sleep(10)
            except:
                print u'\u627e\u4e0d\u5230\u9875\u9762'  #找不到页面
                time.sleep(10)
                browser.visit(
                    'http://xy2.cbg.163.com/cgi-bin/equipquery.py?act=show_overall_search_pet'
                )

            #第一行数据
            #获取召唤兽等级
            try:
                mengji = browser.find_by_value('查看详情')

                for i in mengji:
                    print i.value
                    print 'jieshu'
                    time.sleep(1000000)
                    if browser.find_by_text('已出售') or browser.find_by_text(
                            '被下单'):
                        print u'已经出售'
                    else:
                        # 点击同意公示期规则按钮
                        links_found = browser.find_by_id('agree_fair_show_pay')
                        links_found.click()

                        # 点击预定(加入购物车)
                        links_found = browser.find_by_id('buy_btn')
                        links_found.click()

                        to_list = ''
                        sub = u'已购买成功'
                        content = u'已购买'
                        sendEmail.send_mail(to_list, sub, content)
                        time.sleep(10)

                print 'done'
            except:
                print u'\u627e\u4e0d\u5230\u53ec\u5524\u517d\u7b49\u7ea7'  #找不到召唤兽等级
                time.sleep(30)
                continue
コード例 #27
0
 def config_trade(self,
                  stock_code,
                  pre_holding_amount,
                  trade_amount,
                  trade_direct='B'):
     """定时买入某只股票
     :param stock_code: 股票代码
     :param buy_rate: 买出比例,默认全买
     :param set_time: datetime type, 买入时间
     :return trade_state: float type, -2 系统异常,-1 反向操作,0实质无成交,0.5部分成交,1按计划成交,2超额成交
     """
     trade_state = 0
     #print(self.position)
     pos_holding_amount = self.get_position_info(stock_code,
                                                 info_column='股份余额')
     msg_content = ''
     if pos_holding_amount < 0:
         log.debug('帐户空仓,无任何持仓股票')
         trade_state = -2
     else:
         if trade_direct == 'B':
             if pos_holding_amount < pre_holding_amount:
                 msg_content = '原计划买入 %s %s股,实质卖出%s股' % (
                     stock_code, trade_amount,
                     (pre_holding_amount - pos_holding_amount))
                 trade_state = -1
             elif pos_holding_amount == pre_holding_amount:
                 msg_content = '原计划买入 %s %s股,实质无任何买入' % (stock_code,
                                                         trade_amount)
                 trade_state = 0
             elif pos_holding_amount < (pre_holding_amount + trade_amount):
                 msg_content = '原计划买入 %s %s股,实质部分买入%s股' % (
                     stock_code, trade_amount,
                     (pos_holding_amount - pre_holding_amount))
                 trade_state = 0.5
             elif pos_holding_amount == (pre_holding_amount + trade_amount):
                 msg_content = '按原计划买入 %s %s股' % (stock_code, trade_amount)
                 trade_state = 1
             else:
                 msg_content = '原计划买入 %s %s股,实质超额买入,共买入%s股' % (
                     stock_code, trade_amount,
                     (pos_holding_amount - pre_holding_amount))
                 trade_state = 2
         elif trade_direct == 'S':
             if pos_holding_amount > pre_holding_amount:
                 msg_content = '原计划卖出 %s %s股,实质买入%s股' % (
                     stock_code, trade_amount,
                     (pos_holding_amount - pre_holding_amount))
                 trade_state = -1
             elif pos_holding_amount == pre_holding_amount:
                 msg_content = '原计划卖出 %s %s股,实质无任何卖出' % (stock_code,
                                                         trade_amount)
                 trade_state = 0
             elif pos_holding_amount > (pre_holding_amount - trade_amount):
                 msg_content = '原计划卖出 %s %s股,实质部分卖出%s股' % (
                     stock_code, trade_amount,
                     (pre_holding_amount - pos_holding_amount))
                 trade_state = 0.5
             elif pos_holding_amount == (pre_holding_amount - trade_amount):
                 msg_content = '按原计划卖出%s %s股' % (stock_code, trade_amount)
                 trade_state = 1
             else:
                 msg_content = '原计划卖出 %s %s股,实质超额卖出,共卖出%s股' % (
                     stock_code, trade_amount,
                     (pre_holding_amount - pos_holding_amount))
                 trade_state = 2
         else:
             trade_state = -2
     if msg_content:
         log.debug(msg_content)
         sub = '%s 交易结果确认' % stock_code
         sm.send_mail(sub, msg_content)
     return trade_state
コード例 #28
0
ファイル: batchJob.py プロジェクト: tomli1981/mail
    def send_email_by_control_id(self, control_id):

        conn = get_connection()
        cur = conn.cursor()
        ret_code = 2
        args = (control_id, 0, 0)

        while True:

            cur.callproc('GetMailLIstByControlID', args)
            mails = cur.fetchall()

            if len(mails) == 0:
                break
            while cur.nextset():
                pass

            cur.execute("select @_GetMailLIstByControlID_1")
            mail_step_time = cur.fetchone()[0]

            cur.execute("select @_GetMailLIstByControlID_2")
            next_waiting_interval = cur.fetchone()[0]

            if next_waiting_interval == -1:
                break
            else:
                time.sleep(next_waiting_interval)

            for item in mails:


                try:
                    if item[4] == 0:

                        if validate_email(item[1], verify=True):
                            cur.execute("update mail set mail.type_flag = 1 where id =%d" % item[3])
                            cur.execute("commit")
                        else:
                            cur.execute("update mail set mail.type_flag = -1 where id =%d" % item[3])
                            cur.execute("commit")
                    else:
                        time.sleep(mail_step_time)

                    sendEmail.send_mail(self.mail_from, item[1], self.subject, self.msg_txt)
                    ret_code = 2

                except smtplib.SMTPHeloError:
                    ret_code = 3
                except smtplib.SMTPRecipientsRefused:
                    ret_code = 4
                except smtplib.SMTPSenderRefused:
                    ret_code = 5
                except smtplib.SMTPDataError:
                    ret_code = 6
                finally:
                    logging.info('update status: ret_code->%s, mail_sending_log.id->%s , email->%s' % (
                        ret_code, item[0], item[1]))
                    cur.execute(
                        "update mail_sending_log set status=%d, time_stamp=now() where id=%d" % (ret_code, item[0]))
                    conn.commit()
        cur.close()
        conn.commit()
        conn.close()
コード例 #29
0
ファイル: pytrade_tdx.py プロジェクト: taolaptop/pytrade
    def init_hwnd(self):
        self.__top_hwnd = findTopWindow(wantedClass='TdxW_MainFrame_Class')
        self.__button = {
            'refresh': 180,
            'position': 145,
            'deal': 112,
            'withdrawal': 83,
            'sell': 50,
            'buy': 20
        }
        windows = dumpWindows(self.__top_hwnd)
        if self.debug: print('windows=', windows)
        temp_hwnd = 0
        temp_hwnd_guanlian = 0
        p_hwnd = 0
        self.p_acc_hwnd = 0
        self.acc_hwnd = 0
        self.new_stock_order_hwnd = 0
        find_guan_lian = False
        find_new_stock = False
        find_combobox = False
        for window in windows:
            child_hwnd, window_text, window_class = window
            if window_text == '买卖关联同一支股票':
                temp_hwnd_guanlian = child_hwnd
                print("find the hwnd: 买卖关联同一支股票, ", temp_hwnd_guanlian)
            if window_class == 'MHPToolBar' and window_text == 'MainViewBar':
                self.p_acc_hwnd = child_hwnd
                print('parent_acc_combobox_hwnd=', self.p_acc_hwnd)
                p_p_acc_hwnd = getParentWindow(self.p_acc_hwnd)
                acc_windows = dumpWindows(self.p_acc_hwnd)
                for window in acc_windows:
                    child_hwnd, window_text, window_class = window
                    if window_class == 'ComboBox':
                        self.acc_hwnd = child_hwnd
                        find_combobox = True
                        print('acc_combobox_hwnd=', self.acc_hwnd)
            if window_text == '一键申购':
                self.new_stock_order_hwnd = child_hwnd
                find_new_stock = True
            if find_guan_lian and find_new_stock and find_combobox:
                break
        else:
            pass
            #raise Exception("Change saving type failed")

        if temp_hwnd_guanlian:
            p_hwnd = getParentWindow(temp_hwnd_guanlian)  #买卖关联同一支股票的上一级句柄
            if self.debug: print('p_hwnd=', p_hwnd)
            p_hwnd_children = dumpWindow(p_hwnd)
            if self.debug: print('p_hwnd_children=', p_hwnd_children)
            p_p_hwnd = getParentWindow(p_hwnd)  #股票交易第一级句柄
            p_p_hwnd_children = dumpWindow(p_p_hwnd)  #右侧操作区
            self.__menu_hwnds = dumpWindow(p_p_hwnd_children[0][0])
            if self.debug: print(self.__menu_hwnds)
            self.__buy_sell_hwnds = p_hwnd_children
            EXPECT_LEN = 68
            print(len(self.__buy_sell_hwnds))
            if len(self.__buy_sell_hwnds) != EXPECT_LEN:
                sm.send_mail(sub='无法获得通达信对买对卖界面的窗口句柄',
                             content='子句柄数量为 %s,不等于期望数量:%s.也许软件亿升级。' %
                             (len(self.__buy_sell_hwnds), EXPECT_LEN))
                tkinter.messagebox.showerror('错误', '无法获得通达信对买对卖界面的窗口句柄')
            else:
                pass
        else:
            sm.send_mail(sub='无法获得  买卖关联同一支股票 的窗口句柄', content='请点击  双向委托 按钮')
            tkinter.messagebox.showerror('错误', '无法获得 "买卖关联同一支股票"的窗口句柄')
        return
コード例 #30
0
def sendAlert(subj, msg):
    msg = time.strftime("%a, %d %b %Y %H:%M:%S \n", time.localtime()) + msg
    sendEmail.send_mail(sendEmail.ALERT_USERID, subj, msg)
コード例 #31
0
def sendStatus(subj, msg):
    msg = time.strftime("%a, %d %b %Y %H:%M:%S \n", time.localtime()) + msg
    sendEmail.send_mail(sendEmail.STATUS_USERID, subj, msg)
コード例 #32
0
ファイル: radonMaster.py プロジェクト: KurtAndres/radonMaster
    print("Press CTRL+C to exit...\n")

    paramCheck()

    # Display sensor results on program startup
    status, result, tempC = abp.readAbpStatusTemp()
    # change sign of result to convert pressure to vacuum
    s = 'Status: {0:d}  Vacuum: {1:7.3f} {2:s} {3:7.2f} in.wc {4:5.1f} degF\n'.format(
        status, round(-result, 3), abp.PRES_UNITS,
        round(abp.pres2inwc(-result), 2), round(abp.c2f(tempC), 1))
    print(s)

    if alertsEnabled:
        cfgData.loadJsonFile()
        sendEmail.send_mail(cfgData.cfgData_get("GMAIL_USER"),
                            cfgData.password_return(),
                            cfgData.cfgData_get("TO"), "RadonMaster Status",
                            "Program start: " + formatLocalTime() + "\n" + s)

    startTimer()

    print("First averaged set of measurement will display in a few minutes...")

    try:
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        #timer.cancel()
        stopFlag = 1
        time.sleep(tInterval + 1)
        sys.exit(" Exit")
コード例 #33
0
ファイル: pdSql0.py プロジェクト: taolaptop/pytrade
def update_one_stock(symbol,realtime_update=False,dest_dir='C:/hist/day/data/', force_update_from_YH=False):
    """
    运行之前先下载及导出YH历史数据
    """
    """
    :param symbol: string type, stock code
    :param realtime_update: bool type, True for K data force update during trade time 
    :param dest_dir: string type, like csv dir
    :param force_update_from_YH: bool type, force update K data from YH
    :return: Dataframe, history K data for stock
    """
    index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
                     'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
    qq_index_symbol_maps = {'sh':'000001','sz':'399001','zxb':'399005','cyb':'399006',
                         'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
    FIX_FACTOR = 1.0
    d_format='%Y/%m/%d'
    last_date_str = tt.get_last_trade_date(date_format=d_format)
    latest_date_str = tt.get_latest_trade_date(date_format=d_format)
    #print('last_date_str=',last_date_str)
    #print('latest_date_str=',latest_date_str)
    next_date_str = tt.get_next_trade_date(date_format=d_format)
    #print(next_date_str)
    dest_file_name = dest_dir+ '%s.csv' % symbol
    dest_df = get_raw_hist_df(code_str=symbol)
    file_type='csv'
    RAW_HIST_DIR = "C:/中国银河证券海王星/T0002/export/"
    yh_file_name = RAW_HIST_DIR+symbol+'.'+file_type
    if dest_df.empty:
        if symbol in index_symbol_maps.keys():
            symbol = index_symbol_maps[symbol]
        yh_file_name = RAW_HIST_DIR+symbol+'.'+file_type
        #yh_index_df = get_yh_raw_hist_df(code_str=symbol)
        yh_index_df = pd.read_csv(yh_file_name)
        yh_index_df['factor'] = 1.0
        yh_df = yh_index_df.set_index('date')
        yh_df.to_csv(dest_file_name ,encoding='utf-8')
        dest_df = yh_index_df
        #del dest_df['rmb']
        return yh_df
    #print(dest_df)
    dest_df_last_date = dest_df.tail(1).iloc[0]['date']
    #print('dest_df_last_date=',dest_df_last_date)
    if dest_df_last_date<latest_date_str:     
        quotation_date = ''
        try:
            quotation_index_df = qq.get_qq_quotations([symbol], ['code','date','open','high','low','close','volume','amount'])
            quotation_date = quotation_index_df.iloc[0]['date']
            if dest_df_last_date==quotation_date:
                return dest_df
            #quotation_index_df = ts.get_index()
        except:
            time.sleep(3)
            quotation_index_df = qq.get_qq_quotations([symbol], ['code','date','open','high','low','close','volume','amount'])
            quotation_date = quotation_index_df.iloc[0]['date']
            if dest_df_last_date==quotation_date:
                return dest_df
        #print('quotation_date=',quotation_date)
        #print(quotation_index_df)
        quotation_index_df['factor'] = 1.0
        quotation_index_df = quotation_index_df[['date','open','high','low','close','volume','amount','factor']]
        #quotation_index_df.iloc[0]['volume'] = 0
        #quotation_index_df.iloc[0]['amount'] = 0
        #print(quotation_index_df)
        #print(quotation_index_df)
        need_to_send_mail = []
        sub = ''
        index_name = symbol
        #table_update_times = self.get_table_update_time()
        
        if quotation_date:
            yh_symbol = symbol
            if symbol in index_symbol_maps.keys():
                yh_symbol = index_symbol_maps[index_name]
            yh_file_name = RAW_HIST_DIR+yh_symbol+'.'+file_type
            #yh_index_df = get_yh_raw_hist_df(code_str=symbol)
            yh_index_df = pd.read_csv(yh_file_name,encoding='GBK')
            yh_index_df['factor'] = FIX_FACTOR
            yh_last_date = yh_index_df.tail(1).iloc[0]['date']
            #print('yh_last_date=',yh_last_date)
            #print( yh_index_df)#.head(len(yh_index_df)-1))
            
            if yh_last_date>dest_df_last_date:  #dest_df_last_date<latest_date_str
                #date_data = self.query_data(table=index_name,fields='date',condition="date>='%s'" % last_date_str)
                #data_len = len(date_data)
                #this_table_update_time = table_update_times[index_name]
                #print('this_table_update_time=', this_table_update_time)
                if yh_last_date<last_date_str: #no update more than two day
                    """需要手动下载银河客户端数据"""
                    print('Need to manual update %s index from YH APP! Please make suere you have sync up YH data' % index_name)
                    need_to_send_mail.append(index_name)
                    sub = '多于两天没有更新指数数据库'
                    content = '%s 数据表更新可能异常' % need_to_send_mail
                    sm.send_mail(sub,content,mail_to_list=None)
                elif yh_last_date==last_date_str: # update by last date
                    """只需要更新当天数据"""
                    if realtime_update and yh_last_date<latest_date_str:
                        print(' force update %s index' % symbol)
                        yh_index_df = yh_index_df.append(quotation_index_df, ignore_index=True)
                        #print(yh_index_df)
                    pass
                else:# yh_last_date>latest_date_str: #update to  latest date
                    """YH已经更新到今天,要更新盘中获取的当天数据"""
                    print(' %s index updated to %s; not need to update' % (index_name,latest_date_str))
                    """
                    if force_update:
                        print(' force update %s index' % index_name)
                        yh_index_df0 = yh_index_df.head(len(yh_index_df)-1)
                        print(yh_index_df0)
                        yh_index_df = yh_index_df0.append(quotation_index_df, ignore_index=True)
                        print(yh_index_df)
                    else:
                        pass
                    """
                yh_index_df = yh_index_df.set_index('date')
                """
                try:
                    os.remove(file_name)
                    print('Delete and update the csv file')
                except:
                    pass
                """
                yh_index_df.to_csv(dest_file_name ,encoding='utf-8')
            else:
                if force_update_from_YH and yh_last_date==dest_df_last_date:
                    yh_index_df = yh_index_df.set_index('date')
                    yh_index_df.to_csv(dest_file_name ,encoding='utf-8')
                pass
    else:
        print('No need to update data')
        if realtime_update:
            quotation_index_df = qq.get_qq_quotations([symbol], ['code','date','open','high','low','close','volume','amount'])
            quotation_index_df['factor'] = 1.0
            quotation_index_df = quotation_index_df[['date','open','high','low','close','volume','amount','factor']]
            #print(quotation_index_df)
            print(' force update %s index' % symbol)
            dest_df0 = dest_df
            if dest_df_last_date==latest_date_str:
                dest_df0 = dest_df.head(len(dest_df)-1)
            #print(dest_df0)
            dest_df = dest_df0.append(quotation_index_df, ignore_index=True)
            #print(dest_df)
            if quotation_index_df.empty:
                pass
            else:
                dest_df.to_csv(dest_file_name ,encoding='utf-8')
        else:
            pass
    return dest_df
コード例 #34
0
ファイル: test.py プロジェクト: speakfly/findPractice
import sendEmail

message = '<html><body><a href="www.baidu.com">百度</a></body></html>'
mode = "html"
sendEmail.send_mail(message, mode)
コード例 #35
0
ファイル: pdSql_common.py プロジェクト: allisnone/pytrade
def update_one_stock(symbol,realtime_update=False,dest_dir='C:/中国银河证券海王星/T0002/export/', force_update_from_YH=False):
    """
    运行之前先下载及导出YH历史数据
    """
    """
    :param symbol: string type, stock code
    :param realtime_update: bool type, True for K data force update during trade time 
    :param dest_dir: string type, like csv dir
    :param force_update_from_YH: bool type, force update K data from YH
    :return: Dataframe, history K data for stock
    """
    index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
                     'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
    qq_index_symbol_maps = {'sh':'000001','sz':'399001','zxb':'399005','cyb':'399006',
                         'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
    FIX_FACTOR = 1.0
    d_format='%Y/%m/%d'
    last_date_str = tt.get_last_trade_date(date_format=d_format)
    latest_date_str = tt.get_latest_trade_date(date_format=d_format)
    #print('last_date_str=',last_date_str)
    #print('latest_date_str=',latest_date_str)
    next_date_str = tt.get_next_trade_date(date_format=d_format)
    #print(next_date_str)
    dest_file_name = dest_dir+ '%s.csv' % symbol
    dest_df = get_raw_hist_df(code_str=symbol)
    file_type='csv'
    RAW_HIST_DIR = "C:/中国银河证券海王星/T0002/export/"
    yh_file_name = RAW_HIST_DIR+symbol+'.'+file_type
    if symbol in index_symbol_maps.keys():
        symbol = index_symbol_maps[symbol]
        dest_file_name = dest_dir+ '%s.csv' % symbol
    #print('dest_file_name=',dest_file_name)
    if dest_df.empty:
        if symbol in index_symbol_maps.keys():
            symbol = index_symbol_maps[symbol]
        yh_file_name = RAW_HIST_DIR+symbol+'.'+file_type
        #yh_index_df = get_yh_raw_hist_df(code_str=symbol)
        yh_index_df = pd.read_csv(yh_file_name)
        #yh_index_df['factor'] = 1.0
        yh_df = yh_index_df.set_index('date')
        yh_df.to_csv(dest_file_name ,encoding='utf-8')
        dest_df = yh_index_df
        #del dest_df['rmb']
        return yh_df
    #print(dest_df)
    dest_df_last_date = dest_df.tail(1).iloc[0]['date']
    #print('dest_df_last_date=',dest_df_last_date)
    quotation_datetime = datetime.datetime.now()
    if dest_df_last_date<latest_date_str:     
        quotation_date = ''
        try:
            quotation_index_df = qq.get_qq_quotations_df([symbol], ['code','date','open','high','low','close','volume','amount'])
            quotation_date = quotation_index_df.iloc[0]['date']
            #quotation_date = quotation_index_df.iloc[0]['date']
            #quotation_datetime = quotation_index_df.iloc[0]['datetime']
            #del quotation_index_df['datetime']
            if dest_df_last_date==quotation_date:
                return dest_df
            #quotation_index_df = ts.get_index()
        except:
            time.sleep(3)
            quotation_index_df = qq.get_qq_quotations_df([symbol], ['code','date','open','high','low','close','volume','amount'])
            print(quotation_index_df)
            quotation_date = quotation_index_df.iloc[0]['date']
            #quotation_datetime = quotation_index_df.iloc[0]['datetime']
            #del quotation_index_df['datetime']
            if dest_df_last_date==quotation_date:
                return dest_df
        #print('quotation_date=',quotation_date)
        #print(quotation_index_df)
        #quotation_index_df['factor'] = 1.0
        quotation_index_df = quotation_index_df[['date','open','high','low','close','volume','amount']]#,'factor']]
        #quotation_index_df.iloc[0]['volume'] = 0
        #quotation_index_df.iloc[0]['amount'] = 0
        #print(quotation_index_df)
        #print(quotation_index_df)
        need_to_send_mail = []
        sub = ''
        index_name = symbol
        #table_update_times = self.get_table_update_time()
        
        if quotation_date:
            yh_symbol = symbol
            if symbol in index_symbol_maps.keys():
                yh_symbol = index_symbol_maps[index_name]
            yh_file_name = RAW_HIST_DIR+yh_symbol+'.'+file_type
            #yh_index_df = get_yh_raw_hist_df(code_str=symbol)
            yh_index_df = pd.read_csv(yh_file_name,encoding='GBK')
            #yh_index_df['factor'] = FIX_FACTOR
            yh_last_date = yh_index_df.tail(1).iloc[0]['date']
            #print('yh_last_date=',yh_last_date)
            #print( yh_index_df)#.head(len(yh_index_df)-1))
            
            if yh_last_date>dest_df_last_date:  #dest_df_last_date<latest_date_str
                #date_data = self.query_data(table=index_name,fields='date',condition="date>='%s'" % last_date_str)
                #data_len = len(date_data)
                #this_table_update_time = table_update_times[index_name]
                #print('this_table_update_time=', this_table_update_time)
                if yh_last_date<last_date_str: #no update more than two day
                    """需要手动下载银河客户端数据"""
                    print('Need to manual update %s index from YH APP! Please make suere you have sync up YH data' % index_name)
                    need_to_send_mail.append(index_name)
                    sub = '多于两天没有更新指数数据库'
                    content = '%s 数据表更新可能异常' % need_to_send_mail
                    sm.send_mail(sub,content,mail_to_list=None)
                elif yh_last_date==last_date_str: # update by last date
                    """只需要更新当天数据"""
                    realtime_update = tt.is_trade_time_now()
                    if realtime_update:
                        if yh_last_date<latest_date_str:
                            print(' force update %s index' % symbol)
                            yh_index_df = yh_index_df.append(quotation_index_df, ignore_index=True)
                        
                        #elif yh_last_date==latest_date_str:
                        #    print(' delete last update, then force update %s index' % symbol)
                        #    yh_index_df=yh_index_df[:-1]
                        #    yh_index_df = yh_index_df.append(quotation_index_df, ignore_index=True)
                        
                        else:
                            pass
                        #print(yh_index_df)
                    else:
                        pass
                else:# yh_last_date>latest_date_str: #update to  latest date
                    """YH已经更新到今天,要更新盘中获取的当天数据"""
                    print(' %s index updated to %s; not need to update' % (index_name,latest_date_str))
                    """
                    if force_update:
                        print(' force update %s index' % index_name)
                        yh_index_df0 = yh_index_df.head(len(yh_index_df)-1)
                        print(yh_index_df0)
                        yh_index_df = yh_index_df0.append(quotation_index_df, ignore_index=True)
                        print(yh_index_df)
                    else:
                        pass
                    """
                yh_index_df = yh_index_df.set_index('date')
                """
                try:
                    os.remove(file_name)
                    print('Delete and update the csv file')
                except:
                    pass
                """
                yh_index_df.to_csv(dest_file_name ,encoding='utf-8')
            else:
                if force_update_from_YH and yh_last_date==dest_df_last_date:
                    yh_index_df = yh_index_df.set_index('date')
                    yh_index_df.to_csv(dest_file_name ,encoding='utf-8')
                pass
    elif dest_df_last_date==latest_date_str:
        print('No need to update data')
        realtime_update = tt.is_trade_time_now()
        if realtime_update:
            quotation_index_df = qq.get_qq_quotations([symbol], ['code','date','open','high','low','close','volume','amount'])
            #quotation_index_df['factor'] = 1.0
            quotation_index_df = quotation_index_df[['date','open','high','low','close','volume','amount']]#'factor']]
            #print(quotation_index_df)
            print(' force update %s index' % symbol)
            dest_df0 = dest_df
            if dest_df_last_date==latest_date_str:
                dest_df0 = dest_df.head(len(dest_df)-1)
                #dest_df0 = dest_df0[:-1]
            #print(dest_df0)
            dest_df = dest_df0.append(quotation_index_df, ignore_index=True)
            #print(dest_df)
            if quotation_index_df.empty:
                pass
            else:
                yh_index_df = yh_index_df.set_index('date')
                dest_df.to_csv(dest_file_name ,encoding='utf-8')
        else:
            pass
    else:
        pass
    return dest_df
コード例 #36
0
ファイル: radonMaster.py プロジェクト: KurtAndres/radonMaster
def myTimer():
    global timer, count, sensorSum, lastReadTime, statusIntervalCntDn, lastAlertTime

    t = datetime.datetime.now()

    # Send status message
    if (alertsEnabled and t.hour == statusMsgHHMM[0]
            and t.minute == statusMsgHHMM[1] and t.second == 0):
        sendStatus = 0

        # Send status message every n days, after sending first status message
        if statusInterval:
            statusIntervalCntDn = statusIntervalCntDn - 1
            if statusIntervalCntDn <= 0:
                statusIntervalCntDn = statusInterval
                sendStatus = 1

        # Send status message on a day of the month
        elif statusDOM:
            if t.day == statusDOM:
                sendStatus = 1

        # Send status message on a day of the week
        elif t.weekday() == statusDOW:
            sendStatus = 1

        if sendStatus:
            s = "Reporting at " + time.strftime("%a, %d %b %Y %H:%M:%S \n",
                                                time.localtime())
            sendEmail.send_mail(cfgData.cfgData_get("GMAIL_USER"),
                                cfgData.password_return(),
                                cfgData.cfgData_get("TO"),
                                "RadonMaster Status", s)

    # Measure vacuum
    status, result = abp.readAbpStatus()
    if status == 0:
        sensorSum = sensorSum + abp.pres2inwc(
            -result)  # change sign to convert pressure to vacuum
        count = count + 1

    # Calculate average vacuum over interval, log data, and check for alert conditions
    if (count >= tAverage and t.second == 0):
        sensorAvg = sensorSum / count
        sensorSum = 0
        count = 0

        appendCsv(sensorAvg)

        sAlg = radonAlg(sensorAvg)

        statusMsg = '{0:s} Vacuum: {1:7.2f} in.wc'.format(
            formatLocalTime(), round(sensorAvg, 2))
        print(statusMsg + " " + sAlg)

        if not (sAlg == "" or sAlg[:3] == "Cal"):
            alertMsg = "Alert " + formatLocalTime() + " " + sAlg
            print(alertMsg)

            tsec = time.time()
            if ((tsec - lastAlertTime) > minIntervalBtwAlerts):
                lastAlertTime = tsec
                sendEmail.send_mail(cfgData.cfgData_get("GMAIL_USER"),
                                    cfgData.password_return(),
                                    cfgData.cfgData_get("TO"),
                                    "RadonMaster Fan Alert", alertMsg)

    if not stopFlag:
        t = datetime.datetime.now()
        Timer(tInterval - t.microsecond / 1000000.,
              myTimer).start()  # every tInterval seconds