Service · Python · REST · WebSocket

Broker API Trading Automation: Python for Forex and US Stocks

We build broker API trading automation: Python scripts that place orders, log fills and send alerts through official forex and stock broker APIs or the MetaTrader 5 (MT5) Python package. Traders in the UAE and across the Gulf run each script on their own PC or VPS, so their API keys stay with them.

  • Custom built
  • Demo testing before payment
  • Source code option
  • NDA on request
Broker API automation: a Python script trades through the broker's official REST and WebSocket API while the API keys stay on your machine

How it works

Rules → Code → Backtest → Deliver

  1. STEP 01

    Rules

    You share your entry, exit and risk rules in plain words.

  2. STEP 02

    Code

    We write clean MQL4, MQL5, Pine Script or Python code.

  3. STEP 03

    Backtest

    You test the build on your own demo account first.

  4. STEP 04

    Deliver

    You get the final file, a settings guide and setup help.

On this page
Broker API trading automation: Python script cycle from schedule and data fetch to your rules, the order, then a log and alert
One cycle of a scheduled script. It repeats at the interval set in your config file.

Who is this Python service for?

It suits traders whose work has outgrown a single chart. Most requests come from people who:

  • trade forex or stocks with a broker that offers an official API,
  • want a Python model to place trades on MT5 through the terminal,
  • copy fills into a spreadsheet by hand at the end of each day,
  • need alerts or a daily report without watching a screen.

Your broker may ship its own Python library, or only a plain REST API that any language can call. Python handles both. If the whole strategy lives on one MT5 chart, an MT5 Expert Advisor is often simpler, and we say which route fits before we quote.

Broker API trading automation: Python tasks we automate

A typical job combines several of these six tasks.

Task What the script does
Rule-based orders Reads prices, applies your rules and sends each order with a stop and a target
Scheduling Runs at fixed times, such as every five minutes or once at the market open, started by Windows Task Scheduler or a Linux service
Logging Writes every request, order and error to a dated log file, so you can trace what happened and when
Alerts Messages your Telegram bot or your email when an order fills, a rule triggers or a job fails
Data export Saves trade history, positions and prices to CSV or Excel files for your own records
Dashboard Shows open orders, recent fills, job status and errors on a simple local page in your browser
Five layers of a Python trading script, from your rules and risk checks down to the broker client, logs and your own PC or VPS
Risk checks sit between your rules and the broker client, so no order skips them.

How do broker REST and WebSocket APIs work?

Most forex and stock brokers that offer an API split it into two channels. The REST API answers requests: place an order, cancel it, read your positions. A WebSocket stream stays open and pushes live prices and order updates to the script as they happen.

Each broker sets its own limits on top. Many cap the number of requests per minute, and access tokens often expire after a set time. Our scripts count requests against the limit, renew tokens before they lapse and retry with short waits after a network error.

Retries carry one classic risk: a duplicate order. Where the API supports it, every order carries a client order ID that the script chooses. Before a retry, the script looks that ID up, and if the broker already holds the order, the script does not send it again.

A kill switch sits above all of this. It stops new orders once the script hits a daily limit or too many errors.

How do you automate US stock trades with Python?

Many Gulf traders reach US shares through a broker API, and that route needs three extra checks.

The first is order state. An HTTP 200 reply only means the broker received the request. After that, the order moves through states such as accepted, partially filled, filled, rejected or cancelled. Our scripts log a trade as done only once a final state arrives.

Next comes your market data plan. Some broker plans stream real-time prices from a single exchange and send the full market feed delayed unless you pay for it. A rule that reads delayed prices acts on old numbers, so we check your data feed before writing any rule.

The third check is the clock. The NYSE core session runs from 9:30 am to 4:00 pm New York time. In UAE time that is 6:30 pm to 1:00 am while the US is on winter time, and 5:30 pm to midnight during US summer time. Scheduled jobs run on the exchange clock in New York time, whatever time zone your PC uses.

Order status steps for a US stock order sent by a Python script, from HTTP 200 to a filled, rejected or cancelled final state
An HTTP 200 reply is not a fill. The script waits for the final order state.

What can the MetaTrader5 Python package do?

It gives MT5 traders a second route. The official MetaTrader5 package from MetaQuotes lets Python talk to a running MT5 terminal through your normal MT5 login. In it, initialize opens the connection to the terminal, copy_rates_from reads price bars, positions_get lists open positions and order_send passes a trade request from the terminal to the trade server. Each function has its own page in the MetaTrader5 Python package reference.

Two details from that reference shape our code. First, order_send returns a result with a return code (retcode), which the official example compares with TRADE_RETCODE_DONE. Our scripts write that code to the log with every order, along with the error from last_error() when a request fails. Second, each request can carry a magic number, an ID that tags the orders one script sends, so your reports can tell them apart from manual trades.

This route suits Python models that need MT5 prices, and traders who want reports from MT5 history. However, the terminal must stay open, and PyPI lists the package only as Windows builds. A Windows VPS is the usual home for these scripts.

