Example #1
0
def main():
    # Get currency pairs sorted by 24-hour volume
    polo = poloniex.Poloniex(timeout=10, coach=True)
    sorted_tickers = sorted(polo.returnTicker().items(),
                            key=lambda x: float(x[1]['baseVolume']),
                            reverse=True)
    currency_pairs = [(k, float(v['baseVolume'])) for k, v in sorted_tickers
                      if 'BTC_' in k or k == 'USDT_BTC']

    volume_texts = []
    for currency_pair, volume_24h in currency_pairs[0:DISPLAY_NUMS]:
        print("currency_pair={}".format(currency_pair))
        volume_texts.append(
            get_volumes(currency_pair, volume_24h, MINUTES, TICKS))

    body = textwrap.dedent(u"""
    Date  : {date}
    Ticks : {minutes} mins x {ticks}

    {volume_texts}
    """).format(
        date=datetime.now().strftime('%Y/%m/%d %H:%M'),
        minutes=MINUTES,
        ticks=TICKS,
        volume_texts='\n\n'.join(volume_texts),
    ).strip()

    print('----------')
    print(body)
    print('----------')

    email_client = EmailClient()
    # Send an email to myself
    email_client.send_test_email(u"Poloniex trade volumes", body)
Example #2
0
def process_update_record(load_config, update_record_name):
    logger = log_utils.create_logger('pubmed2018_update', load_config.log_files_directory())
    logger.info('Loading update record: ' + str(update_record_name))

    update_records_directory = get_update_records_directory(load_config)
    update_record = file_utils.load_file(update_records_directory, update_record_name)

    local_date = update_record['local_date']
    update_data = update_record['update_data']
    docs_with_new_citations = update_record['docs_with_new_citations']

    logger.info('Update record loaded')
    logger.info('Date: ' + str(local_date))
    logger.info('Update files: ')
    for update_file in update_data:
        logger.info(update_file)

    logger.info('Docs with new citations: ' + str(len(docs_with_new_citations)))

    all_prospects = send_prospective_citations_notifications(logger, docs_with_new_citations)

    # Send update notification
    logger.info('Sending update status mail...')
    EmailClient.send_update_notifications(local_date, update_data, all_prospects)

    logger.info('Done')
Example #3
0
    def send_mail(self, subject, url, params):
        mail_rece = params.get('buyer_email')
        mail_type = params.get('email_type')

        # user_type = 'mws_user_ship'
        # if mail_type == 'AmzReceipt':
        #     user_type = 'mws_user_receipt'
        # elif mail_type == 'AmzInvite':
        #     user_type = 'mws_user_invite'
        # log.info('UserType: %s', user_type)
        mail_user_info = random.choice(
            email_config.mail_user_info.get('mws_users'))
        mail_from = mail_user_info.split(',')[0]
        mail_user = email_config.mail_user_info.get('aws_user').split(',')[0]
        mail_pass = email_config.mail_user_info.get('aws_user').split(',')[1]
        mail_host = email_config.mail_host_info.get('aws_host')

        with open('Template' + url, 'r') as f:
            if mail_type == 'AmzShip':
                m_body = f.read().format(
                    buyer_name=params.get('buyer_name'),
                    carrier_name=params.get('carrier_name'),
                    tracking_number=params.get('tracking_number'),
                    arrival_date=params.get('arrival_date'))
            else:
                m_body = f.read().format(buyer_name=params.get('buyer_name'))

        emc = EmailClient(mail_host)
        msg = emc.make_msg(mail_from, mail_rece, subject, m_body, 'html')
        emc.send(mail_user, mail_pass, mail_from, mail_rece, msg)
Example #4
0
class MyListener(tweepy.StreamListener):
    def __init__(self):
        super(MyListener, self).__init__()
        self.email_client = EmailClient()

    def on_status(self, status):
        if str(status.user.id) in FOLLOW_IDS.keys():
            print('------------------------------')
            print('status={}'.format(status))
            logger.debug('CC official tweeted. user.id={}'.format(
                status.user.id))
            symbol = FOLLOW_IDS[str(status.user.id)]
            is_retweet = hasattr(status, 'retweeted_status')
            is_reply = (status.in_reply_to_user_id is not None)

            subject = u'[CC] Official Tweet Notification ({})'.format(symbol)
            body = textwrap.dedent(u"""
            Date     : {date}
            Name     : {name} (@{screen_name})
            Symbol   : {symbol}
            Followers count : {followers_count}
            Tweet count : {tweet_count}
            Retweet? : {is_retweet}
            Reply?   : {is_reply}
            ==========
            {text}
            ==========
            URL      : https://bittrex.com/Market/Index?MarketName=BTC-{symbol}
            """).format(
                date=datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
                name=status.user.name,
                screen_name=status.user.screen_name,
                symbol=symbol,
                followers_count='{:,}'.format(status.user.followers_count),
                tweet_count='{:,}'.format(status.user.statuses_count),
                is_retweet=is_retweet,
                is_reply=is_reply,
                text=status.text,
            ).strip()
            self.email_client.send_test_email(subject, body)

    def on_error(self, status_code):
        print('Got an error with status code: {}'.format(status_code))
        logger.error('Got an error with status code: {}'.format(status_code))
        if status_code == 420:
            return False

    # See: https://stackoverflow.com/questions/14177327/tweepy-stops-after-a-few-hours
    def on_disconnect(self, notice):
        print('Got a disconnect signal with notice: {}'.format(notice))
        logger.error('Got a disconnect signal with notice: {}'.format(notice))
        return False
Example #5
0
def lambda_handler(event, context):
    try:
        args = parse_args(event)
        if not args['notification_type']:
            raise Exception('notification_type parameter is not passed')

        # Send notification
        if args['notification_type'] == 'api':
            # Check required params
            if not all([
                    args['influx_host'], args['smtp_user'], args['test'],
                    args['test_type'], args['notification_type'],
                    args['smtp_password'], args['user_list']
            ]):
                raise Exception('Some required parameters not passed')

            email = ApiEmailNotification(args).email_notification()
        elif args['notification_type'] == 'ui':
            if not all([args['test_id'], args['report_id']]):
                raise Exception(
                    'test_id and report_id are required for UI reports')

            email = UIEmailNotification(args).ui_email_notification()
        else:
            raise Exception(
                'Incorrect value for notification_type: {}. Must be api or ui'.
                format(args['notification_type']))

        EmailClient(args).send_email(email)

    except Exception as e:
        from traceback import format_exc
        print(format_exc())
        return {'statusCode': 500, 'body': json.dumps(str(e))}
    return {'statusCode': 200, 'body': json.dumps('Email has been sent')}
Example #6
0
def main():
    # Get currency pairs sorted by 24-hour volume
    polo = poloniex.Poloniex(timeout=10, coach=True)
    sorted_tickers = sorted(polo.returnTicker().items(),
                            key=lambda x: float(x[1]['baseVolume']),
                            reverse=True)
    currency_pairs = [k for k, v in sorted_tickers if 'BTC_' in k]

    chart_texts = []
    for currency_pair in currency_pairs[0:DISPLAY_NUMS]:
        print("currency_pair={}".format(currency_pair))
        data = get_chart_data(currency_pair, MINUTES_PER_TICK, TICKS)
        chart_texts.append(
            textwrap.dedent(u"""
        {currency_pair}
        Latest price      : {latest_price} ({price_rate} from highest)
        Latest timestamp  : {latest_timestamp}
        Highest price     : {highest_price}
        Highest timestamp : {highest_timestamp} ({timestamp_diff} before)
        Price up-downs    : {price_up_downs} (past 3 ticks)
        Price deviations  : {deviations_by_sigma} (σ)
        1 sigma price     : {sigma_percent}
        Latest volumes    : {latest_volumes} (past 3 ticks, {latest_volumes_rate} of total)
        Volume up-downs   : {volume_up_downs} (past 3 ticks)
        """).strip().format(**data))

    body = textwrap.dedent(u"""
    Date  : {date}
    Ticks : {minutes} mins x {ticks} ({hours} hours)

    {chart_texts}
    """).format(
        date=datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
        minutes=MINUTES_PER_TICK,
        ticks=TICKS,
        hours=TARGET_HOURS,
        chart_texts='\n\n'.join(chart_texts),
    ).strip()

    # print('----------')
    # print(body)
    # print('----------')

    email_client = EmailClient()
    # Send an email to myself
    email_client.send_test_email(u"Poloniex high break (and sigma)", body)
Example #7
0
def send_notification():
    try:
        email_client = EmailClient()
        email_client.send_notification(notification_email_address)
        email_client.close()
    except:
        print("Could not send success notification")
    def test_empty_email(self):
        # Empty Email message content
        # Email subject
        subject = ''
        # Email body
        body = ''
        # Email signature
        signature = ''

        # sending Email
        email_client = EmailClient(self.__server, self.__port_number,
                                   self.__username, self.__password)
        email_client.set_subject(subject)
        email_client.set_body(body)
        email_client.set_signature(signature)

        # testing
        sent = False
        self.assertEqual(email_client.send(self.__recipient), sent)
Example #9
0
def send_alive_notification(tries, failed, exceptions, successes, alive_since,
                            time_alive):
    try:
        email_client = EmailClient()
        email_client.send_alive_notification(notification_email_address, tries,
                                             failed, exceptions, successes,
                                             alive_since, time_alive)
        email_client.close()
    except:
        print("Could not send alive notification")
    def test_email_client_send_misc(self):
        # Email message content
        # Email subject
        subject = ''

        # sending Email
        email_client = EmailClient(self.__server, self.__port_number,
                                   self.__username, self.__password)
        email_client.set_subject(subject)
        # add Email attachment
        email_client.add_attachment('test.txt')

        # testing
        sent = False
        self.assertEqual(email_client.send(self.__recipient), sent)
