JavaScript bindings for OANDA's v20 REST API, providing comprehensive programmatic access to forex and CFD trading operations including account management, order execution, trade monitoring, position tracking, pricing data, and transaction history.
npm install @oanda/v20const { Context } = require('@oanda/v20/context');ES6:
import { Context } from '@oanda/v20/context';const { Context } = require('@oanda/v20/context');
// Create context for practice environment
const ctx = new Context('api-fxpractice.oanda.com', 443, true, 'MyTradingApp');
// Set authentication token
ctx.setToken('YOUR_API_TOKEN');
// Get account summary
ctx.account.summary('YOUR_ACCOUNT_ID', response => {
if (response.isSuccess()) {
const account = response.body.account;
console.log(`Balance: ${account.balance} ${account.currency}`);
console.log(`Unrealized P/L: ${account.unrealizedPL}`);
} else {
console.error('Error:', response.statusCode, response.statusMessage);
}
});
// Create a market order
ctx.order.market('YOUR_ACCOUNT_ID', {
instrument: 'EUR_USD',
units: '100',
timeInForce: 'FOK',
positionFill: 'DEFAULT'
}, response => {
if (response.isSuccess()) {
console.log('Order created:', response.body.orderFillTransaction);
}
});The @oanda/v20 library is structured around several key components:
Core classes for API interaction and HTTP response handling.
class Context {
constructor(hostname, port, ssl, application);
setToken(token);
request(method, path, body, streamChunkHandler, responseHandler);
// EntitySpec instances for each API area
account;
order;
trade;
position;
pricing;
transaction;
instrument;
user;
primitives;
pricing_common;
site;
}
class Response {
constructor(method, path, statusCode, statusMessage, contentType, rawBody);
isSuccess();
isRedirection();
isClientError();
isServerError();
isError();
// Properties
method;
path;
statusCode;
statusMessage;
contentType;
rawBody;
body;
}Comprehensive account operations including listing accounts, retrieving account details and summaries, querying tradable instruments, configuring account settings, and polling for account changes.
// EntitySpec methods accessed via ctx.account
list(responseHandler);
get(accountID, responseHandler);
summary(accountID, responseHandler);
instruments(accountID, queryParams, responseHandler);
configure(accountID, bodyParams, responseHandler);
changes(accountID, queryParams, responseHandler);Complete order lifecycle management with support for multiple order types (market, limit, stop, market-if-touched, take-profit, stop-loss, trailing-stop-loss), order creation and modification, cancellation, and client extension management.
// EntitySpec methods accessed via ctx.order
create(accountID, bodyParams, responseHandler);
list(accountID, queryParams, responseHandler);
listPending(accountID, responseHandler);
get(accountID, orderSpecifier, responseHandler);
replace(accountID, orderSpecifier, bodyParams, responseHandler);
cancel(accountID, orderSpecifier, responseHandler);
setClientExtensions(accountID, orderSpecifier, bodyParams, responseHandler);
// Helper methods for specific order types
market(accountID, orderSpec, responseCallback);
limit(accountID, orderSpec, responseCallback);
stop(accountID, orderSpec, responseCallback);
marketIfTouched(accountID, orderSpec, responseCallback);
takeProfit(accountID, orderSpec, responseCallback);
stopLoss(accountID, orderSpec, responseCallback);
trailingStopLoss(accountID, orderSpec, responseCallback);Operations for managing open trades including listing all trades, retrieving trade details, closing trades partially or fully, updating client extensions, and managing dependent orders (take-profit, stop-loss, trailing-stop-loss).
// EntitySpec methods accessed via ctx.trade
list(accountID, queryParams, responseHandler);
listOpen(accountID, responseHandler);
get(accountID, tradeSpecifier, responseHandler);
close(accountID, tradeSpecifier, bodyParams, responseHandler);
setClientExtensions(accountID, tradeSpecifier, bodyParams, responseHandler);
setDependentOrders(accountID, tradeSpecifier, bodyParams, responseHandler);Position tracking and management operations for viewing all positions by instrument, listing open positions, retrieving position details with separate long/short side information, and closing positions.
// EntitySpec methods accessed via ctx.position
list(accountID, responseHandler);
listOpen(accountID, responseHandler);
get(accountID, instrument, responseHandler);
close(accountID, instrument, bodyParams, responseHandler);Real-time and historical pricing data access including current price queries, price streaming for live updates, candlestick/OHLC data retrieval with configurable granularities, order book and position book snapshots.
// Pricing methods accessed via ctx.pricing
basePrices(queryParams, responseHandler);
getPriceRange(instrument, queryParams, responseHandler);
get(accountID, queryParams, responseHandler);
stream(accountID, queryParams, streamChunkHandler, responseHandler);
candles(instrument, queryParams, responseHandler);
// Instrument methods accessed via ctx.instrument
candles(instrument, queryParams, responseHandler);
price(instrument, queryParams, responseHandler);
prices(instruments, queryParams, responseHandler);
orderBook(instrument, queryParams, responseHandler);
positionBook(instrument, queryParams, responseHandler);Complete transaction history access with querying by date range or transaction ID, transaction detail retrieval, and transaction streaming for real-time updates on all account activity.
// EntitySpec methods accessed via ctx.transaction
list(accountID, queryParams, responseHandler);
get(accountID, transactionID, responseHandler);
range(accountID, queryParams, responseHandler);
since(accountID, queryParams, responseHandler);
stream(accountID, streamChunkHandler, responseHandler);Operations for retrieving user account information including username, country, email, and FIFO status.
// EntitySpec methods accessed via ctx.user
getInfo(userSpecifier, responseHandler);
getExternalInfo(userSpecifier, responseHandler);All definition classes inherit from a base Definition class:
class Definition {
toJSON(key);
name();
summary();
title();
toString();
fields();
}Client extensions for orders and trades:
interface ClientExtensions {
id?: string;
tag?: string;
comment?: string;
}Instrument specification:
interface Instrument {
name: string;
type: string; // CURRENCY, CFD, METAL
displayName: string;
pipLocation: number;
displayPrecision: number;
tradeUnitsPrecision: number;
minimumTradeSize: string;
maximumTrailingStopDistance: string;
minimumTrailingStopDistance: string;
maximumPositionSize: string;
maximumOrderUnits: string;
marginRate: string;
commission: InstrumentCommission;
}
interface InstrumentCommission {
commission: string;
unitsTraded: string;
minimumCommission: string;
}
interface GuaranteedStopLossOrderLevelRestriction {
volume: string; // Total allowed trade volume within priceRange
priceRange: string; // Price range in price units
}
interface MT4TransactionHeartbeat {
type: string; // Always "HEARTBEAT"
time: string; // DateTime when heartbeat was created
}