コード例 #1
0
def addHashRate():
    a = getSlushPool()
    hr = float(a["hashrate"])
    hr /= 1000000
    hr = round(hr, 2)
    r = float(a["confirmed_reward"])
    r = float(Bitfinex().get_current_price()) * r
    r = round(r, 2)
    d = Label(text=("Hashrate: " + str(hr) + " Th/s"),
              bd=2,
              fg="white",
              bg="black",
              anchor="nw",
              width=50,
              font=("Helvetica Neue light", 15))
    d.place(x=LEFT_SIDE, y=31)
    m = Label(text=("Reward: $" + str(r)),
              bd=2,
              fg="white",
              bg="black",
              anchor="nw",
              width=50,
              font=("Helvetica Neue light", 15))
    m.place(x=LEFT_SIDE, y=61)
    list_of_Labels.append(d)
    list_of_Labels.append(m)
コード例 #2
0
ファイル: clockr.py プロジェクト: mannynotfound/btc-ticker
def print_price(now):
    global last_price
    """main price function"""
    try:
        price = Bitfinex().get_current_price()
    except Exception as e:
        return

    price = int(round(price))
    tick_color = 4 if price >= last_price else 2
    usd_color = 5 if price >= last_price else 3
    last_price = price

    time_line = str(price)
    time_array = ["" for i in range(0, 7)]

    for char in time_line:
        char_array = glyph[char]
        for row in range(0, len(char_array)):
            time_array[row] += char_array[row]

    total_x = 65
    offset_x = int(round((total_x - len(time_array[0])) / 2))

    for y in range(0, len(time_array)):
        for x in range(0, len(time_array[y])):
            char = time_array[y][x]
            color = 1 if char == " " else tick_color

            addstr(y, x + offset_x, " ", curses.color_pair(color))

    addstr(6, offset_x + len(time_array[0]), 'USD',
           curses.color_pair(usd_color))
コード例 #3
0
def create_exchange(exchange):
    if exchange == "liqui":
        from exchanges.liqui import Liqui
        return Liqui()
    if exchange == "hitbtc":
        from exchanges.hitbtc import Hitbtc
        return Hitbtc()
    if exchange == "bittrex":
        from exchanges.bittrex import Bittrex
        return Bittrex()
    if exchange == "binance":
        from exchanges.binance import Binance
        return Binance()
    if exchange == "bithumb":
        from exchanges.bithumb import Bithumb
        return Bithumb()
    if exchange == "bitfinex":
        from exchanges.bitfinex import Bitfinex
        return Bitfinex()
    if exchange == "poloniex":
        from exchanges.poloniex import Poloniex
        return Poloniex()
    if exchange == "bitstamp":
        from exchanges.bitstamp import Bitstamp
        return Bitstamp()
    if exchange == "huobi":
        from exchanges.huobi import Huobi
        return Huobi()
    if exchange == "wex":
        from exchanges.wex import Wex
        return Wex()
    if exchange == "yobit":
        from exchanges.yobit import Yobit
        return Yobit()
コード例 #4
0
ファイル: prices.py プロジェクト: grendias/Nano-Wallet-Server
def bitfinex():
    try:
        bitfinex = Bitfinex().get_current_price()
        print(rdata.hset("prices", "bitfinex:btc-usd", bitfinex))
        print(rdata.hset("prices", "bitfinex:lastupdate", int(time.time())))
    except:
        print("Failed to load from Bitfinex")
コード例 #5
0
ファイル: bot.py プロジェクト: andrewgazelka/UnbelievaBitcoin
 async def buy(ctx, *, amount):
     price = Bitfinex().get_current_price()
     if amount.isdigit():
         amount = int(amount)
         payable = price * amount
         await ctx.send(
             f'Please send {payable} UnBelievaBoat currency to me and type b!check'
         )
     else:
         await ctx.send('no')
コード例 #6
0
def getFlights(request):
    flights = Flights('Zt0AY8d5B9UA7ERLccCjiGF6l6gpcUoS')
    if request.method == 'POST':
        form = FlightForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            resp = flights.extensive_search(
                origin=data['origin'],
                destination=data['destination'],
                #departure_date = '2018-05-15--2018-05-30'
                departure_date=data['startdate'])
            #print(resp)
            #return HttpResponse(resp['results'][0]['price'])
            resp['bitcoin'] = str(Bitfinex().get_current_price())
        return HttpResponse(json.dumps(resp))
