Skip to content

Get Available Instruments

Overview

The "Get Available Instruments" functionality provides users with a comprehensive list of all instruments they have access to, allowing traders to easily manage their subscriptions and stay updated on the instruments that matter to them.

How to get a list of available instruments

In this article you will learn how to use the API to get available instruments.

To get available 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 instrument descriptors.

  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 instrument descriptors.

  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 instrument descriptors.

  4. Printing the results in a readable format.

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

  6. The main JavaScript file.

  1. Login (see the tutorial here)

  2. Create an instance of the instruments manager.

  3. Get a list of instrument descriptors.

  4. Printing the results in a readable format.

Step 1: Login

Follow the steps in the login tutorial here

Step 2: Create an instrument manager object

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

let instrumentsManager = session.getInstrumentsManager();
let instrumentsManager = session.getInstrumentsManager();

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.getAllInstrumentDescriptors();
        this.instrumentsWorker.showInstruments(instruments);
    }
}

final IInstrumentsManager instrumentsManager = session.getInstrumentsManager();

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

Step 3: Get a list of instrument descriptors

The next step is to get a list of all instruments that the user can subscribe 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 getInstrumentDescriptors() method of the instruments manager to get a list of available instruments. This method returns an array of instrument symbols.

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

Get the list of instruments

let descriptors = instrumentsManager.getAllInstrumentDescriptors();
let descriptors = instrumentsManager.getAllInstrumentDescriptors();

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

let instruments = this.instrumentsManager.getAllInstrumentDescriptors();

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 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="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());
    });

final InstrumentDescriptor[] instrumentDescriptors = instrumentsManager.getAllInstrumentDescriptors();

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

The class Descriptor allows you to get the offer ID, subscription status, symbol, and other information, full information about the instrument is available only after subscription.

See also InstrumentDescriptor, getOfferId, getPriceStreamId, getSortOrder, getSubscriptionStatus, getSymbol. Now that you have your list of instruments, you are ready to subscribe to them or perform other actions on them.

For more information about the InstrumentDescriptor interface and its methods, see the API reference.

When you have available instruments, you can:

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

Conclusion

You have learned how to use the API to get the available instruments. You have created an instrument manager object, subscribed to the instrument manager state change event, refreshed the instrument manager object, and got the list of instrument descriptors. You can now use this knowledge to build your own applications that work with the available 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