[英]How do I correctly use the the Binance API to execute a trade in my code?
我创建了一个 python 交易机器人,但我无法获取执行交易的代码。 仅供参考,我不是经验丰富的编码员,并且只使用计算数值解决方案。 我从未使用过 API 和 websockets,idk 如果这是正确的术语。
无论如何,我可以确认所有交易条件都执行得很好,但在运行 execute_trade() function 时会打印以下错误:
执行交易时出错:{'code': -1022, 'msg': 'Signature for this request is not valid.'}
import talib
import pandas as pd
import time
import requests
import json
import logging
import hmac
from datetime import datetime
import hashlib
from hashlib import sha256
import API
# Get current time
now = datetime.now()
# Create a logger
logging.basicConfig(filename='trading_bot.log', level=logging.INFO)
# Binance API endpoint for accessing historical data
api_endpoint = "https://api.binance.com/api/v3/klines"
# Binance API endpoint for placing trades
api_trade = "https://api.binance.com/api/v3/order"
# Binance API endpoint for checking account balance
api_balance = "https://api.binance.com/api/v3/account"
# Binance API keys
api_key = API.API_KEY
api_secret = API.API_SECRET
# Interval of historical data (1 minute)
interval = "1m"
# Currency pair
symbol = "DOGEBUSD"
# Risk management
stop_loss = 0.5 # stop loss in percentage
# Amount of currency to trade
amount = 10
# Timeframe for calculating indicators
timeframe = 30
# Parameters for Bollinger Bands
bb_window = 20
bb_deviation = 2
def hashing(query_string, secret):
return hmac.new(
secret.encode("utf-8"), query_string.encode("utf-8"), hashlib.sha256
).hexdigest()
# Function to retrieve historical data from Binance
def fetch_binance_data():
try:
params = {"symbol": symbol, "interval": interval}
data = requests.get(api_endpoint, params=params).json()
df = pd.DataFrame(data, columns=["timestamp", "open", "high", "low", "close", "volume", "close_time", "quote_asset_volume", "number_of_trades", "taker_buy_base_asset_volume", "taker_buy_quote_assure", "ignore"])
df["timestamp"] = pd.to_datetime(df["timestamp"], unit='ms')
df.set_index("timestamp", inplace=True)
df = df.astype(float)
except Exception as e:
logging.error("Error fetching data from Binance: %s", e)
df = pd.DataFrame()
return df
# Function to check account balance
def check_balance():
try:
params = {"timestamp": int(time.time()*1000)}
query_string = '&'.join([f'{k}={v}' for k, v in params.items()])
signature = hmac.new(api_secret.encode(), query_string.encode(), sha256).hexdigest()
params["signature"] = signature
headers = {"X-MBX-APIKEY": api_key}
response = requests.get(api_balance, params=params, headers=headers)
if response.status_code == 200:
balance = response.json()
print("Your current balance is: ", balance)
return balance
else:
print("Error getting balance information.")
return {}
except Exception as e:
logging.error("Error getting balance information: %s", e)
return {}
# Function to calculate indicators
def calculate_indicators(df):
try:
# Calculate Bollinger Bands
df["bb_upper"], df["bb_middle"], df["bb_lower"] = talib.BBANDS(df["close"], timeperiod=bb_window, nbdevup=bb_deviation, nbdevdn=bb_deviation)
# Calculate RSI
df["rsi"] = talib.RSI(df["close"], timeperiod=timeframe)
except Exception as e:
logging.error("Error calculating indicators: %s", e)
return df
# Global variable to store the buy price
buy_price = 0
# Function to execute trade
def execute_trade(side):
try:
params = {"symbol": symbol, "side": side, "type": "MARKET", "quantity": amount}
query_string = '&'.join([f'{k}={v}' for k, v in params.items()])
timestamp = int(time.time()*1000)
query_string += f"×tamp={timestamp}"
signature = hmac.new(api_secret.encode(), query_string.encode(), hashlib.sha256).hexdigest()
headers = {"X-MBX-APIKEY": api_key, "X-MBX-SIGNATURE": signature}
response = requests.post(api_trade, params=params, headers=headers)
if response.status_code != 200:
logging.error("Error executing trade: %s", response.json())
print("Error executing trade: ", response.json())
else:
logging.info("Trade executed successfully: %s", response.json())
price = data['close'].iloc[-1]
print("Trade executed: ", side, " at price ", price, f"at {current_time}")
except Exception as e:
logging.error("Error executing trade: %s", e)
trade_executed = False
while True:
# Retrieve historical data from Binance
# Get current time
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
data = fetch_binance_data()
# Check for enough data
if len(data) < timeframe:
print("Data insufficient")
continue
# Calculate indicators
# Indicator 1: RSI
data['RSI'] = talib.RSI(data['close'], timeperiod=14)
# Indicator 2: Bollinger Bands
data['upper'], data['middle'], data['lower'] = talib.BBANDS(data['close'], timeperiod=bb_window, nbdevup=bb_deviation, nbdevdn=bb_deviation, matype=talib.MA_Type.EMA)
price = data['close'].iloc[-1]
# Check for buy conditions
if (data['low'].iloc[-1] < data['middle'].iloc[-1] and data['RSI'].iloc[-1] < 50):
# Execute buy trade
if not trade_executed:
execute_trade("BUY")
trade_executed = True
print(f"Buy conditions triggered at {current_time} at {price}")
# Check for sell conditions
if (data['high'].iloc[-1] > data['middle'].iloc[-1] and data['RSI'].iloc[-1] > 60):
# Execute sell trade
if not trade_executed:
execute_trade("SELL")
trade_executed = True
print(f"Sell conditions triggered at {current_time} at {price}")
trade_executed = False
time.sleep(5)
# Main function
def main():
while True:
# Fetch historical data
df = fetch_binance_data()
# Check if dataframe is not empty
if not df.empty:
# Calculate indicators
df = calculate_indicators(df)
# Check trade
time.sleep(20)
if __name__ == "__main__":
main()
您应该为 Binance 交易所 REST API v3使用python-binance
Python 包装器,而不是自己编写代码。 根据包装器,您的代码似乎是正确的(也许您的默认编码不是utf-8
)。
# https://github.com/sammchardy/python-binance/blob/59e3c8045fa13ca0ba038d4a2e0481212b3b665f/binance/client.py#L219
def _generate_signature(self, data: Dict) -> str:
assert self.API_SECRET, "API Secret required for private endpoints"
ordered_data = self._order_params(data)
query_string = '&'.join([f"{d[0]}={d[1]}" for d in ordered_data])
m = hmac.new(self.API_SECRET.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256)
return m.hexdigest()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.