簡體   English   中英

如何正確使用 Binance API 在我的代碼中執行交易?

[英]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"&timestamp={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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM