Exemple #1
0
def imagemod():
    bitcoinprice = CoinDesk().get_current_price()
    img = Image.open("btcprice.png")
    img2 = img.crop((63, 49, 735, 550))
    basewidth = 300
    wpercent = (basewidth / float(img2.size[0]))
    hsize = int((float(img2.size[1]) * float(wpercent)))
    img2 = img2.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
    img3 = Image.open("template.png")
    img3.paste(img2, (0, 90), img2)
    draw = ImageDraw.Draw(img3)
    draw.text((95, 20), str(bitcoinprice), (255, 255, 255), font=font)
    draw = ImageDraw.Draw(img3)
    draw = ImageDraw.Draw(img3)
    bitcoinpricechange = coinmarketcap.cap_change_24h('bitcoin')
    if bitcoinpricechange < 0:
        img4 = Image.open("negative.png")
    else:
        img4 = Image.open("positive.png")
    img3.paste(img4, (65, 55), img4)
    draw = ImageDraw.Draw(img3)
    draw.text((105, 53), str(bitcoinpricechange), (255, 255, 255), font=font)
    draw = ImageDraw.Draw(img3)
    draw = ImageDraw.Draw(img3)
    img3.save("finished.png")
Exemple #2
0
def update_labels():

    time = datetime.now()
    timestamp = str(time.time().strftime('%I:%M %p'))

    price = CoinDesk.get_current_price(currency='USD')
    price_USD = '${:,.2f}'.format(price)
    worth = float(price) * owned
    worth_USD = '${:,.2f}'.format(float(price) * owned)
    margin = worth - invested
    margin_USD = '${:,.2f}'.format(margin)

    if margin > 0:
        label2.text_color = 'green'
    else:
        label2.text_color = 'red'

    x_list.append(time)
    y_list.append(price)

    label1.text = price_USD
    label2.text = margin_USD
    label3.text = timestamp

    graph(x_list, y_list)
Exemple #3
0
def tweet():
    while True:
        imagemod()
        btcprice = str(CoinDesk().get_current_price())
        status = ("The bitcoin price is $" + btcprice + ". #Bitcoin #Price")
        fn = os.path.abspath("finished.png")
        api.update_with_media(fn, status=status)
        time.sleep(7200)
        def sell():
            global rowID
            sell_sum=""    
            sell_sum_string = sell_ent.get() #amount they wish to sell
            try:
                sell_sum = float(sell_sum_string) #attempt to convert to float
            except ValueError:
                numbers = tkinter.messagebox.showinfo("Warning!","Please use numbers only") #if it cannot be covnerted then given value must not be a number

            print ("You want to sell", sell_sum,"BTC")

            if sell_sum_string == (""):
                print ("Empty Field")
                
            elif isinstance(sell_sum,float): 
            
                con = lite.connect('bitcoin.db')
                cur = con.cursor()
                cur.execute("SELECT btc_balance FROM credentials WHERE rowid=?",(rowID))
                btc_balance = cur.fetchone()
                con.commit()
                
                con = lite.connect('bitcoin.db')
                cur = con.cursor()
                cur.execute("SELECT usd_balance FROM credentials WHERE rowid=?",(rowID))
                usd_balance = cur.fetchone()
                
                if usd_balance[0] == None:
                    usd_balance = 0
                if btc_balance[0] == None:
                    btc_balance = 0

                print ("usd balance is",usd_balance) #usd_balance seen as a tuple, converted below
                print ("btc balance is",btc_balance)

                valid_usd = usd_balance[0]
                valid_btc = btc_balance[0]

                if btc_balance == 0:
                    broke_box = tkinter.messagebox.showinfo("Warning!","You do not have enough funds for this sale")

                elif btc_balance!=0:
                    current_price = CoinDesk().get_current_price(currency = 'USD')
                    real_price = current_price[:-5].replace(",","")  #convert price to compatable format
                    real_desired = float(sell_sum)*float(real_price)  #convert desired BTC amount to USD using current price 
                    print ("Desired sell is",real_desired)

                    if float(sell_sum) > float(btc_balance[0]):
                        broke_box = tkinter.messagebox.showinfo("Warning!","You do not have enough bitcoin to sell")
                    else:
                        new_usd = valid_usd + real_desired
                        new_btc = valid_btc - float(sell_sum) #as entry is seen as string,convert to float
                        print ("New USD is",new_usd)
                        print ("New BTC is",new_btc)
                        sell_popup(sell_sum,new_usd,new_btc,real_price)
            else:
                print ("Please use numbers only")
        def update():
#LABLE SHOWING LIVE BITCOIN PRICE

            while True:
                current_price = CoinDesk().get_current_price(currency = 'USD')
                bitcoin_price = current_price[:-5].replace(",","")

                live_price = tk.Label(self,name="livePrice",text =("$",bitcoin_price),font=large_font,bg="#A2A2A2",fg="#0054FF")
                live_price.place(relx=0.615,rely=0.94,relwidth=0.1,anchor="center")
                print (bitcoin_price)
                time.sleep(5)            
        def purchase():
            global rowID
            buy_sum_string = buy_ent.get() #amount they wish to buy
            buy_sum=""            
            try:
                buy_sum = float(buy_sum_string) #convert to float
            except ValueError:
                numbers = tkinter.messagebox.showinfo("Warning!","Please use numbers only")

            if buy_sum_string == (""):
                print("Empty Field")
            elif isinstance(buy_sum,float):                                
                con = lite.connect('bitcoin.db')
                cur = con.cursor()
                cur.execute("SELECT btc_balance FROM credentials WHERE rowid=?",(rowID))
                btc_balance = cur.fetchone()
                con.commit()

                con = lite.connect('bitcoin.db')
                cur = con.cursor()
                cur.execute("SELECT usd_balance FROM credentials WHERE rowid=?",(rowID))
                usd_balance = cur.fetchone()
                
                if usd_balance[0] == None:
                    usd_balance = (0,)
                if btc_balance[0] == None:
                    btc_balance = (0,)

                print ("usd balance is",usd_balance) #usd_balance seen as a tuple, converted below
                print ("btc balance is",btc_balance)

                valid_usd = usd_balance[0]
                valid_btc = btc_balance[0]

                if usd_balance == 0:
                    broke_box = tkinter.messagebox.showinfo("Warning!","You do not have enough funds for this purchase")

                if usd_balance!=0:                
                    current_price = CoinDesk().get_current_price(currency = 'USD')
                    real_price = current_price[:-5].replace(",","")  #convert price to compatable format
                    real_desired = float(buy_sum)*float(real_price)  #convert desired BTC amount to USD using current price 
                    print ("Desired buy is",real_desired)
                                          
                    if float(real_desired) > float(usd_balance[0]):
                        broke_box = tkinter.messagebox.showinfo("Warning!","You do not have enough funds for this purchase")
                    else:
                        new_usd = valid_usd - real_desired
                        new_btc = valid_btc + float(buy_sum)
                        print ("New USD is",new_usd)
                        print ("New BTC is",new_btc)
                        buy_popup(buy_sum,new_usd,new_btc,real_price)
            else:
                print ("You must use numbers only")
        def week():
            end_date = datetime.datetime.now()
            real_end = end_date.strftime("%Y-%m-%d")
                            
            week_delta = datetime.timedelta(days=7)

            start_date = end_date - week_delta
            
            real_start = start_date.strftime("%Y-%m-%d")
            #may not need to round down for week
            pastPrice = CoinDesk().get_historical_data_as_dict(start=real_start, end=real_end)
            write_data(pastPrice)
Exemple #8
0
def twitter(currency):
	if request.method == 'POST':
		print('currency', currency)
		bitcoin_price = CoinDesk().get_historical_data_as_dict(
			start=str(datetime.date.today()-datetime.timedelta(days=5)), 
			end=str(datetime.date.today()))
		current_price = CoinDesk().get_current_price(currency='USD')
		reddit = praw.Reddit(client_id='mWpIWEPU8TrUcg',
							client_secret ='SoWgmjqXuZtWNAkdxqDZn564FzQ' ,
							username='******',user_agent='btcpred')
		tweets = []
		for tweet in tweepy.Cursor(api.search, currency, lang='en').items(100):
			text =re.sub(r'http\S+', '', tweet.text)
			emoji_pattern = re.compile("["
				u"\U0001F600-\U0001F64F"  # emoticons
				u"\U0001F300-\U0001F5FF"  # symbols & pictographs
				u"\U0001F680-\U0001F6FF"  # transport & map symbols
				u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
								   "]+", flags=re.UNICODE)
			text = (emoji_pattern.sub(r'', text)) # no emoji
			text = re.sub(r'@', '', text)
			text = re.sub(r'#', '', text)
			tweets.append(text)
		
		subreddit = reddit.subreddit(currency)
		top_bitcoin = subreddit.top(limit = 1000,time_filter='day')
		for sub in top_bitcoin:
			tweets.append(sub.title)
		
		data, emotion_sents, score, line_sentiment, text, length, db_data = processing_results(tweets, currency, float(current_price))

		bitcoin_price_list = []
		date_list = []
		for i in bitcoin_price:
			bitcoin_price_list.append(float(bitcoin_price[i]))
			date_list.append(i)
		
		return render_template('projects/twitter.html', data=[data, emotion_sents, score, zip(text, line_sentiment), length, date_list, bitcoin_price_list, db_data])
	else:
		return render_template('projects/twitter.html')
        def three_years():
            end_date = datetime.datetime.now()
            real_end = end_date.strftime("%Y-%m-%d")
            
            triple_delta = datetime.timedelta(days=1095)

            start_date = end_date - triple_delta
            real_start = start_date.strftime("%Y-%m-%d")
            #rounding down to the first of the month
            real_start=real_start[:len(real_start)-2]+"01"
            
            pastPrice = CoinDesk().get_historical_data_as_dict(start=real_start, end=real_end)
            write_data(pastPrice)
def fetch_btc_price_dict(delta):

    now = datetime.now()
    past = now - timedelta(days=delta)
    start = past.strftime('%Y-%m-%d')

    print("Retrieving bitcoin price data since: {}".format(start))
    price_dict = cd.get_historical_data_as_dict(start=start, end=None)
    int_days_price_dict = {(datetime.strptime(k, '%Y-%m-%d') - past).days:
                           int(v)
                           for k, v in price_dict.items()}

    return int_days_price_dict
        def getPrice():
            global present

            bitcoinPrice = []

            if present == 0: #global variable present to clear file only on first time run
                open("priceData.txt", "w").close() #clearing file before new price data is saved

            while True:
                currentTime = datetime.datetime.now()                    
                currentPrice = CoinDesk().get_current_price(currency = 'USD')
                currentPrice = currentPrice.replace(",", "") #removing comma from prices to obtain integer value
                bitcoinPrice.append(currentPrice)
                my_list = []
                x = datetime.datetime.now().time()
                my_list.append(x)
                #print (currentPrice, currentTime)
                time.sleep(5)                               
                #Current price is fetched and saved to text file every 5 seconds and then plotted on the chart
                
                with open("priceData.txt", "a") as priceData:
                    priceData.write(str(currentPrice)+","+str(my_list[0])+"\n")
                present +=1
Exemple #12
0
 def _populate_data(self):
     """
     populate the initial interval of data
     :return: dataframe containing the current price
     :rtype: pd.DataFrame
     """
     now = datetime.now()
     price = float(CoinDesk.get_current_price(currency='USD'))
     df = pd.DataFrame(
         [[now, price, self.interval]],
         columns=['date', 'price', 'interval'],
     )
     df = df.set_index('date')
     return df
Exemple #13
0
    def current_price(self):
        """
        updates the interval and self.data with current price.

        :return: current price
        :rtype: float
        """
        now = datetime.now()
        self.interval += 1
        self.current_interval = now
        price = float(CoinDesk.get_current_price(currency='USD'))
        self.last_price = price
        self.data.ix[now] = [price, self.interval]
        return price
        def profit():
            global rowID

            con = lite.connect('bitcoin.db')
            cur = con.cursor()            
            cur.execute("SELECT last_bought FROM credentials WHERE rowid=?",(rowID))
            data = cur.fetchone()
            con.commit()
            last = str(data[0])
            
            current_price = CoinDesk().get_current_price(currency = 'USD')
            bitcoin_price = current_price[:-5].replace(",","")

            difference = int(bitcoin_price) - int(data[0])
            percent = (difference/int(data[0]))*100
            real_percent = str(percent)
            perc = real_percent[:5]

            profit_label = tk.Label(self,name="profit",text =(perc,"%"),font=large_font,bg="#A2A2A2",fg="#0054FF")
            profit_label.place(relx=0.905,rely=0.94,anchor="center")
Exemple #15
0
def update_label():
    time = datetime.now()
    timestamp = str(time.time().strftime('%I:%M %p'))
    price = CoinDesk.get_current_price(currency='USD')
    price_USD = '${:,.2f}'.format(price)
    worth = float(price) * owned
    worth_USD = '${:,.2f}'.format(float(price) * owned)
    margin = worth - invested
    margin_USD = '${:,.2f}'.format(margin)

    app.clearLabel('L1')
    app.setLabel('L1', price_USD)

    app.clearLabel('L2')
    app.setLabel('L2', margin_USD)
    if margin > 0:
        app.setLabelFg('L2', 'dark green')
    else:
        app.setLabelFg('L2', 'red')

    app.clearLabel('L3')
    app.setLabel('L3', timestamp)
Exemple #16
0
 def get(self, *args, **kwargs):
     data = CoinDesk().get_historical_data_as_dict(start='2017-08-01',
                                                   end=None)
     return HttpResponse(json.dumps(data))
import csv
from exchanges.coindesk import CoinDesk


