For the complete documentation index, see llms.txt. This page is also available as Markdown.

Limit Entry with Timeout

Rest a post-only limit below the best bid and cancel it if it does not fill in time.

Use this script to enter at a better price than the market, without leaving a stale order behind.

What This Script Does

  • Reads the best bid and sizes a $500 position at a limit price 0.2% below it

  • Connects to the account stream before placing the order, so the fill cannot be missed

  • Places a post-only LIMIT OPEN_LONG

  • Waits up to 120 seconds for the order to fill

  • Cancels the order if it is still resting at the deadline

Start with Setup & Helpers if you still need the shared prerequisites.

limit_entry.py
#!/usr/bin/env python3
"""Rest a post-only limit LONG below the best bid; cancel it if it does not fill in time."""
import asyncio
import json
import time
from decimal import Decimal

from futures_helpers import (FuturesClient, FuturesApiError, best_quote, connect_private,
                             floor_to_step, get_pairs, keepalive)

API_KEY = "your-api-key"
API_SECRET = "your-api-secret"

SYMBOL = "ETHUSDT"
NOTIONAL = Decimal("500")     # USD position value at the limit price
LEVERAGE = Decimal("10")
DISCOUNT = Decimal("0.002")   # limit price 0.2% below the best bid
TIMEOUT = 120                 # seconds to wait for the fill


async def run():
    client = FuturesClient(API_KEY, API_SECRET)
    pair = get_pairs()[SYMBOL]

    # Step 1 — Price and size
    bid, ask = await best_quote(pair["gid"])
    price = floor_to_step(bid * (1 - DISCOUNT), pair["ts"])
    qty = floor_to_step(NOTIONAL / price, pair["ls"])
    print(f"{SYMBOL} bid {bid} / ask {ask}  →  limit {qty} @ {price}")

    # Step 2 — Listen to the account stream BEFORE placing, so the fill cannot be missed
    ws = await connect_private(API_KEY, API_SECRET, "/ws/account")
    ping = asyncio.create_task(keepalive(ws))
    try:
        # Step 3 — Place the resting limit (post-only: rejected instead of taking liquidity)
        try:
            order = client.post("/api/v1/orders", {
                "pi": pair["gid"], "d": "OPEN_LONG", "ty": "LIMIT",
                "q": qty, "p": price, "l": LEVERAGE, "mm": "ISOLATED", "pso": True,
            })
        except FuturesApiError as err:
            raise SystemExit(f"order rejected: {err}")
        print(f"resting order {order['id']}, reserved fee {order['f']}")

        # Step 4 — Wait for FILLED / CANCELLED of this order id
        deadline = time.monotonic() + TIMEOUT
        while True:
            left = deadline - time.monotonic()
            if left <= 0:
                client.delete(f"/api/v1/orders/{order['id']}")
                print(f"not filled in {TIMEOUT}s: cancelled")
                return
            try:
                raw = await asyncio.wait_for(ws.recv(), timeout=left)
            except asyncio.TimeoutError:
                continue
            if raw == "pong":
                continue
            msg = json.loads(raw, parse_float=Decimal)
            if msg.get("e") != "ORDER" or msg["d"]["id"] != order["id"]:
                continue
            if msg["a"] == "FILLED":
                print(f"filled {msg['d']['fq']} @ {msg['d']['afp']}, position {msg['d']['po']}")
                return
            if msg["a"] == "CANCELLED":
                print("order was cancelled")
                return
    finally:
        ping.cancel()
        await ws.close()


asyncio.run(run())

With pso: true an order that would execute immediately is rejected (FUT-1103) instead of taking liquidity. A resting limit reserves margin plus maker fee until it fills or is cancelled.

  • Place Order

  • Cancel Order

  • Account stream

  • Best Quote

Was this helpful?