Example #11
0
def process_update_files(is_auto_update, load_config, new_update_files):
    now = datetime.datetime.now()
    local_date = now.strftime("%m-%d-%Y")

    logger = log_utils.create_logger('pubmed2018_update', load_config.log_files_directory())
    logger.info(str(len(new_update_files)) +  ' update files to process')

    if len(new_update_files) > 0:
        logger.info(str(new_update_files))

        # Send update start notification
        if is_auto_update:
            EmailClient.send_update_start_notification(local_date, new_update_files)

        # Process files not processed yet
        # Update processed files list
        pubmed_updater = PubmedUpdater(logger, new_update_files)
        pubmed_updater.run()

        # Send prospective cites notifications
        docs_with_new_citations = pubmed_updater.get_docs_with_new_citations()

        # Get the update summary
        logger.info('Generating update summary...')
        update_data = generate_update_summary(pubmed_updater, new_update_files)

        logger.info('Saving update summary...')
        save_update_record_for_date(load_config, local_date, update_data, docs_with_new_citations)
        
        all_prospects = send_prospective_citations_notifications(logger, docs_with_new_citations)

        # # Send update notification
        logger.info('Sending update status mail...')
        EmailClient.send_update_notifications(local_date, update_data, all_prospects)

        # Save existing pmids to file
        logger.info('Saving new pmids...')
        pubmed_updater.save_new_pmids()

        # Update processed files list
        update_processed_update_files(new_update_files)
    else:
        if is_auto_update:
            # Send update notification
            logger.info('Sending update status mail...')
            EmailClient.send_update_notifications(local_date, [], [])
Example #12
0
 def __init__(self):
     super(MyListener, self).__init__()
     self.email_client = EmailClient()
Example #13
0
 def tearDown(self):
     LabelPrinter.reset()
     EmailClient.reset()
     Subscriptions.reset()
     DiscountCodes.reset()
     patch.stopall()
    def test_email_client_reset(self):
        # Email message content
        # Email subject
        subject = 'Testing Reset Method'
        # Email body
        body = 'Email body has not been reset. Please check its functionality.'
        # Email signature
        signature = '\n\nKind regards,\[email protected]'

        # initialising Email
        email_client = EmailClient(self.__server, self.__port_number,
                                   self.__username, self.__password)
        email_client.set_subject(subject)
        email_client.set_body(body)
        email_client.set_signature(signature)
        email_client.add_attachment('test.txt')

        # resetting email content
        email_client.reset_email()

        # adding Email body
        new_body = 'Email body has been reset.'
        email_client.set_body(new_body)

        # testing
        sent = True
        self.assertEqual(email_client.send(self.__recipient), sent)
Example #15
0
def main():
    now = datetime.now()

    # Symbols
    db_symbols = MongoClient().cctweet['symbols']
    symbols = list(
        db_symbols.find({'time': {
            '$exists': False
        }}, {'_id': False},
                        sort=[('count', DESCENDING)]))
    for symbol in symbols:
        # TODO: Need fix? INTERVAL_MINUTES * 1.5
        prev = db_symbols.find_one(
            {
                'key': symbol['key'],
                'time': {
                    '$gte': now - timedelta(minutes=INTERVAL_MINUTES * 1.5)
                }
            },
            sort=[('time', DESCENDING)])
        if prev is not None:
            symbol.update({
                'diff':
                float(symbol['count'] - prev['count']) / float(prev['count'])
            })
        else:
            symbol.update({'diff': float('inf')})
    # Hashtags
    db_hashtags = MongoClient().cctweet['hashtags']
    hashtags = list(
        db_hashtags.find({'time': {
            '$exists': False
        }}, {'_id': False},
                         sort=[('count', DESCENDING)]))
    for hashtag in hashtags:
        # TODO: Need fix? INTERVAL_MINUTES * 1.5
        prev = db_hashtags.find_one(
            {
                'key': hashtag['key'],
                'time': {
                    '$gte': now - timedelta(minutes=INTERVAL_MINUTES * 1.5)
                }
            },
            sort=[('time', DESCENDING)])
        if prev is not None:
            hashtag.update({
                'diff':
                float(hashtag['count'] - prev['count']) / float(prev['count'])
            })
        else:
            hashtag.update({'diff': float('inf')})

    # Update time
    db_symbols.update({'time': {
        '$exists': False
    }}, {'$set': {
        'time': now
    }},
                      multi=True)
    db_hashtags.update({'time': {
        '$exists': False
    }}, {'$set': {
        'time': now
    }},
                       multi=True)

    # Cleanup
    db_symbols.remove({'time': {'$lt': now - timedelta(hours=24)}})
    db_hashtags.remove({'time': {'$lt': now - timedelta(hours=24)}})

    body = textwrap.dedent(u"""
    Date     : {date}

    $ Top Symbols
    =============
    {top_symbols}

    # Top Hashtags
    ==============
    {top_hashtags}
    """).format(
        date=now.strftime('%Y/%m/%d %H:%M'),
        top_symbols='\n'.join([
            u'{}: {} ({})'.format(d['key'], d['count'],
                                  '{:+.0%}'.format(d['diff']))
            for d in symbols[0:SYMBOL_DISPLAY_SIZE]
        ]),
        top_hashtags='\n'.join([
            u'{}: {} ({})'.format(d['key'], d['count'],
                                  '{:+.0%}'.format(d['diff']))
            for d in hashtags[0:HASHTAG_DISPLAY_SIZE]
        ]),
    ).strip()

    email_client = EmailClient()
    email_client.send_test_email(u'CC Tweet Summary', body)
