Skip to content
Advertisement

Python: get crypto pair prices from Binance API, loop pairs from file

I’m trying to get prices of crypto pairs that are on text file. The pairs are written only one pair by line, so every new line has one pair.

my code is:

from binance.client import Client

api_key="..."
api_secret="..."
client = Client(api_key, api_secret)
name = open("file.txt", "r")

def price():
    print(coin_name)
    cry_coin_price = client.get_symbol_ticker(symbol=coin_name)
    cur_price = cry_coin_price["price"]
    print(cur_price)

for x in name:
  coin_name = x
  price()

When i run this code only first pair in file is printed and then I get a lot of errors from Binance client.py, the last error is: APIError(code=-1100): Illegal characters found in parameter ‘symbol’.

When I run the code only to print pairs without getting the prices from Binance it prints the pairs with one empty line between them, so maybe that is the problem as I saw in some similar tutorials that I need to replace “n” with “”. As I’m beginner I’m not sure how to do that here if it really is that the case here.

Advertisement

Answer

Assuming that file has one coin name per line, you want something like this. Note that I’m passing the coin name in, and having it return the value. Let the caller decide what do to with the result, either printing or filing or whatever.

from binance.client import Client

api_key="..."
api_secret="..."
client = Client(api_key, api_secret)

def price(coin_name):
    crycoin_price = client.get_symbol_ticker(symbol=coin_name)
    cur_price = crycoin_price["price"]
    return cur_price

for coin_name in open("file.txt", "r"):
    coin_name = coin_name.rstrip()
    print( price(coin_name) )
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement