Ejemplo n.º 1
0
    def update(self):
        """ Gets the latest data from blockchain.info. """

        from blockchain import statistics, exchangerates

        self.stats = statistics.get()
        self.ticker = exchangerates.get_ticker()
Ejemplo n.º 2
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Get the Bitcoin sensor. """

    from blockchain.wallet import Wallet
    from blockchain import exchangerates, exceptions

    wallet_id = config.get('wallet', None)
    password = config.get('password', None)
    currency = config.get('currency', 'USD')

    if currency not in exchangerates.get_ticker():
        _LOGGER.error('Currency "%s" is not available. Using "USD".', currency)
        currency = 'USD'

    wallet = Wallet(wallet_id, password)

    try:
        wallet.get_balance()
    except exceptions.APIException as error:
        _LOGGER.error(error)
        wallet = None

    data = BitcoinData()
    dev = []
    if wallet is not None and password is not None:
        dev.append(BitcoinSensor(data, 'wallet', currency, wallet))

    for variable in config['display_options']:
        if variable not in OPTION_TYPES:
            _LOGGER.error('Option type: "%s" does not exist', variable)
        else:
            dev.append(BitcoinSensor(data, variable, currency))

    add_devices(dev)
Ejemplo n.º 3
0
    def update(self):
        """ Gets the latest data from blockchain.info. """

        from blockchain import statistics, exchangerates

        self.stats = statistics.get()
        self.ticker = exchangerates.get_ticker()
Ejemplo n.º 4
0
	def receive(self, msg):
		coarse = msg.body.strip().split(' ')
		args = list(filter( lambda x: len(x) > 0, coarse ))

		if args[0] == '!btc':
			curs = args[1:]
			if len(curs) == 0:
				curs = [ self.config.get('currency', 'USD') ]

			# Simplistic rate limiting, TODO better rate limiting
			limit = self.config.get('limit', -1)
			if limit >= 0 and len(curs) > limit:
				self.reply(msg, body="Currency queries are limited to {}.".format(limit))
				return

			# Actually get a return the values
			ticker = exchangerates.get_ticker()
			hit = {} # for not showing the same currency twice

			for c in curs:
				c = c.upper()
				if not c in hit:
					if c in ticker:
						body = '1 BTC ~ {} {}'.format(ticker[c].p15min, c)
					else:
						body = 'Unknown currency: {}'.format(c)
					hit[c] = True
					self.reply(msg, body=body)
Ejemplo n.º 5
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Get the Bitcoin sensor. """

    from blockchain.wallet import Wallet
    from blockchain import exchangerates, exceptions

    wallet_id = config.get('wallet', None)
    password = config.get('password', None)
    currency = config.get('currency', 'USD')

    if currency not in exchangerates.get_ticker():
        _LOGGER.error('Currency "%s" is not available. Using "USD".', currency)
        currency = 'USD'

    wallet = Wallet(wallet_id, password)

    try:
        wallet.get_balance()
    except exceptions.APIException as error:
        _LOGGER.error(error)
        wallet = None

    data = BitcoinData()
    dev = []
    if wallet is not None and password is not None:
        dev.append(BitcoinSensor(data, 'wallet', currency, wallet))

    for variable in config['display_options']:
        if variable not in OPTION_TYPES:
            _LOGGER.error('Option type: "%s" does not exist', variable)
        else:
            dev.append(BitcoinSensor(data, variable, currency))

    add_devices(dev)
Ejemplo n.º 6
0
def exchange_rates():
    ticker = exchangerates.get_ticker()
    d = {}
    for k in ticker:
        d[k] = ticker[k].p15min

    output_peer_string = ''
    for key, item in d.items():
        output_peer_string += str(key) + ' : ' + str(item).replace('{', '').replace('}', '').replace("'", '').replace(',', ', ').title()+'\n'
    sg.popup(output_peer_string, title='Exchange rates')
