Every new crypto developer hits the exact same brick wall on their first automated trade. You want to buy $100 worth of Bitcoin, so your script divides 100 / 94210.50, gets 0.00106145281..., sends that number to Binance, and gets slapped with an ugly error:
BinanceAPIException: APIError(code=-1013): Filter failure: LOT_SIZE
Why did Binance reject a perfectly reasonable trade? Because exchanges do not accept arbitrary decimal places. Every single trading pair on Binance has strict exchange filters (rules) that govern how precise your price and quantity must be—and how big the order must be in dollar terms.
The Three Rules That Reject 95% of Beginner Orders
Before placing any order, Binance checks three core filters for that trading pair:
PRICE_FILTER(tickSize): The smallest allowed price increment. IfBTCUSDThas atickSizeof0.01, you can place an order at$94,210.50, but$94,210.503will be rejected.LOT_SIZE(stepSize,minQty): The smallest allowed quantity increment. IfstepSizeis0.00001, you can buy0.00106BTC, not0.00106145BTC.NOTIONAL/MIN_NOTIONAL(minNotional): The minimum total dollar value of an order (price × quantity). Even if your quantity is rounded cleanly, trying to buy $2 of Bitcoin will fail ifminNotionalis $5 or $10.
We will test our helper against the Binance Spot Testnet (https://testnet.binance.vision) using fake money—and remember, never enable withdrawal permissions on any API key.
Why We Use Decimal Instead of float
In Python, standard floating-point math has tiny binary rounding glitches (0.1 + 0.2 == 0.30000000000000004). Sending 0.0010600000000000001 to Binance triggers a LOT_SIZE rejection! Python's built-in decimal.Decimal module does exact base-10 math and always rounds down (ROUND_DOWN) so you never accidentally try to spend more money than you have.
Prerequisites
Make sure python-binance is installed:
pip install python-binance
The Automatic Order-Rounder Helper
Save this file as order_rounder.py. You can run it directly right now to see it in action, and we will import it into Lesson 10 when we place live Testnet orders!
from decimal import Decimal, ROUND_DOWN
from binance.client import Client
class OrderRounder:
"""
Fetches Binance exchange rules for any symbol and formats prices/quantities
so orders never fail PRICE_FILTER, LOT_SIZE, or NOTIONAL checks.
"""
def __init__(self, client: Client):
self.client = client
self._cache = {}
def get_rules(self, symbol: str) -> dict:
symbol = symbol.upper()
if symbol in self._cache:
return self._cache[symbol]
info = self.client.get_symbol_info(symbol)
if not info:
raise ValueError(f"Symbol '{symbol}' not found on Binance.")
rules = {
"tick_size": Decimal("0.01"),
"step_size": Decimal("0.00001"),
"min_qty": Decimal("0"),
"min_notional": Decimal("0"),
}
for f in info["filters"]:
ftype = f["filterType"]
if ftype == "PRICE_FILTER":
rules["tick_size"] = Decimal(f["tickSize"]).normalize()
elif ftype == "LOT_SIZE":
rules["step_size"] = Decimal(f["stepSize"]).normalize()
rules["min_qty"] = Decimal(f["minQty"]).normalize()
elif ftype in ("NOTIONAL", "MIN_NOTIONAL"):
rules["min_notional"] = Decimal(f["minNotional"]).normalize()
self._cache[symbol] = rules
return rules
@staticmethod
def _floor_to_step(value: Decimal, step: Decimal) -> Decimal:
"""Round value DOWN to the nearest exact multiple of step."""
return (value // step) * step
def format_price(self, symbol: str, raw_price) -> str:
rules = self.get_rules(symbol)
price = Decimal(str(raw_price))
rounded = self._floor_to_step(price, rules["tick_size"])
# Format cleanly without scientific notation (e.g., '0.00001', not '1E-5')
return format(rounded.normalize(), "f")
def format_quantity(self, symbol: str, raw_qty) -> str:
rules = self.get_rules(symbol)
qty = Decimal(str(raw_qty))
rounded = self._floor_to_step(qty, rules["step_size"])
if rounded < rules["min_qty"]:
raise ValueError(
f"Quantity {rounded} is below Binance minQty ({rules['min_qty']}) for {symbol}."
)
return format(rounded.normalize(), "f")
def prepare_order(self, symbol: str, raw_price, raw_usd_budget) -> dict:
"""
Given a target price and a USD budget (e.g., $100), compute an exact,
Binance-valid price and quantity pair.
"""
rules = self.get_rules(symbol)
price_str = self.format_price(symbol, raw_price)
clean_price = Decimal(price_str)
raw_qty = Decimal(str(raw_usd_budget)) / clean_price
qty_str = self.format_quantity(symbol, raw_qty)
clean_qty = Decimal(qty_str)
order_value = clean_price * clean_qty
if order_value < rules["min_notional"]:
raise ValueError(
f"Order value ${order_value:.2f} is below Binance minNotional "
f"(${rules['min_notional']}) for {symbol}."
)
return {
"symbol": symbol.upper(),
"price": price_str,
"quantity": qty_str,
"notional_usd": f"{order_value:.2f}",
"rules": rules,
}
def main():
# Connect to Binance Spot Testnet (public exchangeInfo needs no API keys)
client = Client(api_key="", api_secret="", testnet=True)
rounder = OrderRounder(client)
symbol = "BTCUSDT"
ticker = client.get_symbol_ticker(symbol=symbol)
live_price = float(ticker["price"])
# Deliberately messy inputs that Binance would normally reject
messy_price = live_price * 0.995123456
budget_usd = 100.00
print(f"Live Testnet {symbol} Price : ${live_price:,.4f}")
print(f"Messy target price : ${messy_price:,.8f}")
print(f"Target USD budget : ${budget_usd:.2f}\n")
order = rounder.prepare_order(symbol, messy_price, budget_usd)
rules = order["rules"]
print("--- Binance Exchange Rules ---")
print(f" tickSize : {rules['tick_size']}")
print(f" stepSize : {rules['step_size']}")
print(f" minQty : {rules['min_qty']}")
print(f" minNotional : ${rules['min_notional']}")
print("\n--- Ready-to-Send Order ---")
print(f" Symbol : {order['symbol']}")
print(f" Clean Price : {order['price']}")
print(f" Clean Qty : {order['quantity']}")
print(f" Order Value : ${order['notional_usd']}")
if __name__ == "__main__":
main()
Run it from your terminal:
python order_rounder.py
Expected Terminal Output
Live Testnet BTCUSDT Price : $94,210.5000
Messy target price : $93,751.07645996
Target USD budget : $100.00
--- Binance Exchange Rules ---
tickSize : 0.01
stepSize : 0.00001
minQty : 0.00001
minNotional : $5
--- Ready-to-Send Order ---
Symbol : BTCUSDT
Clean Price : 93751.07
Clean Qty : 0.00106
Order Value : $99.38
Common Beginner Mistake: Using Python's built-in
round(qty, 5)on floats. Not only canround()round up (causing anInsufficient Balanceerror when you try to sell 100% of your coins), floats can also serialize into scientific notation like1e-05, which Binance's API immediately rejects. Always useDecimalwith floor rounding andformat(..., "f").
Study & Practice Recap
- Never hardcode decimal places: Every coin has different
tickSizeandstepSizerules, and Binance occasionally updates them. Always fetch them dynamically withget_symbol_info(). - Round down with
Decimal: Floor rounding prevents both floating-point precision bugs and accidental overdrafts. - Check
minNotionalbefore sending: Catching orders that are too small inside Python saves you from failed API calls.
Tiny Hands-On Exercise: Run order_rounder.py after changing symbol = "ETHUSDT" and budget_usd = 3.00. Watch your helper catch the minNotional violation cleanly before it ever hits Binance!