or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

account.mdcore.mdindex.mdorder.mdposition.mdpricing.mdtrade.mdtransaction.mduser.md
tile.json

tessl/npm-oanda--v20

JavaScript bindings for OANDA's v20 REST API enabling programmatic forex and CFD trading operations.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@oanda/v20@3.0.x

To install, run

npx @tessl/cli install tessl/npm-oanda--v20@3.0.3

index.mddocs/

OANDA v20 API

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.

Package Information

  • Package Name: @oanda/v20
  • Package Type: npm
  • Language: JavaScript (ES6)
  • Installation: npm install @oanda/v20

Core Imports

const { Context } = require('@oanda/v20/context');

ES6:

import { Context } from '@oanda/v20/context';

Basic Usage

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

Architecture

The @oanda/v20 library is structured around several key components:

  • Context Class: Main entry point that manages HTTP communication with OANDA's API servers and provides access to all API endpoints through EntitySpec instances
  • EntitySpec Classes: Domain-specific API wrappers for each functional area (account, order, trade, position, pricing, transaction, instrument, user)
  • Definition Classes: Strongly-typed data models representing all API entities, inheriting from a base Definition class with common serialization methods
  • Response Class: Wrapper for HTTP responses with status checking convenience methods
  • Callback Pattern: All API methods use asynchronous callbacks receiving Response objects

Capabilities

Context and Response

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;
}

Core Classes

Account Management

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

Account Management

Order Management

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

Order Management

Trade Management

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

Trade Management

Position Management

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

Position Management

Pricing and Market Data

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

Pricing and Market Data

Transaction History

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

Transaction History

User Information

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

User Information

Common Types

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
}