I am trying to connect my trading bot application to binance. However, I am getting various errors that I am sharing down below. I checked my API keys multiple times both are correct.
Traceback (most recent call last):
File “/home/arda/.local/lib/python3.10/site-packages/ccxt/base/exchange.py”, line 651, in fetch
response.raise_for_status()
File “/usr/local/lib/python3.10/dist-packages/requests/models.py”, line 960, 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=1720480926838&recvWindow=10000&signature=1acb2df04f432f370921a6f2756bacf7b675d368d1ec8860 6083d7689fd95a76
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/arda/Desktop/TradeBot/bot.py", line 92, in <module>
run()
File "/home/arda/Desktop/TradeBot/bot.py", line 75, in run
bars = exchange.fetch_ohlcv(ASSET_NAME, timeframe=TIMEFRAME, limit=FETCHING_LIMIT)
File "/home/arda/.local/lib/python3.10/site-packages/ccxt/binance.py", line 4086, in fetch_ohlcv
self.load_markets()
File "/home/arda/.local/lib/python3.10/site-packages/ccxt/base/exchange.py", line 1539, in load_markets
currencies = self.fetch_currencies()
File "/home/arda/.local/lib/python3.10/site-packages/ccxt/binance.py", line 2636, in fetch_currencies
response = self.sapiGetCapitalConfigGetall(params)
File "/home/arda/.local/lib/python3.10/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 "/home/arda/.local/lib/python3.10/site-packages/ccxt/binance.py", line 10419, in request
response = self.fetch2(path, api, method, params, headers, body, config)
File "/home/arda/.local/lib/python3.10/site-packages/ccxt/base/exchange.py", line 3752, in fetch2
raise e
File "/home/arda/.local/lib/python3.10/site-packages/ccxt/base/exchange.py", line 3743, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/home/arda/.local/lib/python3.10/site-packages/ccxt/base/exchange.py", line 667, 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 "/home/arda/.local/lib/python3.10/site-packages/ccxt/binance.py", line 10387, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "/home/arda/.local/lib/python3.10/site-packages/ccxt/base/exchange.py", line 4138, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.AuthenticationError: binance {“code”:-2015,”msg”:”Invalid API-key, IP, or permissions for action.”}
import ccxt
import pandas as pd
import datetime
import numpy as np
import secret
import supertrend as indicators
from bollinger import calculate_bollinger_bands
from ewma import calculate_ewma
from ema import calculate_ema
pd.set_option('display.max_rows', None)
import warnings
warnings.filterwarnings('ignore')
ASSET_NAME = 'BTC/USDT'
TIMEFRAME = '5m'
FETCHING_LIMIT = 1500
TRADE_SIZE = 0.0002 # ~ 10$ worth of Bitcoin right now
# Initiate our ccxt connection
exchange = ccxt.binance({
"apiKey": secret.PUBLIC_KEY,
"secret": secret.SECRET_KEY,
"options": {
"adjustForTimeDifference": True,
},
})
def in_position():
for position in exchange.fetch_positions():
if float(position['info']['size']) > 0:
return True
return False
def execute(df):
in_uptrend = df['in_uptrend'].iloc[-1]
curr_datetime = str(df['timestamp'].iloc[-1])
curr_close = df['close'].iloc[-1]
# Supertrend Strategy
if not in_position() and in_uptrend:
exchange.create_order(ASSET_NAME, 'market', 'buy', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' bought at price ' + str(curr_close) + ' (Supertrend Buy Signal)n')
elif in_position() and not in_uptrend:
exchange.create_order(ASSET_NAME, 'market', 'sell', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' sold at price ' + str(curr_close) + ' (Supertrend Sell Signal)n' + 'n')
# Bollinger Bands Strategy
if not in_position() and df['close'].iloc[-1] < df['lowerband_bb'].iloc[-1]:
exchange.create_order(ASSET_NAME, 'market', 'buy', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' bought at price ' + str(curr_close) + ' (Bollinger Bands Buy Signal)n')
elif in_position() and df['close'].iloc[-1] > df['upperband_bb'].iloc[-1]:
exchange.create_order(ASSET_NAME, 'market', 'sell', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' sold at price ' + str(curr_close) + ' (Bollinger Bands Sell Signal)n')
# EWMA Strategy
if not in_position() and df['close'].iloc[-1] > df['ewma'].iloc[-1] and df['close'].iloc[-2] <= df['ewma'].iloc[-2]:
exchange.create_order(ASSET_NAME, 'market', 'buy', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' bought at price ' + str(curr_close) + ' (EWMA Buy Signal)n')
elif in_position() and df['close'].iloc[-1] < df['ewma'].iloc[-1] and df['close'].iloc[-2] >= df['ewma'].iloc[-2]:
exchange.create_order(ASSET_NAME, 'market', 'sell', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' sold at price ' + str(curr_close) + ' (EWMA Sell Signal)n')
# EMA Strategy
if not in_position() and df['close'].iloc[-1] > df['ema'].iloc[-1] and df['close'].iloc[-2] <= df['ema'].iloc[-2]:
exchange.create_order(ASSET_NAME, 'market', 'buy', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' bought at price ' + str(curr_close) + ' (EMA Buy Signal)n')
elif in_position() and df['close'].iloc[-1] < df['ema'].iloc[-1] and df['close'].iloc[-2] >= df['ema'].iloc[-2]:
exchange.create_order(ASSET_NAME, 'market', 'sell', TRADE_SIZE)
print(curr_datetime + ', ' + ASSET_NAME + ' sold at price ' + str(curr_close) + ' (EMA Sell Signal)n')
def run():
# Fetch our Bitcoin price data (Open, High, Low, Close, Volume)
bars = exchange.fetch_ohlcv(ASSET_NAME, timeframe=TIMEFRAME, limit=FETCHING_LIMIT)
# Create our pandas data frame
df = pd.DataFrame(bars[:], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
# Calculate Supertrend
df = indicators.supertrend(df)
# Calculate other indicators
df = calculate_bollinger_bands(df)
df = calculate_ewma(df)
df = calculate_ema(df)
# Execute strategies
execute(df)
run()