Exemple #1
0
def test_RealTimeBTC():
    from pricing_engine.engine import realtime_price
    ticker = 'BTC'
    results = realtime_price(ticker)
    run_time = datetime.now()

    if results is None:
        health = False
        price = None
        error_message = 'Realtime Price returned None'
    try:
        price = results['price']
        health = True
        error_message = None
    except Exception as e:
        health = False
        price = None
        error_message = f"Realtime Price returned an error: {e}"

    data = {
        'health': health,
        'price': price,
        'error_message': error_message,
        'run_time': run_time
    }

    filename = 'status_realtime_btc.pkl'
    pickle_it(action='save', filename=filename, data=data)

    return (data)
Exemple #2
0
def realtime_btc():
    try:
        fx_details = fx_rate()
        fx_r = {
            'cross': fx_details['symbol'],
            'fx_rate': fx_details['fx_rate']
        }
        fx_r['btc_usd'] = realtime_price("BTC", fx='USD')['price']
        fx_r['btc_fx'] = fx_r['btc_usd'] * fx_r['fx_rate']
    except Exception as e:
        logging.warn(
            f"There was an error while getting realtime prices. Error: {e}")
        fx_r = 0
    return json.dumps(fx_r)
Exemple #3
0
def positions_json():
    # Get all transactions and cost details
    # This serves the main page
    try:
        dfdyn, piedata = positions_dynamic()
        btc_price = realtime_price("BTC")['price'] * fx_rate()['fx_rate']
        dfdyn = dfdyn.to_dict(orient='index')
    except Exception:
        dfdyn = piedata = None
        btc_price = 0
    try:
        btc = realtime_price("BTC")['price']
    except TypeError:
        btc = 0
    if not btc:
        btc = 0

    json_dict = {
        'positions': dfdyn,
        'piechart': piedata,
        'user': current_app.fx,
        'btc': btc_price
    }
    return simplejson.dumps(json_dict, ignore_nan=True)
Exemple #4
0
def price_and_position():
    # Gets price and position data for a specific ticker
    ticker = request.args.get("ticker")
    fx = request.args.get("fx")
    if fx is None:
        fx = fx_rate()['base']

    # Gets Price and market data first
    realtime_data = realtime_price(ticker=ticker, fx=fx)
    historical_data = historical_prices(ticker=ticker, fx=fx)
    historical_data.index = historical_data.index.astype('datetime64[ns]')

    filemeta = (ticker + "_" + fx + ".meta")
    historical_meta = pickle_it(action='load', filename=filemeta)

    price_chart = historical_data[["close_converted", "close"]].copy()
    # dates need to be in Epoch time for Highcharts
    price_chart.index = price_chart.index.astype('datetime64[ns]')
    price_chart.index = (price_chart.index -
                         datetime(1970, 1, 1)).total_seconds()
    price_chart.index = price_chart.index * 1000
    price_chart.index = price_chart.index.astype(np.int64)
    price_chart = price_chart.to_dict()
    price_chart_usd = price_chart["close"]
    price_chart = price_chart["close_converted"]

    # Now gets position data
    df = positions()
    if isinstance(df, pd.DataFrame):
        if not df.empty:
            df = df[df['trade_asset_ticker'] == ticker]

    df_trades = transactions_fx()
    position_chart = None
    if isinstance(df_trades, pd.DataFrame):
        df_trades = df_trades[df_trades['trade_asset_ticker'] == ticker]
        if not df_trades.empty:
            df_trades = df_trades.sort_index(ascending=True)
            df_trades['trade_quantity_cum'] = df_trades[
                'trade_quantity'].cumsum()
            position_chart = df_trades[["trade_quantity_cum"]].copy()
            # dates need to be in Epoch time for Highcharts
            position_chart.index = position_chart.index.astype(
                'datetime64[ns]')
            position_chart.index = (position_chart.index -
                                    datetime(1970, 1, 1)).total_seconds()
            position_chart.index = position_chart.index * 1000
            position_chart.index = position_chart.index.astype(np.int64)
            position_chart = position_chart.to_dict()
            position_chart = position_chart["trade_quantity_cum"]

    if ticker == 'GBTC':
        from pricing_engine.engine import GBTC_premium
        from parseNumbers import parseNumber
        GBTC_price = parseNumber(realtime_data['price'])
        GBTC_fairvalue, GBTC_premium = GBTC_premium(GBTC_price)
    else:
        GBTC_premium = GBTC_fairvalue = None

    return render_template("warden/price_and_position.html",
                           title="Ticker Price and Positions",
                           current_app=current_app,
                           current_user=fx_rate(),
                           realtime_data=realtime_data,
                           historical_data=historical_data,
                           historical_meta=historical_meta,
                           positions=df,
                           ticker=ticker,
                           fx=fx,
                           price_chart=price_chart,
                           price_chart_usd=price_chart_usd,
                           position_chart=position_chart,
                           GBTC_premium=GBTC_premium,
                           GBTC_fairvalue=GBTC_fairvalue)
