Document

Logo

Remote Lock of Metatrader

Logo Project Data
Logo Details

📘 TV2MT WEB API DOCUMENTATION

This documentation contains full technical details of all API endpoints configured in the router_api.py file including parameters, schemas, validation rules, and examples.


# 🔐 Global Rule — IP Restriction Behavior

All API routes first verify the client's IP:

  • client_ip is fetched from Request Headers (X-Real-IP) or connection socket (request.client.host).

Restriction Logic Used in Every API

# Check if the user's IP is allowed to access the system:
IF client_ip is not allowed:
    RAISE HTTP Exception:
    {
      "status_code": 403,
      "detail": "This IP is not allowed to access this API"
    }

Important Logic Flow:

Primary Check (List Table): The system checks the restricted_ips list table first. If the table contains records, the client IP must exist in this table or else access is blocked with a 403 error.

Secondary Fallback (Company Info): If the table is empty, the system checks the fallback single restricted_ip in the company_info table.

Empty Config Rule: If the fallback IP configuration is empty, null, or set to "0", ALL IPs are allowed.

Single Match Rule: If the fallback IP contains a specific address, ONLY that exact client IP is allowed access.


# 📌 API Routes Table View

SR. No. Method API Route Name Endpoint Path Description
1️⃣POSTUpdate Account & Get Trades/api/update-account-and-get-tradesUpdates profit/loss metrics and retrieves active MQL trades.
2️⃣POSTGet Last Trade ID/api/get-last-trade-idRetrieves the highest saved trade database index ID.
3️⃣POSTGet Last Trade Type & Info/api/last-trade-typeReturns last trade type details and updates metrics.
4️⃣POSTTradingView to MT5 Webhook/api/tv-mt/{webhook_code}Processes TradingView alert signals and queues trades.
5️⃣POSTUpdate Account EA Data/api/update-account-ea-dataUpdates trade metrics for specific Expert Advisor.
6️⃣POSTGet Enabled Accounts/api/get-enabled-accountsReturns comma-separated string list of enabled active accounts.
7️⃣POSTCheck Account Status/api/check-account-statusVerifies if a MetaTrader account is verified and active.
8️⃣POSTAdd MT User/api/add_mt_userAdmin action to register a new MT copy-trading profile.
9️⃣POSTGet All MT Users/api/all_mt_userRetrieves list of all registered MetaTrader accounts.
🔟POSTDelete MT User/api/delete_mt_userPermanently deletes a registered user profile.
1️⃣1️⃣POSTToggle MT User Status (On/Off)/api/on_off_mt_userSuspends or activates copy-trading status.
1️⃣2️⃣POSTUpdate MT User Details/api/update_mt_userModifies fields of an existing MT user profile.
1️⃣3️⃣GETGet All EA Product IDs/api/all_ea_idsReturns friendly name mapping of Expert Advisor IDs.

## 1️⃣ Update Account & Get Trades

Endpoint

POST /api/update-account-and-get-trades

Description

Updates profit/loss metrics for a specific MetaTrader 5 account and retrieves all active trade signals from the broker execution queue mapped for MQL.

Query Parameters

Parameter Type Required Description
data_idIntegerYesCurrent processed trade track ID. Used to fetch new trade entries.
max_delay_minutesIntegerYesThe maximum allowed age of trades in minutes.
data_stringStringYesFormatted account details. Example: '123,raj mandviwala,52360,123,206,523,USD'. Use 'null' to delete orders.
account_numberIntegerYesThe target MT5 account number.

Input Validation Rules

Field Expected Value / Type Constraints & Verification Logic
data_idPositive Integer (e.g. 123)Used as a threshold to query newer trades. Must be >= 0.
max_delay_minutesPositive Integer (e.g. 10)Filters out trading signals older than this limit. Must be > 0.
data_stringComma-separated CSV string or 'null'Expected format: 'order_id,name,balance,equity,margin,free_margin,currency'. If empty, validation fails (returns failed). If 'null', clears MQL orders.
account_numberPositive Integer (e.g. 52360)Verifies account exists in the database. Account must be active (on_off = 1) and start/end subscription dates must be valid (not expired). If invalid, returns not_allowed.

Example Response

10052,buy,0.02,GBPUSD|10053,sell,0.1,XAUUSD

## 2️⃣ Get Last Trade ID

Endpoint

POST /api/get-last-trade-id

Description

Queries and returns the highest trade database index ID that has been saved in the system.

Query Parameters

Parameter Type Required Description
account_numberIntegerYesThe MT5 client account number.

Input Validation Rules

Field Expected Value / Type Constraints & Verification Logic
account_numberPositive Integer (e.g. 52360)Account must exist, be enabled (on_off = 1), and have a valid subscription. Returns not_allowed if checks fail, or failed_abc if lookup error occurs.

