Skip to content

Latest commit

 

History

History
672 lines (487 loc) · 16 KB

reference.md

File metadata and controls

672 lines (487 loc) · 16 KB
sidebar_position 1

BinaryOptionsTools API Reference

:::tip Skip the boilerplate Everything on this page is the manual path: you wire up the client, the candles, the risk checks and the deployment yourself. If you would rather go from idea to backtested strategy in an afternoon, ChipaEditor generates the strategy from a plain language description in CHTL, backtests it on historical data, and deploys it to a live broker connection. Free to start — then come back here when you need full control. :::

Complete API reference for BinaryOptionsTools with examples in all supported languages.

Installation

Python

pip install binaryoptionstoolsv2

JavaScript/TypeScript

The Node.js bindings are built from source; Node.js 18+ and a Rust toolchain are required.

cd nodejs
npm run build

Rust

[dependencies]
binary_options_tools = "0.2.17"
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"

Kotlin, Swift, Go, Ruby, C# (UniFFI)

These bindings are not published to any package registry — there is no Maven, NuGet, RubyGems or Go module to install, and no Swift package. They are generated from this repository with uniffi-bindgen (proc-macro based, no .udl file):

# supported languages: kotlin, swift, python, ruby
cargo run -p binary_options_tools_uni --bin uniffi-bindgen generate --library --language kotlin --out-dir out/kotlin
cargo run -p binary_options_tools_uni --bin uniffi-bindgen generate --library --language swift  --out-dir out/swift

# then add the generated sources plus the compiled library to your project
cargo build --release -p binary_options_tools_uni

Go and C# are not supported by the in-repo generator; use the community uniffi-bindgen-go / uniffi-bindgen-cs against the same compiled library. See crates/bindings_uniffi/README.md for the per-language build notes and the examples for the API shape.


Quick Start

Initialize Client

Python (Async)

import asyncio
from BinaryOptionsToolsV2 import PocketOptionAsync

async def main():
    async with PocketOptionAsync("your_ssid") as client:
        balance = await client.balance()
        print(f"Balance: ${balance}")

asyncio.run(main())

Python (Sync)

from BinaryOptionsToolsV2 import PocketOption

with PocketOption("your_ssid") as client:
    balance = client.balance()
    print(f"Balance: ${balance}")

JavaScript

const { PocketOption } = require("binary-options-tools");

async function main() {
  // The constructor connects in the background; every method awaits it.
  const client = new PocketOption("your_ssid");

  const balance = await client.balance();
  console.log(`Balance: $${balance}`);

  await client.shutdown();
}

main();

Rust

use binary_options_tools::pocketoption::PocketOption;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = PocketOption::new("your_ssid").await?;
    tokio::time::sleep(std::time::Duration::from_secs(2)).await;

    let balance = client.balance().await?;
    println!("Balance: ${}", balance);

    client.shutdown().await?;
    Ok(())
}

Trading Operations

Place a Call (Buy) Trade

Python

# Place a $1 call trade on EURUSD_otc for 60 seconds
trade_id, trade = await client.buy("EURUSD_otc", 1.0, 60)
print(f"Trade ID: {trade.id}")
print(f"Asset: {trade.asset}")
print(f"Amount: ${trade.amount}")

JavaScript

// Place a $1 call trade on EURUSD_otc for 60 seconds
const [tradeId, deal] = await client.buy("EURUSD_otc", 1.0, 60);
console.log(`Trade ID: ${tradeId}`);
console.log(`Asset: ${deal.asset}`);
console.log(`Amount: $${deal.amount}`);

Rust

// Place a $1 call trade on EURUSD_otc for 60 seconds
let trade = client.buy("EURUSD_otc", 60, 1.0).await?;
println!("Trade ID: {}", trade.id);
println!("Asset: {}", trade.asset);
println!("Amount: ${}", trade.amount);

Place a Put (Sell) Trade

Python

# Place a $1 put trade on EURUSD_otc for 60 seconds
trade_id, trade = await client.sell("EURUSD_otc", 1.0, 60)
print(f"Trade ID: {trade.id}")

JavaScript

// Place a $1 put trade on EURUSD_otc for 60 seconds
const [tradeId] = await client.sell("EURUSD_otc", 1.0, 60);
console.log(`Trade ID: ${tradeId}`);

Rust

// Place a $1 put trade on EURUSD_otc for 60 seconds
let trade = client.sell("EURUSD_otc", 60, 1.0).await?;
println!("Trade ID: {}", trade.id);

Check Trade Result

Python

# Check if a trade won or lost
result = await client.check_win(trade_id)
print(f"Result: {'WIN' if result.profit > 0 else 'LOSS'}")
print(f"Profit: ${result.profit}")

JavaScript

// Waits for the trade to settle, then reports it
const result = await client.result(tradeId);
console.log(`Result: ${result.profit > 0 ? "WIN" : "LOSS"}`);
console.log(`Profit: $${result.profit}`);

Rust

// Check if a trade won or lost
let result = client.result(trade.id).await?;
println!("Result: {}", if result.profit > 0 { "WIN" } else { "LOSS" });
println!("Profit: ${}", result.profit);

Account Management

Get Balance

Python

balance = await client.balance()
print(f"Current balance: ${balance:.2f}")

JavaScript

const balance = await client.balance();
console.log(`Current balance: $${balance.toFixed(2)}`);

Rust

let balance = client.balance().await?;
println!("Current balance: ${:.2}", balance);

Check if Demo Account

Python

is_demo = client.is_demo()
account_type = "Demo" if is_demo else "Real"
print(f"Account type: {account_type}")

JavaScript

const isDemo = await client.isDemo();
const accountType = isDemo ? "Demo" : "Real";
console.log(`Account type: ${accountType}`);

Rust

let is_demo = client.is_demo().await?;
let account_type = if is_demo { "Demo" } else { "Real" };
println!("Account type: {}", account_type);

Get Open Deals

Python

open_deals = await client.opened_deals()
print(f"Open trades: {len(open_deals)}")
for deal in open_deals:
    print(f"  {deal.asset}: ${deal.amount} ({deal.action})")

JavaScript

// Running deals, keyed by deal id
const openDeals = await client.openedDeals();
console.log(`Open trades: ${Object.keys(openDeals).length}`);
for (const deal of Object.values(openDeals)) {
  console.log(`  ${deal.asset}: $${deal.amount} (${deal.action})`);
}

Rust

let open_deals = client.get_opened_deals().await?;
println!("Open trades: {}", open_deals.len());
for deal in open_deals {
    println!("  {}: ${} ({})", deal.asset, deal.amount, deal.action);
}

Get Closed Deals

Python

closed_deals = await client.closed_deals()
print(f"Closed trades: {len(closed_deals)}")
for deal in closed_deals:
    result = "WIN" if deal.profit > 0 else "LOSS"
    print(f"  {deal.asset}: {result} (${deal.profit:.2f})")

JavaScript

// Settled deals, keyed by deal id
const closedDeals = await client.closedDeals();
console.log(`Closed trades: ${Object.keys(closedDeals).length}`);
for (const deal of Object.values(closedDeals)) {
  const result = deal.profit > 0 ? "WIN" : "LOSS";
  console.log(`  ${deal.asset}: ${result} ($${deal.profit.toFixed(2)})`);
}

Rust

let closed_deals = client.get_closed_deals().await?;
println!("Closed trades: {}", closed_deals.len());
for deal in closed_deals {
    let result = if deal.profit > 0 { "WIN" } else { "LOSS" };
    println!("  {}: {} (${})", deal.asset, result, deal.profit);
}

Market Data

Get Historical Candles

Note: Historical candles are fetched and manually compiled locally on the client from 1-second raw ticks. Timestamps are grouped strictly according to UTC calendar boundaries (timestamp / period * period), avoiding server-side candle time-alignment mismatches, gaps, or overlaps ("merges"). This applies to both .candles() (default 1000 periods lookback) and .compile_candles() (custom lookback period).

Python

# Get last 100 candles with 60-second period
candles = await client.get_candles("EURUSD_otc", 60, 100)
print(f"Retrieved {len(candles)} candles")
for candle in candles[:5]:  # Show first 5
    print(f"  Time: {candle.time}, Close: {candle.close}")

JavaScript

// 60-second candles, looking back one hour
const candles = await client.getCandles("EURUSD_otc", 60, 3600);
console.log(`Retrieved ${candles.length} candles`);
candles.slice(0, 5).forEach((candle) => {
  console.log(`  Time: ${candle.time}, Close: ${candle.close}`);
});

Rust

// Get last 100 candles with 60-second period
let candles = client.get_candles("EURUSD_otc", 60, 100).await?;
println!("Retrieved {} candles", candles.len());
for candle in candles.iter().take(5) {
    println!("  Time: {}, Close: {}", candle.time, candle.close);
}

Get Server Time

Python

server_time = await client.get_server_time()
print(f"Server timestamp: {server_time}")

JavaScript

const serverTime = await client.serverTime();
console.log(`Server timestamp: ${serverTime}`);

Rust

let server_time = client.server_time().await?;
println!("Server timestamp: {}", server_time);

Real-time Subscriptions

Subscribe to Asset

Python

# Subscribe to 60-second candles
subscription = await client.subscribe_symbol("EURUSD_otc")
print("Subscribed to EURUSD_otc")

# Iterate over candles
async for candle in subscription:
    print(f"Candle: {candle}")

