Get All Accounts
Overview
The "Get All Accounts" feature is a valuable tool for traders and brokers, allowing them to access a comprehensive list of all accounts associated with a particular login. With this information at their fingertips, users can efficiently manage multiple accounts from a single login, streamlining their trading operations and gaining a comprehensive view of their financial portfolios. This page provides essential insights on how to navigate and utilize this functionality to its fullest potential.
How to Get a List of All Accounts
In this article you will learn how to use the API to get a list of accounts. You need to follow these steps:
-
Login (see the tutorial here)
-
Listen for account changes
-
Subscribe to account changes
-
Get and print accounts
-
Print account properties
Step 1: Login
Follow the steps in the login tutorial here.
Step 2: Listen for Account Changes
The first step is to create an account change listener. This is a class that will be called whenever an account is added, removed, or updated. You can use the AccountInfo interface to access the account details.
Below, you can see some example code to create an account change listener:
class AccountChangeListener implements FXConnectLite.IAccountChangeListener {
onChange(accountInfo: FXConnectLite.AccountInfo): void {
}
onAdd(accountInfo: FXConnectLite.AccountInfo): void {
}
onRefresh(): void {
}
onDelete(accountInfo: FXConnectLite.AccountInfo): void {
}
}
class AccountChangeListener {
constructor(session) {
this.session = session;
}
onChange(accountInfo) {
}
onAdd(accountInfo) {
}
onDelete(accountInfo) {
}
onRefresh() {
}
}
In order to keep our code modular and easy to manage, we will be creating the file accounts\account-change-listener.js which will contain our listener.
class AccountChangeListener {
constructor(accountsWorker, session) {
this.accountWorker = accountsWorker;
this.session = session;
}
onChange(accountInfo) {
}
onAdd(accountInfo) {
}
onDelete(accountInfo) {
this.accountWorker.removeDetails();
this.accountWorker.removeAccount(accountInfo.getId());
}
onRefresh() {
}
}
accounts\account-worker.js that will retreive the account data for each item which will then be passed to the TableBuilder class to display.
class AccountsWorker {
constructor(session) {
this.session = session;
this.tableBuilder = new AccountTableBuilder();
}
#getAccountDetails(account) {
return new Map([
['Balance', account.getBalance()],
['Base currency', account.getBaseCurrency()],
['Order amount limit', account.getOrderAmountLimit()],
['ATP Id', account.getATPId()],
['Size of one lot', account.getBaseUnitSize()],
['Last occurrence of a Margin Call', account.getLastMarginCallDate()],
['ID of an account leverage profile', account.getLeverageProfileId()],
['Equity balance at the beginning of the trading day', account.getM2MEquity()],
['Rollover maintenance flag', account.getMaintenanceFlag()],
['Type of position maintenance', account.getMaintenanceType()],
['ID of the funds manager account', account.getManagerAccountId()],
['The limitation state of the account', account.getMarginCallFlag()],
['The amount of transactions during the day', account.getNonTradeEquity()]
]);
}
removeAccount(accountId) {
document.getElementById('item-' + accountId).remove();
}
showAccountDetails(account) {
let accountId = account.getAccountId();
let accountDetails = this.#getAccountDetails(account);
this.tableBuilder.renderAccountDetailsSubtable(accountId, accountDetails);
}
showAccounts(accountsManager) {
let accountsInfo = accountsManager.getAccountsInfo();
this.tableBuilder.renderAccountTable(accountsManager, this, accountsInfo);
}
}
Next, we need to load the account worker when the page has finished loading, so we add this to our index.js file.
const sessionFactory = FXConnectLite.FXConnectLiteSessionFactory;
const LoggerFactory = FXConnectLite.LoggerFactory;
document.addEventListener('DOMContentLoaded', () => {
let session = sessionFactory.create('GetAccountsSample');
session.setLogger(LoggerFactory.createLogger(LoggerFactory.LEVEL_DEBUG));
let accountManager = session.getAccountsManager();
let accountWorker = new AccountsWorker(session);
session.subscribeConnectionStatusChange(new ConnectionStatusChangeListener(accountWorker, session, accountManager));
accountManager.subscribeAccountChange(new AccountChangeListener(accountWorker, session));
bindConnectionRelatedEvents(session);
});
See also AccountInfo
Step 3: Subscribe to Account Changes
The next step is to get an instance of the account manager and subscribe to account changes. The account manager is an object that provides methods for managing accounts. You can use the IAccountsManager interface to access its methods.
Below, you can see some example code to get an instance of the account manager and subscribe to account changes using the account change listener:
let accountChangeListener = new AccountChangeListener(); // create an account change listener.
session.getAccountsManager().subscribeAccountChange(accountChangeListener); // subscribe
let accountChangeListener = new AccountChangeListener(session);
accountManager.subscribeAccountChange(accountChangeListener);
We need to add changes to our index.js file to subscribe to the account changes.
const sessionFactory = FXConnectLite.FXConnectLiteSessionFactory;
const LoggerFactory = FXConnectLite.LoggerFactory;
document.addEventListener('DOMContentLoaded', () => {
let session = sessionFactory.create('GetAccountsSample');
session.setLogger(LoggerFactory.createLogger(LoggerFactory.LEVEL_DEBUG));
let accountManager = session.getAccountsManager();
let accountWorker = new AccountsWorker(session);
session.subscribeConnectionStatusChange(new ConnectionStatusChangeListener(accountWorker, session, accountManager));
accountManager.subscribeAccountChange(new AccountChangeListener(accountWorker, session));
bindConnectionRelatedEvents(session);
});
See also IAccountsManager
Step 4: Get and Print Accounts
The fourth step is to create a function that will get and print the list of accounts.
You can use the getAccountsSnapshot method of the account manager to get a snapshot of the current accounts.
This method returns a promise that resolves with an array of AccountInfo objects.
Below, you can see some example code to create a function that will get and print the list of accounts:
private getAndPrintAccounts = async (session, application) => {
return new Promise<void>((resolve, reject) => {
application.resolveGetAccounts = resolve;
let accountsManager = session.getAccountsManager();
application.printAccountsSnapshot(accountsManager);
})
}
let accountWorker = new AccountWorker();
let callback = new GetAccountActionCallback(accountWorker);
accountManager.getAccountsSnapshot(callback);
For printing the results of the command, we have first created a file which will contain our TableBuilder class.
Follow the instruction in the Table Builder tutorial here.
We then have a second class file specific for accounts called accounts\account-table-builder.js, which takes the data returned from our request and inserts it into the structure created by the previous class.
class AccountTableBuilder {
constructor() {
this.builder = new TableBuilder();
}
#onAccountClick(id, accountManager, accountWorker) {
let callback = function () {
accountManager.getAccount({
getId: function () {
return id;
}
}, new GetAccountActionCallback(accountWorker));
};
this.builder.onRowClick(id, callback);
}
#onSubtableClick() {
this.builder.removeSubtable();
}
#renderAccountTableHeader() {
let columns = [
{ className: 'col-sm-2', value: 'ID' },
{ className: 'col-sm-5', value: 'Name' },
{ className: 'col-sm-5', value: 'Type' }
];
this.builder.createHeaderTableRow(columns);
}
#renderDataTableRow(accountsManager, accountWorker, accountInfo) {
let columns = [
{ className: 'col-sm-2', value: accountInfo.id },
{ className: 'col-sm-5', value: accountInfo.name },
{ className: 'col-sm-5', value: accountInfo.type }
];
let row = this.builder.createDataTableRow(columns);
row.onclick = () => this.#onAccountClick(accountInfo.id, accountsManager, accountWorker);
}
renderAccountDetailsSubtable(id, details) {
let columns = [];
details.forEach((k, v) => {
columns.push({ className: 'col-sm-6', value: v });
columns.push({ className: 'col-sm-6', value: k });
});
let detailsRow = this.builder.createDataSubtable(id, columns, 'row mb-3 details');
detailsRow.onclick = () => this.#onSubtableClick();
}
renderAccountTable(accountsManager, accountWorker, accountsInfo) {
this.#renderAccountTableHeader();
accountsInfo.forEach((accountInfo) => {
this.#renderDataTableRow(accountsManager, accountWorker, accountInfo);
});
this.builder.showContainer();
}
}
See also getAccountsSnapshot
And the code of callback for providing information about all accounts:
private getAccountsSnapshotCallback = new class implements FXConnectLite.IGetAccountsSnapshotCallback {
onAccountsReceived(accounts: FXConnectLite.Account[]): void {
accounts.forEach(account => {
Printer.print(`Current snapshot:`);
Application.printAccount(account);
});
application.resolveGetAccounts();
}
}();
class GetAccountActionCallback {
constructor(accountWorker) {
this.accountWorker = accountWorker;
}
onAccountsReceived(accounts) {
this.accountWorker.showAccountsDetails(accounts);
}
}
We create our callback in accounts\get-account-action-callback.js
class GetAccountActionCallback {
constructor(accountsWorker) {
this.accountWorker = accountsWorker;
}
onAccountReceived(account) {
this.accountWorker.showAccountDetails(account);
}
}
See also onAccountReceived
Step 5: Add the Method to Print Account Properties
The method to print account properties.
public static formatDate(date: any): string {
return date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);
}
public static printAccount(account: FXConnectLite.Account): void {
Printer.print(``)
Printer.print(`AccountId = ${account.getAccountId()}`)
Printer.print(`AccountName = ${account.getAccountName()}`)
Printer.print(`AccountKind = ${account.getAccountKind()}`)
Printer.print(`Base currency = ${account.getBaseCurrency()}`)
Printer.print(`Base currency precision = ${account.getBaseCurrencyPrecision()}`)
Printer.print(`ATPId = ${account.getATPId()}`)
Printer.print(`Balance = ${account.getBalance()}`)
Printer.print(`BaseUnitSize = ${account.getBaseUnitSize()}`)
Printer.print(`DayPL = ${account.getDayPL()}`)
Printer.print(`Equity = ${account.getEquity()}`)
Printer.print(`GrossPL = ${account.getGrossPL()}`)
Printer.print(`LastMarginCallDate = ${Application.formatDate(account.getLastMarginCallDate())}`)
Printer.print(`LeverageProfileId = ${account.getLeverageProfileId()}`)
Printer.print(`M2MEquity = ${account.getM2MEquity()}`)
Printer.print(`MaintenanceFlag = ${account.getMaintenanceFlag()}`)
Printer.print(`MaintenanceType = ${account.getMaintenanceType()}`)
Printer.print(`ManagerAccountId = ${account.getManagerAccountId()}`)
Printer.print(`MarginCallFlag = ${account.getMarginCallFlag()}`)
Printer.print(`NonTradeEquity = ${account.getNonTradeEquity()}`)
Printer.print(`OrderAmountLimit = ${account.getOrderAmountLimit()}`)
Printer.print(`UsableMaintenanceMargin = ${account.getUsableMaintenanceMargin()}`)
Printer.print(`UsableMaintenanceMarginPercentage = ${account.getUsableMaintenanceMarginPercentage()}`)
Printer.print(`UsableMargin = ${account.getUsableMargin()}`)
Printer.print(`UsableMarginPercentage = ${account.getUsableMarginPercentage()}`)
Printer.print(`UsedMaintenanceMargin = ${account.getUsedMaintenanceMargin()}`)
Printer.print(`UsedMargin = ${account.getUsedMargin()}`)
Printer.print(``)
}
class AccountWorker {
showAccountDetails(account) {
let accountDetails = `
AccountId = ${account.getAccountId()}
AccountName = ${account.getAccountName()}
AccountKind = ${account.getAccountKind()}
Base currency = ${account.getBaseCurrency()}
Base currency precision = ${account.getBaseCurrencyPrecision()}
ATPId = ${account.getATPId()}
Balance = ${account.getBalance()}
BaseUnitSize = ${account.getBaseUnitSize()}
DayPL = ${account.getDayPL()}
Equity = ${account.getEquity()}
GrossPL = ${account.getGrossPL()}
LastMarginCallDate = ${account.getLastMarginCallDate()}
LeverageProfileId = ${account.getLeverageProfileId()}
M2MEquity = ${account.getM2MEquity()}
MaintenanceFlag = ${account.getMaintenanceFlag()}
MaintenanceType = ${account.getMaintenanceType()}
ManagerAccountId = ${account.getManagerAccountId()}
MarginCallFlag = ${account.getMarginCallFlag()}
NonTradeEquity = ${account.getNonTradeEquity()}
OrderAmountLimit = ${account.getOrderAmountLimit()}
UsableMaintenanceMargin = ${account.getUsableMaintenanceMargin()}
UsableMaintenanceMarginPercentage = ${account.getUsableMaintenanceMarginPercentage()}
UsableMargin = ${account.getUsableMargin()}
UsableMarginPercentage = ${account.getUsableMarginPercentage()}
UsedMaintenanceMargin = ${account.getUsedMaintenanceMargin()}
UsedMargin = ${account.getUsedMargin()}
`;
console.log('Account details:');
console.log(accountDetails);
}
showAccountsDetails(accounts) {
accounts.forEach((account) => {
this.showAccountDetails(account);
});
}
}
We have already performed this task in our AccountWorker class with the .showAccountDetails() method.
However one final thing we need to do is to include all of our js files in our index.html file.
<script src="fclite/forex-connect-lite.js"></script>
<script src="common/table-builder.js"></script>
<script src="connection_management/connection-management.js"></script>
<script src="connection_management/connection-status-change-listener.js"></script>
<script src="connection_management/login-callback.js"></script>
<script src="accounts/account-change-listener.js"></script>
<script src="accounts/account-table-builder.js"></script>
<script src="accounts/account-worker.js"></script>
<script src="accounts/get-account-action-callback.js"></script>
<script src="index.js"></script>
See also Account
If you require basic information about all accounts belonging to a particular user, the method getAccountsInfo can assist you.
When you have a list of all account, you can:
- Get available instruments.
- Subscribe and Unsubscribe to instruments.
- Get price updates for an instrument.
- Get historical prices for an instrument.
- Create a market order.
- Create an entry order.
- Get open positions.
Conclusion
You have learned how to use the API to get a list of accounts. You have created an account change listener, subscribed to account changes, and learned how to get and print accounts. You have also learned about the AccountInfo class, the IAccountsManager interface, and how to use them to manage accounts. You can now use this knowledge to build your own applications that work with accounts in FCLite.
Download the sample Node TypeScript, Node JavaScript, Javascript.
| Table of Contents | |
|---|---|
| Accounts API Commands used to get account history information |
|
| Get All Accounts The article teaches how to get a list of all accounts. |
|
| Refresh Account Profile Data The article teaches how to refresh an accounts profile data. |