Пример #1
0
 def get_tushare_quote(self):
     while True:
         if self.kill == 1:
             #winsound.PlaySound('./wav/stop price monitor CN.wav',winsound.SND_ASYNC)
             playsound(mac_say='price monitor stopped',
                       win_sound='./wav/stop price monitor CN.wav',
                       frequency=600,
                       duration=500)
             break
         if self.stockcode <> False:
             try:
                 self.result = tushare.get_realtime_quotes(self.stockcode)
             except Exception as e:
                 log.error(e)
                 time.sleep(.5)
                 continue
             self.show_tushare_price(self.result)
         time.sleep(.5)
Пример #2
0
    def login(self):
        #log.info('%s Active...' % threading.current_thread().name)
        while True:
            if self.kill == 1:
                break
            if not self.login_flag:
                #print  '[%s] : %s' % (time.strftime('%H:%M:%S') ,'Logging...')
                log.info('Logging ...')
                for i in xrange(2):
                    self.thread_auth = threading.Thread(
                        target=self.__authorization,
                        name='Thread-auth-' + str(i))
                    self.thread_auth.setDaemon(True)
                    self.thread_auth.start()
                while self.login_flag == False:
                    time.sleep(.5)
                print '[%s] : %s' % (time.strftime('%H:%M:%S'),
                                     'Login Success!')
                playsound(mac_say='login success',
                          win_sound='./wav/login success.wav',
                          frequency=450,
                          duration=150)

            time.sleep(.5)
Пример #3
0
 def login_a(self):
     #log.info('%s Active...' % threading.current_thread().name)
     while True:
         if self.kill == 1:
             break
         if not self.login_flag:
             #print  '[%s] : %s' % (time.strftime('%H:%M:%S') ,'Logging...')
             log.info('Logging ...')
             try:
                 self.__authorization()
                 #print  '[%s] : %s' % (time.strftime('%H:%M:%S') ,'Login Success!')
                 if self.login_flag == True:
                     log.info('Login Success')
                     #os.system("say login success")
                     #Beep(450,150)
                     #winsound.PlaySound('./wav/login success.wav',winsound.SND_ASYNC)
                     playsound(mac_say='login success',
                               win_sound='./wav/login success.wav',
                               frequency=450,
                               duration=150)
                 else:
                     log.info('Login Failed')
                     #Beep(450,150)
                     playsound(mac_say='login failed',
                               win_sound='./wav/login failed.wav',
                               frequency=450,
                               duration=150)
                     time.sleep(3)
             except Exception:
                 #winsound.PlaySound('./wav/connection lost.wav',winsound.SND_ASYNC)
                 #os.system("say connection lost")
                 #Beep(600,500)
                 playsound(mac_say='connection lost',
                           win_sound='./wav/connection lost.wav',
                           frequency=600,
                           duration=500)
                 time.sleep(1)
                 log.info("Login connection lost !!!")
         time.sleep(.5)
Пример #4
0
    def __authorization(self):
        while self.login_flag == False:
            headers = {
                'Host': 'jy.xzsec.com',
                'User-Agent':
                'Mozilla/5.0 (Windows NT 6.1; rv:50.0) Gecko/20100101 Firefox/50.0',
                'Accept':
                'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                'Accept-Encoding': 'gzip, deflate, br',
                'Referer': 'https://jy.xzsec.com/Trade/Buy',
                'Connection': 'keep-alive',
                'Upgrade-Insecure-Requests': '1'
            }
            self.s.headers.update(headers)
            login_params = json.load(file("./config/dfcf.json"))

            #获取验证码:
            try:
                randNum, vcode = self.queue.get(block=False)
                print "use queue: %d, vcode: %s, randNum: %s" % (
                    self.queue.qsize(), vcode, randNum)
            except:
                randNum = "%.16f" % float(random.random())
                url_yzm = "https://jy.xzsec.com/Login/YZM?randNum=" + randNum
                #img = Image.open(cStringIO.StringIO(self.s.get(url_yzm).content))
                #img.show()
                #vcode=raw_input('Enter:')
                vcode = ""
                digits = list(string.digits)
                i = 0
                while True:
                    if self.login_flag == True: return
                    vcode, im = self.verify_code.get_verify_code(url_yzm)
                    if len(vcode) == 4:
                        for k in xrange(4):
                            if vcode[
                                    k] not in digits:  #[str(x) for x in xrange(10)]:
                                break
                        else:
                            #plt.figure("verify code")
                            #plt.imshow(im)
                            #plt.show()
                            print "\rCode:[%4s]    Retry Times:%2d" % (vcode,
                                                                       i)
                            break
                    sys.stdout.write(u"\r验证码识别:%s " % (vcode))
                    sys.stdout.flush()
                    i += 1

            if self.login_flag == True: return

            login_params.update({'identifyCode': vcode, 'randNumber': randNum})
            res = self.s.post('https://jy.xzsec.com/Login/Authentication',
                              login_params)

            if int(res.json()["Status"]) <> 0:
                playsound(mac_say='login failed',
                          win_sound='./wav/login failed.wav',
                          frequency=450,
                          duration=150)
                continue

            if self.login_flag == True: return

            #获取 validatekey:
            get_validatekey = self.s.get('https://jy.xzsec.com/Trade/Buy')
            if re.search(r'em_validatekey.*?>', get_validatekey.text).group():
                self.validatekey = re.search(
                    r'em_validatekey.*?>', get_validatekey.text).group()[37:73]
                #print "\nvalidatekey: %s" % self.validatekey
                self.url_suffix = '?validatekey=' + self.validatekey

                self.login_flag = True
                self.login_message = res.json()
                return self.login_message
            else:
                continue