Ejemplo n.º 7
0
def converter_real_bitcoin(quantidade):
    """
    Metódo para converter Bitcoin para Real utilizando a API em Python da 'BlockChain Info'
    utilizando dados em tempo real
    """
    util.TIMEOUT = 5  #time out after 5 seconds
    ticker = exchangerates.get_ticker()
    temp_resultado = float(ticker['BRL'].last) * float(quantidade)
    locale.setlocale(locale.LC_MONETARY, 'pt_BR.UTF-8')
    resultado = locale.currency(temp_resultado, grouping=True, symbol=True)
    return resultado
Ejemplo n.º 8
0
def main():
    currency_symbols = er.get_ticker()

    for c in currency_symbols:
        print(c)

    for c in currency_symbols:
        print(c, ":", currency_symbols[c].p15min)

    for c in currency_symbols:
        print("1 BTC:", 1 / currency_symbols[c].p15min)

    cad_base_btc = er.to_btc("CAD", 5000)
    print("5000 CAD costs", cad_base_btc, "BTCs")
Ejemplo n.º 9
0
def setup_platform(opp, config, add_entities, discovery_info=None):
    """Set up the Bitcoin sensors."""

    currency = config[CONF_CURRENCY]

    if currency not in exchangerates.get_ticker():
        _LOGGER.warning("Currency %s is not available. Using USD", currency)
        currency = DEFAULT_CURRENCY

    data = BitcoinData()
    dev = []
    for variable in config[CONF_DISPLAY_OPTIONS]:
        dev.append(BitcoinSensor(data, variable, currency))

    add_entities(dev, True)
Ejemplo n.º 10
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Bitcoin sensors."""
    from blockchain import exchangerates

    currency = config.get(CONF_CURRENCY)

    if currency not in exchangerates.get_ticker():
        _LOGGER.error('Currency "%s" is not available. Using "USD"', currency)
        currency = 'USD'

    data = BitcoinData()
    dev = []
    for variable in config[CONF_DISPLAY_OPTIONS]:
        dev.append(BitcoinSensor(data, variable, currency))

    add_devices(dev)
Ejemplo n.º 11
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Bitcoin sensors."""
    from blockchain import exchangerates

    currency = config.get(CONF_CURRENCY)

    if currency not in exchangerates.get_ticker():
        _LOGGER.warning("Currency %s is not available. Using USD", currency)
        currency = DEFAULT_CURRENCY

    data = BitcoinData()
    dev = []
    for variable in config[CONF_DISPLAY_OPTIONS]:
        dev.append(BitcoinSensor(data, variable, currency))

    add_entities(dev, True)
Ejemplo n.º 12
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Bitcoin sensors."""
    from blockchain import exchangerates

    currency = config.get(CONF_CURRENCY)

    if currency not in exchangerates.get_ticker():
        _LOGGER.warning("Currency %s is not available. Using USD", currency)
        currency = DEFAULT_CURRENCY

    data = BitcoinData()
    dev = []
    for variable in config[CONF_DISPLAY_OPTIONS]:
        dev.append(BitcoinSensor(data, variable, currency))

    add_devices(dev)
Ejemplo n.º 13
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Bitcoin sensors."""

    currency = config[CONF_CURRENCY]

    if currency not in exchangerates.get_ticker():
        _LOGGER.warning("Currency %s is not available. Using USD", currency)
        currency = DEFAULT_CURRENCY

    data = BitcoinData()
    entities = [
        BitcoinSensor(data, currency, description)
        for description in SENSOR_TYPES
        if description.key in config[CONF_DISPLAY_OPTIONS]
    ]

    add_entities(entities, True)
