Placing a trade with code is exciting, but entering a position without an exit plan is how traders lose sleep—and accounts. In this final lesson of Phase 2, you will put everything together: connecting safely to the Binance Spot Testnet (https://testnet.binance.vision), rounding your numbers to Binance's exact rules, entering a trade, and immediately attaching both a Stop-Loss and a Take-Profit target.
The Three Core Order Types in Plain English
- Market Order: "Buy or sell right now at whatever the best available price is." Guaranteed to fill immediately, but you pay the spread.
- Limit Order: "Only buy or sell at this exact price or better." Gives you price control, though it may wait if the market never reaches your price.
- OCO (One-Cancels-the-Other) Order: The secret weapon for automated risk management. An OCO sell order links two exit orders together:
- A Take-Profit Limit order above your entry price (locks in gains).
- A Stop-Loss Limit order below your entry price (caps your maximum loss).
- The moment either one triggers, Binance automatically cancels the other so you never accidentally sell twice.
Safety First: This script runs exclusively on Binance Spot Testnet (
https://testnet.binance.vision) with fake money (testnet=True). Never enable withdrawal permissions on any Binance API key.
Prerequisites
Install python-binance and python-dotenv, and make sure your .env file from Lesson 6 has your Testnet keys:
pip install python-binance python-dotenv
BINANCE_TESTNET_API_KEY=paste_your_testnet_api_key_here
BINANCE_TESTNET_API_SECRET=paste_your_testnet_secret_key_here
Complete Trade-Execution Script (Entry + Stop-Loss + Take-Profit)
Save this script as execute_protected_trade.py. It buys $100 of Testnet BTCUSDT with a Market order, calculates the exact average fill price, rounds every price and quantity to Binance's tickSize and stepSize rules, and immediately attaches a +2% Take-Profit and -1% Stop-Loss via an OCO order.
import os
import sys
from decimal import Decimal
from dotenv import load_dotenv
from binance.client import Client
from binance.enums import SIDE_BUY, SIDE_SELL, ORDER_TYPE_MARKET, TIME_IN_FORCE_GTC
from binance.exceptions import BinanceAPIException
def get_symbol_filters(client: Client, symbol: str) -> dict:
"""Fetch tickSize and stepSize rules directly from Binance."""
info = client.get_symbol_info(symbol)
if not info:
raise ValueError(f"Symbol {symbol} not found.")
rules = {}
for f in info["filters"]:
if f["filterType"] == "PRICE_FILTER":
rules["tick_size"] = Decimal(f["tickSize"]).normalize()
elif f["filterType"] == "LOT_SIZE":
rules["step_size"] = Decimal(f["stepSize"]).normalize()
return rules
def floor_step(value: Decimal, step: Decimal) -> str:
"""Round DOWN to an exact multiple of step and return a plain string."""
rounded = (value // step) * step
return format(rounded.normalize(), "f")
def calculate_avg_fill_price(order_response: dict) -> Decimal:
"""Compute the true weighted-average entry price from Binance's fills list."""
fills = order_response.get("fills", [])
total_qty = sum(Decimal(f["qty"]) for f in fills)
total_cost = sum(Decimal(f["price"]) * Decimal(f["qty"]) for f in fills)
return total_cost / total_qty
def main():
load_dotenv()
api_key = os.getenv("BINANCE_TESTNET_API_KEY")
api_secret = os.getenv("BINANCE_TESTNET_API_SECRET")
if not api_key or not api_secret:
print("ERROR: Missing Testnet API keys in .env file.")
sys.exit(1)
# Always use testnet=True while learning and testing
client = Client(api_key, api_secret, testnet=True)
symbol = "BTCUSDT"
budget_usdt = Decimal("100")
take_profit_pct = Decimal("0.02") # +2.0% profit target
stop_loss_pct = Decimal("0.01") # -1.0% stop trigger
stop_limit_slippage = Decimal("0.002") # 0.2% buffer below stop trigger so it fills
try:
rules = get_symbol_filters(client, symbol)
current_price = Decimal(client.get_symbol_ticker(symbol=symbol)["price"])
buy_qty = floor_step(budget_usdt / current_price, rules["step_size"])
print(f"--- Step 1: Placing Market Buy on Binance Spot Testnet ---")
print(f"Symbol: {symbol} | Est. Price: ${current_price:,.2f} | Qty: {buy_qty}")
entry_order = client.create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=buy_qty,
)
entry_price = calculate_avg_fill_price(entry_order)
filled_qty = floor_step(Decimal(entry_order["executedQty"]), rules["step_size"])
print(f"FILLED! Order ID: {entry_order['orderId']}")
print(f"Actual Entry Price : ${entry_price:,.2f}")
print(f"Actual Filled Qty : {filled_qty} BTC\n")
# Calculate rounded Take-Profit and Stop-Loss prices
tp_price = floor_step(entry_price * (Decimal("1") + take_profit_pct), rules["tick_size"])
stop_trigger = floor_step(entry_price * (Decimal("1") - stop_loss_pct), rules["tick_size"])
stop_limit = floor_step(
Decimal(stop_trigger) * (Decimal("1") - stop_limit_slippage),
rules["tick_size"],
)
print(f"--- Step 2: Attaching OCO Exit (Take-Profit + Stop-Loss) ---")
print(f"Take-Profit Limit : ${tp_price} (+2.0%)")
print(f"Stop-Loss Trigger : ${stop_trigger} (-1.0%)")
print(f"Stop-Loss Limit : ${stop_limit} (0.2% fill buffer)")
oco_order = client.create_oco_order(
symbol=symbol,
side=SIDE_SELL,
quantity=filled_qty,
price=tp_price,
stopPrice=stop_trigger,
stopLimitPrice=stop_limit,
stopLimitTimeInForce=TIME_IN_FORCE_GTC,
)
print(f"\nSUCCESS! OCO Protection Active (Order List ID: {oco_order['orderListId']})")
# Confirm the active open orders sitting on the exchange
open_orders = client.get_open_orders(symbol=symbol)
print(f"\n--- Currently Open Orders for {symbol} ({len(open_orders)}) ---")
for o in open_orders:
print(
f" ID {o['orderId']} | {o['type']:<16} | "
f"Side: {o['side']} | Qty: {o['origQty']} | "
f"Price: ${o['price']} | Stop: ${o['stopPrice']}"
)
except BinanceAPIException as exc:
print(f"Binance API Error ({exc.code}): {exc.message}")
sys.exit(1)
if __name__ == "__main__":
main()
Run your complete trade-execution script on the Spot Testnet:
python execute_protected_trade.py
Expected Terminal Output
--- Step 1: Placing Market Buy on Binance Spot Testnet ---
Symbol: BTCUSDT | Est. Price: $94,210.50 | Qty: 0.00106
FILLED! Order ID: 8492014
Actual Entry Price : $94,211.00
Actual Filled Qty : 0.00106 BTC
--- Step 2: Attaching OCO Exit (Take-Profit + Stop-Loss) ---
Take-Profit Limit : $96095.22 (+2.0%)
Stop-Loss Trigger : $93268.89 (-1.0%)
Stop-Loss Limit : $93082.35 (0.2% fill buffer)
SUCCESS! OCO Protection Active (Order List ID: 194820)
--- Currently Open Orders for BTCUSDT (2) ---
ID 8492015 | STOP_LOSS_LIMIT | Side: SELL | Qty: 0.00106000 | Price: $93082.35000000 | Stop: $93268.89000000
ID 8492016 | LIMIT_MAKER | Side: SELL | Qty: 0.00106000 | Price: $96095.22000000 | Stop: $0.00000000
Common Beginner Mistake: Setting
stopLimitPriceequal tostopPrice(or forgetting to account for trading fees when selling 100% of your bought coins). In a fast drop, a stop-limit with zero buffer can get skipped completely—always placestopLimitPriceslightly belowstopPrice(e.g., 0.2% lower) so your exit actually fills. And if you pay trading fees in BTC instead of BNB, your actual received BTC may be slightly less thanexecutedQty, so always check your free balance before selling 100%.
Study & Practice Recap
- Always base exits on actual fill price: Calculate your take-profit and stop-loss from the real
fillsprice returned by Binance, not the stale ticker price from before your order. - OCO orders protect you while you sleep: Linking a take-profit limit and a stop-loss limit ensures one cancels the other automatically.
- Give stop-limits breathing room: Setting
stopLimitPriceslightly belowstopPricehelps your stop-loss fill reliably during sudden volatility.
Tiny Hands-On Exercise: Write a 10-line cleanup script (or add a --cancel flag) that calls client.cancel_order(symbol="BTCUSDT", orderId=...) to cancel your open Testnet OCO order and verify client.get_open_orders(symbol="BTCUSDT") returns an empty list.