Skip to content

API Reference

mt4_account

MT4Account

Source code in package/MetaRpcMT4/mt4_account.py
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
class MT4Account:
    def __init__(self, user: int, password: str, grpc_server: Optional[str] = None, id_: Optional[str] = None):
        self.user = user
        self.password = password
        self.grpc_server = grpc_server or "mt4.mrpc.pro:443"   # default server
        self.id = id_

        # Async gRPC secure channel (TLS)
        self.channel = grpc.aio.secure_channel(
            self.grpc_server,
            grpc.ssl_channel_credentials()
        )

        # Init stubs directly (like in C#)
        self.connection_client = connection_pb2_grpc.ConnectionStub(self.channel)
        self.subscription_client = subscriptions_pb2_grpc.SubscriptionServiceStub(self.channel)
        self.account_client = account_helper_pb2_grpc.AccountHelperStub(self.channel)
        self.trade_client = trading_helper_pb2_grpc.TradingHelperStub(self.channel)
        self.market_info_client = market_info_pb2_grpc.MarketInfoStub(self.channel)

        # Connection state
        self.host = None
        self.port = None
        self.server_name = None
        self.base_chart_symbol = None
        self.connect_timeout_seconds = 30


    # === Utility: headers ===
    def get_headers(self):
        return [("id", self.id)]

    # === Utility: reconnect ===
    async def reconnect(self, deadline: Optional[datetime] = None):
        if self.server_name:
            await self.connect_by_server_name(self.server_name, self.base_chart_symbol or "EURUSD",
                                              True, self.connect_timeout_seconds, deadline)
        elif self.host:
            await self.connect_by_host_port(self.host, self.port or 443,
                                            self.base_chart_symbol or "EURUSD", True,
                                            self.connect_timeout_seconds, deadline)

    # === Core retry wrapper ===
    async def execute_with_reconnect(
        self,
        grpc_call: Callable[[list[tuple[str, str]]], Awaitable[Any]],
        error_selector: Callable[[Any], Optional[Any]],
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        while cancellation_event is None or not cancellation_event.is_set():
            headers = self.get_headers()
            try:
                res = await grpc_call(headers)
            except grpc.aio.AioRpcError as ex:
                if ex.code() == grpc.StatusCode.UNAVAILABLE:
                    await asyncio.sleep(0.5)
                    await self.reconnect(deadline)
                    continue
                raise

            error = error_selector(res)
            if error and error.error_code in ("TERMINAL_INSTANCE_NOT_FOUND", "TERMINAL_REGISTRY_TERMINAL_NOT_FOUND"):
                await asyncio.sleep(0.5)
                await self.reconnect(deadline)
                continue

            if res.HasField("error") and res.error.error_message:
                raise ApiExceptionMT4(res.error)

            return res

        raise asyncio.CancelledError("The operation was canceled by the caller.")

    # === Connect methods ===
    async def connect_by_host_port(
        self,
        host: str,
        port: int = 443,
        base_chart_symbol: str = "EURUSD",
        wait_for_terminal_is_alive: bool = True,
        timeout_seconds: int = 30,
        deadline: Optional[datetime] = None,
    ):
        #Build connect request (from your proto)
        request = connection_pb2.ConnectRequest(
            user=self.user,
            password=self.password,
            host=host,
            port=port,
            base_chart_symbol=base_chart_symbol,
            wait_for_terminal_is_alive=wait_for_terminal_is_alive,
            terminal_readiness_waiting_timeout_seconds=timeout_seconds,
        )

        headers = []
        if self.id:
            headers.append(("id", str(self.id)))

        res = await self.connection_client.Connect(
            request,
            metadata=headers,
            timeout=30.0 if deadline is None else (deadline - datetime.utcnow()).total_seconds(),
        )

        if res.HasField("error") and res.error.error_message:
            raise ApiExceptionMT4(res.error)

        # Save state
        self.host = host
        self.port = port
        self.base_chart_symbol = base_chart_symbol
        self.connect_timeout_seconds = timeout_seconds
        self.id = res.data.terminalInstanceGuid

    async def connect_by_server_name(
        self,
        server_name: str,
        base_chart_symbol: str = "EURUSD",
        wait_for_terminal_is_alive: bool = True,
        timeout_seconds: int = 30,
        deadline: Optional[datetime] = None,
    ):
        # Build connect request (from your proto)
        request = connection_pb2.ConnectExRequest(
            user=self.user,
            password=self.password,
            mt_cluster_name=server_name,
            base_chart_symbol=base_chart_symbol,
            terminal_readiness_waiting_timeout_seconds=timeout_seconds,
        )

        headers = []
        if self.id:
            headers.append(("id", str(self.id)))
        res = await self.connection_client.ConnectEx(
            request,
            metadata=headers,
            timeout=30.0 if deadline is None else (deadline - datetime.utcnow()).total_seconds(),
        )

        if res.HasField("error") and res.error.error_message:
            raise ApiExceptionMT4(res.error)

        # Save state
        self.server_name = server_name
        self.base_chart_symbol = base_chart_symbol
        self.connect_timeout_seconds = timeout_seconds
        self.id = res.data.terminal_instance_guid


#
#    Account helper --------------------------------------------------------------------------------------------------------
#    

    async def account_summary(
        self,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Gets the summary information for a trading account asynchronously.

        Args:
            deadline (datetime, optional): Deadline after which the request will be canceled
                if not completed.
            cancellation_event (asyncio.Event, optional): Event to cancel the request.

        Returns:
            AccountSummaryData: The server's response containing account summary data.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an error in the response.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        """
        if not (self.host or self.server_name):
            raise ConnectExceptionMT4("Please call connect method first")

        request = account_helper_pb2.AccountSummaryRequest()

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = (deadline - datetime.utcnow()).total_seconds()
                if timeout < 0:
                    timeout = 0
            return await self.account_client.AccountSummary(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )

        return res.data

    async def opened_orders(
        self,
        sort_mode: account_helper_pb2.EnumOpenedOrderSortType = account_helper_pb2.EnumOpenedOrderSortType.SORT_BY_OPEN_TIME_ASC,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Gets the currently opened orders and positions for the connected account asynchronously.

        Args:
            sort_mode (EnumOpenedOrderSortType): The sort mode for the opened orders
                (e.g. SORT_BY_OPEN_TIME_ASC, SORT_BY_ORDER_TICKET_ID_DESC).
            deadline (datetime, optional): Deadline after which the request will be canceled
                if not completed.
            cancellation_event (asyncio.Event, optional): Event to cancel the request.

        Returns:
            OpenedOrdersData: The result containing opened orders and positions.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an error in the response.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        # Build request
        request = account_helper_pb2.OpenedOrdersRequest(sort_type=sort_mode)

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = (deadline - datetime.utcnow()).total_seconds()
                if timeout < 0:
                    timeout = 0
            return await self.account_client.OpenedOrders(
                request,
                metadata=headers,
                timeout=timeout,
            )

        # Execute with automatic reconnect logic
        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )

        return res.data


    async def opened_orders_tickets(
        self,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Gets the list of tickets for all currently opened orders.

        Returns:
            OpenedOrdersTicketsData: The result containing the list of tickets.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an error in the response.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        request = account_helper_pb2.OpenedOrdersTicketsRequest()

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = (deadline - datetime.utcnow()).total_seconds()
                if timeout < 0:
                    timeout = 0
            return await self.account_client.OpenedOrdersTickets(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )

        return res.data


    async def orders_history(
        self,
        sort_mode: account_helper_pb2.EnumOrderHistorySortType = account_helper_pb2.EnumOrderHistorySortType.HISTORY_SORT_BY_CLOSE_TIME_DESC,
        from_time: Optional[datetime] = None,
        to_time: Optional[datetime] = None,
        page_number: Optional[int] = None,
        items_per_page: Optional[int] = None,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Gets the order history for the connected account.

        Args:
            sort_mode (EnumOrderHistorySortType): Sorting mode for orders.
            from_time (datetime, optional): Start of the history period.
            to_time (datetime, optional): End of the history period.
            page_number (int, optional): Page number for pagination.
            items_per_page (int, optional): Items per page.

        Returns:
            OrdersHistoryData: The result containing historical orders.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an error in the response.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        # Convert datetime → Timestamp (protobuf)
        ts_from = None
        ts_to = None
        if from_time:
            ts_from = Timestamp()
            ts_from.FromDatetime(from_time)
        if to_time:
            ts_to = Timestamp()
            ts_to.FromDatetime(to_time)

        request = account_helper_pb2.OrdersHistoryRequest(
            input_sort_mode=sort_mode,
            input_from=ts_from,
            input_to=ts_to,
            page_number=page_number,
            items_per_page=items_per_page,
        )

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = (deadline - datetime.utcnow()).total_seconds()
                if timeout < 0:
                    timeout = 0
            return await self.account_client.OrdersHistory(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )

        return res.data


    async def symbol_params_many(
        self,
        symbol_name: Optional[str] = None,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Retrieves symbol parameters (for one or all symbols).

        Args:
            symbol_name (str, optional): Symbol name. If None, returns all.

        Returns:
            SymbolParamsManyData: The result containing symbol parameters.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an error in the response.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        request = account_helper_pb2.SymbolParamsManyRequest(symbol_name=symbol_name or "")

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = (deadline - datetime.utcnow()).total_seconds()
                if timeout < 0:
                    timeout = 0
            return await self.account_client.SymbolParamsMany(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )

        return res.data


    async def tick_value_with_size(
        self,
        symbol_names: list[str],
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Gets tick value, tick size, and contract size for multiple symbols.

        Args:
            symbol_names (list[str]): List of symbol names.

        Returns: 
            TickValueWithSizeData: The result containing tick values and sizes.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an error in the response.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        request = account_helper_pb2.TickValueWithSizeRequest(symbol_names=symbol_names)

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = (deadline - datetime.utcnow()).total_seconds()
                if timeout < 0:
                    timeout = 0
            return await self.account_client.TickValueWithSize(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )

        return res.data

#
#    Streams --------------------------------------------------------------------------------------------------------
#    

    async def execute_stream_with_reconnect(
        self,
        request: Any,
        stream_invoker: Callable[[Any, list[tuple[str, str]]], grpc.aio.StreamStreamCall],
        get_error: Callable[[Any], Optional[Any]],
        get_data: Callable[[Any], Any],
        cancellation_event: Optional[asyncio.Event] = None,
    ) -> AsyncGenerator[Any, None]:
        """
        Executes a gRPC server-streaming call with automatic reconnection logic on recoverable errors.

        Args:
            request: The request object to initiate the stream with.
            stream_invoker (Callable): A function that opens the stream. It receives the request and metadata headers,
                and returns an async streaming call.
            get_error (Callable): A function that extracts the error object (if any) from a reply.
                Return an object with .error_code == "TERMINAL_INSTANCE_NOT_FOUND" to trigger reconnect,
                or any non-null error to raise ApiExceptionMT5.
            get_data (Callable): A function that extracts the data object from a reply. If it returns None, the
                message is skipped.
            cancellation_event (asyncio.Event, optional): Event to cancel streaming and reconnection attempts.

        Yields:
            Extracted data items streamed from the server.

        Raises:
            ConnectExceptionMT4: If reconnection logic fails due to missing account context.
            ApiExceptionMT4: When the stream response contains a known API error.
            grpc.aio.AioRpcError: If a non-recoverable gRPC error occurs.
        """
        while cancellation_event is None or not cancellation_event.is_set():
            reconnect_required = False
            stream = None
            try:
                stream = stream_invoker(request, self.get_headers())
                async for reply in stream:
                    error = get_error(reply)

                    if error and error.error_code in (
                        "TERMINAL_INSTANCE_NOT_FOUND",
                        "TERMINAL_REGISTRY_TERMINAL_NOT_FOUND",
                    ):
                        reconnect_required = True
                        break

                    if error and getattr(error, "message", None):
                        raise ApiExceptionMT4(error)

                    data = get_data(reply)
                    if data is not None:
                        yield data

            except grpc.aio.AioRpcError as ex:
                if ex.code() == grpc.StatusCode.UNAVAILABLE:
                    reconnect_required = True
                else:
                    raise

            finally:
                if stream:
                    stream.cancel()  # close stream properly

            if reconnect_required:
                await asyncio.sleep(0.5)
                await self.reconnect()
            else:
                break


    async def on_symbol_tick(
        self,
        symbols: list[str],
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Subscribes to real-time tick data for specified symbols.

        Args:
            symbols (list[str]): The symbol names to subscribe to.
            cancellation_event (asyncio.Event, optional): Event to cancel streaming.

        Yields:
            OnSymbolTickData: Async stream of tick data responses.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an error in the stream.
            grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
        """
        if not self.id:
            raise ConnectExceptionMT4("Please call connect method first")

        request = subscriptions_pb2.OnSymbolTickRequest()
        request.symbol_names.extend(symbols)

        async for data in self.execute_stream_with_reconnect(
            request=request,
            stream_invoker=lambda req, headers: self.subscription_client.OnSymbolTick(req, metadata=headers),
            get_error=lambda reply: reply.error,
            get_data=lambda reply: reply.data,
            cancellation_event=cancellation_event,
        ):
            yield data

    async def on_trade(
        self,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Subscribes to all trade-related events: orders, deals, positions.

        Args:
            cancellation_event (asyncio.Event, optional): Event to cancel streaming.

        Yields:
            OnTradeData: Trade event data.

        Raises:
            ConnectExceptionMT4: If the account is not connected.
            ApiExceptionMT4: If the server returns a known API error.
            grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
        """
        if not self.id:
            raise ConnectExceptionMT4("Please call connect method first")

        request = subscriptions_pb2.OnTradeRequest()

        async for data in self.execute_stream_with_reconnect(
            request=request,
            stream_invoker=lambda req, headers: self.subscription_client.OnTrade(req, metadata=headers),
            get_error=lambda reply: reply.error,
            get_data=lambda reply: reply.data,
            cancellation_event=cancellation_event,
        ):
            yield data


    async def on_opened_orders_tickets(
        self,
        pull_interval_milliseconds: int = 500,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Subscribes to live lists of opened order tickets (positions & pending orders).

        Args:
            pull_interval_milliseconds (int): Server-side polling interval.
            cancellation_event (asyncio.Event, optional): Event to cancel streaming.

        Yields:
            OnOpenedOrdersTicketsData

        Raises:
            ConnectExceptionMT4: If the account is not connected.
            ApiExceptionMT4: If the server returns a known API error.
            grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
        """
        if not self.id:
            raise ConnectExceptionMT4("Please call connect method first")

        request = subscriptions_pb2.OnOpenedOrdersTicketsRequest(
            pull_interval_milliseconds=pull_interval_milliseconds
        )

        async for data in self.execute_stream_with_reconnect(
            request=request,
            stream_invoker=lambda req, headers: self.subscription_client.OnOpenedOrdersTickets(
                req, metadata=headers
            ),
            get_error=lambda reply: reply.error,
            get_data=lambda reply: reply.data,
            cancellation_event=cancellation_event,
        ):
            yield data


    async def on_opened_orders_profit(
        self,
        timer_period_milliseconds: int = 1000,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Subscribes to real-time profit updates for opened orders (plus account snapshot).

        Args:
            timer_period_milliseconds (int): Server timer period for updates.
            cancellation_event (asyncio.Event, optional): Event to cancel streaming.

        Yields:
            OnOpenedOrdersProfitData

        Raises:
            ConnectExceptionMT4: If the account is not connected.
            ApiExceptionMT4: If the server returns a known API error.
            grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
        """
        if not self.id:
            raise ConnectExceptionMT4("Please call connect method first")

        request = subscriptions_pb2.OnOpenedOrdersProfitRequest(
            timer_period_milliseconds=timer_period_milliseconds
        )

        async for data in self.execute_stream_with_reconnect(
            request=request,
            stream_invoker=lambda req, headers: self.subscription_client.OnOpenedOrdersProfit(
                req, metadata=headers
            ),
            get_error=lambda reply: reply.error,
            get_data=lambda reply: reply.data,
            cancellation_event=cancellation_event,
        ):
            yield data


#
# Trade functions --------------------------------------------------------------------------------------------------------
#
    async def order_send(
        self,
        symbol: str,
        operation_type: trading_helper_pb2.OrderSendOperationType,
        volume: float,
        price: Optional[float] = None,
        slippage: Optional[int] = None,
        stoploss: Optional[float] = None,
        takeprofit: Optional[float] = None,
        comment: Optional[str] = None,
        magic_number: Optional[int] = None,
        expiration: Optional[datetime] = None,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Opens a new trade order (market or pending).

        Args:
            symbol (str): Symbol to trade, e.g. "EURUSD".
            operation_type (OrderSendOperationType): Operation type (BUY, SELL, BUYLIMIT, etc.).
            volume (float): Trade volume in lots.
            price (float, optional): Open price for pending orders.
            slippage (int, optional): Allowed price deviation in points.
            stoploss (float, optional): Stop loss price.
            takeprofit (float, optional): Take profit price.
            comment (str, optional): Comment for the order.
            magic_number (int, optional): Custom magic number to identify the order.
            expiration (datetime, optional): Expiration time for pending orders.
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the operation.

        Returns:
            OrderSendData: The server's response containing new order details.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        req = trading_helper_pb2.OrderSendRequest(
            symbol=symbol,
            operation_type=operation_type,
            volume=volume,
        )
        if price is not None:
            req.price = price
        if slippage is not None:
            req.slippage = slippage
        if stoploss is not None:
            req.stoploss = stoploss
        if takeprofit is not None:
            req.takeprofit = takeprofit
        if comment:
            req.comment = comment
        if magic_number is not None:
            req.magic_number = magic_number
        if expiration:
            ts = Timestamp()
            ts.FromDatetime(expiration)
            req.expiration.CopyFrom(ts)

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.trade_client.OrderSend(req, metadata=headers, timeout=timeout)

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data


    async def order_modify(
        self,
        order_ticket: int,
        new_price: Optional[float] = None,
        new_stop_loss: Optional[float] = None,
        new_take_profit: Optional[float] = None,
        new_expiration: Optional[datetime] = None,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Modifies an existing order (price, SL/TP, expiration).

        Args:
            order_ticket (int): Ticket number of the order to modify.
            new_price (float, optional): New open price.
            new_stop_loss (float, optional): New stop loss.
            new_take_profit (float, optional): New take profit.
            new_expiration (datetime, optional): New expiration time.
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the operation.

        Returns:
            OrderModifyData: The server's response containing modification result.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        req = trading_helper_pb2.OrderModifyRequest(order_ticket=order_ticket)
        if new_price is not None:
            req.new_price = new_price
        if new_stop_loss is not None:
            req.new_stop_loss = new_stop_loss
        if new_take_profit is not None:
            req.new_take_profit = new_take_profit
        if new_expiration:
            ts = Timestamp()
            ts.FromDatetime(new_expiration)
            req.new_expiration.CopyFrom(ts)

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.trade_client.OrderModify(req, metadata=headers, timeout=timeout)

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data


    async def order_close_delete(
        self,
        order_ticket: int,
        lots: Optional[float] = None,
        closing_price: Optional[float] = None,
        slippage: Optional[int] = None,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Closes or deletes an order (market or pending).

        Args:
            order_ticket (int): Ticket of the order to close or delete.
            lots (float, optional): Volume to close (for partial close).
            closing_price (float, optional): Desired closing price.
            slippage (int, optional): Allowed price deviation in points.
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the operation.

        Returns:
            OrderCloseDeleteData: The server's response indicating close/delete status.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        req = trading_helper_pb2.OrderCloseDeleteRequest(order_ticket=order_ticket)
        if lots is not None:
            req.lots = lots
        if closing_price is not None:
            req.closing_price = closing_price
        if slippage is not None:
            req.slippage = slippage

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.trade_client.OrderCloseDelete(req, metadata=headers, timeout=timeout)

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data


    async def order_close_by(
        self,
        ticket_to_close: int,
        opposite_ticket_closing_by: int,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Closes one position by another (close-by operation).

        Args:
            ticket_to_close (int): Ticket of the order being closed.
            opposite_ticket_closing_by (int): Opposite ticket to close by.
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the operation.

        Returns:
            OrderCloseByData: The server's response containing close-by result.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        req = trading_helper_pb2.OrderCloseByRequest(
            ticket_to_close=ticket_to_close,
            opposite_ticket_closing_by=opposite_ticket_closing_by,
        )

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.trade_client.OrderCloseBy(req, metadata=headers, timeout=timeout)

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data

#
# Market info --------------------------------------------------------------------------------------------------------
#

    async def quote(
        self,
        symbol: str,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Retrieves the latest quote for a single symbol.

        Args:
            symbol (str): The symbol name (e.g., "EURUSD").
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the request.

        Returns:
            QuoteData: The latest bid/ask/high/low prices with timestamp.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        request = market_info_pb2.QuoteRequest(symbol=symbol)

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.market_info_client.Quote(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data


    async def quote_many(
        self,
        symbols: list[str],
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Retrieves quotes for multiple symbols.

        Args:
            symbols (list[str]): List of symbol names (e.g., ["EURUSD", "GBPUSD"]).
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the request.

        Returns:
            QuoteManyData: The response containing quotes for all requested symbols.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        request = market_info_pb2.QuoteManyRequest(symbols=symbols)

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.market_info_client.QuoteMany(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data


    async def symbols(
        self,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Retrieves the full list of tradable symbols from the connected terminal.

        Args:
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the request.

        Returns:
            SymbolsData: The response containing all available symbol names and indices.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        request = market_info_pb2.SymbolsRequest()

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.market_info_client.Symbols(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data


    async def quote_history(
        self,
        symbol: str,
        timeframe: market_info_pb2.ENUM_QUOTE_HISTORY_TIMEFRAME,
        from_time: datetime,
        to_time: datetime,
        deadline: Optional[datetime] = None,
        cancellation_event: Optional[asyncio.Event] = None,
    ):
        """
        Retrieves historical OHLC quotes for a symbol within a specified time range.

        Args:
            symbol (str): The symbol name (e.g., "EURUSD").
            timeframe (ENUM_QUOTE_HISTORY_TIMEFRAME): The timeframe (e.g., QH_PERIOD_H1).
            from_time (datetime): Start of the requested historical period.
            to_time (datetime): End of the requested historical period.
            deadline (datetime, optional): Deadline for the gRPC request.
            cancellation_event (asyncio.Event, optional): Event to cancel the request.

        Returns:
            QuoteHistoryData: The server's response containing OHLC and volume data.

        Raises:
            ConnectExceptionMT4: If the account is not connected before calling this method.
            ApiExceptionMT4: If the server returns an API error.
            grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
            asyncio.CancelledError: If cancelled via `cancellation_event`.
        """
        if not (self.host or self.server_name or self.id):
            raise ConnectExceptionMT4("Please call connect method first")

        ts_from = Timestamp()
        ts_from.FromDatetime(from_time)
        ts_to = Timestamp()
        ts_to.FromDatetime(to_time)

        request = market_info_pb2.QuoteHistoryRequest(
            symbol=symbol,
            timeframe=timeframe,
            fromTime=ts_from,
            toTime=ts_to,
        )

        async def grpc_call(headers):
            timeout = None
            if deadline:
                timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
            return await self.market_info_client.QuoteHistory(
                request,
                metadata=headers,
                timeout=timeout,
            )

        res = await self.execute_with_reconnect(
            grpc_call=grpc_call,
            error_selector=lambda r: getattr(r, "error", None),
            deadline=deadline,
            cancellation_event=cancellation_event,
        )
        return res.data

account_summary async

account_summary(deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Gets the summary information for a trading account asynchronously.

Parameters:

Name Type Description Default
deadline datetime

Deadline after which the request will be canceled if not completed.

None
cancellation_event Event

Event to cancel the request.

None

Returns:

Name Type Description
AccountSummaryData

The server's response containing account summary data.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an error in the response.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
async def account_summary(
    self,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Gets the summary information for a trading account asynchronously.

    Args:
        deadline (datetime, optional): Deadline after which the request will be canceled
            if not completed.
        cancellation_event (asyncio.Event, optional): Event to cancel the request.

    Returns:
        AccountSummaryData: The server's response containing account summary data.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an error in the response.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
    """
    if not (self.host or self.server_name):
        raise ConnectExceptionMT4("Please call connect method first")

    request = account_helper_pb2.AccountSummaryRequest()

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = (deadline - datetime.utcnow()).total_seconds()
            if timeout < 0:
                timeout = 0
        return await self.account_client.AccountSummary(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )

    return res.data

opened_orders async

opened_orders(sort_mode: EnumOpenedOrderSortType = account_helper_pb2.EnumOpenedOrderSortType.SORT_BY_OPEN_TIME_ASC, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Gets the currently opened orders and positions for the connected account asynchronously.

Parameters:

Name Type Description Default
sort_mode EnumOpenedOrderSortType

The sort mode for the opened orders (e.g. SORT_BY_OPEN_TIME_ASC, SORT_BY_ORDER_TICKET_ID_DESC).

SORT_BY_OPEN_TIME_ASC
deadline datetime

Deadline after which the request will be canceled if not completed.

None
cancellation_event Event

Event to cancel the request.

None

Returns:

Name Type Description
OpenedOrdersData

The result containing opened orders and positions.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an error in the response.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
async def opened_orders(
    self,
    sort_mode: account_helper_pb2.EnumOpenedOrderSortType = account_helper_pb2.EnumOpenedOrderSortType.SORT_BY_OPEN_TIME_ASC,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Gets the currently opened orders and positions for the connected account asynchronously.

    Args:
        sort_mode (EnumOpenedOrderSortType): The sort mode for the opened orders
            (e.g. SORT_BY_OPEN_TIME_ASC, SORT_BY_ORDER_TICKET_ID_DESC).
        deadline (datetime, optional): Deadline after which the request will be canceled
            if not completed.
        cancellation_event (asyncio.Event, optional): Event to cancel the request.

    Returns:
        OpenedOrdersData: The result containing opened orders and positions.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an error in the response.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    # Build request
    request = account_helper_pb2.OpenedOrdersRequest(sort_type=sort_mode)

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = (deadline - datetime.utcnow()).total_seconds()
            if timeout < 0:
                timeout = 0
        return await self.account_client.OpenedOrders(
            request,
            metadata=headers,
            timeout=timeout,
        )

    # Execute with automatic reconnect logic
    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )

    return res.data

opened_orders_tickets async

opened_orders_tickets(deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Gets the list of tickets for all currently opened orders.

Returns:

Name Type Description
OpenedOrdersTicketsData

The result containing the list of tickets.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an error in the response.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
async def opened_orders_tickets(
    self,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Gets the list of tickets for all currently opened orders.

    Returns:
        OpenedOrdersTicketsData: The result containing the list of tickets.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an error in the response.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    request = account_helper_pb2.OpenedOrdersTicketsRequest()

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = (deadline - datetime.utcnow()).total_seconds()
            if timeout < 0:
                timeout = 0
        return await self.account_client.OpenedOrdersTickets(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )

    return res.data

orders_history async

orders_history(sort_mode: EnumOrderHistorySortType = account_helper_pb2.EnumOrderHistorySortType.HISTORY_SORT_BY_CLOSE_TIME_DESC, from_time: Optional[datetime] = None, to_time: Optional[datetime] = None, page_number: Optional[int] = None, items_per_page: Optional[int] = None, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Gets the order history for the connected account.

Parameters:

Name Type Description Default
sort_mode EnumOrderHistorySortType

Sorting mode for orders.

HISTORY_SORT_BY_CLOSE_TIME_DESC
from_time datetime

Start of the history period.

None
to_time datetime

End of the history period.

None
page_number int

Page number for pagination.

None
items_per_page int

Items per page.

None

Returns:

Name Type Description
OrdersHistoryData

The result containing historical orders.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an error in the response.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
async def orders_history(
    self,
    sort_mode: account_helper_pb2.EnumOrderHistorySortType = account_helper_pb2.EnumOrderHistorySortType.HISTORY_SORT_BY_CLOSE_TIME_DESC,
    from_time: Optional[datetime] = None,
    to_time: Optional[datetime] = None,
    page_number: Optional[int] = None,
    items_per_page: Optional[int] = None,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Gets the order history for the connected account.

    Args:
        sort_mode (EnumOrderHistorySortType): Sorting mode for orders.
        from_time (datetime, optional): Start of the history period.
        to_time (datetime, optional): End of the history period.
        page_number (int, optional): Page number for pagination.
        items_per_page (int, optional): Items per page.

    Returns:
        OrdersHistoryData: The result containing historical orders.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an error in the response.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    # Convert datetime → Timestamp (protobuf)
    ts_from = None
    ts_to = None
    if from_time:
        ts_from = Timestamp()
        ts_from.FromDatetime(from_time)
    if to_time:
        ts_to = Timestamp()
        ts_to.FromDatetime(to_time)

    request = account_helper_pb2.OrdersHistoryRequest(
        input_sort_mode=sort_mode,
        input_from=ts_from,
        input_to=ts_to,
        page_number=page_number,
        items_per_page=items_per_page,
    )

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = (deadline - datetime.utcnow()).total_seconds()
            if timeout < 0:
                timeout = 0
        return await self.account_client.OrdersHistory(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )

    return res.data

symbol_params_many async

symbol_params_many(symbol_name: Optional[str] = None, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Retrieves symbol parameters (for one or all symbols).

Parameters:

Name Type Description Default
symbol_name str

Symbol name. If None, returns all.

None

Returns:

Name Type Description
SymbolParamsManyData

The result containing symbol parameters.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an error in the response.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
async def symbol_params_many(
    self,
    symbol_name: Optional[str] = None,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Retrieves symbol parameters (for one or all symbols).

    Args:
        symbol_name (str, optional): Symbol name. If None, returns all.

    Returns:
        SymbolParamsManyData: The result containing symbol parameters.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an error in the response.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    request = account_helper_pb2.SymbolParamsManyRequest(symbol_name=symbol_name or "")

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = (deadline - datetime.utcnow()).total_seconds()
            if timeout < 0:
                timeout = 0
        return await self.account_client.SymbolParamsMany(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )

    return res.data

tick_value_with_size async

tick_value_with_size(symbol_names: list[str], deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Gets tick value, tick size, and contract size for multiple symbols.

Parameters:

Name Type Description Default
symbol_names list[str]

List of symbol names.

required

Returns:

Name Type Description
TickValueWithSizeData

The result containing tick values and sizes.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an error in the response.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
async def tick_value_with_size(
    self,
    symbol_names: list[str],
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Gets tick value, tick size, and contract size for multiple symbols.

    Args:
        symbol_names (list[str]): List of symbol names.

    Returns: 
        TickValueWithSizeData: The result containing tick values and sizes.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an error in the response.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    request = account_helper_pb2.TickValueWithSizeRequest(symbol_names=symbol_names)

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = (deadline - datetime.utcnow()).total_seconds()
            if timeout < 0:
                timeout = 0
        return await self.account_client.TickValueWithSize(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )

    return res.data

execute_stream_with_reconnect async

execute_stream_with_reconnect(request: Any, stream_invoker: Callable[[Any, list[tuple[str, str]]], StreamStreamCall], get_error: Callable[[Any], Optional[Any]], get_data: Callable[[Any], Any], cancellation_event: Optional[Event] = None) -> AsyncGenerator[Any, None]

Executes a gRPC server-streaming call with automatic reconnection logic on recoverable errors.

Parameters:

Name Type Description Default
request Any

The request object to initiate the stream with.

required
stream_invoker Callable

A function that opens the stream. It receives the request and metadata headers, and returns an async streaming call.

required
get_error Callable

A function that extracts the error object (if any) from a reply. Return an object with .error_code == "TERMINAL_INSTANCE_NOT_FOUND" to trigger reconnect, or any non-null error to raise ApiExceptionMT5.

required
get_data Callable

A function that extracts the data object from a reply. If it returns None, the message is skipped.

required
cancellation_event Event

Event to cancel streaming and reconnection attempts.

None

Yields:

Type Description
AsyncGenerator[Any, None]

Extracted data items streamed from the server.

Raises:

Type Description
ConnectExceptionMT4

If reconnection logic fails due to missing account context.

ApiExceptionMT4

When the stream response contains a known API error.

AioRpcError

If a non-recoverable gRPC error occurs.

Source code in package/MetaRpcMT4/mt4_account.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
async def execute_stream_with_reconnect(
    self,
    request: Any,
    stream_invoker: Callable[[Any, list[tuple[str, str]]], grpc.aio.StreamStreamCall],
    get_error: Callable[[Any], Optional[Any]],
    get_data: Callable[[Any], Any],
    cancellation_event: Optional[asyncio.Event] = None,
) -> AsyncGenerator[Any, None]:
    """
    Executes a gRPC server-streaming call with automatic reconnection logic on recoverable errors.

    Args:
        request: The request object to initiate the stream with.
        stream_invoker (Callable): A function that opens the stream. It receives the request and metadata headers,
            and returns an async streaming call.
        get_error (Callable): A function that extracts the error object (if any) from a reply.
            Return an object with .error_code == "TERMINAL_INSTANCE_NOT_FOUND" to trigger reconnect,
            or any non-null error to raise ApiExceptionMT5.
        get_data (Callable): A function that extracts the data object from a reply. If it returns None, the
            message is skipped.
        cancellation_event (asyncio.Event, optional): Event to cancel streaming and reconnection attempts.

    Yields:
        Extracted data items streamed from the server.

    Raises:
        ConnectExceptionMT4: If reconnection logic fails due to missing account context.
        ApiExceptionMT4: When the stream response contains a known API error.
        grpc.aio.AioRpcError: If a non-recoverable gRPC error occurs.
    """
    while cancellation_event is None or not cancellation_event.is_set():
        reconnect_required = False
        stream = None
        try:
            stream = stream_invoker(request, self.get_headers())
            async for reply in stream:
                error = get_error(reply)

                if error and error.error_code in (
                    "TERMINAL_INSTANCE_NOT_FOUND",
                    "TERMINAL_REGISTRY_TERMINAL_NOT_FOUND",
                ):
                    reconnect_required = True
                    break

                if error and getattr(error, "message", None):
                    raise ApiExceptionMT4(error)

                data = get_data(reply)
                if data is not None:
                    yield data

        except grpc.aio.AioRpcError as ex:
            if ex.code() == grpc.StatusCode.UNAVAILABLE:
                reconnect_required = True
            else:
                raise

        finally:
            if stream:
                stream.cancel()  # close stream properly

        if reconnect_required:
            await asyncio.sleep(0.5)
            await self.reconnect()
        else:
            break

on_symbol_tick async

on_symbol_tick(symbols: list[str], cancellation_event: Optional[Event] = None)

Subscribes to real-time tick data for specified symbols.

Parameters:

Name Type Description Default
symbols list[str]

The symbol names to subscribe to.

required
cancellation_event Event

Event to cancel streaming.

None

Yields:

Name Type Description
OnSymbolTickData

Async stream of tick data responses.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an error in the stream.

AioRpcError

If the stream fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
async def on_symbol_tick(
    self,
    symbols: list[str],
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Subscribes to real-time tick data for specified symbols.

    Args:
        symbols (list[str]): The symbol names to subscribe to.
        cancellation_event (asyncio.Event, optional): Event to cancel streaming.

    Yields:
        OnSymbolTickData: Async stream of tick data responses.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an error in the stream.
        grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
    """
    if not self.id:
        raise ConnectExceptionMT4("Please call connect method first")

    request = subscriptions_pb2.OnSymbolTickRequest()
    request.symbol_names.extend(symbols)

    async for data in self.execute_stream_with_reconnect(
        request=request,
        stream_invoker=lambda req, headers: self.subscription_client.OnSymbolTick(req, metadata=headers),
        get_error=lambda reply: reply.error,
        get_data=lambda reply: reply.data,
        cancellation_event=cancellation_event,
    ):
        yield data

on_trade async

on_trade(cancellation_event: Optional[Event] = None)

Subscribes to all trade-related events: orders, deals, positions.

Parameters:

Name Type Description Default
cancellation_event Event

Event to cancel streaming.

None

Yields:

Name Type Description
OnTradeData

Trade event data.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected.

ApiExceptionMT4

If the server returns a known API error.

AioRpcError

If the stream fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
async def on_trade(
    self,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Subscribes to all trade-related events: orders, deals, positions.

    Args:
        cancellation_event (asyncio.Event, optional): Event to cancel streaming.

    Yields:
        OnTradeData: Trade event data.

    Raises:
        ConnectExceptionMT4: If the account is not connected.
        ApiExceptionMT4: If the server returns a known API error.
        grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
    """
    if not self.id:
        raise ConnectExceptionMT4("Please call connect method first")

    request = subscriptions_pb2.OnTradeRequest()

    async for data in self.execute_stream_with_reconnect(
        request=request,
        stream_invoker=lambda req, headers: self.subscription_client.OnTrade(req, metadata=headers),
        get_error=lambda reply: reply.error,
        get_data=lambda reply: reply.data,
        cancellation_event=cancellation_event,
    ):
        yield data

on_opened_orders_tickets async

on_opened_orders_tickets(pull_interval_milliseconds: int = 500, cancellation_event: Optional[Event] = None)

Subscribes to live lists of opened order tickets (positions & pending orders).

Parameters:

Name Type Description Default
pull_interval_milliseconds int

Server-side polling interval.

500
cancellation_event Event

Event to cancel streaming.

None

Yields:

Type Description

OnOpenedOrdersTicketsData

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected.

ApiExceptionMT4

If the server returns a known API error.

AioRpcError

If the stream fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
async def on_opened_orders_tickets(
    self,
    pull_interval_milliseconds: int = 500,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Subscribes to live lists of opened order tickets (positions & pending orders).

    Args:
        pull_interval_milliseconds (int): Server-side polling interval.
        cancellation_event (asyncio.Event, optional): Event to cancel streaming.

    Yields:
        OnOpenedOrdersTicketsData

    Raises:
        ConnectExceptionMT4: If the account is not connected.
        ApiExceptionMT4: If the server returns a known API error.
        grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
    """
    if not self.id:
        raise ConnectExceptionMT4("Please call connect method first")

    request = subscriptions_pb2.OnOpenedOrdersTicketsRequest(
        pull_interval_milliseconds=pull_interval_milliseconds
    )

    async for data in self.execute_stream_with_reconnect(
        request=request,
        stream_invoker=lambda req, headers: self.subscription_client.OnOpenedOrdersTickets(
            req, metadata=headers
        ),
        get_error=lambda reply: reply.error,
        get_data=lambda reply: reply.data,
        cancellation_event=cancellation_event,
    ):
        yield data

on_opened_orders_profit async

on_opened_orders_profit(timer_period_milliseconds: int = 1000, cancellation_event: Optional[Event] = None)

Subscribes to real-time profit updates for opened orders (plus account snapshot).

Parameters:

Name Type Description Default
timer_period_milliseconds int

Server timer period for updates.

1000
cancellation_event Event

Event to cancel streaming.

None

Yields:

Type Description

OnOpenedOrdersProfitData

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected.

ApiExceptionMT4

If the server returns a known API error.

AioRpcError

If the stream fails due to communication or protocol errors.

Source code in package/MetaRpcMT4/mt4_account.py
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
async def on_opened_orders_profit(
    self,
    timer_period_milliseconds: int = 1000,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Subscribes to real-time profit updates for opened orders (plus account snapshot).

    Args:
        timer_period_milliseconds (int): Server timer period for updates.
        cancellation_event (asyncio.Event, optional): Event to cancel streaming.

    Yields:
        OnOpenedOrdersProfitData

    Raises:
        ConnectExceptionMT4: If the account is not connected.
        ApiExceptionMT4: If the server returns a known API error.
        grpc.aio.AioRpcError: If the stream fails due to communication or protocol errors.
    """
    if not self.id:
        raise ConnectExceptionMT4("Please call connect method first")

    request = subscriptions_pb2.OnOpenedOrdersProfitRequest(
        timer_period_milliseconds=timer_period_milliseconds
    )

    async for data in self.execute_stream_with_reconnect(
        request=request,
        stream_invoker=lambda req, headers: self.subscription_client.OnOpenedOrdersProfit(
            req, metadata=headers
        ),
        get_error=lambda reply: reply.error,
        get_data=lambda reply: reply.data,
        cancellation_event=cancellation_event,
    ):
        yield data

order_send async

order_send(symbol: str, operation_type: OrderSendOperationType, volume: float, price: Optional[float] = None, slippage: Optional[int] = None, stoploss: Optional[float] = None, takeprofit: Optional[float] = None, comment: Optional[str] = None, magic_number: Optional[int] = None, expiration: Optional[datetime] = None, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Opens a new trade order (market or pending).

Parameters:

Name Type Description Default
symbol str

Symbol to trade, e.g. "EURUSD".

required
operation_type OrderSendOperationType

Operation type (BUY, SELL, BUYLIMIT, etc.).

required
volume float

Trade volume in lots.

required
price float

Open price for pending orders.

None
slippage int

Allowed price deviation in points.

None
stoploss float

Stop loss price.

None
takeprofit float

Take profit price.

None
comment str

Comment for the order.

None
magic_number int

Custom magic number to identify the order.

None
expiration datetime

Expiration time for pending orders.

None
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the operation.

None

Returns:

Name Type Description
OrderSendData

The server's response containing new order details.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
async def order_send(
    self,
    symbol: str,
    operation_type: trading_helper_pb2.OrderSendOperationType,
    volume: float,
    price: Optional[float] = None,
    slippage: Optional[int] = None,
    stoploss: Optional[float] = None,
    takeprofit: Optional[float] = None,
    comment: Optional[str] = None,
    magic_number: Optional[int] = None,
    expiration: Optional[datetime] = None,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Opens a new trade order (market or pending).

    Args:
        symbol (str): Symbol to trade, e.g. "EURUSD".
        operation_type (OrderSendOperationType): Operation type (BUY, SELL, BUYLIMIT, etc.).
        volume (float): Trade volume in lots.
        price (float, optional): Open price for pending orders.
        slippage (int, optional): Allowed price deviation in points.
        stoploss (float, optional): Stop loss price.
        takeprofit (float, optional): Take profit price.
        comment (str, optional): Comment for the order.
        magic_number (int, optional): Custom magic number to identify the order.
        expiration (datetime, optional): Expiration time for pending orders.
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the operation.

    Returns:
        OrderSendData: The server's response containing new order details.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    req = trading_helper_pb2.OrderSendRequest(
        symbol=symbol,
        operation_type=operation_type,
        volume=volume,
    )
    if price is not None:
        req.price = price
    if slippage is not None:
        req.slippage = slippage
    if stoploss is not None:
        req.stoploss = stoploss
    if takeprofit is not None:
        req.takeprofit = takeprofit
    if comment:
        req.comment = comment
    if magic_number is not None:
        req.magic_number = magic_number
    if expiration:
        ts = Timestamp()
        ts.FromDatetime(expiration)
        req.expiration.CopyFrom(ts)

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.trade_client.OrderSend(req, metadata=headers, timeout=timeout)

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data

order_modify async

order_modify(order_ticket: int, new_price: Optional[float] = None, new_stop_loss: Optional[float] = None, new_take_profit: Optional[float] = None, new_expiration: Optional[datetime] = None, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Modifies an existing order (price, SL/TP, expiration).

Parameters:

Name Type Description Default
order_ticket int

Ticket number of the order to modify.

required
new_price float

New open price.

None
new_stop_loss float

New stop loss.

None
new_take_profit float

New take profit.

None
new_expiration datetime

New expiration time.

None
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the operation.

None

Returns:

Name Type Description
OrderModifyData

The server's response containing modification result.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
async def order_modify(
    self,
    order_ticket: int,
    new_price: Optional[float] = None,
    new_stop_loss: Optional[float] = None,
    new_take_profit: Optional[float] = None,
    new_expiration: Optional[datetime] = None,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Modifies an existing order (price, SL/TP, expiration).

    Args:
        order_ticket (int): Ticket number of the order to modify.
        new_price (float, optional): New open price.
        new_stop_loss (float, optional): New stop loss.
        new_take_profit (float, optional): New take profit.
        new_expiration (datetime, optional): New expiration time.
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the operation.

    Returns:
        OrderModifyData: The server's response containing modification result.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    req = trading_helper_pb2.OrderModifyRequest(order_ticket=order_ticket)
    if new_price is not None:
        req.new_price = new_price
    if new_stop_loss is not None:
        req.new_stop_loss = new_stop_loss
    if new_take_profit is not None:
        req.new_take_profit = new_take_profit
    if new_expiration:
        ts = Timestamp()
        ts.FromDatetime(new_expiration)
        req.new_expiration.CopyFrom(ts)

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.trade_client.OrderModify(req, metadata=headers, timeout=timeout)

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data

order_close_delete async

order_close_delete(order_ticket: int, lots: Optional[float] = None, closing_price: Optional[float] = None, slippage: Optional[int] = None, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Closes or deletes an order (market or pending).

Parameters:

Name Type Description Default
order_ticket int

Ticket of the order to close or delete.

required
lots float

Volume to close (for partial close).

None
closing_price float

Desired closing price.

None
slippage int

Allowed price deviation in points.

None
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the operation.

None

Returns:

Name Type Description
OrderCloseDeleteData

The server's response indicating close/delete status.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
async def order_close_delete(
    self,
    order_ticket: int,
    lots: Optional[float] = None,
    closing_price: Optional[float] = None,
    slippage: Optional[int] = None,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Closes or deletes an order (market or pending).

    Args:
        order_ticket (int): Ticket of the order to close or delete.
        lots (float, optional): Volume to close (for partial close).
        closing_price (float, optional): Desired closing price.
        slippage (int, optional): Allowed price deviation in points.
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the operation.

    Returns:
        OrderCloseDeleteData: The server's response indicating close/delete status.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    req = trading_helper_pb2.OrderCloseDeleteRequest(order_ticket=order_ticket)
    if lots is not None:
        req.lots = lots
    if closing_price is not None:
        req.closing_price = closing_price
    if slippage is not None:
        req.slippage = slippage

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.trade_client.OrderCloseDelete(req, metadata=headers, timeout=timeout)

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data

order_close_by async

order_close_by(ticket_to_close: int, opposite_ticket_closing_by: int, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Closes one position by another (close-by operation).

Parameters:

Name Type Description Default
ticket_to_close int

Ticket of the order being closed.

required
opposite_ticket_closing_by int

Opposite ticket to close by.

required
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the operation.

None

Returns:

Name Type Description
OrderCloseByData

The server's response containing close-by result.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
async def order_close_by(
    self,
    ticket_to_close: int,
    opposite_ticket_closing_by: int,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Closes one position by another (close-by operation).

    Args:
        ticket_to_close (int): Ticket of the order being closed.
        opposite_ticket_closing_by (int): Opposite ticket to close by.
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the operation.

    Returns:
        OrderCloseByData: The server's response containing close-by result.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    req = trading_helper_pb2.OrderCloseByRequest(
        ticket_to_close=ticket_to_close,
        opposite_ticket_closing_by=opposite_ticket_closing_by,
    )

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.trade_client.OrderCloseBy(req, metadata=headers, timeout=timeout)

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data

quote async

quote(symbol: str, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Retrieves the latest quote for a single symbol.

Parameters:

Name Type Description Default
symbol str

The symbol name (e.g., "EURUSD").

required
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the request.

None

Returns:

Name Type Description
QuoteData

The latest bid/ask/high/low prices with timestamp.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
async def quote(
    self,
    symbol: str,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Retrieves the latest quote for a single symbol.

    Args:
        symbol (str): The symbol name (e.g., "EURUSD").
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the request.

    Returns:
        QuoteData: The latest bid/ask/high/low prices with timestamp.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    request = market_info_pb2.QuoteRequest(symbol=symbol)

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.market_info_client.Quote(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data

quote_many async

quote_many(symbols: list[str], deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Retrieves quotes for multiple symbols.

Parameters:

Name Type Description Default
symbols list[str]

List of symbol names (e.g., ["EURUSD", "GBPUSD"]).

required
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the request.

None

Returns:

Name Type Description
QuoteManyData

The response containing quotes for all requested symbols.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
async def quote_many(
    self,
    symbols: list[str],
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Retrieves quotes for multiple symbols.

    Args:
        symbols (list[str]): List of symbol names (e.g., ["EURUSD", "GBPUSD"]).
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the request.

    Returns:
        QuoteManyData: The response containing quotes for all requested symbols.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    request = market_info_pb2.QuoteManyRequest(symbols=symbols)

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.market_info_client.QuoteMany(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data

symbols async

symbols(deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Retrieves the full list of tradable symbols from the connected terminal.

Parameters:

Name Type Description Default
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the request.

None

Returns:

Name Type Description
SymbolsData

The response containing all available symbol names and indices.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
async def symbols(
    self,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Retrieves the full list of tradable symbols from the connected terminal.

    Args:
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the request.

    Returns:
        SymbolsData: The response containing all available symbol names and indices.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    request = market_info_pb2.SymbolsRequest()

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.market_info_client.Symbols(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data

quote_history async

quote_history(symbol: str, timeframe: ENUM_QUOTE_HISTORY_TIMEFRAME, from_time: datetime, to_time: datetime, deadline: Optional[datetime] = None, cancellation_event: Optional[Event] = None)

Retrieves historical OHLC quotes for a symbol within a specified time range.

Parameters:

Name Type Description Default
symbol str

The symbol name (e.g., "EURUSD").

required
timeframe ENUM_QUOTE_HISTORY_TIMEFRAME

The timeframe (e.g., QH_PERIOD_H1).

required
from_time datetime

Start of the requested historical period.

required
to_time datetime

End of the requested historical period.

required
deadline datetime

Deadline for the gRPC request.

None
cancellation_event Event

Event to cancel the request.

None

Returns:

Name Type Description
QuoteHistoryData

The server's response containing OHLC and volume data.

Raises:

Type Description
ConnectExceptionMT4

If the account is not connected before calling this method.

ApiExceptionMT4

If the server returns an API error.

AioRpcError

If the gRPC call fails due to communication or protocol errors.

CancelledError

If cancelled via cancellation_event.

Source code in package/MetaRpcMT4/mt4_account.py
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
async def quote_history(
    self,
    symbol: str,
    timeframe: market_info_pb2.ENUM_QUOTE_HISTORY_TIMEFRAME,
    from_time: datetime,
    to_time: datetime,
    deadline: Optional[datetime] = None,
    cancellation_event: Optional[asyncio.Event] = None,
):
    """
    Retrieves historical OHLC quotes for a symbol within a specified time range.

    Args:
        symbol (str): The symbol name (e.g., "EURUSD").
        timeframe (ENUM_QUOTE_HISTORY_TIMEFRAME): The timeframe (e.g., QH_PERIOD_H1).
        from_time (datetime): Start of the requested historical period.
        to_time (datetime): End of the requested historical period.
        deadline (datetime, optional): Deadline for the gRPC request.
        cancellation_event (asyncio.Event, optional): Event to cancel the request.

    Returns:
        QuoteHistoryData: The server's response containing OHLC and volume data.

    Raises:
        ConnectExceptionMT4: If the account is not connected before calling this method.
        ApiExceptionMT4: If the server returns an API error.
        grpc.aio.AioRpcError: If the gRPC call fails due to communication or protocol errors.
        asyncio.CancelledError: If cancelled via `cancellation_event`.
    """
    if not (self.host or self.server_name or self.id):
        raise ConnectExceptionMT4("Please call connect method first")

    ts_from = Timestamp()
    ts_from.FromDatetime(from_time)
    ts_to = Timestamp()
    ts_to.FromDatetime(to_time)

    request = market_info_pb2.QuoteHistoryRequest(
        symbol=symbol,
        timeframe=timeframe,
        fromTime=ts_from,
        toTime=ts_to,
    )

    async def grpc_call(headers):
        timeout = None
        if deadline:
            timeout = max((deadline - datetime.utcnow()).total_seconds(), 0)
        return await self.market_info_client.QuoteHistory(
            request,
            metadata=headers,
            timeout=timeout,
        )

    res = await self.execute_with_reconnect(
        grpc_call=grpc_call,
        error_selector=lambda r: getattr(r, "error", None),
        deadline=deadline,
        cancellation_event=cancellation_event,
    )
    return res.data