Success Response

12894

Failure Response

failed_abc

## 3️⃣ Get Last Trade Type & Info

Endpoint

POST /api/last-trade-type

Description

Logs updated account details and returns metadata about the last trade matching the symbol, magic number, and type.

Query Parameters

Parameter Type Required Description
data_stringStringYesComma-separated account data metrics.
tv_acc_noIntegerYesTradingView account identifier.
real_acc_noIntegerYesActive broker MetaTrader account number.
symbolStringYesTrading symbol identifier (e.g. EURUSD).
entry_exitStringYesTrade type entry or exit flag.
magic_numberIntegerYesMagic number identifier code.

Input Validation Rules

Field Expected Value / Type Constraints & Verification Logic
data_stringComma-separated CSV stringRequired. Expected format matches Route 1. Returns failed,no,-1 if empty or invalid.
real_acc_noPositive Integer (e.g. 52360)Account must exist, be active (on_off = 1), and have a valid subscription. Returns not_allowed,no,-1 if checks fail.
symbolString (e.g. GBPUSD)Must be a valid symbol string mapped for trading.
entry_exitString (entry or exit)Allowed values: 'entry' or 'exit'. Case-sensitive.
magic_numberInteger (e.g. 123456)The unique EA magic identifier matching the target order signal.

Success Response

success,buy,14

Failure Response

failed,no,-1

## 4️⃣ TradingView to MT5 Webhook

Endpoint

POST /api/tv-mt/{webhook_code}

Description

Processes alerts generated by TradingView strategies. Validates web host domains, security keys, and pushes trades directly to active MT5 accounts.

Path Parameters

Parameter Type Required Description
webhook_codeStringYesUnique security webhook authorization token configured by Admin.

Input Validation Rules

Field Expected Value / Type Constraints & Verification Logic
webhook_code (Path)String (e.g. 'a1b2c3')Must match the unique admin_webhook generated for the application domain in company_info table, or returns 422 Unprocessable Entity.
account_numberString or IntegerThe target execution account number. Must exist, be active, and not expired, or returns 403 Forbidden.
sideString (buy or sell)Expected value: 'buy', 'sell', or direction indicator. Mapped as trade type.
signal_typeString (entry or exit)Expected value: 'entry', 'exit', or signal state. Mapped as entry/exit type.
lot_typeStringMust be one of: 'fix_lot', 'same_master', 'multiply_from_master', or 'auto_lot'. Mapped as EA copier logic.
reverse_signalString ('true' or 'false')Case-insensitive string boolean flag. If 'true', reverses the order type on execution.
Numeric fields (e.g. fix_lot, sl, tp)Integer / FloatMust be positive numeric values. Defaults to 0 if missing.

Request Body Schema

{
  "symbol": "GBPUSD",
  "price": "1.26450",
  "side": "buy",
  "signal_type": "entry",
  "magic_number": "12345",
  "max_slippage": "10",
  "max_spread": "",
  "reverse_signal": "false",
  "lot_type": "fix_lot",
  "fix_lot": "0.05",
  "auto_lot_factor": "",
  "risk_percent": "",
  "sl": 0,
  "tp": 0,
  "trade_comment": "Strategy Trade",
  "account_number": "654321"
}

Success Response

{
  "message": "MT5 Data saved successfully."
}

Failure Response

{
  "message": "MT5 Data failed."
}

## 5️⃣ Update Account EA Data

Endpoint

POST /api/update-account-ea-data

Description

Saves custom Expert Advisor details and account profit updates into the system database.

Query Parameters

Parameter Type Required Description
data_stringStringYesFormatted account data metrics string.
account_numberIntegerYesMetaTrader 5 broker account.
ea_idIntegerYesThe target expert advisor software ID.

Input Validation Rules

Field Expected Value / Type Constraints & Verification Logic
data_stringComma-separated CSV stringRequired. Expected format matches Route 1. Returns failed if empty or invalid.
account_numberPositive Integer (e.g. 52360)Account must exist, be active (on_off = 1), and have a valid subscription. Returns not_allowed if checks fail.
ea_idInteger (e.g. 1)Expert Advisor ID. System checks if the user has access to this EA. If not, returns not_allowed.

Responses

  • success: Information stored successfully.
  • failed: Database write or validation error.
  • not_allowed: Subscription verification failed.

## 6️⃣ Get Enabled Accounts

Endpoint

POST /api/get-enabled-accounts

Description

Retrieves all currently enabled and active account numbers registered within the system.

Success Response

123456,789012,345678

Failure Response

-1

## 7️⃣ Check Account Status

Endpoint

POST /api/check-account-status

Description

Verifies whether an account is active and verified for copy trading.

Query Parameters

Parameter Type Required Description
account_numberIntegerYesThe target account code to audit.

Input Validation Rules

