Esempio n. 1
0
def index(request):
    c = CurrencyConverter()

    market = coinmarketcap.Market()
    coin = market.ticker('stellar')
    cena = coin[0]['price_usd']

    market_cap = float(coin[0]['market_cap_usd'])
    x24h_volume = float(coin[0]['24h_volume_usd'])
    x1h_change = coin[0]['percent_change_1h']
    x24h_change = coin[0]['percent_change_24h']
    x7d_change = coin[0]['percent_change_7d']
    price_btc = coin[0]['price_btc']
    rank = coin[0]['rank']

    market_cap = format(round(int(market_cap)), ',d')
    x24h_volume = format(round(int(x24h_volume)), ',d')

    cena_eur = c.convert(cena, 'USD', 'EUR')
    cena_eur = float("{0:.5f}".format(cena_eur))

    cena_yen = c.convert(cena, 'USD', 'CNY')
    cena_yen = float("{0:.5f}".format(cena_yen))

    up_green = "#2ECC40"
    down_red = "#FF4136"
    if float(x1h_change) < 0:
        change_1h = down_red
    elif float(x1h_change) > 0:
        change_1h = up_green

    if float(x24h_change) < 0:
        change_24h = down_red
    elif float(x24h_change) > 0:
        change_24h = up_green

    if float(x7d_change) < 0:
        change_7d = down_red
    elif float(x7d_change) > 0:
        change_7d = up_green

    return render(
        request, 'watcher/home.html', {
            "change_1h": change_1h,
            "change_24h": change_24h,
            "change_7d": change_7d,
            'cena': cena,
            'cena_eur': cena_eur,
            'cena_yen': cena_yen,
            'market_cap': market_cap,
            '24h_volume': x24h_volume,
            '1h_change': x1h_change,
            '24h_change': x24h_change,
            '7d_change': x7d_change,
            'price_btc': price_btc,
            'rank': rank,
            "x1h_change": x1h_change,
            "x24h_change": x24h_change,
            "x7d_change": x7d_change
        })
def get_prices_from_cmc(flat_list_of_symbols):
    """Gets prices for symbols passed in and formats correctly for API call. 

    Returns:
        List of price in USD and market cap in USD
    """
    market = coinmarketcap.Market()
    crypto_market_info = market.ticker()

    print(
        'Getting current USD price and market cap for specified crypto symbols...'
    ) if DEBUG_MODE == True else None
    values_to_write = []

    # Not the cleanest... but need to double iterate rather just checking if the symbol is
    # in the list_of_symbols because the order does matter for API call. Filter the dict first to truncate iteration size.
    filt_crypto_market_info = list(
        filter(lambda d: d['symbol'] in flat_list_of_symbols,
               crypto_market_info))
    for crypto_symbol in flat_list_of_symbols:
        for crypto_info in filt_crypto_market_info:
            if crypto_symbol == crypto_info['symbol']:
                values_to_write.append([
                    crypto_info['price_usd'], crypto_info['market_cap_usd'],
                    crypto_info['percent_change_24h'] + '%'
                ])  # need to add % for excel
                break

    print('Done.') if DEBUG_MODE == True else None
    return values_to_write
Esempio n. 3
0
    def get_ticker(self):
        """ method to get coinmarketcap tickers
        Args: None
        Returns:
            ticker_resp: list of dict, each dict contains each coin's
            data e.g. [{'24h_volume_usd': '2119330000.0',
                        'available_supply': '96373480.0',
                        'cached': False,
                        'id': 'ethereum',
                        'last_updated': '1513423457',
                        'market_cap_usd': '67667289797.0',
                        'max_supply': None,
                        'name': 'Ethereum',
                        'percent_change_1h': '0.71',
                        'percent_change_24h': '7.6',
                        'percent_change_7d': '44.6',
                        'price_btc': '0.0390053',
                        'price_usd': '702.136',
                        'rank': '2',
                        'symbol': 'ETH',
                        'total_supply': '96373480.0'}]
        """
        logger = logging.getLogger(__name__)
        logger.debug("Retrieving Coinmarketcap tickers...")
        client = coinmarketcap.Market()
        ticker_resp = client.ticker(limit=500)

        return ticker_resp
Esempio n. 4
0
 def __init__(self, init_from_file=True):
     self._market = coinmarketcap.Market()
     self._data = SortedSet()
     if init_from_file:
         for filename in os.listdir(STORAGE_DIR):
             with open(os.path.join(STORAGE_DIR, filename), 'r') as fp:
                 datapoint_list = json.load(
                     fp, object_hook=_CDPEncoder.decode_hook)
                 self._data.update(datapoint_list)
def get_ticker_update():
    global api_list_all
    global api_list_all_chunked

    logging.debug('get_ticker_update()')
    #create new API into coinmarketcap.com
    cmc_api = coinmarketcap.Market()

    #load global variable api_list_all with JSON response
    api_list_all = cmc_api.ticker(
        "", limit=API_PULL_LIMIT,
        convert='USD')  #contains the raw query data from coinmarketcap API
Esempio n. 6
0
def get_crypto_market_info(crypto_symbols):
    """Returns the pertinent information concerning the cryptos specified by the parameter symbol list."""
    market = coinmarketcap.Market()
    crypto_market_info = market.ticker(limit=10)
    string_builder = '\n'
    for currency in crypto_market_info:
        if currency["symbol"] in crypto_symbols:
            string_builder += "Name: {0}\nMarketCap: ${1:,.2f} \nPrice: ${2:,.2f} \nPercentChange(7d): {3}% \nPercentChange(24hr): {4}%\n\n".format(currency['name'],
                                                                                                                                  float(currency['market_cap_usd']),
                                                                                                                                  float(currency['price_usd']),
                                                                                                                                  currency['percent_change_7d'],
                                                                                                                                  currency['percent_change_24h'])
    return string_builder
Esempio n. 7
0
def getCoinList():
    market = coinmarketcap.Market()
    coinList = pd.DataFrame(market.ticker(limit=300)).set_index("id")
    coinList['percent_change_1h'] = coinList['percent_change_1h'].astype(float)
    coinList = coinList.sort_values('percent_change_1h',
                                    axis='index',
                                    ascending=0)
    coinList['symbol'] = '$' + coinList['symbol']
    a = [
        'symbol', 'percent_change_1h', 'percent_change_24h',
        'percent_change_7d', 'price_btc', 'price_usd', 'market_cap_usd',
        '24h_volume_usd'
    ]
    return (coinList[a])
Esempio n. 8
0
def _DownloadNewDataPoint():
    market = coinmarketcap.Market()
    cmc_dict = market.ticker(limit=0)

    with sql.GetCursor() as cursor:
        for coin in sorted(cmc_dict, key=lambda d: int(d["rank"])):
            if coin["price_usd"]:
                try:
                    cursor.execute(
                        'insert into coinhistory (symbol, price, timestamp) values '
                        '("%s", %s, %s)' % (coin["symbol"].upper(),
                                            float(coin["price_usd"].replace(
                                                ',', '')), int(time.time())))
                except Exception as e:
                    if not "Duplicate entry" in str(e):
                        raise
Esempio n. 9
0
def getPrice():

    market = coinmarketcap.Market()

    #this is a dictionary of the top 5 cryptocurrency
    #to index a specific item:
    #print(coin_dictionary["name of crypto"][0]["name of what you want to print, i.e "id"]
    coin_dictionary = {"BTC" : market.ticker("Bitcoin"),
    "ETH" : market.ticker("Ethereum"),
    "XRP" : market.ticker("Ripple"),
    "BCH" : market.ticker("bitcoin-cash"),
    "EOS" : market.ticker("EOS")}

    price_and_value_dictionary = {}
    # this loops through each key in the dictionary and retrieves the symbol and price
    # for each currency.
    for key in coin_dictionary:

        symbol = coin_dictionary[key][0]["symbol"]
        price = coin_dictionary[key][0]["price_usd"]
        price_and_value_dictionary[symbol] = float(price)
    return(price_and_value_dictionary)
