Home Python Docs JavaScript Docs Rust Docs Examples API Reference Bot Services

Quick Start

Get up and running with BinaryOptionsToolsV2 in minutes

1

Install the Package

pip install BinaryOptionsToolsV2
2

Get Your SSID

Follow our SSID tutorial to extract your session ID from PocketOption

3

Start Trading

from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
import asyncio

async def main():
    api = PocketOptionAsync(your_ssid)
    balance = await api.balance()
    print(f"Balance: {balance}")

asyncio.run(main())

Trading Operations

Essential trading functions - buy, sell, and manage your trades

Basic Trading - Buy & Sell

Beginner

Learn how to place basic buy and sell orders with BinaryOptionsToolsV2

basic_trading.py
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
import asyncio

async def main(ssid: str):
    # The API automatically detects if the 'ssid' is for real or demo account
    api = PocketOptionAsync(ssid)
    
    # Place a BUY order
    (buy_id, buy_data) = await api.buy(
        asset="EURUSD_otc", 
        amount=1.0, 
        time=60, 
        check_win=False
    )
    print(f"Buy trade id: {buy_id}")
    print(f"Buy trade data: {buy_data}")
    
    # Place a SELL order  
    (sell_id, sell_data) = await api.sell(
        asset="EURUSD_otc", 
        amount=1.0, 
        time=60, 
        check_win=False
    )
    print(f"Sell trade id: {sell_id}")
    print(f"Sell trade data: {sell_data}")

if __name__ == '__main__':
    ssid = input('Please enter your ssid: ')
    asyncio.run(main(ssid))

Check Trade Results

Beginner

Monitor your trades and check win/loss results

check_win.py
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
import asyncio

async def main(ssid: str):
    # Initialize API
    api = PocketOptionAsync(ssid)
    
    # Place trades without automatic win checking
    (buy_id, _) = await api.buy(
        asset="EURUSD_otc", 
        amount=1.0, 
        time=15, 
        check_win=False
    )
    (sell_id, _) = await api.sell(
        asset="EURUSD_otc", 
        amount=1.0, 
        time=300, 
        check_win=False
    )
    print(f"Trade IDs: Buy={buy_id}, Sell={sell_id}")
    
    # Manually check trade results
    buy_data = await api.check_win(buy_id)
    print(f"Buy trade result: {buy_data['result']}")
    print(f"Buy trade data: {buy_data}")
    
    sell_data = await api.check_win(sell_id)
    print(f"Sell trade result: {sell_data['result']}")
    print(f"Sell trade data: {sell_data}")

if __name__ == '__main__':
    ssid = input('Please enter your ssid: ')
    asyncio.run(main(ssid))

Trade History & Open Positions

Intermediate

Retrieve and monitor your open and closed trades

trade_history.py
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
import asyncio

async def main(ssid: str):
    api = PocketOptionAsync(ssid)
    
    # Place some test trades
    _ = await api.buy(asset="EURUSD_otc", amount=1.0, time=60, check_win=False)
    _ = await api.sell(asset="EURUSD_otc", amount=1.0, time=60, check_win=False)
    
    # Get currently opened deals
    opened_deals = await api.opened_deals()
    print(f"Opened deals: {opened_deals}")
    print(f"Number of opened deals: {len(opened_deals)} (should be at least 2)")
    
    # Wait for trades to complete
    await asyncio.sleep(62)
    
    # Get closed deals history
    closed_deals = await api.closed_deals()
    print(f"Closed deals: {closed_deals}")
    print(f"Number of closed deals: {len(closed_deals)} (should be at least 2)")

if __name__ == '__main__':
    ssid = input('Please enter your ssid: ')
    asyncio.run(main(ssid))

Market Data

Access real-time and historical market data

Account Balance

Beginner

Retrieve your current account balance

get_balance.py
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
import asyncio

async def main(ssid: str):
    # The API automatically detects if the 'ssid' is for real or demo account
    api = PocketOptionAsync(ssid)
    await asyncio.sleep(5)  # Wait for connection
    
    balance = await api.balance()
    print(f"Current Balance: ${balance}")

if __name__ == '__main__':
    ssid = input('Please enter your ssid: ')
    asyncio.run(main(ssid))

Historical Candles

Intermediate

Fetch historical candlestick data for technical analysis

get_candles.py
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
import pandas as pd
import asyncio

async def main(ssid: str):
    api = PocketOptionAsync(ssid)    
    await asyncio.sleep(5)  # Wait for connection
    
    # Test different time frames and periods
    times = [3600 * i for i in range(1, 11)]  # 1-10 hours back
    time_frames = [1, 5, 15, 30, 60, 300]  # Different timeframes in seconds
    
    for time in times:
        for frame in time_frames:
            # Get candles data
            candles = await api.get_candles("EURUSD_otc", frame, time)
            
            # Convert to pandas DataFrame for analysis
            candles_df = pd.DataFrame.from_dict(candles)
            print(f"Timeframe: {frame}s, Period: {time}s")
            print(f"Candles DataFrame: {candles_df.head()}")
            print(f"Number of candles: {len(candles_df)}")
            print("-" * 50)

if __name__ == '__main__':
    ssid = input('Please enter your ssid: ')
    asyncio.run(main(ssid))

Payout Rates

Beginner

Get current payout rates for different assets

payout_rates.py
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
import asyncio

async def main(ssid: str):
    api = PocketOptionAsync(ssid)    
    await asyncio.sleep(5)  # Wait for connection
    
    # Get all available payouts
    full_payout = await api.payout()
    print(f"All Payouts: {full_payout}")
    
    # Get payouts for specific assets
    assets = ["EURUSD_otc", "EURUSD", "AEX25"]
    partial_payout = await api.payout(assets)
    print(f"Specific Assets Payout: {partial_payout}")
    
    # Get payout for single asset
    single_payout = await api.payout("EURUSD_otc")
    print(f"EURUSD_otc Payout: {single_payout}%")

if __name__ == '__main__':
    ssid = input('Please enter your ssid: ')
    asyncio.run(main(ssid))

Python Examples

Practical Python examples for binary options trading

Basic Operations

Beginner

Get balance, place orders, and check results

python
from BinaryOptionsToolsV2 import PocketOption

# Initialize client
client = PocketOption(ssid="your_ssid_here")

# Get account balance
balance = client.get_balance()
print(f"Current balance: ${balance:.2f}")

# Get candles for analysis
candles = client.get_candles("EURUSD_otc", 60, 50)
print(f"Retrieved {len(candles)} candles")

# Place a simple order
order = client.create_raw_order(
    asset="EURUSD_otc",
    amount=10.0,
    action="call",
    expiration=60
)

if order.success:
    print(f"Order placed! ID: {order.order_id}")
    
    # Wait for order to complete
    import time
    time.sleep(65)
    
    # Check result
    result = client.check_win(order.order_id)
    print(f"Order result: {result}")
else:
    print(f"Order failed: {order.message}")

Async Streaming

Intermediate

Real-time data streaming with async/await

python
import asyncio
from BinaryOptionsToolsV2 import AsyncPocketOption

async def stream_candles():
    client = AsyncPocketOption(ssid="your_ssid_here")
    
    print("Starting candle stream...")
    
    # Stream candles for multiple assets
    assets = ["EURUSD_otc", "GBPUSD_otc", "USDJPY_otc"]
    
    async def handle_asset(asset):
        async for candle in client.stream_candles(asset, 60):
            print(f"{asset}: {candle.close} (Volume: {candle.volume})")
            
            # Simple trading logic
            if candle.volume > 1000:
                await place_order_if_signal(client, asset, candle)
    
    # Stream multiple assets concurrently
    tasks = [handle_asset(asset) for asset in assets]
    await asyncio.gather(*tasks)

async def place_order_if_signal(client, asset, candle):
    """Place order based on simple signal"""
    # Example: Buy if closing higher than opening
    if candle.close > candle.open:
        try:
            order = await client.create_raw_order(
                asset=asset,
                amount=5.0,
                action="call",
                expiration=60
            )
            print(f"๐Ÿ“ˆ Placed CALL order for {asset}: {order.order_id}")
        except Exception as e:
            print(f"โŒ Order failed: {e}")

# Run the async function
asyncio.run(stream_candles())

Trading Bot

Advanced

Complete trading bot with risk management

python
import asyncio
import logging
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import Dict, List
from BinaryOptionsToolsV2 import AsyncPocketOption

@dataclass
class TradingConfig:
    max_concurrent_orders: int = 3
    risk_per_trade: float = 2.0  # Percentage of balance
    min_volume_threshold: float = 1000.0
    assets: List[str] = None

    def __post_init__(self):
        if self.assets is None:
            self.assets = ["EURUSD_otc", "GBPUSD_otc", "USDJPY_otc"]

