I used this code: import time from binance.client import Client from binance.enums…
- User
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import ccxt
Get the current time and timestamp
now = dt.datetime.now() date = now.strftime("%m/%d/%Y %H:%M:%S") print(date)
timestamp = int(time.time() * 1000)
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 binance_futures = ccxt.binance({ 'apiKey': '', 'secret': '', 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } })
binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } })
Load the market symbols
markets = binance_futures.load_markets()
symbol = 'BTC/USDT' if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market")
Get server time and time difference
def get_server_time(exchange): server_time = exchange.fetch_time() return server_time
def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference
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(symbol, '1m', 44640)
- Assistant
The error occurs because the
current_positionvariable is None, meaning there is no existing position for thesymbolbeing traded. Therefore, when checking thepositionAmtkey in thecurrent_positiondictionary, aTypeErroris raised because you cannot subscript a NoneType object.To fix this, you should add a check for None before accessing the
positionAmtkey. For example:current_position = None positions = binance_futures.fapiPrivateGetPositionRisk() for position in positions: if position["symbol"] == symbol: current_position = position if current_position is not None and current_position["positionAmt"] != 0: binance_futures.fapiPrivatePostOrder( symbol=symbol, side='SELL' if current_position["positionSide"] == "LONG" else 'BUY', type='MARKET', quantity=abs(float(current_position["positionAmt"])), positionSide=current_position["positionSide"], reduceOnly=True )This will skip the order execution code if there is no existing position for the symbol being traded.
- User
Now I getting another ERROR: 06/03/2023 15:49:25 BTC/USDT found in the market Error in get_klines: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/klines?symbol=BTC/USDT&interval=1m&startTime=2023-05-03%2015:49:30.545966&endTime=2023-06-03%2015:49:30.545966 Error in get_klines: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/klines?symbol=BTC/USDT&interval=1m&startTime=2023-05-03%2015:49:31.613408&endTime=2023-06-03%2015:49:31.613408 Error in get_klines: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/klines?symbol=BTC/USDT&interval=1m&startTime=2023-05-03%2015:49:32.679802&endTime=2023-06-03%2015:49:32.679802 The signal time is: 2023-06-03 15:49:33 : Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 224, in order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 193, in order_execution take_profit_price = round_step_size(price * (1 - take_profit_percentage / 100), step_size=step_size) ^^^^^ UnboundLocalError: cannot access local variable 'price' where it is not associated with a value
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.