> 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/margin-call-guard.md).

# Margin Call Guard

Reduce cross positions automatically when a margin call arrives.

Use this script to act on margin calls even when you are away from the screen.

## What This Script Does

* Listens to the margin call stream and reconnects if the connection drops.
* On a margin call, loads your open `CROSS` positions.
* Closes `50%` of every position the margin call lists, at market.
* Reduces the same position at most once every `5` minutes, because margin calls repeat while the pool stays at risk.

Start with [Setup & Helpers](broken://pages/5f82d3397698cce89dbce1b8ec851e2c9aceba84) if you still need the shared prerequisites.

{% code title="margin\_call\_guard.py" %}

```python
#!/usr/bin/env python3
"""On a margin call, cut every CROSS position of the pool at risk by a fixed fraction."""
import asyncio
import json
import time
from decimal import Decimal

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

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

REDUCE = Decimal("0.5")   # close 50% of each position at risk
COOLDOWN = 300            # seconds before the same position may be reduced again

client = FuturesClient(API_KEY, API_SECRET)
lot = {p["gid"]: p["ls"] for p in get_pairs().values()}
last_cut = {}             # position id -> monotonic time of the last reduction


def reduce_positions(at_risk):
    open_cross = {p["id"]: p for p in client.get("/api/v1/positions", params={"mm": "CROSS"})}
    for item in at_risk:
        pos = open_cross.get(item["id"])
        if pos is None:
            continue   # already closed or liquidated
        if time.monotonic() - last_cut.get(pos["id"], -COOLDOWN) < COOLDOWN:
            print(f"  {item['symbol']} {item['side']}: reduced recently, skipping")
            continue
        qty = floor_to_step(pos["sz"] * REDUCE, lot[pos["pi"]])
        if qty <= 0:
            continue
        try:
            after = client.post(f"/api/v1/positions/{pos['id']}/close", {"q": qty})
            last_cut[pos["id"]] = time.monotonic()
            print(f"  {item['symbol']} {item['side']}: closed {qty}, left {after['sz']}")
        except FuturesApiError as err:
            print(f"  {item['symbol']} {item['side']}: close failed: {err}")


async def run():
    while True:
        try:
            ws = await connect_private(API_KEY, API_SECRET, "/ws/margin-call")
            ping = asyncio.create_task(keepalive(ws))
            print("watching margin calls…")
            try:
                async for raw in ws:
                    if raw == "pong":
                        continue
                    msg = json.loads(raw)
                    if msg.get("type") == "MARGIN_CALL":
                        print(f"MARGIN CALL at {time.strftime('%H:%M:%S', time.gmtime())} UTC")
                        # Blocking REST calls run off the event loop so pings keep flowing
                        await asyncio.to_thread(reduce_positions, msg.get("positions", []))
            finally:
                ping.cancel()
        except Exception as err:   # disconnected: margin calls are not replayed, reconnect fast
            print(f"stream lost ({err!r}), reconnecting")
            await asyncio.sleep(2)


asyncio.run(run())
```

{% endcode %}

{% hint style="warning" %}
Margin calls are not stored or replayed: one that fires while the script is disconnected is lost. A close that would leave less than one lot closes the whole position. Test the reduction rules on small positions first.
{% endhint %}

## Related Pages

* [Margin Call stream](broken://pages/89a1e88fa35f1e0581f4a113d958cf8bd799eeee)
* [Close Position](broken://pages/8a65b0267b58d7282fdacb75e81c6a9b308f8eac#close-position)
* [Get Open Positions](broken://pages/8a65b0267b58d7282fdacb75e81c6a9b308f8eac#get-open-positions)


---

# 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/margin-call-guard.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.