コード例 #7
0
ファイル: book.py プロジェクト: adrianrfreedman/waxRb
    def populate(self):
        self.exchanges = [
            Bancor(self.base, self.term),
            Tidex(self.base, self.term, self.depth),
            Huobi(self.base, self.term, self.depth),
            Bittrex(self.base, self.term),
            Bitfinex(self.base, self.term, self.depth),
        ]

        for e in self.exchanges:
            if e.bid != None:
                self.bids.append([e.bid, e.depth, e.name, e.stamp])
            if e.ask != None:
                self.asks.append([e.ask, e.depth, e.name, e.stamp])

        self.bids = sorted(self.bids, reverse=True)
        self.asks = sorted(self.asks)
コード例 #8
0
ファイル: main.py プロジェクト: eian-lee/zcat
def main():
    ctx = zmq.Context()
    socket = ctx.socket(zmq.REP)
    socket.bind("tcp://*:%s" % ZMQ_PORT)
    # 거래소 객체 생성
    # bitstamp = Bitstamp(pairs='BTC/USD', depth=10)
    kraken = Kraken(pairs='BTC/USD', depth=10)
    bitfinex = Bitfinex(pairs='BTC/USD')
    # upbit = Upbit(pairs='BTC/KRW')
    threads(kraken, bitfinex)
    # 오더북 담을곳
    order1 = {}
    order2 = {}
    
    while True:
        message = json.loads(socket.recv())
        
        # 거래소 이름 검사
        try:
            if 'Kraken' == message['name']:
                order1 = message
            if 'Bitfinex' == message['name']:
                order2 = message
        
            # order1과 order2에 값이 있을 때
            if (order1 and order2):
                pprint(order1)
                # case1, case2 = calculate(order1, order2)
                # 크라켄 ASK 가격 1,2,3 ... N / 비트파이넥스 BID 가격 1,2,3 ... N
                # 비트파이넥스 BID 가격 1.2.3 ... N / 크라켄 ASK 가격 1.2.3 ... N
                # 각 주문인덱스 끼리 교차계산, 인덱스 N이 5인경우 
                # BestOffer부터 5틱 즉, 10가지 계산을 순차가 아닌 동시성으로 처리
                # 이는 TCP 통신으로 누락이 있을 수 있어 BestOffer만 계산하면 위험하기때문
                # print(f"Case1: {case1[:3]}\nCase2: {case2[:3]}\n")
            socket.send_json(message)
        except TypeError:
            continue
コード例 #9
0
ファイル: Ui.py プロジェクト: THEMaxNorman/SmartMirror
def getBtc():
    return ("The Value of Bitcoin is: " + str(round(Bitfinex().get_current_price(),2)) + "USD")
コード例 #10
0
inv_yhat = str(inv_yhat[:, 0])
print(inv_yhat)

# test_y = test_y.reshape((len(test_y), 1))
# inv_y = np.concatenate((test_y, test_X[:, -4:]), axis=1)
# inv_y = scaler.inverse_transform(inv_y)
# inv_y = inv_y[:, 0]
#print(inv_y)

#print(inv_yhat.shape)
#df = pd.DataFrame({'forecast': inv_yhat})

from datetime import date
import datetime
today = date.today()
tomorrow = today + datetime.timedelta(days=1)

from exchanges.bitfinex import Bitfinex
price = Bitfinex().get_current_price()