class TradingBot:
    def __init__(self, ssid: str, config: TradingConfig):
        self.client = AsyncPocketOption(ssid)
        self.config = config
        self.active_orders: Dict[str, dict] = {}
        self.balance = 0.0
        
        # Setup logging
        logging.basicConfig(level=logging.INFO)
        self.logger = logging.getLogger(__name__)

    async def start(self):
        """Start the trading bot"""
        self.logger.info("๐Ÿš€ Trading bot starting...")
        
        # Get initial balance
        self.balance = await self.client.get_balance()
        self.logger.info(f"๐Ÿ’ฐ Initial balance: ${self.balance:.2f}")
        
        # Start monitoring orders and streaming data
        await asyncio.gather(
            self.monitor_orders(),
            self.stream_market_data()
        )

    async def stream_market_data(self):
        """Stream market data for all configured assets"""
        async def handle_asset_stream(asset):
            try:
                async for candle in self.client.stream_candles(asset, 60):
                    await self.analyze_candle(asset, candle)
            except Exception as e:
                self.logger.error(f"Stream error for {asset}: {e}")

        # Start streaming for all assets
        tasks = [handle_asset_stream(asset) for asset in self.config.assets]
        await asyncio.gather(*tasks, return_exceptions=True)

    async def analyze_candle(self, asset: str, candle):
        """Analyze candle and decide whether to trade"""
        # Check if we can place more orders
        if len(self.active_orders) >= self.config.max_concurrent_orders:
            return

        # Simple strategy: high volume + price movement
        price_change = abs(candle.close - candle.open) / candle.open * 100
        
        if (candle.volume > self.config.min_volume_threshold and 
            price_change > 0.1):
            
            # Determine direction
            action = "call" if candle.close > candle.open else "put"
            
            # Calculate position size
            amount = self.calculate_position_size()
            
            await self.place_order(asset, amount, action)

    def calculate_position_size(self) -> float:
        """Calculate position size based on risk management"""
        risk_amount = self.balance * (self.config.risk_per_trade / 100)
        return max(1.0, min(risk_amount, 50.0))  # Min $1, Max $50

    async def place_order(self, asset: str, amount: float, action: str):
        """Place a trading order"""
        try:
            order = await self.client.create_raw_order(
                asset=asset,
                amount=amount,
                action=action,
                expiration=60
            )
            
            if order.success:
                self.active_orders[order.order_id] = {
                    'asset': asset,
                    'amount': amount,
                    'action': action,
                    'timestamp': datetime.now()
                }
                
                self.logger.info(
                    f"๐Ÿ“Š Order placed: {asset} {action.upper()} "
                    f"${amount:.2f} (ID: {order.order_id})"
                )
            else:
                self.logger.error(f"โŒ Order failed: {order.message}")
                
        except Exception as e:
            self.logger.error(f"Order placement error: {e}")

    async def monitor_orders(self):
        """Monitor active orders and update results"""
        while True:
            if not self.active_orders:
                await asyncio.sleep(5)
                continue
                
            completed_orders = []
            
            for order_id, order_info in self.active_orders.items():
                # Check if order should be completed (after 60+ seconds)
                if datetime.now() - order_info['timestamp'] > timedelta(seconds=65):
                    try:
                        result = await self.client.check_win(order_id)
                        
                        if result != "pending":
                            completed_orders.append(order_id)
                            await self.handle_order_result(order_id, order_info, result)
                            
                    except Exception as e:
                        self.logger.error(f"Error checking order {order_id}: {e}")
            
            # Remove completed orders
            for order_id in completed_orders:
                del self.active_orders[order_id]
            
            # Update balance periodically
            try:
                self.balance = await self.client.get_balance()
            except Exception as e:
                self.logger.error(f"Error updating balance: {e}")
            
            await asyncio.sleep(10)

    async def handle_order_result(self, order_id: str, order_info: dict, result: str):
        """Handle completed order result"""
        asset = order_info['asset']
        amount = order_info['amount']
        action = order_info['action']
        
        if result == "win":
            profit = amount * 0.8  # Assuming 80% payout
            self.logger.info(
                f"โœ… WIN: {asset} {action.upper()} +${profit:.2f} "
                f"(Balance: ${self.balance:.2f})"
            )
        else:
            self.logger.info(
                f"โŒ LOSS: {asset} {action.upper()} -${amount:.2f} "
                f"(Balance: ${self.balance:.2f})"
            )

# Usage example
async def main():
    config = TradingConfig(
        max_concurrent_orders=2,
        risk_per_trade=1.5,
        assets=["EURUSD_otc", "GBPUSD_otc"]
    )
    
    bot = TradingBot(ssid="your_ssid_here", config=config)
    await bot.start()

if __name__ == "__main__":
    asyncio.run(main())

JavaScript Examples

Practical JavaScript examples for Node.js and browser environments

Basic Node.js Usage

Beginner

Simple trading operations in Node.js

javascript
const { PocketOption } = require('binaryoptionstools-v2');