Esempio n. 10
0
    def ticker(currency=None):
        """
        Retrieves data from coinmarketcap.com API using the
        coinmarketcap module and converts it into a CryptoCoinData
        instance. Returns an arrange of CryptoCoinData
        """

        try:
            results = coinmarketcap.Market().ticker()

        except:
            raise self.ERROR
            return

        data = [
            CrytoCoinData(res.get("id"), res.get("name"), res.get("symbol"),
                          res.get("price_usd"), res.get("price_btc"),
                          res.get("rank"), res.get("24h_volume_usd"),
                          res.get("percent_change_24h"),
                          res.get("available_supply")) for res in results
        ]

        return data
Esempio n. 11
0
import coinmarketcap
import json
import pandas as pd
import time
import datetime

market = coinmarketcap.Market()
coins = market.ticker()
now = datetime.datetime.now()

for i in range(96):
    #this creates a dataframe with the top 100 coins
    coinArray = pd.DataFrame([pd.Series(coins[i])
                              for i in range(100)]).set_index('id')

    #timestamps and stores the csv file
    location = 'c://Data/' + str('Cryptodata') + str(now.year) + str(
        now.month) + str(now.day) + '.csv'
    coinArray.to_csv(location)

#waits an hour until collecting data again
#not needed with cron
time.sleep(10)
#pairsedCoin = json.loads(coin)
#print(json.dumps(parsedCoin, indent=4, sort_keys=True))
Esempio n. 12
0
def cycleDownload():
    # Grabs all of the coin data available
    numCoins = 150
    numPerformers = 15
    waitPeriod = 60*60*3
    warmup = 0
    summaryFile = open("summary.txt", "w")
    dicBestPerformers ={}
    dicWorsePerformers = {}
    loopind=0

    # price_usd, price_btc, percent_change_24h, percent_change_1h
    while(1):
        # retrive data
        loopind = loopind + 1
        market = coinmarketcap.Market()
        coins = market.ticker(limit=numCoins)
        # this creates a dataframe with the top numCoins
        coinDataFrame = pd.DataFrame([pd.Series(coins[i]) for i in range(numCoins)]).set_index('id')
        coinDataFrame = coinDataFrame.apply(pd.to_numeric, errors='ignore')
        coinDataFrame = coinDataFrame.sort_values(by=['percent_change_24h'])
        currentTime = datetime.datetime.now().strftime("%Y,%m,%d,%H,%M")

        #----------------------------------------------------------------------------#
        #print top 10 worse performers:
        #----------------------------------------------------------------------------#
        stringSort ='worse,'+ currentTime
        newWorsePerformers = []
        for i in range(numPerformers):
            coinName = coinDataFrame.iloc[i].name
            coinUsdPrice=coinDataFrame.iloc[i]['price_usd']
            coinPercentageChange=coinDataFrame.iloc[i]['percent_change_24h']
            coinHourPercentageChange = coinDataFrame.iloc[i]['percent_change_1h']
            stringSort = stringSort + ',' + \
                         coinName + ',' + \
                         str(coinPercentageChange)+ ',' +\
                         str(coinUsdPrice)
            if (coinName not in dicWorsePerformers and loopind>warmup):
                print("New worse performer found", coinName,coinPercentageChange, coinPercentageChange)
                newWorsePerformers.append([coinName,coinPercentageChange, coinHourPercentageChange, coinUsdPrice])

            dicWorsePerformers[coinName] = coinUsdPrice

        # print ot console worse performers
        print(stringSort)
        summaryFile.write(stringSort+'\n')
        summaryFile.flush()

        #----------------------------------------------------------------------------#
        #print top 10 best performers
        #----------------------------------------------------------------------------#
        stringSort='best,'+ currentTime
        newBestPerformers=[]
        for i in range(numCoins-1,numCoins-numPerformers-1, -1):
            coinName = coinDataFrame.iloc[i].name
            coinUsdPrice=coinDataFrame.iloc[i]['price_usd']
            coinPercentageChange=coinDataFrame.iloc[i]['percent_change_24h']
            coinHourPercentageChange = coinDataFrame.iloc[i]['percent_change_1h']
            stringSort = stringSort + ',' + \
                         coinName + ',' + \
                         str(coinPercentageChange)+ ',' +\
                         str(coinUsdPrice)
            if (coinName not in dicBestPerformers and loopind>warmup):
                print("New best performer found ", coinName, coinPercentageChange, coinPercentageChange)
                newBestPerformers.append([coinName,coinPercentageChange, coinHourPercentageChange, coinUsdPrice])

            dicBestPerformers[coinName] = coinUsdPrice

        # print ot console best performers
        print(stringSort)
        summaryFile.write(stringSort+'\n')
        summaryFile.flush()

        #----------------------------------------------------------------------------#
        # send an email with the stats
        #----------------------------------------------------------------------------#
        #send email with the best performes
        text=''
        if(newBestPerformers):
            text ='The new best performers are (name, 24%, 1%, price Usd)'+ '\n'
            newBestPerformers.sort(key = lambda l: (l[2], l[1]))
            for coin in newBestPerformers:
                text = text+ \
                       ' ' + str(coin[0]) +  \
                       ' ' + str(coin[1]) + \
                       ' ' + str(coin[2]) + \
                       ' ' + str(coin[3]) + '\n'
        #send email with the worse performes
        if (newWorsePerformers):
            text = text + '\n' + 'The new worse performers are (name, 24%, 1%, price Usd)'+ '\n'
            newWorsePerformers.sort(key=lambda l: (l[2], l[1]))
            for coin in newWorsePerformers:
                text = text+ \
                       ' ' + str(coin[0]) +  \
                       ' ' + str(coin[1]) + \
                       ' ' + str(coin[2]) + \
                       ' ' + str(coin[3]) + '\n'

        if(text):
            sendEmail("Market check", text)

        # timestamps and stores the csv file
        currentTimeFile = datetime.datetime.now().strftime("%Y-%m-%d_%H%M")
        coinDataFrame.to_csv(str(currentTimeFile) + '.csv')
        coinDataFrame.to_pickle(str(currentTimeFile) + '.pkl')

        # waits an hour until collecting data again
        time.sleep(waitPeriod)

    summaryFile.close()
Esempio n. 13
0
def coin_names():
    obj = cmc.Market()
    data = obj.ticker()
    return [coin['id'] for coin in data]
Esempio n. 14
0
def collect_data(n=10):
    obj = cmc.Market()
    data = obj.ticker(limit=10)
    return data
Esempio n. 15
0
#!/usr/bin/env python
# NOTE: Python 3 6 is required
import curses, datetime, coinmarketcap, pickle, sys, threading, time, traceback
from collections import defaultdict

cmc = coinmarketcap.Market()
histories = defaultdict(list)  # A map of form: "CUR1/CUR2": [CONVERSION...]
histfile = "/tmp/cmchistory.pickle"
last, updated = datetime.datetime.now(), []

pairs = (
    "bitcoin/ethereum",
    "bitcoin/litecoin",
    "ethereum/litecoin",
    "nano/decred",
)


def tick(c1, c2):
    ct1 = cmc.ticker(c1)[0]
    ct2 = cmc.ticker(c2)[0]
    forward = float(ct1["price_usd"]) / float(ct2["price_usd"])
    timestamp = datetime.datetime.fromtimestamp(int(ct1["last_updated"]))
    ticker = f"{c1}/{c2}"
    # Only add changed values.
    try:
        if str(forward) == str(histories[ticker][-1][1]):
            return
    except IndexError:
        pass
    global updated
Esempio n. 16
0
def coin_market(request):
    api = coinmarketcap.Market()
    return api.ticker(request)
Esempio n. 17
0
    def __test_strategies(self, market_data):
        """Test the strategies and perform notifications as required

        Args:
            market_data (dict): A dictionary containing the market data of the symbols to analyze.
        """

        channels = ['UCLXo7UDZvByw2ixzpQCufnA',
        'UCTKyJALgd09WxZBuWVbZzXQ',
        'UCmA06PHZc6O--2Yw4Vt4Wug',
        'UCkpMhY4N4ZjpqKMIjzLplKw',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UC67AEEecqFEc92nVvcqKdhA',
        'UCTKyJALgd09WxZBuWVbZzXQ',
        'UCmaAtMHgspY0au0NR5oz8PA',
        'UCt_oM56Ui0BCCgi0Yc-Wh3Q',
        'UCcx5piGsKocIXdgnEIASKFA',
        'UCLnQ34ZBSjy2JQjeRudFEDw',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UCCoF3Mm-VzzZXSHtQKD8Skg',
        'UCEhFzdgTPR8MmeL0z-xbA3g',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UCkpt3vvZ0Y0wvTX2L-lkxsg',
        'UCLXo7UDZvByw2ixzpQCufnA',
        'UCv6-ssVyI8zNcZsghkwudHA',
        'UCUullOp2tc92dsu-yW3p_0g',
        'UC-f5nPBEDyUBZz_jOPBwAfQ',
        'UCu7Sre5A1NMV8J3s2FhluCw']

        #twitter_sentiment = self.sentiment_analyzer.analyze_twitter_sentiment(market_data[exchange][market_pair]['symbol'])

        
        symbols = []
        symbol_name = {}
        name_symbol = {}
        #get all coins from coinmarketcap
        coinmarketcapTicker = coinmarketcap.Market()
        coins = coinmarketcapTicker.ticker()
        

        for exchange in market_data:
            print(exchange)
            print(self.exchange_interface.fetch_balance())
            if exchange == "binance":
                 
                
                for market_pair in market_data[exchange]:
                    #print(market_data[exchange][market_pair])
                    symbols.append(market_data[exchange][market_pair]['info']['symbol'])
                    symbol = market_data[exchange][market_pair]['info']['baseAsset']
                    #print(symbol)
                    #lookup altcoin name by altcoin symbol
                    for coin in coins:
                        #print(coin['symbol'])
                        #print(coin['name'])
                        if coin['symbol'] == symbol:
                            name = coin['name'].lower()
                            name_symbol[name] = symbol
                            symbol_name[symbol] = name
                            #print(name)

                    
                    #name = market_data[exchange][market_pair]['info']['MarketCurrencyLong'].lower()
                    
                    
                #print(symbol_name)
                #print(name_symbol)
                
                try:

                    youtube_sentiment = self.sentiment_analyzer.analyze_youtube_sentiment(channels,symbols,symbol_name,name_symbol)
                    #print(youtube_sentiment)

                    for coin in youtube_sentiment:
                        print(coin)
                        print(youtube_sentiment.count(coin))
                    #sentiment_payload = {'exchange': exchange,'symbol': symbol,'volume_free': 0,'volume_used': 0,'volume_total': 0}

                    #self.db_handler.create_youtubesentiment(sentiment_payload)
                except Exception as e:
                    print(e)
Esempio n. 18
0
Created on Feb 19, 2018

