Andrey Kanava
Andrey Kanava

Reputation: 57

How to make 'real-time' print in python?

my code:

import requests
from colorama import Fore
while True:
    def get_price(symbol, prices):
        for price in prices:
            if symbol == price['symbol']:
                return price['price']

    prices = requests.get('https://api.binance.com/api/v3/ticker/price').json()

    curethpriceview = get_price('ETHUSDT', prices)
    curbtcpriceview = get_price('BTCUSDT', prices)
    curdotpriceview = get_price('DOTUSDT', prices)
    curbnbpriceview = get_price('BNBUSDT', prices)
    curxrppriceview = get_price('XRPUSDT', prices)
    curlunapriceview = get_price('LUNAUSDT', prices)
    cursolpriceview = get_price('SOLUSDT', prices)
    curtrxpriceview = get_price('TRXUSDT', prices)

    print(Fore.LIGHTWHITE_EX + '***********************************')
    print(Fore.GREEN + 'current eth price:', curethpriceview)
    print(Fore.YELLOW + 'current btc price:', curbtcpriceview)
    print(Fore.BLUE + 'current dot price:', curdotpriceview)
    print(Fore.CYAN + 'current bnb price:', curbnbpriceview)
    print(Fore.MAGENTA + 'current xrp price:', curxrppriceview)
    print(Fore.LIGHTYELLOW_EX + 'current luna price:', curlunapriceview)
    print(Fore.LIGHTCYAN_EX + 'current sol price:', cursolpriceview)
    print(Fore.RED + 'current trx price', curtrxpriceview)
    print(Fore.LIGHTWHITE_EX + '***********************************')

    print(Fore.GREEN + '1-eth,', Fore.YELLOW + '2-btc,', Fore.BLUE + '3-dot,', Fore.CYAN + '4-bnb,',
          Fore.MAGENTA + '5-xrp,')
    print(Fore.LIGHTYELLOW_EX + '6-luna,', Fore.LIGHTCYAN_EX + '7-sol,', Fore.RED + '8-trx,',
          Fore.LIGHTBLUE_EX + '9-credit', Fore.RESET)

    chcur = input(': ')

i am doing trading simulator and it is a problem with current prices. To get actual price i need to restart 'while' loop. And i need to see how price changig in real time. I need something like dynamic print. Later i will do trading script with each cryptocurrency so i need input 'chcur' for selection crypto. And now i need to do 'real-time' prices. I hope i made my question more understandable. Thanks!

Upvotes: 1

Views: 140

Answers (1)

jgru
jgru

Reputation: 191

in order to solve your problem, you need concurrency, which means, that you need to retrieve the prices and calculate the price differences in parallel or at least interleaved.

Python hosts several ways to run actions in parallel or quasi parallel. The best and most elegant way to achieve this for your example is to use so-called cooperative programming with the help of Python's core library asyncio.

The following code snippet illustrates how to achieve, what you want to. It reads the pricelist in a certain interval and checks, whether the ETH to BTC conversion range changed in the meantime. If the price changed the current price is printed on stdout:

#!/usr/bin/env python3
import asyncio
import aiohttp
from colorama import Fore
from datetime import datetime

# Stores the prices retrieved last
pricelist = []


def get_price(symbol, prices):
    for price in prices:
        if symbol == price["symbol"]:
            return price["price"]


async def retrieve_pricelist(
    interval=1.0, url="https://api.binance.com/api/v3/ticker/price"
):
    global pricelist

    while True:
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                pricelist = await resp.json()
        await asyncio.sleep(interval)


async def print_price(interval=1.0):
    old_eth, cur_eth = None, None

    while True:
        old_eth, cur_eth = cur_eth, get_price("ETHBTC", pricelist)
        if old_eth != cur_eth and cur_eth:

It has the following exemplary output:

2022-01-07T12:01:58.452494      ETH price in BTC: 0.07630400
2022-01-07T12:02:00.454558      ETH price in BTC: 0.07630200
2022-01-07T12:02:02.457471      ETH price in BTC: 0.07629600
2022-01-07T12:02:03.458650      ETH price in BTC: 0.07629700
2022-01-07T12:02:06.461845      ETH price in BTC: 0.07628800
2022-01-07T12:02:07.462594      ETH price in BTC: 0.07628900

To run the script, install the library aiohttp via the help of the package manager of your choice (.e.g pip)

Please note, that clean shut-down behaviour and error checking has been omitted for the sake of brevity.

The resulting quasi parallelism is achieved by using async functions (so-called coroutines) and async libraries (like aiohttp, which are scheduled on the event loop and run basically in an interleaved manner. At every await-keyword execution is handed back to the event loop, where the next waiting task is executed until the awaited operation is ready. Note, that this only works, if no operation is "blocking".

I hope this helps to get you going.

Upvotes: 1

Related Questions