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' quantity = 1 symbol = 'BTC/USDT' 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()
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" end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace("/", "") # remove slash from symbol 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', 133920)
- Assistant
It seems like there are two issues with the code:
- The market symbol is not being parsed correctly. The symbol variable is set as 'BTC/USDT', however, the load_markets() function in the ccxt library uses the format 'BTCUSDT'. To fix this, you can replace the slash in the symbol variable with an empty space using:
codesymbol = symbol.replace("/", "") # remove slash from symbol- The price variable is not being initialized correctly in some cases. In the order_execution() function, the price variable is being set from the ticker dictionary. However, if the 'askPrice' key is missing from this dictionary, the price variable will not be associated with a value. To fix this, you can set a default value for the price variable before initializing it from the ticker dictionary using:
codeprice = 0 # default price if 'askPrice' in ticker: price = ticker['askPrice'] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) - User
And what do you mean in this line?Am I need to change it to symbol = symbol.replace(“BTC/USDT”, “”) # remove slash from symbol ?
- Assistant
No, you don't need to change that line to
symbol = symbol.replace("BTC/USDT", "").The
symbol = symbol.replace("/", "")line is used to remove the forward slash from thesymbolvariable, which is initially set as'BTC/USDT'. This is needed becauseload_markets()function in the ccxt library uses the symbol format without the forward slash, so 'BTC/USDT' needs to be converted to 'BTCUSDT'.The
symbol = symbol.replace("BTC/USDT", "")line you suggested would not work because it replaces the symbol string 'BTC/USDT' with an empty string, which is not what we want. We want to just remove the forward slash from the string.