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

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 if you still need the shared prerequisites.

margin_call_guard.py
#!/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())
  • Margin Call stream

  • Close Position

  • Get Open Positions

Was this helpful?