Standard library · Trading

metatrader

Read account, symbols, rates and history, and send trades through a local MetaTrader 5 bridge.

import metatrader

metatrader is a client for a local bridge to a running MetaTrader 5 terminal. The package speaks HTTP and JSON: every call sends a request to the bridge, and the bridge asks the terminal for the data or the trade. There is no DLL, no COM and no terminal plugin inside your program, so the same Salam program runs on Linux, macOS and Windows as long as the bridge is reachable.

The terminal itself must be running and logged in, and a bridge must be listening on the address you set. The default is http://127.0.0.1:18812, the value of DEFAULT_BRIDGE_URL. The bridge implements the endpoints below; the package only calls them and decodes the JSON.

EndpointUsed by
POST /initialize, POST /login, POST /shutdownInitialize, Login, Shutdown
GET /version, GET /account_info, GET /terminal_infoVersion, GetAccountInfo, GetTerminalInfo
GET /symbols_total, GET /symbols_get, GET /symbol_info, GET /symbol_info_tick, POST /symbol_selectSymbol calls
GET /copy_rates_from, GET /copy_rates_from_pos, GET /copy_rates_rangeCopyRates*
GET /copy_ticks_from, GET /copy_ticks_rangeCopyTicks*
GET /orders_total, GET /orders_get, GET /positions_total, GET /positions_getOrder and position reads
GET /history_orders_*, GET /history_deals_*History calls
POST /order_calc_margin, POST /order_calc_profit, POST /order_check, POST /order_sendTrading calls
POST /market_book_add, GET /market_book_get, POST /market_book_releaseMarket depth calls

Start with the account

Set the bridge address once, call Initialize, then read the account. Every call returns a value even when it fails, so check Ok or LastError after the calls that matter, and stop when the bridge is not there.

metatrader-quickstart.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    if not metatrader.Initialize("", 0 as i64, "", "", 60000, false):
        e := metatrader.LastError()
        printerrln "no bridge:", e.code, e.description
        ret 1
    end

    a := metatrader.GetAccountInfo()
    if not metatrader.Ok():
        e := metatrader.LastError()
        printerrln "account failed:", e.code, e.description
        metatrader.Shutdown()
        ret 1
    end
    println a.login, a.name, a.currency
    println "balance", a.balance, "equity", a.equity
    println "margin", a.margin, "free", a.margin_free

    t := metatrader.GetTerminalInfo()
    println t.company, t.name, t.build, t.connected

    metatrader.Shutdown()
    ret 0
end

Initialize and Login mark the session connected only when the bridge answers with a 2xx status. IsConnected reports that flag, not a live socket: call Version or GetTerminalInfo when you need to know that the terminal is still there. Shutdown only asks the bridge to close; it does not free anything in your program.

Errors and retcodes

A failed call returns the zero value of its type, an empty vector, an empty struct, or false, and leaves the reason in LastError. Ok is true exactly when the last code is RES_S_OK. The bridge uses the RES_E_* constants for transport and parameter errors, and the trade server uses TRADE_RETCODE_* in the result of OrderCheck and OrderSend.

a := metatrader.GetAccountInfo()
if not metatrader.Ok():
    e := metatrader.LastError()
    printerrln "account failed:", e.code, e.description
    ret 1
end
println a.balance

An HTTP error and a rejected trade are different: the first leaves Ok false, the second is a normal answer with a retcode. Always read retcode after OrderSend; a successful HTTP call does not mean the trade was accepted.

Symbols, prices and ticks

SymbolsGet returns every symbol with its contract rules and session data; the group forms filter with a mask such as *USD*, where * matches any text. GetSymbolInfo asks for one symbol, and SymbolInfoTick is the cheap call for the current bid and ask.

metatrader-symbols.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    println "symbols:", metatrader.SymbolsTotal()
    each s in metatrader.SymbolsGet():
        println s.name, s.digits, s.spread, s.trade_mode
    end

    majors := metatrader.SymbolsGetGroup("*USD*")
    println "usd symbols:", majors.len()

    info := metatrader.GetSymbolInfo("EURUSD")
    println info.bid, info.ask, info.point, info.digits
    println info.volume_min, info.volume_step, info.volume_max
    println info.trade_stops_level, info.trade_contract_size

    tick := metatrader.SymbolInfoTick("EURUSD")
    println tick.time, tick.bid, tick.ask, tick.last, tick.volume

    if not metatrader.SymbolSelect("EURUSD", true):
        printerrln "cannot select EURUSD"
    end
    ret 0
end

digits and point tell you how to round a price; volume_min, volume_max and volume_step tell you which volumes the server accepts; trade_stops_level is the shortest distance in points between the price and a stop loss or take profit.

Candles and ticks

Rates are returned oldest first. CopyRatesFromPos counts from the newest candle, so position 0 is the candle that is still forming, and CopyRatesFrom starts at a time. Times are seconds since the epoch, as in time; tick times are milliseconds in time_msc, which is what CopyTicksRange expects.

metatrader-rates.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    from := metatrader.CopyRatesFrom("EURUSD", metatrader.TIMEFRAME_H1, 1700000000 as i64, 10)
    each r in from:
        println r.time, r.open, r.high, r.low, r.close, r.tick_volume
    end

    recent := metatrader.CopyRatesFromPos("EURUSD", metatrader.TIMEFRAME_M5, 0, 5)
    println "recent:", recent.len()

    window := metatrader.CopyRatesRange("EURUSD", metatrader.TIMEFRAME_D1, 1700000000 as i64, 1700086400 as i64)
    println "daily:", window.len()

    ticks := metatrader.CopyTicksFrom("EURUSD", 1700000000 as i64, 100, metatrader.COPY_TICKS_ALL)
    each t in ticks:
        println t.time_msc, t.bid, t.ask, t.last, t.flags
    end

    trade_ticks := metatrader.CopyTicksRange("EURUSD", 1700000000000 as i64, 1700000600000 as i64, metatrader.COPY_TICKS_TRADE)
    println "trade ticks:", trade_ticks.len()
    ret 0
end

The tick filters keep the payload small: COPY_TICKS_INFO keeps bid and ask changes, COPY_TICKS_TRADE keeps trades, and COPY_TICKS_ALL keeps both. Check flags on each tick when you need to know which side changed.

Checking and sending an order

Fill a TradeRequest, call OrderCheck, and look at its margin fields before you send anything. Then call OrderSend and read retcode. A check returning 0 means the request is valid; the send returns TRADE_RETCODE_DONE for a filled order, TRADE_RETCODE_PLACED for a pending order, and an error code otherwise.

metatrader-trade.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    println "orders:", metatrader.OrdersTotal()
    each o in metatrader.OrdersGet():
        println o.ticket, o.symbol, o.order_type, o.state, o.volume_current, o.price_open
    end
    each p in metatrader.PositionsGet():
        println p.ticket, p.symbol, p.position_type, p.volume, p.price_open, p.profit
    end

    mut req := metatrader.TradeRequest {}
    req.action = metatrader.TRADE_ACTION_DEAL
    req.symbol = "EURUSD"
    req.volume = 0.10
    req.price = 1.0821
    req.order_type = metatrader.ORDER_TYPE_BUY
    req.type_filling = metatrader.ORDER_FILLING_IOC
    req.type_time = metatrader.ORDER_TIME_GTC
    req.deviation = 10
    req.magic = 2026
    req.comment = "salam"

    check := metatrader.OrderCheck(req)
    println "check:", check.retcode, check.margin, check.margin_free, check.comment
    if check.retcode != 0:
        ret 1
    end

    sent := metatrader.OrderSend(req)
    println "send:", sent.retcode, sent.order, sent.deal, sent.price
    if sent.retcode != metatrader.TRADE_RETCODE_DONE and sent.retcode != metatrader.TRADE_RETCODE_PLACED:
        printerrln "order rejected:", sent.comment
        ret 1
    end

    margin := metatrader.OrderCalcMargin(metatrader.ORDER_TYPE_BUY, "EURUSD", 0.10, 1.0821)
    profit := metatrader.OrderCalcProfit(metatrader.ORDER_TYPE_BUY, "EURUSD", 0.10, 1.0821, 1.09)
    println margin, profit
    ret 0
end

action selects what the request does: TRADE_ACTION_DEAL for a market order, TRADE_ACTION_PENDING for a pending one, TRADE_ACTION_SLTP to change stops, TRADE_ACTION_MODIFY and TRADE_ACTION_REMOVE for pending orders, and TRADE_ACTION_CLOSE_BY to close one position with another. Set type_filling to a mode the symbol allows, and set magic so you can find your own orders later.

Orders, positions and history

OrdersGet returns active orders, PositionsGet returns open positions, and the history calls return what is already closed. Every filter has a total and a get form; the get form returns a vector, even when you ask by ticket, because the bridge keeps one answer shape.

History times are seconds since the epoch. Give both ends of the range; an empty range returns an empty vector, not an error.

metatrader-history.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    date_from := 1700000000 as i64
    date_to := 1700086400 as i64

    println "orders:", metatrader.HistoryOrdersTotal(date_from, date_to)
    each o in metatrader.HistoryOrdersGet(date_from, date_to):
        println o.ticket, o.symbol, o.state, o.volume_initial, o.price_open
    end

    println "deals:", metatrader.HistoryDealsTotal(date_from, date_to)
    each d in metatrader.HistoryDealsGet(date_from, date_to):
        println d.ticket, d.order, d.position_id, d.deal_type, d.entry, d.profit, d.commission, d.swap
    end

    if metatrader.MarketBookAdd("EURUSD"):
        each b in metatrader.MarketBookGet("EURUSD"):
            println b.book_type, b.price, b.volume
        end
        metatrader.MarketBookRelease("EURUSD")
    end
    ret 0
end

Market depth

Market depth is a subscription. Call MarketBookAdd once, read the levels with MarketBookGet as often as you need, and call MarketBookRelease when you stop. The depth stays empty until the terminal has it and the subscription is active.

Types and units

TypeWhat it holds
AccountInfoBalance, equity, margin, free margin, margin level, currency and account limits.
TerminalInfoConnection, build, folders, language and permissions of the terminal.
SymbolInfoPrices, spread, digits, point, contract size, volume limits, swap and session data.
Tick, RateOne price change and one candle; times are seconds, and tick times also have milliseconds.
TradeOrderAn order with its state, volume, prices and the position it belongs to.
TradePositionAn open position with its volume, profit, swap and stop prices.
TradeDealAn executed deal with its profit, commission, swap and fee.
TradeRequest, OrderCheckResult, OrderSendResultThe input and the two possible answers of the trading calls.

What the package does not do

  • It does not start the terminal. The bridge must be running and the terminal logged in; Initialize is a request to the bridge, not to the terminal process.
  • It does not retry. A timeout, a closed bridge or an HTTP 5xx is returned once; decide in your own code whether to repeat the call.
  • It does not replace OrderCheck with local validation. The broker has the last word on volume, stops, filling and market hours.
  • It does not keep a cache. Every call asks the bridge for fresh data, so a tight loop of SymbolInfoTick is a lot of HTTP requests; sleep between them.

Types

LastErrorInfo

struct LastErrorInfo
The last result of the package: a code and a description.
NameTypeDescription
codeint = 1The result code; RES_S_OK on success.
descriptionstr = "ok"The human readable description of the code or instrument.

VersionInfo

struct VersionInfo
The version and build of the MetaTrader terminal.
NameTypeDescription
terminal_versionint = 0The version of the terminal.
buildint = 0The build number.
build_release_datestr = ""The release date of that build.

AccountInfo

struct AccountInfo
The state of the trading account: balance, equity, margin and limits.
NameTypeDescription
logini64 = 0The account number.
trade_modeint = 0The trade mode of the symbol or account.
leveragei64 = 0The leverage of the account.
limit_ordersint = 0The greatest number of open orders the account allows.
margin_so_modeint = 0The stop out mode of the account.
trade_allowedbool = falseTrue when trading is allowed.
trade_expertbool = falseTrue when expert trading is allowed.
margin_modeint = 0The margin calculation mode of the account.
currency_digitsint = 0The digits used for the deposit currency.
fifo_closebool = falseTrue when positions must close in the order they opened.
balancef64 = 0The account balance in the deposit currency.
creditf64 = 0The credit granted to the account.
profitf64 = 0The floating profit or the profit of the deal.
equityf64 = 0Balance plus floating profit and credit.
marginf64 = 0The margin currently used.
margin_freef64 = 0Free margin available for new positions.
margin_levelf64 = 0Equity divided by margin, in percent.
margin_so_callf64 = 0The margin level that triggers a margin call, in percent.
margin_so_sof64 = 0The margin level that triggers a stop out, in percent.
margin_initialf64 = 0The initial margin of one lot.
margin_maintenancef64 = 0The maintenance margin of one lot.
assetsf64 = 0Total assets in the account.
liabilitiesf64 = 0Total liabilities in the account.
commission_blockedf64 = 0The commission blocked on the account.
namestr = ""The name of the account owner.
serverstr = ""The trade server of the account.
currencystr = ""The deposit currency of the account.
companystr = ""The company that provides the account.

TerminalInfo

struct TerminalInfo
The state of the MetaTrader terminal: connection, folders and permissions.
NameTypeDescription
community_accountbool = falseTrue when the account is a MQL5.community account.
community_connectionbool = falseTrue when the terminal has a MQL5.community connection.
connectedbool = falseTrue while the terminal is connected to the trade server.
dlls_allowedbool = falseTrue when the terminal allows DLL calls.
trade_allowedbool = falseTrue when trading is allowed.
tradeapi_disabledbool = falseTrue when the trade API is disabled in the terminal.
email_enabledbool = falseTrue when email is enabled in the terminal.
ftp_enabledbool = falseTrue when FTP is enabled in the terminal.
notifications_enabledbool = falseTrue when push notifications are enabled.
mqidbool = falseTrue when the terminal has a MetaQuotes ID.
buildint = 0The build number.
maxbarsint = 0The greatest number of bars the terminal keeps.
codepageint = 0The code page of the terminal.
ping_lastint = 0The last ping to the trade server, in milliseconds.
community_balancef64 = 0The MQL5.community balance.
retransmissionf64 = 0The share of retransmitted data, in percent.
companystr = ""The company that provides the account.
namestr = ""The name of the terminal.
languagestr = ""The interface language of the terminal.
pathstr = ""The installation folder of the terminal.
data_pathstr = ""The data folder of this terminal.
commondata_pathstr = ""The shared data folder of all terminals.

SymbolInfo

struct SymbolInfo
Everything the terminal knows about one symbol, from prices to contract rules.
NameTypeDescription
custombool = falseTrue when the symbol is custom, not from the server.
chart_modeint = 0How the symbol is shown in Market Watch.
selectbool = falseTrue when the symbol is selected in Market Watch.
visiblebool = falseTrue when the symbol is visible in Market Watch.
session_dealsint = 0The deals made in the session.
session_buy_ordersint = 0The buy orders placed in the session.
session_sell_ordersint = 0The sell orders placed in the session.
volumei64 = 0The tick volume of the day.
volumehighi64 = 0The highest volume of the day.
volumelowi64 = 0The lowest volume of the day.
timei64 = 0The time in seconds since the epoch.
digitsint = 0The digits after the decimal point in the price.
spreadint = 0The spread in points.
spread_floatbool = falseTrue when the spread floats.
ticks_bookdepthint = 0The depth of the book the ticks cover.
trade_calc_modeint = 0The profit calculation mode of the symbol.
trade_modeint = 0The trade mode of the symbol or account.
start_timei64 = 0The time the symbol starts trading, in seconds since the epoch.
expiration_timei64 = 0The expiration time of the symbol, in seconds since the epoch; 0 when it does not expire.
trade_stops_levelint = 0The shortest allowed distance to the price for stops, in points.
trade_freeze_levelint = 0The distance in points where orders cannot be changed.
trade_exemodeint = 0The execution mode of the symbol.
swap_modeint = 0The swap calculation mode of the symbol.
swap_rollover3daysint = 0The weekday with triple swap: 0 is Sunday.
margin_hedged_use_legbool = falseTrue when the hedged margin uses the larger leg.
expiration_modeint = 0The expiration modes the symbol allows.
filling_modeint = 0The filling modes the symbol allows, as a bit mask.
order_modeint = 0The order types the symbol allows, as a bit mask.
order_gtc_modeint = 0The GTC order mode of the symbol.
option_modeint = 0The option mode of the symbol.
option_rightint = 0The option right of the symbol.
bidf64 = 0The best bid price.
bidhighf64 = 0The highest bid of the session.
bidlowf64 = 0The lowest bid of the session.
askf64 = 0The best ask price.
askhighf64 = 0The highest ask of the session.
asklowf64 = 0The lowest ask of the session.
lastf64 = 0The last trade price.
lasthighf64 = 0The highest last price of the session.
lastlowf64 = 0The lowest last price of the session.
volume_realf64 = 0The real volume, in contracts or units.
volumehigh_realf64 = 0The highest real volume of the day.
volumelow_realf64 = 0The lowest real volume of the day.
option_strikef64 = 0The strike price of the option.
pointf64 = 0The point size of the symbol.
trade_tick_valuef64 = 0The value of one tick in the deposit currency.
trade_tick_value_profitf64 = 0The value of one tick for a profit.
trade_tick_value_lossf64 = 0The value of one tick for a loss.
trade_tick_sizef64 = 0The tick size used for profit.
trade_contract_sizef64 = 0The size of one contract.
trade_accrued_interestf64 = 0The accrued interest of the instrument.
trade_face_valuef64 = 0The face value of the instrument.
trade_liquidity_ratef64 = 0The liquidity rate of the instrument.
volume_minf64 = 0The smallest volume of one order.
volume_maxf64 = 0The greatest volume of one position.
volume_stepf64 = 0The step between volumes.
volume_limitf64 = 0The greatest volume of one order.
swap_longf64 = 0The swap of a long position per lot per day.
swap_shortf64 = 0The swap of a short position per lot per day.
margin_initialf64 = 0The initial margin of one lot.
margin_maintenancef64 = 0The maintenance margin of one lot.
session_volumef64 = 0The volume of the session.
session_turnoverf64 = 0The turnover of the session.
session_interestf64 = 0The open interest of the session.
session_buy_orders_volumef64 = 0The volume of the buy orders of the session.
session_sell_orders_volumef64 = 0The volume of the sell orders of the session.
session_openf64 = 0The open price of the session.
session_closef64 = 0The close price of the session.
session_awf64 = 0The weighted average price of the session.
session_price_settlementf64 = 0The settlement price of the session.
session_price_limit_minf64 = 0The lower price limit of the session.
session_price_limit_maxf64 = 0The upper price limit of the session.
margin_hedgedf64 = 0The margin of a hedged position.
price_changef64 = 0The price change of the day, in percent.
price_volatilityf64 = 0The price volatility of the instrument.
price_theoreticalf64 = 0The theoretical price of the option.
price_greeks_deltaf64 = 0The delta of the option.
price_greeks_thetaf64 = 0The theta of the option.
price_greeks_gammaf64 = 0The gamma of the option.
price_greeks_vegaf64 = 0The vega of the option.
price_greeks_rhof64 = 0The rho of the option.
price_greeks_omegaf64 = 0The omega of the option.
price_sensitivityf64 = 0The price sensitivity of the instrument.
basisstr = ""The basis of the instrument.
categorystr = ""The category of the instrument.
currency_basestr = ""The base currency of the symbol.
currency_profitstr = ""The profit currency of the symbol.
currency_marginstr = ""The margin currency of the symbol.
bankstr = ""The bank of the instrument, for exchange instruments.
descriptionstr = ""The human readable description of the code or instrument.
exchangestr = ""The exchange of the instrument.
formulastr = ""The pricing formula of the instrument.
isinstr = ""The ISIN of the instrument.
namestr = ""The name of the account, symbol or terminal.
pagestr = ""The web page of the instrument.
pathstr = ""The path of the symbol in the symbol tree.

Tick

struct Tick
One price change of a symbol.
NameTypeDescription
timei64 = 0The time in seconds since the epoch.
bidf64 = 0The best bid price.
askf64 = 0The best ask price.
lastf64 = 0The last trade price.
volumei64 = 0The tick volume.
time_msci64 = 0The time in milliseconds since the epoch.
flagsint = 0The tick flags, a combination of TICK_FLAG_*.
volume_realf64 = 0The real volume, in contracts or units.

Rate

struct Rate
One candle of a symbol at a timeframe.
NameTypeDescription
timei64 = 0The time in seconds since the epoch.
openf64 = 0The open price of the candle.
highf64 = 0The high price of the candle.
lowf64 = 0The low price of the candle.
closef64 = 0The close price of the candle.
tick_volumei64 = 0The tick volume of the candle.
spreadint = 0The spread in points.
real_volumei64 = 0The real volume of the candle or tick, in contracts.

BookInfo

struct BookInfo
One level of the market depth, a price and its volume.
NameTypeDescription
book_typeint = 0The side of the book level, BOOK_TYPE_SELL or BOOK_TYPE_BUY.
pricef64 = 0The price of the request, the book level or the result.
volumei64 = 0The volume of the book level, in lots.
volume_dblf64 = 0The volume of the book level as a floating point number.

TradeRequest

struct TradeRequest
A trade request for OrderCheck and OrderSend.
NameTypeDescription
actionint = 0The trade operation, one of the TRADE_ACTION_* values.
magici64 = 0The magic number that identifies the expert.
orderi64 = 0The order ticket.
symbolstr = ""The trading symbol.
volumef64 = 0The volume to trade, in lots.
pricef64 = 0The price of the request; for a market order the current price.
stoplimitf64 = 0The stop limit price, in points from the stop price.
slf64 = 0The stop loss price; 0 when there is none.
tpf64 = 0The take profit price; 0 when there is none.
deviationint = 0The allowed slippage in points.
order_typeint = 0The order type, one of ORDER_TYPE_*.
type_fillingint = 0The filling type of the order, one of ORDER_FILLING_*.
type_timeint = 0The time type of the order, one of ORDER_TIME_*.
expirationi64 = 0The expiration time of the request, in seconds since the epoch.
commentstr = ""The comment stored with the record.
positioni64 = 0The ticket of the position the request changes.
position_byi64 = 0The ticket of the opposite position for a close by.

OrderCheckResult

struct OrderCheckResult
What OrderCheck reports: the result code and the margin the order would use.
NameTypeDescription
retcodeint = 0The result code of the trade request.
balancef64 = 0The balance after the order.
equityf64 = 0The equity after the order.
profitf64 = 0The profit the order would add.
marginf64 = 0The margin the order would use.
margin_freef64 = 0The free margin after the order.
margin_levelf64 = 0Equity divided by margin, in percent.
commentstr = ""The comment stored with the record.
requestTradeRequestThe request that produced this result.

OrderSendResult

struct OrderSendResult
What OrderSend reports: the result code and the tickets it created.
NameTypeDescription
retcodeint = 0The result code of the trade request.
deali64 = 0The ticket of the deal the server created.
orderi64 = 0The ticket of the order the server created.
volumef64 = 0The volume in lots.
pricef64 = 0The price of the request, the book level or the result.
bidf64 = 0The best bid price.
askf64 = 0The best ask price.
commentstr = ""The comment stored with the record.
request_idint = 0The identifier the server assigned to the request.
retcode_externalint = 0The result code of the external system.
requestTradeRequestThe request that produced this result.

TradeOrder

struct TradeOrder
An active or historical order.
NameTypeDescription
ticketi64 = 0The ticket of the record.
time_setupi64 = 0The time the order was placed, in seconds since the epoch.
time_setup_msci64 = 0The time the order was placed, in milliseconds since the epoch.
time_donei64 = 0The time the order was done, in seconds since the epoch.
time_done_msci64 = 0The time the order was done, in milliseconds since the epoch.
time_expirationi64 = 0The expiration time of the order, in seconds since the epoch.
order_typeint = 0The order type, one of ORDER_TYPE_*.
type_timeint = 0The time type of the order, one of ORDER_TIME_*.
type_fillingint = 0The filling type of the order, one of ORDER_FILLING_*.
stateint = 0The order state, one of ORDER_STATE_*.
magici64 = 0The magic number that identifies the expert.
position_idi64 = 0The identifier of the position.
position_by_idi64 = 0The identifier of the opposite position.
reasonint = 0The reason the record was created, one of the reason constants.
volume_initialf64 = 0The volume the order was placed with.
volume_currentf64 = 0The volume still open on the order.
price_openf64 = 0The price the order was placed at.
slf64 = 0The stop loss price; 0 when there is none.
tpf64 = 0The take profit price; 0 when there is none.
price_currentf64 = 0The current price of the order or position.
price_stoplimitf64 = 0The stop limit price of a stop limit order.
symbolstr = ""The trading symbol.
commentstr = ""The comment stored with the record.
external_idstr = ""The exchange identifier of the order, position or deal.

TradePosition

struct TradePosition
An open position, with its volume, prices and profit.
NameTypeDescription
ticketi64 = 0The ticket of the record.
timei64 = 0The time in seconds since the epoch.
time_msci64 = 0The time in milliseconds since the epoch.
time_updatei64 = 0The time of the last update, in seconds since the epoch.
time_update_msci64 = 0The time of the last update, in milliseconds since the epoch.
position_typeint = 0The position type, POSITION_TYPE_BUY or POSITION_TYPE_SELL.
magici64 = 0The magic number that identifies the expert.
identifieri64 = 0The identifier of the position.
reasonint = 0The reason the record was created, one of the reason constants.
volumef64 = 0The volume of the position, in lots.
price_openf64 = 0The price the position opened at.
slf64 = 0The stop loss price; 0 when there is none.
tpf64 = 0The take profit price; 0 when there is none.
price_currentf64 = 0The current price of the order or position.
swapf64 = 0The swap charged on the position or deal.
profitf64 = 0The floating profit or the profit of the deal.
symbolstr = ""The trading symbol.
commentstr = ""The comment stored with the record.
external_idstr = ""The exchange identifier of the order, position or deal.

TradeDeal

struct TradeDeal
A deal that was executed, with its profit, commission and swap.
NameTypeDescription
ticketi64 = 0The ticket of the record.
orderi64 = 0The ticket of the order the deal came from.
timei64 = 0The time in seconds since the epoch.
time_msci64 = 0The time in milliseconds since the epoch.
deal_typeint = 0The deal type, one of the DEAL_TYPE_* values.
entryint = 0How the deal entered or left the position, one of DEAL_ENTRY_*.
magici64 = 0The magic number that identifies the expert.
position_idi64 = 0The identifier of the position.
reasonint = 0The reason the record was created, one of the reason constants.
volumef64 = 0The volume of the deal, in lots.
pricef64 = 0The price of the request, the book level or the result.
commissionf64 = 0The commission charged for the deal.
swapf64 = 0The swap charged on the position or deal.
profitf64 = 0The floating profit or the profit of the deal.
feef64 = 0The fee charged for the deal.
symbolstr = ""The trading symbol.
commentstr = ""The comment stored with the record.
external_idstr = ""The exchange identifier of the order, position or deal.

Constants and variables

DEFAULT_BRIDGE_URL

const DEFAULT_BRIDGE_URL: str = "http://127.0.0.1:18812"
The default address of the bridge.

DEFAULT_TIMEOUT_MS

const DEFAULT_TIMEOUT_MS: i32 = 60000
The default timeout of a bridge call, in milliseconds: 60000.

Timeframes TIMEFRAME_…

Chart timeframes, the values of the MQL5 ENUM_TIMEFRAMES.
NameValue
TIMEFRAME_M11
TIMEFRAME_M22
TIMEFRAME_M33
TIMEFRAME_M44
TIMEFRAME_M55
TIMEFRAME_M66
TIMEFRAME_M1010
TIMEFRAME_M1212
TIMEFRAME_M1515
TIMEFRAME_M2020
TIMEFRAME_M3030
TIMEFRAME_H116385
TIMEFRAME_H216386
TIMEFRAME_H316387
TIMEFRAME_H416388
TIMEFRAME_H616390
TIMEFRAME_H816392
TIMEFRAME_H1216396
TIMEFRAME_D116408
TIMEFRAME_W132769
TIMEFRAME_MN149153

Order types ORDER_TYPE_…

Order types, the values of ENUM_ORDER_TYPE.
NameValue
ORDER_TYPE_BUY0
ORDER_TYPE_SELL1
ORDER_TYPE_BUY_LIMIT2
ORDER_TYPE_SELL_LIMIT3
ORDER_TYPE_BUY_STOP4
ORDER_TYPE_SELL_STOP5
ORDER_TYPE_BUY_STOP_LIMIT6
ORDER_TYPE_SELL_STOP_LIMIT7
ORDER_TYPE_CLOSE_BY8

Order states ORDER_STATE_…

Order states, the values of ENUM_ORDER_STATE.
NameValue
ORDER_STATE_STARTED0
ORDER_STATE_PLACED1
ORDER_STATE_CANCELED2
ORDER_STATE_PARTIAL3
ORDER_STATE_FILLED4
ORDER_STATE_REJECTED5
ORDER_STATE_EXPIRED6
ORDER_STATE_REQUEST_ADD7
ORDER_STATE_REQUEST_MODIFY8
ORDER_STATE_REQUEST_CANCEL9

Filling modes ORDER_FILLING_…

Order filling modes, the values of ENUM_ORDER_TYPE_FILLING.
NameValue
ORDER_FILLING_FOK0
ORDER_FILLING_IOC1
ORDER_FILLING_RETURN2
ORDER_FILLING_BOC3

Order lifetimes ORDER_TIME_…

Order time types, the values of ENUM_ORDER_TYPE_TIME.
NameValue
ORDER_TIME_GTC0
ORDER_TIME_DAY1
ORDER_TIME_SPECIFIED2
ORDER_TIME_SPECIFIED_DAY3

Order reasons ORDER_REASON_…

Why the terminal created an order, the values of ENUM_ORDER_REASON.
NameValue
ORDER_REASON_CLIENT0
ORDER_REASON_MOBILE1
ORDER_REASON_WEB2
ORDER_REASON_EXPERT3
ORDER_REASON_SL4
ORDER_REASON_TP5
ORDER_REASON_SO6

Trade actions TRADE_ACTION_…

Trade request actions, the values of ENUM_TRADE_REQUEST_ACTIONS.
NameValue
TRADE_ACTION_DEAL1
TRADE_ACTION_PENDING5
TRADE_ACTION_SLTP6
TRADE_ACTION_MODIFY7
TRADE_ACTION_REMOVE8
TRADE_ACTION_CLOSE_BY10

Position types POSITION_TYPE_…

Position types, the values of ENUM_POSITION_TYPE.
NameValue
POSITION_TYPE_BUY0
POSITION_TYPE_SELL1

Position reasons POSITION_REASON_…

Why the terminal opened a position, the values of ENUM_POSITION_REASON.
NameValue
POSITION_REASON_CLIENT0
POSITION_REASON_MOBILE1
POSITION_REASON_WEB2
POSITION_REASON_EXPERT3

Deal types DEAL_TYPE_…

Deal types, the values of ENUM_DEAL_TYPE.
NameValue
DEAL_TYPE_BUY0
DEAL_TYPE_SELL1
DEAL_TYPE_BALANCE2
DEAL_TYPE_CREDIT3
DEAL_TYPE_CHARGE4
DEAL_TYPE_CORRECTION5
DEAL_TYPE_BONUS6
DEAL_TYPE_COMMISSION7
DEAL_TYPE_COMMISSION_DAILY8
DEAL_TYPE_COMMISSION_MONTHLY9
DEAL_TYPE_COMMISSION_AGENT_DAILY10
DEAL_TYPE_COMMISSION_AGENT_MONTHLY11
DEAL_TYPE_INTEREST12
DEAL_TYPE_BUY_CANCELED13
DEAL_TYPE_SELL_CANCELED14

Deal kinds DEAL_…

Deal kinds that are not a buy or a sell, such as dividends and taxes.
NameValue
DEAL_DIVIDEND15
DEAL_DIVIDEND_FRANKED16
DEAL_TAX17

Deal entries DEAL_ENTRY_…

How a deal changed the position, the values of ENUM_DEAL_ENTRY.
NameValue
DEAL_ENTRY_IN0
DEAL_ENTRY_OUT1
DEAL_ENTRY_INOUT2
DEAL_ENTRY_OUT_BY3

Deal reasons DEAL_REASON_…

Why the terminal made a deal, the values of ENUM_DEAL_REASON.
NameValue
DEAL_REASON_CLIENT0
DEAL_REASON_MOBILE1
DEAL_REASON_WEB2
DEAL_REASON_EXPERT3
DEAL_REASON_SL4
DEAL_REASON_TP5
DEAL_REASON_SO6
DEAL_REASON_ROLLOVER7
DEAL_REASON_VMARGIN8
DEAL_REASON_SPLIT9

Trade result codes TRADE_RETCODE_…

Result codes the trade server returns in retcode.
NameValue
TRADE_RETCODE_REQUOTE10004
TRADE_RETCODE_REJECT10006
TRADE_RETCODE_CANCEL10007
TRADE_RETCODE_PLACED10008
TRADE_RETCODE_DONE10009
TRADE_RETCODE_DONE_PARTIAL10010
TRADE_RETCODE_ERROR10011
TRADE_RETCODE_TIMEOUT10012
TRADE_RETCODE_INVALID10013
TRADE_RETCODE_INVALID_VOLUME10014
TRADE_RETCODE_INVALID_PRICE10015
TRADE_RETCODE_INVALID_STOPS10016
TRADE_RETCODE_TRADE_DISABLED10017
TRADE_RETCODE_MARKET_CLOSED10018
TRADE_RETCODE_NO_MONEY10019
TRADE_RETCODE_PRICE_CHANGED10020
TRADE_RETCODE_PRICE_OFF10021
TRADE_RETCODE_INVALID_EXPIRATION10022
TRADE_RETCODE_ORDER_CHANGED10023
TRADE_RETCODE_TOO_MANY_REQUESTS10024
TRADE_RETCODE_NO_CHANGES10025
TRADE_RETCODE_SERVER_DISABLES_AT10026
TRADE_RETCODE_CLIENT_DISABLES_AT10027
TRADE_RETCODE_LOCKED10028
TRADE_RETCODE_FROZEN10029
TRADE_RETCODE_INVALID_FILL10030
TRADE_RETCODE_CONNECTION10031
TRADE_RETCODE_ONLY_REAL10032
TRADE_RETCODE_LIMIT_ORDERS10033
TRADE_RETCODE_LIMIT_VOLUME10034
TRADE_RETCODE_INVALID_ORDER10035
TRADE_RETCODE_POSITION_CLOSED10036
TRADE_RETCODE_INVALID_CLOSE_VOLUME10038
TRADE_RETCODE_CLOSE_ORDER_EXIST10039
TRADE_RETCODE_LIMIT_POSITIONS10040
TRADE_RETCODE_REJECT_CANCEL10041
TRADE_RETCODE_LONG_ONLY10042
TRADE_RETCODE_SHORT_ONLY10043
TRADE_RETCODE_CLOSE_ONLY10044
TRADE_RETCODE_FIFO_CLOSE10045
TRADE_RETCODE_HEDGE_PROHIBITED10046

Book levels BOOK_TYPE_…

The side of a market depth level, the values of ENUM_BOOK_TYPE.
NameValue
BOOK_TYPE_SELL0
BOOK_TYPE_BUY1
BOOK_TYPE_SELL_MARKET2
BOOK_TYPE_BUY_MARKET3

Tick filters COPY_TICKS_…

What CopyTicksFrom and CopyTicksRange return, the values of ENUM_COPY_TICKS.
NameValue
COPY_TICKS_ALL-1
COPY_TICKS_INFO1
COPY_TICKS_TRADE2

Tick flags TICK_FLAG_…

What a tick carries, as a bit mask in flags.
NameValue
TICK_FLAG_BID2
TICK_FLAG_ASK4
TICK_FLAG_LAST8
TICK_FLAG_VOLUME16
TICK_FLAG_BUY32
TICK_FLAG_SELL64

Symbol trade modes SYMBOL_TRADE_MODE_…

What trading a symbol allows, the values of ENUM_SYMBOL_TRADE_MODE.
NameValue
SYMBOL_TRADE_MODE_DISABLED0
SYMBOL_TRADE_MODE_LONGONLY1
SYMBOL_TRADE_MODE_SHORTONLY2
SYMBOL_TRADE_MODE_CLOSEONLY3
SYMBOL_TRADE_MODE_FULL4

Symbol calculation modes SYMBOL_CALC_MODE_…

How the terminal calculates profit and margin for a symbol, the values of ENUM_SYMBOL_CALC_MODE.
NameValue
SYMBOL_CALC_MODE_FOREX0
SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE1
SYMBOL_CALC_MODE_FUTURES2
SYMBOL_CALC_MODE_CFD3
SYMBOL_CALC_MODE_CFDINDEX4
SYMBOL_CALC_MODE_CFDLEVERAGE5
SYMBOL_CALC_MODE_EXCH_STOCKS32
SYMBOL_CALC_MODE_EXCH_FUTURES33
SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS34
SYMBOL_CALC_MODE_EXCH_BONDS35
SYMBOL_CALC_MODE_EXCH_STOCKS_MOEX36
SYMBOL_CALC_MODE_EXCH_BONDS_MOEX37
SYMBOL_CALC_MODE_SERV_COLLATERAL38

Bridge result codes RES_…

Result codes the bridge and this package use in LastError.
NameValue
RES_S_OK1
RES_E_FAIL-1
RES_E_INVALID_PARAMS-2
RES_E_NO_MEMORY-3
RES_E_NOT_FOUND-4
RES_E_INVALID_VERSION-5
RES_E_AUTH_FAILED-6
RES_E_UNSUPPORTED-7
RES_E_AUTO_TRADING_DISABLED-8
RES_E_INTERNAL_FAIL-10000
RES_E_INTERNAL_FAIL_SEND-10001
RES_E_INTERNAL_FAIL_RECEIVE-10002
RES_E_INTERNAL_FAIL_INIT-10003
RES_E_INTERNAL_FAIL_CONNECT-10003
RES_E_INTERNAL_FAIL_TIMEOUT-10005

Functions

CopyRatesFrom

func CopyRatesFrom(symbol: str, timeframe: int, date_from: i64, count: int): Vector<Rate>
Candles from a time onward: the oldest candle at or after date_from, then up to count candles.
metatrader-Rates.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    from := metatrader.CopyRatesFrom("EURUSD", metatrader.TIMEFRAME_H1, 1700000000 as i64, 10)
    each r in from:
        println r.time, r.open, r.high, r.low, r.close, r.tick_volume
    end

    recent := metatrader.CopyRatesFromPos("EURUSD", metatrader.TIMEFRAME_M5, 0, 5)
    println "recent:", recent.len()

    window := metatrader.CopyRatesRange("EURUSD", metatrader.TIMEFRAME_D1, 1700000000 as i64, 1700086400 as i64)
    println "daily:", window.len()

    ticks := metatrader.CopyTicksFrom("EURUSD", 1700000000 as i64, 100, metatrader.COPY_TICKS_ALL)
    each t in ticks:
        println t.time_msc, t.bid, t.ask, t.last, t.flags
    end

    trade_ticks := metatrader.CopyTicksRange("EURUSD", 1700000000000 as i64, 1700000600000 as i64, metatrader.COPY_TICKS_TRADE)
    println "trade ticks:", trade_ticks.len()
    ret 0
end

CopyRatesFromPos

func CopyRatesFromPos(symbol: str, timeframe: int, start_pos: int, count: int): Vector<Rate>
Candles by position: start_pos is counted from the current candle, 0 being the newest, so 0 and 10 give the last ten candles.

The example for this item is shown with the ones above: metatrader-Rates.salam

CopyRatesRange

func CopyRatesRange(symbol: str, timeframe: int, date_from: i64, date_to: i64): Vector<Rate>
The candles between two times, both in seconds since the epoch.

The example for this item is shown with the ones above: metatrader-Rates.salam

SymbolsTotal

func SymbolsTotal(): int
The number of symbols the terminal offers. Returns 0 on failure.
metatrader-Symbols.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    println "symbols:", metatrader.SymbolsTotal()
    each s in metatrader.SymbolsGet():
        println s.name, s.digits, s.spread, s.trade_mode
    end

    majors := metatrader.SymbolsGetGroup("*USD*")
    println "usd symbols:", majors.len()

    info := metatrader.GetSymbolInfo("EURUSD")
    println info.bid, info.ask, info.point, info.digits
    println info.volume_min, info.volume_step, info.volume_max
    println info.trade_stops_level, info.trade_contract_size

    tick := metatrader.SymbolInfoTick("EURUSD")
    println tick.time, tick.bid, tick.ask, tick.last, tick.volume

    if not metatrader.SymbolSelect("EURUSD", true):
        printerrln "cannot select EURUSD"
    end
    ret 0
end

SymbolsGet

func SymbolsGet(): Vector<SymbolInfo>
Every symbol the terminal offers, with its prices, contract rules and session data.

The example for this item is shown with the ones above: metatrader-Symbols.salam

SymbolsGetGroup

func SymbolsGetGroup(group: str): Vector<SymbolInfo>
The symbols that match a group mask such as *USD*.

The example for this item is shown with the ones above: metatrader-Symbols.salam

GetSymbolInfo

func GetSymbolInfo(symbol: str): SymbolInfo
Everything the terminal knows about one symbol; an empty struct on failure.

The example for this item is shown with the ones above: metatrader-Symbols.salam

SymbolInfoTick

func SymbolInfoTick(symbol: str): Tick
The latest tick of a symbol: bid, ask, last, volume and flags.

The example for this item is shown with the ones above: metatrader-Symbols.salam

SymbolSelect

func SymbolSelect(symbol: str, enable: bool): bool
Adds a symbol to Market Watch or removes it, and returns true when the terminal accepted the change.

The example for this item is shown with the ones above: metatrader-Symbols.salam

SetBridgeUrl

func SetBridgeUrl(url: str)
Sets the base address of the bridge, for example http://127.0.0.1:18812. It applies to every later call.
metatrader-Connect.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")
    println metatrader.BridgeUrl()

    if not metatrader.Initialize("", 12345678 as i64, "secret", "Broker-Demo", 60000, false):
        e := metatrader.LastError()
        printerrln "initialize failed:", e.code, e.description
        ret 1
    end
    if not metatrader.Login(12345678 as i64, "secret", "Broker-Demo", 60000):
        e := metatrader.LastError()
        printerrln "login failed:", e.code, e.description
        ret 1
    end

    v := metatrader.Version()
    println "connected:", metatrader.IsConnected()
    println "terminal:", v.terminal_version, "build", v.build, v.build_release_date
    if not metatrader.Ok():
        e := metatrader.LastError()
        printerrln e.code, e.description
    end

    metatrader.Shutdown()
    ret 0
end

BridgeUrl

func BridgeUrl(): str
The bridge address in use, by default DEFAULT_BRIDGE_URL.

The example for this item is shown with the ones above: metatrader-Connect.salam

Initialize

func Initialize(path: str = "", login: i64 = 0, password: str = "", server: str = "", timeout_ms: int, portable: bool = false): bool
Calls the /initialize endpoint, optionally changing the bridge address, and marks the session connected when the bridge answers. The login and password are passed through for bridges that start the terminal themselves.

The example for this item is shown with the ones above: metatrader-Connect.salam

Login

func Login(login: i64, password: str = "", server: str = "", timeout_ms: int): bool
Calls the /login endpoint with an account number, password, server and timeout, and marks the session connected on success.

The example for this item is shown with the ones above: metatrader-Connect.salam

Shutdown

func Shutdown()
Calls /shutdown and marks the session disconnected. Call it before the program ends so the bridge can close the terminal cleanly.

The example for this item is shown with the ones above: metatrader-Connect.salam

IsConnected

func IsConnected(): bool
True after a successful Initialize or Login and before Shutdown; it reports the last call, not a live check.

The example for this item is shown with the ones above: metatrader-Connect.salam

Version

func Version(): VersionInfo
The terminal version and build, with the release date of the build.

The example for this item is shown with the ones above: metatrader-Connect.salam

LastError

func LastError(): LastErrorInfo
The code and description of the last operation, as the package or the bridge set them.

The example for this item is shown with the ones above: metatrader-Connect.salam

Ok

func Ok(): bool
True when the last operation succeeded, that is when LastError is RES_S_OK.

The example for this item is shown with the ones above: metatrader-Connect.salam

OrdersTotal

func OrdersTotal(): int
The number of active orders, as the terminal reports it. Returns 0 on failure, with LastError set.
metatrader-Trade.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    println "orders:", metatrader.OrdersTotal()
    each o in metatrader.OrdersGet():
        println o.ticket, o.symbol, o.order_type, o.state, o.volume_current, o.price_open
    end
    each p in metatrader.PositionsGet():
        println p.ticket, p.symbol, p.position_type, p.volume, p.price_open, p.profit
    end

    mut req := metatrader.TradeRequest {}
    req.action = metatrader.TRADE_ACTION_DEAL
    req.symbol = "EURUSD"
    req.volume = 0.10
    req.price = 1.0821
    req.order_type = metatrader.ORDER_TYPE_BUY
    req.type_filling = metatrader.ORDER_FILLING_IOC
    req.type_time = metatrader.ORDER_TIME_GTC
    req.deviation = 10
    req.magic = 2026
    req.comment = "salam"

    check := metatrader.OrderCheck(req)
    println "check:", check.retcode, check.margin, check.margin_free, check.comment
    if check.retcode != 0:
        ret 1
    end

    sent := metatrader.OrderSend(req)
    println "send:", sent.retcode, sent.order, sent.deal, sent.price
    if sent.retcode != metatrader.TRADE_RETCODE_DONE and sent.retcode != metatrader.TRADE_RETCODE_PLACED:
        printerrln "order rejected:", sent.comment
        ret 1
    end

    margin := metatrader.OrderCalcMargin(metatrader.ORDER_TYPE_BUY, "EURUSD", 0.10, 1.0821)
    profit := metatrader.OrderCalcProfit(metatrader.ORDER_TYPE_BUY, "EURUSD", 0.10, 1.0821, 1.09)
    println margin, profit
    ret 0
end

OrdersGet

func OrdersGet(): Vector<TradeOrder>
All active orders. Returns an empty vector on failure, with LastError set.

The example for this item is shown with the ones above: metatrader-Trade.salam

OrdersGetSymbol

func OrdersGetSymbol(symbol: str): Vector<TradeOrder>
The active orders of one symbol.

The example for this item is shown with the ones above: metatrader-Trade.salam

OrdersGetGroup

func OrdersGetGroup(group: str): Vector<TradeOrder>
The active orders of the symbols that match a group mask such as *USD*.

The example for this item is shown with the ones above: metatrader-Trade.salam

OrdersGetTicket

func OrdersGetTicket(ticket: i64): Vector<TradeOrder>
The active order with this ticket, as a vector of zero or one item, because the bridge answers in the same shape for every filter.

The example for this item is shown with the ones above: metatrader-Trade.salam

OrderCalcMargin

func OrderCalcMargin(action: int, symbol: str, volume: f64, price: f64): f64
The margin one order would use, in the deposit currency, for an action, symbol, volume and price. Returns 0 on failure.

The example for this item is shown with the ones above: metatrader-Trade.salam

OrderCalcProfit

func OrderCalcProfit(action: int, symbol: str, volume: f64, price_open: f64, price_close: f64): f64
The profit the order would make between two prices. Returns 0 on failure.

The example for this item is shown with the ones above: metatrader-Trade.salam

OrderCheck

func OrderCheck(request: TradeRequest): OrderCheckResult
Checks a request without sending it: the result code, the margin, the free margin after the order, and the balance, equity and profit the account would have.

The example for this item is shown with the ones above: metatrader-Trade.salam

OrderSend

func OrderSend(request: TradeRequest): OrderSendResult
Sends a request to the trade server and returns the result code, the order and deal tickets, the executed volume and price, and the server comment.

The example for this item is shown with the ones above: metatrader-Trade.salam

PositionsTotal

func PositionsTotal(): int
The number of open positions. Returns 0 on failure.

The example for this item is shown with the ones above: metatrader-Trade.salam

PositionsGet

func PositionsGet(): Vector<TradePosition>
All open positions.

The example for this item is shown with the ones above: metatrader-Trade.salam

PositionsGetSymbol

func PositionsGetSymbol(symbol: str): Vector<TradePosition>
The open positions of one symbol.

The example for this item is shown with the ones above: metatrader-Trade.salam

PositionsGetGroup

func PositionsGetGroup(group: str): Vector<TradePosition>
The open positions of the symbols that match a group mask.

The example for this item is shown with the ones above: metatrader-Trade.salam

PositionsGetTicket

func PositionsGetTicket(ticket: i64): Vector<TradePosition>
The open position with this ticket, as a vector of zero or one item.

The example for this item is shown with the ones above: metatrader-Trade.salam

HistoryOrdersTotal

func HistoryOrdersTotal(date_from: i64, date_to: i64): int
The number of orders in the history between two times, both in seconds since the epoch.
metatrader-History.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    date_from := 1700000000 as i64
    date_to := 1700086400 as i64

    println "orders:", metatrader.HistoryOrdersTotal(date_from, date_to)
    each o in metatrader.HistoryOrdersGet(date_from, date_to):
        println o.ticket, o.symbol, o.state, o.volume_initial, o.price_open
    end

    println "deals:", metatrader.HistoryDealsTotal(date_from, date_to)
    each d in metatrader.HistoryDealsGet(date_from, date_to):
        println d.ticket, d.order, d.position_id, d.deal_type, d.entry, d.profit, d.commission, d.swap
    end

    if metatrader.MarketBookAdd("EURUSD"):
        each b in metatrader.MarketBookGet("EURUSD"):
            println b.book_type, b.price, b.volume
        end
        metatrader.MarketBookRelease("EURUSD")
    end
    ret 0
end

HistoryOrdersGet

func HistoryOrdersGet(date_from: i64, date_to: i64): Vector<TradeOrder>
The orders in the history between two times.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryOrdersGetGroup

func HistoryOrdersGetGroup(date_from: i64, date_to: i64, group: str): Vector<TradeOrder>
The historical orders whose symbols match a group mask.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryOrdersGetTicket

func HistoryOrdersGetTicket(ticket: i64): Vector<TradeOrder>
The historical order with this ticket.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryOrdersGetPosition

func HistoryOrdersGetPosition(position: i64): Vector<TradeOrder>
The historical orders of one position.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryDealsTotal

func HistoryDealsTotal(date_from: i64, date_to: i64): int
The number of deals in the history between two times.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryDealsGet

func HistoryDealsGet(date_from: i64, date_to: i64): Vector<TradeDeal>
The deals in the history between two times.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryDealsGetGroup

func HistoryDealsGetGroup(date_from: i64, date_to: i64, group: str): Vector<TradeDeal>
The historical deals whose symbols match a group mask.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryDealsGetTicket

func HistoryDealsGetTicket(ticket: i64): Vector<TradeDeal>
The historical deal with this ticket.

The example for this item is shown with the ones above: metatrader-History.salam

HistoryDealsGetPosition

func HistoryDealsGetPosition(position: i64): Vector<TradeDeal>
The historical deals of one position.

The example for this item is shown with the ones above: metatrader-History.salam

CopyTicksFrom

func CopyTicksFrom(symbol: str, date_from: i64, count: int, flags: int): Vector<Tick>
Ticks from a time onward, up to count, filtered by the COPY_TICKS_* flags.

The example for this item is shown with the ones above: metatrader-Rates.salam

CopyTicksRange

func CopyTicksRange(symbol: str, date_from: i64, date_to: i64, flags: int): Vector<Tick>
The ticks between two times in milliseconds since the epoch, filtered by the COPY_TICKS_* flags.

The example for this item is shown with the ones above: metatrader-Rates.salam

GetAccountInfo

func GetAccountInfo(): AccountInfo
The current account state: login, balance, equity, margin, currency, server and company.
metatrader-Account.salam
import metatrader

func main:
    metatrader.SetBridgeUrl("http://127.0.0.1:18812")

    a := metatrader.GetAccountInfo()
    if not metatrader.Ok():
        e := metatrader.LastError()
        printerrln "account failed:", e.code, e.description
        ret 1
    end
    println a.login, a.name, a.server, a.currency
    println "balance", a.balance, "equity", a.equity
    println "margin", a.margin, "free", a.margin_free, "level", a.margin_level
    println "leverage", a.leverage, "limit", a.limit_orders
    if a.trade_allowed:
        println "trading is allowed"
    end

    t := metatrader.GetTerminalInfo()
    println t.company, t.name, t.build, t.connected
    println t.path
    println t.data_path
    ret 0
end

GetTerminalInfo

func GetTerminalInfo(): TerminalInfo
The current terminal state: connection, build, folders, language and permissions.

The example for this item is shown with the ones above: metatrader-Account.salam

MarketBookAdd

func MarketBookAdd(symbol: str): bool
Asks the terminal to keep the market depth of a symbol and returns true when it started. Read it with MarketBookGet and stop it with MarketBookRelease.

The example for this item is shown with the ones above: metatrader-History.salam

MarketBookGet

func MarketBookGet(symbol: str): Vector<BookInfo>
The current market depth of a symbol, or an empty vector when the depth is not subscribed or is not available.

The example for this item is shown with the ones above: metatrader-History.salam

MarketBookRelease

func MarketBookRelease(symbol: str): bool
Stops the market depth subscription of a symbol.

The example for this item is shown with the ones above: metatrader-History.salam