Ejemplo n.º 14
0
 def add_to_cart(self, product_slug):
     btc_rates = exchangerates.get_ticker()
     btc_eur_rate = btc_rates.get('EUR').buy
     eur_btc_rate = float('{:09.8f}'.format(1 / btc_eur_rate))
     cart = self
     product = Art.objects.get(slug=product_slug)
     new_item, _ = CartItem.objects.get_or_create(product=product,
                                                  item_total=product.price)
     if new_item not in cart.items.all():
         new_item.rent_length = 3
         new_item.item_total = new_item.item_total * 3
         new_item.btc_item_total = '{:12.8f}'.format(
             float(new_item.item_total) * eur_btc_rate)
         new_item.save()
         cart.items.add(new_item)
         cart.save()
         product.available = False
         product.save()
Ejemplo n.º 15
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Bitcoin sensors."""
    from blockchain import exchangerates

    currency = config.get('currency', 'USD')

    if currency not in exchangerates.get_ticker():
        _LOGGER.error('Currency "%s" is not available. Using "USD"', currency)
        currency = 'USD'

    data = BitcoinData()
    dev = []
    for variable in config['display_options']:
        if variable not in OPTION_TYPES:
            _LOGGER.error('Option type: "%s" does not exist', variable)
        else:
            dev.append(BitcoinSensor(data, variable, currency))

    add_devices(dev)
Ejemplo n.º 16
0
def accueilBTC(request):
    graphe = home.Accueil.afficherCours('BTC')
    ticker = exchangerates.get_ticker()
    prix_BTC = ticker['USD'].p15min
    #whales_address = home.Accueil.get_users()
    #home.Accueil.serialize_users(whales_address)
    whales_address = home.Accueil.deserialize_users()
    echanges = home.Accueil.echanges(whales_address)
    echanges_index = home.Accueil.echanges_index(echanges)
    data = home.Accueil.valeurs(echanges)
    chord = home.Accueil.chord(data)
    return render(
        request,
        'accueil/accueil.html',
        {
            'graphe_div': graphe,
            'prix_BTC': prix_BTC,
            'chord': chord,
            "echanges": echanges_index
        },
    )
Ejemplo n.º 17
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Get the Bitcoin sensor. """

    try:
        from blockchain.wallet import Wallet
        from blockchain import exchangerates, exceptions

    except ImportError:
        _LOGGER.exception("Unable to import blockchain. " "Did you maybe not install the 'blockchain' package?")

        return False

    wallet_id = config.get("wallet", None)
    password = config.get("password", None)
    currency = config.get("currency", "USD")

    if currency not in exchangerates.get_ticker():
        _LOGGER.error('Currency "%s" is not available. Using "USD".', currency)
        currency = "USD"

    wallet = Wallet(wallet_id, password)

    try:
        wallet.get_balance()
    except exceptions.APIException as error:
        _LOGGER.error(error)
        wallet = None

    data = BitcoinData()
    dev = []
    if wallet is not None and password is not None:
        dev.append(BitcoinSensor(data, "wallet", currency, wallet))

    for variable in config["display_options"]:
        if variable not in OPTION_TYPES:
            _LOGGER.error('Option type: "%s" does not exist', variable)
        else:
            dev.append(BitcoinSensor(data, variable, currency))

    add_devices(dev)
