npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

iq-option-client

v1.3.7

Published

A robust TypeScript client library for interacting with the IQ Option WebSocket API. Features real-time trading, market data streaming, and order management with SOLID principles.

Readme

IQ Option Client

npm version License: ISC TypeScript

A robust TypeScript client library for interacting with the IQ Option WebSocket API. This library provides a clean, type-safe interface for real-time trading, market data streaming, and order management with full SOLID principles implementation.

✨ Features

  • 🔐 Secure Authentication - Environment-based credential management
  • 📊 Real-time Data Streaming - WebSocket-based candle data, trader sentiment, and option events
  • 📈 Order Management - Binary and digital option order execution
  • 📜 Historical Data - Retrieve historical candles for backtesting and analysis (with configurable timeout)
  • 🎯 Type-Safe - Full TypeScript support with comprehensive type definitions
  • 🏗️ SOLID Architecture - Clean code with design patterns (Strategy, Repository, Factory, Command, Builder)
  • 🔄 Error Handling - Comprehensive error handling with retry logic
  • 📝 Structured Logging - Winston-based logging with context and metadata
  • Input Validation - Built-in validation for all API methods
  • 🔧 Helper Utilities - Market symbol helpers, request ID generators, and validators
  • 🧪 Well Tested - Comprehensive test suite

📦 Installation

npm install iq-option-client

Or with yarn:

yarn add iq-option-client

🚀 Quick Start

Basic Setup

  1. Install the package:
npm install iq-option-client
  1. Create a .env file (or set environment variables):
[email protected]
IQ_OPTION_PASSWORD=your-password
  1. Basic usage:
import { IQOptionApi, IQOptionMarket, IQOptionModel, iqOptionExpired, IQOptionCurrencyType } from 'iq-option-client';

// Initialize client
const api = new IQOptionApi(
  process.env.IQ_OPTION_EMAIL!,
  process.env.IQ_OPTION_PASSWORD!
);

// Connect and authenticate
const profile = await api.connectAsync();

// Get test balance
const testBalance = profile.balances.find(
  b => b.type === IQOptionCurrencyType.TEST
);

// Send a binary order
const result = await api.sendOrderBinary(
  IQOptionMarket.EURUSD_OTC,
  IQOptionModel.BUY,
  iqOptionExpired(1), // 1 minute expiration
  testBalance!.id,
  90, // profit percent
  10  // amount
);

console.log('Order result:', result);

📚 Documentation

Core Classes

IQOptionApi

Main API client for IQ Option operations.

import { IQOptionApi } from 'iq-option-client';

const api = new IQOptionApi(email, password);

// Connect and get profile
const profile = await api.connectAsync();

// Get initialization data
const initData = await api.getInitializationData();

// Get digital option instruments
const instruments = await api.getDigitalOptionInstruments(IQOptionMarket.EURUSD);

// Get historical candles with default timeout (15 seconds)
const historicalCandles = await api.getCandles(
  activeId,    // Market/Active ID (e.g., 1 for EURUSD)
  size,        // Candle size in seconds (60 = 1 min, 120 = 2 min)
  fromId,      // Starting candle ID
  toId,        // Ending candle ID
  true,        // split_normalization (optional, default: true)
  true         // only_closed (optional, default: true)
);

// Get historical candles with custom timeout (30 seconds)
const historicalCandlesWithTimeout = await api.getCandles(
  activeId,
  size,
  fromId,
  toId,
  true,
  true,
  30000        // timeoutMs (optional, default: 15000)
);

// Send binary order
await api.sendOrderBinary(
  market,
  side,
  expirationTime,
  balanceId,
  profitPercent,
  amount
);

// Send digital order
await api.sendOrderDigital(
  market,
  side,
  timeMinutes,
  balanceId,
  amount,
  instrumentIndex
);

Streams

Candle Stream
import { IQOptionStreamCandleGenerated, IQOptionMarket, IQOptionTime } from 'iq-option-client';

const candleStream = new IQOptionStreamCandleGenerated(
  api.getIQOptionWs(),
  IQOptionMarket.EURUSD,
  IQOptionTime.ONE_MINUTE
);

await candleStream.startStream();

