MT Accounts Management

A collection of API methods to perform mt accounts lookup / creation / amendment / removal / querying account info / querying live|historical trades

com.nj4x.node.mt_account.create(mtAccount)

WAMP procedure to add new MT Account to the system.

param mtAccount:
 MtAccount object to create. ClientId, AccountNumber, Broker and Password fields must be defined.
return:(dict) {Entity: MtAccount, Exception: object} - Entity element represents newly created MT Account or None in case of error. Exception field is populated in case of account creation error (e.g. same account exist)
Example:
@inlineCallbacks
def create(self, account):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.create` `WAMP <https://wamp-proto.org>`_ API method.

    :return: :class:`.MtAccount` - newly created MT Account or *None* in case of error.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.create", account)
    #
    if res.get("Exception") is None:
        return res.get("Entity")
    raise Exception(res['Exception']["Message"])
def ct_demo_create_mt_acct(client_id, broker="demo1-amsterdam.fxpro.com", acct_number=6796186, passwd="dpkk4hg"):
    # -------------------------------------------------
    # Create MT4 account
    # -------------------------------------------------
    acct = yield mt_accounts_service.create({
        'ClientId': client_id,
        'Broker': broker,
        'AccountNumber': acct_number,
        'Password': passwd
    })
    print("Created Account: {}".format(acct))
    # -------------------------------------------------
    # Wait for account to be verified
    # -------------------------------------------------
    acct = yield mt_accounts_service.find_by_id(acct["Id"])
    while not acct["VerificationInfo"]["IsVerified"]:
        print("Waiting for account verification: {}".format(acct["VerificationInfo"]))
        yield sleep(2)
        acct = yield mt_accounts_service.find_by_id(acct["Id"])
    #
    print("Account verified: {}".format(acct["VerificationInfo"]))
    if acct["VerificationInfo"]["VerificationStatus"] != 2:
        raise Exception("Account not valid: {}".format(acct["VerificationInfo"]["VerificationMessage"]))
    return acct
com.nj4x.node.mt_account.update(mtAccount)

WAMP procedure to amend MT Account.

Parameters:mtAccountMtAccount object to update Broker / AccountNumber / Password attributes of. Id and Version fields must be defined.
Returns:(dict) {Entity: MtAccount, Exception: object} - Entity element represents updated MT Account or None in case of error. Exception field is populated in case of account amendment error (e.g. same account exist)
Example:
@inlineCallbacks
def update(self, account):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.update` `WAMP <https://wamp-proto.org>`_ API method.

    :return: :class:`.MtAccount` - updated MT Account or *None* in case of error.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.update", account)
    #
    if res.get("Exception") is None:
        return res.get("Entity")
    raise Exception(res['Exception']["Message"])
# -------------------------------------------------
# Update MT4 account setup (Broker/AccountNumber/Password)
# -------------------------------------------------
acct = yield mt_accounts_service.find_by_id(acct_id)
acct['Password'] = 'dpkk4hg'  # password update
updated_acct = yield mt_accounts_service.update(acct)
print("Updated Account: {}".format(updated_acct))
com.nj4x.node.mt_account.delete(account)

WAMP procedure to remove MT Account from the system.

Parameters:accountMtAccount object to delete. Only Id field must be filled, e.g. {“Id”: 1234}
Returns:(dict) {Exception: object} - Exception field is populated in case of account deletion error
Example:
@inlineCallbacks
def delete(self, account):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.delete` `WAMP <https://wamp-proto.org>`_ API method.

    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.delete", account)
    #
    if res.get("Exception") is None:
        return
    raise Exception(res['Exception']["Message"])
# -------------------------------------------------
# Clean-up Demo accounts (lookup by ClientId)
# -------------------------------------------------
accts = yield mt_accounts_service.find_by_client_id(client_id)
for a in accts:
    try:
        yield mt_accounts_service.delete(a)
        print("Removed Account: {}".format(a))
    except Exception as e:
        print("Account delete error: {}".format(e))
com.nj4x.node.mt_account.find_by_client_id(clientId: int)

WAMP procedure to lookup MT Accounts by referenced Client ID.

param clientId:(long) External system client ID to lookup linked MT Accounts of.
return:(dict) {Entities: MtAccount [], Exception: object} - Entities list will be empty in case no MT Accounts are found. Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def find_by_client_id(self, client_id: int):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.find_by_client_id` `WAMP <https://wamp-proto.org>`_ API method.

    :return: list of :class:`.MtAccount` objects (if found) or *None* in case no MT account referencing a specified client exist.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.find_by_client_id", client_id)
    #
    if res.get("Exception") is None:
        return res.get("Entities")
    raise Exception(res['Exception']["Message"])
def ct_demo_find_mt_acct(client_id, acct_no=6796186):
    acct = None
    accts = yield mt_accounts_service.find_by_client_id(client_id)
    for a in accts:
        if a['AccountNumber'] == acct_no:
            acct = a
            break
    print("Found Account: {}".format(acct))
    if acct is None:
        raise Exception("Demo account not found")
    return acct
com.nj4x.node.mt_account.find_by_broker_and_account(broker: str, accountNumber: int)

WAMP procedure to lookup MT Account by its Account number and Broker address.

param broker:(str) MetaTrader Broker’s address (or SRV file name)
param accountNumber:
 (long) MetaTrader Account’s Number
return:(dict) {Entity: MtAccount, Exception: object} - Entity element will be None in case MT Account not found. Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def find_by_broker_and_account(self, broker: str, account_number: int):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.find_by_broker_and_account` `WAMP <https://wamp-proto.org>`_ API method.

    :return: :class:`.MtAccount` dictionary object (if found) or *None* in case MT account does not exist.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.find_by_broker_and_account", broker, account_number)
    #
    if res.get("Exception") is None:
        return res.get("Entity")
    raise Exception(res['Exception']["Message"])
com.nj4x.node.mt_account.find_all()

WAMP procedure to get a list of all configured MT Accounts.

return:(dict) {Entities: MtAccount [], Exception: object} - Entities list will be empty in case no MT Accounts are found. Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def find_all(self):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.find_all` `WAMP <https://wamp-proto.org>`_ API method.

    :return: list of :class:`.MtAccount` objects (if found) or *None* in case no MT accounts exist.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.find_all")
    #
    if res.get("Exception") is None:
        return res.get("Entities")
    raise Exception(res['Exception']["Message"])
com.nj4x.node.mt_account.find_by_id(mtAccountId: int)

WAMP procedure to lookup MT Account by its ID.

param mtAccountId:
 (long) ID of the account to lookup.
return:(dict) {Entity: MtAccount, Exception: object} - Entity element will be None in case MT Account with requested ID is not found. Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def find_by_id(self, mt_account_id):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.find_by_id` `WAMP <https://wamp-proto.org>`_ API method.

    :return: :class:`.MtAccount` dictionary object (if found) or *None* in case MT account with such ID does not exist.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.find_by_id", mt_account_id)
    #
    if res.get("Exception") is None:
        return res.get("Entity")
    raise Exception(res['Exception']["Message"])
com.nj4x.node.mt_account.get_symbols(mtAccount)

WAMP procedure to get a list of MT Account’s trading instruments (symbols).

param mtAccount:
 MtAccount object to retrieve symbols for.
return:(dict) {Result: Symbol [], Exception: object} - Result list of trading instruments Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def get_symbols(self, mt_account):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.get_symbols` `WAMP <https://wamp-proto.org>`_ API method.

    :return: list of :class:`.Symbol` - account's trading instruments.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.get_symbols", mt_account)
    #
    if res.get("Exception") is None:
        return res.get("Result")
    raise Exception(res['Exception']["Message"])
com.nj4x.node.mt_account.get_info(mtAccount)

WAMP procedure to lookup detailed MT Account information.

param mtAccount:
 MtAccount object to retrieve information for.
return:(dict) {Result: MtAccountInfo, Exception: object} - Result element will be None in case MT Account with requested ID is not found. Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def get_info(self, mt_account):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.get_info` `WAMP <https://wamp-proto.org>`_ API method.

    :return: :class:`.MtAccountInfo` - detailed account's information.
    :raises: *Exception* in case of any server error.
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.get_info", mt_account)
    #
    if res.get("Exception") is None:
        return res.get("Result")
    raise Exception(res['Exception']["Message"])
com.nj4x.node.mt_account.get_paged_history(paging, mtAccount, filter, sort)

WAMP procedure to get MT Account historical trades.

param paging:dict {‘PageSize’: int, ‘PageNo’: int} - PageSize - number of rows per page, PageNo - requested page number (starting from 0)
param mtAccount:
 MtAccount object to retrieve historical trades of.
param filter:dict - filtering predicate, e.g. {‘TradeOperation’: {‘$in’: [“OP_SELL”, “OP_BUY”, “OP_DEPOSIT”]}
param sort:dict - sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively., e.g. {‘CloseTime’: 1, ‘Ticket’: -1}
return:(dict) {‘Result’: (dict) {‘PageRows’: list of HistoricalTrade, ‘PageNo’: int, ‘TotalPages’: int, ‘TotalRows’: int}, ‘Exception’: object} - Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def get_paged_history(self, mt_account, paging_req, filters=None, sorts=None):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.get_paged_history` `WAMP <https://wamp-proto.org>`_ API method.

    :return:    *(dict)* {'PageRows': *list* of :class:`.HistoricalTrade`, 'PageNo': int, 'TotalPages': int, 'TotalRows': int}
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.get_paged_history",
                                   **{'mtAccount': {"Id": mt_account["Id"]}, "paging": paging_req,
                                      'filter': filters, 'sort': sorts})
    #
    if res.get("Exception") is None:
        return res.get("Result")
    raise Exception(res['Exception']["Message"])
com.nj4x.node.mt_account.get_paged_active_trades(mtAccount, paging, filter, sort)

WAMP procedure to get active MT Account’s trades.

param mtAccount:
 MtAccount object to retrieve active trades of.