Example #16
0
from email_client import EmailClient

def send_spam(to):
      text = ("The best washing machines in town!\n\n"
              "Only now you can buy a new washing machine "
              "for the cheapest price ever. For more info "
              "go to www.best-washing-machines.com")
    frm = "*****@*****.**"
    subject = "Hi"

    client = EmailClient('smtp.server.com')
    client.send(from, to, subject, text)
Example #17
0
def main():
    # Get all markets
    res = requests.get('https://api.coinmarketcap.com/v1/ticker/')
    markets = res.json()
    print('Number of markets={}'.format(len(markets)))

    # Sort by 24h_volume_usd (Note: some 24h_volume_usd are None, so 'or 0')
    markets.sort(key=lambda x: float(x['24h_volume_usd'] or 0), reverse=True)
    # Pop BTC and USDT (Tether)
    markets = [x for x in markets if x['symbol'] not in ('BTC', 'USDT')]
    # pprint(markets)

    # Get Bitcoin market
    res = requests.get(
        'https://api.coinmarketcap.com/v1/ticker/{}/'.format('bitcoin'))
    bitcoin = res.json()[0]

    df = pd.DataFrame(markets)
    df['price_usd'] = df['price_usd'].astype(float)
    df['price_btc'] = df['price_btc'].astype(float)
    df['24h_volume_usd'] = df['24h_volume_usd'].astype(float)
    df['market_cap_usd'] = df['market_cap_usd'].astype(float)
    df['available_supply'] = df['available_supply'].astype(float)
    df['total_supply'] = df['total_supply'].astype(float)
    df['percent_change_1h'] = df['percent_change_1h'].astype(float)
    df['percent_change_24h'] = df['percent_change_24h'].astype(float)
    df['percent_change_7d'] = df['percent_change_7d'].astype(float)
    df['last_updated'] = df['last_updated'].apply(
        lambda x: datetime.fromtimestamp(float(x)))
    print(df[0:10])

    df_top10 = df[0:10]
    df_top20 = df[0:20]
    df_top30 = df[0:30]
    df_top50 = df[0:50]
    df_top51_100 = df[50:100]
    df_top100 = df[0:100]
    body = textwrap.dedent(u"""
    Bitcoin
    =======
    (1h)  price change : {bitcoin_1h_change:+.1f}%
    (24h) price change : {bitcoin_24h_change:+.1f}%
    (7d)  price change : {bitcoin_7d_change:+.1f}%
    
    Top 10 markets
    ==============
    (1h)  price up/down : {top10_1h_up} / {top10_1h_down}
    (1h)  price mean    : {top10_1h_mean:+.1f}%
    (24h) price up/down : {top10_24h_up} / {top10_24h_down}
    (24h) price mean    : {top10_24h_mean:+.1f}%
    (7d)  price up/down : {top10_7d_up} / {top10_7d_down}
    (7d)  price mean    : {top10_7d_mean:+.1f}%

    Top 20 markets
    ==============
    (1h)  price up/down : {top20_1h_up} / {top20_1h_down}
    (1h)  price mean    : {top20_1h_mean:+.1f}%
    (24h) price up/down : {top20_24h_up} / {top20_24h_down}
    (24h) price mean    : {top20_24h_mean:+.1f}%
    (7d)  price up/down : {top20_7d_up} / {top20_7d_down}
    (7d)  price mean    : {top20_7d_mean:+.1f}%

    Top 30 markets
    ==============
    (1h)  price up/down : {top30_1h_up} / {top30_1h_down}
    (1h)  price mean    : {top30_1h_mean:+.1f}%
    (24h) price up/down : {top30_24h_up} / {top30_24h_down}
    (24h) price mean    : {top30_24h_mean:+.1f}%
    (7d)  price up/down : {top30_7d_up} / {top30_7d_down}
    (7d)  price mean    : {top30_7d_mean:+.1f}%

    Top 50 markets
    ==============
    (1h)  price up/down : {top50_1h_up} / {top50_1h_down}
    (1h)  price mean    : {top50_1h_mean:+.1f}%
    (24h) price up/down : {top50_24h_up} / {top50_24h_down}
    (24h) price mean    : {top50_24h_mean:+.1f}%
    (7d)  price up/down : {top50_7d_up} / {top50_7d_down}
    (7d)  price mean    : {top50_7d_mean:+.1f}%

    Top 51-100 markets
    ==============
    (1h)  price up/down : {top51_100_1h_up} / {top51_100_1h_down}
    (1h)  price mean    : {top51_100_1h_mean:+.1f}%
    (24h) price up/down : {top51_100_24h_up} / {top51_100_24h_down}
    (24h) price mean    : {top51_100_24h_mean:+.1f}%
    (7d)  price up/down : {top51_100_7d_up} / {top51_100_7d_down}
    (7d)  price mean    : {top51_100_7d_mean:+.1f}%

    Top 100 markets
    ===============
    (1h)  price up/down : {top100_1h_up} / {top100_1h_down}
    (1h)  price mean    : {top100_1h_mean:+.1f}%
    (24h) price up/down : {top100_24h_up} / {top100_24h_down}
    (24h) price mean    : {top100_24h_mean:+.1f}%
    (7d)  price up/down : {top100_7d_up} / {top100_7d_down}
    (7d)  price mean    : {top100_7d_mean:+.1f}%
    """).format(
        bitcoin_1h_change=float(bitcoin['percent_change_1h']),
        bitcoin_24h_change=float(bitcoin['percent_change_24h']),
        bitcoin_7d_change=float(bitcoin['percent_change_7d']),
        top10_1h_up=len(df_top10[df_top10['percent_change_1h'] > 0]),
        top10_1h_down=len(df_top10[df_top10['percent_change_1h'] <= 0]),
        top10_1h_mean=df_top10.mean()['percent_change_1h'],
        top10_24h_up=len(df_top10[df_top10['percent_change_24h'] > 0]),
        top10_24h_down=len(df_top10[df_top10['percent_change_24h'] <= 0]),
        top10_24h_mean=df_top10.mean()['percent_change_24h'],
        top10_7d_up=len(df_top10[df_top10['percent_change_7d'] > 0]),
        top10_7d_down=len(df_top10[df_top10['percent_change_7d'] <= 0]),
        top10_7d_mean=df_top10.mean()['percent_change_7d'],
        top20_1h_up=len(df_top20[df_top20['percent_change_1h'] > 0]),
        top20_1h_down=len(df_top20[df_top20['percent_change_1h'] <= 0]),
        top20_1h_mean=df_top20.mean()['percent_change_1h'],
        top20_24h_up=len(df_top20[df_top20['percent_change_24h'] > 0]),
        top20_24h_down=len(df_top20[df_top20['percent_change_24h'] <= 0]),
        top20_24h_mean=df_top20.mean()['percent_change_24h'],
        top20_7d_up=len(df_top20[df_top20['percent_change_7d'] > 0]),
        top20_7d_down=len(df_top20[df_top20['percent_change_7d'] <= 0]),
        top20_7d_mean=df_top20.mean()['percent_change_7d'],
        top30_1h_up=len(df_top30[df_top30['percent_change_1h'] > 0]),
        top30_1h_down=len(df_top30[df_top30['percent_change_1h'] <= 0]),
        top30_1h_mean=df_top30.mean()['percent_change_1h'],
        top30_24h_up=len(df_top30[df_top30['percent_change_24h'] > 0]),
        top30_24h_down=len(df_top30[df_top30['percent_change_24h'] <= 0]),
        top30_24h_mean=df_top30.mean()['percent_change_24h'],
        top30_7d_up=len(df_top30[df_top30['percent_change_7d'] > 0]),
        top30_7d_down=len(df_top30[df_top30['percent_change_7d'] <= 0]),
        top30_7d_mean=df_top30.mean()['percent_change_7d'],
        top50_1h_up=len(df_top50[df_top50['percent_change_1h'] > 0]),
        top50_1h_down=len(df_top50[df_top50['percent_change_1h'] <= 0]),
        top50_1h_mean=df_top50.mean()['percent_change_1h'],
        top50_24h_up=len(df_top50[df_top50['percent_change_24h'] > 0]),
        top50_24h_down=len(df_top50[df_top50['percent_change_24h'] <= 0]),
        top50_24h_mean=df_top50.mean()['percent_change_24h'],
        top50_7d_up=len(df_top50[df_top50['percent_change_7d'] > 0]),
        top50_7d_down=len(df_top50[df_top50['percent_change_7d'] <= 0]),
        top50_7d_mean=df_top50.mean()['percent_change_7d'],
        top51_100_1h_up=len(
            df_top51_100[df_top51_100['percent_change_1h'] > 0]),
        top51_100_1h_down=len(
            df_top51_100[df_top51_100['percent_change_1h'] <= 0]),
        top51_100_1h_mean=df_top51_100.mean()['percent_change_1h'],
        top51_100_24h_up=len(
            df_top51_100[df_top51_100['percent_change_24h'] > 0]),
        top51_100_24h_down=len(
            df_top51_100[df_top51_100['percent_change_24h'] <= 0]),
        top51_100_24h_mean=df_top51_100.mean()['percent_change_24h'],
        top51_100_7d_up=len(
            df_top51_100[df_top51_100['percent_change_7d'] > 0]),
        top51_100_7d_down=len(
            df_top51_100[df_top51_100['percent_change_7d'] <= 0]),
        top51_100_7d_mean=df_top51_100.mean()['percent_change_7d'],
        top100_1h_up=len(df_top100[df_top100['percent_change_1h'] > 0]),
        top100_1h_down=len(df_top100[df_top100['percent_change_1h'] <= 0]),
        top100_1h_mean=df_top100.mean()['percent_change_1h'],
        top100_24h_up=len(df_top100[df_top100['percent_change_24h'] > 0]),
        top100_24h_down=len(df_top100[df_top100['percent_change_24h'] <= 0]),
        top100_24h_mean=df_top100.mean()['percent_change_24h'],
        top100_7d_up=len(df_top100[df_top100['percent_change_7d'] > 0]),
        top100_7d_down=len(df_top100[df_top100['percent_change_7d'] <= 0]),
        top100_7d_mean=df_top100.mean()['percent_change_7d'],
    ).strip()

    email_client = EmailClient()
    # Send an email to myself
    email_client.send_test_email(u'[CC] Entire Market Mood', body)
