예제 #1
0
def main_charts(save=False):
    ### --------- PRICE CHART

    data = {
        'time':
        [t_s(t) for t, p in get_gecko(models()['epic']).data['price_7d']][::2],
        'price':
        [p for t, p in get_gecko(models()['epic']).data['price_7d']][::2],
    }

    df = pd.DataFrame(data)
    source = ColumnDataSource(df)

    DTF = DatetimeTickFormatter()
    DTF.hours = ["%H:%M"]
    DTF.days = ["%d/%m"]
    DTF.months = ["%d/%m/%Y"]
    DTF.years = ["%d/%m/%Y"]

    TOOLS = "pan, wheel_zoom, box_zoom, reset, save"

    p = figure(x_axis_type="datetime",
               tools=TOOLS,
               plot_width=900,
               plot_height=300,
               sizing_mode='scale_width')
    p.line(x='time', y='price', source=source, line_width=2, color='gold')
    p.varea(x='time',
            y1=0,
            y2='price',
            source=source,
            alpha=0.2,
            fill_color='gold')

    hover = HoverTool(tooltips=[("Date: ", "@time{%y-%m-%d}"),
                                ("Time: ", "@time{%H:%M}"),
                                ("Price: ", "@price{$0.00f}")],
                      formatters={
                          "@time": "datetime",
                          'price': 'printf'
                      },
                      mode='vline')
    p.add_tools(hover)

    p.xaxis.major_label_orientation = 3.14 / 4
    p.yaxis.visible = False
    # x stuff
    p.xaxis.visible = True
    p.xgrid.visible = False
    p.xaxis.major_label_text_color = "#cccac4"
    p.xaxis[0].formatter = DTF

    # Y - PRICE
    p.y_range = Range1d(min(data['price']) * 0.9, max(data['price']) * 1.1)
    # p.yaxis.axis_label = "Price in USD"
    p.add_layout(LinearAxis(), 'right')
    p.yaxis[1].formatter = NumeralTickFormatter(format="$0.000")
    p.yaxis.major_label_text_color = "gold"

    p.ygrid.visible = False

    p.background_fill_color = None
    p.border_fill_color = None
    p.outline_line_color = None
    p.toolbar.autohide = True

    epic_7d_price, created = Chart.objects.get_or_create(name='epic_7d_price',
                                                         coin=models()['epic'])
    epic_7d_price.script, epic_7d_price.div = components(p)
    epic_7d_price.updated = timezone.now()
    epic_7d_price.save()

    ### VOLUME CHART
    colors = ["#f2a900", "#459e86"]
    piles = ['Total', 'Citex', 'Vitex']
    targets = ['Bitcoin', 'USD(T)']
    vol_data = {
        'piles':
        piles,
        'Bitcoin': [
            volumes()['total']['btc'],
            volumes()['citex']['btc'],
            volumes()['vitex']['btc'],
        ],
        'USD(T)': [volumes()['total']['usdt'],
                   volumes()['citex']['usdt'], 0]
    }

    p1 = figure(x_range=piles,
                plot_height=50,
                plot_width=150,
                toolbar_location=None,
                tools="hover",
                tooltips="$name: @$name{0 a}",
                sizing_mode='scale_width')

    p1.vbar_stack(targets,
                  x='piles',
                  width=0.7,
                  color=colors,
                  source=vol_data,
                  legend_label=targets)

    labels = LabelSet(x='piles',
                      y=0,
                      text='targets',
                      level='glyph',
                      x_offset=5,
                      y_offset=5,
                      source=source)

    p1.yaxis.formatter = NumeralTickFormatter(format="0,0")
    p1.ygrid.visible = False
    p1.xgrid.visible = False
    p1.legend.orientation = "horizontal"
    p1.legend.background_fill_alpha = 0
    p1.legend.border_line_color = None
    p1.background_fill_color = None
    p1.border_fill_color = None
    p1.outline_line_color = None
    p1.toolbar.autohide = True

    vol_24h, created = Chart.objects.get_or_create(name='vol_24h',
                                                   coin=models()['epic'])
    vol_24h.script, vol_24h.div = components(p1)
    vol_24h.updated = timezone.now()
    vol_24h.save()

    return f'Main charts updated successfully!'