Пример #5
0
def monitor_sell(code, buy_day, sell_day, stock_amount):
    '''
    如果选出的股票在下一个交易日出现停牌、开盘涨跌幅小于-9%、一字板涨跌停、 则取消买入这只股票
    上涨后回撤止盈: 持股期内当收益率触发止盈条件时(某交易日时点出现即触发,而不是收盘价),
    当日便不卖出,而是等下个交易日出现止盈回撤条件触发。
    例如:本来持有4天卖出的股票,
    但是到了第3天,某时点出现收益21%(用户设定的止盈条件是大于20%时,回撤5%止盈),则当天会继续持有,
    到期也不卖出了。当该股收益最高点出现后,从次日起(当日不管是否出现回撤止盈)开始重新监测,
    只要收益从最高点回撤大于5%时就会卖出止盈。
    {目前建议采用的止盈策略,盘中出现持股期间股价新高后,更新止损价, 随时止损}

    特殊情况:当持有股票一字涨跌停时,会继续持有。
    '''
    print '\n\033[3;33m     === Monitor Price for Selling [%s]: ===\033[0m' % code
    quotation.stockcode = code

    while quotation.result is False:
        time.sleep(.5)

    stock_holding_price = quotation.get_holding_period_price(code, buy_day)
    stop_loss_price = stock_holding_price['Open'] * (
        1 - float(strategy.lowerIncome) / 100)  #止损价格
    stop_sell_price = stock_holding_price['Open'] * (
        1 + float(strategy.upperIncome) / 100)  #止盈价格
    price_updated = False  # 判断是否出现新的价格高点, 用来处理到期卖出还是看回撤卖出
    if stock_holding_price['High'] > stop_sell_price:
        stop_sell_price = stock_holding_price['High']  #最新的止盈价格
        stop_loss_price = stop_sell_price * (
            1 - float(strategy.fallIncome) / 100)  #最新的止损价格
        price_updated = True

    dfcf_quote = trader.getquote(code)  #获取东方财富的报价:涨跌停价格不需要即时报价
    print u'止损价:{0:.2f} | 止盈价:{1:.2f} | 跌停价:{2:s} | 涨停价:{3:s}' \
          .format(stop_loss_price,stop_sell_price,dfcf_quote['bottomprice'],dfcf_quote['topprice'])
    #print '跌停价格: %s' % dfcf_quote['bottomprice']

    #卖出日,非一字涨停,如果涨停价也不能触及止盈价,则涨到 4% 就卖出,不用等收盘
    if sell_day <= time.strftime("%Y/%m/%d",time.localtime(time.time())) \
                   and price_updated <> True \
                   and float(dfcf_quote['topprice']) < stop_sell_price:
        print u'今日涨停价达不到止盈价, 因此盘中价格达到 4% 就卖出!'

    quotation.show = 1
    while calendar.trade_time() and calendar.trade_day(
    ) and int(stock_amount) <> 0:
        if float(quotation.result['high']
                 [0]) > stop_sell_price:  #最新止盈价格出现,更新止盈价格,当日停止卖出
            price_updated = True
            quotation.show = 0
            stop_sell_price = float(quotation.result['high'][0])
            stop_loss_price = stop_sell_price * (
                1 - float(strategy.fallIncome) / 100)  #最新的止损价格
            print 'The new highest price: %s occurred at: %s' % (
                stop_sell_price, time.strftime('%X', time.localtime()))
            quotation.show = 1

        #-----------卖出条件触发,发卖出指令-----------
        # .0. 确认是当前股票的报价,并且有仓位可用
        sell_condition_0 = quotation.result['code'][0] == code and int(
            stock_amount) <> 0

        # .1. 触发止损 (用实时行情胡最低价与止损价格比较)
        sell_condition_1 = float(quotation.result['low'][0]) <= stop_loss_price  \
                         and time.localtime()[3:6]>=(9,30,1)

        # .2. 卖出日,没触及止盈点,并且不是一字涨停 (最低价不等于涨停价),收盘价卖出(如果即时选股没有标的, 则根据k线情况保留到下个交易日)
        #     sell_day 为策略理论卖出日,如果因其他原因该卖没卖, 则以后会出现sell_day < 当前日期
        #     而且止盈点也没有出现, 应该自行卖出或由程序隔日卖出。所以条件设置 sell_day <= 当前日
        sell_condition_2 = sell_day <= time.strftime("%Y/%m/%d",time.localtime(time.time())) \
                         and time.localtime()[3:6]>=(14,59,0) and price_updated <> True \
                         and float(quotation.result['low'][0]) <> float(dfcf_quote['topprice'])

        # .3. 卖出日,非一字涨停,如果涨停价也不能触及止盈价,则已昨收盘价为基础,涨到 4% 后,最高点回落 1% 就卖出,不用等收盘
        sell_condition_3 = sell_day <= time.strftime("%Y/%m/%d",time.localtime(time.time())) \
                         and time.localtime()[3:6]>=(9,30,0) \
                         and price_updated <> True \
                         and float(dfcf_quote['topprice']) < stop_sell_price \
                         and float(quotation.result['low'][0]) <> float(dfcf_quote['topprice']) \
                         and float(quotation.result['high'][0]) >= float(quotation.result['pre_close'][0]) * 1.04 \
                         and float(quotation.result['price'][0]) < (float(quotation.result['high'][0])-float(quotation.result['pre_close'][0]) *0.0025*(10-(float(quotation.result['high'][0])-float(quotation.result['pre_close'][0]))/float(quotation.result['pre_close'][0])*100))
        #and float(quotation.result['price'][0]) < (float(quotation.result['high'][0])-float(quotation.result['pre_close'][0]) * 0.01)  \

        #符合条件则下单卖出
        if sell_condition_0 and (sell_condition_1 or sell_condition_2
                                 or sell_condition_3):
            # 如果停牌
            if float(quotation.result['open'][0]) == float(
                    quotation.result['amount'][0]) == 0:
                print "\n%s %s: Suspension\n" % (quotation.result['date'][0],
                                                 quotation.result['name'][0])
                while calendar.trade_time() and calendar.trade_day():
                    time.sleep(2)
            # 正常持股到期, 如果策略即时选股为空,并且盈利 7个点以上,红柱,距离最高价不低于1%, 则顺延到下一个交易日
            if sell_condition_2 == True and len(strategy.pickstock()) == 0 \
               and float(quotation.result['price'][0]) > float(quotation.result['open'][0]) \
               and float(quotation.result['price'][0]) >= (float(quotation.result['high'][0]) - float(quotation.result['pre_close'][0])*0.01)\
               and float(quotation.result['price'][0]) > stock_holding_price['Open'] * 1.07:
                print u"正常持股到期, 策略即时选股为空,且盈利超过7个点,则顺延到下一个交易日"
                while calendar.trade_time() and calendar.trade_day():
                    time.sleep(2)
                break
            quotation.show = 0
            sys.stdout.write("\r")
            sys.stdout.flush()
            log.info('Sell Begin...')
            Wtbh = trader.deal(code, dfcf_quote['name'],
                               str(float(dfcf_quote['bottomprice']) + 0.01), 1,
                               'S')
            if Wtbh is not None:
                log.info('Sell End...')
                #os.system("say order completed")
                #winsound.PlaySound('./wav/transaction completed.wav',winsound.SND_ASYNC)
                playsound(mac_say='transaction completed',
                          win_sound='./wav/transaction completed.wav',
                          frequency=450,
                          duration=150)
                print u"委托编号: [%s]\n" % Wtbh,

                #查询当日委托状态, 如果未成则等待
                while trader.getordersdata()[0]['Wtzt'] <> '已成':
                    sys.stdout.write("\r委托编号: [%s] 还未成交!" % Wtbh)
                    sys.stdout.flush()
                    time.sleep(5)
                sys.stdout.write("\r")
                sys.stdout.flush()
                log.info('Deal Done!')
                stock_amount = trader.getstocklist()[0]['Kysl']
            else:
                break
        #每天中午12:11刷新持仓, 同时也可让Login 的 180分钟 有效期重新开始计算
        if time.localtime()[3]==12 and \
           time.localtime()[4]==11 and \
           time.localtime()[5]>10 and \
           time.localtime()[5]<12:
            quotation.show = 0
            show_assets()
            quotation.show = 1
        time.sleep(1)
