I am stuck on this script, need help plz!!!

I’m new to Python but managed to write a script with the help of ChatGPT. The script is designed to trade on Binance Futures using an algorithm based on Bollinger Bands. However, I’m encountering a persistent issue. Every time the script tries to open a position, I get the following error:

Error al abrir posición corta: binanceusdm {“code”:-4164,“msg”:“Order’s notional must be no smaller than 100 (unless you choose reduce only).”}

Here is the log output from my script:

2024-12-24 12:39:41 - Price: 98063.90
BB Low: 97075.389890, BB High: 98054.610110
Balance: 226.97 USDT, Position: none
Condition to open SHORT met.
Leverage set to 5x for BTC/USDT.
Calculated quantity: 0.001736 BTC (notional: 170.23 USD).
Error al abrir posición corta: binanceusdm {“code”:-4164,“msg”:“Order’s notional must be no smaller than 100 (unless you choose reduce only).”}

Details of the Setup:

Leverage: 5x
Symbol: BTC/USDT
Balance: 226.97 USDT
Calculated notional: 170.23 USD (which should exceed the 100 USD minimum).

What I’ve Tried So Far:

Verified the calculated notional exceeds the minimum required by Binance (100 USD).
Adjusted the quantity to ensure it complies with the market's minQty and stepSize.
Confirmed that leverage is being set correctly (5x) before placing the order.
Ensured that there are no unnecessary reduceOnly flags in the order.

Issue:

Despite all this, the script still fails with the same error, even though the calculated notional is above 100 USD.
Request:

I would appreciate any insights or suggestions to debug and resolve this issue. Is there something specific to Binance Futures that I might be overlooking? Could this be related to account settings, market conditions, or something else?

Thank you in advance for your help!

What’s the full request? The error is pretty straightforward (notional being less than 100), likely the program is sending less than 100 even though it’s reporting 170.23

Try printing out the full request link.

For example on python you can try via the Binance lib:

Try using that with manual parameters and see if it works. Or provide the full request link, for example:
https://fapi.binance.com/fapi/v1/order?symbol=BTCUSDT&side=SELL&positionSide=SHORT&type=MARKET&quantity=0.01&timestamp={{timestamp}}&signature={{signature}}

Hi Arcamus,

Thank you for your valuable suggestions. I’ve made several adjustments to the script following your recommendations, and I’d like to share the changes implemented so far for your review. I’m currently testing the latest version of the bot and will update you with results throughout the day.

  1. Debugging Enhancements

    I’ve added a detailed log that prints all the key parameters of the bot in each iteration. This includes the current price, Bollinger Bands (high, low, and average), balance, position status, calculated notional, and any warnings or errors encountered.

New log generated by the script:

2024-12-25 14:02:08 - Details:

  • Current Price: 98429.20
  • BB Low: 98121.35, BB High: 98713.68
  • BB Average: 98417.51
  • USDT Balance: 226.97
  • BTC Balance: 0.000000
  • Current Position: none
  • Position Size: 0.000000
  • Timeframe: 15m, Leverage: 5x, Stop-Loss: 15.0%

Additionally, if a warning or error occurs, the log includes the related message. For example:

Warning: Time difference is high (-1398 ms). Please verify your system clock.
Error fetching OHLCV data: binanceusdm {“code”:-1021,“msg”:“Timestamp for this request was 1000ms ahead of the server’s time.”}

  1. Time Synchronization

    I implemented a function that syncs the local time with Binance’s server at startup and at regular intervals. Since this adjustment, the {“code”:-1021} timestamp error has not reappeared. However, the bot does issue a warning if the time difference exceeds 1000 ms.

Relevant Code: Time Synchronization

