Медиа Центр

Getting Coin Data with Python and Binance API

In this article, we will show you how to use the Binance API to retrieve specific coin data minute by minute. We assume that you have a basic understanding of Python and the Binance API.

Prerequisites:

  • You have a Binance API key with sufficient permissions.
  • You have installed the pybinance library, which can be installed via pip:

pip install pybinance

Code example:

import pandas as pd

import pybinance

def get_coin_data(pair):

"""

Get data for a given coin pair.

Parameters:

pair (str): Coin pair (e.g. BCHUSDT-1m)

Returns:

pandas.DataFrame: Dataframe containing minute-by-minute coin data

"""

api = pybinance.create_api(key='YOUR_API_Key', secret='YOUR_API_SECRET')

candlestick_data = api.get_candlestick(pair, 'minute', interval='1m').data






Create a dataframe from the data

df = pd.DataFrame(candlestick_data)

return df

def main():

pairs = ['BCHUSDT-1m', 'BTCUSDT-1m']

List of coin pairs to retrieve


Initialize an empty list to store the retrieved data frames

dataframes = []

pairs pairs:

try:

df = get_coin_data(pair)

dataframes.append(df)

except exception like e:

print(f"Error retrieving data for {pair}: {e}")


Combine the retrieved data frames into a single csv file

output_df = pd.concat(dataframes)

output_df.to_csv('coin_data.csv', index=False)

if __name__ == '__main__':

main()

Explanation:

Ethereum: Retrieve all data for specific coin pair (Python-Binance API)

  • We define two functions: "get_coin_data" and "main".
  • In theget_coin_datafunction, we use the Binance API to retrieve minute-by-minute candlestick data for a given coin pair.
  • We create a data frame using pandas from the retrieved data.
  • In the main function, we iterate over the list of coin pairs and callget_coin_datafor each pair. We append the resulting data frame to an empty list calleddataframes.
  • Once all pairs have been processed, we merge thedataframesinto a single data frame using pandas'concatmethod.
  • Finally, we save the merged data frame to a csv file calledcoin_data.csv`.

Example use case:

Let’s say you want to retrieve historical coin data for BTCUSDT-1m and BCHUSDT-1m. You would:

  • Run the script in your preferred Python environment.
  • The script will download the historical minute-by-minute data from Binance for both pairs and save it to a csv file named “coin_data.csv”.
  • You can analyze or visualize this data using pandas dataframe to filter and manipulate the data as needed.

Note: Be sure to replace “YOUR_API_KEY” and “YOUR_API_SECRET” with your actual Binance API credentials.