Build Stock Price Alerts with the moomoo OpenAPI and Python
A step-by-step Python guide: read live prices from the moomoo OpenAPI and send yourself Telegram alerts when a stock crosses your levels.
Affiliate disclosure. This post contains affiliate links. If you sign up or buy through them, I may earn a commission, at no extra cost to you.
Not financial advice. This is a programming guide, not a recommendation to buy or sell anything. Investing involves risk, including the loss of the money you invest. Check that any broker you use is licensed where you live.
Most trading apps let you set a price alert or two. But if you want alerts on your own terms, such as a whole watchlist, levels kept in a file, or messages sent to Telegram, you have to build them. moomoo has an OpenAPI that makes this a weekend project: a small local gateway connects to your moomoo account, and a Python library talks to the gateway.
This guide builds a price-alert bot step by step. It reads prices from the moomoo OpenAPI and sends a Telegram message when a stock crosses a level you choose. It only reads market data and never places orders.
How the moomoo OpenAPI works
There are two pieces:
- OpenD, a gateway program you run on your own computer or server. You sign in to it with your moomoo account, and it keeps the connection to moomoo's servers.
- The
moomoo-apiPython package, which your code uses to talk to OpenD over a local connection, by default127.0.0.1on port11111.
your Python script ⇄ OpenD (on your machine) ⇄ moomoo's servers
Because OpenD runs locally, your script never handles your moomoo password. It just connects to the gateway.
The API can do much more than this guide covers: historical candles, order books, option chains and, with extra setup, placing orders (including in a paper-trading environment). What you can access depends on your account, your region and the markets involved, and some real-time quotes need a quote subscription. Check moomoo's OpenAPI documentation for the details that apply to you.
What you need
- A moomoo account to sign in to OpenD.
- Python 3.9 or newer.
- A Telegram account, if you want alerts on your phone (optional: the bot can just print).
If you don't have a moomoo account yet:
Step 1: Install and start OpenD
Download OpenD from moomoo's OpenAPI page. It comes as a desktop app with a window, or as a command-line version for servers. Start it, sign in with your moomoo account, and leave it running. By default it listens on 127.0.0.1:11111, so only programs on the same machine can reach it.
Keep it that way. If you change OpenD's listening address so other machines can connect, anyone who can reach that port can use your session.
Step 2: Install the Python package
Use a virtual environment so the bot's dependencies stay separate:
python3 -m venv .venv
source .venv/bin/activate # on Windows: .venv\Scripts\activate
pip install moomoo-api
The package pulls in pandas, because most API calls return their data as a pandas DataFrame.
Step 3: Read a price
Start with a one-off snapshot, to check that everything is connected:
from moomoo import OpenQuoteContext, RET_OK
quote_ctx = OpenQuoteContext(host="127.0.0.1", port=11111)
ret, data = quote_ctx.get_market_snapshot(["US.AAPL", "US.MSFT"])
if ret == RET_OK:
print(data[["code", "last_price", "update_time"]])
else:
print("Error:", data)
quote_ctx.close() # always close, or the script keeps a connection open
Two conventions to know:
- Stock codes are prefixed with their market:
US.AAPLfor Apple in the US,HK.00700for Tencent in Hong Kong. - Every call returns a pair: a status (
RET_OKon success) and either the data or an error message. Always check the status before using the data.
If you get a connection error, check that OpenD is running and signed in. If you get a permissions error, your account may not have API quote access for that market.
Step 4: Decide the alert rules
Keep the rules in a JSON file, so you can change them without touching code:
{
"US.AAPL": { "above": 300, "below": 220 },
"US.MSFT": { "above": 600 }
}
These levels are placeholders for the example. Choose your own.
A naive bot that sends an alert every time the price is above a level would message you on every tick. Instead, the bot remembers which zone each stock is in (below, inside or above) and only sends a message when the zone changes:
def zone(price, rule):
if "above" in rule and price >= rule["above"]:
return "above"
if "below" in rule and price <= rule["below"]:
return "below"
return "inside"
If you edit the file by hand, the JSON formatter will point out a missing comma or quote before the bot trips over it.
Step 5: Send alerts to Telegram
Telegram bots are free and take two minutes to set up:
- In Telegram, message @BotFather, send
/newbotand follow the prompts. It gives you a bot token. - Send any message to your new bot, then open
https://api.telegram.org/bot<token>/getUpdatesin a browser. Your chat ID is in the response, underchat→id. - Keep both out of your code. Put them in environment variables:
export TELEGRAM_BOT_TOKEN="123456:ABC..." # from @BotFather
export TELEGRAM_CHAT_ID="123456789"
The token is a password for your bot: never commit it to Git or paste it into a public chat.
Sending a message needs nothing beyond the standard library:
import json
import os
import urllib.request
def notify(text):
token = os.environ.get("TELEGRAM_BOT_TOKEN")
chat_id = os.environ.get("TELEGRAM_CHAT_ID")
if not token or not chat_id:
print(text) # no Telegram set up: print instead
return
request = urllib.request.Request(
f"https://api.telegram.org/bot{token}/sendMessage",
data=json.dumps({"chat_id": chat_id, "text": text}).encode(),
headers={"Content-Type": "application/json"},
)
try:
urllib.request.urlopen(request, timeout=10)
except OSError as error:
print("Telegram failed:", error, "|", text)
Step 6: Live prices with push updates
Asking for a snapshot in a loop works, but the API can also push each new quote to you. You subscribe to the stocks, and a handler class receives every update:
import json
import time
from moomoo import OpenQuoteContext, RET_OK, StockQuoteHandlerBase, SubType
with open("alerts.json") as file:
RULES = json.load(file)
zones = {} # the last zone seen for each stock
class PriceAlerts(StockQuoteHandlerBase):
def on_recv_rsp(self, rsp_pb):
ret, data = super().on_recv_rsp(rsp_pb)
if ret != RET_OK:
print("Quote error:", data)
return ret, data
for _, row in data.iterrows():
code, price = row["code"], row["last_price"]
now = zone(price, RULES[code])
before = zones.get(code)
zones[code] = now
if before is not None and now != before:
if now == "above":
notify(f"📈 {code} is at {price}, above {RULES[code]['above']}")
elif now == "below":
notify(f"📉 {code} is at {price}, below {RULES[code]['below']}")
else:
notify(f"🔄 {code} is back inside its range, at {price}")
return RET_OK, data
quote_ctx = OpenQuoteContext(host="127.0.0.1", port=11111)
quote_ctx.set_handler(PriceAlerts())
ret, error = quote_ctx.subscribe(list(RULES), [SubType.QUOTE])
if ret != RET_OK:
quote_ctx.close()
raise SystemExit(f"Subscribe failed: {error}")
print("Watching", ", ".join(RULES), "(Ctrl+C to stop)")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
quote_ctx.close()
(Put the zone and notify functions from the earlier steps above the class.)
A few details worth noticing:
- The first quote only sets the starting zone. No alert fires on start-up, even if a stock is already above its level, so restarting the bot doesn't spam you. Remove the
before is not Nonecheck if you'd rather hear about it. - Subscriptions are limited. Each account has a quota of how many stocks it can subscribe to at once, so a watchlist of a few dozen stocks is fine, but not the whole market.
finallycloses the connection, even if the script crashes.
Step 7: Keep it running
The push version needs to run continuously while the market is open. Options, from simplest to sturdiest:
- Your own computer, while it's on. Fine for trying it out.
- A small always-on machine, such as a Raspberry Pi or a cheap cloud server, running OpenD's command-line version alongside the script, with a process manager such as systemd restarting both if they stop.
If you'd rather not keep a process running, use the snapshot version from Step 3 on a schedule. US markets open at 09:30 and close at 16:00 New York time, which is 13:30–20:00 UTC in summer and 14:30–21:00 UTC in winter. This cron line checks every 5 minutes across both, on weekdays (on a server set to UTC):
*/5 13-21 * * 1-5 /home/bot/.venv/bin/python /home/bot/check_prices.py >> /home/bot/alerts.log 2>&1
For Malaysia, that's roughly 21:30 to 05:00 the next morning, which is a good reason to automate it. The cron explainer shows the next run times for that line in your own time zone.
Good habits for any market-data bot
- Prices can gap. A stock that closes at 99 can open at 90, straight past your 95 alert. An alert tells you a level was crossed, not that you could have traded at it.
- Data can be delayed or wrong, and connections drop. Log what the bot sees, and don't assume silence means nothing happened.
- Keep it read-only. This bot never unlocks trading. If you ever automate orders, start in paper trading, add hard limits, and test far longer than feels necessary.
- Keep secrets out of code: environment variables for tokens, and OpenD on
127.0.0.1only. - Check that your broker is licensed where you live. According to moomoo, its Malaysian business is licensed by the Securities Commission Malaysia (SC). You can confirm any company on the SC's own list of licensed intermediaries before opening an account.
Summary
- The moomoo OpenAPI has two parts: the OpenD gateway on your machine, and the
moomoo-apiPython package. get_market_snapshotreads prices once, andsubscribewith a handler pushes every update.- Track each stock's zone so alerts fire on a change, not on every tick, and send them to Telegram with a few lines of standard-library code.
- Run it continuously, or on a cron schedule during market hours, and keep it read-only.
From here you can extend the bot with percentage moves, moving averages from historical candles, or a daily summary message. The structure stays the same: read data, decide, notify.