def sync_time_with_binance():
server_time = exchange.fetch_time()
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
print(f"Time synchronized with Binance: Difference of {time_difference} ms.“)
if abs(time_difference) > 1000:
print(f"Warning: Time difference is high ({time_difference} ms). Please verify your system clock.”)
return time_difference

  1. User-Defined Parameters

    At startup, the bot prompts the user to input leverage, timeframe, and Stop-Loss percentage. This allows greater flexibility in tailoring the strategy.

Relevant Code: User Input

def get_user_settings():
lev = int(input("Enter leverage level (e.g., 5): "))
stop_loss_pct = float(input("Enter Stop-Loss percentage (e.g., 0.15 for 15%): "))
timeframe = input("Enter timeframe (e.g., 15m, 5m, 1h): ").lower()
return lev, stop_loss_pct, timeframe

  1. Notional Validation

    The script now validates the notional before submitting the order and logs a message if it is below the 100 USD threshold.

Relevant Code: Notional Validation

def calculate_order_amount(price):
usdt_balance, _, _, _ = get_balance_and_positions()
usdt_to_use = usdt_balance * 0.75
order_amount = usdt_to_use / price
notional = order_amount * price
print(f"Calculated amount: {order_amount:.6f} BTC (Notional: {notional:.2f} USD).“)
if notional < 100:
print(f"Error: Insufficient notional ({notional:.2f} USD). Minimum required is 100 USD.”)
return order_amount

Current Behavior

The bot now generates a comprehensive and detailed log in each iteration, enabling us to analyze all key parameters.
Time synchronization seems to have resolved the timestamp issue, and there are no recent errors related to notional validation.
I am still testing how the bot performs under various market conditions.

Questions

Do you think the current log is sufficient for thorough analysis, or would you recommend adding more details?
Based on the shared code fragments, do you notice any further adjustments we should make?
Is there anything else we should monitor or validate to ensure the bot functions correctly?

I greatly appreciate any feedback or additional suggestions you can provide. I’ll keep you updated on the test results throughout the day.

Best regards,
Daniel

Hi Arcamus,

Thanks again for your guidance. I wanted to share the latest status of the script and the most recent log output. Despite implementing the improvements you suggested, the same error persists.

Here’s the latest log:

2024-12-25 16:58:50.156960 - Details:

  • Current Price: 98995.2000
  • BB Low: 98999.9883
  • BB High: 99269.2917
  • BB Average: 99134.6400
  • USDT Balance: 226.9705
  • BTC Balance: 0.0000
  • Current Position: none
  • Position Amount: 0.0000
  • Timeframe: 1m, Leverage: 10x, Stop-Loss: 5.0%
    ¡¡¡ PRICE BELOW THE LOWER BAND !!!
    Error placing order: binanceusdm {“code”:-4164,“msg”:“Order’s notional must be no smaller than 100 (unless you choose reduce only).”}

Current Issue:

Behavior: The bot detects that the price has moved below the lower Bollinger Band, correctly triggering an attempt to open a long position. However, the error persists:
{"code":-4164,"msg":"Order's notional must be no smaller than 100 (unless you choose reduce only)."}

Details in the Log:
    The USDT balance is sufficient (226.9705 USDT).
    Using 75% of the balance to calculate the trade quantity, the notional value exceeds 100 USD. However, Binance still rejects the order.

Implemented Improvements:
    Time Synchronization: The bot synchronizes time with Binance, resolving timestamp issues.
    Error Logging: Logs now detail Bollinger Band calculations, balances, and order attempts.
    Parameter Initialization: At startup, the bot prompts for and logs leverage, timeframe, and stop-loss settings.
    Order Logic: The bot recognizes when price crosses Bollinger Bands and attempts to place orders.

Request for Feedback:

Could you help verify if the logic for calculating the order quantity and notional value is correct?
Here’s the relevant code snippet:

def calculate_order_amount(price):
“”"
Calculates the amount of BTC to trade using 75% of the USDT balance.
“”"
usdt_balance, _, _, _ = get_balance_and_positions()
usdt_to_use = usdt_balance * 0.75
order_amount = usdt_to_use / price
print(f"Calculated Amount: {order_amount:.4f} BTC (using ~75% of USDT balance).")
return order_amount

Further Observations:

The calculated notional value based on the log should be:

notional = order_amount * price

Example: (0.0017 BTC * 98995.2000 USD = ~170 USD)

Despite this, Binance still rejects the order. If necessary, I can share the full script for additional context. I’m continuing to test the latest version and will share results throughout the day.

Let me know if there’s anything specific you would recommend adjusting or verifying.

Thanks again for your help!
Best regards,
Daniel