Order Management System¶
Place, modify, and cancel orders through a ServLoci-proxied session.
Part 16 of 37 in the ServLoci algo/options trading notebook series — full index in notebooks/README.md.
Setup¶
# Get your dedicated static IPv6 + SOCKS5 credentials free:
# https://comm.servloci.in/register (or /auth/google?free=1 for an instant trial)
# Your api_key / api_secret pair shows up in the portal after signup:
# https://comm.servloci.in/user
!pip install -q "requests[socks]"
!curl -sL https://comm.servloci.in/sdk/servloci.py -o servloci.py
import os
from servloci import ServLoci
SERVLOCI_API_KEY = os.environ.get("SERVLOCI_API_KEY", "dhan:1000000001") # broker:client_id
SERVLOCI_API_SECRET = os.environ.get("SERVLOCI_API_SECRET", "") # from the portal — leave blank to run this notebook in demo mode
sl = None
if SERVLOCI_API_SECRET:
sl = ServLoci(api_key=SERVLOCI_API_KEY, api_secret=SERVLOCI_API_SECRET)
print("ServLoci configured:", sl.host, sl.port)
else:
print("SERVLOCI_API_SECRET not set — running in demo mode (no live proxy calls).")
Why an order management layer exists¶
A strategy that talks to the broker's REST API directly is one retry away from a duplicate fill. An order management system (OMS) sits between "the strategy decided to buy" and "the broker accepted an order" as a boundary that owns retry safety, idempotency, and the order's lifecycle — so the strategy code never has to reason about network failures, partial responses, or "did that POST actually land."
Order types you'll route through this layer:
- Market — fill immediately at the best available price. Fast, but the fill price is not guaranteed, especially in a fast-moving or thin book.
- Limit — fill only at your price or better. Guarantees price, not execution — the order can sit unfilled if the market never reaches it.
- Stop-loss (SL) — becomes a limit order once a trigger price is touched. Used to cap downside without watching the screen.
- Stop-loss market (SL-M) — becomes a market order once triggered. Guarantees the exit happens, not the price it happens at.
Order lifecycle — every order moves through a small state machine:
pending (sent, not yet acknowledged) → open/trigger pending (accepted,
resting) → a terminal state: filled, partially filled, rejected, or
cancelled. A production OMS tracks which state an order is in and refuses to,
say, cancel an order that's already filled, or re-place one that's still pending
a broker acknowledgment — that's the idempotency guarantee: retrying a place()
call after a timeout should never risk two live orders for one intended trade.
class OrderManager:
"""Place / modify / cancel orders through a ServLoci-proxied session."""
def __init__(self, session, base_url):
self.session = session
self.base_url = base_url.rstrip("/")
def place(self, order: dict) -> dict:
r = self.session.post(f"{self.base_url}/orders", json=order, timeout=8)
r.raise_for_status()
return r.json()
def modify(self, order_id: str, changes: dict) -> dict:
r = self.session.put(f"{self.base_url}/orders/{order_id}", json=changes, timeout=8)
r.raise_for_status()
return r.json()
def cancel(self, order_id: str) -> dict:
r = self.session.delete(f"{self.base_url}/orders/{order_id}", timeout=8)
r.raise_for_status()
return r.json()
if sl:
oms = OrderManager(sl.session(), base_url=os.environ.get("BROKER_API_BASE", "https://api.example-broker.com/v1"))
order = {"symbol": "NIFTY24800CE", "transaction_type": "BUY", "quantity": 75, "order_type": "MARKET", "product": "INTRADAY"}
# resp = oms.place(order) # uncomment once BROKER_API_BASE + broker auth headers are set
print("OMS ready — set BROKER_API_BASE and auth headers, then uncomment oms.place(order)")
else:
print("Demo mode — set SERVLOCI_API_SECRET above to build a live OrderManager.")
Notice place(), modify(), and cancel() each map to exactly one broker endpoint and one lifecycle transition — that 1:1 mapping is what makes the layer auditable. If an order's state ever looks wrong, you can trace it to the single call that caused the transition, instead of hunting through strategy logic that also happens to talk to a broker.
« Previous: Position Sizing & Risk Management
Next: Paper Trading Loop »
Try the concepts above interactively: Options Strategy Builder · Docs · Get your static IP