Comparison of the MetaTrader5 Python package, which needs a Windows MT5 terminal, and a broker REST API that runs on Windows or Linux
Pick the MT5 route for MT5 symbols and history, and the REST route for a broker's own API.

Where do your API keys live?

Your keys stay on your own PC or VPS, in a local config file that you fill in yourself. They are the most sensitive part of any broker API setup, so we build and test with demo or paper keys that you create and never ask for your live ones.

  • The script loads keys from that local file or from Windows environment variables, never from the code itself.
  • Turn off any key permission the script does not need, such as withdrawals.
  • Logs stay clean, because keys and tokens never appear in log files or alerts.

Read your broker’s API terms and your local regulations as well. Some brokers ask you to apply for API access, while others limit automated trading on certain account types.

Config file panel with the demo or live switch, local key file, run schedule, order size cap, daily order cap, alerts and log retention
Example values. You change each one in the config file, with no code edit.

How a broker API trading automation project works

  1. Rules. You send your rules and a link to your broker’s API docs. We read the docs and confirm what the API allows before we quote.
  2. Code. We write commented Python, plus a config file for every setting you may change.
  3. Demo test. The script runs against the broker’s demo or paper environment. Where it makes sense, we also backtest your rules on past data first. A backtest and a demo run test different things, so we report them apart.
  4. Delivery. You get the files, a setup guide and a walkthrough on your PC or VPS.

What you receive

Every project ends with files you can run and maintain yourself:

  • a packaged Windows app that runs without a Python install,
  • the Python source code with comments, if you chose that option,
  • a requirements.txt file and a config template,
  • one setup guide for your PC or VPS, plus a walkthrough call,
  • 7 days of fixes after delivery.

Checklist of files delivered with a Python trading script: packaged app, optional source, config template, setup guide, walkthrough call and 7 days of fixes

Safe delivery on a demo or paper account

The trial build runs against your broker’s demo or paper environment, never a live account, and it carries an expiry date. After the final payment, you get the full build and, if you chose it, the Python source.

Trading UAE shares on DFM or ADX? Our page on UAE stock market API automation covers what a local broker connection can and cannot do.

Pricing for broker API trading automation (Python scripts)

A single scheduled script with logs and alerts starts from $100, which is about AED 367 or SAR 375 at the fixed dirham and riyal pegs of 3.6725 and 3.75 to the US dollar. A full rule-based trading script with a dashboard costs more, because it needs more testing. You get one fixed USD quote once we have read the API docs. Coding starts after a 50% deposit in USDT. The deposit is refunded only if you cancel before coding starts, and there is no refund once coding has begun. Our expert advisor development cost page compares typical ranges across services.

Prefer to keep TradingView as your signal source? Our TradingView to MT4/MT5 copier turns alerts into MetaTrader 4 (MT4) or MT5 trades. To mirror trades across your own accounts, see the MT4/MT5 trade copier. Trading Saudi shares instead? Our Saudi stock market automation page explains what you can automate on Tadawul today.

Sources

Frequently asked questions

Which brokers can you work with?

Any broker whose API documentation we can read, for forex or stocks, and any MT5 account through the MetaTrader5 package. We do not name or rank brokers. Without a demo or paper environment, safe testing gets harder, and you hear that from us before the quote.

Do you need my live API keys?

We never need them. We work only with demo or paper keys that you create. If a live key is ever exposed, revoke it in your broker's portal and create a new one. The script reads the new key from the config file, so no code change is needed.

Does the MetaTrader5 Python package work on a Mac?

It does not install on macOS itself. PyPI publishes the package only as Windows (win_amd64) builds, with no macOS or Linux files, so Mac users run it on a Windows VPS. A script for a broker REST API, on the other hand, can run on the Mac directly.

Is API trading allowed by my broker?

That depends on the broker's API agreement and on the type of account you hold, so we read the API docs you send before we quote and tell you if anything in them blocks the plan. Request limits are the other surprise: a free plan can allow far fewer requests per minute than a paid one, and we size the script's polling to the plan you have.

Can the script send alerts to Telegram?

It can. You create a bot with BotFather, which gives you the bot's token. Then you send the bot one message, because Telegram only lets a bot write to a user who has contacted it first. Each alert names the script, the event and the time in your Gulf time zone.

Do I need a VPS for broker API trading automation?

Python scripts that run all day need a VPS or a PC that never sleeps. Sleep mode and Windows updates are the usual reasons a home PC stops a script. A small Linux VPS is enough for most REST scripts, while the MetaTrader5 package needs a Windows one.

What happens if the internet drops?

After it reconnects, the script reads your open orders and positions from the broker before it does anything else. On MT5 that means calling orders_get and positions_get. An order sent just before the drop may have filled, and the script needs to know that before it acts again.

WhatsApp · Email · Telegram

Tell us what you want to automate

Send your rules on WhatsApp. You get a clear quote, then a demo build to test before you pay in full.