async function main() {
    // Initialize the API client
    const api = new PocketOption('your_ssid_here');
    
    // Wait for connection to establish
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    try {
        // Get account balance
        const balance = await api.getBalance();
        console.log(`๐Ÿ’ฐ Balance: $${balance.toFixed(2)}`);
        
        // Get recent candles for analysis
        const candles = await api.getCandles('EURUSD_otc', 60, 20);
        console.log(`๐Ÿ“Š Retrieved ${candles.length} candles`);
        
        // Analyze last candle
        const lastCandle = candles[candles.length - 1];
        console.log(`๐Ÿ“ˆ Last candle: Open=${lastCandle.open}, Close=${lastCandle.close}`);
        
        // Place order based on simple logic
        const action = lastCandle.close > lastCandle.open ? 'call' : 'put';
        const orderResult = await api.createRawOrder({
            asset: 'EURUSD_otc',
            amount: 10.0,
            action: action,
            expiration: 60
        });
        
        if (orderResult.success) {
            console.log(`โœ… Order placed: ${action.toUpperCase()} (ID: ${orderResult.orderId})`);
            
            // Wait for order completion
            setTimeout(async () => {
                try {
                    const result = await api.checkWin(orderResult.orderId);
                    console.log(`๐ŸŽฏ Order result: ${result}`);
                } catch (error) {
                    console.error('Error checking result:', error.message);
                }
            }, 65000);
            
        } else {
            console.error(`โŒ Order failed: ${orderResult.message}`);
        }
        
    } catch (error) {
        console.error('Error:', error.message);
    }
}

main().catch(console.error);

Real-time Data Stream

Intermediate

Stream live market data with event handling

javascript
const { PocketOption } = require('binaryoptionstools-v2');
const EventEmitter = require('events');

class MarketDataStreamer extends EventEmitter {
    constructor(ssid) {
        super();
        this.api = new PocketOption(ssid);
        this.activeStreams = new Map();
        this.candleBuffer = new Map();
    }

    async initialize() {
        // Wait for connection
        await new Promise(resolve => setTimeout(resolve, 5000));
        console.log('๐Ÿ”— Connected to PocketOption');
    }

    async subscribeToAsset(asset, timeframe = 60) {
        try {
            console.log(`๐Ÿ“Š Subscribing to ${asset} (${timeframe}s)`);
            
            // Subscribe to symbol stream
            const stream = await this.api.subscribeSymbol(asset);
            this.activeStreams.set(asset, stream);
            
            // Process stream data
            this.processStream(asset, stream);
            
        } catch (error) {
            console.error(`Error subscribing to ${asset}:`, error.message);
            this.emit('error', { asset, error });
        }
    }

    async processStream(asset, stream) {
        try {
            for await (const data of stream) {
                // Emit raw data
                this.emit('tick', { asset, data });
                
                // Buffer candle data
                this.bufferCandleData(asset, data);
                
                // Check for trading signals
                this.analyzeData(asset, data);
            }
        } catch (error) {
            console.error(`Stream error for ${asset}:`, error);
            this.emit('streamError', { asset, error });
            
            // Attempt to reconnect after delay
            setTimeout(() => {
                console.log(`๐Ÿ”„ Reconnecting to ${asset}...`);
                this.subscribeToAsset(asset);
            }, 5000);
        }
    }

    bufferCandleData(asset, data) {
        if (!this.candleBuffer.has(asset)) {
            this.candleBuffer.set(asset, []);
        }
        
        const buffer = this.candleBuffer.get(asset);
        buffer.push({
            timestamp: Date.now(),
            price: data.price || data.close,
            volume: data.volume || 0,
            ...data
        });
        
        // Keep only last 50 data points
        if (buffer.length > 50) {
            buffer.shift();
        }
    }

    analyzeData(asset, data) {
        const buffer = this.candleBuffer.get(asset) || [];
        if (buffer.length < 10) return; // Need minimum data
        
        const recentPrices = buffer.slice(-10).map(d => d.price);
        const currentPrice = data.price || data.close;
        const avgPrice = recentPrices.reduce((a, b) => a + b) / recentPrices.length;
        
        // Simple momentum strategy
        const momentum = (currentPrice - avgPrice) / avgPrice * 100;
        
        if (Math.abs(momentum) > 0.1) { // 0.1% threshold
            this.emit('signal', {
                asset,
                action: momentum > 0 ? 'call' : 'put',
                strength: Math.abs(momentum),
                price: currentPrice,
                timestamp: Date.now()
            });
        }
    }

    async unsubscribe(asset) {
        const stream = this.activeStreams.get(asset);
        if (stream && stream.return) {
            await stream.return();
        }
        this.activeStreams.delete(asset);
        this.candleBuffer.delete(asset);
        console.log(`โŒ Unsubscribed from ${asset}`);
    }

    async cleanup() {
        console.log('๐Ÿงน Cleaning up streams...');
        for (const [asset] of this.activeStreams) {
            await this.unsubscribe(asset);
        }
    }
}

// Usage example
async function main() {
    const streamer = new MarketDataStreamer('your_ssid_here');
    
    // Event listeners
    streamer.on('tick', ({ asset, data }) => {
        console.log(`๐Ÿ“ˆ ${asset}: ${data.price || data.close}`);
    });
    
    streamer.on('signal', async ({ asset, action, strength, price }) => {
        console.log(`๐Ÿšจ Signal: ${asset} ${action.toUpperCase()} (${strength.toFixed(3)}% @ ${price})`);
        
        // Optional: Place order on signal
        // await placeOrder(asset, action, 5.0);
    });
    
    streamer.on('error', ({ asset, error }) => {
        console.error(`โŒ ${asset} error:`, error.message);
    });
    
    // Initialize and subscribe
    await streamer.initialize();
    await streamer.subscribeToAsset('EURUSD_otc');
    await streamer.subscribeToAsset('GBPUSD_otc');
    
    // Run for 5 minutes then cleanup
    setTimeout(async () => {
        await streamer.cleanup();
        console.log('โœ… Demo completed');
        process.exit(0);
    }, 300000); // 5 minutes
}

main().catch(console.error);

Browser Trading App

Advanced

Complete trading interface for web browsers

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Binary Options Trader</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/binaryoptionstools-v2@latest/dist/index.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #1a1a2e; color: white; }
        .container { max-width: 1200px; margin: 0 auto; }
        .header { display: flex; justify-content: between; align-items: center; margin-bottom: 20px; }
        .balance { font-size: 24px; font-weight: bold; color: #4CAF50; }
        .trading-panel { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; }
        .chart-container { background: #16213e; padding: 20px; border-radius: 10px; }
        .controls { background: #16213e; padding: 20px; border-radius: 10px; }
        .control-group { margin-bottom: 15px; }
        .control-group label { display: block; margin-bottom: 5px; }
        .control-group input, .control-group select { 
            width: 100%; padding: 8px; border-radius: 5px; border: 1px solid #333; 
            background: #0f172a; color: white; 
        }
        .btn { 
            padding: 10px 20px; border: none; border-radius: 5px; 
            cursor: pointer; font-size: 16px; margin: 5px; 
        }
        .btn-call { background: #4CAF50; color: white; }
        .btn-put { background: #f44336; color: white; }
        .btn:hover { opacity: 0.8; }
        .orders { margin-top: 20px; }
        .order { 
            background: #16213e; padding: 10px; margin: 5px 0; 
            border-radius: 5px; border-left: 4px solid #2196F3; 
        }
        .status { margin-top: 20px; padding: 10px; border-radius: 5px; }
        .status.connected { background: #4CAF50; }
        .status.error { background: #f44336; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Binary Options Trader</h1>
            <div class="balance" id="balance">Balance: $0.00</div>
        </div>
        
        <div class="status" id="status">Connecting...</div>
        
        <div class="trading-panel">
            <div class="chart-container">
                <canvas id="priceChart" width="800" height="400"></canvas>
            </div>
            
            <div class="controls">
                <div class="control-group">
                    <label>Asset:</label>
                    <select id="assetSelect">
                        <option value="EURUSD_otc">EUR/USD OTC</option>
                        <option value="GBPUSD_otc">GBP/USD OTC</option>
                        <option value="USDJPY_otc">USD/JPY OTC</option>
                    </select>
                </div>
                
                <div class="control-group">
                    <label>Amount ($):</label>
                    <input type="number" id="amountInput" value="10" step="1" min="1">
                </div>
                
                <div class="control-group">
                    <label>Expiration (seconds):</label>
                    <select id="expirationSelect">
                        <option value="60">1 minute</option>
                        <option value="120">2 minutes</option>
                        <option value="300">5 minutes</option>
                    </select>
                </div>
                
                <div style="text-align: center;">
                    <button class="btn btn-call" id="callBtn">๐Ÿ“ˆ CALL</button>
                    <button class="btn btn-put" id="putBtn">๐Ÿ“‰ PUT</button>
                </div>
                
                <div class="control-group">
                    <label>Current Price: <span id="currentPrice">-.----</span></label>
                    <label>Trend: <span id="trend">-</span></label>
                </div>
            </div>
        </div>
        
        <div class="orders">
            <h3>Active Orders</h3>
            <div id="ordersList"></div>
        </div>
    </div>

    <script>
        class TradingApp {
            constructor() {
                this.client = null;
                this.chart = null;
                this.priceData = [];
                this.activeOrders = new Map();
                this.currentAsset = 'EURUSD_otc';
                
                this.initializeChart();
                this.bindEvents();
                this.initialize();
            }

            async initialize() {
                try {
                    // Initialize client
                    this.client = new BinaryOptionsToolsV2.PocketOption({
                        ssid: prompt('Enter your SSID:') || 'demo_ssid'
                    });
                    
                    await this.connect();
                    this.updateStatus('Connected', 'connected');
                    
                    // Start data stream
                    this.startDataStream();
                    
                    // Update balance
                    await this.updateBalance();
                    
                } catch (error) {
                    this.updateStatus(`Error: ${error.message}`, 'error');
                }
            }

            async connect() {
                // Wait for connection
                await new Promise(resolve => setTimeout(resolve, 3000));
            }

            updateStatus(message, type = '') {
                const statusEl = document.getElementById('status');
                statusEl.textContent = message;
                statusEl.className = `status ${type}`;
            }

            async updateBalance() {
                try {
                    const balance = await this.client.getBalance();
                    document.getElementById('balance').textContent = `Balance: $${balance.toFixed(2)}`;
                } catch (error) {
                    console.error('Balance update error:', error);
                }
            }

            initializeChart() {
                const ctx = document.getElementById('priceChart').getContext('2d');
                this.chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Price',
                            data: [],
                            borderColor: '#2196F3',
                            backgroundColor: 'rgba(33, 150, 243, 0.1)',
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { labels: { color: 'white' } }
                        },
                        scales: {
                            x: { ticks: { color: 'white' }, grid: { color: '#333' } },
                            y: { ticks: { color: 'white' }, grid: { color: '#333' } }
                        }
                    }
                });
            }

            async startDataStream() {
                try {
                    const stream = await this.client.subscribeSymbol(this.currentAsset);
                    
                    for await (const data of stream) {
                        this.updatePriceData(data);
                    }
                } catch (error) {
                    console.error('Stream error:', error);
                    setTimeout(() => this.startDataStream(), 5000);
                }
            }

            updatePriceData(data) {
                const price = data.price || data.close || Math.random() * 1.2 + 1.1;
                const time = new Date().toLocaleTimeString();
                
                this.priceData.push({ time, price });
                if (this.priceData.length > 50) {
                    this.priceData.shift();
                }
                
                // Update chart
                this.chart.data.labels = this.priceData.map(d => d.time);
                this.chart.data.datasets[0].data = this.priceData.map(d => d.price);
                this.chart.update('none');
                
                // Update current price
                document.getElementById('currentPrice').textContent = price.toFixed(5);
                
                // Update trend
                if (this.priceData.length > 1) {
                    const prev = this.priceData[this.priceData.length - 2].price;
                    const trend = price > prev ? '๐Ÿ“ˆ UP' : price < prev ? '๐Ÿ“‰ DOWN' : 'โžก๏ธ FLAT';
                    document.getElementById('trend').textContent = trend;
                }
            }

            bindEvents() {
                document.getElementById('callBtn').addEventListener('click', () => this.placeOrder('call'));
                document.getElementById('putBtn').addEventListener('click', () => this.placeOrder('put'));
                
                document.getElementById('assetSelect').addEventListener('change', (e) => {
                    this.currentAsset = e.target.value;
                    this.startDataStream();
                });
            }

            async placeOrder(action) {
                const amount = parseFloat(document.getElementById('amountInput').value);
                const expiration = parseInt(document.getElementById('expirationSelect').value);
                
                if (!amount || amount < 1) {
                    alert('Please enter a valid amount');
                    return;
                }
                
                try {
                    const order = await this.client.createRawOrder({
                        asset: this.currentAsset,
                        amount: amount,
                        action: action,
                        expiration: expiration
                    });
                    
                    if (order.success) {
                        this.addOrder(order.orderId, {
                            asset: this.currentAsset,
                            amount: amount,
                            action: action,
                            expiration: expiration,
                            timestamp: Date.now()
                        });
                        
                        await this.updateBalance();
                    } else {
                        alert(`Order failed: ${order.message}`);
                    }
                } catch (error) {
                    alert(`Error placing order: ${error.message}`);
                }
            }

            addOrder(orderId, orderInfo) {
                this.activeOrders.set(orderId, orderInfo);
                
                const orderDiv = document.createElement('div');
                orderDiv.className = 'order';
                orderDiv.id = `order-${orderId}`;
                orderDiv.innerHTML = `
                    <strong>${orderInfo.asset}</strong> 
                    ${orderInfo.action.toUpperCase()} 
                    $${orderInfo.amount} 
                    (${orderInfo.expiration}s)
                    <span style="float: right;">โณ Pending</span>
                `;
                
                document.getElementById('ordersList').appendChild(orderDiv);
                
                // Check result after expiration
                setTimeout(async () => {
                    await this.checkOrderResult(orderId);
                }, (orderInfo.expiration + 5) * 1000);
            }

            async checkOrderResult(orderId) {
                try {
                    const result = await this.client.checkWin(orderId);
                    const orderDiv = document.getElementById(`order-${orderId}`);
                    
                    if (orderDiv) {
                        const status = result === 'win' ? 'โœ… WIN' : result === 'lose' ? 'โŒ LOSS' : 'โณ Pending';
                        const color = result === 'win' ? '#4CAF50' : result === 'lose' ? '#f44336' : '#2196F3';
                        
                        orderDiv.style.borderLeftColor = color;
                        orderDiv.querySelector('span').textContent = status;
                        
                        if (result !== 'pending') {
                            this.activeOrders.delete(orderId);
                            await this.updateBalance();
                        }
                    }
                } catch (error) {
                    console.error(`Error checking order ${orderId}:`, error);
                }
            }
        }

        // Initialize the trading app
        window.addEventListener('load', () => {
            new TradingApp();
        });
    </script>
</body>
</html>

Rust Examples

High-performance Rust examples for professional trading

Basic Trading

Beginner

Basic trading operations with error handling

rust
use binary_options_tools_v2::{
    PocketOption, OrderOptions, Result, Error, ErrorKind
};

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize client with error handling
    let client = match PocketOption::new("your_ssid_here").await {
        Ok(client) => {
            println!("โœ… Connected to PocketOption");
            client
        }
        Err(e) => {
            eprintln!("โŒ Connection failed: {}", e);
            return Err(e);
        }
    };

    // Get account balance
    match client.get_balance().await {
        Ok(balance) => println!("๐Ÿ’ฐ Balance: ${:.2}", balance),
        Err(e) => eprintln!("Error getting balance: {}", e),
    }

    // Get candles for analysis
    let candles = client.get_candles("EURUSD_otc", 60, 20).await?;
    println!("๐Ÿ“Š Retrieved {} candles", candles.len());

    // Analyze trend
    if let (Some(first), Some(last)) = (candles.first(), candles.last()) {
        let trend = if last.close > first.close { "๐Ÿ“ˆ Uptrend" } else { "๐Ÿ“‰ Downtrend" };
        println!("Trend analysis: {}", trend);

        // Place order based on trend
        let action = if last.close > first.close { "call" } else { "put" };
        
        let order_options = OrderOptions {
            asset: "EURUSD_otc".to_string(),
            amount: 10.0,
            action: action.to_string(),
            expiration: 60,
        };

        match client.create_raw_order(order_options).await {
            Ok(order_result) => {
                if order_result.success {
                    println!("โœ… Order placed: {} (ID: {})", action.to_uppercase(), order_result.order_id);
                    
                    // Wait for order completion
                    tokio::time::sleep(tokio::time::Duration::from_secs(65)).await;
                    
                    // Check result
                    match client.check_win(&order_result.order_id).await {
                        Ok(result) => println!("๐ŸŽฏ Order result: {:?}", result),
                        Err(e) => eprintln!("Error checking result: {}", e),
                    }
                } else {
                    eprintln!("โŒ Order failed: {}", order_result.message);
                }
            }
            Err(e) => eprintln!("Error placing order: {}", e),
        }
    }

    Ok(())
}

High-Performance Streaming

Intermediate

Concurrent streams with advanced processing

rust
use binary_options_tools_v2::{PocketOption, StreamEvent, OrderOptions};
use futures::{StreamExt, stream::SelectAll};
use tokio::sync::mpsc;
use std::collections::HashMap;
use std::time::{Duration, Instant};

#[derive(Debug, Clone)]
struct MarketData {
    asset: String,
    price: f64,
    timestamp: Instant,
    volume: f64,
}

#[derive(Debug)]
struct TradingSignal {
    asset: String,
    action: String,
    strength: f64,
    price: f64,
}

struct HighPerformanceTrader {
    client: PocketOption,
    price_buffer: HashMap>,
    signal_sender: mpsc::UnboundedSender,
}

impl HighPerformanceTrader {
    async fn new(ssid: &str) -> Result> {
        let client = PocketOption::new(ssid).await?;
        let (signal_sender, _) = mpsc::unbounded_channel();
        
        Ok(Self {
            client,
            price_buffer: HashMap::new(),
            signal_sender,
        })
    }

    async fn start_multi_asset_streaming(&mut self, assets: Vec<&str>) -> Result<(), Box> {
        // Create streams for all assets
        let mut streams = SelectAll::new();
        
        for asset in assets {
            match self.client.stream_candles(asset, 60).await {
                Ok(stream) => {
                    let asset_stream = stream.map(move |event| (asset.to_string(), event));
                    streams.push(asset_stream);
                    println!("๐Ÿ“Š Started stream for {}", asset);
                }
                Err(e) => eprintln!("Failed to start stream for {}: {}", asset, e),
            }
        }

        // Set up signal processing
        let mut signal_receiver = self.setup_signal_processor().await;

        // Process streams concurrently
        tokio::select! {
            _ = self.process_market_streams(streams) => {},
            _ = self.process_trading_signals(&mut signal_receiver) => {},
        }

        Ok(())
    }

    async fn process_market_streams(&mut self, mut streams: SelectAll)> + Unpin>) {
        while let Some((asset, event_result)) = streams.next().await {
            match event_result {
                Ok(StreamEvent::Candle(candle)) => {
                    let market_data = MarketData {
                        asset: asset.clone(),
                        price: candle.close,
                        timestamp: Instant::now(),
                        volume: candle.volume,
                    };

                    // Buffer the data
                    self.buffer_market_data(market_data.clone());

                    // Analyze for signals
                    if let Some(signal) = self.analyze_market_data(&asset, &market_data) {
                        let _ = self.signal_sender.send(signal);
                    }
                }
                Ok(StreamEvent::Error(e)) => {
                    eprintln!("Stream error for {}: {}", asset, e);
                }
                Err(e) => {
                    eprintln!("Failed to receive event for {}: {}", asset, e);
                }
            }
        }
    }

    fn buffer_market_data(&mut self, data: MarketData) {
        let buffer = self.price_buffer.entry(data.asset.clone()).or_insert_with(Vec::new);
        buffer.push(data);

        // Keep only last 100 data points for performance
        if buffer.len() > 100 {
            buffer.drain(0..50); // Remove first 50 elements
        }
    }

    fn analyze_market_data(&self, asset: &str, current_data: &MarketData) -> Option {
        let buffer = self.price_buffer.get(asset)?;
        if buffer.len() < 20 { return None; } // Need minimum data

        // Calculate moving averages
        let short_ma = Self::calculate_moving_average(&buffer[buffer.len()-10..]);
        let long_ma = Self::calculate_moving_average(&buffer[buffer.len()-20..]);

        // Calculate momentum
        let momentum = (short_ma - long_ma) / long_ma * 100.0;

        // Generate signal if momentum is strong enough
        if momentum.abs() > 0.05 { // 0.05% threshold
            Some(TradingSignal {
                asset: asset.to_string(),
                action: if momentum > 0.0 { "call".to_string() } else { "put".to_string() },
                strength: momentum.abs(),
                price: current_data.price,
            })
        } else {
            None
        }
    }

    async fn setup_signal_processor(&self) -> mpsc::UnboundedReceiver {
        let (sender, receiver) = mpsc::unbounded_channel();
        self.signal_sender.clone(); // Store sender for later use
        receiver
    }

    async fn process_trading_signals(&self, receiver: &mut mpsc::UnboundedReceiver) {
        let mut active_orders = HashMap::new();
        let mut last_order_time = HashMap::new();

        while let Some(signal) = receiver.recv().await {
            // Rate limiting: only one order per asset every 2 minutes
            let now = Instant::now();
            if let Some(&last_time) = last_order_time.get(&signal.asset) {
                if now.duration_since(last_time) < Duration::from_secs(120) {
                    continue;
                }
            }

            // Check if we already have an active order for this asset
            if active_orders.contains_key(&signal.asset) {
                continue;
            }

            println!("๐Ÿšจ Signal: {} {} (strength: {:.3}%)", 
                signal.asset, signal.action.to_uppercase(), signal.strength);

            // Place order
            match self.place_order_from_signal(&signal).await {
                Ok(order_id) => {
                    active_orders.insert(signal.asset.clone(), order_id);
                    last_order_time.insert(signal.asset.clone(), now);
                }
                Err(e) => eprintln!("Failed to place order: {}", e),
            }
        }
    }

    async fn place_order_from_signal(&self, signal: &TradingSignal) -> Result> {
        let order_options = OrderOptions {
            asset: signal.asset.clone(),
            amount: 10.0, // Fixed amount for this example
            action: signal.action.clone(),
            expiration: 60,
        };

        let order_result = self.client.create_raw_order(order_options).await?;
        
        if order_result.success {
            println!("โœ… Order placed: {} {} $10 (ID: {})", 
                signal.asset, signal.action.to_uppercase(), order_result.order_id);
            
            // Schedule result check
            let client = self.client.clone();
            let order_id = order_result.order_id.clone();
            let asset = signal.asset.clone();
            
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_secs(65)).await;
                match client.check_win(&order_id).await {
                    Ok(result) => {
                        let emoji = match result.as_str() {
                            "win" => "โœ…",
                            "lose" => "โŒ", 
                            _ => "โณ"
                        };
                        println!("{} {} order result: {}", emoji, asset, result);
                    }
                    Err(e) => eprintln!("Error checking order {}: {}", order_id, e),
                }
            });
            
            Ok(order_result.order_id)
        } else {
            Err(format!("Order failed: {}", order_result.message).into())
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box> {
    println!("๐Ÿš€ Starting high-performance trading system...");

    let mut trader = HighPerformanceTrader::new("your_ssid_here").await?;
    
    let assets = vec!["EURUSD_otc", "GBPUSD_otc", "USDJPY_otc", "AUDUSD_otc"];
    
    trader.start_multi_asset_streaming(assets).await?;

    Ok(())
}

Ready to Build Your Trading Bot?

Professional bot development services available at chipa.tech