Example #18
0
from sel import Selenium
from cloudinary_management import Cloudinary
# from whatsapp import send_message
import os
from pathlib import Path

parent_username = os.getenv("parent_username")
parent_password = os.getenv("parent_password")
email_username = os.getenv("email_username")
email_password = os.getenv("email_password")
to_whatsapp_numbers = os.getenv("to_whatsapp_numbers")
to_email = os.getenv("to_email")

sel = Selenium()
cloud = Cloudinary()
mail = EmailClient(username=email_username,
                   password=email_password,
                   recipients=to_email)

if __name__ == '__main__':
    sel.launch_chrome()
    sel.go_to_decleration_page()
    sel.login(username=parent_username, password=parent_password)
    sel.sign_health_decleration()
    screenshot = sel.save_screenshot()
    file = Path(__file__).parent / screenshot
    mail.send_mail_with_file(filename=file)
    message_url = cloud.upload_files(file=screenshot)
    # send_message(message=screenshot, message_url=message_url, to_whatsapp_numbers=to_whatsapp_numbers)
    sel.quit()
    def test_empty_subject_mails(self):
        """
        This function tests that mail is not sent when attachment is present but no subject is added
        """
        # initialize the email client
        email_client = EmailClient(self.server, self.server_port, self.mail_id,
                                   self.password)

        # set subject of email to empty string
        email_client.set_subject('')

        # set email contents to test strings and files
        email_client.set_body(self.test_body)
        email_client.set_signature(self.test_signature)
        email_client.add_attachment(self.test_attachment)

        # verify that the email is sent
        self.assertFalse(email_client.send(self.recipient))
    def test_valid_mails(self):
        """
        This function tests that the mail is not sent when email contents are empty
        """
        # initialize the email client
        email_client = EmailClient(self.server, self.server_port, self.mail_id,
                                   self.password)

        # set email contents to test strings and files
        email_client.set_subject(self.test_subject)
        email_client.set_body(self.test_body)
        email_client.set_signature(self.test_signature)
        email_client.add_attachment(self.test_attachment)

        # verify that the email is sent
        self.assertTrue(email_client.send(self.recipient))
    def test_empty_mails(self):
        """
        This function tests that the mail is sent successfully when all the mail contents are proper
        """
        # initialize the email client
        email_client = EmailClient(self.server, self.server_port, self.mail_id,
                                   self.password)

        # set email contents to empty string
        email_client.set_subject('')
        email_client.set_body('')
        email_client.set_signature('')
        email_client.add_attachment('')

        # verify that the email is not sent
        self.assertFalse(email_client.send(self.recipient))
