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:
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 datadf = 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 framesdataframes = []
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 fileoutput_df = pd.concat(dataframes)
output_df.to_csv('coin_data.csv', index=False)
if __name__ == '__main__':
main()
Explanation:
function, we use the Binance API to retrieve minute-by-minute candlestick data for a given coin pair.
for each pair. We append the resulting data frame to an empty list called
dataframes.
into a single data frame using pandas'
concatmethod.
Example use case:
Let’s say you want to retrieve historical coin data for BTCUSDT-1m and BCHUSDT-1m. You would:
Note: Be sure to replace “YOUR_API_KEY” and “YOUR_API_SECRET” with your actual Binance API credentials.