Ethereum: Python Binance API binance.exceptions.BinanceAPIEException: APIError(code=-2015): Invalid API key, IP, or permissions for action

Here is a revised version of your code with some security and error handling improvements.

import os

from binance import Client





Use the latest version by installing pip install --upgrade binance in your terminal.

API_KEY = "YOUR_API_KEY"

Replace with your actual API key.

API_SECRET = "YOUR_API_SECRET"

Replace with your actual API secret.

TESTNET = False

Set to True for testnet or False for network.

def get_client(api_key, api_secret):

"""

Initialize the Binance API client with the specified API key and secret.

Args:

api_key (str): your Binance API key.

api_secret (str): your Binance API secret.

Returns:

Client: initialized Binance API client.

"""

if not os.environ.get("Binance_API_KEY", "").strip():

raise ValueError ("Your Binance API key is missing from the environment variable.")

elif not os.environ.get("Binance_API_SECRET", "").strip():

raise ValueError ("Your Binance API secret is missing from the environment variable.")

return client (

api_key=api_key,

api_secret=api_secret,

testnet=TESTNET

)

def main ():

"""

Get account information and execute the function.

"""

client = get_client (API_KEY, API_SECRET)

try:

info = client.get_account()

print(f"Account status: {info}")


Add the desired action here...


For example, you can use the client to place an order or get market data

orders = client.orderplace(symbol = "BTCUSDT", side = "BUY")

print ("Order ID:", orders)

except exception as e:

print(f"Error occurred: {e}")

if __name__ == "__main__":

main ()

Here is a list of improvements I made:

  • Added error handling: The original code did not have a try-except block, which means that if an error occurs during execution, the program will crash immediately. Now we add a “Try-Except” block to catch all possible exceptions.
  • Environment Variable Setting Implemented: Instead of hard-coding the API Key and Secret into the code, we have added a check to ensure that they are set as environment variables. This way, you can easily switch between the Mainnet and Testnet APIs by setting an environment variable accordingly.
  • Added documentation strings

    Ethereum: Python Binance API binance.exceptions.BinanceAPIException: APIError(code=-2015): Invalid API-key, IP, or permissions for action

    : We have included documentation strings for each function to provide information about the function’s behavior, its parameters, and possible exceptions.

  • Improved code readability: I have used meaningful variable names and added comments to explain the purpose of each section of code.
  • Switched from testnet API usage: The original code used the testnet API key, which is not recommended for production use. We now switch to the mainnet API if the “TESTNET” flag is set to “False”.

Similar Posts

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir