Skip to content

Trade

CTrade

Source code in strategytester5\trade_classes\Trade.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 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
class CTrade:
    def __init__(
            self,
            magic_number: int,
            filling_type_symbol: str,
            deviation_points: int,
            terminal: Union[OverLoadedMetaTrader5API|MetaTrader5],
            logger: logging.Logger | None = None
    ):
        """
        Initialize a CTrade wrapper for MetaTrader 5 trade operations.

        This class resembles the MQL5 Standard Library class `CTrade` and provides
        a convenient Python interface for sending and managing trade requests through
        the MetaTrader 5 Python API.

        [MQL5 Reference](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade)

        Args:

        terminal (Any):
            MetaTrader5 module-like or the overloaded/simulated MetaTrader5 instance

        magic_number (int):
            Expert Advisor identifier used to tag and track orders and positions
            created by this trade object.

        filling_type_symbol (str):
            Symbol name used to determine the appropriate order filling policy
            through the internal `_get_type_filling()` helper.

        deviation_points (int):
            Maximum allowed price deviation, in points, when executing market
            orders.

        logger (logging.Logger | None, optional):
            Logger instance used for diagnostic and error messages. If None,
            logging output is handled only by the class' internal logic.

        Notes
        -----
        - The constructor resolves and stores the filling type for the provided
          symbol at initialization time.
        - If the filling type cannot be resolved, initialization logs a critical
          error and returns early.
        - This class is intended to act similarly to MQL5's `CTrade`, where trade
          settings such as magic number, filling mode, and deviation are configured
          once and reused across requests.
        """

        self.logger = logger

        self.terminal = terminal

        self.magic_number = magic_number
        self.deviation_points = deviation_points
        self.filling_type = self._get_type_filling(filling_type_symbol)

        if self.filling_type == -1:
            self._critical_log("Failed to initialize the class, Invalid filling type. Check your symbol")
            return

    def _critical_log(self, message: str):
        if self.logger:
            self.logger.critical(message)
        else:
            print(f"CRITICAL: {message}")

    def _info_log(self, message: str):
        if self.logger:
            self.logger.info(message)
        else:
            print(f"INFO: {message}")

    def _error_log(self, message: str):
        if self.logger:
            self.logger.error(message)
        else:
            print(f"ERROR: {message}")

    def _warning_log(self, message: str):
        if self.logger:
            self.logger.warning(message)
        else:
            print(f"WARNING: {message}")

    def _get_type_filling(self, symbol):

        symbol_info = self.terminal.symbol_info(symbol)
        if symbol_info is None:
            self._warning_log(f"Failed to get symbol info for {symbol}")

        filling_map = {
            1: self.terminal.ORDER_FILLING_FOK,
            2: self.terminal.ORDER_FILLING_IOC,
            4: self.terminal.ORDER_FILLING_BOC,
            8: self.terminal.ORDER_FILLING_RETURN
        }

        return filling_map.get(symbol_info.filling_mode, f"Unknown Filling type")

    def position_open(self, symbol: str, volume: float, order_type: int, price: float, sl: float=0.0, tp: float=0.0, comment: str="") -> bool:

        """
        Open a market position (instant execution).

        Executes either a buy or sell order at the current market price. This is for immediate
        position opening, not pending orders.

        Args:
            symbol: Trading symbol (e.g., "EURUSD", "GBPUSD")
            volume: Trade volume in lots (e.g., 0.1 for micro lot)
            order_type: Trade direction (either ORDER_TYPE_BUY or ORDER_TYPE_SELL)
            price: Execution price. For market orders, this should be the current:
                - Ask price for BUY orders
                - Bid price for SELL orders
            sl: Stop loss price (set to 0.0 to disable)
            tp: Take profit price (set to 0.0 to disable)
            comment: Optional order comment (max 31 characters, will be truncated automatically)

        Returns:
            bool: True if position was opened successfully, False otherwise
        """

        request = {
            "action": self.terminal.TRADE_ACTION_DEAL,
            "symbol": symbol,
            "volume": volume,
            "type": order_type,
            "price": price,
            "deviation": self.deviation_points,
            "magic": self.magic_number,
            "comment": comment,
            "type_time": self.terminal.ORDER_TIME_GTC,
            "type_filling":  self.filling_type,
        }

        if sl > 0.0:
            request["sl"] = sl
        if tp > 0.0:
            request["tp"] = tp

        result = self.terminal.order_send(request)
        if result.retcode != self.terminal.TRADE_RETCODE_DONE:
            return False

        self._info_log(f"Position #{result.deal} Opened successfully!")
        return True


    def order_open(self, symbol: str, volume: float, order_type: int, price: float, sl: float = 0.0, tp: float = 0.0, type_time: int = 0, expiration: datetime = None, comment: str = "") -> bool:

        """
        Opens a pending order with full control over order parameters.

        Args:
            symbol: Trading symbol (e.g., "EURUSD")
            volume: Order volume in lots
            order_type: Order type (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_STOP, etc.)
            price: Activation price for pending order
            sl: Stop loss price (0 to disable)
            tp: Take profit price (0 to disable)
            type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
                    - ORDER_TIME_GTC (Good-Til-Canceled)
                    - ORDER_TIME_DAY (Good for current day)
                    - ORDER_TIME_SPECIFIED (expires at specific datetime)
                    - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
            expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
            comment: Optional order comment (max 31 characters)

        Returns:
            bool: True if order was placed successfully, False otherwise
        """

        # Validate expiration for time-specific orders
        if type_time in (self.terminal.ORDER_TIME_SPECIFIED, self.terminal.ORDER_TIME_SPECIFIED_DAY) and expiration is None:
            self._error_log(f"Expiration required for order type {type_time}")
            return False

        request = {
            "action": self.terminal.TRADE_ACTION_PENDING,
            "symbol": symbol,
            "volume": volume,
            "type": order_type,
            "price": price,
            "sl": sl,
            "tp": tp,
            "deviation": self.deviation_points,
            "magic": self.magic_number,
            "comment": comment[:31],  # MT5 comment max length is 31 chars
            "type_time": type_time,
            "type_filling": self.filling_type,
        }

        # Add expiration if required
        if type_time in (self.terminal.ORDER_TIME_SPECIFIED, self.terminal.ORDER_TIME_SPECIFIED_DAY) and expiration is not None:

            # Convert to broker's expected format (UTC timestamp in milliseconds)

            expiration_utc = expiration.astimezone(timezone.utc) if expiration.tzinfo else expiration.replace(tzinfo=timezone.utc)
            request["expiration"] = int(expiration_utc.timestamp() * 1000)


        # Send order
        result = self.terminal.order_send(request)
        if result.retcode != self.terminal.TRADE_RETCODE_DONE:
            return False

        # self._info_log(f"Order opened successfully!")
        return True


    def buy(self, volume: float, symbol: str, price: float, sl: float=0.0, tp: float=0.0, comment: str="") -> bool:

        """
        Opens a buy (market) position.

        Args:
            volume: Trade volume (lot size)
            symbol: Trading symbol (e.g., "EURUSD")
            price: Execution price
            sl: Stop loss price (optional, default=0.0)
            tp: Take profit price (optional, default=0.0)
            comment: Position comment (optional, default="")

        Returns:
            bool: True if order was sent successfully, False otherwise
        """

        return self.position_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_BUY, price=price, sl=sl, tp=tp, comment=comment)

    def sell(self, volume: float, symbol: str, price: float, sl: float=0.0, tp: float=0.0, comment: str="") -> bool:

        """
        Opens a sell (market) position.

        Args:
            volume: Trade volume (lot size)
            symbol: Trading symbol (e.g., "EURUSD")
            price: Execution price
            sl: Stop loss price (optional, default=0.0)
            tp: Take profit price (optional, default=0.0)
            comment: Position comment (optional, default="")

        Returns:
            bool: True if order was sent successfully, False otherwise
        """

        return self.position_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_SELL, price=price, sl=sl, tp=tp, comment=comment)

    def buy_limit(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

        """
        Places a buy limit pending order.

        Args:
            volume: Trade volume (lot size)
            price: Execution price
            symbol: Trading symbol (e.g., "EURUSD")
            sl: Stop loss price (optional, default=0.0)
            tp: Take profit price (optional, default=0.0)
            type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
                - ORDER_TIME_GTC (Good-Til-Canceled)
                - ORDER_TIME_DAY (Good for current day)
                - ORDER_TIME_SPECIFIED (expires at specific datetime)
                - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
            expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
            comment: Order comment (optional, default="")

        Returns:
            bool: True if order was placed successfully, False otherwise
        """

        return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_BUY_LIMIT, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)

    def sell_limit(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

        """
        Places a sell limit pending order.

        Args:
            volume: Trade volume (lot size)
            price: Execution price
            symbol: Trading symbol (e.g., "EURUSD")
            sl: Stop loss price (optional, default=0.0)
            tp: Take profit price (optional, default=0.0)
            type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
                - ORDER_TIME_GTC (Good-Til-Canceled)
                - ORDER_TIME_DAY (Good for current day)
                - ORDER_TIME_SPECIFIED (expires at specific datetime)
                - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
            expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
            comment: Order comment (optional, default="")

        Returns:
            bool: True if order was placed successfully, False otherwise
        """

        return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_SELL_LIMIT, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)

    def buy_stop(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

        """
        Places a buy stop pending order.

        Args:
            volume: Trade volume (lot size)
            price: Execution price
            symbol: Trading symbol (e.g., "EURUSD")
            sl: Stop loss price (optional, default=0.0)
            tp: Take profit price (optional, default=0.0)
            type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
                - ORDER_TIME_GTC (Good-Til-Canceled)
                - ORDER_TIME_DAY (Good for current day)
                - ORDER_TIME_SPECIFIED (expires at specific datetime)
                - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
            expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
            comment: Order comment (optional, default="")

        Returns:
            bool: True if order was placed successfully, False otherwise
        """

        return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_BUY_STOP, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)

    def sell_stop(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

        """
        Places a sell stop pending order.

        Args:
            volume: Trade volume (lot size)
            price: Execution price
            symbol: Trading symbol (e.g., "EURUSD")
            sl: Stop loss price (optional, default=0.0)
            tp: Take profit price (optional, default=0.0)
            type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
                  - ORDER_TIME_GTC (Good-Til-Canceled)
                  - ORDER_TIME_DAY (Good for current day)
                  - ORDER_TIME_SPECIFIED (expires at specific datetime)
                  - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
            expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
            comment: Order comment (optional, default="")

        Returns:
            bool: True if order was placed successfully, False otherwise
        """

        return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_SELL_STOP, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)

    def position_close(self, ticket: int, deviation: float=float("nan")) -> bool:

        """
        Closes an open position by ticket number.

        Args:
            ticket: Position ticket number
            deviation: Maximum price deviation in points (optional)

        Returns:
            bool: True if position was closed successfully, False otherwise

        Raises:
            Prints error message if position not found or close fails
        """

        # Select position by ticket
        if not self.terminal.positions_get(ticket=ticket):
            self._warning_log(f"Position with ticket {ticket} not found.")
            return False

        position = self.terminal.positions_get(ticket=ticket)[0]
        symbol = position.symbol
        volume = position.volume
        position_type = position.type  # 0=BUY, 1=SELL

        # Get close price (BID for buy, ASK for sell)

        tick_info = self.terminal.symbol_info_tick(symbol)
        price = tick_info.bid if position_type == self.terminal.POSITION_TYPE_BUY else tick_info.ask

        # Set close order type
        order_type = self.terminal.ORDER_TYPE_SELL if position_type == self.terminal.POSITION_TYPE_BUY else self.terminal.ORDER_TYPE_BUY

        request = {
            "action": self.terminal.TRADE_ACTION_DEAL,
            "position": ticket,
            "symbol": symbol,
            "volume": volume,
            "magic": self.magic_number,
            "type": order_type,
            "price": price,
            "deviation": deviation if not isinstance(deviation, float) or not str(deviation) == 'nan' else self.deviation_points, 
            "type_time": self.terminal.ORDER_TIME_GTC,
            "type_filling": self.filling_type,
        }

        # Send the close request

        if self.terminal.order_send(request) is None:
            return False

        self._info_log(f"Position {ticket} closed successfully!")
        return True

    def order_delete(self, ticket: int) -> bool:

        """
        Deletes a pending order by ticket number.

        Args:
            ticket: Order ticket number

        Returns:
            bool: True if order was deleted successfully, False otherwise

        Raises:
            Prints error message if deletion fails
        """

        order = self.terminal.orders_get(ticket=ticket)[0]
        if order is None:
            self._info_log(f"Order {order} not found!")

        request = {
            "action": self.terminal.TRADE_ACTION_REMOVE,
            "order": ticket,
            "magic": self.magic_number,
            "symbol": order.symbol
        }

        # Send the delete request

        if self.terminal.order_send(request) is None:
            return False

        self._info_log(f"Order {ticket} deleted successfully!")
        return True


    def position_modify(self, ticket: int, sl: float, tp: float) -> bool:

        """
        Modifies stop loss and take profit of an open position.

        Args:
            ticket: Position ticket number
            sl: New stop loss price
            tp: New take profit price

        Returns:
            bool: True if modification was successful, False otherwise

        Raises:
            Prints error message if position not found or modification fails
        """

        # Select position by ticket
        if not self.terminal.positions_get(ticket=ticket):
            self._warning_log(f"Position with ticket {ticket} not found.")
            return False

        position = self.terminal.positions_get(ticket=ticket)[0]
        symbol = position.symbol

        request = {
            "action": self.terminal.TRADE_ACTION_SLTP,
            "position": ticket,
            "magic": self.magic_number,
            "symbol": symbol,
            "sl": sl,
            "tp": tp
        }

        # send a position modify request

        if self.terminal.order_send(request) is None:
            return False

        self._info_log(f"Position {ticket} modified successfully!")
        return True

    def order_modify(self, ticket: int, price: float, sl: float, tp: float, type_time: int = 0, expiration: datetime = None, stoplimit: float = 0.0) -> bool:

        """
        Modify parameters of a pending order with full control similar to MQL5's OrderModify.

        Args:
            ticket: Order ticket number
            price: New activation price for the pending order
            sl: New stop loss price (0 to remove)
            tp: New take profit price (0 to remove)
            type_time: Order expiration type (ORDER_TIME_GTC, ORDER_TIME_DAY, etc.)
            expiration: Order expiration time (required for ORDER_TIME_SPECIFIED)
            stoplimit: StopLimit price for STOP_LIMIT orders

        Returns:
            bool: True if order was modified successfully, False otherwise

        Raises:
            Prints error message if modification fails
        """

        # Get the order by ticket
        order = self.terminal.orders_get(ticket=ticket)
        if not order:
            self._warning_log(f"Order with ticket {ticket} not found")
            return False

        order = order[0]  # Get the first (and only) order

        request = {
            "action": self.terminal.TRADE_ACTION_MODIFY,
            "order": ticket,
            "price": price,
            "sl": sl,
            "tp": tp,
            "symbol": order.symbol,
            "type": order.type,
            "magic": self.magic_number,
            "type_time": type_time,
            "type_filling": self.filling_type,
        }

        # Add expiration if specified (for ORDER_TIME_SPECIFIED)
        if type_time == self.terminal.ORDER_TIME_SPECIFIED:
            if expiration is None:
                self._warning_log("Error: expiration must be specified for ORDER_TIME_SPECIFIED")
                return False

            request["expiration"] = expiration

        # Add stoplimit for STOP_LIMIT orders
        if order.type in (self.terminal.ORDER_TYPE_BUY_STOP_LIMIT, self.terminal.ORDER_TYPE_SELL_STOP_LIMIT):
            request["stoplimit"] = stoplimit

        # Send the modification request

        result = self.terminal.order_send(request=request)
        if result.retcode != self.terminal.TRADE_RETCODE_DONE:
            return False

        # self._info_log(f"Order {ticket} modified successfully!")
        return True

__init__(magic_number, filling_type_symbol, deviation_points, terminal, logger=None)

Initialize a CTrade wrapper for MetaTrader 5 trade operations.

This class resembles the MQL5 Standard Library class CTrade and provides a convenient Python interface for sending and managing trade requests through the MetaTrader 5 Python API.

MQL5 Reference

Args:

terminal (Any): MetaTrader5 module-like or the overloaded/simulated MetaTrader5 instance

magic_number (int): Expert Advisor identifier used to tag and track orders and positions created by this trade object.

filling_type_symbol (str): Symbol name used to determine the appropriate order filling policy through the internal _get_type_filling() helper.

deviation_points (int): Maximum allowed price deviation, in points, when executing market orders.

logger (logging.Logger | None, optional): Logger instance used for diagnostic and error messages. If None, logging output is handled only by the class' internal logic.

Notes
  • The constructor resolves and stores the filling type for the provided symbol at initialization time.
  • If the filling type cannot be resolved, initialization logs a critical error and returns early.
  • This class is intended to act similarly to MQL5's CTrade, where trade settings such as magic number, filling mode, and deviation are configured once and reused across requests.
Source code in strategytester5\trade_classes\Trade.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
def __init__(
        self,
        magic_number: int,
        filling_type_symbol: str,
        deviation_points: int,
        terminal: Union[OverLoadedMetaTrader5API|MetaTrader5],
        logger: logging.Logger | None = None
):
    """
    Initialize a CTrade wrapper for MetaTrader 5 trade operations.

    This class resembles the MQL5 Standard Library class `CTrade` and provides
    a convenient Python interface for sending and managing trade requests through
    the MetaTrader 5 Python API.

    [MQL5 Reference](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade)

    Args:

    terminal (Any):
        MetaTrader5 module-like or the overloaded/simulated MetaTrader5 instance

    magic_number (int):
        Expert Advisor identifier used to tag and track orders and positions
        created by this trade object.

    filling_type_symbol (str):
        Symbol name used to determine the appropriate order filling policy
        through the internal `_get_type_filling()` helper.

    deviation_points (int):
        Maximum allowed price deviation, in points, when executing market
        orders.

    logger (logging.Logger | None, optional):
        Logger instance used for diagnostic and error messages. If None,
        logging output is handled only by the class' internal logic.

    Notes
    -----
    - The constructor resolves and stores the filling type for the provided
      symbol at initialization time.
    - If the filling type cannot be resolved, initialization logs a critical
      error and returns early.
    - This class is intended to act similarly to MQL5's `CTrade`, where trade
      settings such as magic number, filling mode, and deviation are configured
      once and reused across requests.
    """

    self.logger = logger

    self.terminal = terminal

    self.magic_number = magic_number
    self.deviation_points = deviation_points
    self.filling_type = self._get_type_filling(filling_type_symbol)

    if self.filling_type == -1:
        self._critical_log("Failed to initialize the class, Invalid filling type. Check your symbol")
        return

buy(volume, symbol, price, sl=0.0, tp=0.0, comment='')

Opens a buy (market) position.

Parameters:

Name Type Description Default
volume float

Trade volume (lot size)

required
symbol str

Trading symbol (e.g., "EURUSD")

required
price float

Execution price

required
sl float

Stop loss price (optional, default=0.0)

0.0
tp float

Take profit price (optional, default=0.0)

0.0
comment str

Position comment (optional, default="")

''

Returns:

Name Type Description
bool bool

True if order was sent successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def buy(self, volume: float, symbol: str, price: float, sl: float=0.0, tp: float=0.0, comment: str="") -> bool:

    """
    Opens a buy (market) position.

    Args:
        volume: Trade volume (lot size)
        symbol: Trading symbol (e.g., "EURUSD")
        price: Execution price
        sl: Stop loss price (optional, default=0.0)
        tp: Take profit price (optional, default=0.0)
        comment: Position comment (optional, default="")

    Returns:
        bool: True if order was sent successfully, False otherwise
    """

    return self.position_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_BUY, price=price, sl=sl, tp=tp, comment=comment)

buy_limit(volume, price, symbol, sl=0.0, tp=0.0, type_time=0, expiration=None, comment='')

Places a buy limit pending order.

Parameters:

Name Type Description Default
volume float