candleStream.on('data', (candle) => {
  console.log('New candle:', {
    open: candle.open,
    close: candle.close,
    high: candle.max,
    low: candle.min,
    time: candle.from
  });
});
Traders Sentiment Stream
import { IQOptionStreamOptionTradersSentiment } from 'iq-option-client';

const sentimentStream = new IQOptionStreamOptionTradersSentiment(
  api.getIQOptionWs(),
  IQOptionMarket.EURUSD
);

await sentimentStream.startStream();

sentimentStream.on('data', (data) => {
  console.log('Traders sentiment:', data.value);
  // value > 0.8 = strong buy sentiment
  // value < 0.22 = strong sell sentiment
});
Option Close Stream
import { IQOptionStreamOptionClose } from 'iq-option-client';

const closeStream = new IQOptionStreamOptionClose(api.getIQOptionWs());

await closeStream.startStream();

closeStream.on('data', (data) => {
  console.log('Option closed:', {
    result: data.win,
    profit: data.profit,
    optionId: data.option_id
  });
});
User Alerts Stream
import { IQOptionStreamUserAlerts } from 'iq-option-client';

const alertsStream = new IQOptionStreamUserAlerts(api.getIQOptionWs());

await alertsStream.startStream();
await alertsStream.subscribe();

alertsStream.on('data', (alert) => {
  console.log('User alert:', alert);
});

Get Historical Candles

import { IQOptionApi } from 'iq-option-client';

// Get historical candles with default timeout (15 seconds)
const candles = await api.getCandles(
  activeId,    // Market/Active ID (e.g., 1 for EURUSD, 76, 1874, etc.)
  size,        // Candle size in seconds (60 = 1 min, 120 = 2 min)
  fromId,      // Starting candle ID
  toId,        // Ending candle ID
  true,        // split_normalization (optional, default: true)
  true         // only_closed (optional, default: true)
);

// Get historical candles with custom timeout (30 seconds)
const candlesWithTimeout = await api.getCandles(
  activeId,
  size,
  fromId,
  toId,
  true,
  true,
  30000  // timeoutMs (optional, default: 15000)
);

console.log(`Received ${candles.length} historical candles`);
candles.forEach(candle => {
  console.log('Candle:', {
    id: candle.id,
    open: candle.open,
    close: candle.close,
    high: candle.max,
    low: candle.min,
    timestamp: new Date(candle.from * 1000)
  });
});

Note: To get real candle IDs, you can:

  1. Get them from the candle stream (each candle has an id field)
  2. Calculate them based on timestamps and candle size
  3. Use IDs from previous API responses

Advanced Usage

Using Design Patterns

The library implements several design patterns for extensibility:

Strategy Pattern - Order Types
import { 
  BinaryOrderStrategy, 
  DigitalOrderStrategy,
  WebSocketRepository 
} from 'iq-option-client';

const repository = new WebSocketRepository(api.getIQOptionWs());

// Binary order strategy
const binaryStrategy = new BinaryOrderStrategy(repository, 90); // 90% profit
await binaryStrategy.execute(market, side, time, balanceId, amount);

// Digital order strategy
const digitalStrategy = new DigitalOrderStrategy(repository, instrumentIndex);
await digitalStrategy.execute(market, side, time, balanceId, amount);
Builder Pattern - Order Construction
import { OrderBuilder, IQOptionMarket, IQOptionModel } from 'iq-option-client';

const order = new OrderBuilder()
  .withMarket(IQOptionMarket.EURUSD_OTC)
  .withSide(IQOptionModel.BUY)
  .withTime(iqOptionExpired(1))
  .withBalance(balanceId)
  .withAmount(10)
  .withProfitPercent(90)
  .build();
Factory Pattern - Stream Creation
import { StreamFactory, StreamType } from 'iq-option-client';

const factory = new StreamFactory(api.getIQOptionWs());

const candleStream = factory.create(
  StreamType.CANDLE,
  IQOptionMarket.EURUSD,
  IQOptionTime.ONE_MINUTE
);
Command Pattern - Encapsulated Operations
import { 
  SendOrderCommand, 
  GetProfileCommand,
  CommandInvoker 
} from 'iq-option-client';

const invoker = new CommandInvoker();

// Execute order command
const orderCommand = new SendOrderCommand(strategy, orderRequest);
const result = await invoker.execute(orderCommand);

// Execute profile command
const profileCommand = new GetProfileCommand(repository);
const profile = await invoker.execute(profileCommand);