예제 #2
0
def mw_charts(save=False):
    for i, coin in enumerate(all_coins()):
        if coin.mw_coin:
            data = {
                'time':
                [t_s(t) for t, p in get_gecko(coin).data['price_7d']][::5],
                'price': [p for t, p in get_gecko(coin).data['price_7d']][::5],
            }

        df = pd.DataFrame(data)
        df['time'] = pd.to_datetime(df['time'])
        source = ColumnDataSource(df)

        DTF = DatetimeTickFormatter()
        DTF.hours = ["%H:%M"]
        DTF.days = ["%d/%m/'%y"]
        DTF.months = ["%d/%m/%Y"]
        DTF.years = ["%d/%m/%Y"]

        p = figure(x_axis_type="datetime",
                   plot_width=190,
                   plot_height=45,
                   toolbar_location=None)
        p.line(x='time',
               y='price',
               line_width=1.5,
               source=source,
               color=colors[coin.name])
        p.varea(x='time',
                y1=0,
                y2='price',
                alpha=0.1,
                source=source,
                fill_color=colors[coin.name])

        hover = HoverTool(tooltips=[("Date: ", "@time{%y-%m-%d}"),
                                    ("Time: ", "@time{%H:%M}"),
                                    ("Price: ", "@price{$0.00f}")],
                          formatters={
                              "@time": "datetime",
                              'price': 'printf'
                          },
                          mode='vline')
        p.add_tools(hover)

        p.xaxis.major_label_orientation = 3.14 / 4
        p.yaxis.visible = False
        # x stuff
        p.xaxis.visible = False
        p.xgrid.visible = False
        p.xaxis.major_label_text_color = "grey"
        p.xaxis[0].formatter = DTF

        # Y - PRICE
        p.y_range = Range1d(min(data['price']) * 0.7, max(data['price']) * 1.1)
        # # p.yaxis.axis_label = "Price in USD"
        # p.add_layout(LinearAxis(), 'right')
        # p.yaxis[1].formatter = NumeralTickFormatter(format="$0.000")
        # p.yaxis.major_label_text_color = "gold"

        p.ygrid.visible = False

        p.background_fill_color = None
        p.border_fill_color = None
        p.outline_line_color = None
        p.toolbar.autohide = True

        mw_chart, created = Chart.objects.get_or_create(name='mw_chart',
                                                        coin=coin)
        mw_chart.script, mw_chart.div = components(p)
        mw_chart.updated = timezone.now()
        mw_chart.save()

    return f'MW charts updated successfully!'
예제 #3
0
파일: data.py 프로젝트: blacktyger/tickerv4
def vitex_data():
    start_time = monotonic()
    queries = {
        'depth': 'depth?symbol=',
        'orderbook': 'ticker/bookTicker?symbol=',
        'ticker': 'ticker/24hr?symbols=',
        'market': 'market?symbol=',
        'trades': 'trades?symbol=',
        'candles': 'klines?symbol=',
    }

    symbol = 'EPIC-001_BTC-000'
    target = 'btc'
    exchange = models()['vitex']
    coin = models()['epic']

    def vitex_api(query, breaks=False, extra='&interval=hour&limit=20'):
        start_url = "https://api.vitex.net/api/v2/"
        if query == "klines?symbol=":
            url = start_url + query + symbol + extra
        else:
            url = start_url + query + symbol
        # print(f"{url}...")
        if breaks:
            sleep(1.5)
        return json.loads(requests.get(url).content)

    data = {query: vitex_api(queries[query]) for query in queries}
    update = {
        'updated':
        timezone.now(),
        'coin':
        coin,
        'exchange':
        exchange,
        'pair':
        target,
        'trading_url':
        'https://x.vite.net/trade?symbol=' + symbol,
        'last_price':
        d(data['market']['data']['lastPrice']),
        'bid':
        d(data['market']['data']['bidPrice']),
        'ask':
        d(data['market']['data']['askPrice']),
        'spread':
        spread(data['market']['data']['askPrice'],
               data['market']['data']['bidPrice']),
        'high':
        d(data['market']['data']['highPrice']),
        'low':
        d(data['market']['data']['lowPrice']),
        'last_trade':
        t_s(data['trades']['data'][0]['timestamp']),
        'volume':
        d(data['market']['data']['volume']),
        'orders':
        data['depth']['data'],
        'candles':
        data['candles']['data'],
        'trades':
        data['trades']['data']
    }

    last_saved = Ticker.objects.filter(coin=coin,
                                       pair=target,
                                       exchange=exchange,
                                       to_save=True).last()
    last_updated = Ticker.objects.filter(coin=coin,
                                         pair=target,
                                         exchange=exchange,
                                         to_save=False).last()
    save = check_saving(last_saved)
    if save:
        Ticker.objects.create(to_save=save, **update)
        print(f"save=True, record saved")
    else:
        if last_updated:
            updater(last_updated, update)
        else:
            Ticker.objects.create(to_save=save, **update)

    end_time = monotonic()
    return f"ViteX Data saved in db {timedelta(seconds=(end_time - start_time)).total_seconds()} seconds"
