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

Binance Api Problem #508

Open
ompandeyyy opened this issue Nov 12, 2024 · 0 comments
Open

Binance Api Problem #508

ompandeyyy opened this issue Nov 12, 2024 · 0 comments

Comments

@ompandeyyy
Copy link

Code :
import requests
import pandas as pd
import logging
import time
import hashlib
import hmac
import json

Binance API URL

BASE_URL = "https://api.binance.com" # Use this URL if you're using the Binance testnet. Change to 'https://api.binance.com' for live trading # Use this URL if you're using the Binance testnet

logging.basicConfig(filename='trading_bot.log', level=logging.INFO)

def log_trade(message):
logging.info(message)

API_KEY = "YOUR_BINANCE_API_KEY" # Replace with your actual Binance API key # Replace with your Binance API key
SECRET_KEY = "YOUR_BINANCE_SECRET_KEY" # Replace with your actual Binance Secret key # Replace with your Binance Secret key

Symbol and settings

symbol = "BTCUSDT"
interval = "1h"
investment_amount = 10 # Amount to invest per trade (in USDT)

Function to create signature

def create_signature(data):
query_string = "&".join([f"{key}={value}" for key, value in data.items()])
return hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

Function to fetch historical OHLCV data

def fetch_ohlcv(symbol, interval, limit=200):
endpoint = f"/api/v3/klines"
params = {
"symbol": symbol,
"interval": interval,
"limit": limit
}
response = requests.get(BASE_URL + endpoint, params=params)
data = response.json()
df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base', 'taker_buy_quote', 'ignore'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df['close'] = df['close'].astype(float)
return df

Technical indicator function (RSI + Moving Average Cross)

def calculate_indicators(df):
# Calculate RSI
df['rsi'] = df['close'].rolling(window=14).apply(lambda x: 100 - (100 / (1 + (x.diff().clip(lower=0).sum() / -x.diff().clip(upper=0).sum()))))
# Calculate 20-period and 50-period moving averages
df['ma20'] = df['close'].rolling(window=20).mean()
df['ma50'] = df['close'].rolling(window=50).mean()
return df

Signal generation function

def generate_signals(df):
buy_signal = (df['rsi'].iloc[-1] < 30) and (df['ma20'].iloc[-1] > df['ma50'].iloc[-1])
sell_signal = (df['rsi'].iloc[-1] > 70) and (df['ma20'].iloc[-1] < df['ma50'].iloc[-1])
return buy_signal, sell_signal

Function to fetch account balance

def fetch_balance():
# Function to fetch account balance with error handling and debug information
# Debug: Print API key to verify it's correctly loaded
print(f"Using API Key: {API_KEY}")
endpoint = "/api/v3/account"
timestamp = int(time.time() * 1000)
params = {
"timestamp": timestamp
}
signature = create_signature(params)
headers = {
"X-MBX-APIKEY": API_KEY
}
params["signature"] = signature
response = requests.get(BASE_URL + endpoint, headers=headers, params=params)
data = response.json()

# Debugging: Print response to check for issues
print(f"Balance fetch response: {data}")  # Debug print for the response from Binance

if 'balances' not in data:
    if 'code' in data and data['code'] == -2015:
        print("Invalid API key or permissions. Please check your Binance API key and its permissions.")
    print(f"Error fetching balance: {data}")  # Print the error response
    raise Exception("Failed to fetch balances from Binance")

return data

Function to place trades

def place_order(order_type, side, quantity, symbol="BTCUSDT"):
endpoint = "/api/v3/order"
timestamp = int(time.time() * 1000)
params = {
"symbol": symbol,
"side": side,
"type": "MARKET",
"quantity": quantity,
"timestamp": timestamp
}
signature = create_signature(params)
headers = {
"X-MBX-APIKEY": API_KEY
}
params["signature"] = signature
response = requests.post(BASE_URL + endpoint, headers=headers, params=params)
return response.json()

stop_loss_percentage = 0.02 # Stop-loss at 2%
profit_target_percentage = 0.05 # Take-profit at 5%

Function to implement stop-loss and take-profit

def manage_risk(entry_price, current_price, order_type, crypto_balance):
try:
if order_type == 'buy':
stop_loss_price = entry_price * (1 - stop_loss_percentage)
take_profit_price = entry_price * (1 + profit_target_percentage)
if current_price <= stop_loss_price:
place_order('sell', 'SELL', crypto_balance)
log_trade(f"Stop-loss triggered. Sold at {current_price}")
elif current_price >= take_profit_price:
place_order('sell', 'SELL', crypto_balance)
log_trade(f"Take-profit triggered. Sold at {current_price}")
elif order_type == 'sell':
stop_loss_price = entry_price * (1 + stop_loss_percentage)
take_profit_price = entry_price * (1 - profit_target_percentage)
if current_price >= stop_loss_price:
place_order('buy', 'BUY', investment_amount / current_price)
log_trade(f"Stop-loss triggered. Bought at {current_price}")
elif current_price <= take_profit_price:
place_order('buy', 'BUY', investment_amount / current_price)
log_trade(f"Take-profit triggered. Bought at {current_price}")
except Exception as e:
print(f"Error in manage_risk function: {e}")

Main trading loop

def test_api_access()
main_trading_loop(num_iterations=3):
entry_price = None
order_type = None
for _ in range(num_iterations):
try:
# Fetch market data
df = fetch_ohlcv(symbol, interval)
# Calculate technical indicators
df = calculate_indicators(df)
# Generate trading signals
buy_signal, sell_signal = generate_signals(df)
# Get balance
try:
balance = fetch_balance()
usdt_balance = float(next(item['free'] for item in balance['balances'] if item['asset'] == 'USDT'))
crypto_balance = float(next(item['free'] for item in balance['balances'] if item['asset'] == 'BTC'))
except Exception as e:
print(f"Error accessing balance data: {e}")
continue
current_price = df['close'].iloc[-1]

        # Execute trades based on signals
        if buy_signal and usdt_balance >= investment_amount:
            place_order('buy', 'BUY', investment_amount / current_price)
            log_trade(f"Buy Order Placed at {current_price} for {investment_amount} USDT")
            entry_price = current_price
            order_type = 'buy'
        elif sell_signal and crypto_balance > 0:
            place_order('sell', 'SELL', crypto_balance)
            log_trade(f"Sell Order Placed at {current_price} for {crypto_balance} BTC")
            entry_price = current_price
            order_type = 'sell'

        # Risk management
        if entry_price and order_type:
            manage_risk(entry_price, current_price, order_type, crypto_balance)

        # Sleep for a short period (for testing purposes in Jupyter)
        time.sleep(5)  # Sleep for 5 seconds (not 5 minutes)
    except Exception as e:
        print(f"Error in main loop: {e}")
        time.sleep(5)

def test_api_access():
endpoint = "/api/v3/time"
response = requests.get(BASE_URL + endpoint)
if response.status_code == 200:
print("API connection successful.")
else:
print(f"API connection failed: {response.status_code} - {response.text}")

if name == "main":
main_trading_loop(num_iterations=3)

error :
Balance fetch response: {'code': -2015, 'msg': 'Invalid API-key, IP, or permissions for action.'}
Invalid API key or permissions. Please check your Binance API key and its permissions.

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