Get Historical Prices for an Instrument
Overview
The IPriceHistoryManager.getPrices() method allows traders to retrieve past price data for a specific instrument. Below, you can find description and some code examples.
Download a sample in your programming language Node TypeScript, Node JavaScript, JavaScript. The sample helps you to retrieve past price data for a specific instrument.
For login follow the steps in the login tutorial here
Create a callback class for receiving price history
The first step is to create a callback class that will handle the response from the API when requesting price history.
You can use the PriceHistoryManagerCallback interface to define the methods of this class.
class PriceHistoryManagerCallback implements FXConnectLite.IPriceHistoryManagerCallback {
resolve: any;
app: Application;
onSuccess(responseObject: FXConnectLite.IPriceHistoryResponse) {
PriceHistoryPrinter.printAll(responseObject, this.app);
this.resolve();
}
onError(errorObject: FXConnectLite.IFXConnectLiteError) {
Printer.print(errorObject.getMessage());
this.resolve();
}
onCancel() {
this.resolve();
}
constructor(resolve: any, app: Application) {
this.resolve = resolve;
this.app = app;
}
}
let PriceHistoryManagerCallback = /** @class */ (function () {
function PriceHistoryManagerCallback(resolve, app) {
this.resolve = resolve;
this.app = app;
}
PriceHistoryManagerCallback.prototype.onSuccess = function (responseObject) {
PriceHistoryPrinter.printAll(responseObject, this.app);
this.resolve();
};
PriceHistoryManagerCallback.prototype.onError = function (errorObject) {
console.log(errorObject.getMessage());
this.resolve();
};
return PriceHistoryManagerCallback;
}());
The first thing we will need to do is to include the javascript files that we are about to create.
<script src="connection_management/connection-status-change-listener.js"></script>
<script src="instruments/instrument-state-listener.js"></script>
<script src="price_history/price-history-manager-callback.js"></script>
<script src="price_history/price-history-options.js"></script>
<script src="price_history/price-history-table-builder.js"></script>
<script src="price_history/price-history-worker.js"></script>
<script src="index.js"></script>
div inside the workspace-section section.
<div id="item-stats" class="row">
<div class="offset-sm-3 col-sm-6 border pt-3 pb-3 mt-5">
<div>
Instrument:
<i>
<span id="instrument"></span>
</i>
</div>
<div>
Time Frame:
<i>
<span id="time-frame-value"></span>
</i>
</div>
<div>
From:
<i>
<span id="from-date"></span>
</i>
</div>
<div>
To:
<i>
<span id="to-date"></span>
</i>
</div>
<div>
History Count:
<i>
<span id="quote-count"></span>
</i>
</div>
</div>
</div>
price_history\price-history-manager-callback.js
class PriceHistoryManagerCallback {
constructor(priceHistoryWorker) {
this.priceHistoryWorker = priceHistoryWorker;
}
onError(error) {
showErrorAlert(error.getMessage());
};
onSuccess(response) {
this.priceHistoryWorker.showPriceHistory(response);
}
}
instruments\instrument-state-listener.js
class InstrumentStateListener {
constructor(priceHistoryManager, requestOptions) {
this.manager = priceHistoryManager;
this.opts = requestOptions;
}
onStateChange(state) {
if (!state.isLoaded())
return;
this.manager.getPrices(this.opts.instrument, this.opts.timeFrame, this.opts.fromDate, this.opts.toDate, this.opts.quoteCount, this.opts.callback);
}
}
For more information about IPriceHistoryManagerCallback, see the API reference.
Get and Set the Weekend Data
setIncludeWeekendData() method sets whether weekend data will be included in the history, if it is available in the dataset.
manager.setIncludeWeekendData(includeWeekend);
getIncludeWeekendData() method.
manager.setIncludeWeekendData(includeWeekend);
getIncludeWeekendData() method.
Get the price history of an instrument
The next step is to get the price history of a specific instrument. To specify which instrument, and date period etc, you need to set up some parameters.
Then you can use the getPrices() method of the API to request the price history of an instrument by its name.
This method takes a PriceHistoryManagerCallback object as an argument and calls its onSuccess() or onError() methods depending on the result.
let manager = session.getPriceHistoryManager();
this.timeframe = FXConnectLite.Timeframe.create(FXConnectLite.TimeframeUnit.Minute, 30);
manager.getPrices(this.instrument, this.timeframe, this.from, this.to, -1, new PriceHistoryManagerCallback(resolve, this));
let manager = session.getPriceHistoryManager();
let timeframe = FXConnectLite.Timeframe.create(FXConnectLite.TimeframeUnit.Minute, 30);
manager.getPrices(this.instrument, this.timeframe, this.from, this.to, -1, new PriceHistoryManagerCallback(resolve, this));
First we will create a class for storing the options in price_history\price-history-options.js
class PriceHistoryOptions {
constructor(instrument, fromDate, toDate, timeFrame, quoteCount, callback) {
this.callback = callback;
this.instrument = instrument;
this.fromDate = fromDate;
this.toDate = toDate;
this.timeFrame = timeFrame;
this.quoteCount = quoteCount;
}
}
getPrices() in our index.js file.
const sessionFactory = FXConnectLite.FXConnectLiteSessionFactory;
const LoggerFactory = FXConnectLite.LoggerFactory;
function getOptions() {
const instrument = 'EUR/USD';
const fromDate = new Date('2021-07-31');
const toDate = new Date('2022-08-03');
const quoteCount = 100;
const timeFrameValue = 30;
const timeFrame = FXConnectLite.Timeframe.create(FXConnectLite.TimeframeUnit.Minute, timeFrameValue);
let priceHistoryWorker = new PriceHistoryWorker();
let priceHistoryManagerCallback = new PriceHistoryManagerCallback(priceHistoryWorker);
return new PriceHistoryOptions(instrument, fromDate, toDate, timeFrame, quoteCount, priceHistoryManagerCallback);
}
function setQueryDetails(options) {
document.getElementById('instrument')
.textContent = options.instrument;
document.getElementById('time-frame-value')
.textContent = options.timeFrame;
document.getElementById('from-date')
.textContent = options.fromDate;
document.getElementById('to-date')
.textContent = options.toDate;
document.getElementById('quote-count')
.textContent = options.quoteCount;
}
document.addEventListener('DOMContentLoaded', () => {
let options = getOptions();
setQueryDetails(options);
let session = sessionFactory.create('GetHistoryPricesSample');
session.setLogger(LoggerFactory.createLogger(LoggerFactory.LEVEL_DEBUG));
let instrumentsManager = session.getInstrumentsManager();
session.subscribeConnectionStatusChange(new ConnectionStatusChangeListener(session, instrumentsManager));
let priceHistoryManager = session.getPriceHistoryManager();
instrumentsManager.subscribeStateChange(new InstrumentStateListener(priceHistoryManager, options));
bindConnectionRelatedEvents(session, () => priceHistoryManager.getPrices(options.instrument, options.timeFrame, options.fromDate, options.toDate, options.quoteCount, options.priceHistoryManagerCallback)
);
});
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 TableBuilder {
constructor() {
this.#items = document.getElementById('items');
this.lastSelectedId = '';
}
appendColumn(row, className, value) {
let column = document.createElement('div');
column.className = className;
column.textContent = value;
row.appendChild(column);
}
createDataSubtable(parentId, columns, className) {
let subtableRow = this.createDataTableRow(columns, className);
let parentRow = document.getElementById('item-' + parentId);
parentRow.style.backgroundColor = '#dce0e4';
parentRow.after(subtableRow);
return subtableRow;
}
createDataTableRow(columns, className) {
if (className === undefined)
className = 'row mb-0 pb-0 item';
let row = document.createElement('div');
row.className = className;
row.style.cursor = 'pointer';
columns.forEach(column => {
this.appendColumn(row, column.className, column.value);
});
row.id = 'item-' + columns[0].value;
this.items.appendChild(row);
return row;
}
createDataSubtableColumns(itemDetails) {
let columns = [];
itemDetails.forEach((k, v) => {
columns.push({ className: 'col-sm-6', value: v });
columns.push({ className: 'col-sm-6', value: k });
});
return columns;
}
createHeaderTableRow(columns) {
let row = document.createElement('div');
row.className = 'row mb-3';
row.style.backgroundColor = '#adb5bd';
columns.forEach(column => {
this.appendColumn(row, column.className, column.value);
});
this.items.replaceChildren();
this.items.appendChild(row);
return row;
}
onRowClick(id, func) {
if (this.lastSelectedId !== id) {
this.lastSelectedId = id;
func();
} else {
this.removeSubtable();
this.lastSelectedId = '';
}
}
removeSubtable() {
this.lastSelectedId = '';
let subtable = document.querySelector('#items > div.row.mb-3.details');
if (subtable !== null)
subtable.remove();
let parentRows = document.getElementsByClassName('row mb-0 pb-0 item');
for (let row of parentRows)
row.style.backgroundColor = '';
}
showContainer() {
document.getElementById('items-container').style.display = 'block';
}
get items() {
return this.#items;
}
#items;
}
price_history\price-history-table-builder.js which will use the previous Table Builder class and will populate all of the values in the table.
class PriceHistoryTableBuilder {
constructor() {
this.builder = new TableBuilder();
}
#renderDataTableRow(item, i) {
let columns = [
{ className: 'col-sm-2', value: item.getDate(i) },
{ className: 'col-sm-1', value: item.getAskOpen(i).toFixed(5) },
{ className: 'col-sm-1', value: item.getAskClose(i).toFixed(5) },
{ className: 'col-sm-1', value: item.getAskLow(i).toFixed(5) },
{ className: 'col-sm-1', value: item.getAskHigh(i).toFixed(5) },
{ className: 'col-sm-1', value: item.getBidOpen(i).toFixed(5) },
{ className: 'col-sm-1', value: item.getBidClose(i).toFixed(5) },
{ className: 'col-sm-1', value: item.getBidLow(i).toFixed(5) },
{ className: 'col-sm-1', value: item.getBidHigh(i).toFixed(5) },
{ className: 'col-sm-2', value: item.getVolume(i) }
];
let row = this.builder.createDataTableRow(columns);
}
#renderPriceHistoryTableHeader() {
let columns = [
{ className: 'col-sm-2', value: 'Timestamp' },
{ className: 'col-sm-1', value: 'Ask Open' },
{ className: 'col-sm-1', value: 'Ask Close' },
{ className: 'col-sm-1', value: 'Ask Low' },
{ className: 'col-sm-1', value: 'Ask High' },
{ className: 'col-sm-1', value: 'Bid Open' },
{ className: 'col-sm-1', value: 'Bid Close' },
{ className: 'col-sm-1', value: 'Bid Low' },
{ className: 'col-sm-1', value: 'Bid High' },
{ className: 'col-sm-2', value: 'Volume' }
];
this.builder.createHeaderTableRow(columns);
}
renderPriceHistoryTable(response) {
this.#renderPriceHistoryTableHeader();
for (let i = 0; i < response.getCount(); i++) {
this.#renderDataTableRow(response, i);
}
}
}
price_history\price-history-worker.js that will send the retreived results to the table class for display.
class PriceHistoryWorker {
constructor() {
this.builder = new PriceHistoryTableBuilder();
}
showPriceHistory(response) {
this.builder.renderPriceHistoryTable(response);
}
}
See also IPriceHistoryManager
Conclusion
You have learned how to use the API to receive historical prices for an instrument. Before you can get historical data, you need to create a callback class for receiving price history, get the price history of an instrument, and check if the price history contains an ask price. You have also learned how to create a callback class using the PriceHistoryManagerCallback interface and how to get the price history of an instrument using the getPriceHistory() method of the API. You can now use this knowledge to retrieve historical prices for instruments on the platform.
| Table of Contents | |
|---|---|
| Get Price Updates for an Instrument The article teaches how to receive price updates for an instrument. |
|
| Get Historical Prices for an Instrument The article teaches how to receive historical prices for an instrument. |