예제 #4
0
파일: data.py 프로젝트: blacktyger/tickerv4
def explorer_data():
    start_time = monotonic()
    parts = {
        'ex_url':
        'https://explorer.epic.tech/api?q=',
        'ex_params': [
            'circulating', 'getblockcount', 'getdifficulty-randomx',
            'getdifficulty-progpow', 'getdifficulty-cuckoo', 'reward',
            'average-blocktime', 'getblocktime&height='
        ],
        'ice_url':
        'https://icemining.ca/api/',
        'ice_params': ['blocks/epic/']
    }

    data = {
        'coin':
        models()['epic'],
        'updated':
        timezone.now(),
        'last_block':
        t_s(
            api(
                parts['ex_url'], parts['ex_params'][7] +
                str(api(parts['ex_url'], parts['ex_params'][1])))),
        'circulating':
        api(parts['ex_url'], parts['ex_params'][0]),
        'height':
        api(parts['ex_url'], parts['ex_params'][1]),
        'reward':
        api(parts['ex_url'], parts['ex_params'][5]),
        'average_blocktime':
        api(parts['ex_url'], parts['ex_params'][6]),
        'target_diff': {
            'progpow': [
                block for block in models()['icemining'].blocks
                if block['algo'] == 'progpow'
            ][0]['diff'],
            'randomx': [
                block for block in models()['icemining'].blocks
                if block['algo'] == 'randomx'
            ][0]['diff'],
            # 'cuckoo': [block for block in models()['icemining'].blocks if block['algo'] == 'cuckoo'][0]['diff']
        },
        'total_diff': {
            'progpow': api(parts['ex_url'], parts['ex_params'][3]),
            'randomx': api(parts['ex_url'], parts['ex_params'][4]),
            'cuckoo': api(parts['ex_url'], parts['ex_params'][5]),
        }
    }

    last_saved = Explorer.objects.filter(coin=models()['epic'],
                                         to_save=True).last()
    last_updated = Explorer.objects.filter(coin=models()['epic'],
                                           to_save=False).last()
    save = check_saving(last_saved)
    if save:
        Explorer.objects.create(to_save=save, **data)
        print(f"save=True, record saved")
    else:
        if last_updated:
            updater(last_updated, data)
        else:
            Explorer.objects.create(to_save=save, **data)

    end_time = monotonic()
    return f"Explorer data saved to db! {timedelta(seconds=(end_time - start_time)).total_seconds()} seconds"
예제 #5
0
파일: data.py 프로젝트: blacktyger/tickerv4
def citex_data():
    start_time = monotonic()
    exchange = models()['citex']

    def citex_api(que, sym='epic_usdt', si='', ty='', breaks=False):
        """ Create proper urls for API end points """
        start_url = "https://api.citex.co.kr/v1/"
        query = que + '?'
        symbol = 'symbol=' + sym
        size = '&size=' + si
        typ = '&type=' + ty
        url = start_url + query + symbol + size + typ
        if breaks:
            sleep(1.4)
        print(f"{url}...")
        return json.loads(requests.get(url).content)

    data = {target: {} for target in PAIRS}

    for coin in all_coins()[:1]:
        source = copy.deepcopy(citex_api('alltickers')['ticker'])
        for target in PAIRS:
            vol = [
                d(x[::5][1]) for x in citex_api('candles',
                                                sym='epic_' + target,
                                                si="24",
                                                ty="60",
                                                breaks=True)
            ]
            vol = sum(vol)
            for tick in source:
                if tick['symbol'] == coin.symbol.lower() + '_' + target:
                    data[target].update(tick)
                    sleep(1.4)

            update = {
                'updated':
                timezone.now(),
                'coin':
                coin,
                'exchange':
                models()['citex'],
                'pair':
                target,
                'trading_url':
                'https://trade.citex.me/trade/' + coin.symbol + '_' +
                target.upper(),
                'last_price':
                d(data[target]['last']),
                'bid':
                d(data[target]['buy']),
                'ask':
                d(data[target]['sell']),
                'spread':
                spread(data[target]['sell'], data[target]['buy']),
                'high':
                d(data[target]['high']),
                'low':
                d(data[target]['low']),
                'last_trade':
                t_s(
                    citex_api('trades',
                              sym='epic_' + target,
                              si="1",
                              breaks=True)[0]['timestamp']),
                'volume':
                d(vol),
                'orders':
                citex_api('depth', sym='epic_' + target, si="10", breaks=True),
                'candles': {
                    'candles':
                    citex_api('candles',
                              sym='epic_' + target,
                              si="1",
                              ty="60",
                              breaks=True),
                    'c7x1440': [[t_s(x[::5][0]),
                                 float(x[::5][1])]
                                for x in citex_api('candles',
                                                   sym='epic_' + "usdt",
                                                   si="7",
                                                   ty="1440",
                                                   breaks=True)],
                },
                'trades':
                citex_api('trades', sym='epic_' + target, si="10",
                          breaks=True),
            }
            sleep(1.5)

            last_saved = Ticker.objects.filter(coin=coin,
                                               pair=target,
                                               exchange=exchange,
                                               to_save=True).last()
            last_updated = Ticker.objects.filter(coin=coin,
                                                 pair=target,
                                                 exchange=exchange,
                                                 to_save=False).last()
            save = check_saving(last_saved)
            if save:
                Ticker.objects.create(to_save=save, **update)
                print(f"save=True, record saved")
            else:
                if last_updated:
                    updater(last_updated, update)
                else:
                    Ticker.objects.create(to_save=save, **update)

    end_time = monotonic()
    return f"Citex Data saved in db {timedelta(seconds=(end_time - start_time)).total_seconds()} seconds"