> For the complete documentation index, see [llms.txt](https://docs.outpoll.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.outpoll.com/api/futures-api/python-examples/futures-examples/limit-entry-with-timeout.md).

# 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](broken://pages/5f82d3397698cce89dbce1b8ec851e2c9aceba84) if you still need the shared prerequisites.

{% code title="limit\_entry.py" %}

```python
#!/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())
```

{% endcode %}

{% hint style="info" %}
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.
{% endhint %}

### Related Pages

* [Place Order](broken://pages/2d7e1d40d8e19f9de1a0ebe485fd2e9a598d0b28#place-order)
* [Cancel Order](broken://pages/2d7e1d40d8e19f9de1a0ebe485fd2e9a598d0b28#cancel-order)
* [Account stream](broken://pages/cedd682d52eba2750e492fcfadf9fb27ca28deb8)
* [Best Quote](broken://pages/f1d5d4ce1e41b692bc11f5d61d9c6799c0f9477e)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.outpoll.com/api/futures-api/python-examples/futures-examples/limit-entry-with-timeout.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