Пример #6
0
def monitor_buy(code, codename):
    print '=== Monitor Price for Buy: %s ===' % code
    quotation.stockcode = code

    while quotation.result is False:
        time.sleep(.5)

    dfcf_quote = trader.getquote(code)  #获取东方财富的报价:涨跌停价格不需要即时报价
    print u'跌停价:{0:s} | 涨停价:{1:s}'.format(dfcf_quote['bottomprice'],
                                          dfcf_quote['topprice'])

    quotation.show = 1
    while calendar.trade_time() and calendar.trade_day():
        buy_condition_0 = quotation.result['code'][0] == code
        buy_condition_1 = (float(quotation.result['price'][0]) - float(
            quotation.result['pre_close'][0])) * 100 / float(
                quotation.result['pre_close'][0]) > -9
        buy_condition_2 = time.localtime()[3:6] >= (
            9, 25, 30) and time.localtime()[3:6] <= (9, 50, 6)

        if buy_condition_0 and buy_condition_1 and buy_condition_2:
            if float(quotation.result['open'][0]) == float(
                    quotation.result['amount'][0]) == 0:
                print "\n%s %s: Suspension\n" % (quotation.result['date'][0],
                                                 codename)
                while calendar.trade_time() and calendar.trade_day():
                    time.sleep(2)
            quotation.show = 0
            print '\n'
            log.info("Begin Buy -->  %s %s" %
                     (codename, str(float(dfcf_quote['topprice']) - 0.01)))
            #Wtbh=trader.deal(code,codename,str(float(dfcf_quote['topprice'])-0.01),'B')
            '''
            Wtbh=''
            for fen_cang in xrange(2,0,-1):
                print '\n'
                log.info("Begin Buy -->  %s %s" % (codename,format(float(quotation.result['pre_close'])*(0.955+fen_cang/100.0), '.2f')))
                Wtbh+= " | " + trader.deal(code,codename,format(float(dfcf_quote['fivequote']['yesClosePrice'])*(0.955+fen_cang/100.0), '.2f'),fen_cang,'B') 
                if Wtbh is not None:
                    log.info('Buy Order Accomplished!')
                    playsound(mac_say='transaction completed',win_sound='./wav/transaction completed.wav',frequency=450, duration=150)            
                    #查询当日委托状态, 如果未成则等待
                    while trader.getordersdata()[0]['Wtzt'] <> '已成':
                        sys.stdout.write("\r委托编号:[%s] 还未成交!" % Wtbh)
                        sys.stdout.flush()
                        time.sleep(5)
                    log.info('Deal Done!')
                else:
                    return 'buy order failed!'
            return Wtbh
            '''
            Wtbh_01 = None
            Wtbh_01 = trader.deal(code, codename,
                                  str(float(dfcf_quote['topprice']) - 0.01), 2,
                                  'B')
            if Wtbh_01 is not None:
                log.info('Buy Order Accomplished!')
                playsound(mac_say='transaction completed',
                          win_sound='./wav/transaction completed.wav',
                          frequency=450,
                          duration=150)
                #查询当日委托状态, 如果未成则等待
                while trader.getordersdata()[0]['Wtzt'] <> '已成':
                    sys.stdout.write("\r委托编号:[%s] 还未成交!" % Wtbh_01)
                    sys.stdout.flush()
                    time.sleep(5)
                log.info('Deal Done!')
                #return Wtbh
                #按照涨停价-0.01挂单,如果成交价格为开盘价, 则还有10%的资金未利用

                while time.localtime()[3:6] < (9, 45):
                    time.sleep(1)
                Wtbh_02 = None
                if round(float(quotation.result['pre_close']) * 0.96,
                         2) >= float(dfcf_quote['bottomprice']):
                    log.info("Begin Buy -->  %s %s" %
                             (codename,
                              format(
                                  float(quotation.result['pre_close']) * 0.965,
                                  '.2f')))
                    Wtbh_02 = trader.deal(
                        code, codename,
                        format(
                            float(quotation.result['pre_close']) * 0.965,
                            '.2f'), 1, 'B')
                    log.info('Deal Done!')
                #--------------------------------------------------------------------------
                return Wtbh_01 + " | " + Wtbh_02 if Wtbh_02 is not None else Wtbh_01
            else:
                return 'buy order failed!'
        '''
        if quotation.result['code']==code \
           and float(quotation.result['realtimequote']['currentPrice'])>10.80 \
           and float(quotation.result['realtimequote']['zdf'].replace('%',''))>-9 \
           and time.localtime()[3:5]>=(9,29) and time.localtime()[3:5]<=(9,31):
            print "Begin Buy: " + codename
            #Wtbh=trader.deal(code,codename,quotation.result['fivequote']['sale5'],'B') #['topprice']
            #trader.deal("000619","海螺型材","13.4","B")
            winsound.PlaySound('./wav/transaction completed.wav',winsound.SND_ASYNC)
            return Wtbh
        '''
        time.sleep(1)