Example #22
0
def main():
    now = datetime.now()

    # Get markets
    exchange = ccxt.bittrex()
    markets = exchange.fetch_tickers()
    print('Number of markets={}'.format(len(markets)))
    # Altcoins
    altcoins = [
        dict(v, symbol=k.split('/')[0]) for k, v in markets.items()
        if '/BTC' in k
    ]
    # Sort by baseVolume (Note: baseVolume might be None, so 'or 0')
    altcoins.sort(key=lambda x: float(x['quoteVolume'] or 0), reverse=True)
    print('Number of altcoins={}'.format(len(altcoins)))
    print([x['symbol'] for x in altcoins])

    # Get altcoin data from MongoDB
    collection = MongoClient().bittrex['tickers']
    chart_texts = []
    for i, symbol in enumerate(
        [x['symbol'] for x in altcoins[:DISPLAY_NUMBER_OF_ALTCOINS]]):
        print('==========')
        print(symbol)
        tickers = list(
            collection.find(
                {
                    'symbol': symbol,
                    'timestamp': {
                        '$gte': now - timedelta(minutes=TARGET_MINUTES)
                    }
                },
                {
                    '_id': False
                },
            ).sort('timestamp', ASCENDING))
        # pprint(tickers)

        chart_dict = tickers_to_chart_dict(tickers)

        chart_text = textwrap.dedent(u"""
            {i}. {symbol}
            -----------------
            Latest price     : {latest_price:.8f} ({price_diff_rate:+.1%} from highest)
            Highest price    : {highest_price:.8f} ({highest_timestamp_diff} before)
            Price up-downs   : {price_up_downs}
            Price deviations : {price_diff_by_sigma} (σ)
            1 sigma price    : {sigma_percent:.1%}
        """).format(
            i=i + 1,
            symbol=symbol,
            latest_price=chart_dict['latest_price'],
            highest_price=chart_dict['highest_price'],
            highest_timestamp=chart_dict['highest_timestamp'].strftime(
                '%m/%d %H:%M'),
            price_up_downs=', '.join(
                ['{:+.1%}'.format(v) for v in chart_dict['price_up_downs']]),
            highest_timestamp_diff=chart_dict['highest_timestamp_diff'],
            price_diff_rate=(chart_dict['latest_price'] -
                             chart_dict['highest_price']) /
            chart_dict['highest_price'],
            price_diff_by_sigma=', '.join([
                '{:.2f}'.format(v) for v in chart_dict['price_diff_by_sigma']
            ]),
            sigma_percent=chart_dict['sigma_percent'],
        ).strip()
        print('----------')
        print(chart_text)
        chart_texts.append(chart_text)

    body = textwrap.dedent(u"""
    Date  : {date}
    Ticks : {minutes} mins x {ticks:,.0f} ({hours:,.0f} hours)

    {chart_texts}
    """).format(
        date=now.strftime('%Y/%m/%d %H:%M:%S'),
        minutes=MINUTES_PER_TICK,
        ticks=TARGET_MINUTES / MINUTES_PER_TICK,
        hours=TARGET_MINUTES / 60,
        chart_texts='\n\n'.join(chart_texts),
    ).strip()
    print('==========')
    print(body)

    email_client = EmailClient()
    # Send an email to myself
    email_client.send_test_email(u'[CC] Bittrex Tickers', body)
    def test_email_client_send(self):
        # Email message content
        # Email subject
        subject = 'Testing'
        # Email body
        body = 'Hi,\n\nI am Kevin. How are you?'
        # Email signature
        signature = '\n\nKind regards,\n{}'.format(self.__username)

        # sending Email
        email_client = EmailClient(self.__server, self.__port_number,
                                   self.__username, self.__password)
        email_client.set_subject(subject)
        email_client.set_body(body)
        email_client.set_signature(signature)
        email_client.add_attachment('test.txt')

        # testing
        sent = True
        self.assertEqual(email_client.send(self.__recipient), sent)
    def test_invalid_attachment_path_mails(self):
        """
        This functions tests that mail is not sent when attachment path is invalid
        """
        # initialize the email client
        email_client = EmailClient(self.server, self.server_port, self.mail_id,
                                   self.password)

        # set email contents to test strings and files
        email_client.set_subject(self.test_subject)
        email_client.set_body(self.test_body)
        email_client.set_signature(self.test_signature)
        email_client.add_attachment('xyz.txt')

        # verify that the email is sent
        self.assertFalse(email_client.send(self.recipient))
