### Basic fetch example with pandas Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Example from the repository README pattern. Connects to a local MT5 instance, fetches live and historical rates, prints the last rows, and closes the connection. ```python import pandas as pd from siliconmetatrader5 import MetaTrader5 mt5 = MetaTrader5(host="localhost", port=8001) if not mt5.initialize(): raise RuntimeError("MT5 initialization failed!") live_rates = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_M15, 0, 150) hist_rates = mt5.copy_rates_range("EURUSD", mt5.TIMEFRAME_M15, dt_from, dt_to) print(pd.DataFrame(live_rates).tail()) mt5.close() ``` -------------------------------- ### Start the System with Colima and Docker Compose Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Starts the system by checking if Colima is running and starting it if not, then launches Docker Compose in detached mode from the docker directory. ```bash if colima status 2>/dev/null | grep -q "colima is running"; then echo "Colima is ready 🟢" else colima start fi cd docker && docker compose up -d ``` -------------------------------- ### Build and run KasmVNC MT5 runtime Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Use these commands from the docker_kasm/ directory to stop any existing containers, rebuild the KasmVNC-based MT5 runtime image, and start it. The runtime installs MetaTrader 5 into a persistent prefix and opens the desktop for first broker login. ```bash cd docker_kasm docker compose down -v docker compose build docker compose up ``` -------------------------------- ### Market book lifecycle example Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Example showing the market book lifecycle: add, get, and release the order book for EURUSD, with cleanup in a finally block. ```python mt5 = MetaTrader5(host="localhost", port=8001) try: mt5.market_book_add("EURUSD") book = mt5.market_book_get("EURUSD") finally: mt5.market_book_release("EURUSD") mt5.close() ``` -------------------------------- ### Basic usage example Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Shows how to create a MetaTrader5 instance, initialize the connection, and close it. Raises an error if initialization fails. ```python from siliconmetatrader5 import MetaTrader5 mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) if not mt5.initialize(): raise RuntimeError("MT5 initialization failed: %s" % mt5.last_error()) mt5.close() ``` -------------------------------- ### MetaTrader5.__init__ Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Documentation for the MetaTrader5 class constructor, including parameters, behavior, and usage examples. ```APIDOC ## Constructor ### Description Initializes a connection to the MetaTrader5 bridge server using RPyC. It connects immediately, configures the connection for unbounded synchronous timeouts, binds the remote MetaTrader5 module, and optionally starts a background serving thread for async callbacks. ### Method Constructor ### Signature ```python def __init__(self, host="localhost", port=18812, keepalive=False, timeout=None): ``` ### Parameters - **host** (str) - Optional - Host or IP of the bridge server (the Docker container publishing port 8001). Default: `"localhost"`. - **port** (int) - Optional - TCP port of the RPyC classic server. Deployment uses `8001`. Default: `18812`. - **keepalive** (bool) - Optional - When `True`, starts an `rpyc.utils.helpers.BgServingThread` on the connection so the bridge can make async callbacks/streaming work. Default: `False`. - **timeout** (Any) - Optional - Deprecated and ignored; kept for backward compatibility. The synchronous request timeout is deliberately set to `None` (unbounded) on the connection. Default: `None`. ### Behavior 1. Stores host/port/keepalive and initializes internal state: an `RLock` (`__rpc_lock`) serializing all remote calls, an in-flight-call tracker, watchdog thread state (`__watchdog_stop_event`, `__watchdog_thread`, `__watchdog_cfg`), and a health dict (`__health`). 2. Connects immediately: `self.__conn = rpyc.classic.connect(host, port)`. 3. Sets `self.__conn._config["sync_request_timeout"] = None` (unbounded, to avoid false timeouts on slow emulated environments). 4. Binds the remote module via `self.__conn.modules.MetaTrader5`, falling back to `conn.execute("import MetaTrader5 as mt5")` + `conn.eval("mt5")` for older RPyC deployments. 5. Runs `conn.execute("import MetaTrader5 as mt5\nimport datetime")` so `eval`-based calls (`mt5.(...)`) always resolve. 6. If `keepalive=True`, starts `BgServingThread(self.__conn)`. Connection failures during construction surface as raw `rpyc` exceptions — the constructor is not wrapped by `_wrap_error`; only method calls after construction normalize errors. ### Example — basic use ```python from siliconmetatrader5 import MetaTrader5 mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) if not mt5.initialize(): raise RuntimeError("MT5 initialization failed: %s" % mt5.last_error()) mt5.close() ``` ### Example — long-running bot with watchdog and graceful teardown ```python from siliconmetatrader5 import MetaTrader5 mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) mt5.start_watchdog(interval_sec=5.0, max_miss=3, auto_reconnect=True) def on_unhealthy(snapshot): print("bridge degraded:", snapshot["last_error_reason"]) mt5.start_watchdog(on_unhealthy=on_unhealthy) try: # ... strategy loop ... pass finally: mt5.close() # disconnects only this client; remote terminal stays up ``` ``` -------------------------------- ### Start classic VNC desktop services (Xvfb, x11vnc, noVNC proxy) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/endpoints.md Shell commands from docker/start.sh that launch the classic VNC desktop environment for the docker runtime. Starts Xvfb on display :100, x11vnc on port 5901 with no password and caching, and the noVNC proxy on port 6081. Used for manual broker login and visual monitoring, not by the client library. ```bash Xvfb :100 -ac -screen 0 1024x768x16 & x11vnc -display :100 -forever -rfbport 5901 -nopw -ncache 10 & /siliconmt5/noVNC-master/utils/novnc_proxy --vnc localhost:5901 --listen 6081 & ``` -------------------------------- ### Install Homebrew and required packages for MT5 on macOS Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Installs Homebrew and the required packages for running MetaTrader5 on macOS via emulation. The Homebrew command is skipped if already installed; the brew install command installs colima, docker, qemu, lima, and lima-additional-guestagents. ```bash # 1. Install Homebrew (skip if you already have it) /bin/bash -c "$(curl -fsSL [https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh](https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh))" # 2. Install Emulation & Container required packages brew install colima docker qemu lima lima-additional-guestagents ``` -------------------------------- ### Start Colima with x86_64 emulation for MT5 Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Starts Colima with x86_64 emulation using QEMU, allocating 4 CPUs and 8GB memory. The commented colima delete -f command is provided as an optional reset if the Colima state is broken. ```bash # Optional: Reset if Colima state is broken # colima delete -f colima start --arch x86_64 --vm-type=qemu --cpu 4 --memory 8 ``` -------------------------------- ### Watchdog loop semantics and example Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-watchdog.md Describes the internal loop behavior of the watchdog and provides an example of starting a watchdog with an unhealthy callback and auto-reconnect. ```APIDOC ## Watchdog loop semantics The loop (`_watchdog_loop`, `__init__.py:436`) runs every `interval_sec` and: 1. Records `last_probe_ts` and the current `inflight_operation`. 2. If a remote call is in flight: - while younger than `stall_timeout_sec`, sets status `busy` and skips probing; - when older than `stall_timeout_sec`, treats it as a failure with error string `CALL_STUCK::.2fs`. 3. Otherwise probes: `conn.ping()` plus a remote `mt5.version()` call under the RLock, using `probe_timeout_sec` as a temporary `sync_request_timeout`. 4. Success resets `consecutive_failures=0`, status `healthy`. Failure increments `consecutive_failures` and classifies the reason via `_classify_probe_error` (`__init__.py:365`), which maps error text to `TIMEOUT`, `RESULT_EXPIRED`, `CONNECTION_CLOSED`, or `PROBE_FAILED` (strings pass through; `MT5BridgeError` yields its `reason_code`; a closed client yields `CLOSED`). 5. Status becomes `degraded` until `consecutive_failures >= max_miss`, then `unhealthy`; the `on_unhealthy` callback fires once per transition. 6. When `unhealthy` and `auto_reconnect=True`, `_attempt_reconnect()` (`__init__.py:404`) closes the old connection, reconnects with `rpyc.classic.connect`, re-binds the remote module, restarts `BgServingThread` if keepalive is on, and on success sets status `recovered`. ### Example — watchdog with unhealthy callback and reconnect ```python from siliconmetatrader5 import MetaTrader5 mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) def on_unhealthy(snapshot): print("unhealthy:", snapshot["last_error_reason"], "failures:", snapshot["consecutive_failures"]) mt5.start_watchdog( interval_sec=5.0, max_miss=3, probe_timeout_sec=2.0, stall_timeout_sec=30.0, auto_reconnect=True, on_unhealthy=on_unhealthy, ) # ... long-running bot loop ... print(mt5.health_status()["status"]) # 'healthy' | 'busy' | 'degraded' | 'unhealthy' mt5.close() # stop_watchdog is invoked internally by close() ``` ``` -------------------------------- ### Install siliconmetatrader5 1.2.3 Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Upgrade the Python client package to version 1.2.3, which fixes the packaged bridge server layout. ```bash python3 -m pip install --upgrade siliconmetatrader5==1.2.3 ``` -------------------------------- ### Lifecycle example with error handling Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Example showing how to ping the bridge and close the connection while keeping the shared terminal alive for other bots. Uses remote_shutdown=False in the finally block to avoid shutting down the remote terminal. ```python mt5 = MetaTrader5(host="localhost", port=8001) try: ok = mt5.ping() if not ok: print("bridge not reachable") finally: # keep shared terminal alive for other bots mt5.close(remote_shutdown=False) ``` -------------------------------- ### Initialize MT5 server with docker compose up --build Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Initializes the MT5 server by switching to the colima Docker context and running docker compose up --build. Option A runs in the foreground for live logs (recommended for first setup), while Option B runs detached in the background once stable. ```bash cd docker docker context use colima # Option A: Foreground (See live logs - Recommended for first setup) docker compose up --build # Option B: Detached (Run in background once stable) # docker compose up --build -d ``` -------------------------------- ### Launch server inside container (docker/start.sh) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/bridge-server.md Command to start the server inside the container using the package entry point with Windows Python. Uses the host from environment variable and port 8001. ```bash wine python -m siliconmetatrader5 "C:/Python/python.exe" --host "$MT5_HOST" -p 8001 ``` -------------------------------- ### Example — raw ticks with normalization Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Example usage of copy_ticks_range to fetch ticks for EURUSD over the last hour. ```APIDOC ## Example — raw ticks with normalization ### Description Example usage of copy_ticks_range to fetch ticks for EURUSD over the last hour. ### Code ```python from datetime import datetime, timedelta mt5 = MetaTrader5(host="localhost", port=8001) ticks = mt5.copy_ticks_range( "EURUSD", datetime.now() - timedelta(hours=1), datetime.now(), mt5.COPY_TICKS_TRADE, ) print(len(ticks), ticks[-1] if ticks else None) mt5.close() ``` ``` -------------------------------- ### Custom binding with TLS and TCP registry Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/bridge-server.md Command to start the server with threaded mode, TLS certificates, and a TCP registry. Note that the repository's launch scripts do not pass these flags, so the live deployment is unauthenticated plain TCP. ```bash wine python tmp/siliconmetatrader5/server.py -m threaded --host 0.0.0.0 -p 8001 \ --ssl-keyfile key.pem --ssl-certfile cert.pem --ssl-cafile ca.pem \ --registry-type TCP --registry-host 10.0.0.5 --register ``` -------------------------------- ### Start runtime supervisor Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/kasm-runtime.md Executed by the container's autostart mechanism (defaults/autostart) to launch the runtime supervisor in the background. This is the entry point for the Kasm runtime session. ```bash /siliconmt5/scripts/runtime-supervisor.sh & ``` -------------------------------- ### Dockerfile dependencies (requirements.txt) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/docker-runtime.md Pinned Python dependencies for the Wine environment. Installed via `wine pip install -r requirements.txt` during the Docker build. Exact pins are shown. ```plaintext MetaTrader5 siliconmetatrader5==1.2.3 rpyc ``` -------------------------------- ### start_watchdog Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-watchdog.md Starts the watchdog daemon thread for the MetaTrader5 client, with configurable probing and health monitoring parameters. ```APIDOC ## `start_watchdog` ### Description Starts the watchdog daemon thread that periodically probes the RPyC connection and the remote `MetaTrader5` module, detects frozen or stalled calls, optionally reconnects, and exposes a machine-readable health snapshot. Returns `True` if a watchdog thread was started, `False` if one is already alive. ### Method `start_watchdog` ### Signature ```python def start_watchdog( self, interval_sec: float = 5.0, max_miss: int = 3, probe_timeout_sec: float = 2.0, stall_timeout_sec: float = 20.0, auto_reconnect: bool = False, on_unhealthy: Optional[Callable[[Dict[str, Any]], None]] = None, ) -> bool: ``` ### Parameters - `interval_sec` (float) - Optional - Default: `5.0` - Watchdog loop period; clamped to a minimum of `0.05`. - `max_miss` (int) - Optional - Default: `3` - Consecutive failed probes that mark the bridge `unhealthy`; clamped to a minimum of `1`. - `probe_timeout_sec` (float) - Optional - Default: `2.0` - Timeout used for the connection ping + remote `mt5.version()` probe; clamped to a minimum of `0.05`. - `stall_timeout_sec` (float) - Optional - Default: `20.0` - Age (in seconds) after which an in-flight remote call is considered stuck; clamped to a minimum of `0.2`. - `auto_reconnect` (bool) - Optional - Default: `False` - When `True`, attempts `_attempt_reconnect()` once the bridge is unhealthy. - `on_unhealthy` (Optional[Callable[[Dict[str, Any]], None]]) - Optional - Default: `None` - Called once on transition to `unhealthy`, with a health snapshot dict. Exceptions raised by the callback are swallowed. ### Returns - `bool` - `True` if a watchdog thread was started, `False` if one is already alive. ### Errors - `RuntimeError` - Raised if the client is closed ("Cannot start watchdog on closed MetaTrader5 client"). ``` -------------------------------- ### Launch server in docker_kasm variant (scripts/launch-bridge.sh) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/bridge-server.md Command to start the server in the docker_kasm variant, using a different Python path and binding to all interfaces. ```bash wine python -m siliconmetatrader5 "C:/Program Files/Python313/python.exe" --host 0.0.0.0 -p 8001 ``` -------------------------------- ### Docker Compose usage commands Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/docker-runtime.md Commands to start, run, and stop the Docker container using Docker Compose with Colima context. The first run builds (~5–10 min) and boots (~25–30 min), then requires logging into the broker at http://localhost:6081/vnc.html (no password) before running clients. ```bash # macOS host, after `colima start --arch x86_64 --vm-type=qemu --cpu 4 --memory 8` cd docker docker context use colima docker compose up --build # foreground (recommended first run) # or detached: docker compose up --build -d docker compose down # stop ``` -------------------------------- ### start_watchdog method signature Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-watchdog.md Signature of the start_watchdog method from siliconmetatrader5/__init__.py:497. Use it to start the watchdog daemon thread that probes the RPyC connection and remote MetaTrader5 module. Parameters include interval_sec (clamped to min 0.05), max_miss (clamped to min 1), probe_timeout_sec (clamped to min 0.05), stall_timeout_sec (clamped to min 0.2), auto_reconnect (when True attempts _attempt_reconnect() once unhealthy), and on_unhealthy (called once on transition to unhealthy; exceptions swallowed). Returns True if a watchdog thread was started, False if one is already alive. Raises RuntimeError "Cannot start watchdog on closed MetaTrader5 client" if the client is closed. ```python def start_watchdog( self, interval_sec: float = 5.0, max_miss: int = 3, probe_timeout_sec: float = 2.0, stall_timeout_sec: float = 20.0, auto_reconnect: bool = False, on_unhealthy: Optional[Callable[[Dict[str, Any]], None]] = None, ) -> bool: ``` -------------------------------- ### Build and run Kasm runtime with Docker Compose Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/kasm-runtime.md Build and start the Kasm runtime container from the docker_kasm directory. The -v flag on down removes volumes, ensuring a clean state. After startup, access the KasmVNC web UI at http://localhost:3000. ```bash cd docker_kasm docker compose down -v docker compose build docker compose up ``` -------------------------------- ### Example — raw ticks with normalization Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Example usage of copy_ticks_range to fetch raw ticks for EURUSD over the past hour, using COPY_TICKS_TRADE flag. Demonstrates connecting to a local MetaTrader5 instance, normalizing datetime objects, and printing the count and last tick. ```python from datetime import datetime, timedelta mt5 = MetaTrader5(host="localhost", port=8001) ticks = mt5.copy_ticks_range( "EURUSD", datetime.now() - timedelta(hours=1), datetime.now(), mt5.COPY_TICKS_TRADE, ) print(len(ticks), ticks[-1] if ticks else None) mt5.close() ``` -------------------------------- ### Fetch live MT5 data with siliconmetatrader5 Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Boilerplate to start fetching data instantly. Initializes the bridge, fetches live EURUSD M15 rates, prints the last 150 bars, and closes gracefully. ```python import pandas as pd from siliconmetatrader5 import MetaTrader5 # Initialize Bridge mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) if not mt5.initialize(): raise RuntimeError("🚨 MT5 initialization failed!") # Fetch Live Data rates_live = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_M15, 0, 150) print(pd.DataFrame(rates_live).tail()) # Graceful Exit mt5.close() ``` -------------------------------- ### Two-day history window example Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-trading.md Queries a two-day history window: prints total orders and deals, then iterates over deals printing time, symbol, type, and volume. Uses datetime and timedelta for the interval. ```python from datetime import datetime, timedelta mt5 = MetaTrader5(host="localhost", port=8001) now = datetime.now() frm = now - timedelta(days=2) print("orders:", mt5.history_orders_total(frm, now)) print("deals:", mt5.history_deals_total(frm, now)) for deal in mt5.history_deals_get(frm, now) or []: print(deal["time"], deal["symbol"], deal["type"], deal["volume"]) mt5.close() ``` -------------------------------- ### Runtime invocations of python -m siliconmetatrader5 Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/entrypoint-cli.md Invocation examples from the repository runtimes. Both use `wine python -m siliconmetatrader5` with a Windows Python path and `-p 8001`; the first uses the `$MT5_HOST` variable, the second uses `0.0.0.0`. ```bash # docker/start.sh (Wine Python from the base image layout) wine python -m siliconmetatrader5 "C:/Python/python.exe" --host "$MT5_HOST" -p 8001 ``` ```bash # docker_kasm/scripts/launch-bridge.sh (installed Windows Python 3.13) wine python -m siliconmetatrader5 "C:/Program Files/Python313/python.exe" --host 0.0.0.0 -p 8001 ``` -------------------------------- ### copy_rates_from Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Retrieves historical rate bars for a symbol starting from a specified date. Returns a list of rate-bar dictionaries. ```APIDOC ## copy_rates_from ### Description Retrieves historical rate bars for a symbol starting from a specified date. Returns a list of rate-bar dictionaries. ### Method copy_rates_from ### Signature ```python def copy_rates_from(self, symbol, timeframe, date_from, count): ``` ### Parameters - **symbol** (str) - Required - Symbol name, e.g. "EURUSD". - **timeframe** (int) - Required - One of the TIMEFRAME_* class constants. - **date_from** (datetime / int) - Required - Start of the interval; datetime is converted to epoch seconds. - **count** (int) - Required - Maximum number of bars. ### Returns List of rate-bar dicts; each row contains at least `time`, `open`, `high`, `low`, `close`, `tick_volume`, `spread`. `None` or an empty list is returned when there is no history. Recommended for backtesting. ``` -------------------------------- ### Checking and sending a market order with error handling Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-trading.md Example of checking and sending a market order with error handling. It initializes the client, builds a request dict for a EURUSD buy, sends it via order_send, and checks the retcode against TRADE_RETCODE_DONE. Catches MT5BridgeError and prints the reason_code and operation. ```python from siliconmetatrader5 import MetaTrader5, MT5BridgeError mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) if not mt5.initialize(): raise RuntimeError("initialization failed: %s" % mt5.last_error()) request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": "EURUSD", "volume": 0.01, "type": mt5.ORDER_TYPE_BUY, "price": 1.08, # market price at reference point "deviation": 20, "magic": 123456, } try: result = mt5.order_send(request) except MT5BridgeError as e: print("bridge error:", e.reason_code, e.operation) raise if result["retcode"] != mt5.TRADE_RETCODE_DONE: print("trade rejected:", result["retcode"], result.get("comment")) mt5.close() ``` -------------------------------- ### Error handling on fetch methods Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Example showing error handling for the three fetch methods. Catches MT5BridgeError, prints reason_code, operation, and cause, then closes the connection. Also handles the case where no data is returned. ```python from siliconmetatrader5 import MetaTrader5, MT5BridgeError mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) try: rates = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_M5, 0, 100) except MT5BridgeError as e: print("reason_code:", e.reason_code) # e.g. "CONNECTION_CLOSED" / "TIMEOUT" print("operation:", e.operation) # e.g. "copy_rates_from_pos" print("cause:", e.cause) mt5.close() raise if not rates: print("no data yet — broker sync may still be running") mt5.close() ``` -------------------------------- ### Long-running bot with watchdog and graceful teardown Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Demonstrates starting a watchdog with custom unhealthy callback and closing the client in a finally block. The close only disconnects this client; the remote terminal stays up. ```python from siliconmetatrader5 import MetaTrader5 mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) mt5.start_watchdog(interval_sec=5.0, max_miss=3, auto_reconnect=True) def on_unhealthy(snapshot): print("bridge degraded:", snapshot["last_error_reason"]) mt5.start_watchdog(on_unhealthy=on_unhealthy) try: # ... strategy loop ... pass finally: mt5.close() # disconnects only this client; remote terminal stays up ``` -------------------------------- ### copy_rates_from method signature Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Signature of the copy_rates_from method, copied exactly from source. Use to fetch a specified number of rate bars starting from a given date. ```python def copy_rates_from(self, symbol, timeframe, date_from, count): ``` -------------------------------- ### Start watchdog with unhealthy callback and reconnect Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-watchdog.md Configures a watchdog to monitor a remote MetaTrader5 connection. The on_unhealthy callback fires on each transition to unhealthy, printing the last error reason and consecutive failures. With auto_reconnect=True, the library attempts to reconnect when unhealthy. The health status can be 'healthy', 'busy', 'degraded', or 'unhealthy'. Closing the client internally calls stop_watchdog. ```python from siliconmetatrader5 import MetaTrader5 mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) def on_unhealthy(snapshot): print("unhealthy:", snapshot["last_error_reason"], "failures:", snapshot["consecutive_failures"]) mt5.start_watchdog( interval_sec=5.0, max_miss=3, probe_timeout_sec=2.0, stall_timeout_sec=30.0, auto_reconnect=True, on_unhealthy=on_unhealthy, ) # ... long-running bot loop ... print(mt5.health_status()["status"]) # 'healthy' | 'busy' | 'degraded' | 'unhealthy' mt5.close() # stop_watchdog is invoked internally by close() ``` -------------------------------- ### Import siliconmetatrader5.server and access ClassicServer Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/bridge-server.md Shows the import path for the bridge-server module and how to access the ClassicServer application class. ```python import siliconmetatrader5.server as bridge_server classic_server_app = bridge_server.ClassicServer ``` -------------------------------- ### copy_ticks_from signature Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Signature of the copy_ticks_from method, which retrieves a specified number of ticks starting from a given date. Parameters include symbol, start time, count, and flags (COPY_TICKS_ALL, COPY_TICKS_INFO, COPY_TICKS_TRADE). Returns a list of tick dicts. ```python def copy_ticks_from(self, symbol, date_from, count, flags): ``` -------------------------------- ### Configure screen resolution in docker/start.sh Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Adjust visual settings in docker/start.sh. The Xvfb line sets the screen resolution; the openbox line is optional and may increase VNC latency. Apply changes with 'cd docker && docker compose up --build -d'. ```bash # Resolution setup Xvfb :100 -ac -screen 0 1366x768x24 & # Window Manager (Optional - May increase VNC latency) # openbox & ``` -------------------------------- ### initialize(*args, **kwargs) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Forwards arguments to the remote module's initialize method via _remote_call. Used to initialize the MetaTrader 5 connection. ```APIDOC ## Python Function: initialize(*args, **kwargs) ### Description Forwards all arguments and keyword arguments to the remote module method of the same name via `_remote_call`. ### Signature ```python def initialize(self, *args, **kwargs): ``` ### Parameters - **args** (tuple) - Optional - Positional arguments forwarded to the remote method. - **kwargs** (dict) - Optional - Keyword arguments forwarded to the remote method. ### Returns The result of the remote method call. ``` -------------------------------- ### copy_ticks_from Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Retrieves a specified number of ticks for a symbol starting from a given date. The method returns a list of tick dictionaries. ```APIDOC ## copy_ticks_from ### Description Retrieves a specified number of ticks for a symbol starting from a given date. The method returns a list of tick dictionaries. ### Method copy_ticks_from ### Signature ```python def copy_ticks_from(self, symbol, date_from, count, flags): ``` ### Parameters - **symbol** (str) - Required - Symbol name. - **date_from** (datetime / int) - Required - Start time; normalized to epoch seconds. - **count** (int) - Required - Number of ticks. - **flags** (int) - Required - `COPY_TICKS_ALL` / `COPY_TICKS_INFO` / `COPY_TICKS_TRADE` (see constants). ### Returns List of tick dicts (remote obtains the result locally). ``` -------------------------------- ### copy_rates_from_pos Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Retrieves rate bars for a symbol starting from a bar index offset from the current (last) bar. Returns a list of rate-bar dictionaries. ```APIDOC ## copy_rates_from_pos ### Description Retrieves rate bars for a symbol starting from a bar index offset from the current (last) bar. Returns a list of rate-bar dictionaries. ### Method copy_rates_from_pos ### Signature ```python def copy_rates_from_pos(self, symbol, timeframe, start_pos, count): ``` ### Parameters - **symbol** (str) - Required - Symbol name. - **timeframe** (int) - Required - TIMEFRAME_* constant. - **start_pos** (int) - Required - Bar index offset from the current (last) bar; `0` = newest bars. - **count** (int) - Required - Number of bars. ### Returns List of rate-bar dicts. Recommended for live monitoring / fresh bars. ``` -------------------------------- ### Manual run with explicit work directory Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/entrypoint-cli.md Manual run with an explicit work directory via `-s /siliconmt5/bridge`. Uses `python3` instead of `wine python` and passes `--host 0.0.0.0 -p 8001`. ```bash python3 -m siliconmetatrader5 "C:/Python/python.exe" --host 0.0.0.0 -p 8001 -s /siliconmt5/bridge ``` -------------------------------- ### Fetch live and historical rates with copy_rates_from_pos() and copy_rates_range() Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Shows two MetaTrader5 data retrieval methods: copy_rates_from_pos() for live monitoring and copy_rates_range() for historical backtesting. The live call fetches the latest 500 M5 bars for EURUSD, while the historical call retrieves bars between dt_from and dt_to. ```python # 🟢 Live Data Fetching live_rates = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_M5, 0, 500) # 🕒 Historical Backtesting hist_rates = mt5.copy_rates_range("EURUSD", mt5.TIMEFRAME_M5, dt_from, dt_to) ``` -------------------------------- ### Verify connection with test_fetch.py and test_plot.py Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Runs the built-in tests to verify the connection and data flow. A successful connection and data output indicate readiness to build bots. ```bash python tests/test_fetch.py python tests/test_plot.py ``` -------------------------------- ### copy_ticks_range signature Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-data.md Signature of the copy_ticks_range method, which retrieves ticks within a date interval. Parameters include symbol, interval start, interval end, and a COPY_TICKS_* constant. Returns a list of tick dicts. ```python def copy_ticks_range(self, symbol, date_from, date_to, flags): ``` -------------------------------- ### main() argparse CLI definition Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/entrypoint-cli.md Defines the argparse CLI for `python -m siliconmetatrader5`. The positional `python` argument must be a Windows Python path; `--host` defaults to `localhost`, `-p/--port` defaults to `DEFAULT_SERVER_PORT` (18812), and `-s/--server` defaults to `tmp/siliconmetatrader5`. ```python def main(): parser = argparse.ArgumentParser(description="Create Server.") parser.add_argument( "python", type=str, help="Python that will run the server (have to be a Windows version!)" ) parser.add_argument( "--host", type=str, default="localhost", help="The host to connect to. The default is localhost" ) parser.add_argument( "-p", "--port", type=int, default=DEFAULT_SERVER_PORT, help=f"The TCP listener port (default = {DEFAULT_SERVER_PORT!r}, default for SSL = {DEFAULT_SERVER_SSL_PORT!r})" ) parser.add_argument( "-s", "--server", type=str, default="tmp/siliconmetatrader5", help="Path where the server will be build and run (default = /tmp/siliconmetatrader5)" ) ``` -------------------------------- ### Symbol discovery and selection (repository test pattern) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-info.md Initializes the MetaTrader5 client, selects the EURUSD symbol, and retrieves symbol information and ticks. It prints the total symbol count, sample symbols, and the last tick, handling the case where the symbol is not selectable by exiting with code 2. ```python mt5 = MetaTrader5(host="localhost", port=8001, keepalive=True) if not mt5.initialize(): raise RuntimeError("MT5 initialization failed!") if not mt5.symbol_select("EURUSD", True): print("EURUSD not found / not selectable;", mt5.last_error()) mt5.close() raise SystemExit(2) info = mt5.symbol_info("EURUSD") tick = mt5.symbol_info_tick("EURUSD") print("total symbols:", mt5.symbols_total()) print("sample symbols:", mt5.symbols_get("EURUSD")[:5]) print("last tick:", tick) mt5.close() ``` -------------------------------- ### Forwarding method signatures (initialize, login, version, last_error) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Signatures of the four methods that forward *args/**kwargs to the remote module method of the same name via _remote_call. ```python def initialize(self, *args, **kwargs): def login(self, *args, **kwargs): def version(self, *args, **kwargs): def last_error(self, *args, **kwargs): ``` -------------------------------- ### Direct invocation of server.py Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/bridge-server.md Equivalent direct command to run the copied server.py script with Windows Python, binding to all interfaces on port 8001. ```bash wine "C:/Python/python.exe" tmp/siliconmetatrader5/server.py --host 0.0.0.0 -p 8001 ``` -------------------------------- ### Iterate open positions Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-trading.md Iterates over open positions and prints symbol, type, volume, and profit, then prints the total count. Uses MetaTrader5 with host and port, and closes the connection. ```python mt5 = MetaTrader5(host="localhost", port=8001) positions = mt5.positions_get() for pos in positions: print(pos["symbol"], pos["type"], pos["volume"], pos["profit"]) print("total:", mt5.positions_total()) mt5.close() ``` -------------------------------- ### ClassicServer class declaration with CLI switches Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/bridge-server.md Defines the ClassicServer class with all CLI switch attributes for mode, port, host, IPv6, logging, SSL, and registry options. Use this as the base for a classic RPyC server application. ```python class ClassicServer(cli.Application): mode = cli.SwitchAttr( ["-m", "--mode"], cli.Set("threaded", "forking", "stdio", "oneshot"), default="threaded", help="The serving mode (threaded, forking, or 'stdio' for inetd, etc.)" ) port = cli.SwitchAttr( ["-p", "--port"], cli.Range(0, 65535), default=None, help=("The TCP listener port (default = {DEFAULT_SERVER_PORT!r}, " "default for SSL = {DEFAULT_SERVER_SSL_PORT!r})"), group="Socket Options" ) host = cli.SwitchAttr( ["--host"], str, default="", help="The host to bind to. The default is localhost", group="Socket Options" ) ipv6 = cli.Flag(["--ipv6"], help="Enable IPv6", group="Socket Options") logfile = cli.SwitchAttr( "--logfile", str, default=None, help="Specify the log file to use; the default is stderr", group="Logging" ) quiet = cli.Flag(["-q", "--quiet"], help="Quiet mode (only errors will be logged)", group="Logging") ssl_keyfile = cli.SwitchAttr( "--ssl-keyfile", cli.ExistingFile, help="The keyfile to use for SSL. Required for SSL", group="SSL", requires=["--ssl-certfile"]) ssl_certfile = cli.SwitchAttr( "--ssl-certfile", cli.ExistingFile, help="The certificate file to use for SSL. Required for SSL", group="SSL", requires=["--ssl-keyfile"]) ssl_cafile = cli.SwitchAttr( "--ssl-cafile", cli.ExistingFile, help="The certificate authority chain file to use for SSL. Optional; ..." " enables client-side authentication", group="SSL", requires=["--ssl-keyfile"]) auto_register = cli.Flag( "--register", help="Asks the server to attempt registering with a registry server. ...", group="Registry") registry_type = cli.SwitchAttr( ["--registry-type"], cli.Set("UDP", "TCP"), default="UDP", help="Specify a UDP or TCP registry", group="Registry") registry_port = cli.SwitchAttr( ["--registry-port"], cli.Range(0, 65535), default=REGISTRY_PORT, help="The registry's UDP/TCP port", group="Registry") registry_host = cli.SwitchAttr( ["--registry-host"], str, default=None, help="The registry host machine. ...", group="Registry") ``` -------------------------------- ### login(*args, **kwargs) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Forwards arguments to the remote module's login method via _remote_call. Used to authenticate with a trading account. ```APIDOC ## Python Function: login(*args, **kwargs) ### Description Forwards all arguments and keyword arguments to the remote module method of the same name via `_remote_call`. ### Signature ```python def login(self, *args, **kwargs): ``` ### Parameters - **args** (tuple) - Optional - Positional arguments forwarded to the remote method. - **kwargs** (dict) - Optional - Keyword arguments forwarded to the remote method. ### Returns The result of the remote method call. ``` -------------------------------- ### Stop the System Safely with Docker Compose and Colima Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md Stops the system safely by bringing down Docker Compose containers and then stopping Colima. ```bash cd docker && docker compose down colima stop ``` -------------------------------- ### Support via USDT (TRC20) Wallet Address Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/README.md USDT (TRC20) wallet address for supporting the project. ```text TMh8eS5EPRL77Z7L4KhsKmccSNLgf6Rfta ``` -------------------------------- ### history_deals_get Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-trading.md Returns a list of deal dicts. ```APIDOC ## history_deals_get ### Description Returns a list of deal dicts. Datetime-normalizes `args`/`kwargs` and evaluates `mt5.history_deals_get(...)`. ### Method history_deals_get ### Signature ```python def history_deals_get(self, *args, **kwargs): ``` ### Parameters None ### Returns - **list** - List of deal dicts, or `None`. ### Example ```python from datetime import datetime, timedelta mt5 = MetaTrader5(host="localhost", port=8001) now = datetime.now() frm = now - timedelta(days=2) for deal in mt5.history_deals_get(frm, now) or []: print(deal["time"], deal["symbol"], deal["type"], deal["volume"]) mt5.close() ``` ``` -------------------------------- ### Import MetaTrader5 and MT5BridgeError Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Import the MetaTrader5 client class and the MT5BridgeError exception from the siliconmetatrader5 package. ```python from siliconmetatrader5 import MetaTrader5, MT5BridgeError ``` -------------------------------- ### version(*args, **kwargs) Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md Forwards arguments to the remote module's version method via _remote_call. Returns version information of the MetaTrader 5 terminal. ```APIDOC ## Python Function: version(*args, **kwargs) ### Description Forwards all arguments and keyword arguments to the remote module method of the same name via `_remote_call`. ### Signature ```python def version(self, *args, **kwargs): ``` ### Parameters - **args** (tuple) - Optional - Positional arguments forwarded to the remote method. - **kwargs** (dict) - Optional - Keyword arguments forwarded to the remote method. ### Returns The result of the remote method call. ``` -------------------------------- ### Constructor signature Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5.md The constructor signature for the MetaTrader5 class, copied from source. It accepts host, port, keepalive, and timeout parameters. ```python def __init__(self, host="localhost", port=18812, keepalive=False, timeout=None): ``` -------------------------------- ### account_info Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-info.md Retrieves the current account snapshot from the MetaTrader5 terminal. ```APIDOC ## account_info ### Description Returns a dict with the current account snapshot, or None when no account info is available. ### Method account_info ### Signature ```python def account_info(self, *args, **kwargs): ``` ### Returns - **dict** - Account snapshot with fields: `login`, `trade_mode`, `leverage`, `money`, `equity`, `margin`, `margin_free`, `margin_initial`, `margin_maintenance`, `currency`, `name`, `server`, `company`, `type` - **None** - If no account info is available ### Errors - `MT5BridgeError` on remote/transport failure - `RuntimeError` if called after `close()` ``` -------------------------------- ### positions_get Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-trading.md Returns a list of open positions. ```APIDOC ## positions_get ### Description Returns a list of open positions. Datetime-normalizes `args`/`kwargs` and evaluates `mt5.positions_get(...)`. ### Method positions_get ### Signature ```python def positions_get(self, *args, **kwargs): ``` ### Parameters None ### Returns - **list** - A list of position dicts with fields: `position`, `symbol`, `type`, `volume`, `price_open`, `sl`, `tp`, `price_current`, `swap`, `profit`, `time`, `magic`, `comment`, `external_id`. ### Example ```python mt5 = MetaTrader5(host="localhost", port=8001) positions = mt5.positions_get() for pos in positions: print(pos["symbol"], pos["type"], pos["volume"], pos["profit"]) mt5.close() ``` ``` -------------------------------- ### order_calc_margin and order_calc_profit signatures Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-trading.md Signatures of order_calc_margin and order_calc_profit. Both forward to the remote methods via the eval path and return the numeric margin amount or profit computed by the terminal. ```python def order_calc_margin(self, *args, **kwargs): def order_calc_profit(self, *args, **kwargs): ``` -------------------------------- ### positions_total / positions_get signatures Source: https://github.com/bahadirumutiscimen/silicon-metatrader5/blob/main/_autodocs/api-reference/meta-trader5-trading.md Signatures of the positions_total and positions_get methods. positions_total forwards directly; positions_get datetime-normalizes args/kwargs and evaluates mt5.positions_get(...). Returns the integer count of open positions or a list of position dicts. ```python def positions_total(self, *args, **kwargs): def positions_get(self, *args, **kwargs): ```