Skip to content

Get Instrument By Symbol

Overview

Obtaining an instrument by its symbol is a fundamental aspect of forex trading. This article guides traders on how to retrieve detailed information about a specific instrument by specifying its symbol. By using this method, traders gain access to vital data such as pricing, trading hours, and other key characteristics, enabling them to make well-informed trading decisions.

How to get an instrument by symbol

In this article you will learn how to use the API to get an instrument using its symbol as the reference.

To get an instrument using its symbol, you need to follow these steps:

  1. Login (see the tutorial here)

  2. Create an instance of the instruments manager.

  3. Configure the instrument to retrieve and retrieve it.

  4. Printing the results in a readable format.

  1. Login (see the tutorial here)

  2. Create an instance of the instruments manager.

  3. Configure the instrument to retrieve and retrieve it.

  4. Printing the results in a readable format.

  1. Login (see the tutorial here)

  2. Create an instance of the instruments manager.

  3. Configure the instrument to retrieve and retrieve it.

  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();

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 instrument = this.instrumentsManager.getInstrumentBySymbol('USD/JPY');
        this.instrumentsWorker.showInstrumentDetails(instrument);
    }
}
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 an instrument by symbol

The next step is to get an instrument by its symbol. A symbol is a unique identifier for an instrument, such as EUR/USD or USD/JPY. You can use the getInstrumentBySymbol() method of the instruments manager to get an instrument by its symbol. This method takes a symbol as an argument and returns an instrument object if you have subscribed to it. Otherwise, it returns null.

Below, you can see some example code to get an instrument by symbol:

Configure the instrument to retrieve and retrieve it

let instrument = instrumentsManager.getInstrumentBySymbol("USD/JPY");
let instrument = instrumentsManager.getInstrumentBySymbol("USD/JPY");

As you can see in the previous code sample, we are using

let instrument = this.instrumentsManager.getInstrumentBySymbol('USD/JPY');

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="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('GetInstrumentBySymbolSample');
        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 getInstrumentBySymbol method, see the API reference.

When you have got an instrument by symbol, you can:

  1. Get price updates for an instrument.
  2. Get historical prices for an instrument.
  3. Create a market order.
  4. Create an entry order.

Conclusion

You have learned how to use the API to get an instrument by symbol. You have created an instance of the instruments manager and got an instrument by symbol. You can now use this knowledge to build your own applications that work with instruments. Now that you have an instrument, you can subscribe or unsubscribe to it, or create orders.

See also IInstrumentsManager.

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