Trade volume (lot size)

required
price float

Execution price

required
symbol str

Trading symbol (e.g., "EURUSD")

required
sl float

Stop loss price (optional, default=0.0)

0.0
tp float

Take profit price (optional, default=0.0)

0.0
type_time int

Order expiration type (default: ORDER_TIME_GTC). Possible values: - ORDER_TIME_GTC (Good-Til-Canceled) - ORDER_TIME_DAY (Good for current day) - ORDER_TIME_SPECIFIED (expires at specific datetime) - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)

0
expiration datetime

Expiration datetime (required for ORDER_TIME_SPECIFIED types)

None
comment str

Order comment (optional, default="")

''

Returns:

Name Type Description
bool bool

True if order was placed successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def buy_limit(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

    """
    Places a buy limit pending order.

    Args:
        volume: Trade volume (lot size)
        price: Execution price
        symbol: Trading symbol (e.g., "EURUSD")
        sl: Stop loss price (optional, default=0.0)
        tp: Take profit price (optional, default=0.0)
        type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
            - ORDER_TIME_GTC (Good-Til-Canceled)
            - ORDER_TIME_DAY (Good for current day)
            - ORDER_TIME_SPECIFIED (expires at specific datetime)
            - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
        expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
        comment: Order comment (optional, default="")

    Returns:
        bool: True if order was placed successfully, False otherwise
    """

    return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_BUY_LIMIT, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)

buy_stop(volume, price, symbol, sl=0.0, tp=0.0, type_time=0, expiration=None, comment='')

Places a buy stop pending order.

Parameters:

Name Type Description Default
volume float

Trade volume (lot size)

required
price float

Execution price

required
symbol str

Trading symbol (e.g., "EURUSD")

required
sl float

Stop loss price (optional, default=0.0)

0.0
tp float

Take profit price (optional, default=0.0)

0.0
type_time int

Order expiration type (default: ORDER_TIME_GTC). Possible values: - ORDER_TIME_GTC (Good-Til-Canceled) - ORDER_TIME_DAY (Good for current day) - ORDER_TIME_SPECIFIED (expires at specific datetime) - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)

0
expiration datetime

Expiration datetime (required for ORDER_TIME_SPECIFIED types)

None
comment str

Order comment (optional, default="")

''

Returns:

Name Type Description
bool bool

True if order was placed successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def buy_stop(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

    """
    Places a buy stop pending order.

    Args:
        volume: Trade volume (lot size)
        price: Execution price
        symbol: Trading symbol (e.g., "EURUSD")
        sl: Stop loss price (optional, default=0.0)
        tp: Take profit price (optional, default=0.0)
        type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
            - ORDER_TIME_GTC (Good-Til-Canceled)
            - ORDER_TIME_DAY (Good for current day)
            - ORDER_TIME_SPECIFIED (expires at specific datetime)
            - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
        expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
        comment: Order comment (optional, default="")

    Returns:
        bool: True if order was placed successfully, False otherwise
    """

    return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_BUY_STOP, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)

order_delete(ticket)

Deletes a pending order by ticket number.

Parameters:

Name Type Description Default
ticket int

Order ticket number

required

Returns:

Name Type Description
bool bool

True if order was deleted successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
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
def order_delete(self, ticket: int) -> bool:

    """
    Deletes a pending order by ticket number.

    Args:
        ticket: Order ticket number

    Returns:
        bool: True if order was deleted successfully, False otherwise

    Raises:
        Prints error message if deletion fails
    """

    order = self.terminal.orders_get(ticket=ticket)[0]
    if order is None:
        self._info_log(f"Order {order} not found!")

    request = {
        "action": self.terminal.TRADE_ACTION_REMOVE,
        "order": ticket,
        "magic": self.magic_number,
        "symbol": order.symbol
    }

    # Send the delete request

    if self.terminal.order_send(request) is None:
        return False

    self._info_log(f"Order {ticket} deleted successfully!")
    return True

order_modify(ticket, price, sl, tp, type_time=0, expiration=None, stoplimit=0.0)

Modify parameters of a pending order with full control similar to MQL5's OrderModify.

Parameters:

Name Type Description Default
ticket int

Order ticket number

required
price float

New activation price for the pending order

required
sl float

New stop loss price (0 to remove)

required
tp float

New take profit price (0 to remove)

required
type_time int

Order expiration type (ORDER_TIME_GTC, ORDER_TIME_DAY, etc.)

0
expiration datetime

Order expiration time (required for ORDER_TIME_SPECIFIED)

None
stoplimit float

StopLimit price for STOP_LIMIT orders

0.0

Returns:

Name Type Description
bool bool

