MT Streaming API Server Doc
Medved Trader streaming API server documentation.
Please contact us at [email protected] if you're having any problems with the API.
The API is a Websocket API - local connection. You would connect a websocket to 127.0.0.1, with the port being determined when you enable the streaming API in Medved Trader Settings.
To use the API: register, download, install Medved Trader (http://www.medvedtrader.com). Set it up for the data sources and trading brokerages that you're going to use. Make sure everything runs ok inside Medved Trader. Don't forget to enable the API in Medved Trader settings.
The API is designed to run alongside Medved Trader - that is, Medved Trader application has to run (it doesn't have to have any windows open other than its Dashboard) and the API will connect to the application.
We have an API Tester application, written in C# - the source code is at https://medvedtrader.com/gf?File=APITester.zip. This source code will show you how to connect to the API and read the responses.
API Conventions/General
Connecting/security
After websocket connect, before any other commands can be executed, a connect command must be sent by the client, passing the MT login password. Without a successful connect, all other commands are rejected.
Formats
Commands and responses can be JSON or XML. That is determined by the connect command that is sent by the client. If it is in JSON format, all communication that follows will be in JSON. If it is in XML format, all subsequent communication will be in XML.
All the timestamps will be in UTC. All date/times are in standard JSON format.
Any response message to a command sent will have the command name echoed in the response as the cmd parameter.
Any update message - that is, a message that is initiated by the API and is not a response to a command, will end in "Update". For example - L1Update, alertTriggerUpdate, balancesUpdate.
One special Update is APIKeyPressUpdate - for that, you set up a "Send Current Window Info to API" global Keyboard shortcut. When that key is pressed on any content window in Medved Trader, it will send the information from that window to the API. Different windows would send different information, though some will be the same across all windows.
Starting/Stopping streamers for market data and trading
Before a streamer can be used in subscribe or unsubscribe, it has to be started by startDataStreamer.
Before a trading account can be used to place trades or to monitor the account, it has to be started by startTradingAccount.
Matching responses to requests
Any command can have an optional reqID parameter. If it is sent, then any response that the server sends to that command will have the same reqID passed back.
In response to commands, the cmd parameter and reqID (if it was sent) will be echoed back. There will also be three other parameters.
News and Alerts streaming updates
NOTE: News streaming and alerts etc. - you still have to subscribe to news or alerts (see the subscribe / unsubscribe command) - but it is a yes/no subscription, not to specific symbols. If news are subscribed, any new news message that comes into MT, using whatever news source and subscription that was set up in MT, will be echoed to the streamer as a newsUpdate. If alerts are subscribed, any alert that is triggered will be sent in api as alertTriggerUpdate.
Result Values Included in the Response for Every Command
Just not to repeat it everywhere, this document will not include the reqID, success and resultcode values in the Result Values for all the commands below. The Result Values will show what is included in the result return in the response record.
if OK — a text message or a nested JSON with the result of the request
connect (has to be the first command)
The password here is the password you would use to log into Medved Trader.
| Name | Req | Type | Content |
|---|---|---|---|
| cmd | Y | string | connect |
| pwd | Y | string | the password used to log into Medved Trader |
| reqID | N | string | optional correlation ID, echoed back in response |
| Name | Type | Content |
|---|---|---|
| time | string | server timestamp |
| ver | string | MT version string |
| reason | string | "connected" on success, "bad password" on failure |
{ "cmd": "connect", "pwd": "somepassword", "reqID": "1234" }{
"cmd": "connect", "success": "OK", "resultCode": 200, "reqID": "1234",
"result": { "time": "2022-05-06T22:42:38.643", "ver": "1.1.9600.121", "reason": "connected" }
}{
"cmd": "connect", "success": "fail", "resultCode": 401, "reqID": "1234",
"result": { "time": "2022-05-06T22:42:38.643", "ver": "1.1.9600.121", "reason": "bad password" }
}closing UPDATE
As the application terminates (for example, if the user closes it), if at that time the API is connected, it sends a termination notification.
{ "cmd": "closing", "success": "OK", "resultcode": 200, "result": "Session closing Main Application closing" }enumPorts
Lists all the portfolios in MT.
| Name | Type | Content |
|---|---|---|
| ports | array | list of portfolios available |
| ├─ portID | string | the port's ID by which you can refer to it in other commands |
| └─ name | string | the port's name |
{ "cmd": "enumPorts", "reqID": "1234" }{
"cmd": "enumPorts", "success": "OK", "resultCode": 200, "reqID": "1234",
"result": { "ports": [
{ "portID": "HWZD6UEQUO", "name": "Portfolio One" },
{ "portID": "JHKJD8DH8JH", "name": "Another Portfolio" }
]}
}enumPortSymbols
Lists all the symbols in a portfolio in MT.
| Name | Req | Type | Content |
|---|---|---|---|
| portID | Y | string | the ID of the port for which you want to get symbols. NOTE: if the ID is specified as "current", will return the list of symbols for the currently active Portfolio window in the application |
| detailed | N | bool | if false or not specified, will return just the symbols. If true, will return the symbols' details as well |
{ "result": ["AAPL", "MSFT", "FB"] }{ "result": [
{ "sym": "INPX", "itemID": "VpYn9s9tMU" },
{ "sym": "MVIS", "itemID": "gKgKIDNlH0", "qty": 200, "paid": 1.23, "comm": 2.12, "note": "A note", "purchaseDate": "2021-06-09" }
]}addToPort
Adds symbols to a portfolio in MT. Can create a portfolio as well.
| Name | Req | Type | Content |
|---|---|---|---|
| portID | N | string | the ID of the portfolio being updated or created. NOTE: if the ID is specified as "current", will add to the currently active Portfolio window. NOTE: if the ID is NOT specified and the new parameter is true - the new portfolio's ID will be auto-generated |
| new | N | bool | if true a new portfolio will be created. if false an existing portfolio will be updated. |
| name | N | string | name for the portfolio that is being created |
| sym | N | string / array | a comma-separated list of symbols, or an array of symbols |
| items | N | array | an array of detailed portfolio items (sym, itemID, qty, paid, comm, purchaseDate, note). If an itemID is specified and this is not a new portfolio, the existing item with this ID will be updated with the new values. |
{
"cmd": "addToPort", "portID": "SKJDGH7E54D", "reqID": "1234",
"items": [{ "sym": "AAPL", "qty": 3.0, "paid": 1245.0, "comm": 0.2, "note": "some note", "purchaseDate": "2020-08-29" }]
}removeFromPort
Removes symbols from a portfolio in MT.
| Name | Req | Type | Content |
|---|---|---|---|
| portID | Y | string | the ID of the portfolio to remove from |
| itemID | N | string / array | a comma-separated list of item IDs or symbols to remove, or an array of item IDs or symbols. NOTE: as a special case, if * is specified, ALL entries will be removed from the portfolio |
{ "cmd": "removeFromPort", "portID": "SKJDGH7E54D", "itemID": ["l966iQC0e0", "213QZ0E01"] }getLinkedSymbol
The colored-group linked symbols can be set and queried by the API. Gets the current linked symbol for a colored group.
| Name | Req | Type | Content |
|---|---|---|---|
| color | Y | string | the color of the group: one of Blue, Green, Red, Cyan, Brown, Black, Gray, Pink, Purple, LawnGreen, Maroon, Yellow, Olive, Iris, Tan, Apricot, Beige, Mint, Lime, Salmon, NeonPink, Crimson, Khaki, Teal, Chocolate |
| Name | Type | Content |
|---|---|---|
| sym | string | linked symbol |
{ "cmd": "getLinkedSymbol", "color": "Blue", "reqID": "1234" }{ "cmd": "getLinkedSymbol", "success": "OK", "resultCode": 200, "result": { "sym": "AAPL" } }setLinkedSymbol
Sets the current linked symbol for a colored group.
| Name | Req | Type | Content |
|---|---|---|---|
| color | Y | string | the color of the group (see getLinkedSymbol), plus Active |
| sym | Y | string | symbol to set |
{ "cmd": "setLinkedSymbol", "color": "Blue", "sym": "AAPL", "reqID": "1234" }getIntervar (also getIntervarString)
The API can set and read the intervars - that can also be set and read by paintbars and hotkeys in the application. SetInterVar() and GetInterVar() functions in paintbars/scans, and the intervar() function in Hotkeys.
Gets the specified intervar (or all intervars) for the specified symbol.
| Name | Req | Type | Content |
|---|---|---|---|
| sym | N | string | the symbol for the intervar. If no symbol is specified, or "*" is specified for the symbol, then the global intervar value will be returned |
| name | Y | string | the name of the intervar to retrieve. If "*" is specified for the name, all matching intervars will be returned |
{ "cmd": "getIntervar", "sym": "AMD", "name": "CalcPrice", "reqID": "1234" }{ "result": { "sym": "AMD", "name": "CalcPrice", "value": "120.4" } }setIntervar (also setIntervarString)
Sets the intervar for a specified symbol and name.
| Name | Req | Type | Content |
|---|---|---|---|
| name | Y | string | the name of the intervar that is being set |
| sym | N | string | symbol for the intervar. if the symbol is not specified, it is a global intervar |
| value | Y | double or string | the value to set |
{ "cmd": "setIntervar", "sym": "AMD", "name": "LULDUpper", "value": 125.4, "reqID": "1234" }APIKeyPressUpdate UPDATE
In order to receive this message, you set up a "Send Current Window Info to API" global Keyboard shortcut in the application. When that key is pressed on any content window in Medved Trader, it will send the information from that window to the API. Different windows would send different information, though some will be the same across all windows. For example, chart windows will send a "priceAtMouse" field.
| Name | Type | Content |
|---|---|---|
| sym | string | current symbol of the window |
| windowType | string | type of window (Chart, Portfolio, etc.) |
| priceAtMouse | float | (chart windows only) price level at mouse cursor position |
getSymbolSnapshot
Gives the current snapshot for the symbol's data stored in MT. NOTE: this is a snapshot of the current data in the MT symbol database. If it was not included in a running portfolio, it may be out of date, or it may be updated at some point but you would have to re-request to get the update.
| Name | Req | Type | Content |
|---|---|---|---|
| sym | Y | string | the symbol |
| Name | Type | Content |
|---|---|---|
| sym | string | symbol |
| companyName | string | Company Name |
| exchange | string | Exchange |
| timestamp | string | Last trade timestamp |
| bid / ask | string | Bid / Ask |
| bidSize / askSize | string | Bid size / Ask Size |
| last | string | Last trading price |
| volume | string | Daily volumes |
| lastTradeSize | string | Last Trade Size |
| change / prevClose | string | Change (from previous close) / Previous Close |
| open / high / low | string | Session open / high / low |
| high52 / low52 | string | 52 week high / 52 week low |
| dividend / earnings | string | Annual dividend / Earnings |
| marketCap | string | Market Cap |
| sharesOutstanding | string | total # of outstanding shares |
| LULDHigh / LULDLow | string | Limit Up (from LULD) value / Limit Down (from LULD) value |
| interest | string | (for options) open interest |
| volatility | string | volatility (only some sites provide this) |
{ "cmd": "getSymbolSnapshot", "sym": "AAPL", "reqID": "1234" }getPortSnapshot
Gives the current snapshot for all the symbols in the specified portfolio. Same as getSymbolSnapshot - this is the symbols' data stored in MT. NOTE: this is a snapshot of the current data in the MT symbol database.
| Name | Req | Type | Content |
|---|---|---|---|
| portID | Y | string | the ID of the portfolio |
{ "cmd": "getPortSnapshot", "portID": "JKGH10D2", "reqID": "1234" }enumDataStreamers
Lists all the available data streamers in MT. Note that in order for the API to use a data streamer, it has to be set up to work in MT - that is, if it requires name/password, it should be entered in MT. If it is not set up already, trying to activate it in API (by using the startDataStreamer command) will popup the logins in MT.
| Name | Type | Content |
|---|---|---|
| streamerID | string | ID used to refer to this streamer in other commands |
| name | string | display name |
| isSet | bool | (optional) true if the streamer is already configured with credentials in MT |
{ "result": [
{ "streamerID": "GAIN", "name": "GAIN Capital Futures" },
{ "streamerID": "BARCHART", "name": "Barchart Market Data", "isSet": true },
{ "streamerID": "IQFEED", "name": "IQFeed" }
]}startDataStreamer
This will start up a data streamer for further use in the API. It will log in, if necessary, and connect to the streamer. Note that if in MT, when starting the streamer, a login dialog pops up, it will also do that for this API request. Also note that if in MT the streamer is already started and running, this command will immediately return with a "success": "OK" response.
This initiates the starting of the streamer. To monitor the streamer startup and check when it is done, check the dataStreamerStateUpdate and dataStreamerStatusUpdate messages. The streamer is ready to run when its state is "IdleOrStreaming".
| Name | Req | Type | Content |
|---|---|---|---|
| streamerID | Y | string | specifies the streamer to start up. Same as the "streamerID" returned in enumDataStreamers |
| refresh | N | int | sets the refresh interval, in seconds, for snapshot data streamers, for example, Yahoo |
{ "cmd": "startDataStreamer", "streamerID": "AMTD", "reqID": "1234" }stopDataStreamer
This will deactivate a running streamer in the API and unsubscribe from all symbols it was running. Note that it will only deactivate the streamer for the API. If MT is running the streamer, it will continue to be active there.
{ "cmd": "stopDataStreamer", "streamerID": "AMTD", "reqID": "1234" }subscribe / unsubscribe
Subscribes or unsubscribes to/from one of the streaming feeds - L1, L2. Once subscribed, the streaming data will be sent in L1Update and L2Update updates.
| Name | Req | Type | Content |
|---|---|---|---|
| streamerID | Y | string | the ID of the streamer to subscribe to. Same as streamerID returned in enumDataStreamers. L1 only: the special value "PASSIVE" may be used to receive whatever L1 updates MT is already getting from charts or portfolios, without starting or managing a streamer explicitly. Not valid for L2. |
| sub | Y | string | L1 - level 1 feed L2 - level 2 (depth) feed |
| sym | Y | string / array | a comma-separated list of symbols, or an array of symbols. NOTE: for unsubscribe this parameter can be "*" - to unsubscribe from all currently subscribed-to symbols |
| transient | N | bool | L1 only. true - the data received will not be stored in the database for the symbol. false (default) - the data will be stored in the database for the symbol. Not relevant when streamerID is "PASSIVE". |
| syncUpdates | N | bool | L1 only. true - L1Update is sent immediately as quote comes in, synchronously. Guarantees L1Update for every incoming quote. NOTE: may cause performance issues and data delays. Don't use on large list of high volume symbols. false (default) - Update notification is queued and then processed. |
| changes | N | bool | L2 only. true (default) - only the book changes will be sent in the L2Update. false - each L2Update will contain the whole book. |
| maxRows | N | int | L2 only. limits the total number of rows returned in L2Update |
| Name | Type | Content |
|---|---|---|
| subbed | array | list of newly subscribed symbols |
| alreadysubbed | array | list of symbols that the command tried to subscribe that were already subscribed to |
| unsubbed | array | list of unsubscribed symbols |
| werenotsubbed | array | list of symbols that the command tried to unsubscribe that were not subscribed to |
{ "cmd": "subscribe", "reqID": "1234", "sub": "L1", "streamerID": "AMTD", "sym": "MSFT, AAPL, FB" }getSubscriptions
Returns the list of subscribed-to symbols for the streaming feed specified.
| Name | Req | Type | Content |
|---|---|---|---|
| streamerID | Y | string | the ID of the streamer |
| sub | Y | string | L1 or L2 |
{ "result": { "subbed": ["AAPL", "MSFT", "INTC"] } }L1Update UPDATE
Once the subscribe for a symbol is executed with a sub parameter of "L1", the API will start receiving the L1Update messages for each trade and bid/ask change.
| Name | Type | Content |
|---|---|---|
| sym | string | symbol |
| timeStamp | string | the timestamp in ISO 8601 standard |
| price | float | last trade price |
| size | float | last trade volume (if 0, this is just a bid/ask change) |
| volume | float | cumulative volume for the day |
| bid / ask | float | bid / ask |
{
"cmd": "L1Update", "success": "OK", "resultCode": 200,
"result": {
"sym": "AAPL", "timeStamp": "2020-05-05T22:19:40.361",
"price": 299.0, "size": 532.0, "volume": 36898854.0,
"bid": 298.8, "ask": 299.14
}
}L2Update UPDATE
Once the subscribe for a symbol is executed with a sub parameter of "L2", the API will start receiving the L2Update messages. If the initial request had changes set to true, the first message for a symbol will be for a full book snapshot, while subsequent messages will be incremental updates. If it was set to false, every L2Update will contain the whole book.
Each bid/ask entry has an act field: "a" - add the item, "d" - delete the item with that MMID and price, "m" - modify the item with that MMID and price.
{
"cmd": "L2Update", "type": "diff",
"result": {
"sym": "TQQQ",
"bids": [{ "act": "a", "MMID": "NSDQ", "price": 68.55, "size": 30.0, "timeStamp": "2020-05-05T21:24:32.208Z", "numOrders": 1 }],
"asks": [{ "act": "d", "MMID": "EDGX", "price": 68.58, "size": 900.0, "timeStamp": "2020-05-05T21:24:32.208Z", "numOrders": 1 }]
}
}subscribe / unsubscribe
The News and Alerts subscriptions in the API are passive. That means that the API passes through whatever news and alerts happen in the application. The API can also allow you to manage the alerts - see the Managing Alerts documentation section.
Subscribes or unsubscribes to/from News or Alerts. Once subscribed, new news will send a newsUpdate and a newly triggered alert will send an alertTriggerUpdate.
| Name | Req | Type | Content |
|---|---|---|---|
| sub | Y | string | news alerts |
{ "cmd": "subscribe", "reqID": "1234", "sub": "news" }getSubscriptions
Returns whether the News or Alerts are subscribed to.
{ "result": { "subbed": "yes" } }newsUpdate UPDATE
Once subscribed to news, the API will start receiving one newsUpdate message for each new news item that comes in.
| Name | Type | Content |
|---|---|---|
| syms | array of string | symbols relevant to this news item |
| received | string | date/time the news item was received by the application - ISO 8601 |
| timeStamp | string | the timestamp in ISO 8601 standard |
| title | string | title of the news item |
| source | string | the source of the news item |
| URL | string | the URL address of the contents of the news item |
{
"cmd": "newsUpdate", "success": "OK", "resultcode": 200,
"result": {
"syms": ["SEMR"],
"title": "Should You Consider Investing in SEMrush (SEMR)?",
"timeStamp": "2021-06-07T17:04:58.000",
"received": "2021-06-14T01:32:28.000",
"source": "Y! Insider Monkey",
"URL": "https://finance.yahoo.com/news/consider-investing-semrush-semr-170458708.html"
}
}alertTriggerUpdate UPDATE
Once subscribed to alerts, the API will start receiving the alertTriggerUpdate message for each new alert that triggers. See Managing Alerts — alertTriggerUpdate for the full field listing and examples.
backfill
Initiates a backfill (just like you would do in MT from, let's say, a chart window). Note that it does not return the backfilled data - it will only tell you when the backfill is finished. To get the data that was backfilled, use the getCandles or getTicks commands. In order to do both backfill and getCandles or getTicks together, use the backfillAndGetCandles or backfillAndGetTicks command.
| Name | Req | Type | Content |
|---|---|---|---|
| streamerID | Y | string | the same as the streamerID return in enumDataStreamers |
| sym | Y | string | the symbol to backfill |
| type | Y | string | OHLC - backfill intraday one-minute candles tick - backfill tick data if the streamer allows that hist - backfill historical (one-day candles) data |
| backfillType | Y | string | incremental - (default) backfills the data from the last time it backfilled full - does a full period backfill then merges with existing data |
| Name | Type | Content |
|---|---|---|
| action | string | started - sent immediately to acknowledge backfill request finished - sent after the backfill request is fully executed |
| type | string | OHLC, tick or hist - echoes the type from the request |
| sym | string | symbol - echoes the sym from the request |
{ "cmd": "backfill", "reqID": "1234", "type": "OHLC", "streamerID": "AMTD", "sym": "MSFT", "backfillType": "incremental" }{ "result": { "action": "started", "type": "hist", "sym": "AAPL" } }
// ... followed later by:
{ "result": { "action": "finished", "type": "hist", "sym": "AAPL" } }backfillAndGetCandles / backfillAndGetTicks
Initiates a backfill like a backfill command would but as soon as the backfill is finished, initiates the getCandles or getTicks command. Accepts all backfill parameters plus all getCandles/getTicks parameters. After the "finished" response, the candle or tick data follows immediately.
getCandles
Returns OHLC candles for the symbol - from the data that is available in MT.
| Name | Req | Type | Content |
|---|---|---|---|
| sym | Y | string | the symbol |
| candleSize | Y | float or string | if numeric (e.g. 0.5 or 5) specifies the candle size in minutes (intraday candles). If string, a number with a suffix: D (days), W (weeks, only 1W), M (months, only 1M), Y (years, only 1Y), Q (quarters, only 1Q). Example: "3D" |
| startDate | N | string | from Date/Time (ISO 8601). If not specified, will get from the oldest available |
| endDate | N | string | to Date/Time (ISO 8601). If not specified, will go to the latest available |
| regHoursOnly | N | bool | for intraday candles, restricts to regular hours only. Defaults to false. |
| adjustForDividends | N | bool | for historical candles, adjusts the resulting candles for dividends. Defaults to false. |
| lastFew | N | int | the startDate will be ignored and it will return only last N candles in reverse chronological order |
| backfillFirst | N | string | if specified, contains the streamerID on which to initiate a backfill first, then return the requested candles |
| Name | Type | Content |
|---|---|---|
| sym | string | symbol |
| candleSize | string | candle size - echoed from the request |
| data ─ t | array / string | the candle data array / candle timestamp ISO 8601 |
| ├─ o / h / l / c | float | open / high / low / close price |
| └─ v | float | volume |
{
"result": {
"sym": "MSFT", "candleSize": "1D",
"data": [
{ "t": "2010-01-04T00:00:00", "o": 30.62, "h": 31.1, "l": 30.59, "c": 30.95, "v": 38414185 }
]
}
}getTicks
Returns tick data for the symbol - from the data that is available in MT. Accepts same parameters as getCandles (without candleSize), plus tradesOnly (bool - if true filters out bid/ask-only ticks). Each tick record: t (timestamp), b (bid), a (ask), p (price), s (size), bf (true if this is an OHLC backfill pseudo-tick).
getOptionChain
Requests an option chain for a symbol. Returns an immediate "started" response, then the full chain data when complete. MT caches option chains — use forceRefresh: true to bypass the cache.
| Name | Req | Type | Content |
|---|---|---|---|
| streamerID | Y | string | the streamer to use |
| sym | Y | string | the underlying symbol |
| return | Y | string | ExpirationStrikes - returns strikes grouped by expiration StrikeExpirations - returns expirations grouped by strike |
| startDate / endDate | N | string | filter by expiration date range |
| fromStrike / toStrike | N | float | filter by strike price range |
| forceRefresh | N | bool | bypass cached chain and force a fresh fetch |
{
"result": {
"sym": "MSFT",
"expirations": [
{ "expiration": "2022-09-16", "strikes": [240.0, 250.0, 260.0, 270.0] }
]
}
}alertTriggerUpdate UPDATE
Once subscribed to alerts, the API will start receiving the alertTriggerUpdate message for each new alert that triggers.
| Name | Type | Content |
|---|---|---|
| alertID | string | the alert's ID |
| alertType | string | see alertType enumeration |
| alertDesc | string | short description of the alert |
| alertLongDesc | string | longer description of the alert |
| sym | string | (optional) the symbol for the alert |
| timeStamp | string | the timestamp when alert was triggered - ISO 8601 |
| triggerValue | float | the value that triggered the alert |
| refValue | float | (optional) the reference value for the alert (e.g. if price went above X, the refValue would be X) |
| triggerQuote | object | (optional) the quote at the time of trigger: price, bid, ask, size, timestamp |
| newsItem | object | (optional) for News alertType only - the news item details |
enumAlerts
Returns all user-defined alerts, optionally filtered by alertType or alertID.
| Name | Req | Type | Content |
|---|---|---|---|
| alertType | N | string | if specified, only returns alerts of this type |
| alertID | N | string | if specified, returns only the alert with this ID |
{ "cmd": "enumAlerts", "alertType": "PriceUp", "reqID": "1234" }enableDisableAlert
Enables or disables a specific alert.
| Name | Req | Type | Content |
|---|---|---|---|
| alertID | Y | string | the ID of the alert |
| enabled | Y | bool | true to enable, false to disable |
{ "cmd": "enableDisableAlert", "alertID": "XJ23lK25", "enabled": true, "reqID": "1234" }deleteAlert
Permanently deletes an alert.
{ "cmd": "deleteAlert", "alertID": "XJ23lK25", "reqID": "1234" }modifyAlert
Modifies an existing alert. Include only the fields you want to change in the alert object. The alertID is required. Use enumAlerts first to inspect current field names and values.
{ "cmd": "modifyAlert", "alertID": "XJ23lK25", "alert": { "MainPrice": 21.0 }, "reqID": "1234" }addAlert
Creates a new alert. Returns the generated alertID on success. The alert object structure varies by alertType. To find the required fields for a specific alert type, create a prototype alert in MT, then use enumAlerts to inspect its exact JSON structure and replicate it in the API.
{
"cmd": "addAlert", "reqID": "1234",
"alert": {
"alertType": "PriceUp",
"sym": "AAPL",
"MainPrice": 180.0,
"enabled": true
}
}{ "result": { "alertID": "XJ23lK25" } }enableAlertSystem / disableAlertSystem / checkAlertSystemStatus
Controls or checks the global MT alert system. checkAlertSystemStatus returns whether it is currently enabled.
{ "cmd": "enableAlertSystem" }
// Response:
{ "result": { "enabled": true } }enumTradingAccounts
Lists all trading accounts configured in MT.
| Name | Type | Content |
|---|---|---|
| accounts | array | list of configured trading accounts |
| ├─ accountKey | string | key used to refer to this account in other commands |
| ├─ accountID | string | the account ID |
| ├─ loginNick | string | the login nickname for the brokerage connection |
| └─ accountNick | string | the user-defined account nickname |
{
"result": { "accounts": [
{ "accountKey": "AMTD:5551212", "accountID": "5551212", "loginNick": "AMTD", "accountNick": "my account" },
{ "accountKey": "AMTD:5551313", "accountID": "5551313", "loginNick": "AMTD", "accountNick": "another account" }
]}
}startTradingAccount
Logs into and activates a trading account for API use. If a brokerage login screen is needed, it will appear in MT. After a successful start, the API automatically sends balancesUpdate, positionsUpdate, transactionsUpdate, and tradingAccountSettings. The account is ready when its state is "IdleOrStreaming".
{ "cmd": "startTradingAccount", "accountKey": "AMTD:5551212", "reqID": "1234" }stopTradingAccount
Stops a trading account in the API session. Disconnects the trading streamer and cancels all subscriptions. Does not affect MT's own account activity.
{ "cmd": "stopTradingAccount", "accountKey": "AMTD:5551212", "reqID": "1234" }getTradingAccountSettings
Re-requests the tradingAccountSettings for an already-started account. Also sent automatically on startTradingAccount. See the tradingAccountSettings appendix for the full response structure.
{ "cmd": "getTradingAccountSettings", "accountKey": "AMTD:5551212", "reqID": "1234" }getBalances / getPositions / getTransactions
Requests the latest account data. Responses arrive as the corresponding update message (balancesUpdate, positionsUpdate, transactionsUpdate).
| Name | Applies To | Content |
|---|---|---|
| accountKey | All three | key of the started trading account |
| forceRefresh | getPositions, getTransactions | if true, forces a fresh fetch from the broker rather than returning cached data |
| changesOnly | getTransactions | if true, returns only changes from the previous update (ignored if forceRefresh is true) |
subscribe (Trading)
Controls whether positions and transactions updates send full data or only deltas.
| Name | Req | Type | Content |
|---|---|---|---|
| accountKey | Y | string | trading account key |
| sub | Y | string | positions or transactions |
| changes | N | bool | true (default) - send only deltas. false - always send full list. |
balancesUpdate UPDATE
Sent on startTradingAccount, when balances change, and in response to getBalances. Exact field names vary by brokerage — connect and inspect the live response for your account.
positionsUpdate UPDATE
Sent on account start, on position changes, and in response to getPositions. Fields vary by brokerage.
transactionsUpdate UPDATE
Sent on account start (full set), on order events (new/modified/filled/canceled), and in response to getTransactions. setOrChange is "set" for a complete snapshot or "change" for incremental. Each transaction record includes a New boolean (true if this is a brand new transaction).
{
"cmd": "transactionsUpdate",
"result": {
"accountKey": "AMTD:5551212", "setOrChange": "change",
"transactions": [{
"OrderID": "1492551014", "Symbol": "BAC", "StatusID": "Open",
"Action": "Buy", "OrderType": "Limit", "LimitPrice": 25.31,
"QTY": 1.0, "TIF": "Day", "IsOpen": true, "New": false
}]
}
}{
"cmd": "transactionsUpdate",
"result": {
"accountKey": "AMTD:5551212", "setOrChange": "change",
"transactions": [{
"OrderID": "1489360600", "Symbol": "BOXL", "StatusID": "Filled",
"FilledQTY": 600.0, "FilledPrice": 1.43998917,
"Fills": [
{ "FillID": "17279254533", "QTY": 250.0, "Price": 1.4399 },
{ "FillID": "17279254535", "QTY": 300.0, "Price": 1.4399 },
{ "FillID": "17279254537", "QTY": 50.0, "Price": 1.4398 }
], "New": true
}]
}
}tradeCommandUpdate UPDATE
Sent whenever a new order, modify, or cancel is submitted to a broker — from either the API or from MT directly. The action field is "NewOrder", "ModifyOrder", or "CancelOrder".
{
"cmd": "tradeCommandUpdate",
"result": {
"accountKey": "AMTD:5551212", "action": "NewOrder",
"order": {
"ConditionalType": "None",
"Legs": [{ "Symbol": "BAC", "Quantity": 1, "Action": "Buy", "OrderType": "Limit", "LimitPrice": 26.36, "TIF": "Day" }]
}
}
}{
"cmd": "tradeCommandUpdate",
"result": {
"accountKey": "AMTD:5551212", "action": "ModifyOrder",
"order": {
"OrderID": "1492551014",
"Legs": [{ "Symbol": "BAC", "Quantity": 1, "LimitPrice": 26.41 }]
}
}
}{
"cmd": "tradeCommandUpdate",
"result": { "accountKey": "AMTD:5551212", "action": "CancelOrder", "orderID": "1492551014" }
}tradeCommandNew
Places a new order. Simple orders have one leg; conditional orders (OTO, OTOTA, etc.) have 2–3 legs. To determine valid parameters for your specific broker, monitor tradeCommandUpdate while placing a test order manually in MT.
| Field | Req | Content |
|---|---|---|
| Symbol | Y | ticker symbol |
| Quantity | Y | order size |
| Action | Y | Buy, Sell, Short, etc. (broker-dependent — see tradingAccountSettings) |
| OrderType | Y | Limit, Market, StopMarket, etc. (broker-dependent) |
| LimitPrice | * | required for Limit orders |
| StopPrice | * | required for stop orders |
| TIF | Y | time-in-force: Day, GTC, etc. |
| Routing | N | route (e.g. "SMART"). Default: "" |
| ConditionalType | N | "None", "OTO", "OTOTA", etc. Default: "None" |
{
"cmd": "tradeCommandNew", "accountKey": "BRKR:ACCTNUM12345", "reqID": "1234",
"order": {
"ConditionalType": "None",
"Legs": [{ "Symbol": "AAPL", "Quantity": 1, "Action": "Buy", "OrderType": "Limit", "LimitPrice": 444.33, "TIF": "Day" }]
}
}{
"cmd": "tradeCommandNew", "accountKey": "AMTD:1234321", "reqID": "1234",
"order": {
"ConditionalType": "OTOTA",
"Legs": [
{ "Symbol": "BAC", "Quantity": 1, "Action": "Buy", "OrderType": "Limit", "LimitPrice": 26.36, "TIF": "Day" },
{ "Symbol": "BAC", "Quantity": 1, "Action": "Sell", "OrderType": "StopMarket", "StopPrice": 26.27, "TIF": "Day" },
{ "Symbol": "BAC", "Quantity": 1, "Action": "Buy", "OrderType": "Limit", "LimitPrice": 26.23, "TIF": "Day" }
]
}
}tradeCommandFromHotkey
Executes an MT hotkey order via the API. The hotkey must specify a symbol and account, and contain only Order actions. To get the correct hotkeyJSON: in MT's hotkey list, right-click the hotkey and choose "Copy for Paste API". Paste the result as the hotkeyJSON value.
{
"cmd": "tradeCommandFromHotkey",
"hotkeyJSON": {
"Command": {
"Disabled": false,
"Order": {
"Account": "AMTD:5551212", "Symbol": "BAC",
"Legs": [{ "OrderType": "Limit", "Quantity": "1", "Action": "Sell", "LimitPrice": "Ask+0.1" }]
}
}
}
}tradeCommandCancel
Cancels one or more open orders. Accepts a single orderID, a comma-separated string, or an array. The result echoes in tradeCommandUpdate.
{ "cmd": "tradeCommandCancel", "accountKey": "WEBULLPAPER:WB_PAPER1234567", "orderID": ["1781234", "8723681"] }tradeCommandModify
Modifies an existing open order. Specify only the fields to change — unchanged fields are filled automatically from the existing order. Requires OrderID in the order object.
{
"cmd": "tradeCommandModify", "accountKey": "BRKR:ACCTNUM12345", "reqID": "1234",
"order": {
"OrderID": "18723653",
"Legs": [{ "LimitPrice": 444.33, "Quantity": 1 }]
}
}alertType Enumeration
Used in the alertType field of enumAlerts, addAlert, modifyAlert, and alertTriggerUpdate.
| alertType | Short Description | Trigger Condition |
|---|---|---|
| PriceUp | Price Above | Price moves above a set point |
| PriceDown | Price Below | Price moves below a set point |
| PriceUpDown | Price Above/Below | Price moves above or below a set point |
| CrossingUp | Price Crossing Up | Price crosses a point on the way up |
| CrossingDown | Price Crossing Down | Price crosses a point on the way down |
| CrossingUpDown | Price Crossing Up/Down | Price crosses a point in either direction |
| MovingUp | Moving Up | Price moves up by specified amount within timeframe |
| MovingDown | Moving Down | Price moves down by specified amount within timeframe |
| MovingUpDown | Moving Up/Down | Price moves up or down by specified amount |
| MovingUpPT | Moving Up % | Price moves up by specified % within timeframe |
| MovingDownPT | Moving Down % | Price moves down by specified % within timeframe |
| MovingUpDownPT | Moving Up/Down % | Price moves up or down by specified % |
| NewHigh | Daily High | New daily high set |
| NewLow | Daily Low | New daily low set |
| NewHighLow | Daily High/Low | New daily high or low set |
| NewHigh52 | 52 Week High | New 52-week high set |
| NewLow52 | 52 Week Low | New 52-week low set |
| NewHighLow52 | 52 Week High/Low | New 52-week high or low set |
| TrailingStopUp | Trailing Stop Buy | Price moves up more than set value/% from low |
| TrailingStopDown | Trailing Stop Sell | Price moves more than set value/% down from high |
| TrailingStopUpDown | Trailing Stop Buy/Sell | Price moves more than set value/% from high or low |
| TradeSize | Trade Size | Trade size ≥ specified value |
| TrendlineUp | Cross Trendline Up | Price crosses specified trendline on the way up |
| TrendlineDown | Cross Trendline Down | Price crosses specified trendline on the way down |
| TrendlineUpDown | Cross Trendline Up/Down | Price crosses specified trendline in either direction |
| Volume | Volume | Volume increases by set amount within timeframe |
| VolumeInc | Volume % Increase | Volume increases by set % |
| News | News | News received within specified age for monitored symbol |
| Reminder | Reminder | Pure time-based reminder alert |
| CrossingUpRangePercent | Crossing Daily Range Up | Price crosses a point on daily range on the way up |
| CrossingDownRangePercent | Crossing Daily Range Down | Price crosses a point on daily range on the way down |
| FibRetracementUp | Cross Fib Retracement Up | Price crosses Fibonacci Retracement on the way up |
| FibRetracementDown | Cross Fib Retracement Down | Price crosses Fibonacci Retracement on the way down |
| FibExpansionUp | Cross Fib Expansion Up | Price crosses Fibonacci Expansion on the way up |
| FibExpansionDown | Cross Fib Expansion Down | Price crosses Fibonacci Expansion on the way down |
| PivotPointUp | Cross Pivot Point Up | Price crosses Pivot Point on the way up |
| PivotPointDown | Cross Pivot Point Down | Price crosses Pivot Point on the way down |
| PivotPointUpDown | Cross Pivot Point Up/Down | Price crosses Pivot Point in either direction |
| Paintbar | Paintbar | Triggered by a chart paintbar |
| Scan | Scan | Triggered by a portfolio scan |
| TradeFill | Trade Fill | Any order execution occurs |
| TradeFillFull | Trade Fill: Full | Order completely filled |
| TradeFillPartial | Trade Fill: Partial | Order partially filled |
tradingAccountSettings
Sent automatically on startTradingAccount and re-requestable via getTradingAccountSettings. Describes the valid parameters for the connected broker. Values vary per brokerage — inspect the live response for your account.
| Field | Content |
|---|---|
| tradingInstruments | parameters for each supported trading instrument type |
| ConditionalType | supported conditional order types (OTO, OTOTA, etc.) |
| Action | available order actions (Buy, Sell, Short — broker-dependent) |
| OrderType | supported order types |
| TIF | available Time-in-Force values |
| SpInstructions | special instructions available per instrument |
| AllowRouting | boolean — whether routing is available |
| RoutingOptions | available routes if routing is enabled |
| RoutingOrderTypes | order type availability per route |
| UseDateOnGTC | whether a date must be supplied with GTC orders |
| TrailingParamPercentInc | valid increment for trailing stop % |