df=pd.read_csv("input_to_chart.csv")
df = df.drop(df.columns[0], axis=1)
df.iloc[-1, df.columns.get_loc('Actual_Price')] = price
inv_yhat = inv_yhat[1:-1]
new_row = {'Date': tomorrow , 'Predicted_Price' : inv_yhat}
df=df.append(new_row, ignore_index=True)
#print(df)
# df.reset_index(drop=True, inplace=True)
# print(df)
df.to_csv('input_to_chart.csv')
コード例 #11
0
def interact_timer(bot, update, top_p, mx, temperature):
    while True:
        global BUY
        global bitold
        global dec
        global mode
        global money
        global b

        if BUY == True:
            money = dec
            decimal = float(Bitfinex().get_current_price())
            one = decimal - bitold
            two = (one / decimal)  # * 100
            mon = money * two
            money = mon + money
            up = str(money)
            update.message.reply_text('Current money is: ' + up)
            print(money)
            print(dec)
            print(bitold)
            print("BUY SIGNAL CALC")
        if BUY == False:
            dec = money
            up = str(money)
            update.message.reply_text('Current money is: ' + up)
            print(money)
            print(dec)
            print(bitold)
            print("HOLD SIGNAL CALC")

        model_name = '1558M'
        nsamples = 1
        batch_size = 1
        top_k = 0
        models_dir = 'models'
        tex = scrape()
        raw_text = str(tex)
        #############################################
        if mode == False:
            cat = len(raw_text.split(" "))
            length = cat
            if length > 300:
                while length > 300:
                    raw_text = raw_text.split(':', 1)[-1]
                    length = len(raw_text.split(" "))
            cat = length
        tx = float(top_p)
        cax = float(cat)
        cay = float(mx)
        caz = float(cax * cay)
        ta = ((1 - tx) / caz)
        top_p = ((tx) + (ta))
        if top_p > 1:
            top_p = 1
        if top_p < 0.005:
            top_p = 0.005


