medvedtrader.com support

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.

WebSocket · Local JSON or XML Requires MT Running

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.

Name
Type
Content
cmd
string
reqID
string
success
string
OK or fail
resultcode
int
200   OK 400   BadRequest 401   Unauthorized 404   NotFound 429   Too Many Requests 500   InternalServerError 503   ServiceUnavailable
result
string
if fail — a text message why it failed
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.

Request Parameters
NameReqTypeContent
cmdYstringconnect
pwdYstringthe password used to log into Medved Trader
reqIDNstringoptional correlation ID, echoed back in response
Response Values
NameTypeContent
timestringserver timestamp
verstringMT version string
reasonstring"connected" on success, "bad password" on failure
EXAMPLE REQUEST
{ "cmd": "connect", "pwd": "somepassword", "reqID": "1234" }
EXAMPLE RESPONSE — success
{
  "cmd": "connect", "success": "OK", "resultCode": 200, "reqID": "1234",
  "result": { "time": "2022-05-06T22:42:38.643", "ver": "1.1.9600.121", "reason": "connected" }
}
EXAMPLE RESPONSE — failure
{
  "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.

EXAMPLE
{ "cmd": "closing", "success": "OK", "resultcode": 200, "result": "Session closing Main Application closing" }

enumPorts

Lists all the portfolios in MT.

Response Values
NameTypeContent
portsarraylist of portfolios available
├─ portIDstringthe port's ID by which you can refer to it in other commands
└─ namestringthe port's name
EXAMPLE REQUEST
{ "cmd": "enumPorts", "reqID": "1234" }
EXAMPLE RESPONSE
{
  "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.

Request Parameters
NameReqTypeContent
portIDYstringthe 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
detailedNboolif false or not specified, will return just the symbols. If true, will return the symbols' details as well
EXAMPLE RESPONSE — detailed: false
{ "result": ["AAPL", "MSFT", "FB"] }
EXAMPLE RESPONSE — detailed: true
{ "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.

Request Parameters
NameReqTypeContent
portIDNstringthe 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
newNboolif true a new portfolio will be created. if false an existing portfolio will be updated.
nameNstringname for the portfolio that is being created
symNstring / arraya comma-separated list of symbols, or an array of symbols
itemsNarrayan 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.
EXAMPLE REQUEST
{
  "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.

Request Parameters
NameReqTypeContent
portIDYstringthe ID of the portfolio to remove from
itemIDNstring / arraya 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
EXAMPLE REQUEST
{ "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.

Request Parameters
NameReqTypeContent
colorYstringthe 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
Response Values
NameTypeContent
symstringlinked symbol
EXAMPLE REQUEST
{ "cmd": "getLinkedSymbol", "color": "Blue", "reqID": "1234" }
EXAMPLE RESPONSE
{ "cmd": "getLinkedSymbol", "success": "OK", "resultCode": 200, "result": { "sym": "AAPL" } }

setLinkedSymbol

Sets the current linked symbol for a colored group.

Request Parameters
NameReqTypeContent
colorYstringthe color of the group (see getLinkedSymbol), plus Active
symYstringsymbol to set
EXAMPLE REQUEST
{ "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.

Request Parameters
NameReqTypeContent
symNstringthe symbol for the intervar. If no symbol is specified, or "*" is specified for the symbol, then the global intervar value will be returned
nameYstringthe name of the intervar to retrieve. If "*" is specified for the name, all matching intervars will be returned
EXAMPLE REQUEST
{ "cmd": "getIntervar", "sym": "AMD", "name": "CalcPrice", "reqID": "1234" }
EXAMPLE RESPONSE
{ "result": { "sym": "AMD", "name": "CalcPrice", "value": "120.4" } }

setIntervar (also setIntervarString)

Sets the intervar for a specified symbol and name.

Request Parameters
NameReqTypeContent
nameYstringthe name of the intervar that is being set
symNstringsymbol for the intervar. if the symbol is not specified, it is a global intervar
valueYdouble or stringthe value to set
EXAMPLE REQUEST
{ "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.

Update Values (common across all windows)
NameTypeContent
symstringcurrent symbol of the window
windowTypestringtype of window (Chart, Portfolio, etc.)
priceAtMousefloat(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.

Request Parameters
NameReqTypeContent
symYstringthe symbol
Response Values
NameTypeContent
symstringsymbol
companyNamestringCompany Name
exchangestringExchange
timestampstringLast trade timestamp
bid / askstringBid / Ask
bidSize / askSizestringBid size / Ask Size
laststringLast trading price
volumestringDaily volumes
lastTradeSizestringLast Trade Size
change / prevClosestringChange (from previous close) / Previous Close
open / high / lowstringSession open / high / low
high52 / low52string52 week high / 52 week low
dividend / earningsstringAnnual dividend / Earnings
marketCapstringMarket Cap
sharesOutstandingstringtotal # of outstanding shares
LULDHigh / LULDLowstringLimit Up (from LULD) value / Limit Down (from LULD) value
intereststring(for options) open interest
volatilitystringvolatility (only some sites provide this)
EXAMPLE REQUEST
{ "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.

Request Parameters
NameReqTypeContent
portIDYstringthe ID of the portfolio
EXAMPLE REQUEST
{ "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.

Response Values
NameTypeContent
streamerIDstringID used to refer to this streamer in other commands
namestringdisplay name
isSetbool(optional) true if the streamer is already configured with credentials in MT
EXAMPLE RESPONSE
{ "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".

Request Parameters
NameReqTypeContent
streamerIDYstringspecifies the streamer to start up. Same as the "streamerID" returned in enumDataStreamers
refreshNintsets the refresh interval, in seconds, for snapshot data streamers, for example, Yahoo
EXAMPLE REQUEST
{ "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.

EXAMPLE REQUEST
{ "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.

Request Parameters
NameReqTypeContent
streamerIDYstringthe 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.
subYstringL1 - level 1 feed
L2 - level 2 (depth) feed
symYstring / arraya 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
transientNboolL1 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".
syncUpdatesNboolL1 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.
changesNboolL2 only. true (default) - only the book changes will be sent in the L2Update. false - each L2Update will contain the whole book.
maxRowsNintL2 only. limits the total number of rows returned in L2Update
Response Values
NameTypeContent
subbedarraylist of newly subscribed symbols
alreadysubbedarraylist of symbols that the command tried to subscribe that were already subscribed to
unsubbedarraylist of unsubscribed symbols
werenotsubbedarraylist of symbols that the command tried to unsubscribe that were not subscribed to
EXAMPLE REQUEST
{ "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.

Request Parameters
NameReqTypeContent
streamerIDYstringthe ID of the streamer
subYstringL1 or L2
EXAMPLE RESPONSE
{ "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.

Update Values
NameTypeContent
symstringsymbol
timeStampstringthe timestamp in ISO 8601 standard
pricefloatlast trade price
sizefloatlast trade volume (if 0, this is just a bid/ask change)
volumefloatcumulative volume for the day
bid / askfloatbid / ask
EXAMPLE L1 UPDATE
{
  "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.

EXAMPLE L2 UPDATE
{
  "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.

Request Parameters
NameReqTypeContent
subYstringnews
alerts
EXAMPLE REQUEST
{ "cmd": "subscribe", "reqID": "1234", "sub": "news" }

getSubscriptions

Returns whether the News or Alerts are subscribed to.

EXAMPLE RESPONSE
{ "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.

Update Values
NameTypeContent
symsarray of stringsymbols relevant to this news item
receivedstringdate/time the news item was received by the application - ISO 8601
timeStampstringthe timestamp in ISO 8601 standard
titlestringtitle of the news item
sourcestringthe source of the news item
URLstringthe URL address of the contents of the news item
EXAMPLE newsUpdate
{
  "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.

Request Parameters
NameReqTypeContent
streamerIDYstringthe same as the streamerID return in enumDataStreamers
symYstringthe symbol to backfill
typeYstringOHLC - backfill intraday one-minute candles
tick - backfill tick data if the streamer allows that
hist - backfill historical (one-day candles) data
backfillTypeYstringincremental - (default) backfills the data from the last time it backfilled
full - does a full period backfill then merges with existing data
Response Values
NameTypeContent
actionstringstarted - sent immediately to acknowledge backfill request
finished - sent after the backfill request is fully executed
typestringOHLC, tick or hist - echoes the type from the request
symstringsymbol - echoes the sym from the request
EXAMPLE REQUEST
{ "cmd": "backfill", "reqID": "1234", "type": "OHLC", "streamerID": "AMTD", "sym": "MSFT", "backfillType": "incremental" }
EXAMPLE RESPONSE
{ "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.

Request Parameters
NameReqTypeContent
symYstringthe symbol
candleSizeYfloat or stringif 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"
startDateNstringfrom Date/Time (ISO 8601). If not specified, will get from the oldest available
endDateNstringto Date/Time (ISO 8601). If not specified, will go to the latest available
regHoursOnlyNboolfor intraday candles, restricts to regular hours only. Defaults to false.
adjustForDividendsNboolfor historical candles, adjusts the resulting candles for dividends. Defaults to false.
lastFewNintthe startDate will be ignored and it will return only last N candles in reverse chronological order
backfillFirstNstringif specified, contains the streamerID on which to initiate a backfill first, then return the requested candles
Response Values
NameTypeContent
symstringsymbol
candleSizestringcandle size - echoed from the request
data ─ tarray / stringthe candle data array / candle timestamp ISO 8601
├─ o / h / l / cfloatopen / high / low / close price
└─ vfloatvolume
EXAMPLE RESPONSE
{
  "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.

Request Parameters
NameReqTypeContent
streamerIDYstringthe streamer to use
symYstringthe underlying symbol
returnYstringExpirationStrikes - returns strikes grouped by expiration
StrikeExpirations - returns expirations grouped by strike
startDate / endDateNstringfilter by expiration date range
fromStrike / toStrikeNfloatfilter by strike price range
forceRefreshNboolbypass cached chain and force a fresh fetch
EXAMPLE RESPONSE — ExpirationStrikes
{
  "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.

Update Values
NameTypeContent
alertIDstringthe alert's ID
alertTypestringsee alertType enumeration
alertDescstringshort description of the alert
alertLongDescstringlonger description of the alert
symstring(optional) the symbol for the alert
timeStampstringthe timestamp when alert was triggered - ISO 8601
triggerValuefloatthe value that triggered the alert
refValuefloat(optional) the reference value for the alert (e.g. if price went above X, the refValue would be X)
triggerQuoteobject(optional) the quote at the time of trigger: price, bid, ask, size, timestamp
newsItemobject(optional) for News alertType only - the news item details

enumAlerts

Returns all user-defined alerts, optionally filtered by alertType or alertID.

Request Parameters
NameReqTypeContent
alertTypeNstringif specified, only returns alerts of this type
alertIDNstringif specified, returns only the alert with this ID
EXAMPLE REQUEST
{ "cmd": "enumAlerts", "alertType": "PriceUp", "reqID": "1234" }

enableDisableAlert

Enables or disables a specific alert.

Request Parameters
NameReqTypeContent
alertIDYstringthe ID of the alert
enabledYbooltrue to enable, false to disable
EXAMPLE REQUEST
{ "cmd": "enableDisableAlert", "alertID": "XJ23lK25", "enabled": true, "reqID": "1234" }

deleteAlert

Permanently deletes an alert.

EXAMPLE REQUEST
{ "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.

EXAMPLE REQUEST
{ "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.

EXAMPLE REQUEST
{
  "cmd": "addAlert", "reqID": "1234",
  "alert": {
    "alertType": "PriceUp",
    "sym": "AAPL",
    "MainPrice": 180.0,
    "enabled": true
  }
}
EXAMPLE RESPONSE
{ "result": { "alertID": "XJ23lK25" } }

enableAlertSystem / disableAlertSystem / checkAlertSystemStatus

Controls or checks the global MT alert system. checkAlertSystemStatus returns whether it is currently enabled.

EXAMPLE REQUEST / RESPONSE
{ "cmd": "enableAlertSystem" }
// Response:
{ "result": { "enabled": true } }

enumTradingAccounts

Lists all trading accounts configured in MT.

Response Values
NameTypeContent
accountsarraylist of configured trading accounts
├─ accountKeystringkey used to refer to this account in other commands
├─ accountIDstringthe account ID
├─ loginNickstringthe login nickname for the brokerage connection
└─ accountNickstringthe user-defined account nickname
EXAMPLE RESPONSE
{
  "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".

EXAMPLE REQUEST
{ "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.

EXAMPLE REQUEST
{ "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.

EXAMPLE REQUEST
{ "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).

Request Parameters
NameApplies ToContent
accountKeyAll threekey of the started trading account
forceRefreshgetPositions, getTransactionsif true, forces a fresh fetch from the broker rather than returning cached data
changesOnlygetTransactionsif 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.

Request Parameters
NameReqTypeContent
accountKeyYstringtrading account key
subYstringpositions or transactions
changesNbooltrue (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).

EXAMPLE — Opened Order
{
  "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
    }]
  }
}
EXAMPLE — Filled Order (multiple fills)
{
  "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".

A successful CancelOrder update only confirms the cancel request was sent to the broker. Monitor transactionsUpdate to confirm the order was actually canceled.
EXAMPLE — NewOrder
{
  "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" }]
    }
  }
}
EXAMPLE — ModifyOrder
{
  "cmd": "tradeCommandUpdate",
  "result": {
    "accountKey": "AMTD:5551212", "action": "ModifyOrder",
    "order": {
      "OrderID": "1492551014",
      "Legs": [{ "Symbol": "BAC", "Quantity": 1, "LimitPrice": 26.41 }]
    }
  }
}
EXAMPLE — CancelOrder
{
  "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.

Order Leg Parameters
FieldReqContent
SymbolYticker symbol
QuantityYorder size
ActionYBuy, Sell, Short, etc. (broker-dependent — see tradingAccountSettings)
OrderTypeYLimit, Market, StopMarket, etc. (broker-dependent)
LimitPrice*required for Limit orders
StopPrice*required for stop orders
TIFYtime-in-force: Day, GTC, etc.
RoutingNroute (e.g. "SMART"). Default: ""
ConditionalTypeN"None", "OTO", "OTOTA", etc. Default: "None"
EXAMPLE — Simple Order
{
  "cmd": "tradeCommandNew", "accountKey": "BRKR:ACCTNUM12345", "reqID": "1234",
  "order": {
    "ConditionalType": "None",
    "Legs": [{ "Symbol": "AAPL", "Quantity": 1, "Action": "Buy", "OrderType": "Limit", "LimitPrice": 444.33, "TIF": "Day" }]
  }
}
EXAMPLE — OTOTA (3-leg conditional)
{
  "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.

EXAMPLE REQUEST
{
  "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.

EXAMPLE REQUEST
{ "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.

EXAMPLE REQUEST
{
  "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.

alertTypeShort DescriptionTrigger Condition
PriceUpPrice AbovePrice moves above a set point
PriceDownPrice BelowPrice moves below a set point
PriceUpDownPrice Above/BelowPrice moves above or below a set point
CrossingUpPrice Crossing UpPrice crosses a point on the way up
CrossingDownPrice Crossing DownPrice crosses a point on the way down
CrossingUpDownPrice Crossing Up/DownPrice crosses a point in either direction
MovingUpMoving UpPrice moves up by specified amount within timeframe
MovingDownMoving DownPrice moves down by specified amount within timeframe
MovingUpDownMoving Up/DownPrice moves up or down by specified amount
MovingUpPTMoving Up %Price moves up by specified % within timeframe
MovingDownPTMoving Down %Price moves down by specified % within timeframe
MovingUpDownPTMoving Up/Down %Price moves up or down by specified %
NewHighDaily HighNew daily high set
NewLowDaily LowNew daily low set
NewHighLowDaily High/LowNew daily high or low set
NewHigh5252 Week HighNew 52-week high set
NewLow5252 Week LowNew 52-week low set
NewHighLow5252 Week High/LowNew 52-week high or low set
TrailingStopUpTrailing Stop BuyPrice moves up more than set value/% from low
TrailingStopDownTrailing Stop SellPrice moves more than set value/% down from high
TrailingStopUpDownTrailing Stop Buy/SellPrice moves more than set value/% from high or low
TradeSizeTrade SizeTrade size ≥ specified value
TrendlineUpCross Trendline UpPrice crosses specified trendline on the way up
TrendlineDownCross Trendline DownPrice crosses specified trendline on the way down
TrendlineUpDownCross Trendline Up/DownPrice crosses specified trendline in either direction
VolumeVolumeVolume increases by set amount within timeframe
VolumeIncVolume % IncreaseVolume increases by set %
NewsNewsNews received within specified age for monitored symbol
ReminderReminderPure time-based reminder alert
CrossingUpRangePercentCrossing Daily Range UpPrice crosses a point on daily range on the way up
CrossingDownRangePercentCrossing Daily Range DownPrice crosses a point on daily range on the way down
FibRetracementUpCross Fib Retracement UpPrice crosses Fibonacci Retracement on the way up
FibRetracementDownCross Fib Retracement DownPrice crosses Fibonacci Retracement on the way down
FibExpansionUpCross Fib Expansion UpPrice crosses Fibonacci Expansion on the way up
FibExpansionDownCross Fib Expansion DownPrice crosses Fibonacci Expansion on the way down
PivotPointUpCross Pivot Point UpPrice crosses Pivot Point on the way up
PivotPointDownCross Pivot Point DownPrice crosses Pivot Point on the way down
PivotPointUpDownCross Pivot Point Up/DownPrice crosses Pivot Point in either direction
PaintbarPaintbarTriggered by a chart paintbar
ScanScanTriggered by a portfolio scan
TradeFillTrade FillAny order execution occurs
TradeFillFullTrade Fill: FullOrder completely filled
TradeFillPartialTrade Fill: PartialOrder 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.

FieldContent
tradingInstrumentsparameters for each supported trading instrument type
ConditionalTypesupported conditional order types (OTO, OTOTA, etc.)
Actionavailable order actions (Buy, Sell, Short — broker-dependent)
OrderTypesupported order types
TIFavailable Time-in-Force values
SpInstructionsspecial instructions available per instrument
AllowRoutingboolean — whether routing is available
RoutingOptionsavailable routes if routing is enabled
RoutingOrderTypesorder type availability per route
UseDateOnGTCwhether a date must be supplied with GTC orders
TrailingParamPercentIncvalid increment for trailing stop %