{"cells":[{"cell_type":"markdown","id":"md_binance_001","metadata":{"id":"md_binance_001"},"source":["# Execute Trades on Binance\n","\n","## 1. Overview\n","\n","This notebook demonstrates how to execute trades programmatically on **Binance** using the `python-binance` library. It covers the full execution workflow — from authentication and market data retrieval to placing market and limit orders.\n","\n","### What You Will Learn\n","\n","| Step | Description |\n","|---|---|\n","| Authentication | Connect to Binance via API keys |\n","| Market Data | Fetch ticker prices and order book depth |\n","| Fee Lookup | Retrieve your account's trading fee tier |\n","| Market Order | Place an immediate buy/sell order |\n","| Limit Order | Place a price-controlled buy/sell order |\n","| Order Status | Query and display order fill details |\n","| Cancel Order | Cancel an open limit order |\n","\n","> **Note:** This notebook uses the Binance **Testnet** by default. Switch `testnet=True` to `testnet=False` and supply live API keys to trade on the real exchange.\n","> **Dummy Mode:** Live API calls in this notebook are commented out and replaced with realistic dummy data so it can run end-to-end without a live connection or trading funds. Uncomment the real calls and remove the dummy assignments to run against a real account. The Google Colab `userdata` dependency has also been replaced with plain placeholder variables so this runs outside Colab too.\n"]},{"cell_type":"markdown","id":"md_binance_002","metadata":{"id":"md_binance_002"},"source":["## 2. Dependency Imports\n","\n","Install and import the required libraries. `python-binance` is the official community client for the Binance REST and WebSocket APIs."]},{"cell_type":"code","execution_count":9,"id":"cd_binance_install","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:16.890048Z","iopub.status.busy":"2026-06-11T12:22:16.889819Z","iopub.status.idle":"2026-06-11T12:22:17.496172Z","shell.execute_reply":"2026-06-11T12:22:17.494247Z"},"id":"cd_binance_install","executionInfo":{"status":"ok","timestamp":1781180614290,"user_tz":-300,"elapsed":9789,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["# Install the Binance client library if not already present.\n","!pip install python-binance --quiet"]},{"cell_type":"code","execution_count":10,"id":"cd_binance_imports","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:17.498693Z","iopub.status.busy":"2026-06-11T12:22:17.498480Z","iopub.status.idle":"2026-06-11T12:22:18.129711Z","shell.execute_reply":"2026-06-11T12:22:18.128065Z"},"id":"cd_binance_imports","executionInfo":{"status":"ok","timestamp":1781180614301,"user_tz":-300,"elapsed":5,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["from binance.client import Client\n","from binance.enums import (\n","    SIDE_BUY, SIDE_SELL,\n","    ORDER_TYPE_MARKET, ORDER_TYPE_LIMIT,\n","    TIME_IN_FORCE_GTC,\n",")\n","import warnings\n","\n","# Suppress all warnings for cleaner output in a demonstration context.\n","warnings.filterwarnings(\"ignore\")"]},{"cell_type":"markdown","id":"md_binance_003","metadata":{"id":"md_binance_003"},"source":["## 3. Authentication\n","\n","### 3.1. `create_client` Function\n","\n","This function initialises a Binance `Client` using your API key and secret. Set `testnet=True` to connect to the Binance Spot Testnet — no real funds are involved."]},{"cell_type":"code","execution_count":11,"id":"cd_binance_auth","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.134535Z","iopub.status.busy":"2026-06-11T12:22:18.132488Z","iopub.status.idle":"2026-06-11T12:22:18.139797Z","shell.execute_reply":"2026-06-11T12:22:18.138675Z"},"id":"cd_binance_auth","executionInfo":{"status":"ok","timestamp":1781180614311,"user_tz":-300,"elapsed":4,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def create_client(api_key: str, api_secret: str, testnet: bool = True) -> Client:\n","    \"\"\"Create and return an authenticated Binance client.\n","\n","    Parameters\n","    ----------\n","    api_key    : Your Binance API key.\n","    api_secret : Your Binance API secret.\n","    testnet    : If True, connects to Binance Testnet (safe for learning).\n","\n","    Returns\n","    -------\n","    Client: Authenticated Binance client instance.\n","    \"\"\"\n","    # Initialise client; testnet flag routes requests to the test environment.\n","    client = Client(api_key, api_secret, testnet=testnet)\n","    return client"]},{"cell_type":"markdown","metadata":{"id":"be88a535"},"source":["### Explanation of `create_client` function\n","\n","This function is crucial for establishing a connection to the Binance API. It takes your `api_key` and `api_secret` to authenticate your requests. The `testnet` parameter is very important: if set to `True`, it directs your requests to the Binance Spot Testnet, which is a simulated environment. This allows you to test your trading strategies and code without risking real funds. If `testnet` is set to `False`, your requests will go to the live Binance exchange, where actual trades will be executed with real money. The function returns an authenticated `Client` object, which you will use for all subsequent API calls."],"id":"be88a535"},{"cell_type":"code","execution_count":12,"id":"03f36b35","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.141937Z","iopub.status.busy":"2026-06-11T12:22:18.141737Z","iopub.status.idle":"2026-06-11T12:22:18.147329Z","shell.execute_reply":"2026-06-11T12:22:18.146258Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"03f36b35","executionInfo":{"status":"ok","timestamp":1781180614343,"user_tz":-300,"elapsed":27,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"2b6e1ff9-2714-4bb3-c6f3-2c78f75f4027"},"outputs":[{"output_type":"stream","name":"stdout","text":["Binance client created successfully.\n"]}],"source":["# ── Replace with your own keys ──────────────────────────────────────────────\n","API_KEY    = \"YOUR_BINANCE_API_KEY\"\n","API_SECRET = \"YOUR_BINANCE_API_SECRET\"\n","# ────────────────────────────────────────────────────────────────────────────\n","\n","# Create the client (testnet = True by default).\n","# Commented out to run locally without network access / real keys\n","# client = create_client(API_KEY, API_SECRET, testnet=True)\n","\n","client = None  # Dummy placeholder client (no live connection in this offline run)\n","print(\"Binance client created successfully.\")\n"]},{"cell_type":"markdown","id":"md_binance_004","metadata":{"id":"md_binance_004"},"source":["## 4. Market Data Functions\n","\n","### 4.1. `get_ticker_price` Function\n","\n","Fetches the latest best bid/ask prices for a trading symbol from the Binance order book ticker endpoint."]},{"cell_type":"code","execution_count":13,"id":"cd_binance_ticker","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.149375Z","iopub.status.busy":"2026-06-11T12:22:18.149186Z","iopub.status.idle":"2026-06-11T12:22:18.154016Z","shell.execute_reply":"2026-06-11T12:22:18.152882Z"},"id":"cd_binance_ticker","executionInfo":{"status":"ok","timestamp":1781180614350,"user_tz":-300,"elapsed":3,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def get_ticker_price(client: Client, symbol: str) -> dict:\n","    \"\"\"Return the best bid and ask price for a symbol.\n","\n","    Parameters\n","    ----------\n","    client : Authenticated Binance client.\n","    symbol : Trading pair symbol, e.g. 'BTCUSDT'.\n","\n","    Returns\n","    -------\n","    dict: Contains 'bid' and 'ask' as floats.\n","    \"\"\"\n","    # get_orderbook_ticker returns the best bid and ask for the symbol.\n","    ticker = client.get_orderbook_ticker(symbol=symbol)\n","    return {\n","        \"bid\": float(ticker[\"bidPrice\"]),\n","        \"ask\": float(ticker[\"askPrice\"]),\n","    }"]},{"cell_type":"markdown","metadata":{"id":"ee1970f7"},"source":["### Explanation of `get_ticker_price` function\n","\n","This function retrieves real-time market data, specifically the best bid and ask prices for a given trading `symbol` (e.g., 'BTCUSDT').\n","\n","*   **`client.get_orderbook_ticker(symbol=symbol)`**: This is the core API call. It fetches the current best bid (highest price a buyer is willing to pay) and best ask (lowest price a seller is willing to accept) from the order book.\n","*   **`ticker['bidPrice']` and `ticker['askPrice']`**: These keys in the API response contain the bid and ask prices, respectively. They are typically strings, so they are converted to `float` for numerical operations.\n","*   **Return Value**: The function returns a dictionary with 'bid' and 'ask' prices, making it easy to access the current market spread."],"id":"ee1970f7"},{"cell_type":"code","execution_count":14,"id":"7b85150b","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.156503Z","iopub.status.busy":"2026-06-11T12:22:18.155733Z","iopub.status.idle":"2026-06-11T12:22:18.161468Z","shell.execute_reply":"2026-06-11T12:22:18.160506Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"7b85150b","executionInfo":{"status":"ok","timestamp":1781180614430,"user_tz":-300,"elapsed":23,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"ba34c35f-81d0-4019-ef1e-43cf324f59a3"},"outputs":[{"output_type":"stream","name":"stdout","text":["BTCUSDT — Bid: 60,000.00 | Ask: 60,005.00\n"]}],"source":["# Fetch the current BTCUSDT ticker.\n","# Commented out to run locally with dummy data\n","# ticker = get_ticker_price(client, \"BTCUSDT\")\n","\n","ticker = {\"bid\": 60000.00, \"ask\": 60005.00}  # Dummy data\n","\n","print(f\"BTCUSDT — Bid: {ticker['bid']:,.2f} | Ask: {ticker['ask']:,.2f}\")\n"]},{"cell_type":"markdown","id":"md_binance_005","metadata":{"id":"md_binance_005"},"source":["### 4.2. `get_order_book` Function\n","\n","Retrieves the top N levels of the order book for a symbol. Useful for understanding available liquidity before placing large orders."]},{"cell_type":"code","execution_count":15,"id":"cd_binance_orderbook","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.164078Z","iopub.status.busy":"2026-06-11T12:22:18.163220Z","iopub.status.idle":"2026-06-11T12:22:18.168525Z","shell.execute_reply":"2026-06-11T12:22:18.167588Z"},"id":"cd_binance_orderbook","executionInfo":{"status":"ok","timestamp":1781180614451,"user_tz":-300,"elapsed":26,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def get_order_book(client: Client, symbol: str, depth: int = 5) -> dict:\n","    \"\"\"Return the top N bid and ask levels from the order book.\n","\n","    Parameters\n","    ----------\n","    client : Authenticated Binance client.\n","    symbol : Trading pair symbol, e.g. 'BTCUSDT'.\n","    depth  : Number of price levels to retrieve (default: 5).\n","\n","    Returns\n","    -------\n","    dict: Contains 'bids' and 'asks' as lists of [price, quantity].\n","    \"\"\"\n","    # get_order_book returns a dict with 'bids' and 'asks' lists.\n","    book = client.get_order_book(symbol=symbol, limit=depth)\n","    return {\n","        \"bids\": [[float(p), float(q)] for p, q in book[\"bids\"]],\n","        \"asks\": [[float(p), float(q)] for p, q in book[\"asks\"]],\n","    }"]},{"cell_type":"markdown","metadata":{"id":"3ca94c20"},"source":["### Explanation of `get_order_book` function\n","\n","This function provides a deeper look into the market's liquidity by fetching the top `depth` levels of the order book for a specified `symbol`.\n","\n","*   **`client.get_order_book(symbol=symbol, limit=depth)`**: This API call retrieves a snapshot of the order book. The `limit` parameter controls how many bid and ask levels are returned (e.g., `depth=5` gets the top 5 bids and asks).\n","*   **`book['bids']` and `book['asks']`**: The API response contains two lists: 'bids' (representing buy orders) and 'asks' (representing sell orders). Each element in these lists is a `[price, quantity]` pair.\n","*   **List Comprehension `[[float(p), float(q)] for p, q in book['bids']]`**: This concise syntax iterates through the raw bid/ask data, converting both price `p` and quantity `q` from strings to floats, ensuring they can be used for calculations.\n","*   **Return Value**: The function returns a dictionary containing processed lists of 'bids' and 'asks', where each is a list of `[price, quantity]` pairs, ordered from best to worst price."],"id":"3ca94c20"},{"cell_type":"code","execution_count":16,"id":"f35f8a88","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.170983Z","iopub.status.busy":"2026-06-11T12:22:18.170260Z","iopub.status.idle":"2026-06-11T12:22:18.177410Z","shell.execute_reply":"2026-06-11T12:22:18.176437Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"f35f8a88","executionInfo":{"status":"ok","timestamp":1781180614473,"user_tz":-300,"elapsed":40,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"2d95d9d7-2432-4532-dd9b-49400ee5f021"},"outputs":[{"output_type":"stream","name":"stdout","text":["Top 5 Asks (sell side):\n","     60,002.50  |  0.290000 BTC\n","     60,002.00  |  1.760000 BTC\n","     60,001.50  |  0.905000 BTC\n","     60,001.00  |  1.150000 BTC\n","     60,000.50  |  0.470000 BTC\n","-----------------------------------\n","Top 5 Bids (buy side):\n","     59,999.50  |  0.512000 BTC\n","     59,999.00  |  1.204000 BTC\n","     59,998.50  |  0.880000 BTC\n","     59,998.00  |  2.001000 BTC\n","     59,997.50  |  0.330000 BTC\n"]}],"source":["# Display the top 5 levels of the BTCUSDT order book.\n","# Commented out to run locally with dummy data\n","# book = get_order_book(client, \"BTCUSDT\", depth=5)\n","\n","book = {  # Dummy data\n","    \"bids\": [[59999.5, 0.512], [59999.0, 1.204], [59998.5, 0.880], [59998.0, 2.001], [59997.5, 0.330]],\n","    \"asks\": [[60000.5, 0.470], [60001.0, 1.150], [60001.5, 0.905], [60002.0, 1.760], [60002.5, 0.290]],\n","}\n","\n","print(\"Top 5 Asks (sell side):\")\n","for price, qty in reversed(book[\"asks\"]):\n","    print(f\"  {price:>12,.2f}  |  {qty:.6f} BTC\")\n","\n","print(\"-\" * 35)\n","print(\"Top 5 Bids (buy side):\")\n","for price, qty in book[\"bids\"]:\n","    print(f\"  {price:>12,.2f}  |  {qty:.6f} BTC\")\n"]},{"cell_type":"markdown","id":"md_binance_006","metadata":{"id":"md_binance_006"},"source":["## 5. Fee Information\n","\n","### 5.1. `get_trade_fee` Function\n","\n","Queries your account's current maker and taker fee rates for a given symbol. Binance fees depend on your 30-day trading volume and BNB holdings."]},{"cell_type":"code","execution_count":17,"id":"cd_binance_fee","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.179994Z","iopub.status.busy":"2026-06-11T12:22:18.179004Z","iopub.status.idle":"2026-06-11T12:22:18.185472Z","shell.execute_reply":"2026-06-11T12:22:18.184409Z"},"id":"cd_binance_fee","executionInfo":{"status":"ok","timestamp":1781180614478,"user_tz":-300,"elapsed":30,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def get_trade_fee(client: Client, symbol: str) -> dict:\n","    \"\"\"Return maker and taker fee rates for a symbol.\n","\n","    Parameters\n","    ----------\n","    client : Authenticated Binance client.\n","    symbol : Trading pair symbol, e.g. 'BTCUSDT'.\n","\n","    Returns\n","    -------\n","    dict: Contains 'maker_fee' and 'taker_fee' as floats (e.g., 0.001 = 0.1%).\n","    \"\"\"\n","    # get_trade_fee returns a list of fee objects; we extract the first match.\n","    fees = client.get_trade_fee(symbol=symbol)\n","    fee_info = fees[0] if fees else {\"makerCommission\": 0.001, \"takerCommission\": 0.001}\n","    return {\n","        \"maker_fee\": float(fee_info.get(\"makerCommission\", 0.001)),\n","        \"taker_fee\": float(fee_info.get(\"takerCommission\", 0.001)),\n","    }"]},{"cell_type":"markdown","metadata":{"id":"38486842"},"source":["### Explanation of `get_trade_fee` function\n","\n","This function is used to retrieve the current trading fee rates for your account on a specific `symbol`. Trading fees on Binance can vary based on your VIP level, which is determined by your 30-day trading volume and BNB holdings.\n","\n","*   **`client.get_trade_fee(symbol=symbol)`**: This API call fetches an array of fee information for the specified trading pair. Even if you only query for one symbol, the API returns a list.\n","*   **`fees[0] if fees else {'makerCommission': 0.001, 'takerCommission': 0.001}`**: This line safely extracts the first (and likely only) fee object from the `fees` list. It also provides default values (0.1% for both maker and taker) in case the API call returns an empty list or fails to provide specific commission rates, preventing errors.\n","*   **`fee_info.get("],"id":"38486842"},{"cell_type":"code","execution_count":18,"id":"5f3bfb98","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.187888Z","iopub.status.busy":"2026-06-11T12:22:18.187076Z","iopub.status.idle":"2026-06-11T12:22:18.192905Z","shell.execute_reply":"2026-06-11T12:22:18.191918Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"5f3bfb98","executionInfo":{"status":"ok","timestamp":1781180614482,"user_tz":-300,"elapsed":25,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"e41ed158-9ca8-466e-a6f6-9dd179db0ff3"},"outputs":[{"output_type":"stream","name":"stdout","text":["BTCUSDT Fees — Maker: 0.0200% | Taker: 0.0400%\n"]}],"source":["# Display the fee rates for BTCUSDT.\n","# Commented out to run locally with dummy data\n","# fees = get_trade_fee(client, \"BTCUSDT\")\n","\n","fees = {\"maker_fee\": 0.0002, \"taker_fee\": 0.0004}  # Dummy data (default Binance VIP0 rates)\n","\n","print(f\"BTCUSDT Fees — Maker: {fees['maker_fee']*100:.4f}% | Taker: {fees['taker_fee']*100:.4f}%\")\n"]},{"cell_type":"markdown","id":"md_binance_007","metadata":{"id":"md_binance_007"},"source":["## 6. Order Execution Functions\n","\n","### 6.1. `place_market_order` Function\n","\n","Places a market order on Binance. A market order executes immediately at the best available price. Use this when **execution certainty** is more important than price precision."]},{"cell_type":"code","execution_count":19,"id":"cd_binance_market","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.194705Z","iopub.status.busy":"2026-06-11T12:22:18.194524Z","iopub.status.idle":"2026-06-11T12:22:18.199801Z","shell.execute_reply":"2026-06-11T12:22:18.198716Z"},"id":"cd_binance_market","executionInfo":{"status":"ok","timestamp":1781180614488,"user_tz":-300,"elapsed":3,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def place_market_order(client: Client, symbol: str, side: str, quantity: float) -> dict:\n","    \"\"\"Place a market order on Binance.\n","\n","    Parameters\n","    ----------\n","    client   : Authenticated Binance client.\n","    symbol   : Trading pair symbol, e.g. 'BTCUSDT'.\n","    side     : 'BUY' or 'SELL'.\n","    quantity : Amount of base asset to buy or sell.\n","\n","    Returns\n","    -------\n","    dict: Full order response from Binance including orderId and fills.\n","    \"\"\"\n","    # Map string side to the Binance enum constant.\n","    binance_side = SIDE_BUY if side.upper() == \"BUY\" else SIDE_SELL\n","\n","    # Submit the market order via the REST API.\n","    order = client.order_market(\n","        symbol=symbol,\n","        side=binance_side,\n","        quantity=quantity,\n","    )\n","    return order"]},{"cell_type":"code","execution_count":20,"id":"5f922157","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.201682Z","iopub.status.busy":"2026-06-11T12:22:18.201490Z","iopub.status.idle":"2026-06-11T12:22:18.207786Z","shell.execute_reply":"2026-06-11T12:22:18.206827Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"5f922157","executionInfo":{"status":"ok","timestamp":1781180614508,"user_tz":-300,"elapsed":16,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"afd5b719-65da-471c-a9b8-2d4404c42dfc"},"outputs":[{"output_type":"stream","name":"stdout","text":["Market Order Placed:\n","  Order ID  : 100001\n","  Symbol    : BTCUSDT\n","  Side      : BUY\n","  Status    : FILLED\n","  Qty Filled: 0.00100000 BTC\n"]}],"source":["# Place a market BUY order for 0.001 BTC on the testnet.\n","# Commented out to run locally with dummy data\n","# market_order = place_market_order(client, \"BTCUSDT\", side=\"BUY\", quantity=0.001)\n","\n","market_order = {  # Dummy data\n","    \"orderId\": 100001,\n","    \"symbol\": \"BTCUSDT\",\n","    \"side\": \"BUY\",\n","    \"status\": \"FILLED\",\n","    \"executedQty\": \"0.00100000\",\n","}\n","\n","print(\"Market Order Placed:\")\n","print(f\"  Order ID  : {market_order['orderId']}\")\n","print(f\"  Symbol    : {market_order['symbol']}\")\n","print(f\"  Side      : {market_order['side']}\")\n","print(f\"  Status    : {market_order['status']}\")\n","print(f\"  Qty Filled: {market_order['executedQty']} BTC\")\n"]},{"cell_type":"markdown","id":"md_binance_008","metadata":{"id":"md_binance_008"},"source":["### 6.2. `place_limit_order` Function\n","\n","Places a limit order on Binance. A limit order rests in the order book until the market reaches your specified price. Use this when **price control** matters more than immediate execution."]},{"cell_type":"code","execution_count":21,"id":"cd_binance_limit","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.209668Z","iopub.status.busy":"2026-06-11T12:22:18.209507Z","iopub.status.idle":"2026-06-11T12:22:18.214195Z","shell.execute_reply":"2026-06-11T12:22:18.213227Z"},"id":"cd_binance_limit","executionInfo":{"status":"ok","timestamp":1781180614515,"user_tz":-300,"elapsed":4,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def place_limit_order(\n","    client: Client, symbol: str, side: str, quantity: float, price: float\n",") -> dict:\n","    \"\"\"Place a limit order on Binance (Good-Till-Cancelled).\n","\n","    Parameters\n","    ----------\n","    client   : Authenticated Binance client.\n","    symbol   : Trading pair symbol, e.g. 'BTCUSDT'.\n","    side     : 'BUY' or 'SELL'.\n","    quantity : Amount of base asset to buy or sell.\n","    price    : Limit price at which to execute.\n","\n","    Returns\n","    -------\n","    dict: Full order response from Binance including orderId.\n","    \"\"\"\n","    # Map string side to the Binance enum constant.\n","    binance_side = SIDE_BUY if side.upper() == \"BUY\" else SIDE_SELL\n","\n","    # Submit the limit GTC order; it will rest in the book until filled or cancelled.\n","    order = client.order_limit(\n","        symbol=symbol,\n","        side=binance_side,\n","        quantity=quantity,\n","        price=str(price),\n","        timeInForce=TIME_IN_FORCE_GTC,\n","    )\n","    return order"]},{"cell_type":"code","execution_count":22,"id":"79c0a986","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.216691Z","iopub.status.busy":"2026-06-11T12:22:18.215878Z","iopub.status.idle":"2026-06-11T12:22:18.222451Z","shell.execute_reply":"2026-06-11T12:22:18.221507Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"79c0a986","executionInfo":{"status":"ok","timestamp":1781180614534,"user_tz":-300,"elapsed":14,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"7c389cf5-eecb-4cf3-a5fb-673eb0dc6620"},"outputs":[{"output_type":"stream","name":"stdout","text":["Limit Order Placed:\n","  Order ID   : 100002\n","  Symbol     : BTCUSDT\n","  Side       : BUY\n","  Limit Price: 59,404.95 USDT\n","  Status     : NEW\n"]}],"source":["# Fetch current ask price and place a passive limit BUY 1% below ask.\n","# Commented out to run locally with dummy data\n","# current_ask = get_ticker_price(client, \"BTCUSDT\")[\"ask\"]\n","current_ask = ticker[\"ask\"]  # reuse dummy ticker from earlier\n","limit_price  = round(current_ask * 0.99, 2)   # 1% below current ask.\n","\n","# limit_order = place_limit_order(\n","#     client, \"BTCUSDT\", side=\"BUY\", quantity=0.001, price=limit_price\n","# )\n","\n","limit_order = {  # Dummy data\n","    \"orderId\": 100002,\n","    \"symbol\": \"BTCUSDT\",\n","    \"side\": \"BUY\",\n","    \"status\": \"NEW\",\n","}\n","\n","print(\"Limit Order Placed:\")\n","print(f\"  Order ID   : {limit_order['orderId']}\")\n","print(f\"  Symbol     : {limit_order['symbol']}\")\n","print(f\"  Side       : {limit_order['side']}\")\n","print(f\"  Limit Price: {limit_price:,.2f} USDT\")\n","print(f\"  Status     : {limit_order['status']}\")\n"]},{"cell_type":"markdown","id":"md_binance_009","metadata":{"id":"md_binance_009"},"source":["## 7. Order Management Functions\n","\n","### 7.1. `get_order_status` Function\n","\n","Retrieves the current status of an order by its ID. Returns key fields such as fill quantity and average price."]},{"cell_type":"code","execution_count":23,"id":"cd_binance_status","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.224165Z","iopub.status.busy":"2026-06-11T12:22:18.223965Z","iopub.status.idle":"2026-06-11T12:22:18.228992Z","shell.execute_reply":"2026-06-11T12:22:18.228055Z"},"id":"cd_binance_status","executionInfo":{"status":"ok","timestamp":1781180614540,"user_tz":-300,"elapsed":3,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def get_order_status(client: Client, symbol: str, order_id: int) -> dict:\n","    \"\"\"Return the status of an existing order.\n","\n","    Parameters\n","    ----------\n","    client   : Authenticated Binance client.\n","    symbol   : Trading pair symbol, e.g. 'BTCUSDT'.\n","    order_id : The integer order ID returned when the order was placed.\n","\n","    Returns\n","    -------\n","    dict: Contains 'status', 'executed_qty', and 'avg_price'.\n","    \"\"\"\n","    # Query the order by symbol and ID.\n","    order = client.get_order(symbol=symbol, orderId=order_id)\n","    executed_qty = float(order[\"executedQty\"])\n","    avg_price    = (\n","        float(order[\"cummulativeQuoteQty\"]) / executed_qty\n","        if executed_qty > 0 else 0.0\n","    )\n","    return {\n","        \"status\"      : order[\"status\"],\n","        \"executed_qty\": executed_qty,\n","        \"avg_price\"   : round(avg_price, 2),\n","    }"]},{"cell_type":"code","execution_count":24,"id":"74a4c9b1","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.231231Z","iopub.status.busy":"2026-06-11T12:22:18.230524Z","iopub.status.idle":"2026-06-11T12:22:18.236557Z","shell.execute_reply":"2026-06-11T12:22:18.235590Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"74a4c9b1","executionInfo":{"status":"ok","timestamp":1781180614560,"user_tz":-300,"elapsed":15,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"71d7bf52-a2d3-4da8-9ae4-ebf15974559f"},"outputs":[{"output_type":"stream","name":"stdout","text":["Limit Order Status:\n","  Status       : NEW\n","  Executed Qty : 0.0 BTC\n","  Avg Fill Price: 0.00 USDT\n"]}],"source":["# Check the status of the limit order we just placed.\n","# Commented out to run locally with dummy data\n","# status = get_order_status(client, \"BTCUSDT\", limit_order[\"orderId\"])\n","\n","status = {\"status\": \"NEW\", \"executed_qty\": 0.0, \"avg_price\": 0.0}  # Dummy data\n","\n","print(\"Limit Order Status:\")\n","print(f\"  Status       : {status['status']}\")\n","print(f\"  Executed Qty : {status['executed_qty']} BTC\")\n","print(f\"  Avg Fill Price: {status['avg_price']:,.2f} USDT\")\n"]},{"cell_type":"markdown","id":"md_binance_010","metadata":{"id":"md_binance_010"},"source":["### 7.2. `cancel_order` Function\n","\n","Cancels an open order on Binance. Only orders with status `NEW` or `PARTIALLY_FILLED` can be cancelled."]},{"cell_type":"code","execution_count":25,"id":"cd_binance_cancel","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.238827Z","iopub.status.busy":"2026-06-11T12:22:18.238517Z","iopub.status.idle":"2026-06-11T12:22:18.243218Z","shell.execute_reply":"2026-06-11T12:22:18.242253Z"},"id":"cd_binance_cancel","executionInfo":{"status":"ok","timestamp":1781180614566,"user_tz":-300,"elapsed":3,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}}},"outputs":[],"source":["def cancel_order(client: Client, symbol: str, order_id: int) -> dict:\n","    \"\"\"Cancel an open order on Binance.\n","\n","    Parameters\n","    ----------\n","    client   : Authenticated Binance client.\n","    symbol   : Trading pair symbol, e.g. 'BTCUSDT'.\n","    order_id : The integer order ID to cancel.\n","\n","    Returns\n","    -------\n","    dict: Cancellation confirmation from Binance.\n","    \"\"\"\n","    # Send the cancel request; raises an exception if the order is already filled.\n","    result = client.cancel_order(symbol=symbol, orderId=order_id)\n","    return result"]},{"cell_type":"code","execution_count":26,"id":"2f22e08b","metadata":{"execution":{"iopub.execute_input":"2026-06-11T12:22:18.245091Z","iopub.status.busy":"2026-06-11T12:22:18.244924Z","iopub.status.idle":"2026-06-11T12:22:18.250095Z","shell.execute_reply":"2026-06-11T12:22:18.249041Z"},"colab":{"base_uri":"https://localhost:8080/"},"id":"2f22e08b","executionInfo":{"status":"ok","timestamp":1781180614589,"user_tz":-300,"elapsed":11,"user":{"displayName":"Arsalan Bakhtiar","userId":"11466190921627274456"}},"outputId":"98dacc9f-cfe8-44b7-90c9-52e24cac5b78"},"outputs":[{"output_type":"stream","name":"stdout","text":["Order Cancelled:\n","  Order ID : 100002\n","  Status   : CANCELED\n"]}],"source":["# Cancel the limit order if it is still open.\n","# Commented out to run locally with dummy data\n","# cancel_result = cancel_order(client, \"BTCUSDT\", limit_order[\"orderId\"])\n","\n","cancel_result = {\"orderId\": limit_order[\"orderId\"], \"status\": \"CANCELED\"}  # Dummy data\n","\n","print(\"Order Cancelled:\")\n","print(f\"  Order ID : {cancel_result['orderId']}\")\n","print(f\"  Status   : {cancel_result['status']}\")\n"]},{"cell_type":"markdown","id":"md_binance_011","metadata":{"id":"md_binance_011"},"source":["## 8. Execution Decision Framework\n","\n","Choosing the right order type on Binance depends on your execution goal:\n","\n","### When to Use a Market Order\n","- You need to **enter or exit immediately** (e.g., stop-loss, signal with rapid decay).\n","- Order size is **small relative to book depth** (< 0.5% of visible liquidity).\n","- Speed matters more than the exact fill price.\n","\n","### When to Use a Limit Order\n","- You want **price certainty** and can wait for the market to come to you.\n","- Order size is **large** (> 1% of book depth) — avoids eating through multiple levels.\n","- Market is volatile (spread > 5 bps) — anchor your execution price.\n","- You want to qualify for **maker rebates** (limit orders that rest in the book).\n","\n","### Binance-Specific Notes\n","- Default fee tier: **Taker 0.04% / Maker 0.02%** (USDT-margined perpetuals).\n","- Holding BNB in your account reduces fees by **25%**.\n","- The `TIME_IN_FORCE_GTC` flag keeps the order alive until it fills or you cancel it."]},{"cell_type":"markdown","metadata":{"id":"468ee75a"},"source":["## Resources"],"id":"468ee75a"},{"cell_type":"markdown","metadata":{"id":"2adb6410"},"source":["Here are some additional resources to deepen your understanding and further explore the capabilities of the `python-binance` library and Binance API:\n","\n","*   **`python-binance` GitHub Repository**: The official source code, detailed documentation, and examples for the `python-binance` library.\n","    [https://github.com/sammchardy/python-binance](https://github.com/sammchardy/python-binance)\n","\n","*   **Binance API Documentation**: Comprehensive documentation for all Binance API endpoints, including REST API, WebSocket, and more.\n","    [https://binance-docs.github.io/apidocs/spot/en/](https://binance-docs.github.io/apidocs/spot/en/)\n","\n","*   **Binance Testnet**: Information and access to the Binance Spot Testnet for risk-free development and testing.\n","    [https://testnet.binance.vision/](https://testnet.binance.vision/)\n","\n","*   **Binance Academy**: Educational articles and tutorials on various aspects of cryptocurrency trading, blockchain, and the Binance ecosystem.\n","    [https://academy.binance.com/](https://academy.binance.com/)"],"id":"2adb6410"}],"metadata":{"colab":{"provenance":[]},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.12.3"}},"nbformat":4,"nbformat_minor":5}