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.
Maintainers
Readme
IQ Option Client
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-clientOr with yarn:
yarn add iq-option-client🚀 Quick Start
Basic Setup
- Install the package:
npm install iq-option-client- Create a
.envfile (or set environment variables):
[email protected]
IQ_OPTION_PASSWORD=your-password- 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:
- Get them from the candle stream (each candle has an
idfield) - Calculate them based on timestamps and candle size
- 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 clientIQOptionWs- WebSocket clientIQOptionWrapper- Authentication wrapperIQOptionStreamCandleGenerated- Candle data streamIQOptionStreamOptionClose- Option close events streamIQOptionStreamOptionTradersSentiment- Traders sentiment streamIQOptionStreamUserAlerts- User alerts streamWebSocketRepository- Repository for WebSocket operationsBinaryOrderStrategy- Strategy for binary ordersDigitalOrderStrategy- Strategy for digital orders
Helper Functions
iqOptionExpired(minutes)- Calculate expiration timestampLoggerFactory- Create logger instancesRequestIdGenerator- Generate unique request IDsInputValidator- Validate input parametersCandleValidator- Validate candle data structureCurrencyValidator- Validate currency update messagesMarketHelper- 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 levelLogging 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:200candlesNote: Tests require valid IQ Option credentials set in environment variables:
TEST_IQ_OPTION_EMAILorIQ_OPTION_EMAILTEST_IQ_OPTION_PASSWORDorIQ_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
.envfile - Add.envto.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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - 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
