Instrument Subscriptions
Overview
FXCM offers many different asset classes which encompass the broad array of financial assets available for trading, including currency pairs, stocks, indices, and more.
The ability to manage these instruments and access essential information is made seamless through the IInstrumentsManager interface.
This powerful tool allows traders to effortlessly subscribe to or unsubscribe from specific instruments, offering a tailored trading experience that meets their unique preferences and strategies. Whether it's tracking currency exchange rates, monitoring stock performance, or staying updated on market indices, this interface empowers traders with the data they need to make informed decisions in the dynamic world of forex trading.
Subscribe To Or Unsubscribe From An Instrument
In this article you will learn how to subscribe and unsubscribe to instruments. To subscribe to or unsubscribe from instruments, you need to follow these steps:
-
Login (see the tutorial here)
-
Create a SubscribeCallback object
-
Get a list of your subscribed instruments
-
Get an instrument symbol
-
Subscribing To An Instrument
-
Unsubscribing From An Instrument
-
Login (see the tutorial here)
-
Create a SubscribeCallback object
-
Get a list of your subscribed instruments
-
Get an instrument symbol
-
Subscribing To An Instrument
-
Unsubscribing From An Instrument
-
Login (see the tutorial here)
-
Create a SubscribeCallback object
-
Get a list of your subscribed instruments
-
Get an instrument symbol
-
Subscribing To An Instrument
-
Unsubscribing From An Instrument
-
Printing the results in a readable format.
-
Updating the html to include our new JavaScript files.
-
The main JavaScript file.
Step 1: Login
Follow the steps in the login tutorial here
Step 2: Create a SubscribeCallback object
You can use the following code to create a SubscribeCallback object:
SubscribeCallback
class SubscribeCallback implements FXConnectLite.ISubscribeInstrumentsCallback {
resolve;
constructor(resolve) {
this.resolve = resolve;
}
onSuccess() {
Printer.print("Subscribe success");
this.resolve();
}
onError(error: string) {
Printer.print("Subscribe error: "+ error);
this.resolve();
}
}
let subscribeInstrumentsCallback = {
onSuccess: function () {
console.log('Subscribe Success:', { subscribedSymbols: subscribedSymbols });
},
onError: function (error) {
console.log('Subscribe Fail:', { error: error });
}
};
In the JavaScript version we create the file instruments\instrument-subscription-callback.js where we will add the class for our callback.
class InstrumentSubscriptionCallback {
constructor(resolve, reject) {
this.resolve = resolve;
this.reject = reject;
}
onSuccess(responseObject) {
this.resolve();
}
onError(errorObject) {
this.reject();
}
}
The onError method is called if at least one subscription to an instrument fails.
Step 3: Get a list of your subscribed instruments
You can check the list of subscribed instruments by calling the instrument manager's getSubscribedInstruments method.
Get a list of subscribed instruments
session.getInstrumentsManager().refresh(); // refresh it before using it to make sure it contains the latest info.
let instrumentsManager = session.getInstrumentsManager();
let subscribedInstruments = instrumentsManager.getSubscribedInstruments();
session.getInstrumentsManager().refresh(); // refresh it before using it to make sure it contains the latest info.
let instrumentsManager = session.getInstrumentsManager();
let subscribedInstruments = instrumentsManager.getSubscribedInstruments();
In our instruments\instrument-worker.js file we have the method showInstruments where we get the subscribed instruments.
async showInstruments() {
let instruments = this.instrumentsManager.getSubscribedInstruments();
this.tableBuilder.renderInstrumentTable(instruments, this);
}
Step 4: Get an instrument symbol
Get an instrument symbol using the InstrumentDescriptor class, which is a helper class that helps you identify an instrument by its name, type, and exchange.
You can use the following code to get an instrument symbol:
Get an instrument symbol
let instrumentSymbol = instrumentsManager.getSubscribedInstruments()[0].getSymbol();
instrumentsManager.unsubscribeInstruments([instrumentSymbol], new UnsubscribeCallback(resolve));
let instrumentSymbol = instrumentsManager.getSubscribedInstruments()[0].getSymbol();
session.getInstrumentsManager().unsubscribeInstruments([instrumentSymbol], unsubscribeInstrumentsCallback);
In our main index.js file we have the method: getInstrumentsSubscription where we can see how to get the instruments symbol.
async function getInstrumentsSubscription(session) {
let instrumentsManager = session.getInstrumentsManager();
await loadManager(instrumentsManager);
let subscribedInstruments = instrumentsManager.getSubscribedInstruments();
let instrument = subscribedInstruments[0];
let symbol = instrument.getSymbol();
let symbols = [ symbol ];
let instrumentWorker = new InstrumentWorker(instrumentsManager);
instrumentWorker.showInstruments();
await instrumentWorker.unsubscribe(symbols);
instrumentWorker.showInstruments();
await wait(5000);
await instrumentWorker.subscribe(symbols);
instrumentWorker.showInstruments();
}
Step 5: Subscribing To An Instrument
To subscribe to an instrument, you use the instrument manager's subscribe method and pass it the symbol of the instrument and the callback function.
You can use the following code to create a SubscribeCallback object:
Subscribe to an instrument
instrumentsManager.subscribeInstruments(["EUR/GBP", "EUR/USD"], new SubscribeCallback(resolve));
session.getInstrumentsManager().subscribeInstruments(["EUR/GBP", "EUR/USD"], subscribeInstrumentsCallback);
Here we have two methods in our worker class for subscribing.
subscribe(symbol) {
return new Promise((resolve, reject) => {
let callback = new InstrumentSubscriptionCallback(resolve, reject);
this.instrumentsManager.subscribeInstrumentsAndStoreOnServer(symbol, callback);
});
}
This instrument will now appear on your list of subscribed instruments when performing the getSubscribedInstruments action.
See also IInstrumentsManager, ISubscribeInstrumentsCallback
Step 6: Unsubscribing To An Instrument
Create an UnsubscribeCallback object, which is a callback class that handles the unsubscription results.
You can use the following code to create an UnsubscribeCallback object:
Unsubscribe to an instrument
class UnsubscribeCallback implements FXConnectLite.ISubscribeInstrumentsCallback {
resolve;
constructor(resolve) {
this.resolve = resolve;
}
onSuccess() {
Printer.print("Unsubscribe success");
this.resolve();
}
onError(error: string) {
Printer.print("Unsubscribe error: "+ error);
this.resolve();
}
}
let unsubscribeInstrumentsCallback = {
onSuccess: function () {
console.log('Unsubscribe Success:', { subscribedSymbols: subscribedSymbols });
},
onError: function (error) {
console.log('Unsubscribe Fail:', { error: error });
}
};
Here we have two methods in our worker class for unsubscribing.
unsubscribe(symbol) {
return new Promise((resolve, reject) => {
let callback = new InstrumentSubscriptionCallback(resolve, reject);
this.instrumentsManager.unsubscribeInstrumentsAndStoreOnServer(symbol, callback);
});
}
The onError() method is called if at least one unsubscription to an instrument fails.
This instrument will no longer appear on your list of subscribed instruments when performing the getSubscribedInstruments() action.
See also IInstrumentsManager, ISubscribeInstrumentsCallback
Step 7: Printing the results in a readable format.
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 have the instruments\instrument-table-builder.js which passes the results to the table class.
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();
}
}
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;
}
}
instruments\instrument-worker.js. This class is responsible for passing the results to the printing functions and is responsible for creating the order.
class InstrumentWorker {
constructor(instrumentsManager) {
this.instrumentsManager = instrumentsManager;
this.tableBuilder = new InstrumentTableBuilder();
}
showInstrumentDetails(instrument) {
this.tableBuilder.renderInstrumentDetailsSubtable(instrument);
}
async showInstruments() {
let instruments = this.instrumentsManager.getSubscribedInstruments();
this.tableBuilder.renderInstrumentTable(instruments, this);
}
subscribe(symbol) {
return new Promise((resolve, reject) => {
let callback = new InstrumentSubscriptionCallback(resolve, reject);
this.instrumentsManager.subscribeInstrumentsAndStoreOnServer(symbol, callback);
});
}
unsubscribe(symbol) {
return new Promise((resolve, reject) => {
let callback = new InstrumentSubscriptionCallback(resolve, reject);
this.instrumentsManager.unsubscribeInstrumentsAndStoreOnServer(symbol, callback);
});
}
}
Step 8: Updating the html to include our new JavaScript files.
<script src="instruments/instrument-subscription-callback.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="index.js"></script>
Step 9: The main JavaScript file.
index.js
async function getInstrumentsSubscription(session) {
let instrumentsManager = session.getInstrumentsManager();
await loadManager(instrumentsManager);
let subscribedInstruments = instrumentsManager.getSubscribedInstruments();
let instrument = subscribedInstruments[0];
let symbol = instrument.getSymbol();
let symbols = [ symbol ];
let instrumentWorker = new InstrumentWorker(instrumentsManager);
instrumentWorker.showInstruments();
await instrumentWorker.unsubscribe(symbols);
instrumentWorker.showInstruments();
await wait(5000);
await instrumentWorker.subscribe(symbols);
instrumentWorker.showInstruments();
}
document.addEventListener('DOMContentLoaded', () => {
let logLevel = FXConnectLite.LoggerFactory.LEVEL_DEBUG;
let logger = FXConnectLite.LoggerFactory.createLogger(logLevel);
let session = FXConnectLite.FXConnectLiteSessionFactory.create('InstrumentSubscriptionsSample');
session.setLogger(logger);
let callback = getInstrumentsSubscription;
let connectionStatusChangeListener = new ConnectionStatusChangeListener(session, callback);
session.subscribeConnectionStatusChange(connectionStatusChangeListener);
bindConnectionRelatedEvents(session, () => callback(session));
});
When instruments are subscribed, you can:
- Get available instruments.
- Get price updates for an instrument.
- Get historical prices for an instrument.
Conclusion
You have learned how to subscribe and unsubscribe to instruments using the IInstrumentsManager interface. You have created a SubscribeCallback object, which is a callback class that handles the subscription results. You have also learned how to check the list of subscribed instruments by calling the instrument manager's getSubscribedInstruments method. Additionally, you have learned how to get an instrument symbol using the InstrumentDescriptor class. You can now use this knowledge to manage your subscriptions and get information about the instruments on the platform.
Download the sample Node TypeScript, Node JavaScript.
Note
Questions and answers
What are indices?
Indices are a measurement of the performance of a group of stocks. Trading indices enables you to gain exposure to a specific sector of the economy while only needing to open one position.
| 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 |