Field Expected Value / Type Constraints & Verification Logic
account_numberPositive Integer (e.g. 52360)System queries ea_users. Account must exist, be active (on_off = 1), and have a valid subscription. Returns ok on success, not_allowed on validation failure, or -1 on database exception.

Responses

  • ok: Account is verified and active.
  • not_allowed: Account is inactive or disabled.
  • -1: Processing exception error.

## 8️⃣ Add MT User

Endpoint

POST /api/add_mt_user

Description

Admin endpoint to provision a new MetaTrader client/user profile inside the copy trading network database.

Request Body Schema

{
  "name": "Alex Mercer",
  "email": "alex@trade.com",
  "mobile_number": "+15550199",
  "account_number": 998877,
  "ea_id": [1, 2],
  "start_date": "2026-08-01",
  "end_date": "2027-08-01",
  "password": "securepassword"
}

Field Schema & Validation

Field Type Required Constraints & Verification Logic
nameStringYesNon-empty user name. Max length 255.
emailStringYesMust be a valid email format. Checked against database; must be unique or registration fails.
mobile_numberStringYesMust contain valid mobile/phone number format. Checked for unique constraint.
account_numberIntegerYesMetaTrader account number. Must be unique; if the account number is already registered in the system, returns registration failure message.
ea_idArray of IntegersNoList of Expert Advisor IDs. Default is [] if not provided.
start_dateString (YYYY-MM-DD)NoActivation date. Must match pattern or validation fails. Defaults to current date if empty.
end_dateString (YYYY-MM-DD)NoExpiration date. Must match pattern. Defaults to infinite/None if empty.
passwordStringNoAuthentication password for user portal login. Default None.

Success Response

{
  "message": "User added successfully"
}

Failure Response

{
  "message": "Failed to add user, account number might already exist"
}

## 9️⃣ Get All MT Users

Endpoint

POST /api/all_mt_user

Description

Fetches list records of all MetaTrader users registered on the platform.

Success Response

{
  "message": "Success",
  "data": [
    {
      "account_number": 998877,
      "name": "Alex Mercer",
      "email": "alex@trade.com",
      "status": 1
    }
  ]
}

## 🔟 Delete MT User

Endpoint

POST /api/delete_mt_user

Description

Permanently deletes a registered user profile and subscription mapping data.

Request Body Schema

{
  "account_number": 998877
}

Input Validation Rules

Field Type Required Constraints & Verification Logic
account_numberIntegerYesMust exist in system. If not found, database delete operations complete with 0 rows affected (returns 500 Failed to delete account).

Success Response

{
  "status": "success",
  "message": "Account deleted successfully"
}

## 1️⃣1️⃣ Toggle MT User Status (On/Off)

Endpoint

POST /api/on_off_mt_user

Description

Suspends or restores copy-trading capability for a MetaTrader client profile.

Request Body Schema

{
  "account_number": 998877,
  "on_off": false
}

Input Validation Rules

Field Type Required Constraints & Verification Logic
account_numberIntegerYesMetaTrader client ID account number. Must exist.
on_offBooleanYesExpected values: true or false. Updates system execution status (active/inactive).

Success Response

{
  "status": "success",
  "message": "'on_off' updated to false"
}

## 1️⃣2️⃣ Update MT User Details

Endpoint

POST /api/update_mt_user

Description

Modifies settings (email, mobile, name, expiration date, or EAs list) for an existing user account.

Request Body Schema

{
  "account_number": 998877,
  "name": "Alex Updated",
  "email": "alex_new@trade.com",
  "mobile_number": "+15559999",
  "ea_id": [1, 2, 3],
  "start_date": "2026-08-01",
  "end_date": "2028-08-01",
  "password": "newsecurepassword"
}

Field Schema & Validation

Field Type Required Constraints & Verification Logic
account_numberIntegerYesPrimary key reference. Target account must exist in the system, or else returns 500 Failed to update user details.
nameStringNoUpdated name. Optional.
emailStringNoOptional. Validates format. If provided, checks if it is unique (not assigned to other users).
mobile_numberStringNoOptional. Validates unique constraint.
ea_idArray of IntegersNoOptional. Replaces the list of Expert Advisor product IDs.
start_dateString (YYYY-MM-DD)NoOptional. Updates user start date.
end_dateString (YYYY-MM-DD)NoOptional. Updates user end date.
passwordStringNoOptional. Updates user portal login password.

Success Response

{
  "status": "success",
  "message": "User details updated successfully"
}

## 1️⃣3️⃣ Get All EA Product IDs

Endpoint

GET /api/all_ea_ids

Description

Retrieves a key-value mapping of all Expert Advisor product identifiers and their friendly names.

Success Response

{
  "message": "Success",
  "data": {
    "1": "Gold Master Scalper",
    "2": "Trend Rider EA"
  }
}