コード例 #1
0
ファイル: ticker.py プロジェクト: lisogallo/bitcharts-core
def get_avg(exchanges):
    """Calculate average last value from the specified exchanges

    Args:
        exchanges (LIST): Exchanges' names

    Returns:
        FLOAT: Average value
    """
    values = []
    for exchange in active_exchanges():
        exchange_lower = exchange.name.lower().replace(' ', '_')
        if exchange_lower in exchanges:
            res = get_alternate_value(exchange, position='previous')
            if res:
                last, buy, trend = res
                values.append(last)
    avg = reduce(lambda x, y: x + y, values) / len(values)
    return avg
コード例 #2
0
ファイル: exchanges.py プロジェクト: lisogallo/bitcharts-core
def get_exchanges_info():
    """Generate response used by the exchanges API

    Returns:
        DICT: Exchanges info and last value
    """
    now = datetime.now()

    res = {
        '_timestamp': now.strftime('%a %b %d %Y, %H:%M:%S'),
    }

    for exchange in active_exchanges():

        if exchange.key_buy:
            previous = last = buy = trend = None

            # Get the last/buy values and trend computed by the get_values task
            previous = get_alternate_value(exchange, position='previous')
            if previous:
                last, buy, trend = previous

            # Get the last value history from the last 10 days
            query = Graph.query.filter_by(
                exchange_id=exchange.id).order_by(
                Graph.date.desc()).limit(10).all()

            history = []
            for assoc in query:
                history.append(assoc.last)

            key = exchange.name.lower().replace(' ', '_')

            res[key] = {
                'currency': exchange.currency_to.name,
                'buy': buy,
                'sell': last,
                'history': history[::-1],
                'trend': trend or None,
            }

    return res
コード例 #3
0
ファイル: ticker.py プロジェクト: lisogallo/bitcharts-core
def get_values():
    """
    Manager command to get last values from all active exchanges
    """
    for exchange in active_exchanges():

        ticker = exchange.url + exchange.api
        subject = '[ERROR] %s exchange' % exchange.name
        error_msg = "Exchange: %s\nTicker: %s\nException: " % (exchange.name,
                                                               ticker)

        try:
            previous_last = last = buy = trend = None

            last = exchange.get_value(exchange.key_last)
            if exchange.key_buy:
                buy = exchange.get_value(exchange.key_buy)
            # Close session opened after the execution of get_value method
            db.session.close()

            # Also get previous to calculate trend
            res = get_alternate_value(exchange, position='previous')
            if res:
                previous_last, previous_buy, trend = res

            if previous_last and last:
                if previous_last < last:
                    trend = 'up'
                elif previous_last > last:
                    trend = 'down'
                else:
                    trend = 'equal'

            assoc = Association(
                exchange_id=exchange.id,
                last=last,
                buy=buy,
                trend=trend or None,
                date=date.today(),
                time=datetime.now().time()
            )
            if assoc.last:
                print '%s: %s %s %s' % (exchange.name,
                                        assoc.last,
                                        exchange.currency_to.name,
                                        trend or '')

                db.session.add(assoc)
            else:
                raise Exception

        except Exception as err:
            if not err.message:
                err.message = 'Connection Error. Ticker API is down.'
            print subject + ': ' + str(err.message)
            if app.config.get('ENABLE_MAIL_NOTIFICATIONS', False):
                send_async_email(subject, error_msg + str(err.message))

        finally:
            db.session.commit()
            db.session.close()
コード例 #4
0
ファイル: graphs.py プロジェクト: lisogallo/bitcharts-core
def get_graphs():
    """
    Store graph data in database to be used later by the graphs API
    """
    # List of exchanges to store values for a candlesticks graph
    candlesticks_exchanges = ['Bitstamp']

    for exchange in active_exchanges():

        ticker = exchange.url + exchange.api
        subject = '[ERROR] %s exchange (GRAPH)' % exchange.name
        error_msg = "Exchange: %s\nTicker: %s\nException: " % (exchange.name,
                                                               ticker)

        try:

            last = opn = high = low = close = volume = None
            last = exchange.get_value(exchange.key_last)
            # Close session opened after the execution of get_value method
            db.session.close()
            if exchange.name in candlesticks_exchanges:
                # Get the open value (the first value of the day)
                opn, buy, trend = get_alternate_value(exchange,
                                                      position='first')
                # Get ticker to obtain additional values to show in graph
                response = get_ticker_response(exchange)

                if opn and response:

                    # Serialize ticker response
                    json = loads(response.content)

                    close = json['last'] or None,
                    high = json['high'] or None,
                    low = json['low'] or None,
                    volume = float(json['volume']) or None,

        except ConnectionError:
            if not last:
                previous = get_alternate_value(exchange, position='previous')
                if previous:
                    last = previous[0]
                    excep = 'Error connecting with API. Using previous value.'
                    if app.config.get('ENABLE_MAIL_NOTIFICATIONS', False):
                        send_async_email(subject, error_msg + excep)
                else:
                    excep = 'Error connecting with API. No previous value get.'
                    if app.config.get('ENABLE_MAIL_NOTIFICATIONS', False):
                        send_async_email(subject, error_msg + excep)
                print subject + ': ' + excep

        except Exception as err:
            print subject + ': ' + str(err.message)
            if app.config.get('ENABLE_MAIL_NOTIFICATIONS', False):
                send_async_email(subject, error_msg + str(err.message))

        finally:
            try:
                # Write obtained values to database
                graph = Graph(
                    exchange_id=exchange.id,
                    last=last,
                    opn=opn,
                    close=close,
                    high=high,
                    low=low,
                    volume=volume,
                    date=date.today(),
                    time=datetime.now().time()
                )

                if graph.last:
                    print "Getting graph data for '%s'" % exchange.name
                    db.session.add(graph)
                else:
                    raise Exception

            except Exception as err:
                if not err.message:
                    err.message = 'Connection Error. Ticker API is down.'
                print subject + ': ' + str(err.message)
                if app.config.get('ENABLE_MAIL_NOTIFICATIONS', False):
                    send_async_email(subject, error_msg + str(err.message))

            finally:
                db.session.commit()
                db.session.close()