param paging:dict {‘PageSize’: int, ‘PageNo’: int} - PageSize - number of rows per page, PageNo - requested page number (starting from 0)
param filter:dict - filtering predicate, e.g. {‘TradeOperation’: {‘$in’: [“OP_SELL”, “OP_BUY”]}
param sort:dict - sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively., e.g. {‘CloseTime’: 1, ‘Ticket’: -1}
return:(dict) {‘Result’: (dict) {‘PageRows’: list of HistoricalTrade, ‘PageNo’: int, ‘TotalPages’: int, ‘TotalRows’: int}, ‘Exception’: object} - Exception field is populated in case of any system error.
Example:
@inlineCallbacks
def get_paged_active_trades(self, mt_account, paging_req, filters=None, sorts=None):
    """
    This function is a wrapper for :func:`~com.nj4x.node.mt_account.get_paged_active_trades` `WAMP <https://wamp-proto.org>`_ API method.

    :return:    *(dict)* {'PageRows': *list* of :class:`.HistoricalTrade`, 'PageNo': int, 'TotalPages': int, 'TotalRows': int}
    """
    self._check_session()
    #
    res = yield self._session.call(u"com.nj4x.node.mt_account.get_paged_active_trades",
                                   **{'mtAccount': {"Id": mt_account["Id"]}, "paging": paging_req,
                                      'filter': filters, 'sort': sorts})
    #
    if res.get("Exception") is None:
        return res.get("Result")
    raise Exception(res['Exception']["Message"])
class com.nj4x.node.mt_account.MtAccount(client_id: int, broker: str, account_no: int, password: str)

A class used to represent Meta Trader’s Account

Id : long
Copy trading system database primary key for the MT Account
ClientId: long
External CRM system’s client ID
MtGroupRef: int
Copy trading system internal MT Accounts Group ID
Version: long
Entity’s version number. It is incremented on each update
AccountNumber: int
MetaTrader Account’s Number
Broker: str
MetaTrader Broker’s address (or SRV file name)
Password: str
MetaTrader Account’s Password
VerificationInfo: {
IsVerified: bool
True - in case MT Account’s credentials have been verified and connection to a broker successfully established
VerificationStatus: int
0=Unknown, 1=Pending, 2=ValidAccount, 3=InvalidAccount, 4=Error
VerificationMessage: str
Error message
VerificationRetryCount: int
Number of performed verification checks
}
System defined MT Account’s status
class com.nj4x.node.mt_account.MtAccountInfo

A class used to represent detailed trading account information.

Balance: float
Account balance in the deposit currency
Company: str
Name of a company that serves the account, e.g. ‘FxPro Financial Services Ltd’
Credit: float
Account credit in the deposit currency
Currency: str
Account currency
Equity: float
Account equity in the deposit currency
FreeMargin: float
Free margin of an account in the deposit currency
IsTradeAllowed: bool
‘true’ if trade is allowed for the current account
IsTradeExpert: bool
‘true’ if trade is allowed for an Expert Advisor
Leverage: int
Account leverage
LimitOrders: int
Maximum allowed number of active pending orders (0-unlimited)
Login: long
Account number
Margin: float
Account margin used in the deposit currency
MarginLevel: float
Account margin level in percents
MarginSoCall: float
Margin call level. Depending on the set ACCOUNT_MARGIN_SO_MODE is expressed in percents or in the deposit currency
MarginSoLevel: float
Margin stop out level. Depending on the set ACCOUNT_MARGIN_SO_MODE is expressed in percents or in the deposit currency
Name: str
Client name
Profit: float
Current profit of an account in the deposit currency
Server: str
Trade server name, e.g. ‘FxPro.com-Demo01’
StopOutMode: int
Mode for setting the minimal allowed margin: Percent=0, Money=1
TradeMode: int
Account trade mode: Demo=0, Contest=1, Real=2
class com.nj4x.node.mt_account.Symbol

A class used to represent trading instrument (a symbol)

Id: str
Symbol identifier, e.g. ‘EURUSD’
Ask: float
Ask - best buy offer
AskHigh: float
Maximal Ask of the day
AskLow: float
Minimal Ask of the day
BaseCurrency: str
Basic currency of a symbol, e.g. ‘USD’
Bid: float
Bid - best sell offer
BidHigh: float
Maximal Bid of the day
BidLow: float
Minimal Bid of the day
ContractPriceCalculationMode: int
Contract price calculation mode: Forex=0, Futures=1, CFD=2, CFDIndex=3, CFDLeverage=4, ExchStocks=5, ExchFutures=6, ExchFuturesForts=7
Description: str
Symbol’s description
Digits: int
Digits after a decimal point
ExpirationModes: list
allowed order expiration modes, *int*s - GTC=0, Day=1, Specified=2, SpecifiedDay=3
ExpirationTime: str
Date of the symbol trade end (usually used for futures) - format: ‘1970-01-01T00:00:00Z’
FillingModes: list
allowed order filling modes, *int*s - FillOrKill=0, ImmediateOrCancel=1, Return=2
FreezeLevel: int
Distance to freeze trade operations in points
InitialMargin: float
Initial margin means the amount in the margin currency required for opening an order with the volume of one lot. It is used for checking a client’s assets when he or she enters the market.
IsFloatingSpread: bool
Indication of a floating spread
IsSelected: bool
true if symbol is selected in Market Watch
Last: float
Price of the last deal
LastHigh: float
Maximal Last of the day
LastLow: float
Minimal Last of the day
LimitMargin: float
Rate of margin charging on limit orders
LimitVolume: float
Maximum allowed aggregate volume of an opened and pending orders in one direction (buy or sell) for the symbol
LongMargin: float
Rate of margin charging on buy orders
LongSwap: float
Buy order swap value
MaintenanceMargin: float
The maintenance margin for a symbol.
MarginCurrency: str
Margin currency of a symbol
MaxVolume: float
Maximal volume for a deal
MinVolume: float
Minimal volume for a deal
OrderModes: list
allowed order types: list of *int*s - Market=0, Limit=1, Stop=2, StopLimit=3, SL=4, TP=5
Path: str
Path in the symbol tree, e.g. ‘US Shares#21stFOX’
Point: float
Symbol point value
ProfitCurrency: str
Profit currency of a symbol
SessionAverageWeightedPrice: float
Average weighted price of the current session
SessionBuyOrders: int
Number of Buy orders at the moment
SessionBuyOrdersVolume: float
Current volume of Buy orders
SessionClosePrice: float
Close price of the current session
SessionDeals: int
Number of deals in the current session
SessionInterest: float
Summary open interest
SessionMaxLimitPrice: float
Maximal price of the current session
SessionMinLimitPrice: float
Minimal price of the current session
SessionOpenPrice: float
Open price of the current session
SessionSellOrders: int
Number of Sell orders at the moment
SessionSellOrdersVolume: float
Current volume of Sell orders
SessionSettlementPrice: float
Settlement price of the current session
SessionTurnover: float
Summary turnover of the current session
SessionVolume: float
Summary volume of current session deals
ShortMargin: float
Rate of margin charging on sell orders
ShortSwap: float
Sell order swap value
Spread: int
Spread value in points
StartTime: str
Date of the symbol trade beginning (usually used for futures, format: ‘1970-01-01T00:00:00Z’)
StepVolume: float
Minimal volume change step for deal execution
StopLimitMargin: float
Rate of margin charging on stop limit orders
StopMargin: float
Rate of margin charging on stop orders
StopsLevel: int
Minimal indention in points from the current close price to place Stop orders
SwapMode: int
Swap calculation model
SwapRollover3Days: int
Weekday to charge 3 days swap rollover
Time: str
Time of the last quote (format: ‘1970-01-01T00:00:00Z’)
TradeContractSize: float
Trade contract size
TradeExecutionMode: int
Deal execution mode: Request=0, Instant=1, Market=2, Exchange=3
TradeMode: int
Order execution type: Disabled=0, LongOnly=1, ShortOnly=2, CloseOnly=3, Full=4
TradeTickSize: float
minimal price change
TradeTickValue: float
Value of calculated tick price for a profitable order
TradeTickValueLoss: float
Calculated tick price for a losing order
TradeTickValueProfit: float
Calculated tick price for a profitable order
Volume: long
Volume of the last deal
VolumeHigh: long
Maximal day volume
VolumeLow: long
Minimal day volume
class com.nj4x.node.mt_account.HistoricalTrade

A class used to represent active or historical trade (order)

Id: long
primary key
MtAccountRef: long
Reference to the MTAccount (mt account’s ID)
Ticket: long
Order’s ticket number.
TradeOperation: str
Orders operation type: OP_BUY (0), OP_SELL (1), OP_BUYLIMIT (2), OP_SELLLIMIT (3), OP_BUYSTOP (4), OP_SELLSTOP (5), OP_DEPOSIT (6)
OpenTime: str
Order’s open date. The server time order was opened at, e.g. ‘2018-11-09T15:57:53Z’
OpenTimeUtc: str
Order’s open date. The UTC time order was opened at, e.g. ‘2018-11-09T13:57:53Z’
CloseTime: str
Order’s close date. The server time order was closed at (format: ‘1970-01-01T00:00:00Z’)
CloseTimeUtc: str
Order’s close date. The UTC time order was closed at (format: ‘1970-01-01T00:00:00Z’)
Magic: long
User-defined magic number.
Lots: float
Amount of lots for the order.
OpenPrice: float
The price order was opened at.
ClosePrice: float
The price order was closed at.
StopLoss: float
Stop loss level.
TakeProfit: float
Take profit level.
Profit: float
Order’s net profit value (without swaps or commissions). For open positions, it is the current unrealized profit. For closed orders, it is the fixed profit.
Commission: float
Calculated commission value for the order.
Swap: float
Swap value for the order.
Symbol: str
Order’s symbol, e.g. ‘EURUSD’
SymbolDigits: int
number of digits after comma for the symbol
Comment: str
User-defined order comments.
Expiration: str
Pending oder’s expiration date (format: ‘1970-01-01T00:00:00Z’)
TradeDuration: int
trade duration in seconds
NetProfit: float
Profit + Commission + Swap