True if order was modified successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
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
def order_modify(self, ticket: int, price: float, sl: float, tp: float, type_time: int = 0, expiration: datetime = None, stoplimit: float = 0.0) -> bool:

    """
    Modify parameters of a pending order with full control similar to MQL5's OrderModify.

    Args:
        ticket: Order ticket number
        price: New activation price for the pending order
        sl: New stop loss price (0 to remove)
        tp: New take profit price (0 to remove)
        type_time: Order expiration type (ORDER_TIME_GTC, ORDER_TIME_DAY, etc.)
        expiration: Order expiration time (required for ORDER_TIME_SPECIFIED)
        stoplimit: StopLimit price for STOP_LIMIT orders

    Returns:
        bool: True if order was modified successfully, False otherwise

    Raises:
        Prints error message if modification fails
    """

    # Get the order by ticket
    order = self.terminal.orders_get(ticket=ticket)
    if not order:
        self._warning_log(f"Order with ticket {ticket} not found")
        return False

    order = order[0]  # Get the first (and only) order

    request = {
        "action": self.terminal.TRADE_ACTION_MODIFY,
        "order": ticket,
        "price": price,
        "sl": sl,
        "tp": tp,
        "symbol": order.symbol,
        "type": order.type,
        "magic": self.magic_number,
        "type_time": type_time,
        "type_filling": self.filling_type,
    }

    # Add expiration if specified (for ORDER_TIME_SPECIFIED)
    if type_time == self.terminal.ORDER_TIME_SPECIFIED:
        if expiration is None:
            self._warning_log("Error: expiration must be specified for ORDER_TIME_SPECIFIED")
            return False

        request["expiration"] = expiration

    # Add stoplimit for STOP_LIMIT orders
    if order.type in (self.terminal.ORDER_TYPE_BUY_STOP_LIMIT, self.terminal.ORDER_TYPE_SELL_STOP_LIMIT):
        request["stoplimit"] = stoplimit

    # Send the modification request

    result = self.terminal.order_send(request=request)
    if result.retcode != self.terminal.TRADE_RETCODE_DONE:
        return False

    # self._info_log(f"Order {ticket} modified successfully!")
    return True

order_open(symbol, volume, order_type, price, sl=0.0, tp=0.0, type_time=0, expiration=None, comment='')

Opens a pending order with full control over order parameters.

Parameters:

Name Type Description Default
symbol str

Trading symbol (e.g., "EURUSD")

required
volume float

Order volume in lots

required
order_type int

Order type (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_STOP, etc.)

required
price float

Activation price for pending order

required
sl float

Stop loss price (0 to disable)

0.0
tp float

Take profit price (0 to disable)

0.0
type_time int

Order expiration type (default: ORDER_TIME_GTC). Possible values: - ORDER_TIME_GTC (Good-Til-Canceled) - ORDER_TIME_DAY (Good for current day) - ORDER_TIME_SPECIFIED (expires at specific datetime) - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)

0
expiration datetime

Expiration datetime (required for ORDER_TIME_SPECIFIED types)

None
comment str

Optional order comment (max 31 characters)

''

Returns:

Name Type Description
bool bool

True if order was placed successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
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
def order_open(self, symbol: str, volume: float, order_type: int, price: float, sl: float = 0.0, tp: float = 0.0, type_time: int = 0, expiration: datetime = None, comment: str = "") -> bool:

    """
    Opens a pending order with full control over order parameters.

    Args:
        symbol: Trading symbol (e.g., "EURUSD")
        volume: Order volume in lots
        order_type: Order type (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_STOP, etc.)
        price: Activation price for pending order
        sl: Stop loss price (0 to disable)
        tp: Take profit price (0 to disable)
        type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
                - ORDER_TIME_GTC (Good-Til-Canceled)
                - ORDER_TIME_DAY (Good for current day)
                - ORDER_TIME_SPECIFIED (expires at specific datetime)
                - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
        expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
        comment: Optional order comment (max 31 characters)

    Returns:
        bool: True if order was placed successfully, False otherwise
    """

    # Validate expiration for time-specific orders
    if type_time in (self.terminal.ORDER_TIME_SPECIFIED, self.terminal.ORDER_TIME_SPECIFIED_DAY) and expiration is None:
        self._error_log(f"Expiration required for order type {type_time}")
        return False

    request = {
        "action": self.terminal.TRADE_ACTION_PENDING,
        "symbol": symbol,
        "volume": volume,
        "type": order_type,
        "price": price,
        "sl": sl,
        "tp": tp,
        "deviation": self.deviation_points,
        "magic": self.magic_number,
        "comment": comment[:31],  # MT5 comment max length is 31 chars
        "type_time": type_time,
        "type_filling": self.filling_type,
    }

    # Add expiration if required
    if type_time in (self.terminal.ORDER_TIME_SPECIFIED, self.terminal.ORDER_TIME_SPECIFIED_DAY) and expiration is not None:

        # Convert to broker's expected format (UTC timestamp in milliseconds)

        expiration_utc = expiration.astimezone(timezone.utc) if expiration.tzinfo else expiration.replace(tzinfo=timezone.utc)
        request["expiration"] = int(expiration_utc.timestamp() * 1000)


    # Send order
    result = self.terminal.order_send(request)
    if result.retcode != self.terminal.TRADE_RETCODE_DONE:
        return False

    # self._info_log(f"Order opened successfully!")
    return True

position_close(ticket, deviation=float('nan'))

Closes an open position by ticket number.

Parameters:

Name Type Description Default
ticket int

Position ticket number

required
deviation float

Maximum price deviation in points (optional)

float('nan')

Returns:

Name Type Description
bool bool

True if position was closed successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
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
def position_close(self, ticket: int, deviation: float=float("nan")) -> bool:

    """
    Closes an open position by ticket number.

    Args:
        ticket: Position ticket number
        deviation: Maximum price deviation in points (optional)

    Returns:
        bool: True if position was closed successfully, False otherwise

    Raises:
        Prints error message if position not found or close fails
    """

    # Select position by ticket
    if not self.terminal.positions_get(ticket=ticket):
        self._warning_log(f"Position with ticket {ticket} not found.")
        return False

    position = self.terminal.positions_get(ticket=ticket)[0]
    symbol = position.symbol
    volume = position.volume
    position_type = position.type  # 0=BUY, 1=SELL

    # Get close price (BID for buy, ASK for sell)

    tick_info = self.terminal.symbol_info_tick(symbol)
    price = tick_info.bid if position_type == self.terminal.POSITION_TYPE_BUY else tick_info.ask

    # Set close order type
    order_type = self.terminal.ORDER_TYPE_SELL if position_type == self.terminal.POSITION_TYPE_BUY else self.terminal.ORDER_TYPE_BUY

    request = {
        "action": self.terminal.TRADE_ACTION_DEAL,
        "position": ticket,
        "symbol": symbol,
        "volume": volume,
        "magic": self.magic_number,
        "type": order_type,
        "price": price,
        "deviation": deviation if not isinstance(deviation, float) or not str(deviation) == 'nan' else self.deviation_points, 
        "type_time": self.terminal.ORDER_TIME_GTC,
        "type_filling": self.filling_type,
    }

    # Send the close request

    if self.terminal.order_send(request) is None:
        return False

    self._info_log(f"Position {ticket} closed successfully!")
    return True

position_modify(ticket, sl, tp)

Modifies stop loss and take profit of an open position.

Parameters:

Name Type Description Default
ticket int

Position ticket number

required
sl float

New stop loss price

required
tp float

New take profit price

required

Returns:

Name Type Description
bool bool

True if modification was successful, False otherwise

Source code in strategytester5\trade_classes\Trade.py
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
def position_modify(self, ticket: int, sl: float, tp: float) -> bool:

    """
    Modifies stop loss and take profit of an open position.

    Args:
        ticket: Position ticket number
        sl: New stop loss price
        tp: New take profit price

    Returns:
        bool: True if modification was successful, False otherwise

    Raises:
        Prints error message if position not found or modification fails
    """

    # Select position by ticket
    if not self.terminal.positions_get(ticket=ticket):
        self._warning_log(f"Position with ticket {ticket} not found.")
        return False

    position = self.terminal.positions_get(ticket=ticket)[0]
    symbol = position.symbol

    request = {
        "action": self.terminal.TRADE_ACTION_SLTP,
        "position": ticket,
        "magic": self.magic_number,
        "symbol": symbol,
        "sl": sl,
        "tp": tp
    }

    # send a position modify request

    if self.terminal.order_send(request) is None:
        return False

    self._info_log(f"Position {ticket} modified successfully!")
    return True

position_open(symbol, volume, order_type, price, sl=0.0, tp=0.0, comment='')

Open a market position (instant execution).

Executes either a buy or sell order at the current market price. This is for immediate position opening, not pending orders.

Parameters:

Name Type Description Default
symbol str

Trading symbol (e.g., "EURUSD", "GBPUSD")

required
volume float

Trade volume in lots (e.g., 0.1 for micro lot)

required
order_type int

Trade direction (either ORDER_TYPE_BUY or ORDER_TYPE_SELL)

required
price float

Execution price. For market orders, this should be the current: - Ask price for BUY orders - Bid price for SELL orders

required
sl float

Stop loss price (set to 0.0 to disable)

0.0
tp float

Take profit price (set to 0.0 to disable)

0.0
comment str

Optional order comment (max 31 characters, will be truncated automatically)

''

Returns:

Name Type Description
bool bool

True if position was opened successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
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
def position_open(self, symbol: str, volume: float, order_type: int, price: float, sl: float=0.0, tp: float=0.0, comment: str="") -> bool:

    """
    Open a market position (instant execution).

    Executes either a buy or sell order at the current market price. This is for immediate
    position opening, not pending orders.

    Args:
        symbol: Trading symbol (e.g., "EURUSD", "GBPUSD")
        volume: Trade volume in lots (e.g., 0.1 for micro lot)
        order_type: Trade direction (either ORDER_TYPE_BUY or ORDER_TYPE_SELL)
        price: Execution price. For market orders, this should be the current:
            - Ask price for BUY orders
            - Bid price for SELL orders
        sl: Stop loss price (set to 0.0 to disable)
        tp: Take profit price (set to 0.0 to disable)
        comment: Optional order comment (max 31 characters, will be truncated automatically)

    Returns:
        bool: True if position was opened successfully, False otherwise
    """

    request = {
        "action": self.terminal.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": volume,
        "type": order_type,
        "price": price,
        "deviation": self.deviation_points,
        "magic": self.magic_number,
        "comment": comment,
        "type_time": self.terminal.ORDER_TIME_GTC,
        "type_filling":  self.filling_type,
    }

    if sl > 0.0:
        request["sl"] = sl
    if tp > 0.0:
        request["tp"] = tp

    result = self.terminal.order_send(request)
    if result.retcode != self.terminal.TRADE_RETCODE_DONE:
        return False

    self._info_log(f"Position #{result.deal} Opened successfully!")
    return True

