Skip to content

Get Opened Orders and Positions Ticket IDs

Request: ticket IDs of all currently opened orders and positions (lightweight alternative to full details).

API Information:

  • Low-level API: MT5Account.opened_orders_tickets(...) (defined in package/MetaRpcMT5/helpers/mt5_account.py)
  • gRPC service: mt5_term_api.AccountHelper
  • Proto definition: OpenedOrdersTickets (defined in mt5-term-api-account-helper.proto)

RPC

  • Service: mt5_term_api.AccountHelper
  • Method: OpenedOrdersTickets(OpenedOrdersTicketsRequest) -> OpenedOrdersTicketsReply
  • Low-level client (generated): AccountHelperStub.OpenedOrdersTickets(request, metadata, timeout)

💬 Just the essentials

  • What it is. Get only the ticket IDs of opened orders and positions without full details.
  • Why you need it. Lightweight check for what orders/positions exist. More efficient than opened_orders().
  • When to use. Use this when you only need ticket IDs. Use opened_orders() for full details.

🎯 Purpose

Use it to get ticket IDs only:

  • Check which orders/positions are currently open
  • Track ticket IDs for later queries
  • Monitor for new/closed orders efficiently
  • Lighter payload than full opened_orders()
  • Quick existence check before fetching full details

📚 Tutorial

For a detailed line-by-line explanation with examples, see: -> opened_orders_tickets - How it works


Method Signature

async def opened_orders_tickets(
    self,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
) -> account_helper_pb2.OpenedOrdersTicketsData

Request message:

message OpenedOrdersTicketsRequest {
  // Empty - no parameters needed
}

Reply message:

message OpenedOrdersTicketsReply {
  oneof response {
    OpenedOrdersTicketsData data = 1;
    Error error = 2;
  }
}

message OpenedOrdersTicketsData {
  repeated int64 opened_orders_tickets = 1;
  repeated int64 opened_position_tickets = 2;
}

🔽 Input

Parameter Type Description
deadline datetime (optional) Deadline for the gRPC call (UTC datetime)
cancellation_event asyncio.Event (optional) Event to cancel the operation

No additional parameters - this method returns ticket IDs only.

Deadline options:

from datetime import datetime, timedelta

# With deadline
deadline = datetime.utcnow() + timedelta(seconds=3)
data = await account.opened_orders_tickets(deadline=deadline)

# Without deadline
data = await account.opened_orders_tickets()

⬆️ Output - OpenedOrdersTicketsData

Field Type Python Type Description
opened_orders_tickets repeated int64 list[int] List of pending order ticket IDs
opened_position_tickets repeated int64 list[int] List of open position ticket IDs

Return value: The method returns OpenedOrdersTicketsData object with both lists accessible as attributes.


No enums used by this method.


🧩 Notes & Tips

  • Automatic reconnection: All MT5Account methods have built-in protection against transient gRPC errors.
  • Lightweight: Only ticket IDs are returned - much smaller payload than opened_orders().
  • Two separate lists: Order tickets and position tickets are in separate lists.
  • Connection required: You must call connect_by_host_port() or connect_by_server_name() first.
  • Thread safety: Safe to call concurrently from multiple asyncio tasks.
  • UUID handling: The terminal instance UUID is auto-generated by the server if not provided. For explicit control (e.g., in streaming scenarios), pass id_=uuid4() to constructor.

🔗 Usage Examples

1) Get all ticket IDs

import asyncio
from datetime import datetime, timedelta
from MetaRpcMT5 import MT5Account

async def main():
    account = MT5Account(
        user=12345678,
        password="your_password",
        grpc_server="mt5.mrpc.pro:443"
    )

    await account.connect_by_server_name(
        server_name="YourBroker-Demo",
        base_chart_symbol="EURUSD"
    )

    try:
        deadline = datetime.utcnow() + timedelta(seconds=3)
        data = await account.opened_orders_tickets(deadline=deadline)

        print(f"Order tickets: {data.opened_orders_tickets}")
        print(f"Position tickets: {data.opened_position_tickets}")

    finally:
        await account.channel.close()

asyncio.run(main())

2) Check if ticket exists

async def ticket_exists(account: MT5Account, ticket: int) -> bool:
    """Check if ticket ID exists in opened orders/positions"""
    data = await account.opened_orders_tickets()

    exists = (
        ticket in data.opened_orders_tickets or
        ticket in data.opened_position_tickets
    )

    if exists:
        print(f"[OK] Ticket #{ticket} found")
    else:
        print(f"[INFO] Ticket #{ticket} not found")

    return exists

# Usage:
if await ticket_exists(account, 123456):
    print("Order/position still open")

3) Monitor for ticket changes

async def monitor_tickets(account: MT5Account, interval: float = 5.0):
    """Monitor for changes in ticket IDs"""
    previous_tickets = set()

    while True:
        try:
            data = await account.opened_orders_tickets()

            current_tickets = set(data.opened_orders_tickets + data.opened_position_tickets)

            if previous_tickets:
                new = current_tickets - previous_tickets
                closed = previous_tickets - current_tickets

                for ticket in new:
                    print(f"[+] New ticket: #{ticket}")
                for ticket in closed:
                    print(f"[-] Closed ticket: #{ticket}")

            previous_tickets = current_tickets

        except Exception as e:
            print(f"[ERROR] {e}")

        await asyncio.sleep(interval)

# Usage:
# await monitor_tickets(account, interval=5.0)

4) Get all tickets combined

async def get_all_tickets(account: MT5Account) -> list[int]:
    """Get all order and position tickets combined"""
    data = await account.opened_orders_tickets()

    all_tickets = list(data.opened_orders_tickets) + list(data.opened_position_tickets)

    print(f"[OK] Total tickets: {len(all_tickets)}")
    return all_tickets

# Usage:
tickets = await get_all_tickets(account)
print(f"All tickets: {tickets}")

5) Compare with previous snapshot

async def compare_tickets(
    account: MT5Account,
    previous_orders: list[int],
    previous_positions: list[int]
) -> dict:
    """Compare current tickets with previous snapshot"""
    data = await account.opened_orders_tickets()

    result = {
        "new_orders": list(set(data.opened_orders_tickets) - set(previous_orders)),
        "closed_orders": list(set(previous_orders) - set(data.opened_orders_tickets)),
        "new_positions": list(set(data.opened_position_tickets) - set(previous_positions)),
        "closed_positions": list(set(previous_positions) - set(data.opened_position_tickets))
    }

    if result["new_orders"]:
        print(f"[+] New orders: {result['new_orders']}")
    if result["closed_orders"]:
        print(f"[-] Closed orders: {result['closed_orders']}")
    if result["new_positions"]:
        print(f"[+] New positions: {result['new_positions']}")
    if result["closed_positions"]:
        print(f"[-] Closed positions: {result['closed_positions']}")

    return result

# Usage:
# prev_orders = [12345, 12346]
# prev_positions = [12347]
# changes = await compare_tickets(account, prev_orders, prev_positions)

Common Patterns

Quick count check

async def get_tickets_count(account: MT5Account) -> dict:
    """Get count of orders and positions"""
    data = await account.opened_orders_tickets()
    return {
        "orders": len(data.opened_orders_tickets),
        "positions": len(data.opened_position_tickets),
        "total": len(data.opened_orders_tickets) + len(data.opened_position_tickets)
    }

Ticket set operations

async def get_ticket_sets(account: MT5Account) -> tuple:
    """Get ticket IDs as sets for easy comparison"""
    data = await account.opened_orders_tickets()
    return (
        set(data.opened_orders_tickets),
        set(data.opened_position_tickets)
    )

📚 See also