Exemple #5
0
    def find_data(ticker):
        notes = None
        last_up_source = None
        source = None
        try:
            # Parse the cryptocompare data
            price = multi_price["RAW"][ticker][fx]["PRICE"]
            # GBTC should not be requested from multi_price as there is a
            # coin with same ticker
            if ticker in ['GBTC', 'MSTR', 'TSLA', 'SQ']:
                raise KeyError
            price = float(price)
            high = float(multi_price["RAW"][ticker][fx]["HIGHDAY"])
            low = float(multi_price["RAW"][ticker][fx]["LOWDAY"])
            chg = multi_price["RAW"][ticker][fx]["CHANGEPCT24HOUR"]
            mktcap = multi_price["DISPLAY"][ticker][fx]["MKTCAP"]
            volume = multi_price["DISPLAY"][ticker][fx]["VOLUME24HOURTO"]
            last_up_source = multi_price["RAW"][ticker][fx]["LASTUPDATE"]
            source = multi_price["DISPLAY"][ticker][fx]["LASTMARKET"]
            last_update = datetime.now()
        except (KeyError, TypeError):
            # Couldn't find price with CryptoCompare. Let's try a different source
            # and populate data in the same format [aa = alphavantage]
            try:
                single_price = realtime_price(ticker)
                if single_price is None:
                    raise KeyError
                price = clean_float(single_price['price'])
                last_up_source = last_update = single_price['time']

                try:
                    chg = parseNumber(single_price['chg'])
                except Exception:
                    chg = 0

                try:
                    source = last_up_source = single_price['source']
                except Exception:
                    source = last_up_source = '-'

                try:
                    high = single_price['high']
                    low = single_price['low']
                    mktcap = volume = '-'
                except Exception:
                    mktcap = high = low = volume = '-'

            except Exception:
                try:
                    # Finally, if realtime price is unavailable, find the latest
                    # saved value in historical prices
                    # Create a price class
                    price_class = historical_prices(ticker, fx)
                    if price_class is None:
                        raise KeyError
                    price = clean_float(
                        price_class.df['close_converted'].iloc[0])
                    high = '-'
                    low = '-'
                    volume = '-'
                    mktcap = chg = 0
                    source = last_up_source = 'Historical Data'
                    last_update = price_class.df.index[0]
                except Exception as e:
                    price = high = low = chg = mktcap = last_up_source = last_update = volume = 0
                    source = '-'
                    logging.error(
                        f"There was an error getting the price for {ticker}." +
                        f"Error: {e}")

        if ticker.upper() == 'BTC':
            nonlocal btc_price
            btc_price = price

        # check if 24hr change is indeed 24h or data is old, if so 24hr change = 0
        try:
            checker = last_update
            if not isinstance(checker, datetime):
                checker = parser.parse(last_update)
            if checker < (datetime.now() - timedelta(days=1)):
                chg = 0
        except Exception:
            pass

        return price, last_update, high, low, chg, mktcap, last_up_source, volume, source, notes
Exemple #6
0
def single_price(ticker):
    return (realtime_price(ticker)['price'], datetime.now())
Exemple #7
0
 def test_realtime_parsed(self):
     ticker_list = ['BTC', 'GBTC', 'ETH', 'IBM', 'MSTR', 'TSLA']
     for ticker in ticker_list:
         results = realtime_price(ticker)['price']
         self.assertIsNotNone(results,
                              f'Could not get realtime price for {ticker}')