Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ccxt.base.errors.AuthenticationError: binance {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."} #16

Open
Petroskab opened this issue Feb 7, 2025 · 0 comments

Comments

@Petroskab
Copy link

Petroskab commented Feb 7, 2025

Hello guys, I'm new here and in programming. I need some help abouta project I work on. It's my first time working on something like that and I don't know some things. So, my problem is that I have designed a code for a crypto trading bot and I'm trying to run it but I have some problems. First of all, I use python for writing the code and I was trying to run it in Anacoda Prompt. I will have my code and errors down to check it and if anyone has an idea of what the problem might is and ways to make my code better I'll be glad to hear it! Also, the comments on the code is in greek so sorry if you find it deficult to understand the code. In addition, I alredy tried to see if I had wrong API keys but thats not the problem and I have checked all the permissions for the API keys but nothing is working and I can't understant what is it.

THE CODE:

import ccxt
import pandas as pd
import talib
from telegram import Bot
from Crypto.Cipher import AES
import base64
import os
import asyncio

Encryption of API keys

class AESCipher:
def init(self, key):
self.key = key.encode('utf-8')
self.bs = AES.block_size

def encrypt(self, raw):
    raw = self._pad(raw)
    iv = os.urandom(AES.block_size)
    cipher = AES.new(self.key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw.encode('utf-8')))

def decrypt(self, enc):
    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(self.key, AES.MODE_CBC, iv)
    return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

def _pad(self, s):
    return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

@staticmethod
def _unpad(s):
    return s[:-ord(s[len(s)-1:])]

Encryption of API keys

cipher = AESCipher('.....') # Define a secret key
encrypted_api_key = cipher.encrypt('.....')
encrypted_secret_key = cipher.encrypt('....')

Decryption of API keys

api_key = cipher.decrypt(encrypted_api_key)
secret_key = cipher.decrypt(encrypted_secret_key)

Connection with Binance

exchange = ccxt.binance({
'apiKey': api_key,
'secret': secret_key,
})

Time synchronization

exchange.load_time_difference()

Connection with Telegram

telegram_token = '...' # Αντικατέστησε με το σωστό token
chat_id = '....' # Αντικατέστησε με το σωστό chat ID
bot = Bot(token=telegram_token)

Asychronous functionfor sending a message

async def send_telegram_message(message):
await bot.send_message(chat_id=chat_id, text=message)

Test notification

asyncio.run(send_telegram_message("Το bot ξεκίνησε!"))

Data downloads

symbol = 'BTC/USDT'
timeframe = '1d'
limit = 100
ohlcv = exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])

Technical analysis

df['rsi'] = talib.RSI(df['close'], timeperiod=14)
df['macd'], df['macd_signal'], df['macd_hist'] = talib.MACD(df['close'], fastperiod=12, slowperiod=26, signalperiod=9)

Strategy

async def execute_trade(action, amount):
if action == "buy":
order = exchange.create_market_buy_order(symbol, amount)
await send_telegram_message(f"Αγορά {symbol} ποσότητας {amount}")
elif action == "sell":
order = exchange.create_market_sell_order(symbol, amount)
await send_telegram_message(f"Πώληση {symbol} ποσότητας {amount}")
return order

Risk management

async def check_risk(amount):
if amount > 100: # Αν η επένδυση είναι μεγαλύτερη από 100 ευρώ
await send_telegram_message(f"Προσοχή! Μεγάλη επένδυση: {amount} ευρώ. Επιβεβαίωση; (Απάντησε 'ok' ή 'no')")
response = input() # Εδώ θα χρησιμοποιήσεις το Telegram για να λάβεις την απάντηση
if response.lower() == 'ok':
return True
else:
return False
return True

Main logic

async def main():
for index, row in df.iterrows():
print(f"Ελέγχω γραμμή {index}: RSI = {row['rsi']}, MACD = {row['macd']}, MACD Signal = {row['macd_signal']}")

    if row['rsi'] < 30 and row['macd'] > row['macd_signal']:  # Αγορά όταν RSI < 30 και MACD > MACD Signal
        amount = 0.001  # Quantity for sale
        print(f"Συνθήκη αγοράς ικανοποιήθηκε: RSI = {row['rsi']}, MACD = {row['macd']}, MACD Signal = {row['macd_signal']}")
        if await check_risk(amount * float(row['close'])):  # Risk control
            print(f"Εκτέλεση αγοράς για {symbol} ποσότητας {amount}")
            await execute_trade("buy", amount)

    elif row['rsi'] > 70 and row['macd'] < row['macd_signal']:  # Πώληση όταν RSI > 70 και MACD < MACD Signal
        amount = 0.001  # Quantity for sale
        print(f"Συνθήκη πώλησης ικανοποιήθηκε: RSI = {row['rsi']}, MACD = {row['macd']}, MACD Signal = {row['macd_signal']}")
        if await check_risk(amount * float(row['close'])):  # Risk control
            print(f"Εκτέλεση πώλησης για {symbol} ποσότητας {amount}")
            await execute_trade("sell", amount)

    await asyncio.sleep(1)  # Wait 1 second between each repetition
print("Ο κώδικας ολοκληρώθηκε!")

Executing asychronous code

asyncio.run(main())

ERRORS:

Traceback (most recent call last):
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\base\exchange.py", line 580, in fetch
response.raise_for_status()
File "C:\ProgramData\anaconda3\Lib\site-packages\requests\models.py", line 1024, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1738938907912&recvWindow=10000&signature=1ed6cfeab6d1ced9554ef1abce990859c9cdc6079f4890afa353b717579cbc5b

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\user\crypto_bot_Corrected7test.py", line 69, in
ohlcv = exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\binance.py", line 4608, in fetch_ohlcv
self.load_markets()
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\base\exchange.py", line 1515, in load_markets
currencies = self.fetch_currencies()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\binance.py", line 2988, in fetch_currencies
promises = [self.sapiGetCapitalConfigGetall(params)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\base\types.py", line 35, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\binance.py", line 11387, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\base\exchange.py", line 4329, in fetch2
raise e
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\base\exchange.py", line 4319, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\base\exchange.py", line 596, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\binance.py", line 11355, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\ccxt\base\exchange.py", line 4715, in throw_exactly_matched_exception
raise exactstring
ccxt.base.errors.AuthenticationError: binance {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant