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_M1
1
TIMEFRAME_M2
2
TIMEFRAME_M3
3
TIMEFRAME_M4
4
TIMEFRAME_M5
5
TIMEFRAME_M6
6
TIMEFRAME_M10
10
TIMEFRAME_M12
12
TIMEFRAME_M15
15
TIMEFRAME_M20
20
TIMEFRAME_M30
30
TIMEFRAME_H1
16385
TIMEFRAME_H2
16386
TIMEFRAME_H3
16387
TIMEFRAME_H4
16388
TIMEFRAME_H6
16390
TIMEFRAME_H8
16392
TIMEFRAME_H12
16396
TIMEFRAME_D1
16408
TIMEFRAME_W1
32769
TIMEFRAME_MN1
49153

Order types

ORDER_TYPE_…#

Order types, the values of ENUM_ORDER_TYPE.

NameValue
ORDER_TYPE_BUY
0
ORDER_TYPE_SELL
1
ORDER_TYPE_BUY_LIMIT
2
ORDER_TYPE_SELL_LIMIT
3
ORDER_TYPE_BUY_STOP
4
ORDER_TYPE_SELL_STOP
5
ORDER_TYPE_BUY_STOP_LIMIT
6
ORDER_TYPE_SELL_STOP_LIMIT
7
ORDER_TYPE_CLOSE_BY
8

Order states

ORDER_STATE_…#

Order states, the values of ENUM_ORDER_STATE.

NameValue
ORDER_STATE_STARTED
0
ORDER_STATE_PLACED
1
ORDER_STATE_CANCELED
2
ORDER_STATE_PARTIAL
3
ORDER_STATE_FILLED
4
ORDER_STATE_REJECTED
5
ORDER_STATE_EXPIRED
6
ORDER_STATE_REQUEST_ADD
7
ORDER_STATE_REQUEST_MODIFY
8
ORDER_STATE_REQUEST_CANCEL
9

Filling modes

ORDER_FILLING_…#

Order filling modes, the values of ENUM_ORDER_TYPE_FILLING.

NameValue
ORDER_FILLING_FOK
0
ORDER_FILLING_IOC
1
ORDER_FILLING_RETURN
2
ORDER_FILLING_BOC
3

Order lifetimes

ORDER_TIME_…#

Order time types, the values of ENUM_ORDER_TYPE_TIME.

NameValue
ORDER_TIME_GTC
0
ORDER_TIME_DAY
1
ORDER_TIME_SPECIFIED
2
ORDER_TIME_SPECIFIED_DAY
3

Order reasons

ORDER_REASON_…#

Why the terminal created an order, the values of ENUM_ORDER_REASON.

NameValue
ORDER_REASON_CLIENT
0
ORDER_REASON_MOBILE
1
ORDER_REASON_WEB
2
ORDER_REASON_EXPERT
3
ORDER_REASON_SL
4
ORDER_REASON_TP
5
ORDER_REASON_SO
6

Trade actions

TRADE_ACTION_…#

Trade request actions, the values of ENUM_TRADE_REQUEST_ACTIONS.

NameValue
TRADE_ACTION_DEAL
1
TRADE_ACTION_PENDING
5
TRADE_ACTION_SLTP
6
TRADE_ACTION_MODIFY
7
TRADE_ACTION_REMOVE
8
TRADE_ACTION_CLOSE_BY
10

Position types

POSITION_TYPE_…#

Position types, the values of ENUM_POSITION_TYPE.

NameValue
POSITION_TYPE_BUY
0
POSITION_TYPE_SELL
1

Position reasons

POSITION_REASON_…#

Why the terminal opened a position, the values of ENUM_POSITION_REASON.

NameValue
POSITION_REASON_CLIENT
0
POSITION_REASON_MOBILE
1
POSITION_REASON_WEB
2
POSITION_REASON_EXPERT
3

Deal types

DEAL_TYPE_…#

Deal types, the values of ENUM_DEAL_TYPE.

NameValue
DEAL_TYPE_BUY
0
DEAL_TYPE_SELL
1
DEAL_TYPE_BALANCE
2
DEAL_TYPE_CREDIT
3
DEAL_TYPE_CHARGE
4
DEAL_TYPE_CORRECTION
5
DEAL_TYPE_BONUS
6
DEAL_TYPE_COMMISSION
7
DEAL_TYPE_COMMISSION_DAILY
8
DEAL_TYPE_COMMISSION_MONTHLY
9
DEAL_TYPE_COMMISSION_AGENT_DAILY
10
DEAL_TYPE_COMMISSION_AGENT_MONTHLY
11
DEAL_TYPE_INTEREST
12
DEAL_TYPE_BUY_CANCELED
13
DEAL_TYPE_SELL_CANCELED
14

Deal kinds

DEAL_…#

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

NameValue
DEAL_DIVIDEND
15
DEAL_DIVIDEND_FRANKED
16
DEAL_TAX
17

Deal entries

DEAL_ENTRY_…#

How a deal changed the position, the values of ENUM_DEAL_ENTRY.

NameValue
DEAL_ENTRY_IN
0
DEAL_ENTRY_OUT
1
DEAL_ENTRY_INOUT
2
DEAL_ENTRY_OUT_BY
3

Deal reasons

DEAL_REASON_…#

Why the terminal made a deal, the values of ENUM_DEAL_REASON.

NameValue
DEAL_REASON_CLIENT
0
DEAL_REASON_MOBILE
1
DEAL_REASON_WEB
2
DEAL_REASON_EXPERT
3
DEAL_REASON_SL
4
DEAL_REASON_TP
5
DEAL_REASON_SO
6
DEAL_REASON_ROLLOVER
7
DEAL_REASON_VMARGIN
8
DEAL_REASON_SPLIT
9

Trade result codes

TRADE_RETCODE_…#

Result codes the trade server returns in retcode.

NameValue
TRADE_RETCODE_REQUOTE
10004
TRADE_RETCODE_REJECT
10006
TRADE_RETCODE_CANCEL
10007
TRADE_RETCODE_PLACED
10008
TRADE_RETCODE_DONE
10009
TRADE_RETCODE_DONE_PARTIAL
10010
TRADE_RETCODE_ERROR
10011
TRADE_RETCODE_TIMEOUT
10012
TRADE_RETCODE_INVALID
10013
TRADE_RETCODE_INVALID_VOLUME
10014
TRADE_RETCODE_INVALID_PRICE
10015
TRADE_RETCODE_INVALID_STOPS
10016
TRADE_RETCODE_TRADE_DISABLED
10017
TRADE_RETCODE_MARKET_CLOSED
10018
TRADE_RETCODE_NO_MONEY
10019
TRADE_RETCODE_PRICE_CHANGED
10020
TRADE_RETCODE_PRICE_OFF
10021
TRADE_RETCODE_INVALID_EXPIRATION
10022
TRADE_RETCODE_ORDER_CHANGED
10023
TRADE_RETCODE_TOO_MANY_REQUESTS
10024
TRADE_RETCODE_NO_CHANGES
10025
TRADE_RETCODE_SERVER_DISABLES_AT
10026
TRADE_RETCODE_CLIENT_DISABLES_AT
10027
TRADE_RETCODE_LOCKED
10028
TRADE_RETCODE_FROZEN
10029
TRADE_RETCODE_INVALID_FILL
10030
TRADE_RETCODE_CONNECTION
10031
TRADE_RETCODE_ONLY_REAL
10032
TRADE_RETCODE_LIMIT_ORDERS
10033
TRADE_RETCODE_LIMIT_VOLUME
10034
TRADE_RETCODE_INVALID_ORDER
10035
TRADE_RETCODE_POSITION_CLOSED
10036
TRADE_RETCODE_INVALID_CLOSE_VOLUME
10038
TRADE_RETCODE_CLOSE_ORDER_EXIST
10039
TRADE_RETCODE_LIMIT_POSITIONS
10040
TRADE_RETCODE_REJECT_CANCEL
10041
TRADE_RETCODE_LONG_ONLY
10042
TRADE_RETCODE_SHORT_ONLY
10043
TRADE_RETCODE_CLOSE_ONLY
10044
TRADE_RETCODE_FIFO_CLOSE
10045
TRADE_RETCODE_HEDGE_PROHIBITED
10046

Book levels

BOOK_TYPE_…#

The side of a market depth level, the values of ENUM_BOOK_TYPE.

NameValue
BOOK_TYPE_SELL
0
BOOK_TYPE_BUY
1
BOOK_TYPE_SELL_MARKET
2
BOOK_TYPE_BUY_MARKET
3

Tick filters

COPY_TICKS_…#

What CopyTicksFrom and CopyTicksRange return, the values of ENUM_COPY_TICKS.

NameValue
COPY_TICKS_ALL
-1
COPY_TICKS_INFO
1
COPY_TICKS_TRADE
2

Tick flags

TICK_FLAG_…#

What a tick carries, as a bit mask in flags.

NameValue
TICK_FLAG_BID
2
TICK_FLAG_ASK
4
TICK_FLAG_LAST
8
TICK_FLAG_VOLUME
16
TICK_FLAG_BUY
32
TICK_FLAG_SELL
64

Symbol trade modes

SYMBOL_TRADE_MODE_…#

What trading a symbol allows, the values of ENUM_SYMBOL_TRADE_MODE.

NameValue
SYMBOL_TRADE_MODE_DISABLED
0
SYMBOL_TRADE_MODE_LONGONLY
1
SYMBOL_TRADE_MODE_SHORTONLY
2
SYMBOL_TRADE_MODE_CLOSEONLY
3
SYMBOL_TRADE_MODE_FULL
4

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_FOREX
0
SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE
1
SYMBOL_CALC_MODE_FUTURES
2
SYMBOL_CALC_MODE_CFD
3
SYMBOL_CALC_MODE_CFDINDEX
4
SYMBOL_CALC_MODE_CFDLEVERAGE
5
SYMBOL_CALC_MODE_EXCH_STOCKS
32
SYMBOL_CALC_MODE_EXCH_FUTURES
33
SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS
34
SYMBOL_CALC_MODE_EXCH_BONDS
35
SYMBOL_CALC_MODE_EXCH_STOCKS_MOEX
36
SYMBOL_CALC_MODE_EXCH_BONDS_MOEX
37
SYMBOL_CALC_MODE_SERV_COLLATERAL
38

Bridge result codes

RES_…#

Result codes the bridge and this package use in LastError.

NameValue
RES_S_OK
1
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

PositionsTotal

#
func PositionsTotal(): int

The number of open positions. Returns 0 on failure.

metatrader-Positions.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
    println "EURUSD orders:", metatrader.OrdersGetSymbol("EURUSD").Len()
    println "USD orders:", metatrader.OrdersGetGroup("*USD*").Len()
    pending := metatrader.OrdersGetTicket(1001 as i64)
    if pending.Len() > 0:
        println "order 1001:", pending.Get(0).symbol, pending.Get(0).price_open
    end

    println "positions:", metatrader.PositionsTotal()
    each p in metatrader.PositionsGet():
        println p.ticket, p.symbol, p.position_type, p.volume, p.price_open, p.profit
    end
    println "EURUSD positions:", metatrader.PositionsGetSymbol("EURUSD").Len()
    println "USD positions:", metatrader.PositionsGetGroup("*USD*").Len()
    open := metatrader.PositionsGetTicket(2001 as i64)
    if open.Len() > 0:
        println "position 2001:", open.Get(0).symbol, open.Get(0).profit
    end
    ret 0
end

PositionsGet

#
func PositionsGet(): Vector<TradePosition>

All open positions.

The example for this item is shown with the ones above: metatrader-Positions.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-Positions.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-Positions.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-Positions.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

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, 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

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.

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

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

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

OrdersTotal

#
func OrdersTotal(): int

The number of active orders, as the terminal reports it. Returns 0 on failure, with LastError set.

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

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-Positions.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-Positions.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-Positions.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-Positions.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.

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

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

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 "group orders:", metatrader.HistoryOrdersGetGroup(date_from, date_to, "*USD*").Len()
    println "ticket orders:", metatrader.HistoryOrdersGetTicket(3001 as i64).Len()
    println "position orders:", metatrader.HistoryOrdersGetPosition(2001 as i64).Len()

    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

    println "group deals:", metatrader.HistoryDealsGetGroup(date_from, date_to, "*USD*").Len()
    println "ticket deals:", metatrader.HistoryDealsGetTicket(4001 as i64).Len()
    println "position deals:", metatrader.HistoryDealsGetPosition(2001 as i64).Len()

    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

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.

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

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

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