i am getting this error continuously Long condition met, entering long position
Account balance: 74.73
Leverage: 1
Trade amount: 67.257
Insufficient funds: binanceusdm {“code”:-2019,“msg”:“Margin is insufficient.”}
Current USDT balance: 74.73
this is my code, is there anyone that can help?
import ccxt
import pandas as pd
import talib
import time
import threading
import signal
api_key = ‘’
api_secret = ‘’
symbol = ‘BTC/USDT’
timeframe = ‘5m’
fast_length = 1
slow_length = 19
leverage = 10
stop_loss_percentage = 0.07
trade_percentage = 0.9
exchange = ccxt.binanceusdm({
“apiKey”: api_key,
“secret”: api_secret,
“enableRateLimit”: True,
“options”: {“adjustForTimeDifference”: True},
“timeout”: 30000
})
exchange.load_markets(True)
def fetch_data(symbol, timeframe):
data = exchange.fetch_ohlcv(symbol, timeframe)
df = pd.DataFrame(data, columns=[‘timestamp’, ‘open’, ‘high’, ‘low’, ‘close’, ‘volume’])
return df
def ema(data, length):
return data.ewm(span=length).mean()
def calculate_trade_amount(balance, leverage, trade_percentage):
trade_amount = (balance * trade_percentage) / leverage
return int(trade_amount)
def get_trade_signals(df):
df[‘fast_ema’] = ema(df[‘close’], fast_length)
df[‘slow_ema’] = ema(df[‘close’], slow_length)
long_condition = df['fast_ema'].iloc[-2] < df['slow_ema'].iloc[-2] and df['fast_ema'].iloc[-1] > df['slow_ema'].iloc[-1]
short_condition = df['fast_ema'].iloc[-2] > df['slow_ema'].iloc[-2] and df['fast_ema'].iloc[-1] < df['slow_ema'].iloc[-1]
return long_condition, short_condition
def get_av_balance(exchange):
while True:
try:
account_info = exchange.fapiPrivate_get_account()
av_balance = None
for asset in account_info["assets"]:
if asset["asset"] == "USDT":
av_balance = float(asset["availableBalance"])
if len(account_info) > 0:
av_balance = float("{:.2f}".format(av_balance))
return av_balance
except Exception as e:
print("Account Error:", e)
time.sleep(1)
pass
def close_current_position():
positions = exchange.fapiPrivateGetPositionRisk()
position = [p for p in positions if p[‘symbol’] == symbol.replace("/", “”)]
if len(position) > 0:
position = position[0]
if float(position['positionAmt']) > 0:
exchange.create_market_sell_order(symbol, float(position['positionAmt']))
elif float(position['positionAmt']) < 0:
exchange.create_market_buy_order(symbol, abs(float(position['positionAmt'])))
def main():
balance = exchange.fetch_balance()
print(“Starting USDT balance:”, balance[‘USDT’][‘free’])
# Set leverage
try:
response = exchange.fapiPrivate_post_leverage({
'symbol': symbol.replace("/", ""),
'leverage': leverage
})
if 'leverage' not in response or int(response['leverage']) != leverage:
raise ValueError("Leverage not set correctly")
print("Leverage set to:", response['leverage'])
except Exception as e:
print("Failed to set leverage:", e)
return
while True:
balance = get_av_balance(exchange) # Refresh balance on every check
min_trade_amount = exchange.market(symbol)['limits']['cost']['min']
trade_amount = calculate_trade_amount(balance, leverage, trade_percentage)
if trade_amount < exchange.market(symbol)['limits']['cost']['min']:
print("Trade amount too low, skipping this check")
time.sleep(30)
continue
df = fetch_data(symbol, timeframe)
long_condition, short_condition = get_trade_signals(df)
close_current_position()
if long_condition:
print("Long condition met, entering long position")
print("Account balance:", balance)
print("Leverage:", leverage)
print("Trade amount:", trade_amount)
try:
order = exchange.create_market_buy_order(symbol, trade_amount)
print("Order details:", order) # Print order details
# ... (rest of the long condition handling)
except ccxt.InsufficientFunds as e:
print("Insufficient funds:", e)
elif short_condition:
print("Short condition met, entering short position")
print("Account balance:", balance)
print("Leverage:", leverage)
print("Trade amount:", trade_amount)
try:
order = exchange.create_market_sell_order(symbol, trade_amount)
stop_loss_price = order['price'] * (1 + stop_loss_percentage)
exchange.create_order(symbol, 'STOP_MARKET', 'buy', trade_amount, stop_loss_price, {'stopPrice': stop_loss_price})
except ccxt.InsufficientFunds as e:
print("Insufficient funds:", e)
else:
print("No trade signal found, waiting for the next check")
if trade_amount <= min_trade_amount:
print(f"Trade amount too low ({trade_amount}), skipping this check")
time.sleep(30)
continue
if name == “main”:
main()