#############################################
        update.message.reply_text('Computing for 6 generations...')
        cache = []
        for x in range(0, 6):
            seed = random.randint(1431655765, 2863311530)
            models_dir = os.path.expanduser(os.path.expandvars(models_dir))
            if batch_size is None:
                batch_size = 1
            assert nsamples % batch_size == 0
            enc = encoder.get_encoder(model_name, models_dir)
            hparams = model.default_hparams()
            with open(os.path.join(models_dir, model_name,
                                   'hparams.json')) as f:
                hparams.override_from_dict(json.load(f))
            if length is None:
                length = hparams.n_ctx // 2
            elif length > hparams.n_ctx:
                raise ValueError(
                    "Can't get samples longer than window size: %s" %
                    hparams.n_ctx)
            with tf.Session(graph=tf.Graph()) as sess:
                context = tf.placeholder(tf.int32, [batch_size, None])
                np.random.seed(seed)
                tf.set_random_seed(seed)
                output = sample.sample_sequence(hparams=hparams,
                                                length=length,
                                                context=context,
                                                batch_size=batch_size,
                                                temperature=temperature,
                                                top_k=top_k,
                                                top_p=top_p)
                saver = tf.train.Saver()
                ckpt = tf.train.latest_checkpoint(
                    os.path.join(models_dir, model_name))
                saver.restore(sess, ckpt)
                context_tokens = enc.encode(raw_text)
                generated = 0
                for _ in range(nsamples // batch_size):
                    out = sess.run(
                        output,
                        feed_dict={
                            context:
                            [context_tokens for _ in range(batch_size)]
                        })[:, len(context_tokens):]
                    for i in range(batch_size):
                        generated += 1
                        text = enc.decode(out[i])
                        pika = text
                        stripes = pika.encode(encoding=sys.stdout.encoding,
                                              errors='ignore')
                        tigger = stripes.decode("utf-8")
                        meow = str(tigger)
                        analyzer = SentimentIntensityAnalyzer()
                        vs = analyzer.polarity_scores(meow)
                        data = vs.get('compound')
                        cache.append(data)
                        score = str(vs)
                        print("==========")
                        print("{:-<65} {}".format(meow, str(vs)))
                        print("==========")
                        lent = str(length)
                        print("Length: " + lent)
                        print("==========")
                        print("Output: " + meow)
                        print("==========")
                        tps = str(top_p)
                        print("top_p out: " + tps)
                        print("==========")
                        tpa = str(tx)
                        print("top_p in: " + tpa)
                        print("==========")
            sess.close()
        print(cache)
        sent = str(cache)
        rounded = mean(cache)
        rou = str(rounded)
        update.message.reply_text('Sentiment of generations are:' + rou)

        if BUY == True:
            money = dec
            decimal = float(Bitfinex().get_current_price())
            one = decimal - bitold
            two = (one / decimal)  # * 100
            mon = money * two
            money = mon + money
            up = str(money)
            print(money)
            print(dec)
            print(bitold)
            print("BUY SIGNAL CALC")
        if BUY == False:
            dec = money
            up = str(money)
            print(money)
            print(dec)
            print(bitold)
            print("HOLD SIGNAL CALC")

        if rounded < 0:
            BUY = True
        if rounded > 0:
            BUY = False
        if BUY == True:
            if b == False:
                bitold = float(Bitfinex().get_current_price())
            b = True
            update.message.reply_text('Buy Signal...')
            print(money)
            print(dec)
            print(bitold)
            print("BUY SIGNAL")
        if BUY == False:
            b = False
            update.message.reply_text('Hold Signal...')
            print(money)
            print(dec)
            print(bitold)
            print("HOLD SIGNAL")
コード例 #12
0
# Temperature (refer to gpt-2 documentation)
temperature = 1
# Multuplier/Divider for top_p/length calc.(The more words the more token learning when positive, top_p decreases.)
# Adjust in small increments. The target is between 0.6 and 1 for top_p.
mx = 1
# Virtual USD
USD = 100

# End settings
mode = False
user = ""
running = False
BUY = False
dec = float(USD)
money = float(USD)
bitold = float(Bitfinex().get_current_price())
b = False


def scrape():
    arr = []
    for tweet in get_tweets('Bitcoin', pages=1):
        a = str(tweet['time'])
        b = str(tweet['text'])
        if "http" not in b:
            if ".com" not in b:
                arr.append([a, b])
    sort = sorted(arr, key=lambda x: time.strptime(x[0], "%Y-%m-%d %H:%M:%S"))
    out = str(sort).strip('[]')
    out1 = out.replace("',", ":")
    out2 = out1.replace("']", "")
コード例 #13
0
    # login to the email server
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(email_user, email_password)

    # send email
    server.sendmail(email_from, email_to, msg)
    server.quit()


# define buy and sell threshholds for Bitcoin
buy_thresh = 4400
sell_thresh = 4400

# get Bitcoin prices
btc_sell_price = Bitfinex().get_current_bid()
btc_buy_price = Bitfinex().get_current_ask()

# Trigger Buy email if buy price is lower then threadhold
if btc_buy_price < buy_thresh:

    email_msg = """
    Bitcoin Buy Price is %s which is lower then
    threshhold price of %s.
    Good time to buy!""" % (btc_buy_price, buy_thresh)

    trigger_email(email_msg)

# Trigger sell email if sell price is higher then threashold
if btc_sell_price > sell_thresh:
コード例 #14
0
from bitrex_custom.biterx_client import BittrexClient, BittrexConfig
from koinex.koinex_client import KoinexClient, KoinexConfig
from exchanges.bitfinex import Bitfinex

CONFIG = {"BCH": "BTC-BCC", "ETH": "BTC-ETH", "XRP": "BTC-XRP"}
transaction_mode = "XRP"

VALUE = ["BTC"]
if __name__ == '__main__':

    koinex_client = KoinexClient(KoinexConfig.VALUE)

    koinex_market_values = koinex_client.get_market_value()

    for value in VALUE:
        koinex_value = koinex_market_values.get(value)
        bitfinex_client = Bitfinex()
        current_btc_value = bitfinex_client.get_current_price()
        inr_btc_value = int(current_btc_value) * 64.52
        print(koinex_value, inr_btc_value)
コード例 #15
0
def fetch():
    global price, fetched_at
    price = round(Bitfinex().get_current_price(), 2)
    fetched_at = datetime.now()
    print(f'    fetched new price: {price} ({fetched_at})')
コード例 #16
0
import itertools

from exchanges.poloniex import Poloniex
from exchanges.bitfinex import Bitfinex

pn = Poloniex()
bf = Bitfinex()

book_pn = pn.query_order_book('BTC', 'ETH')
book_bf = bf.query_order_book('ETH', 'BTC')

rows_pn = zip(book_pn['bids'], book_pn['asks'])[:10]
rows_bf = zip(book_bf['bids'], book_bf['asks'])[:10]

length = min(len(rows_bf), len(rows_pn))

print '{:>18s}{:>18s}{:>18s}{:>18s}{:>18s}{:>18s}{:>18s}{:>18s}'.format(
    'PN BID PRICE', 'PN BID AMNT', 'PN ASK PRICE', 'PN ASK AMNT',
    'BF BID PRICE', 'BF BID AMNT', 'BF ASK PRICE', 'BF ASK AMNT',
)
for i in range(length):
    print '{:18.6f}{:18.6f}{:18.6f}{:18.6f}{:18.6f}{:18.6f}{:18.6f}{:18.6f}'.format(
        float(rows_pn[i][0][0]), float(rows_pn[i][0][1]), float(rows_pn[i][1][0]), float(rows_pn[i][1][1]),
        float(rows_bf[i][0][0]), float(rows_bf[i][0][1]), float(rows_bf[i][1][0]), float(rows_bf[i][1][1]),
    )

if book_pn['asks'][0][0] < book_bf['bids'][0][0]:
    print 'Buy in PN and Sell in BF!'

if book_bf['asks'][0][0] < book_pn['bids'][0][0]:
    print 'Buy in BF and Sell in PN!'
コード例 #17
0
ファイル: zebpay.py プロジェクト: Rapternmn/Python-Scripts
import time
from exchanges.bitfinex import Bitfinex
import subprocess as s

# url_inr = "https://live.zebapi.com/api/v2/ticker?currencyCode=INR"
# url_usd = "https://live.zebapi.com/api/v2/ticker?currencyCode=USD"

url_ltc = "https://api.cryptowat.ch/markets/bitfinex/ltcusd/price"

# max_num = 820000
# min_num = 800000

# exchange_rate_orig = 74.46

curr_price_orig = int(Bitfinex().get_current_price())

min_ltc = max_ltc = 0
min_btc = max_btc = 0
init_flag = 1

curr_price_ltc = 125

while (1):
    sound_flag = 0
    # response_inr = urllib.urlopen(url_inr)
    # response_usd = urllib.urlopen(url_usd)
    response_ltc = urllib.urlopen(url_ltc)

    # data_inr = json.loads(response_inr.read())
    # data_usd = json.loads(response_usd.read())
コード例 #18
0
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.template import loader
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from itertools import chain
from exchanges.bitfinex import Bitfinex
from exchanges.coindesk import CoinDesk
from exchange.forms import ProfileForm, UserForm
from exchange.models import Transactions, Wallets, Contacts, Profile

# Fetching current price at server launch to avoid lagging
current_price_usd = Bitfinex().get_current_price()


# common class context
class WebsiteCommonMixin(generic.base.ContextMixin):
    def get_context_data(self, **kwargs):
        context = super(WebsiteCommonMixin, self).get_context_data(**kwargs)
        try:
            context.update(
                dict(contact_list=Contacts.objects.filter(
                    friend=User.objects.filter(
                        id=self.request.user.id)).order_by('-created_at')[:],
                     transaction_list=Transactions.objects.filter(
                         walletFrom=Wallets.objects.filter(
                             owner=self.request.user.id)).order_by(
                                 '-created_at')[:5],
コード例 #19
0
def commands():
    print(
        "------------------------------------\nCommands: \n'query' to fetch the answer to a question\n'time' to fetch the time \n'bitcoin' to fetch the current bitcoin price in dollars\n'speak' to make the computer say a message\n-------------------------------"
    )


#Main game loop
command = 1
commands()
while True:
    typed = input()

    #Fetches and speaks bitcoin price

    if typed == "bitcoin" and command == 1:
        variable = Bitfinex().get_current_price()
        print(variable)
        engine.say(str(variable))
        engine.runAndWait()
        commands()

    #Fetches and speaks time

    elif typed == "time" and command == 1:
        now = datetime.now()
        current_time = now.strftime("%H:%M")
        hour = now.strftime("%H")
        if int(hour) < 13:
            ampm = " AM"
            ampmsay = " Ay Em."
        else:
コード例 #20
0
ファイル: bot.py プロジェクト: andrewgazelka/UnbelievaBitcoin
 async def value(ctx):
     price = Bitfinex().get_current_price()
     priceembed = discord.Embed(title=f'**Price of 1 BTC:** {price}',
                                type='rich',
                                url='https://www.bitfinex.com/')
     await ctx.send(embed=priceembed)