sell(volume, symbol, price, sl=0.0, tp=0.0, comment='')

Opens a sell (market) position.

Parameters:

Name Type Description Default
volume float

Trade volume (lot size)

required
symbol str

Trading symbol (e.g., "EURUSD")

required
price float

Execution price

required
sl float

Stop loss price (optional, default=0.0)

0.0
tp float

Take profit price (optional, default=0.0)

0.0
comment str

Position comment (optional, default="")

''

Returns:

Name Type Description
bool bool

True if order was sent successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def sell(self, volume: float, symbol: str, price: float, sl: float=0.0, tp: float=0.0, comment: str="") -> bool:

    """
    Opens a sell (market) position.

    Args:
        volume: Trade volume (lot size)
        symbol: Trading symbol (e.g., "EURUSD")
        price: Execution price
        sl: Stop loss price (optional, default=0.0)
        tp: Take profit price (optional, default=0.0)
        comment: Position comment (optional, default="")

    Returns:
        bool: True if order was sent successfully, False otherwise
    """

    return self.position_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_SELL, price=price, sl=sl, tp=tp, comment=comment)

sell_limit(volume, price, symbol, sl=0.0, tp=0.0, type_time=0, expiration=None, comment='')

Places a sell limit pending order.

Parameters:

Name Type Description Default
volume float

Trade volume (lot size)

required
price float

Execution price

required
symbol str

Trading symbol (e.g., "EURUSD")

required
sl float

Stop loss price (optional, default=0.0)

0.0
tp float

Take profit price (optional, default=0.0)

0.0
type_time int

Order expiration type (default: ORDER_TIME_GTC). Possible values: - ORDER_TIME_GTC (Good-Til-Canceled) - ORDER_TIME_DAY (Good for current day) - ORDER_TIME_SPECIFIED (expires at specific datetime) - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)

0
expiration datetime

Expiration datetime (required for ORDER_TIME_SPECIFIED types)

None
comment str

Order comment (optional, default="")

''

Returns:

Name Type Description
bool bool

True if order was placed successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def sell_limit(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

    """
    Places a sell limit pending order.

    Args:
        volume: Trade volume (lot size)
        price: Execution price
        symbol: Trading symbol (e.g., "EURUSD")
        sl: Stop loss price (optional, default=0.0)
        tp: Take profit price (optional, default=0.0)
        type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
            - ORDER_TIME_GTC (Good-Til-Canceled)
            - ORDER_TIME_DAY (Good for current day)
            - ORDER_TIME_SPECIFIED (expires at specific datetime)
            - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
        expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
        comment: Order comment (optional, default="")

    Returns:
        bool: True if order was placed successfully, False otherwise
    """

    return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_SELL_LIMIT, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)

sell_stop(volume, price, symbol, sl=0.0, tp=0.0, type_time=0, expiration=None, comment='')

Places a sell stop pending order.

Parameters:

Name Type Description Default
volume float

Trade volume (lot size)

required
price float

Execution price

required
symbol str

Trading symbol (e.g., "EURUSD")

required
sl float

Stop loss price (optional, default=0.0)

0.0
tp float

Take profit price (optional, default=0.0)

0.0
type_time int

Order expiration type (default: ORDER_TIME_GTC). Possible values: - ORDER_TIME_GTC (Good-Til-Canceled) - ORDER_TIME_DAY (Good for current day) - ORDER_TIME_SPECIFIED (expires at specific datetime) - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)

0
expiration datetime

Expiration datetime (required for ORDER_TIME_SPECIFIED types)

None
comment str

Order comment (optional, default="")

''

Returns:

Name Type Description
bool bool

True if order was placed successfully, False otherwise

Source code in strategytester5\trade_classes\Trade.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
def sell_stop(self, volume: float, price: float, symbol: str, sl: float=0.0, tp: float=0.0, type_time: int=0, expiration: datetime=None, comment: str="") -> bool:

    """
    Places a sell stop pending order.

    Args:
        volume: Trade volume (lot size)
        price: Execution price
        symbol: Trading symbol (e.g., "EURUSD")
        sl: Stop loss price (optional, default=0.0)
        tp: Take profit price (optional, default=0.0)
        type_time: Order expiration type (default: ORDER_TIME_GTC). Possible values:
              - ORDER_TIME_GTC (Good-Til-Canceled)
              - ORDER_TIME_DAY (Good for current day)
              - ORDER_TIME_SPECIFIED (expires at specific datetime)
              - ORDER_TIME_SPECIFIED_DAY (expires at end of specified day)
        expiration: Expiration datetime (required for ORDER_TIME_SPECIFIED types)
        comment: Order comment (optional, default="")

    Returns:
        bool: True if order was placed successfully, False otherwise
    """

    return self.order_open(symbol=symbol, volume=volume, order_type=self.terminal.ORDER_TYPE_SELL_STOP, price=price, sl=sl, tp=tp, type_time=type_time, expiration=expiration, comment=comment)