Retriving Coin Data with Python and Binance API
In this article, we’ll show you to to to to tell We’ll assum, that you a basic understanding of Python and the Binance API.
Prerequisites:
- You has a Binance API ky sufficient permissions.
- You has installed the
pybinance
library, it is installed via pip:
pybinance pybinance
Code Example:
import pandas as pd
import pybinance
def get_coin_data(pair):
"""
Retrieve for a specification coin pair.
Parameters:
pair (str): Coin pair (e.g. BCHUSDT-1m)
Returns:
pandas.DataFrame: Dataframe containing coin data in minute-to-minute time steps
"""
api = pybinance.create_api(key='YOUR_APIY', secret='YOUR_APICRET')
Candlestick_data = api.get_canandlestick(pair, 'minute', interval='1m').data
Create a Dataframe from the Data
df = pd.DataFrame(candlestick_data)
return df
def main():
pars = ['BCHUSDT-1m', 'BTCUSDT-1m']
Initialize an empty list
dataframes = []
for pair in pairs:
triy:
df = get_coin_data(pair)
dataframes.append(df)
Except Exception as e:
print(f"Error retrieving for {pair}: {e}))
Combine retrieved dataframes into a single csv file
output_df = pd.concat(dataframes)
output_df.to_csv('coin_data.csv', index=False)
if __name__ == '__main__':
main()
Explanation:
- We define two functions:
get_coin_data
andmain
.
- In the
get_coin_data
function, we are the Binance API to retrieve minute-to-minute candlesastics.
- We create a Dataframe from the retrieved data pandas.
- In the
main
function, weterate over the list of coin pairs and callett_coin_data
for ev. We append the dataframe to an empty listeddataframes
.
- After all pairs has been processed, we comme the
dataframes
into a single dataframe uses’concat
method.
- Finally, we save the combined dataframe to a csv file
coin_data.csv
.
Example Use Case:
Suppose you want to retrieve is hisistorial coin data for BTCUSDT-1m and BCHUSDT-1m. You would:
- Run the script in your preferred Python environment.
—
- To analyze or visualize this data, you can a pandas data data to filter and manipulate
Note: Make soer to replace YOUR_API_KEY
and YOUR_API_SECRET
wyth your actal Binance API credentials.