I used your code: import time from binance.client import Client from binance.enums…
- User
I used your code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import ccxt binance_futures = ccxt.binance({ 'option': { 'defaultMarket': 'futures' } })
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date)
url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content)
API keys and other configuration
API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 100 max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback)) end_time = dt.datetime.now() query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } try: response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print('No data found for the given timeframe and symbol') return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index('Open time', inplace=True) return df except requests.exceptions.RequestException as e: print(f'Error in get_klines: {e}') return None df = get_klines('BTCUSDT', '15m', 44640)
def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2]
# Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return ""df = get_klines('BTCUSDT', '15m', 44640) def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): max_trade_quantity = None account_balance = binance_futures.fetch_balance() usdt_balance = 0 for b in account_balance['assets']: if b['asset'] == 'USDT': usdt_balance = float(b['balance']) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
- Assistant
The error message suggests that there is an issue with the
binance_futures.fetch_balance()function call, which is causing the program to crash.Here are some things you could try to troubleshoot the issue:
-
Double-check that your API keys are correct and have the necessary permissions to access your account balances.
-
Check that you have an active internet connection, as the error could be related to a timeout or connection issue.
-
Try running the
binance_futures.fetch_balance()function call outside of theorder_execution()function to see if it returns any errors. -
Check the Binance API documentation to see if there are any known issues or changes to the API that could be causing the error.
-
Consider reaching out to Binance support for assistance if you are unable to resolve the issue.
-
- User
I tryed and checked that all, but I getting this ERROR in futures order execution, please tell me my code have any issue ?
- Assistant
It's hard to say without more information about the error you're experiencing. Can you provide the exact error message or traceback?
However, here are a few potential areas to check for issues:
-
Check that your API keys have the necessary permissions to execute futures orders.
-
Make sure that you have sufficient collateral in your futures wallet to cover the margin requirements for your orders.
-
Check that the
symbolpassed to theorder_execution()function matches thesymbolvariable used in theget_klines()function. -
Double-check the parameter values passed to the
futures_create_order()function calls, such as thequantityandleverageparameters. -
Consider using try-except blocks around your futures order execution code to catch and handle any errors that may occur.
Again, without more information about the specific error message or traceback, it's challenging to provide more targeted troubleshooting advice.
-
- User
In same time my futures_position_information and futures_create_order are undefined , what I need to do ?
- Assistant
- User
But in your code fapiPrivatePOSTOrder is undefined
- Assistant
I apologize for the confusion. The correct function name is
fapiPrivate_post_order, with underscores instead of camel case.Here's the modified
order_execution()function using the correct function names: