-3

At this point in my development I am trying to gather market data for more than one currency every 10 seconds and filter out only price, time, and currency name and put it in a dataframe. Here is my code so far:

import websocket, json, pandas as pd

def on_open(ws):
    print("The Socket is Opened")
    subscribe_message = { 'type': 'subscribe',
        'channels':[
            {'name':'ticker',
            'product_ids':['BTC-USD','ETH-USD','ATOM-USD']}
        ]
    }
    ws.send(json.dumps(subscribe_message))



def on_message(ws, message):
    data = json.loads(message)
    df = createframe(data)
    time.sleep(10)
    print(df)



def createframe(msg):
    df = pd.DataFrame([msg])
    df = df.loc[:,['product_id','price','time']]
    df.columns = ['Crypto','Price','Time']
    return df




 socket = "wss://ws-feed.pro.coinbase.com"

 ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)
 ws.run_forever()

My result is good but not entirely what I want. It gives me a new dataframe every 10 seconds but only has one crypto in it, I would like to have all 3. I also have another program that compiles all three cryptos onto one neat dataframe but it only does it once per execution, I will post that as well in case someone can just loop it or something.

import cbpro
import pandas as pd
c = cbpro.PublicClient()

BTCTicker = c.get_product_ticker('BTC-USD')
ETHTicker = c.get_product_ticker('ETH-USD')
ATOMTicker = c.get_product_ticker('ATOM-USD')
BTCPrice = (BTCTicker['price'])
ETHPrice = (ETHTicker['price'])
ATOMPrice = (ATOMTicker['price'])
BTCTime = (BTCTicker['time'])
ETHTime = (ETHTicker['time'])
ATOMTime = (ATOMTicker['time'])

Data = { 
    'Price': [BTCPrice, ETHPrice, ATOMPrice],
    'Time': [BTCTime, ETHTime, ATOMTime]
}

Row_Labels= ['Bitcoin', 'Ethereum', 'Cosmos']

df = pd.DataFrame(data=Data, index=Row_Labels)
print(df)

Thanks for any help!

  • 1
    For your 10 seconds, an easy solution is to add a `time.sleep(10)` between calls. – echefede Feb 07 '22 at 19:57
  • @echefede Thank you for that, I added that and now it will show me one crypto on a dataframe every 10 seconds. Any idea how I could implement this into my second program to repeatedly call every 10 seconds for all 3? – ayden stacy Feb 07 '22 at 20:27
  • @PřemyslŠťastný Editied. – ayden stacy Feb 07 '22 at 21:09

1 Answers1

0

I Dont have much to offer much other than you might enjoy a look at asynco library, its daughting but its not hard once you get into it

other than that you might want to look into making the "" get ticker"" block into somthing like

markets = ['BTC-USD','ETH-USD','ATOM-USD']

for cur_market in markets: 
    ticker = c.get_product_ticker(cur_market)
    price = ticker['price']
    time =  ticker['time']
....
Dharman
  • 30,962
  • 25
  • 85
  • 135
will floyd
  • 11
  • 4