Ejemplo n.º 18
0
def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Bitcoin sensors."""

    currency = config[CONF_CURRENCY]

    if currency not in exchangerates.get_ticker():
        _LOGGER.warning("Currency %s is not available. Using USD", currency)
        currency = DEFAULT_CURRENCY

    data = BitcoinData()
    entities = [
        BitcoinSensor(data, currency, description)
        for description in SENSOR_TYPES
        if description.key in config[CONF_DISPLAY_OPTIONS]
    ]

    add_entities(entities, True)
Ejemplo n.º 19
0
def btc_current_rates():
    btc_rates = exchangerates.get_ticker()
    btc_eur_rate = btc_rates.get('EUR').buy
    eur_btc_rate = float('{:09.8f}'.format(1 / btc_eur_rate))
    return eur_btc_rate
Ejemplo n.º 20
0
    def update(self):
        """Get the latest data from blockchain.com."""

        self.stats = statistics.get()
        self.ticker = exchangerates.get_ticker()
Ejemplo n.º 21
0
from blockchain import exchangerates
import time
import os

ticker = exchangerates.get_ticker()

base = ticker['BRL'].sell
taxa_alerta = 0.04
tempo_base = 8 #minutos
flag = 'Comprar' #Comprar ou Vender
while True:
	try:
		ticker = exchangerates.get_ticker()
		sell = ticker['BRL'].sell
		buy = ticker['BRL'].buy
	except Exception as e:
		continue
	
	if flag == 'Comprar':
		valor = buy
	else:
		valor = sell
	msg = "Sell: R$ "+str(valor)+" Buy: R$ "+str(buy)

	if abs(1-(valor/base)) >= taxa_alerta:
		try:
			command = 'curl -X POST  https://rest.nexmo.com/sms/json -d api_key=KEY -d api_secret=SECRET -d to=55DDDSeuTELEFONE -d from="NEXMO" -d text="'+msg+'"'
			command = 'echo '+flag
			if flag == 'Comprar':
				flag = 'Vender'
			else:
Ejemplo n.º 22
0
def get_tickerf():
    ticker = exchangerates.get_ticker()
    #print the 15 min price for every currency
    for k in ticker:
        print(k, ticker[k].p15min)
# Copyright Chainhaus
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Rates
#
# Docs: https://github.com/blockchain/api-v1-client-python/blob/master/docs/exchangerates.md

from blockchain import exchangerates as er

symbols = er.get_ticker()
for k in symbols:
    print(str(k), symbols[k].p15min)

# How much BTC can USD buy?

for d in range(0, 100000, 10000):
    print("$", d, " = ", er.to_btc('USD', d), " BTC")
Ejemplo n.º 24
0
from blockchain import exchangerates

ticker = exchangerates.get_ticker(
)  #get_ticker method will return exchange rate in dict form
print("bitcoin  prices in differnt currencies :")
for k in ticker:
    print(k, ticker[k].p15min)  #value from past 15 mins

btc = exchangerates.to_btc('INR',
                           1000)  #exchange the currency value in bitcoin
print("\n1000 indian rupee in bitcoin : {}".format(btc))
Ejemplo n.º 25
0
def getBitcoinPrice():
    btcAmount = exchangerates.get_ticker()
    return(btcAmount['USD'].last)
Ejemplo n.º 26
0
from flask import Flask, render_template, request, redirect, url_for, Blueprint
from blockchain import exchangerates, statistics
import urllib2, json, requests, datetime
import pandas as pd
import numpy as np
import scipy.stats

chart = Blueprint('chart',__name__)

#For statistics
stats = statistics.get()
actualtimelist = []
actualtimelist_rev = []
ticker = exchangerates.get_ticker()

#Chart section
jsonfilein = 'https://blockchain.info/charts/market-price?showDataPoints=false&timespan=&show_header=true&daysAverageString=1&scale=0&format=json&address='
r = requests.get(jsonfilein)
j = r.json()
entries = j['values']

def ccylists():
	return ticker

def ccyprice():
	for k in ticker:
		yield ticker[k].p15min

def ccysymbol():
	for s in ticker:
		yield ticker[s].symbol
Ejemplo n.º 27
0
def convert_to_rub(amount):
    return amount * float(exchangerates.get_ticker()['RUB'].p15min)
Ejemplo n.º 28
0
    def get_all_bitcoin_price(self, request, *args, **kwargs):
        response = list(map(lambda x: {x[0]: x[1].__dict__}, get_ticker().items()))

        return Response(response, status.HTTP_200_OK)
Ejemplo n.º 29
0
def get_rates():
    ticker = exchangerates.get_ticker()
    return float(ticker['RUB'].p15min), float(ticker['USD'].p15min)
Ejemplo n.º 30
0
def ticker():
    eDict = copy.deepcopy(exchangerates.get_ticker())
    return eDict