JavaScript

// Subscribe to 60-second candles
const subscription = await client.subscribe("EURUSD_otc", 60);
console.log("Subscribed to EURUSD_otc");

// Receive candles (async iterator)
for await (const candle of subscription) {
  console.log(`Candle: ${JSON.stringify(candle)}`);
}

Rust

use binary_options_tools::pocketoption::candle::SubscriptionType;

// Subscribe to 60-second candles
let mut subscription = client
    .subscribe("EURUSD_otc", SubscriptionType::time(Duration::from_secs(60)))
    .await?;
println!("Subscribed to {}", subscription.asset());

// `SubscriptionStream` is not a `Stream`: it yields completed candles via receive()
loop {
    match subscription.receive().await {
        Ok(candle) => println!("Candle {} -> {}", candle.timestamp, candle.close),
        Err(e) => {
            eprintln!("stream ended: {e}");
            break;
        }
    }
}

Unsubscribe from Asset

Python

await client.unsubscribe("EURUSD_otc")
print("Unsubscribed from EURUSD_otc")

JavaScript

await client.unsubscribe("EURUSD_otc");
console.log("Unsubscribed from EURUSD_otc");

Rust

client.unsubscribe("EURUSD_otc").await?;
println!("Unsubscribed from EURUSD_otc");

Connection Management

Reconnect

Python

await client.reconnect()
await asyncio.sleep(2)  # Wait for reconnection
print("Reconnected to server")

JavaScript

await client.reconnect();
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log("Reconnected to server");

Rust

client.reconnect().await?;
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
println!("Reconnected to server");

Shutdown

Python

await client.shutdown()
print("Client shut down gracefully")

JavaScript

await client.shutdown();
console.log("Client shut down gracefully");

Rust

client.shutdown().await?;
println!("Client shut down gracefully");

Error Handling

Python

from BinaryOptionsToolsV2 import PocketOptionAsync, PocketError

try:
    client = await PocketOptionAsync("invalid_ssid")
    balance = await client.balance()
except PocketError as e:
    print(f"Error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

JavaScript

const { PocketOption } = require("binary-options-tools");

try {
  const client = new PocketOption("invalid_ssid");
  const balance = await client.balance();
} catch (e) {
  // The message is prefixed with the error kind, e.g.
  // "PocketOptionError: ..." or "TimeoutError: ...".
  console.log(`Error: ${e.message}`);
}

Rust

use binary_options_tools::error::PocketError;

match PocketOption::new("invalid_ssid").await {
    Ok(client) => {
        match client.balance().await {
            Ok(balance) => println!("Balance: {}", balance),
            Err(e) => eprintln!("Error: {}", e),
        }
    }
    Err(e) => eprintln!("Error: {}", e),
}

Best Practices

1. Always Wait for Initialization

Wait 2 seconds after creating the client:

  • Python: await asyncio.sleep(2)
  • Rust: tokio::time::sleep(Duration::from_secs(2)).await

JavaScript is the exception: every method already awaits the pending connection, so no sleep is needed. Use await PocketOption.create(ssid) when a failed connection should reject up front.

2. Always Shutdown Gracefully

Call shutdown() when done to clean up resources.

3. Check Demo vs Real Account

Always verify account type before trading with real money:

if not client.is_demo():
    print("WARNING: Using REAL account!")

4. Handle Errors Appropriately

Use try-catch blocks to handle connection errors and invalid operations.

5. Use Appropriate Timeouts

For time-sensitive operations, use result_with_timeout():

result = await client.check_win(trade_id, timeout_seconds=120)

Complete Examples

See the examples directory for complete working examples in each language:


Method naming by language

The Rust core is the source of truth; the bindings rename a few methods. Python optically renamed the trade-result and deal accessors, which is why a Python snippet cannot be pasted into the other examples:

Concept Rust / UniFFI Node Python
Place a trade buy(asset, time, amount) buy(asset, amount, time) buy(asset, amount, time)
Trade settled result(id) result(id) check_win(id, timeout_seconds=None)
Open trades get_opened_deals() openedDeals() / get_opened_deals() opened_deals()
Closed trades get_closed_deals() closedDeals() / get_closed_deals() closed_deals()
Broker clock server_time() serverTime() / server_time() get_server_time()
Subscribe subscribe(asset) subscribe(asset) subscribe_symbol(asset)

The time/amount order differs between Rust and Node/Python — the most common porting mistake. Node also exposes snake_case aliases for its camelCase methods (getOpenedDeals() / get_opened_deals(), checkWin() / check_win()), all documented in nodejs/index.d.ts.

For the complete, current list per language see Python API, nodejs/index.d.ts and the PocketOption impl.


Support


Version: 0.2.17
Last Updated: October 2026
Platform Support: PocketOption (Quick Trading)