Example #25
0
 def tearDown(self):
     LabelPrinter.reset()
     EmailClient.reset()
     Subscriptions.reset()
Example #26
0
def main():
    now = datetime.now()

    # Get all markets
    res = requests.get('https://api.coinmarketcap.com/v1/ticker/')
    markets = res.json()
    print('Number of markets={}'.format(len(markets)))
    # Pop base currency and USDT (Tether)
    symbols = ['{}/{}'.format(x['symbol'], BASE_CURRENCY) for x in markets if x['symbol'] not in (BASE_CURRENCY, 'USDT')]
    print(symbols)
    # TODO: ZRX
    symbols.append('ZRX/{}'.format(BASE_CURRENCY))

    symbol_texts = []
    for symbol in symbols[:DISPLAY_NUMBER_OF_ALTCOINS]:
        ex_count = 0
        max_bid = 0
        max_bid_ex_name = ''
        max_bid_ex_url = ''
        max_bid_volume = 0
        min_ask = float('inf')
        min_ask_ex_name = ''
        min_ask_ex_url = ''
        min_ask_volume = 0
        for ex, ex_url in EXCHANGES:
            try:
                ex_ticker = ex.fetch_ticker(symbol)
            # TODO: Also catch urllib.error.HTTPError?
            except ccxt.errors.RequestTimeout:
                continue
            except TypeError:
                # Looks not to deal in this exchange
                continue
            except Exception as e:
                logger.warning(e)
                continue
            ex_count += 1
            ex_ask = ex_ticker.get('ask') or 0
            ex_bid = ex_ticker.get('bid') or 0
            ex_volume = ex_ticker.get('quoteVolume') or 0  # Volume
            # print('-' * 30)
            # print('{}'.format(ex.name))
            # print('Ask: {:.8f}'.format(ex_ask))
            # print('Bid: {:.8f}'.format(ex_bid))
            # print('Volume: {:.1f}'.format(ex_volume))
            if MIN_VOLUME < ex_volume:
                # Price to sell
                if max_bid < ex_bid:
                    max_bid = ex_bid
                    max_bid_ex_name = ex.name
                    max_bid_ex_url = ex_url
                    max_bid_volume = ex_volume
                # Price to buy
                if ex_ask < min_ask:
                    min_ask = ex_ask
                    min_ask_ex_name = ex.name
                    min_ask_ex_url = ex_url
                    min_ask_volume = ex_volume

        profit = max_bid - min_ask
        profit_rate = (profit / min_ask) if min_ask != 0 else 0  # TODO: else float('inf') ?
        if profit_rate >= PROFIT_RATE_THRESHOLD:
            symbol_text = textwrap.dedent(u"""
            {symbol} ({ex_count})
            --------------------
            Sell at : {max_bid_ex_name:10} {max_bid_ex_url}
            Buy  at : {min_ask_ex_name:10} {min_ask_ex_url}
            Bid     : {max_bid:.8f} ({max_bid_volume:.1f} {base_currency}/day)
            Ask     : {min_ask:.8f} ({min_ask_volume:.1f} {base_currency}/day)
            Profit  : {profit:.8f} ({profit_rate:+.1%})
            """).format(
                symbol=symbol,
                base_currency=BASE_CURRENCY.lower(),
                ex_count=ex_count,
                max_bid_ex_name=max_bid_ex_name,
                max_bid_ex_url=max_bid_ex_url.format(*symbol.split('/')),
                max_bid=max_bid,
                max_bid_volume=max_bid_volume,
                min_ask_ex_name=min_ask_ex_name,
                min_ask_ex_url=min_ask_ex_url.format(*symbol.split('/')),
                min_ask=min_ask,
                min_ask_volume=min_ask_volume,
                profit=profit,
                profit_rate=profit_rate,
            ).strip()
            # print('=' * 40)
            # print(symbol_text)
            symbol_texts.append((symbol_text, profit_rate))

    # Sort by profit rate
    symbol_texts = [x[0] for x in sorted(symbol_texts, key=lambda x: x[1], reverse=True)]

    body = textwrap.dedent(u"""
    Date  : {date}
    Top {number_of_altcoins} Currencies from {number_of_exchanges} Exchanges
    Volume Threshold : {min_volume} {base_currency}/day

    {symbol_text}
    """).format(
        date=now.strftime('%Y/%m/%d %H:%M:%S'),
        number_of_altcoins=DISPLAY_NUMBER_OF_ALTCOINS,
        number_of_exchanges=len(EXCHANGES),
        min_volume=MIN_VOLUME,
        base_currency=BASE_CURRENCY.lower(),
        symbol_text='\n\n'.join(symbol_texts),
    ).strip()
    print(body)

    email_client = EmailClient()
    # Send an email to myself
    email_client.send_test_email(u'[CC] Check Price Difference (by {})'.format(BASE_CURRENCY), body)
    def test_reset_functionality(self):
        """
        This functions tests that mail contents are reset after calling reset()
        """
        # initialize the email client
        email_client = EmailClient(self.server, self.server_port, self.mail_id,
                                   self.password)

        # set email contents to test strings and files
        email_client.set_subject(self.test_subject)
        email_client.set_body(self.test_body)
        email_client.set_signature(self.test_signature)
        email_client.add_attachment(self.test_attachment)

        # before reset will be true as email will be sent
        before_reset = email_client.send(self.recipient)

        # reset the email contents
        email_client.reset_email()

        # after reset will be false as email won't be sent as the contents removed
        after_reset = email_client.send(self.recipient)

        # compare that both are not equal
        self.assertNotEqual(before_reset, after_reset)