train_data = CoinDesk.get_historical_data_as_dict(start='2013-09-01', end='2017-12-31')
with open('train_btc.csv','wb') as csv_file1:
    writer = csv.writer(csv_file1)
    for key, value in train_data.items():
          writer.writerow([key,value])

print('training data done')

test_data = CoinDesk.get_historical_data_as_dict(start='2018-02-01', end='2018-03-12')

with open('test_btc.csv','wb') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in test_data.items():
          writer.writerow([key,value])

print('end of program')


#from exchanges.bitfinex import Bitfinex
from exchanges.coindesk import CoinDesk

curr_price = CoinDesk().get_current_price()
print(curr_price)

#print(Bitfinex().get_current_price(currency='EUR'))
#print(Bitfinex().get_current_price(currency='TRY'))
Exemple #19
0
from exchanges.coindesk import CoinDesk as cd
import csv

#Open/Create a file to append data
csvFile = open('C:\\Users\\Marco\\Desktop\\bitcoin3.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile, delimiter='\t')

start_date = '2017-01-01'
end_date = '2017-11-18'
values = cd.get_historical_data_as_dict(start=start_date, end=end_date)
for date in values:
    csvWriter.writerow([date, values[date]])
Exemple #20
0
current_ip = socket.gethostbyname(socket.gethostname())

if current_ip == "127.0.1.1":

    gam_input = "ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'"
    result_1 = os.popen(gam_input).read()
    current_ip = result_1

invested = 122.44
owned = .01

time = datetime.now()
timestamp = str(time.time().strftime('%I:%M %p'))

price = CoinDesk.get_current_price(currency='USD')
price_USD = '${:,.2f}'.format(price)
worth = float(price) * owned
worth_USD = '${:,.2f}'.format(float(price) * owned)
margin = worth - invested
margin_USD = '${:,.2f}'.format(margin)


def update_label():
    time = datetime.now()
    timestamp = str(time.time().strftime('%I:%M %p'))
    price = CoinDesk.get_current_price(currency='USD')
    price_USD = '${:,.2f}'.format(price)
    worth = float(price) * owned
    worth_USD = '${:,.2f}'.format(float(price) * owned)
    margin = worth - invested
def getBCdata(start='2017-01-01', end=None):
    return CoinDesk.get_historical_data_as_dict(start, end)
Exemple #22
0
import os
from exchanges.coindesk import CoinDesk
import math
## Create a proxy object and connect to the bitcoin.rpc
myproxy = bitcoin.rpc.Proxy()
## Get the latest CBlock data from bitcoin rpc proxy
block_info = myproxy.getblock(myproxy.getblockhash(myproxy.getblockcount()))

#Setting these as variables will make them easier for future edits
app_key = ''
app_secret = ''
oauth_token = ''
oauth_token_secret = ''

## Get the value
the_price = CoinDesk().get_current_price(currency='GBP')
the_price = round(the_price, 2)
#Prepare your twitter, you will need it for everything
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
#The above should just be a single line, without the break
#/home/pi/Music/first1.py is AN EXAMPLE path location of the file to run it
txt1 = "#bitcoin CBlock Object Info: Height "
txt2 = " Hash: "
txt3 = " TXVol: "
txt4 = " GBP"
tx_count = len(block_info.vtx)
block_hash = bitcoin.core.b2lx(block_info.GetHash())
block_number = myproxy.getblockcount()
twit = txt1 + str(block_number) + txt2 + str(block_hash) + txt3 + str(
    tx_count) + " " + str(the_price) + txt4
if tx_count == 1:
#Get Bitcoin price updates in real time

#from sense_hat import SenseHat
from sense_emu import SenseHat
import time
import datetime
import csv
import sys
sys.path.append(
    '/media/newhd/Raspberry_Pi/SenseHatProjects/bitcoin-price-api-master')
from exchanges.coindesk import CoinDesk

#Fetching current bitcoin price in INR from CoinDesk API
bitcoin_price = float(round(CoinDesk().get_current_price(currency='INR'), 2))

#Fetching last recorded price for comaprision with current price
price_csv = open(
    "/media/newhd/Raspberry_Pi/SenseHatProjects/Bitcoin_Price_Ticker/bitcoin_price.csv",
    "r")
lastrow = None
for lastrow in csv.reader(price_csv):
    pass

#Displaying price in Green, Red or White based on fluctuation in price, running on simulator Pi-Sense-Hat Simulator
sense = SenseHat()
if (float(lastrow[1]) > bitcoin_price):
    sense.show_message(str(bitcoin_price), text_colour=[0, 255, 0])
elif ((float(lastrow[1]) < bitcoin_price)):
    sense.show_message(str(bitcoin_price), text_colour=[255, 0, 0])
else:
    sense.show_message(str(bitcoin_price), text_colour=[255, 255, 255])