@author: Spare
'''
from google.cloud import bigquery
import pandas as pd
import pandas_gbq as gbq
import Queue
import threading
import logging
import time
import datetime
import coinmarketcap as cmc
import schedule

market = cmc.Market()


def timenow():
    currenttimestr = "{:%Y-%m-%d %H:%M}".format(datetime.datetime.now())
    return currenttimestr


def get500t(q, qout, logger):
    args = q.get()
    # Reference API call: market.ticker('?start=0&limit=100')
    connected = False
    while connected == False:
        try:
            data = market.ticker('?start={0}&limit={1}'.format(
                args[0], args[1]))
def coinmarketdata():

    count = 5
    import coinmarketcap
    import json
    import pandas as pd
    import time
    import pickle
    import os.path
    import timeit
    start_time = timeit.default_timer()

    market = coinmarketcap.Market()
    coin = market.ticker(limit=0)

    parsedCoin = json.loads(json.dumps(coin))
    parsedCoin = json.dumps(parsedCoin, indent=4, sort_keys=True)
    df = pd.read_json(parsedCoin)
    df_sort_change1h = df.sort_values(by=['percent_change_1h'],
                                      ascending=False)
    #print(df_sort_change1h)

    import requests
    import datetime
    from datetime import datetime
    markets = requests.get('https://www.coinexchange.io/api/v1/getmarkets')
    markets_pandas = pd.read_json(markets.text)
    markets_result = markets_pandas['result']
    markets_df = pd.Series.to_frame(markets_result)
    markets_panel = pd.Panel(
        {'markets': markets_df['result'].apply(pd.Series)})
    markets = markets_panel.markets
    #print(markets)

    market_id = markets['MarketID']

    if os.path.isfile('coinoutput.pkl') == True:
        with open('coinoutput.pkl', 'rb') as f:
            lastprice, pricechange24hr, pricechange, volume, buyorderscount, sellorderscount, tradecount24hr, highprice, lowprice, buyorder24hr, sellorder24hr = pickle.load(
                f)
    else:
        lastprice = [None] * 12
        pricechange = [None] * 12
        volume = [None] * 12
        buyorderscount = [None] * 12
        sellorderscount = [None] * 12

    coinanalysis = dict()
    buytradedensity = dict()
    selltradedensity = dict()

    for index, row in markets.iterrows():
        if row['Active'] == True and row['BaseCurrencyCode'] == 'BTC':
            marketid = row['MarketID']

            lastprice2 = lastprice

            assetname = row['MarketAssetName']
            coinanalysis[assetname] = []

            lastprice = [lastprice[-1]] + lastprice[:-1]
            volume = [volume[-1]] + volume[:-1]
            buyorderscount = [buyorderscount[-1]] + buyorderscount[:-1]
            sellorderscount = [buyorderscount[-1]] + buyorderscount[:-1]

            marketsummary = requests.get(
                'https://www.coinexchange.io/api/v1/getmarketsummary?market_id='
                + str(marketid))
            marketsummary_pandas = pd.read_json(marketsummary.text)
            marketsummary_result = marketsummary_pandas['result']

            lastprice[0] = marketsummary_result["LastPrice"]
            volume[0] = marketsummary_result["Volume"]

            for i in range(0, len(lastprice)):
                if (lastprice2[i] != None) & (lastprice[i] != None):
                    pricechange[i] = (
                        (lastprice[i] - lastprice2[i]) / lastprice2[i]) * 100
                else:
                    pricechange[i] = None

            tradecount24hr = marketsummary_result["TradeCount"]
            highprice = marketsummary_result["HighPrice"]
            lowprice = marketsummary_result["LowPrice"]
            pricechange24hr = marketsummary_result["Change"]
            buyorder24hr = marketsummary_result["BuyOrderCount"]
            sellorder24hr = marketsummary_result["BuyOrderCount"]

            orders = requests.get(
                'https://www.coinexchange.io/api/v1/getorderbook?market_id=' +
                str(marketid))
            orders_pandas = pd.read_json(orders.text)
            buyorders_result = orders_pandas['result']['BuyOrders']
            if len(buyorders_result) != 0:
                buyorders_df = pd.DataFrame({'buyorders': buyorders_result})
                buyorders_panel = pd.Panel(
                    {'buyorders': buyorders_df['buyorders'].apply(pd.Series)})
                buyorders = buyorders_panel.buyorders
                buyorders['market_id'] = marketid
                buyorders = buyorders.sort_values(by=['OrderTime'],
                                                  ascending=False)
                buyorders = buyorders.reset_index(drop=True)

                utcnow = datetime.utcnow()
                utchour = utcnow.hour
                utcminute = utcnow.minute
                utcsecond = utcnow.second
                utctime = str(utchour) + ':' + str(utcminute) + ':' + str(
                    utcsecond)

                utcday = utcnow.day
                utcmonth = utcnow.month
                utcyear = utcnow.year
                utcdate = str(utcyear) + '-' + str(utcmonth) + '-' + str(
                    utcday)

                buyordercount = 0
                for index, row in buyorders.iterrows():
                    dayelapse = datetime.strptime(
                        utcdate, '%Y-%m-%d') - datetime.strptime(
                            row['OrderTime'].split(' ')[0], '%Y-%m-%d')
                    timeelapse = datetime.strptime(
                        utctime, '%H:%M:%S') - datetime.strptime(
                            row['OrderTime'].split(' ')[1], '%H:%M:%S')
                    if timeelapse.seconds <= 300 & dayelapse.days == 0:
                        buyordercount = +1

                nooforders = buyorders.shape[0]
                orderdate = datetime.strptime(
                    buyorders['OrderTime'][0].split(' ')[0],
                    '%Y-%m-%d') - datetime.strptime(
                        buyorders['OrderTime'][nooforders - 1].split(' ')[0],
                        '%Y-%m-%d')
                ordertime = datetime.strptime(
                    buyorders['OrderTime'][0].split(' ')[1],
                    '%H:%M:%S') - datetime.strptime(
                        buyorders['OrderTime'][nooforders - 1].split(' ')[1],
                        '%H:%M:%S')
                buytradedensity[marketid] = [
                    orderdate.days, ordertime.seconds, nooforders,
                    markets[markets.MarketID == marketid]
                    ['MarketAssetName'].iloc[0], markets[
                        markets.MarketID == marketid]['BaseCurrency'].iloc[0]
                ]

            buyorderscount[0] = buyordercount

            sellorders_result = orders_pandas['result']['SellOrders']
            if len(sellorders_result) != 0:
                sellorders_df = pd.DataFrame({'sellorders': sellorders_result})
                sellorders_panel = pd.Panel({
                    'sellorders':
                    sellorders_df['sellorders'].apply(pd.Series)
                })
                sellorders = sellorders_panel.sellorders
                sellorders['market_id'] = marketid
                sellorders = sellorders.sort_values(by=['OrderTime'],
                                                    ascending=False)
                sellorders = sellorders.reset_index(drop=True)

                utcnow = datetime.utcnow()
                utchour = utcnow.hour
                utcminute = utcnow.minute
                utcsecond = utcnow.second
                utctime = str(utchour) + ':' + str(utcminute) + ':' + str(
                    utcsecond)

                utcday = utcnow.day
                utcmonth = utcnow.month
                utcyear = utcnow.year
                utcdate = str(utcyear) + '-' + str(utcmonth) + '-' + str(
                    utcday)

                sellordercount = 0
                for index, row in sellorders.iterrows():
                    dayelapse = datetime.strptime(
                        utcdate, '%Y-%m-%d') - datetime.strptime(
                            row['OrderTime'].split(' ')[0], '%Y-%m-%d')
                    timeelapse = datetime.strptime(
                        utctime, '%H:%M:%S') - datetime.strptime(
                            row['OrderTime'].split(' ')[1], '%H:%M:%S')
                    if timeelapse.seconds <= 300 & dayelapse.days == 0:
                        sellordercount = +1

                nooforders = sellorders.shape[0]
                orderdate = datetime.strptime(
                    sellorders['OrderTime'][0].split(' ')[0],
                    '%Y-%m-%d') - datetime.strptime(
                        sellorders['OrderTime'][nooforders - 1].split(' ')[0],
                        '%Y-%m-%d')
                ordertime = datetime.strptime(
                    sellorders['OrderTime'][0].split(' ')[1],
                    '%H:%M:%S') - datetime.strptime(
                        sellorders['OrderTime'][nooforders - 1].split(' ')[1],
                        '%H:%M:%S')
                selltradedensity[marketid] = [
                    orderdate.days, ordertime.seconds, nooforders,
                    markets[markets.MarketID == marketid]
                    ['MarketAssetName'].iloc[0], markets[
                        markets.MarketID == marketid]['BaseCurrency'].iloc[0]
                ]

            sellorderscount[0] = sellordercount

            coinanalysis[assetname].extend(lastprice)
            coinanalysis[assetname].append(pricechange24hr)
            coinanalysis[assetname].extend(pricechange)
            coinanalysis[assetname].extend(volume)
            coinanalysis[assetname].extend(buyorderscount)
            coinanalysis[assetname].extend(sellorderscount)
            coinanalysis[assetname].append(tradecount24hr)
            coinanalysis[assetname].append(highprice)
            coinanalysis[assetname].append(lowprice)
            coinanalysis[assetname].append(buyorder24hr)
            coinanalysis[assetname].append(sellorder24hr)

    buytradedensity = pd.DataFrame.from_dict(buytradedensity, orient='index')
    buytradedensity.columns = [
        'days', 'seconds', 'buyorders', 'assetname', 'baseprice'
    ]
    buytradedensity = buytradedensity.sort_values(
        by=['buyorders', 'days', 'seconds'], ascending=[False, True, True])
    buytradedensity = buytradedensity.reset_index(drop=True)

    selltradedensity = pd.DataFrame.from_dict(selltradedensity, orient='index')
    selltradedensity.columns = [
        'days', 'seconds', 'buyorders', 'assetname', 'baseprice'
    ]
    selltradedensity = selltradedensity.sort_values(
        by=['buyorders', 'days', 'seconds'], ascending=[False, True, True])
    selltradedensity = selltradedensity.reset_index(drop=True)
    #print(tradedensity)

    with open('coinoutput.pkl', 'wb') as f:
        pickle.dump((lastprice, pricechange24hr, pricechange, volume,
                     buyorderscount, sellorderscount, tradecount24hr,
                     highprice, lowprice, buyorder24hr, sellorder24hr), f, -1)

    coinanalysis = pd.DataFrame.from_dict(coinanalysis, orient='index')
    coinanalysis.columns = [
        'LP5', 'LP10', 'LP15', 'LP20', 'LP25', 'LP30', 'LP35', 'LP40', 'LP45',
        'LP50', 'LP55', 'LP60', '24hr Price Change', 'PC5', 'PC10', 'PC15',
        'PC20', 'PC25', 'PC30', 'PC35', 'PC40', 'PC45', 'PC50', 'PC55', 'PC60',
        'V5', 'V10', 'V15', 'V20', 'V25', 'V30', 'V35', 'V40', 'V45', 'V50',
        'V55', 'V60', 'BO5', 'BO10', 'BO15', 'BO20', 'BO25', 'BO30', 'BO35',
        'BO40', 'BO45', 'BO50', 'BO55', 'BO60', 'SO5', 'SO10', 'SO15', 'SO20',
        'SO25', 'SO30', 'SO35', 'SO40', 'SO45', 'SO50', 'SO55', 'SO60',
        '24hr Trade count', 'High Price 24hr', 'Low Price 24hr',
        'Buy Order 24hr', 'Sell Order 24hr'
    ]

    #print(coinanalysis)

    if count % 60 == 0:
        writer = pd.ExcelWriter('output' + str(utcnow).replace(':', '') +
                                '.xlsx')
        print('saved')
        coinanalysis.to_excel(writer, 'Sheet1')
        writer.save()
    else:
        count += 5

    elapsed = timeit.default_timer() - start_time
    print('timeofexecution', elapsed)

    time.sleep(10)
Esempio n. 20
0
def syncCMCMarkets():
    caps = coinmarketcap.Market()
    caps.ticker()
    caps.ticker("BTC", limit=3, convert='EUR')