Error Handling

import { 
  IQOptionError,
  AuthenticationError,
  ConnectionError,
  OrderError,
  TimeoutError,
  ErrorHandler 
} from 'iq-option-client';

try {
  await api.connectAsync();
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else if (error instanceof ConnectionError) {
    console.error('Connection failed:', error.message);
    // Connection errors are retryable
  } else if (error instanceof TimeoutError) {
    console.error('Operation timed out:', error.message);
  } else if (error instanceof IQOptionError) {
    console.error('IQ Option error:', error.toJSON());
  }
}

Logging

import { LoggerFactory } from 'iq-option-client';

const logger = LoggerFactory.create({ 
  className: 'MyClass',
  methodName: 'myMethod' 
});

logger.info('Operation started', { operation: 'trade' });
logger.debug('Debug information', { metadata: { value: 123 } });
logger.error('Error occurred', { operation: 'trade' }, error);
logger.performance('Operation completed', 150, { operation: 'trade' });

Input Validation

All public methods include built-in validation:

// These will throw IQOptionError if invalid
await api.sendOrderBinary(
  IQOptionMarket.EURUSD_OTC,  // Validated
  IQOptionModel.BUY,           // Validated
  iqOptionExpired(1),          // Validated (> 0)
  balanceId,                   // Validated (> 0)
  90,                          // Validated (0-100)
  10                           // Validated (> 0)
);

Market Helper

Get market symbol/name from market ID for logging and error messages:

import { MarketHelper, IQOptionMarket } from 'iq-option-client';

// Get market symbol
const symbol = MarketHelper.getMarketSymbol(IQOptionMarket.EURUSD);
console.log(symbol); // "EURUSD"

// Get market symbol with fallback
const symbolWithFallback = MarketHelper.getMarketSymbolWithFallback(
  IQOptionMarket.USDJPY,
  "UNKNOWN"
);
console.log(symbolWithFallback); // "USDJPY"

// Check if market exists
const exists = MarketHelper.hasMarketSymbol(IQOptionMarket.GBPUSD);
console.log(exists); // true

// Example: Use in error handling
try {
  await api.sendOrderBinary(
    IQOptionMarket.EURUSD_OTC,
    IQOptionModel.BUY,
    iqOptionExpired(1),
    balanceId,
    90,
    10
  );
} catch (error) {
  const symbol = MarketHelper.getMarketSymbol(IQOptionMarket.EURUSD_OTC);
  console.error(`[✗] Erro ao enviar ordem: ${symbol}`, error);
}

🎯 API Reference

Enums

  • IQOptionMarket - Available markets (EURUSD, EURUSD_OTC, etc.)
  • IQOptionModel - Order direction (BUY, SELL)
  • IQOptionTime - Time intervals (ONE_MINUTE, FIVE_MINUTES, etc.)
  • IQOptionCurrency - Currency types (USD, EUR, etc.)
  • IQOptionCurrencyType - Balance types (FIAT, TEST, etc.)

Main Classes

  • IQOptionApi - Main API client
  • IQOptionWs - WebSocket client
  • IQOptionWrapper - Authentication wrapper
  • IQOptionStreamCandleGenerated - Candle data stream
  • IQOptionStreamOptionClose - Option close events stream
  • IQOptionStreamOptionTradersSentiment - Traders sentiment stream
  • IQOptionStreamUserAlerts - User alerts stream
  • WebSocketRepository - Repository for WebSocket operations
  • BinaryOrderStrategy - Strategy for binary orders
  • DigitalOrderStrategy - Strategy for digital orders

Helper Functions

  • iqOptionExpired(minutes) - Calculate expiration timestamp
  • LoggerFactory - Create logger instances
  • RequestIdGenerator - Generate unique request IDs
  • InputValidator - Validate input parameters
  • CandleValidator - Validate candle data structure
  • CurrencyValidator - Validate currency update messages
  • MarketHelper - Get market symbol/name from market ID

🔧 Configuration

Environment Variables

# Required
[email protected]
IQ_OPTION_PASSWORD=your-password

# Optional - Logging
LOG_LEVEL=info                    # debug, info, warn, error
LOG_DIR=./logs                    # Directory for log files
IQC_LOG_LEVEL=info                # Library-specific log level

Logging Configuration

