Exemple #1
0
    def _performance(bot: Bot, update: Update) -> None:
        """
        Handler for /performance.
        Shows a performance statistic from finished trades
        :param bot: telegram bot
        :param update: message update
        :return: None
        """
        from main import get_instance
        if not get_instance().is_alive():
            TelegramHandler.send_msg('`trader is not running`', bot=bot)
            return

        pair_rates = Session.query(Trade.pair, func.sum(Trade.close_profit).label('profit_sum')) \
            .filter(Trade.is_open.is_(False)) \
            .group_by(Trade.pair) \
            .order_by('profit_sum DESC') \
            .all()

        stats = '\n'.join(
            '{}. <code>{}\t{}%</code>'.format(i + 1, pair, round(rate, 2))
            for i, (pair, rate) in enumerate(pair_rates))

        message = '<b>Performance:</b>\n{}\n'.format(stats)
        logger.debug(message)
        TelegramHandler.send_msg(message, parse_mode=ParseMode.HTML)
Exemple #2
0
    def _profit(bot: Bot, update: Update) -> None:
        """
        Handler for /profit.
        Returns a cumulative profit statistics.
        :param bot: telegram bot
        :param update: message update
        :return: None
        """
        trades = Trade.query.order_by(Trade.id).all()

        profit_amounts = []
        profits = []
        durations = []
        for trade in trades:
            if trade.close_date:
                durations.append(
                    (trade.close_date - trade.open_date).total_seconds())
            if trade.close_profit:
                profit = trade.close_profit
            else:
                # Get current rate
                current_rate = api_wrapper.get_ticker(trade.pair)['bid']
                profit = 100 * (
                    (current_rate - trade.open_rate) / trade.open_rate)

            profit_amounts.append((profit / 100) * trade.btc_amount)
            profits.append(profit)

        bp_pair, bp_rate = Session.query(Trade.pair, func.sum(Trade.close_profit).label('profit_sum')) \
            .filter(Trade.is_open.is_(False)) \
            .group_by(Trade.pair) \
            .order_by('profit_sum DESC') \
            .first()

        markdown_msg = """
*ROI:* `{profit_btc} ({profit}%)`
*Trade Count:* `{trade_count}`
*First Trade opened:* `{first_trade_date}`
*Latest Trade opened:* `{latest_trade_date}`
*Avg. Duration:* `{avg_duration}`
*Best Performing:* `{best_pair}: {best_rate}%`
        """.format(
            profit_btc=round(sum(profit_amounts), 8),
            profit=round(sum(profits), 2),
            trade_count=len(trades),
            first_trade_date=arrow.get(trades[0].open_date).humanize(),
            latest_trade_date=arrow.get(trades[-1].open_date).humanize(),
            avg_duration=str(
                timedelta(seconds=sum(durations) /
                          float(len(durations)))).split('.')[0],
            best_pair=bp_pair,
            best_rate=round(bp_rate, 2),
        )
        TelegramHandler.send_msg(markdown_msg, bot=bot)
Exemple #3
0
def main():
    log.info("------------------------------------------------------------")
    session = Session()
    (options, args) = parser.parse_args()
    if options.filename is not None:
        feeds = [options.filename]
    else:
        feeds = settings.get('main', 'feeds').split()
    preferred_quality = settings.get('main', 'preferred_quality')
    if settings.has_option('main', 'global_exclude_regex'):
        exclude_regex = re.compile(settings.get('main', 'global_exclude_regex'))
    else:
        exclude_regex = None

    for feed_url in feeds:
        feed = parse(feed_url)
        log.info("Checking %s" % feed['feed']['subtitle'])
        for entry in feed.entries:
            if (exclude_regex is not None and
                exclude_regex.search(entry.description.lower()) is not None):
                log.info("SKIP %s" % entry.description)
                continue
            data = extract_metadata(entry.description)
            try:
                data['torrent_url'] = entry.enclosures[0]['href']
            except (IndexError, KeyError):
                log.warning("No torrent found for %(name)s" % data)
            show = TVShow(**data)
            existing_qualities = session.query(TVShow).filter(TVShow.name==show.name).\
                filter(TVShow.season==show.season).\
                filter(TVShow.episode==show.episode)
            preferred_qualities = existing_qualities.\
                filter(TVShow.quality==preferred_quality)

            # nothing yet? then add unconditionally
            if existing_qualities.count()==0:
                session.add(show)
                log.info("ADDED %(name)s %(season)s %(episode)s in %(quality)s" % show.__dict__)
            # already in preferred quality?
            elif preferred_qualities.count() > 0:
                log.info("HAVE %(name)s %(season)s %(episode)s to %(quality)s" % show.__dict__)
                continue
            # update existing quality with this one:
            else:
                existing_quality = existing_qualities.one()
                if show.quality != existing_quality.quality:
                    session.delete(existing_quality)
                    session.add(show)
                    log.info("UPDATED %(name)s %(season)s %(episode)s to %(quality)s" % show.__dict__)
    
    torrent_download_dir = path.expanduser(settings.get('main', 'torrent_download_dir'))
    shows = session.query(TVShow).filter(TVShow.status==u'new')
    if shows.count() > 0:
        log.info("downloading torrents to %s" % torrent_download_dir)
        for show in session.query(TVShow).filter(TVShow.status==u'new'):
            torrent_path, result = urlretrieve(show.torrent_url, path.join(torrent_download_dir,
                "%s.torrent" % show.filename))
            if result.type == 'application/x-bittorrent':
                show.status = u'torrent_downloaded'
                log.info("DOWNLOAD %(name)s %(season)s %(episode)s in %(quality)s" % show.__dict__)
            else:
                log.error("Couldn't download %s" % show.torrent_url)
    else:
        log.info("no shows to download")

    session.commit()