python-binance
** library. Here’s a step-by-step guide to building a basic bot that can place orders, monitor balances, and fetch price data.python-binance
Library**: This is the official library for interacting with the Binance API.python-binance
Librarybash
pip install python-binance
python
import os
from binance.client import Client
# Replace with your actual API key and secret or store in environment variables
API_KEY = os.getenv("BINANCE_API_KEY")
API_SECRET = os.getenv("BINANCE_API_SECRET")
client = Client(API_KEY, API_SECRET)
python
# Get current price for a symbol
symbol = "BTCUSDT"
ticker = client.get_symbol_ticker(symbol=symbol)
print(f"Current price of {symbol}: {ticker['price']}")
python
# Example of a market order
def place_market_order(symbol, quantity, side):
try:
order = client.order_market(
symbol=symbol,
side=side, # "BUY" or "SELL"
quantity=quantity
)
print("Order placed:", order)
except Exception as e:
print("An error occurred:", e)
# Example usage
place_market_order(symbol="BTCUSDT", quantity=0.001, side="BUY")
python
# Example of a limit order
def place_limit_order(symbol, quantity, price, side):
try:
order = client.order_limit(
symbol=symbol,
side=side, # "BUY" or "SELL"
quantity=quantity,
price=price
)
print("Order placed:", order)
except Exception as e:
print("An error occurred:", e)
# Example usage
place_limit_order(symbol="BTCUSDT", quantity=0.001, price="30000", side="BUY")
python
# Get account balance
def get_balance(asset):
balance = client.get_asset_balance(asset=asset)
print(f"Balance for {asset}: {balance['free']}")
# Example usage
get_balance("BTC")
get_balance("USDT")
python
import numpy as np
import pandas as pd
# Fetch historical price data
def get_historical_data(symbol, interval, limit):
klines = client.get_klines(symbol=symbol, interval=interval, limit=limit)
data = pd.DataFrame(klines, columns=[
'timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time',
'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume',
'taker_buy_quote_asset_volume', 'ignore'
])
data['close'] = data['close'].astype(float)
return data['close']
# Calculate moving averages and place orders
def moving_average_strategy(symbol, short_window, long_window):
data = get_historical_data(symbol, interval="1m", limit=long_window)
short_ma = data.rolling(window=short_window).mean()
long_ma = data.rolling(window=long_window).mean()
# Check for crossover
if short_ma.iloc[-1] > long_ma.iloc[-1] and short_ma.iloc[-2] <= long_ma.iloc[-2]:
print("Buy signal")
place_market_order(symbol, quantity=0.001, side="BUY")
elif short_ma.iloc[-1] < long_ma.iloc[-1] and short_ma.iloc[-2] >= long_ma.iloc[-2]:
print("Sell signal")
place_market_order(symbol, quantity=0.001, side="SELL")
else:
print("No signal")
# Example usage
moving_average_strategy("BTCUSDT", short_window=5, long_window=20)
python
import time
def run_bot():
while True:
try:
moving_average_strategy("BTCUSDT", short_window=5, long_window=20)
time.sleep(60) # Delay of 1 minute between checks
except Exception as e:
print("Error in bot loop:", e)
time.sleep(60) # Retry after a delay if an error occurs
# Start the bot
run_bot()