Skip to content

Get Subscribed Instruments

Overview

The "Get a List of Subscribed Instruments" method is a valuable one for traders to access a comprehensive list of instruments they are subscribed to. It allows users to effortlessly retrieve information about the assets they are actively tracking or trading, whether it's currency pairs, stocks, indices, or any other tradable instruments.

How to get a list of subscribed instruments

In this article you will learn how to use the API to get a list of subscribed instruments.

To get a list of subscribed instruments, you need to follow these steps:

  1. Login (see the tutorial here)

  2. Create an instance of the instruments manager.

  3. Get a list of subscribed instruments.

  4. Printing the results in a readable format.

  1. Login (see the tutorial here)

  2. Create an instance of the instruments manager.

  3. Get a list of subscribed instruments.

  4. Printing the results in a readable format.

  1. Login (see the tutorial here)

  2. Create an instance of the instruments manager..

  3. Get a list of subscribed instruments.

  4. Printing the results in a readable format.

  5. Updating the html to include our new JavaScript files.

  6. The main JavaScript file.

Step 1: Login

Follow the steps in the login tutorial here

Step 2: Create an instance of the instrumentsManager

The first step is to create an instance of the IInstrumentsManager. This is an object that provides methods for managing instruments. You can use the IInstrumentsManager interface to access its methods and properties.

Below you can see some example code to create an instance of the instrumentsManager:

Create an instance of the instrumentsManager

session.getInstrumentsManager().refresh(); // refresh it before using it to make sure it contains the latest info.
let instrumentsManager = session.getInstrumentsManager();
let instrumentsManager = session.getInstrumentsManager();
await refresh(instrumentsManager);

In our index.js file, we create an instance of the instrumentManager when the web page has completed loading, However we also need to create a listener for updates to the instruments. For this we create the file instruments\instrument-state-listener.js

class InstrumentStateListener {
    constructor(instrumentsManager, instrumentsWorker) {
        this.instrumentsManager = instrumentsManager;
        this.instrumentsWorker = instrumentsWorker;
    }

    onStateChange(state) {
        this.instrumentsWorker.updateState(state);
        if (!state.isLoaded()) 
            return;

        let instruments = this.instrumentsManager.getSubscribedInstruments();
        this.instrumentsWorker.showInstruments(instruments);
    }
}
Now that we have the listener, we can subscribe to it to listen for changes. We do this in our index.js file
session.getInstrumentsManager().subscribeStateChange(new instrumentsStateListener());

For more information about the IInstrumentsManager interface, see the API reference.

Step 3: Get a list of subscribed instruments

The next step is to get a list of instruments that you have subscribed to. Subscribing to an instrument means that you will receive updates on its data, such as its price, volume, or spread. You can use the getSubscribedInstruments() method of the instruments manager to get a list of subscribed instruments. This method returns an array of instrument symbols.

Below, you can see some example code to get a list of subscribed instruments:

Obtain a list of instruments

let subscribedInstruments = instrumentsManager.getSubscribedInstruments();
let instruments = instrumentsManager.getSubscribedInstruments();

This we do in our instruments\instrument-state-listener.js file.

let instruments = this.instrumentsManager.getSubscribedInstruments();

Step 4: Printing the results in a readable format

For printing the results of the command, we have first created a common\table-builder.js file which will contain our table builder class. This class will be used in all of our samples.

class InstrumentsPrinter{

    private instrumentsManager: FXConnectLite.IInstrumentsManager;
    private tradingSettingsProvider: FXConnectLite.ITradingSettingsProvider;
    private accountsManager: FXConnectLite.IAccountsManager;
    private offersManager: FXConnectLite.IOffersManager;
    private marginProvider: FXConnectLite.IMarginProvider;
    private accountCommissionsManager : FXConnectLite.IAccountCommissionsManager;

    public constructor(instrumentManager: FXConnectLite.IInstrumentsManager, session: FXConnectLite.IFXConnectLiteSession) {
        this.instrumentsManager = instrumentManager;
        this.tradingSettingsProvider = session.getTradingSettingsProvider();
        this.accountsManager = session.getAccountsManager();
        this.offersManager = session.getOffersManager();
        this.marginProvider = session.getMarginProvider();
        this.accountCommissionsManager = session.getAccountCommissionsManager();
    }

    printInstruments(title: string, instruments: FXConnectLite.Instrument[]) {
        Printer.print(``);
        Printer.print(title);
        Printer.print(``);
        Printer.print(InstrumentFormatter.TITLE);
        const accountsInfo = this.accountsManager.getAccountsInfo();
        const account = this.accountsManager.getAccountById(accountsInfo[0].getId());

        instruments.forEach(instrument => {
            const minQuantity = this.tradingSettingsProvider.getMinQuantity(instrument, account);
            const offer = this.offersManager.getOfferById(instrument.getOfferId());
            let openBuyCommission = 0;
            let openSellCommission = 0;

            if(offer != null) {
                openBuyCommission = this.accountCommissionsManager.getOpenCommission(offer, account, minQuantity, "B", offer.getAsk());
                openSellCommission = this.accountCommissionsManager.getOpenCommission(offer, account, minQuantity, "S", offer.getBid());
            } else {
                Printer.print("Not found offer with ID: " + instrument.getOfferId());
            }

            let mmr = this.marginProvider.getMMR(instrument, account);
            Printer.print(InstrumentFormatter.format(instrument, minQuantity, openBuyCommission, openSellCommission, mmr))
        });
    }

    print(): void {
        this.printInstruments(`All subscribed instruments:`, this.instrumentsManager.getSubscribedInstruments());
    }
}
import InstrumentTypeDecoder from './instrument-type-decoder.js'

class InstrumentWorker {
    constructor() {
        this.decoder = new InstrumentTypeDecoder();
    }


    showInstrumentDetails(instrument) {
        let typeDescription = this.decoder.decode(instrument.getInstrumentType());

        let message = `
        Offer ID: ${instrument.getOfferId()}
        Symbol: ${instrument.getSymbol()}
        Contract currency: ${instrument.getContractCurrency()}
        Digits: ${instrument.getDigits()}
        Point size: ${instrument.getPointSize()}
        Instrument type: ${typeDescription}
        Trading status': ${instrument.getTradingStatus()}
        Contract multiplier: ${instrument.getContractMultiplier()}
        Buy interest: ${instrument.getBuyInterest()}
        Sell interest: ${instrument.getSellInterest()}
        Subscription status: ${instrument.getSubscriptionStatus()}
        Dividend buy: ${instrument.getDividendBuy()}
        Dividend sell: ${instrument.getDividendSell()}
        Sort order: ${instrument.getSortOrder()}
        Price stream ID: ${instrument.getPriceStreamId()}
        Condition dist stop: ${instrument.getConditionDistStop()}
        Condition dist limit: ${instrument.getConditionDistLimit()}
        Condition dist entry stop: ${instrument.getConditionDistEntryStop()}
        Condition dist entry limit: ${instrument.getConditionDistEntryLimit()}
        Ask adjustment: ${instrument.getAskAdjustment()}
        Bid adjustment: ${instrument.getBidAdjustment()}
        Fractional pip size: ${instrument.getFractionalPipSize()}

        `;

        console.log(message);
    }


    showInstruments(instruments) {
        instruments.forEach(instrument => {
            this.showInstrumentDetails(instrument);
        });
    }
}

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.

Next we will create the file instruments\instrument-table-builder.js which will use the previous Table Builder class and will populate all of the values in the table.

class InstrumentTableBuilder {
    constructor() {
        this.builder = new TableBuilder();

        this.decoder = new InstrumentTypeDecoder();
    }

    #getInstrumentDetails(instrument) {
        let typeDescription = this.decoder.decode(instrument.getInstrumentType());

        return new Map([
            [ 'Offer ID', instrument.getOfferId() ],
            [ 'Symbol', instrument.getSymbol() ],
            [ 'Contract currency', instrument.getContractCurrency() ],
            [ 'Digits', instrument.getDigits() ],
            [ 'Point size', instrument.getPointSize() ],
            [ 'Instrument type', typeDescription ],
            [ 'Trading status', instrument.getTradingStatus() ],
            [ 'Contract multiplier', instrument.getContractMultiplier() ],
            [ 'Buy interest', instrument.getBuyInterest() ],
            [ 'Sell interest', instrument.getSellInterest() ],
            [ 'Subscription status', instrument.getSubscriptionStatus() ],
            [ 'Dividend buy', instrument.getDividendBuy() ],
            [ 'Dividend sell', instrument.getDividendSell() ],
            [ 'Sort order', instrument.getSortOrder() ],
            [ 'Price stream ID', instrument.getPriceStreamId() ],
            [ 'Condition dist stop', instrument.getConditionDistStop() ],
            [ 'Condition dist limit', instrument.getConditionDistLimit() ],
            [ 'Condition dist entry stop', instrument.getConditionDistEntryStop() ],
            [ 'Condition dist entry limit', instrument.getConditionDistEntryLimit() ],
            [ 'Ask adjustment', instrument.getAskAdjustment() ],
            [ 'Bid adjustment', instrument.getBidAdjustment() ],
            [ 'Fractional pip size', instrument.getFractionalPipSize() ]
        ]);
    }

    #onInstrumentClick(instrument, instrumentWorker) {
        let callback = function() {
            instrumentWorker.showInstrumentDetails(instrument);
        };

        this.builder.onRowClick(instrument.getOfferId(), callback);
    }

    #renderDataTableRow(instrument, instrumentWorker) {
        let typeDescription = this.decoder.decode(instrument.getInstrumentType());

        let columns = [
            { className: 'col-sm-3', value: instrument.getOfferId() },
            { className: 'col-sm-3', value: instrument.getSymbol() },
            { className: 'col-sm-4', value: typeDescription }
        ];

        let row = this.builder.createDataTableRow(columns);
        row.onclick = () => this.#onInstrumentClick(instrument, instrumentWorker);
    }

    #renderInstrumentTableHeader() {
        let columns = [
            { className: 'col-sm-3', value: 'ID' },
            { className: 'col-sm-3', value: 'Symbol' },
            { className: 'col-sm-4', value: 'Type' }
        ];

        this.builder.createHeaderTableRow(columns);
    }

    renderInstrumentDetailsSubtable(instrument) {
        let details = this.#getInstrumentDetails(instrument);
        let columns = this.builder.createDataSubtableColumns(details);

        let detailsRow = this.builder.createDataSubtable(instrument.getOfferId(), columns, 'row mb-3 details');
        detailsRow.onclick = () => this.builder.removeSubtable();
    }

    renderInstrumentTable(instruments, instrumentWorker) {
        this.#renderInstrumentTableHeader();

        for (let instrument of instruments)
            this.#renderDataTableRow(instrument, instrumentWorker);

        this.builder.showContainer();
    }
}
The instument type will need to be determines in order to display the type in a textual format. For this, we have created instruments\instrument-type-decoder.js
class InstrumentTypeDecoder {
    decode(type) {
        switch (type) {
            case 1:
                return 'Forex';
            case 2:
                return 'Indices';
            case 3:
                return 'Commodity';
            case 4:
                return 'Treasury';
            case 5:
                return 'Bullion';
            case 6:
                return 'Shares';
            case 7:
                return 'FXIndex';
            case 8:
                return 'CFD Shares';
            case 9:
                return 'Cryptocurrency';
        }

        return type;
    }
}
Lastly, we will create the worker class instruments\instrument-worker.js that will pass the results into the table builder classes.
class InstrumentWorker {
    constructor() {
        this.tableBuilder = new InstrumentTableBuilder();
    }

    #getDataManagerStateString(state) {
        if (state.isNotLoaded())
            return 'not loaded';

        if (state.isLoading())
            return 'loading';

        if (state.isLoaded())
            return 'loaded';

        return '(has error)';
    }

    showInstrumentDetails(instrument) {
        this.tableBuilder.renderInstrumentDetailsSubtable(instrument);
    }

    showInstruments(instruments) {
        this.tableBuilder.renderInstrumentTable(instruments, this);
    }

    updateState(state) {
        document.getElementById('state')
            .textContent = this.#getDataManagerStateString(state);
    }
}

Step 5: Updating the html to include our new JavaScript files.

However one final thing we need to do is to include all of our js files into the head section of our index.html file.

<script src="connection_management/connection-status-change-listener.js"></script>
<script src="instruments/instrument-state-listener.js"></script>
<script src="instruments/instrument-table-builder.js"></script>
<script src="instruments/instrument-type-decoder.js"></script>
<script src="instruments/instrument-worker.js"></script>
<script src="common/table-builder.js"></script>
<script src="instruments/instrument-type-decoder.js"></script>
<script src="index.js"></script>

Step 6: The main JavaScript file

index.js

const sessionFactory = FXConnectLite.FXConnectLiteSessionFactory;
const LoggerFactory = FXConnectLite.LoggerFactory;

    document.addEventListener('DOMContentLoaded', () => {
        let session = sessionFactory.create('GetAllInstrumentsSample');
        session.setLogger(LoggerFactory.createLogger(LoggerFactory.LEVEL_DEBUG));

        let instrumentsManager = session.getInstrumentsManager();
        let instrumentsWorker = new InstrumentWorker();
        instrumentsManager.subscribeStateChange(new InstrumentStateListener(instrumentsManager, instrumentsWorker));

        session.subscribeConnectionStatusChange(new ConnectionStatusChangeListener(session, instrumentsManager));

        bindConnectionRelatedEvents(session, () => instrumentsManager.refresh());
    });

For more information about the getSubscribedInstruments() method, see the API reference.

When you have a list of all subscribed instruments, you can:

  1. Subscribe and Unsubscribe to instruments.
  2. Get price updates for an instrument.
  3. Get historical prices for an instrument.
  4. Create a market order.
  5. Create an entry order.

Conclusion

You have learned how to use the API to get a list of subscribed instruments. You have created an instance of the instruments manager and gotten a list of subscribed instruments. You can now use this knowledge to build your own applications that work with subscribed instruments.

Download the sample Node TypeScript, Node JavaScript, JavaScript.

Table of Contents
Get Available Instruments
The article teaches how to get a list of available instruments.
Get Subscribed Instruments
The article teaches how to get a list of subscribed instruments.
Subscribe to Instruments
API Command used to subscribe and unsubscribe to/from an instrument
Get Instrument By Symbol
The article teaches how to get an instrument using its symbol.
Search for Instruments
API Command used to search for an instrument
Instrument Details
API Command used to get the details of an instrument