The library uses Winston for logging. Configure via environment variables:

  • LOG_LEVEL - Global log level (default: info)
  • LOG_DIR - Directory for log files (optional, enables file logging)
  • IQC_LOG_LEVEL - Library-specific log level

🧪 Testing

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run sample application
npm run sample:iqoption

# Run quick example (3 markets)
npm run sample:quick

# Test historical candles functionality
npm run test:candles

# Test fetching 200 candles
npm run test:200candles

Note: Tests require valid IQ Option credentials set in environment variables:

  • TEST_IQ_OPTION_EMAIL or IQ_OPTION_EMAIL
  • TEST_IQ_OPTION_PASSWORD or IQ_OPTION_PASSWORD

📋 Requirements

  • Node.js >= 14.0.0
  • TypeScript >= 5.0.0 (for TypeScript projects)

🏗️ Architecture

This library follows SOLID principles and implements several design patterns:

  • Single Responsibility Principle - Each class has a single, well-defined purpose
  • Open/Closed Principle - Extensible through interfaces and strategies
  • Liskov Substitution Principle - Interfaces can be substituted
  • Interface Segregation - Focused, specific interfaces
  • Dependency Inversion - Dependencies injected via constructors

Design Patterns

  • Strategy Pattern - Different order execution strategies
  • Repository Pattern - Data access abstraction
  • Factory Pattern - Stream creation
  • Command Pattern - Encapsulated operations
  • Builder Pattern - Fluent object construction
  • Adapter Pattern - Stream interface unification

🔒 Security

  • Never commit credentials - Always use environment variables
  • Use .env file - Add .env to .gitignore
  • Validate inputs - All public methods validate inputs
  • Error handling - Comprehensive error handling prevents information leakage

📝 Examples

Complete Trading Bot Example

import {
  IQOptionApi,
  IQOptionMarket,
  IQOptionModel,
  IQOptionTime,
  IQOptionCurrencyType,
  IQOptionStreamCandleGenerated,
  IQOptionStreamOptionTradersSentiment,
  iqOptionExpired,
  LoggerFactory
} from 'iq-option-client';

const logger = LoggerFactory.getDefault();
const api = new IQOptionApi(
  process.env.IQ_OPTION_EMAIL!,
  process.env.IQ_OPTION_PASSWORD!
);

// Connect
const profile = await api.connectAsync();
const testBalance = profile.balances.find(
  b => b.type === IQOptionCurrencyType.TEST
);

// Setup sentiment stream
const sentimentStream = new IQOptionStreamOptionTradersSentiment(
  api.getIQOptionWs(),
  IQOptionMarket.EURUSD
);
await sentimentStream.startStream();

sentimentStream.on('data', async (data) => {
  if (data.value > 0.8) {
    logger.info('Strong buy signal detected');
    // Execute buy order
    await api.sendOrderBinary(
      IQOptionMarket.EURUSD_OTC,
      IQOptionModel.BUY,
      iqOptionExpired(1),
      testBalance!.id,
      90,
      10
    );
  }
});

// Setup candle stream for analysis
const candleStream = new IQOptionStreamCandleGenerated(
  api.getIQOptionWs(),
  IQOptionMarket.EURUSD,
  IQOptionTime.ONE_MINUTE
);
await candleStream.startStream();

candleStream.on('data', async (candle) => {
  // Perform technical analysis
  logger.debug('New candle received', { candle });
  
  // Get historical candles for backtesting
  try {
    const historicalCandles = await api.getCandles(
      candle.active_id,
      candle.size,
      candle.id - 100,  // Last 100 candles
      candle.id,
      true,
      true,
      30000  // Custom timeout for large requests
    );
    
    logger.info(`Retrieved ${historicalCandles.length} historical candles for analysis`);
  } catch (error) {
    logger.error('Failed to get historical candles', {}, error);
  }
});

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

This project is licensed under the ISC License - see the LICENSE file for details.

👤 Author

Wellington Rocha

🙏 Acknowledgments

  • IQ Option for providing the WebSocket API
  • All contributors and users of this library

⚠️ Disclaimer

This library is not officially affiliated with IQ Option. Use at your own risk. Trading involves substantial risk of loss. Only trade with money you can afford to lose.

📞 Support

For issues, questions, or contributions, please open an issue on GitHub.


Made with ❤️ by the community