From 37af02d829ed13a89718294ebb7a6b0178864c26 Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Tue, 13 Jul 2021 22:15:19 +0200 Subject: [PATCH 01/11] Init --- algobot/enums.py | 17 +++++++++++++-- algobot/interface/configuration.py | 8 ++++---- algobot/traders/trader.py | 33 +++++++++++++++--------------- tests/test_backtester.py | 16 +++++++-------- tests/test_base_trader.py | 22 ++++++++++---------- 5 files changed, 55 insertions(+), 41 deletions(-) diff --git a/algobot/enums.py b/algobot/enums.py index 7445e8bd..dd688c6b 100644 --- a/algobot/enums.py +++ b/algobot/enums.py @@ -13,8 +13,21 @@ LONG = 1 SHORT = -1 -TRAILING = 2 -STOP = 1 + +class StopType: + TRAILING = 2 + STOP = 1 + + +class LossStrategy: + TRAILING = 2 + STOP = 1 + + +class ProfitType: + TRAILING = 2 + STOP = 1 + BACKTEST = 2 SIMULATION = 3 diff --git a/algobot/interface/configuration.py b/algobot/interface/configuration.py index 83924216..ab82983f 100644 --- a/algobot/interface/configuration.py +++ b/algobot/interface/configuration.py @@ -8,7 +8,7 @@ QTabWidget) import algobot.helpers as helpers -from algobot.enums import BACKTEST, LIVE, OPTIMIZER, SIMULATION, STOP, TRAILING +from algobot.enums import BACKTEST, LIVE, OPTIMIZER, SIMULATION, StopType from algobot.graph_helpers import create_infinite_line from algobot.interface.config_utils.credential_utils import load_credentials from algobot.interface.config_utils.slot_utils import load_slots @@ -341,9 +341,9 @@ def get_take_profit_settings(self, caller) -> dict: dictionary = self.takeProfitDict if dictionary[tab, 'groupBox'].isChecked(): if dictionary[tab, 'takeProfitType'].currentText() == "Trailing": - takeProfitType = TRAILING + takeProfitType = StopType.TRAILING else: - takeProfitType = STOP + takeProfitType = StopType.STOP else: takeProfitType = None @@ -378,7 +378,7 @@ def get_loss_settings(self, caller: int) -> dict: tab = self.get_category_tab(caller) dictionary = self.lossDict if dictionary[tab, 'groupBox'].isChecked(): - lossType = TRAILING if dictionary[tab, "lossType"].currentText() == "Trailing" else STOP + lossType = StopType.TRAILING if dictionary[tab, "lossType"].currentText() == "Trailing" else StopType.STOP else: lossType = None diff --git a/algobot/traders/trader.py b/algobot/traders/trader.py index 87b1785d..4c6de6a1 100644 --- a/algobot/traders/trader.py +++ b/algobot/traders/trader.py @@ -2,10 +2,11 @@ This will be the main Trader class that all other Traders will inherit from. """ from datetime import datetime -from typing import Dict, List, Union +from typing import Dict, List, Optional, Union from algobot.enums import (BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, - EXIT_LONG, EXIT_SHORT, LONG, SHORT, STOP, TRAILING) + EXIT_LONG, EXIT_SHORT, LONG, SHORT, LossStrategy, + ProfitType, StopType) from algobot.helpers import get_label_string, parse_strategy_name from algobot.strategies.strategy import Strategy @@ -224,16 +225,16 @@ def get_stop_loss(self): if self.currentPosition == SHORT: if self.smartStopLossEnter and self.previousStopLoss > self.currentPrice: self.stopLoss = self.previousStopLoss - elif self.lossStrategy == TRAILING: + elif self.lossStrategy == LossStrategy.TRAILING: self.stopLoss = self.shortTrailingPrice * (1 + self.lossPercentageDecimal) - elif self.lossStrategy == STOP: + elif self.lossStrategy == LossStrategy.STOP: self.stopLoss = self.sellShortPrice * (1 + self.lossPercentageDecimal) elif self.currentPosition == LONG: if self.smartStopLossEnter and self.previousStopLoss < self.currentPrice: self.stopLoss = self.previousStopLoss - elif self.lossStrategy == TRAILING: + elif self.lossStrategy == LossStrategy.TRAILING: self.stopLoss = self.longTrailingPrice * (1 - self.lossPercentageDecimal) - elif self.lossStrategy == STOP: + elif self.lossStrategy == LossStrategy.STOP: self.stopLoss = self.buyLongPrice * (1 - self.lossPercentageDecimal) if self.stopLoss is not None: # This is for the smart stop loss to reenter position. @@ -246,9 +247,9 @@ def get_stop_loss_strategy_string(self) -> str: Returns stop loss strategy in string format, instead of integer enum. :return: Stop loss strategy in string format. """ - if self.lossStrategy == STOP: + if self.lossStrategy == LossStrategy.STOP: return 'Stop Loss' - elif self.lossStrategy == TRAILING: + elif self.lossStrategy == LossStrategy.TRAILING: return 'Trailing Loss' elif self.lossStrategy is None: return 'None' @@ -322,16 +323,16 @@ def get_profit_percentage(initialNet: float, finalNet: float) -> float: return -1 * (100 - finalNet / initialNet * 100) @staticmethod - def get_trailing_or_stop_type_string(stopType: Union[int, None]) -> str: + def get_trailing_or_stop_type_string(stop_type: Optional[int]) -> str: """ Returns stop type in string format instead of integer enum. :return: Stop type in string format. """ - if stopType == STOP: + if stop_type == StopType.STOP: return 'Stop' - elif stopType == TRAILING: + elif stop_type == StopType.TRAILING: return 'Trailing' - elif stopType is None: + elif stop_type is None: return 'None' else: raise ValueError("Unknown type of exit position type.") @@ -339,9 +340,9 @@ def get_trailing_or_stop_type_string(stopType: Union[int, None]) -> str: @staticmethod def get_enum_from_str(string): if string.lower() == "trailing": - return TRAILING + return StopType.TRAILING elif string.lower() == 'stop': - return STOP + return StopType.STOP @staticmethod def get_trend_string(trend) -> str: @@ -436,12 +437,12 @@ def get_take_profit(self) -> Union[float, None]: return None if self.currentPosition == SHORT: - if self.takeProfitType == STOP: + if self.takeProfitType == ProfitType.STOP: self.takeProfitPoint = self.sellShortPrice * (1 - self.takeProfitPercentageDecimal) else: raise ValueError("Invalid type of take profit type provided.") elif self.currentPosition == LONG: - if self.takeProfitType == STOP: + if self.takeProfitType == ProfitType.STOP: self.takeProfitPoint = self.buyLongPrice * (1 + self.takeProfitPercentageDecimal) else: raise ValueError("Invalid type of take profit type provided.") diff --git a/tests/test_backtester.py b/tests/test_backtester.py index 83c2d3e7..161f70f2 100644 --- a/tests/test_backtester.py +++ b/tests/test_backtester.py @@ -4,7 +4,7 @@ import pytest -from algobot.enums import LONG, SHORT, STOP, TRAILING +from algobot.enums import LONG, SHORT, LossStrategy, ProfitType, StopType from algobot.helpers import convert_all_dates_to_datetime, load_from_csv from algobot.traders.backtester import Backtester @@ -25,8 +25,8 @@ def setUp(self) -> None: symbol="1INCHUSDT", marginEnabled=True, ) - self.backtester.apply_take_profit_settings({'takeProfitType': TRAILING, 'takeProfitPercentage': 5}) - self.backtester.apply_loss_settings({'lossType': TRAILING, 'lossPercentage': 5}) + self.backtester.apply_take_profit_settings({'takeProfitType': StopType.TRAILING, 'takeProfitPercentage': 5}) + self.backtester.apply_loss_settings({'lossType': StopType.TRAILING, 'lossPercentage': 5}) def test_initialization(self): """ @@ -281,7 +281,7 @@ def test_long_stop_loss(self): Test backtester stop loss logic in a long position. """ backtester = self.backtester - backtester.lossStrategy = STOP + backtester.lossStrategy = LossStrategy.STOP backtester.set_priced_current_price_and_period(5) backtester.buy_long("Test purchase.") self.assertEqual(backtester.get_stop_loss(), 5 * (1 - backtester.lossPercentageDecimal)) @@ -289,7 +289,7 @@ def test_long_stop_loss(self): backtester.set_priced_current_price_and_period(10) self.assertEqual(backtester.get_stop_loss(), 5 * (1 - backtester.lossPercentageDecimal)) - backtester.lossStrategy = TRAILING + backtester.lossStrategy = LossStrategy.TRAILING self.assertEqual(backtester.get_stop_loss(), 10 * (1 - backtester.lossPercentageDecimal)) def test_short_stop_loss(self): @@ -297,7 +297,7 @@ def test_short_stop_loss(self): Test backtester stop loss logic in a short position. """ backtester = self.backtester - backtester.lossStrategy = STOP + backtester.lossStrategy = LossStrategy.STOP backtester.set_priced_current_price_and_period(5) backtester.sell_short("Test short.") self.assertEqual(backtester.get_stop_loss(), 5 * (1 + backtester.lossPercentageDecimal)) @@ -305,7 +305,7 @@ def test_short_stop_loss(self): backtester.set_priced_current_price_and_period(3) self.assertEqual(backtester.get_stop_loss(), 5 * (1 + backtester.lossPercentageDecimal)) - backtester.lossStrategy = TRAILING + backtester.lossStrategy = LossStrategy.TRAILING self.assertEqual(backtester.get_stop_loss(), 3 * (1 + backtester.lossPercentageDecimal)) def test_stop_take_profit(self): @@ -313,7 +313,7 @@ def test_stop_take_profit(self): Test backtester take profit logic. """ backtester = self.backtester - backtester.takeProfitType = STOP + backtester.takeProfitType = ProfitType.STOP backtester.set_priced_current_price_and_period(10) backtester.buy_long("Test purchase.") self.assertEqual(backtester.get_take_profit(), 10 * (1 + backtester.takeProfitPercentageDecimal)) diff --git a/tests/test_base_trader.py b/tests/test_base_trader.py index 85012201..0bb53ef9 100644 --- a/tests/test_base_trader.py +++ b/tests/test_base_trader.py @@ -2,7 +2,7 @@ import pytest -from algobot.enums import BEARISH, BULLISH, LONG, SHORT, STOP, TRAILING +from algobot.enums import BEARISH, BULLISH, LONG, SHORT, LossStrategy, StopType from algobot.strategies.strategy import Strategy from algobot.traders.trader import Trader @@ -149,30 +149,30 @@ def test_set_safety_timer(self): def test_apply_take_profit_settings(self): take_profit_settings = { 'takeProfitPercentage': 25, - 'takeProfitType': STOP + 'takeProfitType': StopType.STOP } self.trader.apply_take_profit_settings(take_profit_settings) self.assertEqual(self.trader.takeProfitPercentageDecimal, 0.25) - self.assertEqual(self.trader.takeProfitType, STOP) + self.assertEqual(self.trader.takeProfitType, StopType.STOP) def test_apply_loss_settings(self): loss_settings = { - 'lossType': STOP, + 'lossType': StopType.STOP, 'lossPercentage': 5.5, 'smartStopLossCounter': 15, 'safetyTimer': 45 } self.trader.apply_loss_settings(loss_settings) - self.assertEqual(self.trader.lossStrategy, STOP) + self.assertEqual(self.trader.lossStrategy, StopType.STOP) self.assertEqual(self.trader.lossPercentageDecimal, 0.055) self.assertEqual(self.trader.smartStopLossInitialCounter, 15) self.assertEqual(self.trader.smartStopLossCounter, 15) self.assertEqual(self.trader.safetyTimer, 45) def test_get_stop_loss(self): - self.trader.lossStrategy = STOP + self.trader.lossStrategy = StopType.STOP self.trader.lossPercentageDecimal = 0.1 self.trader.currentPrice = 5 @@ -190,10 +190,10 @@ def test_get_stop_loss(self): # TODO implement trailing stop loss test def test_get_stop_loss_strategy_string(self): - self.trader.lossStrategy = STOP + self.trader.lossStrategy = LossStrategy.STOP self.assertEqual(self.trader.get_stop_loss_strategy_string(), "Stop Loss") - self.trader.lossStrategy = TRAILING + self.trader.lossStrategy = LossStrategy.TRAILING self.assertEqual(self.trader.get_stop_loss_strategy_string(), "Trailing Loss") self.trader.lossStrategy = None @@ -274,8 +274,8 @@ def test_get_profit_percentage(self): self.assertEqual(self.trader.get_profit_percentage(100, 130), 30) def test_get_trailing_or_stop_loss_string(self): - self.assertEqual(self.trader.get_trailing_or_stop_type_string(STOP), 'Stop') - self.assertEqual(self.trader.get_trailing_or_stop_type_string(TRAILING), 'Trailing') + self.assertEqual(self.trader.get_trailing_or_stop_type_string(StopType.STOP), 'Stop') + self.assertEqual(self.trader.get_trailing_or_stop_type_string(StopType.TRAILING), 'Trailing') self.assertEqual(self.trader.get_trailing_or_stop_type_string(None), 'None') def test_get_trend_string(self): @@ -321,7 +321,7 @@ def test_get_safe_rounded_string(self): multiplier=5), '6.15*') def test_get_take_profit(self): - self.trader.takeProfitType = STOP + self.trader.takeProfitType = StopType.STOP self.trader.takeProfitPercentageDecimal = 0.05 self.trader.currentPosition = LONG From 322cba107cd8986089a2c431167fc73a3702f372 Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Tue, 13 Jul 2021 22:26:07 +0200 Subject: [PATCH 02/11] Refactor --- algobot/interface/configuration.py | 16 +++++++++------- tests/test_backtester.py | 6 +++--- tests/test_base_trader.py | 4 ++-- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/algobot/interface/configuration.py b/algobot/interface/configuration.py index ab82983f..9a21b73f 100644 --- a/algobot/interface/configuration.py +++ b/algobot/interface/configuration.py @@ -8,7 +8,8 @@ QTabWidget) import algobot.helpers as helpers -from algobot.enums import BACKTEST, LIVE, OPTIMIZER, SIMULATION, StopType +from algobot.enums import (BACKTEST, LIVE, OPTIMIZER, SIMULATION, LossStrategy, + StopType) from algobot.graph_helpers import create_infinite_line from algobot.interface.config_utils.credential_utils import load_credentials from algobot.interface.config_utils.slot_utils import load_slots @@ -378,21 +379,22 @@ def get_loss_settings(self, caller: int) -> dict: tab = self.get_category_tab(caller) dictionary = self.lossDict if dictionary[tab, 'groupBox'].isChecked(): - lossType = StopType.TRAILING if dictionary[tab, "lossType"].currentText() == "Trailing" else StopType.STOP + loss_type = dictionary[tab, "lossType"].currentText() + loss_strategy = LossStrategy.TRAILING if loss_type == "Trailing" else LossStrategy.STOP else: - lossType = None + loss_strategy = None - lossSettings = { - 'lossType': lossType, + loss_settings = { + 'lossType': loss_strategy, 'lossTypeIndex': dictionary[tab, "lossType"].currentIndex(), 'lossPercentage': dictionary[tab, 'lossPercentage'].value(), 'smartStopLossCounter': dictionary[tab, 'smartStopLossCounter'].value() } if tab != self.backtestConfigurationTabWidget: - lossSettings['safetyTimer'] = dictionary[tab, 'safetyTimer'].value() + loss_settings['safetyTimer'] = dictionary[tab, 'safetyTimer'].value() - return lossSettings + return loss_settings def add_strategy_to_config(self, caller: int, strategyName: str, config: dict): """ diff --git a/tests/test_backtester.py b/tests/test_backtester.py index 161f70f2..66fc1022 100644 --- a/tests/test_backtester.py +++ b/tests/test_backtester.py @@ -4,7 +4,7 @@ import pytest -from algobot.enums import LONG, SHORT, LossStrategy, ProfitType, StopType +from algobot.enums import LONG, SHORT, LossStrategy, ProfitType from algobot.helpers import convert_all_dates_to_datetime, load_from_csv from algobot.traders.backtester import Backtester @@ -25,8 +25,8 @@ def setUp(self) -> None: symbol="1INCHUSDT", marginEnabled=True, ) - self.backtester.apply_take_profit_settings({'takeProfitType': StopType.TRAILING, 'takeProfitPercentage': 5}) - self.backtester.apply_loss_settings({'lossType': StopType.TRAILING, 'lossPercentage': 5}) + self.backtester.apply_take_profit_settings({'takeProfitType': ProfitType.TRAILING, 'takeProfitPercentage': 5}) + self.backtester.apply_loss_settings({'lossType': LossStrategy.TRAILING, 'lossPercentage': 5}) def test_initialization(self): """ diff --git a/tests/test_base_trader.py b/tests/test_base_trader.py index 0bb53ef9..41d8c78f 100644 --- a/tests/test_base_trader.py +++ b/tests/test_base_trader.py @@ -165,14 +165,14 @@ def test_apply_loss_settings(self): } self.trader.apply_loss_settings(loss_settings) - self.assertEqual(self.trader.lossStrategy, StopType.STOP) + self.assertEqual(self.trader.lossStrategy, LossStrategy.STOP) self.assertEqual(self.trader.lossPercentageDecimal, 0.055) self.assertEqual(self.trader.smartStopLossInitialCounter, 15) self.assertEqual(self.trader.smartStopLossCounter, 15) self.assertEqual(self.trader.safetyTimer, 45) def test_get_stop_loss(self): - self.trader.lossStrategy = StopType.STOP + self.trader.lossStrategy = LossStrategy.STOP self.trader.lossPercentageDecimal = 0.1 self.trader.currentPrice = 5 From abaa8633b6c40c439af2e2c0da665eab72821e47 Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Tue, 13 Jul 2021 22:32:50 +0200 Subject: [PATCH 03/11] Update --- algobot/interface/configuration.py | 6 +++--- algobot/traders/trader.py | 20 ++++++++++---------- tests/test_base_trader.py | 9 +++++---- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/algobot/interface/configuration.py b/algobot/interface/configuration.py index 9a21b73f..df278ce1 100644 --- a/algobot/interface/configuration.py +++ b/algobot/interface/configuration.py @@ -9,7 +9,7 @@ import algobot.helpers as helpers from algobot.enums import (BACKTEST, LIVE, OPTIMIZER, SIMULATION, LossStrategy, - StopType) + ProfitType) from algobot.graph_helpers import create_infinite_line from algobot.interface.config_utils.credential_utils import load_credentials from algobot.interface.config_utils.slot_utils import load_slots @@ -342,9 +342,9 @@ def get_take_profit_settings(self, caller) -> dict: dictionary = self.takeProfitDict if dictionary[tab, 'groupBox'].isChecked(): if dictionary[tab, 'takeProfitType'].currentText() == "Trailing": - takeProfitType = StopType.TRAILING + takeProfitType = ProfitType.TRAILING else: - takeProfitType = StopType.STOP + takeProfitType = ProfitType.STOP else: takeProfitType = None diff --git a/algobot/traders/trader.py b/algobot/traders/trader.py index 4c6de6a1..f66b3a48 100644 --- a/algobot/traders/trader.py +++ b/algobot/traders/trader.py @@ -6,7 +6,7 @@ from algobot.enums import (BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, EXIT_LONG, EXIT_SHORT, LONG, SHORT, LossStrategy, - ProfitType, StopType) + ProfitType) from algobot.helpers import get_label_string, parse_strategy_name from algobot.strategies.strategy import Strategy @@ -323,26 +323,26 @@ def get_profit_percentage(initialNet: float, finalNet: float) -> float: return -1 * (100 - finalNet / initialNet * 100) @staticmethod - def get_trailing_or_stop_type_string(stop_type: Optional[int]) -> str: + def get_trailing_or_stop_type_string(profit_type: Optional[int]) -> str: """ Returns stop type in string format instead of integer enum. :return: Stop type in string format. """ - if stop_type == StopType.STOP: + if profit_type == ProfitType.STOP: return 'Stop' - elif stop_type == StopType.TRAILING: + elif profit_type == ProfitType.TRAILING: return 'Trailing' - elif stop_type is None: + elif profit_type is None: return 'None' else: raise ValueError("Unknown type of exit position type.") @staticmethod - def get_enum_from_str(string): - if string.lower() == "trailing": - return StopType.TRAILING - elif string.lower() == 'stop': - return StopType.STOP + def get_enum_from_str(value: str) -> int: + if value.lower() == "trailing": + return ProfitType.TRAILING + elif value.lower() == 'stop': + return ProfitType.STOP @staticmethod def get_trend_string(trend) -> str: diff --git a/tests/test_base_trader.py b/tests/test_base_trader.py index 41d8c78f..cf314da6 100644 --- a/tests/test_base_trader.py +++ b/tests/test_base_trader.py @@ -2,7 +2,8 @@ import pytest -from algobot.enums import BEARISH, BULLISH, LONG, SHORT, LossStrategy, StopType +from algobot.enums import (BEARISH, BULLISH, LONG, SHORT, LossStrategy, + ProfitType, StopType) from algobot.strategies.strategy import Strategy from algobot.traders.trader import Trader @@ -274,8 +275,8 @@ def test_get_profit_percentage(self): self.assertEqual(self.trader.get_profit_percentage(100, 130), 30) def test_get_trailing_or_stop_loss_string(self): - self.assertEqual(self.trader.get_trailing_or_stop_type_string(StopType.STOP), 'Stop') - self.assertEqual(self.trader.get_trailing_or_stop_type_string(StopType.TRAILING), 'Trailing') + self.assertEqual(self.trader.get_trailing_or_stop_type_string(ProfitType.STOP), 'Stop') + self.assertEqual(self.trader.get_trailing_or_stop_type_string(ProfitType.TRAILING), 'Trailing') self.assertEqual(self.trader.get_trailing_or_stop_type_string(None), 'None') def test_get_trend_string(self): @@ -321,7 +322,7 @@ def test_get_safe_rounded_string(self): multiplier=5), '6.15*') def test_get_take_profit(self): - self.trader.takeProfitType = StopType.STOP + self.trader.takeProfitType = ProfitType.STOP self.trader.takeProfitPercentageDecimal = 0.05 self.trader.currentPosition = LONG From 1f7f0938af5537c91af56450d712fbbb588a93bc Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Tue, 13 Jul 2021 22:33:48 +0200 Subject: [PATCH 04/11] Update --- algobot/enums.py | 5 ----- tests/test_base_trader.py | 8 ++++---- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/algobot/enums.py b/algobot/enums.py index dd688c6b..2a08b016 100644 --- a/algobot/enums.py +++ b/algobot/enums.py @@ -14,11 +14,6 @@ SHORT = -1 -class StopType: - TRAILING = 2 - STOP = 1 - - class LossStrategy: TRAILING = 2 STOP = 1 diff --git a/tests/test_base_trader.py b/tests/test_base_trader.py index cf314da6..ca6104dd 100644 --- a/tests/test_base_trader.py +++ b/tests/test_base_trader.py @@ -3,7 +3,7 @@ import pytest from algobot.enums import (BEARISH, BULLISH, LONG, SHORT, LossStrategy, - ProfitType, StopType) + ProfitType) from algobot.strategies.strategy import Strategy from algobot.traders.trader import Trader @@ -150,16 +150,16 @@ def test_set_safety_timer(self): def test_apply_take_profit_settings(self): take_profit_settings = { 'takeProfitPercentage': 25, - 'takeProfitType': StopType.STOP + 'takeProfitType': ProfitType.STOP } self.trader.apply_take_profit_settings(take_profit_settings) self.assertEqual(self.trader.takeProfitPercentageDecimal, 0.25) - self.assertEqual(self.trader.takeProfitType, StopType.STOP) + self.assertEqual(self.trader.takeProfitType, ProfitType.STOP) def test_apply_loss_settings(self): loss_settings = { - 'lossType': StopType.STOP, + 'lossType': LossStrategy.STOP, 'lossPercentage': 5.5, 'smartStopLossCounter': 15, 'safetyTimer': 45 From 318440618db9f9988996380d0e9e4b2dd3d620cb Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Tue, 13 Jul 2021 22:56:38 +0200 Subject: [PATCH 05/11] Refactor and add tests --- algobot/enums.py | 41 +++++++++++++++++++++++++++++ algobot/traders/backtester.py | 9 ++++--- algobot/traders/simulationtrader.py | 4 +-- algobot/traders/trader.py | 24 +---------------- tests/test_base_trader.py | 5 ---- tests/test_enums.py | 17 ++++++++++++ 6 files changed, 66 insertions(+), 34 deletions(-) create mode 100644 tests/test_enums.py diff --git a/algobot/enums.py b/algobot/enums.py index 2a08b016..1d8ef94e 100644 --- a/algobot/enums.py +++ b/algobot/enums.py @@ -1,4 +1,5 @@ # TODO: Add unit tests. +from typing import Optional BULLISH = 1 BEARISH = -1 @@ -18,11 +19,51 @@ class LossStrategy: TRAILING = 2 STOP = 1 + @staticmethod + def from_str(value: str) -> int: + if value.lower() == "trailing": + return LossStrategy.TRAILING + elif value.lower() == "stop": + return LossStrategy.STOP + else: + ValueError(f"{value} is unsupported") + + @staticmethod + def to_str(loss_strategy: Optional[int]) -> str: + if loss_strategy == LossStrategy.STOP: + return "Stop" + elif loss_strategy == LossStrategy.TRAILING: + return "Trailing" + elif loss_strategy is None: + return "None" + else: + raise ValueError(f"Unknown type {loss_strategy}") + class ProfitType: TRAILING = 2 STOP = 1 + @staticmethod + def from_str(value: str) -> int: + if value.lower() == "trailing": + return ProfitType.TRAILING + elif value.lower() == "stop": + return ProfitType.STOP + else: + ValueError(f"{value} is unsupported") + + @staticmethod + def to_str(loss_strategy: Optional[int]) -> str: + if loss_strategy == LossStrategy.STOP: + return "Stop" + elif loss_strategy == LossStrategy.TRAILING: + return "Trailing" + elif loss_strategy is None: + return "None" + else: + raise ValueError(f"Unknown type {loss_strategy}") + BACKTEST = 2 SIMULATION = 3 diff --git a/algobot/traders/backtester.py b/algobot/traders/backtester.py index d539a537..2c874c29 100644 --- a/algobot/traders/backtester.py +++ b/algobot/traders/backtester.py @@ -12,7 +12,8 @@ from dateutil import parser from algobot.enums import (BACKTEST, BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, - EXIT_LONG, EXIT_SHORT, LONG, OPTIMIZER, SHORT) + EXIT_LONG, EXIT_SHORT, LONG, OPTIMIZER, SHORT, + LossStrategy, ProfitType) from algobot.helpers import (LOG_FOLDER, ROOT_DIR, convert_all_dates_to_datetime, convert_small_interval, get_interval_minutes, @@ -444,7 +445,7 @@ def get_basic_optimize_info(self, run: int, totalRuns: int, result: str = 'PASSE round(self.get_net() / self.startingBalance * 100 - 100, 2), self.get_stop_loss_strategy_string(), self.get_safe_rounded_string(self.lossPercentageDecimal, multiplier=100, symbol='%'), - self.get_trailing_or_stop_type_string(self.takeProfitType), + ProfitType.to_str(self.takeProfitType), self.get_safe_rounded_string(self.takeProfitPercentageDecimal, multiplier=100, symbol='%'), self.symbol, self.interval, @@ -481,11 +482,11 @@ def apply_general_settings(self, settings: Dict[str, Union[float, str, dict]]): :param settings: Dictionary with keys and values to set. """ if 'takeProfitType' in settings: - self.takeProfitType = self.get_enum_from_str(settings['takeProfitType']) + self.takeProfitType = ProfitType.from_str(settings['takeProfitType']) self.takeProfitPercentageDecimal = settings['takeProfitPercentage'] / 100 if 'lossType' in settings: - self.lossStrategy = self.get_enum_from_str(settings['lossType']) + self.lossStrategy = LossStrategy.from_str(settings['lossType']) self.lossPercentageDecimal = settings['lossPercentage'] / 100 if 'stopLossCounter' in settings: diff --git a/algobot/traders/simulationtrader.py b/algobot/traders/simulationtrader.py index f6bb0ee6..d925b080 100644 --- a/algobot/traders/simulationtrader.py +++ b/algobot/traders/simulationtrader.py @@ -5,7 +5,7 @@ from algobot.data import Data from algobot.enums import (BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, - EXIT_LONG, EXIT_SHORT, LONG, SHORT) + EXIT_LONG, EXIT_SHORT, LONG, SHORT, ProfitType) from algobot.helpers import convert_small_interval, get_logger from algobot.traders.trader import Trader @@ -107,7 +107,7 @@ def get_grouped_statistics(self) -> dict: if self.takeProfitType is not None: groupedDict['takeProfit'] = { - 'takeProfitType': self.get_trailing_or_stop_type_string(self.takeProfitType), + 'takeProfitType': ProfitType.to_str(self.takeProfitType), 'takeProfitPercentage': self.get_safe_rounded_percentage(self.takeProfitPercentageDecimal), 'trailingTakeProfitActivated': str(self.trailingTakeProfitActivated), 'takeProfitPoint': self.get_safe_rounded_string(self.takeProfitPoint), diff --git a/algobot/traders/trader.py b/algobot/traders/trader.py index f66b3a48..b31b5f9c 100644 --- a/algobot/traders/trader.py +++ b/algobot/traders/trader.py @@ -2,7 +2,7 @@ This will be the main Trader class that all other Traders will inherit from. """ from datetime import datetime -from typing import Dict, List, Optional, Union +from typing import Dict, List, Union from algobot.enums import (BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, EXIT_LONG, EXIT_SHORT, LONG, SHORT, LossStrategy, @@ -322,28 +322,6 @@ def get_profit_percentage(initialNet: float, finalNet: float) -> float: else: return -1 * (100 - finalNet / initialNet * 100) - @staticmethod - def get_trailing_or_stop_type_string(profit_type: Optional[int]) -> str: - """ - Returns stop type in string format instead of integer enum. - :return: Stop type in string format. - """ - if profit_type == ProfitType.STOP: - return 'Stop' - elif profit_type == ProfitType.TRAILING: - return 'Trailing' - elif profit_type is None: - return 'None' - else: - raise ValueError("Unknown type of exit position type.") - - @staticmethod - def get_enum_from_str(value: str) -> int: - if value.lower() == "trailing": - return ProfitType.TRAILING - elif value.lower() == 'stop': - return ProfitType.STOP - @staticmethod def get_trend_string(trend) -> str: """ diff --git a/tests/test_base_trader.py b/tests/test_base_trader.py index ca6104dd..34b52b12 100644 --- a/tests/test_base_trader.py +++ b/tests/test_base_trader.py @@ -274,11 +274,6 @@ def test_get_profit_percentage(self): self.assertEqual(self.trader.get_profit_percentage(100, 50), -50) self.assertEqual(self.trader.get_profit_percentage(100, 130), 30) - def test_get_trailing_or_stop_loss_string(self): - self.assertEqual(self.trader.get_trailing_or_stop_type_string(ProfitType.STOP), 'Stop') - self.assertEqual(self.trader.get_trailing_or_stop_type_string(ProfitType.TRAILING), 'Trailing') - self.assertEqual(self.trader.get_trailing_or_stop_type_string(None), 'None') - def test_get_trend_string(self): self.assertEqual(self.trader.get_trend_string(None), str(None)) self.assertEqual(self.trader.get_trend_string(BEARISH), "Bearish") diff --git a/tests/test_enums.py b/tests/test_enums.py new file mode 100644 index 00000000..958d7e3c --- /dev/null +++ b/tests/test_enums.py @@ -0,0 +1,17 @@ +import unittest + +from algobot.enums import LossStrategy, ProfitType + + +class ProfitTypeTest(unittest.TestCase): + def test_get_trailing_or_stop_loss_string(self): + self.assertEqual(ProfitType.to_str(ProfitType.STOP), "Stop") + self.assertEqual(ProfitType.to_str(ProfitType.TRAILING), "Trailing") + self.assertEqual(ProfitType.to_str(None), "None") + + +class LossStrategyTest(unittest.TestCase): + def test_get_trailing_or_stop_loss_string(self): + self.assertEqual(LossStrategy.to_str(ProfitType.STOP), "Stop") + self.assertEqual(LossStrategy.to_str(ProfitType.TRAILING), "Trailing") + self.assertEqual(LossStrategy.to_str(None), "None") From 45aa480e43d2adc2101d320c5fdd97555aae16ff Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Wed, 14 Jul 2021 20:53:27 +0200 Subject: [PATCH 06/11] Consolidate --- algobot/enums.py | 35 ++++---------------------- algobot/interface/configuration.py | 39 ++++++++++++++--------------- algobot/traders/backtester.py | 16 ++++++------ algobot/traders/simulationtrader.py | 6 ++--- algobot/traders/trader.py | 25 +++++++++--------- tests/test_backtester.py | 16 ++++++------ tests/test_base_trader.py | 23 ++++++++--------- tests/test_enums.py | 16 ++++++------ 8 files changed, 74 insertions(+), 102 deletions(-) diff --git a/algobot/enums.py b/algobot/enums.py index 1d8ef94e..570ff791 100644 --- a/algobot/enums.py +++ b/algobot/enums.py @@ -15,49 +15,24 @@ SHORT = -1 -class LossStrategy: +class OrderType: TRAILING = 2 STOP = 1 @staticmethod def from_str(value: str) -> int: if value.lower() == "trailing": - return LossStrategy.TRAILING + return OrderType.TRAILING elif value.lower() == "stop": - return LossStrategy.STOP + return OrderType.STOP else: ValueError(f"{value} is unsupported") @staticmethod def to_str(loss_strategy: Optional[int]) -> str: - if loss_strategy == LossStrategy.STOP: + if loss_strategy == OrderType.STOP: return "Stop" - elif loss_strategy == LossStrategy.TRAILING: - return "Trailing" - elif loss_strategy is None: - return "None" - else: - raise ValueError(f"Unknown type {loss_strategy}") - - -class ProfitType: - TRAILING = 2 - STOP = 1 - - @staticmethod - def from_str(value: str) -> int: - if value.lower() == "trailing": - return ProfitType.TRAILING - elif value.lower() == "stop": - return ProfitType.STOP - else: - ValueError(f"{value} is unsupported") - - @staticmethod - def to_str(loss_strategy: Optional[int]) -> str: - if loss_strategy == LossStrategy.STOP: - return "Stop" - elif loss_strategy == LossStrategy.TRAILING: + elif loss_strategy == OrderType.TRAILING: return "Trailing" elif loss_strategy is None: return "None" diff --git a/algobot/interface/configuration.py b/algobot/interface/configuration.py index df278ce1..ecaca6fd 100644 --- a/algobot/interface/configuration.py +++ b/algobot/interface/configuration.py @@ -8,8 +8,7 @@ QTabWidget) import algobot.helpers as helpers -from algobot.enums import (BACKTEST, LIVE, OPTIMIZER, SIMULATION, LossStrategy, - ProfitType) +from algobot.enums import BACKTEST, LIVE, OPTIMIZER, SIMULATION, OrderType from algobot.graph_helpers import create_infinite_line from algobot.interface.config_utils.credential_utils import load_credentials from algobot.interface.config_utils.slot_utils import load_slots @@ -74,7 +73,7 @@ def __init__(self, parent: QMainWindow, logger: Logger = None): } self.lossTypes = ("Trailing", "Stop") - self.takeProfitTypes = ('Stop',) + self.takeOrderTypes = ('Stop',) self.lossOptimizerTypes = ('lossPercentage', 'stopLossCounter') self.takeProfitOptimizerTypes = ('takeProfitPercentage',) @@ -200,7 +199,7 @@ def get_optimizer_settings(self) -> dict: settings = {} self.helper_get_optimizer(tab, self.lossDict, 'lossType', self.lossOptimizerTypes, settings) - self.helper_get_optimizer(tab, self.takeProfitDict, 'takeProfitType', self.takeProfitOptimizerTypes, settings) + self.helper_get_optimizer(tab, self.takeProfitDict, 'takeOrderType', self.takeProfitOptimizerTypes, settings) self.get_strategy_intervals_for_optimizer(settings) settings['strategies'] = {} @@ -280,10 +279,10 @@ def create_take_profit_inputs(self, tab: QTabWidget, innerLayout: QLayout, isOpt if isOptimizer: self.takeProfitDict['optimizerTypes'] = [] innerLayout.addRow(QLabel("Take Profit Types")) - for takeProfitType in self.takeProfitTypes: - checkbox = QCheckBox(f'Enable {takeProfitType} take profit?') + for takeOrderType in self.takeOrderTypes: + checkbox = QCheckBox(f'Enable {takeOrderType} take profit?') innerLayout.addRow(checkbox) - self.takeProfitDict['optimizerTypes'].append((takeProfitType, checkbox)) + self.takeProfitDict['optimizerTypes'].append((takeOrderType, checkbox)) for optimizerType in self.takeProfitOptimizerTypes: self.takeProfitDict[optimizerType, 'start'] = start = get_default_widget(QSpinBox, 1, 0) @@ -291,15 +290,15 @@ def create_take_profit_inputs(self, tab: QTabWidget, innerLayout: QLayout, isOpt self.takeProfitDict[optimizerType, 'step'] = step = get_default_widget(QSpinBox, 1) add_start_end_step_to_layout(innerLayout, optimizerType, start, end, step) else: - self.takeProfitDict[tab, 'takeProfitType'] = takeProfitTypeComboBox = QComboBox() + self.takeProfitDict[tab, 'takeOrderType'] = takeOrderTypeComboBox = QComboBox() self.takeProfitDict[tab, 'takeProfitPercentage'] = takeProfitPercentage = QDoubleSpinBox() - takeProfitTypeComboBox.addItems(self.takeProfitTypes) - takeProfitTypeComboBox.currentIndexChanged.connect(lambda: self.update_take_profit_settings(tab)) + takeOrderTypeComboBox.addItems(self.takeOrderTypes) + takeOrderTypeComboBox.currentIndexChanged.connect(lambda: self.update_take_profit_settings(tab)) takeProfitPercentage.setValue(5) takeProfitPercentage.valueChanged.connect(lambda: self.update_take_profit_settings(tab)) - innerLayout.addRow(QLabel("Take Profit Type"), takeProfitTypeComboBox) + innerLayout.addRow(QLabel("Take Profit Type"), takeOrderTypeComboBox) innerLayout.addRow(QLabel('Take Profit Percentage'), takeProfitPercentage) def set_loss_settings(self, caller: int, config: dict): @@ -325,11 +324,11 @@ def set_take_profit_settings(self, caller: int, config: dict): :param caller: This caller's tab's GUI will be modified by this function. :param config: Configuration dictionary from which to get take profit settings. """ - if "takeProfitTypeIndex" not in config: # We don't have this data in config, so just return. + if "takeOrderTypeIndex" not in config: # We don't have this data in config, so just return. return tab = self.get_category_tab(caller) - self.takeProfitDict[tab, 'takeProfitType'].setCurrentIndex(config["takeProfitTypeIndex"]) + self.takeProfitDict[tab, 'takeOrderType'].setCurrentIndex(config["takeOrderTypeIndex"]) self.takeProfitDict[tab, 'takeProfitPercentage'].setValue(config["takeProfitPercentage"]) def get_take_profit_settings(self, caller) -> dict: @@ -341,16 +340,16 @@ def get_take_profit_settings(self, caller) -> dict: tab = self.get_category_tab(caller) dictionary = self.takeProfitDict if dictionary[tab, 'groupBox'].isChecked(): - if dictionary[tab, 'takeProfitType'].currentText() == "Trailing": - takeProfitType = ProfitType.TRAILING + if dictionary[tab, 'takeOrderType'].currentText() == "Trailing": + takeOrderType = OrderType.TRAILING else: - takeProfitType = ProfitType.STOP + takeOrderType = OrderType.STOP else: - takeProfitType = None + takeOrderType = None return { - 'takeProfitType': takeProfitType, - 'takeProfitTypeIndex': dictionary[tab, 'takeProfitType'].currentIndex(), + 'takeOrderType': takeOrderType, + 'takeOrderTypeIndex': dictionary[tab, 'takeOrderType'].currentIndex(), 'takeProfitPercentage': dictionary[tab, 'takeProfitPercentage'].value() } @@ -380,7 +379,7 @@ def get_loss_settings(self, caller: int) -> dict: dictionary = self.lossDict if dictionary[tab, 'groupBox'].isChecked(): loss_type = dictionary[tab, "lossType"].currentText() - loss_strategy = LossStrategy.TRAILING if loss_type == "Trailing" else LossStrategy.STOP + loss_strategy = OrderType.TRAILING if loss_type == "Trailing" else OrderType.STOP else: loss_strategy = None diff --git a/algobot/traders/backtester.py b/algobot/traders/backtester.py index 2c874c29..4948d5cf 100644 --- a/algobot/traders/backtester.py +++ b/algobot/traders/backtester.py @@ -13,7 +13,7 @@ from algobot.enums import (BACKTEST, BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, EXIT_LONG, EXIT_SHORT, LONG, OPTIMIZER, SHORT, - LossStrategy, ProfitType) + OrderType) from algobot.helpers import (LOG_FOLDER, ROOT_DIR, convert_all_dates_to_datetime, convert_small_interval, get_interval_minutes, @@ -445,7 +445,7 @@ def get_basic_optimize_info(self, run: int, totalRuns: int, result: str = 'PASSE round(self.get_net() / self.startingBalance * 100 - 100, 2), self.get_stop_loss_strategy_string(), self.get_safe_rounded_string(self.lossPercentageDecimal, multiplier=100, symbol='%'), - ProfitType.to_str(self.takeProfitType), + OrderType.to_str(self.takeOrderType), self.get_safe_rounded_string(self.takeProfitPercentageDecimal, multiplier=100, symbol='%'), self.symbol, self.interval, @@ -481,12 +481,12 @@ def apply_general_settings(self, settings: Dict[str, Union[float, str, dict]]): Apples settings provided from the settings argument to the backtester object. :param settings: Dictionary with keys and values to set. """ - if 'takeProfitType' in settings: - self.takeProfitType = ProfitType.from_str(settings['takeProfitType']) + if 'takeOrderType' in settings: + self.takeOrderType = OrderType.from_str(settings['takeOrderType']) self.takeProfitPercentageDecimal = settings['takeProfitPercentage'] / 100 if 'lossType' in settings: - self.lossStrategy = LossStrategy.from_str(settings['lossType']) + self.lossStrategy = OrderType.from_str(settings['lossType']) self.lossPercentageDecimal = settings['lossPercentage'] / 100 if 'stopLossCounter' in settings: @@ -632,7 +632,7 @@ def main_logic(self): if self.currentPosition == SHORT: if self.lossStrategy is not None and self.currentPrice > self.get_stop_loss(): self.buy_short('Exited short because a stop loss was triggered.', stopLossExit=True) - elif self.takeProfitType is not None and self.currentPrice <= self.get_take_profit(): + elif self.takeOrderType is not None and self.currentPrice <= self.get_take_profit(): self.buy_short("Exited short because of take profit.") elif trend == BULLISH: self.buy_short('Exited short because a bullish trend was detected.') @@ -642,7 +642,7 @@ def main_logic(self): elif self.currentPosition == LONG: if self.lossStrategy is not None and self.currentPrice < self.get_stop_loss(): self.sell_long('Exited long because a stop loss was triggered.', stopLossExit=True) - elif self.takeProfitType is not None and self.currentPrice >= self.get_take_profit(): + elif self.takeOrderType is not None and self.currentPrice >= self.get_take_profit(): self.sell_long("Exited long because of take profit.") elif trend == BEARISH: self.sell_long('Exited long because a bearish trend was detected.') @@ -691,7 +691,7 @@ def print_configuration_parameters(self, stdout=None): print(f'\tMargin Enabled: {self.marginEnabled}') print(f"\tStarting Balance: ${self.startingBalance}") - if self.takeProfitType is not None: + if self.takeOrderType is not None: print(f'\tTake Profit Percentage: {round(self.takeProfitPercentageDecimal * 100, 2)}%') if self.lossStrategy is not None: diff --git a/algobot/traders/simulationtrader.py b/algobot/traders/simulationtrader.py index d925b080..0d51c749 100644 --- a/algobot/traders/simulationtrader.py +++ b/algobot/traders/simulationtrader.py @@ -5,7 +5,7 @@ from algobot.data import Data from algobot.enums import (BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, - EXIT_LONG, EXIT_SHORT, LONG, SHORT, ProfitType) + EXIT_LONG, EXIT_SHORT, LONG, SHORT, OrderType) from algobot.helpers import convert_small_interval, get_logger from algobot.traders.trader import Trader @@ -105,9 +105,9 @@ def get_grouped_statistics(self) -> dict: 'scheduledTimerRemaining': self.get_remaining_safety_timer(), } - if self.takeProfitType is not None: + if self.takeOrderType is not None: groupedDict['takeProfit'] = { - 'takeProfitType': ProfitType.to_str(self.takeProfitType), + 'takeOrderType': OrderType.to_str(self.takeOrderType), 'takeProfitPercentage': self.get_safe_rounded_percentage(self.takeProfitPercentageDecimal), 'trailingTakeProfitActivated': str(self.trailingTakeProfitActivated), 'takeProfitPoint': self.get_safe_rounded_string(self.takeProfitPoint), diff --git a/algobot/traders/trader.py b/algobot/traders/trader.py index b31b5f9c..bb5af01e 100644 --- a/algobot/traders/trader.py +++ b/algobot/traders/trader.py @@ -5,8 +5,7 @@ from typing import Dict, List, Union from algobot.enums import (BEARISH, BULLISH, ENTER_LONG, ENTER_SHORT, - EXIT_LONG, EXIT_SHORT, LONG, SHORT, LossStrategy, - ProfitType) + EXIT_LONG, EXIT_SHORT, LONG, SHORT, OrderType) from algobot.helpers import get_label_string, parse_strategy_name from algobot.strategies.strategy import Strategy @@ -37,7 +36,7 @@ def __init__(self, symbol, precision, startingBalance, marginEnabled: bool = Tru self.takeProfitPoint = None # Price at which bot will exit trade to secure profits. self.trailingTakeProfitActivated = False # Boolean that'll turn true if a stop order is activated. - self.takeProfitType = None # Type of take profit: trailing or stop. + self.takeOrderType = None # Type of take profit: trailing or stop. self.takeProfitPercentageDecimal = None # Percentage of profit to exit trade at. # Prices information. @@ -173,7 +172,7 @@ def apply_take_profit_settings(self, takeProfitDict: Dict[str, int]): :return: None """ self.takeProfitPercentageDecimal = takeProfitDict["takeProfitPercentage"] / 100 - self.takeProfitType = takeProfitDict["takeProfitType"] + self.takeOrderType = takeProfitDict["takeOrderType"] def apply_loss_settings(self, lossDict: Dict[str, int]): """ @@ -225,16 +224,16 @@ def get_stop_loss(self): if self.currentPosition == SHORT: if self.smartStopLossEnter and self.previousStopLoss > self.currentPrice: self.stopLoss = self.previousStopLoss - elif self.lossStrategy == LossStrategy.TRAILING: + elif self.lossStrategy == OrderType.TRAILING: self.stopLoss = self.shortTrailingPrice * (1 + self.lossPercentageDecimal) - elif self.lossStrategy == LossStrategy.STOP: + elif self.lossStrategy == OrderType.STOP: self.stopLoss = self.sellShortPrice * (1 + self.lossPercentageDecimal) elif self.currentPosition == LONG: if self.smartStopLossEnter and self.previousStopLoss < self.currentPrice: self.stopLoss = self.previousStopLoss - elif self.lossStrategy == LossStrategy.TRAILING: + elif self.lossStrategy == OrderType.TRAILING: self.stopLoss = self.longTrailingPrice * (1 - self.lossPercentageDecimal) - elif self.lossStrategy == LossStrategy.STOP: + elif self.lossStrategy == OrderType.STOP: self.stopLoss = self.buyLongPrice * (1 - self.lossPercentageDecimal) if self.stopLoss is not None: # This is for the smart stop loss to reenter position. @@ -247,9 +246,9 @@ def get_stop_loss_strategy_string(self) -> str: Returns stop loss strategy in string format, instead of integer enum. :return: Stop loss strategy in string format. """ - if self.lossStrategy == LossStrategy.STOP: + if self.lossStrategy == OrderType.STOP: return 'Stop Loss' - elif self.lossStrategy == LossStrategy.TRAILING: + elif self.lossStrategy == OrderType.TRAILING: return 'Trailing Loss' elif self.lossStrategy is None: return 'None' @@ -411,16 +410,16 @@ def get_take_profit(self) -> Union[float, None]: Returns price at which position will be exited to secure profits. :return: Price at which to exit position. """ - if self.takeProfitType is None: + if self.takeOrderType is None: return None if self.currentPosition == SHORT: - if self.takeProfitType == ProfitType.STOP: + if self.takeOrderType == OrderType.STOP: self.takeProfitPoint = self.sellShortPrice * (1 - self.takeProfitPercentageDecimal) else: raise ValueError("Invalid type of take profit type provided.") elif self.currentPosition == LONG: - if self.takeProfitType == ProfitType.STOP: + if self.takeOrderType == OrderType.STOP: self.takeProfitPoint = self.buyLongPrice * (1 + self.takeProfitPercentageDecimal) else: raise ValueError("Invalid type of take profit type provided.") diff --git a/tests/test_backtester.py b/tests/test_backtester.py index 66fc1022..daa157bc 100644 --- a/tests/test_backtester.py +++ b/tests/test_backtester.py @@ -4,7 +4,7 @@ import pytest -from algobot.enums import LONG, SHORT, LossStrategy, ProfitType +from algobot.enums import LONG, SHORT, OrderType from algobot.helpers import convert_all_dates_to_datetime, load_from_csv from algobot.traders.backtester import Backtester @@ -25,8 +25,8 @@ def setUp(self) -> None: symbol="1INCHUSDT", marginEnabled=True, ) - self.backtester.apply_take_profit_settings({'takeProfitType': ProfitType.TRAILING, 'takeProfitPercentage': 5}) - self.backtester.apply_loss_settings({'lossType': LossStrategy.TRAILING, 'lossPercentage': 5}) + self.backtester.apply_take_profit_settings({'takeOrderType': OrderType.TRAILING, 'takeProfitPercentage': 5}) + self.backtester.apply_loss_settings({'lossType': OrderType.TRAILING, 'lossPercentage': 5}) def test_initialization(self): """ @@ -281,7 +281,7 @@ def test_long_stop_loss(self): Test backtester stop loss logic in a long position. """ backtester = self.backtester - backtester.lossStrategy = LossStrategy.STOP + backtester.lossStrategy = OrderType.STOP backtester.set_priced_current_price_and_period(5) backtester.buy_long("Test purchase.") self.assertEqual(backtester.get_stop_loss(), 5 * (1 - backtester.lossPercentageDecimal)) @@ -289,7 +289,7 @@ def test_long_stop_loss(self): backtester.set_priced_current_price_and_period(10) self.assertEqual(backtester.get_stop_loss(), 5 * (1 - backtester.lossPercentageDecimal)) - backtester.lossStrategy = LossStrategy.TRAILING + backtester.lossStrategy = OrderType.TRAILING self.assertEqual(backtester.get_stop_loss(), 10 * (1 - backtester.lossPercentageDecimal)) def test_short_stop_loss(self): @@ -297,7 +297,7 @@ def test_short_stop_loss(self): Test backtester stop loss logic in a short position. """ backtester = self.backtester - backtester.lossStrategy = LossStrategy.STOP + backtester.lossStrategy = OrderType.STOP backtester.set_priced_current_price_and_period(5) backtester.sell_short("Test short.") self.assertEqual(backtester.get_stop_loss(), 5 * (1 + backtester.lossPercentageDecimal)) @@ -305,7 +305,7 @@ def test_short_stop_loss(self): backtester.set_priced_current_price_and_period(3) self.assertEqual(backtester.get_stop_loss(), 5 * (1 + backtester.lossPercentageDecimal)) - backtester.lossStrategy = LossStrategy.TRAILING + backtester.lossStrategy = OrderType.TRAILING self.assertEqual(backtester.get_stop_loss(), 3 * (1 + backtester.lossPercentageDecimal)) def test_stop_take_profit(self): @@ -313,7 +313,7 @@ def test_stop_take_profit(self): Test backtester take profit logic. """ backtester = self.backtester - backtester.takeProfitType = ProfitType.STOP + backtester.takeOrderType = OrderType.STOP backtester.set_priced_current_price_and_period(10) backtester.buy_long("Test purchase.") self.assertEqual(backtester.get_take_profit(), 10 * (1 + backtester.takeProfitPercentageDecimal)) diff --git a/tests/test_base_trader.py b/tests/test_base_trader.py index 34b52b12..d6fa6f57 100644 --- a/tests/test_base_trader.py +++ b/tests/test_base_trader.py @@ -2,8 +2,7 @@ import pytest -from algobot.enums import (BEARISH, BULLISH, LONG, SHORT, LossStrategy, - ProfitType) +from algobot.enums import BEARISH, BULLISH, LONG, SHORT, OrderType from algobot.strategies.strategy import Strategy from algobot.traders.trader import Trader @@ -150,30 +149,30 @@ def test_set_safety_timer(self): def test_apply_take_profit_settings(self): take_profit_settings = { 'takeProfitPercentage': 25, - 'takeProfitType': ProfitType.STOP + 'takeOrderType': OrderType.STOP } self.trader.apply_take_profit_settings(take_profit_settings) self.assertEqual(self.trader.takeProfitPercentageDecimal, 0.25) - self.assertEqual(self.trader.takeProfitType, ProfitType.STOP) + self.assertEqual(self.trader.takeOrderType, OrderType.STOP) def test_apply_loss_settings(self): loss_settings = { - 'lossType': LossStrategy.STOP, + 'lossType': OrderType.STOP, 'lossPercentage': 5.5, 'smartStopLossCounter': 15, 'safetyTimer': 45 } self.trader.apply_loss_settings(loss_settings) - self.assertEqual(self.trader.lossStrategy, LossStrategy.STOP) + self.assertEqual(self.trader.lossStrategy, OrderType.STOP) self.assertEqual(self.trader.lossPercentageDecimal, 0.055) self.assertEqual(self.trader.smartStopLossInitialCounter, 15) self.assertEqual(self.trader.smartStopLossCounter, 15) self.assertEqual(self.trader.safetyTimer, 45) def test_get_stop_loss(self): - self.trader.lossStrategy = LossStrategy.STOP + self.trader.lossStrategy = OrderType.STOP self.trader.lossPercentageDecimal = 0.1 self.trader.currentPrice = 5 @@ -191,10 +190,10 @@ def test_get_stop_loss(self): # TODO implement trailing stop loss test def test_get_stop_loss_strategy_string(self): - self.trader.lossStrategy = LossStrategy.STOP + self.trader.lossStrategy = OrderType.STOP self.assertEqual(self.trader.get_stop_loss_strategy_string(), "Stop Loss") - self.trader.lossStrategy = LossStrategy.TRAILING + self.trader.lossStrategy = OrderType.TRAILING self.assertEqual(self.trader.get_stop_loss_strategy_string(), "Trailing Loss") self.trader.lossStrategy = None @@ -317,7 +316,7 @@ def test_get_safe_rounded_string(self): multiplier=5), '6.15*') def test_get_take_profit(self): - self.trader.takeProfitType = ProfitType.STOP + self.trader.takeOrderType = OrderType.STOP self.trader.takeProfitPercentageDecimal = 0.05 self.trader.currentPosition = LONG @@ -328,10 +327,10 @@ def test_get_take_profit(self): self.trader.sellShortPrice = 10 self.assertEqual(self.trader.get_take_profit(), 10 * (1 - 0.05)) - self.trader.takeProfitType = None + self.trader.takeOrderType = None self.assertEqual(self.trader.get_take_profit(), None) - self.trader.takeProfitType = 5 + self.trader.takeOrderType = 5 with pytest.raises(ValueError, match="Invalid type of take profit type provided."): self.trader.get_take_profit() diff --git a/tests/test_enums.py b/tests/test_enums.py index 958d7e3c..eb6bb2bd 100644 --- a/tests/test_enums.py +++ b/tests/test_enums.py @@ -1,17 +1,17 @@ import unittest -from algobot.enums import LossStrategy, ProfitType +from algobot.enums import OrderType -class ProfitTypeTest(unittest.TestCase): +class OrderTypeTest(unittest.TestCase): def test_get_trailing_or_stop_loss_string(self): - self.assertEqual(ProfitType.to_str(ProfitType.STOP), "Stop") - self.assertEqual(ProfitType.to_str(ProfitType.TRAILING), "Trailing") - self.assertEqual(ProfitType.to_str(None), "None") + self.assertEqual(OrderType.to_str(OrderType.STOP), "Stop") + self.assertEqual(OrderType.to_str(OrderType.TRAILING), "Trailing") + self.assertEqual(OrderType.to_str(None), "None") class LossStrategyTest(unittest.TestCase): def test_get_trailing_or_stop_loss_string(self): - self.assertEqual(LossStrategy.to_str(ProfitType.STOP), "Stop") - self.assertEqual(LossStrategy.to_str(ProfitType.TRAILING), "Trailing") - self.assertEqual(LossStrategy.to_str(None), "None") + self.assertEqual(OrderType.to_str(OrderType.STOP), "Stop") + self.assertEqual(OrderType.to_str(OrderType.TRAILING), "Trailing") + self.assertEqual(OrderType.to_str(None), "None") From fdd9e96be8c2825768cb42f78e6cfeb2bec4448f Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Wed, 14 Jul 2021 20:56:42 +0200 Subject: [PATCH 07/11] Fix up tests --- tests/test_enums.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tests/test_enums.py b/tests/test_enums.py index eb6bb2bd..106af431 100644 --- a/tests/test_enums.py +++ b/tests/test_enums.py @@ -4,14 +4,11 @@ class OrderTypeTest(unittest.TestCase): - def test_get_trailing_or_stop_loss_string(self): + def test_to_str(self): self.assertEqual(OrderType.to_str(OrderType.STOP), "Stop") self.assertEqual(OrderType.to_str(OrderType.TRAILING), "Trailing") self.assertEqual(OrderType.to_str(None), "None") - -class LossStrategyTest(unittest.TestCase): - def test_get_trailing_or_stop_loss_string(self): - self.assertEqual(OrderType.to_str(OrderType.STOP), "Stop") - self.assertEqual(OrderType.to_str(OrderType.TRAILING), "Trailing") - self.assertEqual(OrderType.to_str(None), "None") + def test_to_str_unsupported(self): + with self.assertRaises(ValueError): + OrderType.to_str(100) From aa9dea7a153b1e559385069e53855296e7fc8843 Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Wed, 14 Jul 2021 20:58:13 +0200 Subject: [PATCH 08/11] Tidy --- algobot/enums.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/algobot/enums.py b/algobot/enums.py index 570ff791..885c5807 100644 --- a/algobot/enums.py +++ b/algobot/enums.py @@ -29,15 +29,15 @@ def from_str(value: str) -> int: ValueError(f"{value} is unsupported") @staticmethod - def to_str(loss_strategy: Optional[int]) -> str: - if loss_strategy == OrderType.STOP: + def to_str(order_type: Optional[int]) -> str: + if order_type == OrderType.STOP: return "Stop" - elif loss_strategy == OrderType.TRAILING: + elif order_type == OrderType.TRAILING: return "Trailing" - elif loss_strategy is None: + elif order_type is None: return "None" else: - raise ValueError(f"Unknown type {loss_strategy}") + raise ValueError(f"Unknown OrderType with value {order_type}") BACKTEST = 2 From 7ad843bef39bd37649ec65778c4857dbafa01dc7 Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Wed, 14 Jul 2021 21:13:58 +0200 Subject: [PATCH 09/11] More tests --- algobot/enums.py | 2 +- tests/test_enums.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/algobot/enums.py b/algobot/enums.py index bde491b6..65d35ead 100644 --- a/algobot/enums.py +++ b/algobot/enums.py @@ -30,7 +30,7 @@ def from_str(value: str) -> int: elif value.lower() == "stop": return OrderType.STOP else: - ValueError(f"{value} is unsupported") + raise ValueError(f"{value} is unsupported") @staticmethod def to_str(order_type: Optional[int]) -> str: diff --git a/tests/test_enums.py b/tests/test_enums.py index 106af431..db1380ca 100644 --- a/tests/test_enums.py +++ b/tests/test_enums.py @@ -4,6 +4,14 @@ class OrderTypeTest(unittest.TestCase): + def test_from_str(self): + self.assertEqual(OrderType.from_str("Stop"), OrderType.STOP) + self.assertEqual(OrderType.from_str("Trailing"), OrderType.TRAILING) + + def test_from_str_unsupported(self): + with self.assertRaises(ValueError): + OrderType.from_str("Random") + def test_to_str(self): self.assertEqual(OrderType.to_str(OrderType.STOP), "Stop") self.assertEqual(OrderType.to_str(OrderType.TRAILING), "Trailing") From 3f5ad32fb230bc30218025af2c1f7f8e4d2a4c5a Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Thu, 15 Jul 2021 20:33:37 +0200 Subject: [PATCH 10/11] Fix bad refactor --- algobot/interface/configuration.py | 34 ++++++++++++++--------------- algobot/traders/backtester.py | 12 +++++----- algobot/traders/simulationtrader.py | 4 ++-- algobot/traders/trader.py | 10 ++++----- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/algobot/interface/configuration.py b/algobot/interface/configuration.py index ad4f8992..73dbbc72 100644 --- a/algobot/interface/configuration.py +++ b/algobot/interface/configuration.py @@ -73,7 +73,7 @@ def __init__(self, parent: QMainWindow, logger: Logger = None): } self.lossTypes = ("Trailing", "Stop") - self.takeOrderTypes = ('Stop',) + self.takeProfitTypes = ('Stop',) self.lossOptimizerTypes = ('lossPercentage', 'stopLossCounter') self.takeProfitOptimizerTypes = ('takeProfitPercentage',) @@ -199,7 +199,7 @@ def get_optimizer_settings(self) -> dict: settings = {} self.helper_get_optimizer(tab, self.lossDict, 'lossType', self.lossOptimizerTypes, settings) - self.helper_get_optimizer(tab, self.takeProfitDict, 'takeOrderType', self.takeProfitOptimizerTypes, settings) + self.helper_get_optimizer(tab, self.takeProfitDict, 'takeProfitType', self.takeProfitOptimizerTypes, settings) self.get_strategy_intervals_for_optimizer(settings) settings['strategies'] = {} @@ -282,10 +282,10 @@ def create_take_profit_inputs(self, tab: QTabWidget, innerLayout: QLayout, isOpt if isOptimizer: self.takeProfitDict['optimizerTypes'] = [] innerLayout.addRow(QLabel("Take Profit Types")) - for takeOrderType in self.takeOrderTypes: - checkbox = QCheckBox(f'Enable {takeOrderType} take profit?') + for takeProfitType in self.takeProfitTypes: + checkbox = QCheckBox(f'Enable {takeProfitType} take profit?') innerLayout.addRow(checkbox) - self.takeProfitDict['optimizerTypes'].append((takeOrderType, checkbox)) + self.takeProfitDict['optimizerTypes'].append((takeProfitType, checkbox)) for optimizerType in self.takeProfitOptimizerTypes: self.takeProfitDict[optimizerType, 'start'] = start = get_default_widget(QSpinBox, 1, 0) @@ -293,15 +293,15 @@ def create_take_profit_inputs(self, tab: QTabWidget, innerLayout: QLayout, isOpt self.takeProfitDict[optimizerType, 'step'] = step = get_default_widget(QSpinBox, 1) add_start_end_step_to_layout(innerLayout, optimizerType, start, end, step) else: - self.takeProfitDict[tab, 'takeOrderType'] = takeOrderTypeComboBox = QComboBox() + self.takeProfitDict[tab, 'takeProfitType'] = takeProfitTypeComboBox = QComboBox() self.takeProfitDict[tab, 'takeProfitPercentage'] = takeProfitPercentage = QDoubleSpinBox() - takeOrderTypeComboBox.addItems(self.takeOrderTypes) - takeOrderTypeComboBox.currentIndexChanged.connect(lambda: self.update_take_profit_settings(tab)) + takeProfitTypeComboBox.addItems(self.takeProfitTypes) + takeProfitTypeComboBox.currentIndexChanged.connect(lambda: self.update_take_profit_settings(tab)) takeProfitPercentage.setValue(5) takeProfitPercentage.valueChanged.connect(lambda: self.update_take_profit_settings(tab)) - innerLayout.addRow(QLabel("Take Profit Type"), takeOrderTypeComboBox) + innerLayout.addRow(QLabel("Take Profit Type"), takeProfitTypeComboBox) innerLayout.addRow(QLabel('Take Profit Percentage'), takeProfitPercentage) def set_loss_settings(self, caller: int, config: dict): @@ -327,11 +327,11 @@ def set_take_profit_settings(self, caller: int, config: dict): :param caller: This caller's tab's GUI will be modified by this function. :param config: Configuration dictionary from which to get take profit settings. """ - if "takeOrderTypeIndex" not in config: # We don't have this data in config, so just return. + if "takeProfitTypeIndex" not in config: # We don't have this data in config, so just return. return tab = self.get_category_tab(caller) - self.takeProfitDict[tab, 'takeOrderType'].setCurrentIndex(config["takeOrderTypeIndex"]) + self.takeProfitDict[tab, 'takeProfitType'].setCurrentIndex(config["takeProfitTypeIndex"]) self.takeProfitDict[tab, 'takeProfitPercentage'].setValue(config["takeProfitPercentage"]) def get_take_profit_settings(self, caller) -> dict: @@ -343,16 +343,16 @@ def get_take_profit_settings(self, caller) -> dict: tab = self.get_category_tab(caller) dictionary = self.takeProfitDict if dictionary[tab, 'groupBox'].isChecked(): - if dictionary[tab, 'takeOrderType'].currentText() == "Trailing": - takeOrderType = OrderType.TRAILING + if dictionary[tab, 'takeProfitType'].currentText() == "Trailing": + takeProfitType = OrderType.TRAILING else: - takeOrderType = OrderType.STOP + takeProfitType = OrderType.STOP else: - takeOrderType = None + takeProfitType = None return { - 'takeOrderType': takeOrderType, - 'takeOrderTypeIndex': dictionary[tab, 'takeOrderType'].currentIndex(), + 'takeProfitType': takeProfitType, + 'takeProfitTypeIndex': dictionary[tab, 'takeProfitType'].currentIndex(), 'takeProfitPercentage': dictionary[tab, 'takeProfitPercentage'].value() } diff --git a/algobot/traders/backtester.py b/algobot/traders/backtester.py index e3533215..0ac6425f 100644 --- a/algobot/traders/backtester.py +++ b/algobot/traders/backtester.py @@ -443,7 +443,7 @@ def get_basic_optimize_info(self, run: int, totalRuns: int, result: str = 'PASSE round(self.get_net() / self.startingBalance * 100 - 100, 2), self.get_stop_loss_strategy_string(), self.get_safe_rounded_string(self.lossPercentageDecimal, multiplier=100, symbol='%'), - OrderType.to_str(self.takeOrderType), + OrderType.to_str(self.takeProfitType), self.get_safe_rounded_string(self.takeProfitPercentageDecimal, multiplier=100, symbol='%'), self.symbol, self.interval, @@ -479,8 +479,8 @@ def apply_general_settings(self, settings: Dict[str, Union[float, str, dict]]): Apples settings provided from the settings argument to the backtester object. :param settings: Dictionary with keys and values to set. """ - if 'takeOrderType' in settings: - self.takeOrderType = OrderType.from_str(settings['takeOrderType']) + if 'takeProfitType' in settings: + self.takeProfitType = OrderType.from_str(settings['takeProfitType']) self.takeProfitPercentageDecimal = settings['takeProfitPercentage'] / 100 if 'lossType' in settings: @@ -630,7 +630,7 @@ def main_logic(self): if self.currentPosition == SHORT: if self.lossStrategy is not None and self.currentPrice > self.get_stop_loss(): self.buy_short('Exited short because a stop loss was triggered.', stopLossExit=True) - elif self.takeOrderType is not None and self.currentPrice <= self.get_take_profit(): + elif self.takeProfitType is not None and self.currentPrice <= self.get_take_profit(): self.buy_short("Exited short because of take profit.") elif trend == BULLISH: self.buy_short('Exited short because a bullish trend was detected.') @@ -640,7 +640,7 @@ def main_logic(self): elif self.currentPosition == LONG: if self.lossStrategy is not None and self.currentPrice < self.get_stop_loss(): self.sell_long('Exited long because a stop loss was triggered.', stopLossExit=True) - elif self.takeOrderType is not None and self.currentPrice >= self.get_take_profit(): + elif self.takeProfitType is not None and self.currentPrice >= self.get_take_profit(): self.sell_long("Exited long because of take profit.") elif trend == BEARISH: self.sell_long('Exited long because a bearish trend was detected.') @@ -689,7 +689,7 @@ def print_configuration_parameters(self, stdout=None): print(f'\tMargin Enabled: {self.marginEnabled}') print(f"\tStarting Balance: ${self.startingBalance}") - if self.takeOrderType is not None: + if self.takeProfitType is not None: print(f'\tTake Profit Percentage: {round(self.takeProfitPercentageDecimal * 100, 2)}%') if self.lossStrategy is not None: diff --git a/algobot/traders/simulationtrader.py b/algobot/traders/simulationtrader.py index 74bdc550..c68a4d73 100644 --- a/algobot/traders/simulationtrader.py +++ b/algobot/traders/simulationtrader.py @@ -105,9 +105,9 @@ def get_grouped_statistics(self) -> dict: 'scheduledTimerRemaining': self.get_remaining_safety_timer(), } - if self.takeOrderType is not None: + if self.takeProfitType is not None: groupedDict['takeProfit'] = { - 'takeOrderType': OrderType.to_str(self.takeOrderType), + 'takeProfitType': OrderType.to_str(self.takeProfitType), 'takeProfitPercentage': self.get_safe_rounded_percentage(self.takeProfitPercentageDecimal), 'trailingTakeProfitActivated': str(self.trailingTakeProfitActivated), 'takeProfitPoint': self.get_safe_rounded_string(self.takeProfitPoint), diff --git a/algobot/traders/trader.py b/algobot/traders/trader.py index beda86f5..9b27d61e 100644 --- a/algobot/traders/trader.py +++ b/algobot/traders/trader.py @@ -36,7 +36,7 @@ def __init__(self, symbol, precision, startingBalance, marginEnabled: bool = Tru self.takeProfitPoint = None # Price at which bot will exit trade to secure profits. self.trailingTakeProfitActivated = False # Boolean that'll turn true if a stop order is activated. - self.takeOrderType = None # Type of take profit: trailing or stop. + self.takeProfitType = None # Type of take profit: trailing or stop. self.takeProfitPercentageDecimal = None # Percentage of profit to exit trade at. # Prices information. @@ -172,7 +172,7 @@ def apply_take_profit_settings(self, takeProfitDict: Dict[str, int]): :return: None """ self.takeProfitPercentageDecimal = takeProfitDict["takeProfitPercentage"] / 100 - self.takeOrderType = takeProfitDict["takeOrderType"] + self.takeProfitType = takeProfitDict["takeProfitType"] def apply_loss_settings(self, lossDict: Dict[str, int]): """ @@ -410,16 +410,16 @@ def get_take_profit(self) -> Union[float, None]: Returns price at which position will be exited to secure profits. :return: Price at which to exit position. """ - if self.takeOrderType is None: + if self.takeProfitType is None: return None if self.currentPosition == SHORT: - if self.takeOrderType == OrderType.STOP: + if self.takeProfitType == OrderType.STOP: self.takeProfitPoint = self.sellShortPrice * (1 - self.takeProfitPercentageDecimal) else: raise ValueError("Invalid type of take profit type provided.") elif self.currentPosition == LONG: - if self.takeOrderType == OrderType.STOP: + if self.takeProfitType == OrderType.STOP: self.takeProfitPoint = self.buyLongPrice * (1 + self.takeProfitPercentageDecimal) else: raise ValueError("Invalid type of take profit type provided.") From d42426623812a61c9b7c6f2aa5fd6343d5c8f28f Mon Sep 17 00:00:00 2001 From: Malachi Soord Date: Thu, 15 Jul 2021 20:36:28 +0200 Subject: [PATCH 11/11] Fix tests --- tests/test_backtester.py | 4 ++-- tests/test_base_trader.py | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/test_backtester.py b/tests/test_backtester.py index daa157bc..f0c31929 100644 --- a/tests/test_backtester.py +++ b/tests/test_backtester.py @@ -25,7 +25,7 @@ def setUp(self) -> None: symbol="1INCHUSDT", marginEnabled=True, ) - self.backtester.apply_take_profit_settings({'takeOrderType': OrderType.TRAILING, 'takeProfitPercentage': 5}) + self.backtester.apply_take_profit_settings({'takeProfitType': OrderType.TRAILING, 'takeProfitPercentage': 5}) self.backtester.apply_loss_settings({'lossType': OrderType.TRAILING, 'lossPercentage': 5}) def test_initialization(self): @@ -313,7 +313,7 @@ def test_stop_take_profit(self): Test backtester take profit logic. """ backtester = self.backtester - backtester.takeOrderType = OrderType.STOP + backtester.takeProfitType = OrderType.STOP backtester.set_priced_current_price_and_period(10) backtester.buy_long("Test purchase.") self.assertEqual(backtester.get_take_profit(), 10 * (1 + backtester.takeProfitPercentageDecimal)) diff --git a/tests/test_base_trader.py b/tests/test_base_trader.py index 5a663c19..17c17bf6 100644 --- a/tests/test_base_trader.py +++ b/tests/test_base_trader.py @@ -149,12 +149,12 @@ def test_set_safety_timer(self): def test_apply_take_profit_settings(self): take_profit_settings = { 'takeProfitPercentage': 25, - 'takeOrderType': OrderType.STOP + 'takeProfitType': OrderType.STOP } self.trader.apply_take_profit_settings(take_profit_settings) self.assertEqual(self.trader.takeProfitPercentageDecimal, 0.25) - self.assertEqual(self.trader.takeOrderType, OrderType.STOP) + self.assertEqual(self.trader.takeProfitType, OrderType.STOP) def test_apply_loss_settings(self): loss_settings = { @@ -316,7 +316,7 @@ def test_get_safe_rounded_string(self): multiplier=5), '6.15*') def test_get_take_profit(self): - self.trader.takeOrderType = OrderType.STOP + self.trader.takeProfitType = OrderType.STOP self.trader.takeProfitPercentageDecimal = 0.05 self.trader.currentPosition = LONG @@ -327,10 +327,10 @@ def test_get_take_profit(self): self.trader.sellShortPrice = 10 self.assertEqual(self.trader.get_take_profit(), 10 * (1 - 0.05)) - self.trader.takeOrderType = None + self.trader.takeProfitType = None self.assertEqual(self.trader.get_take_profit(), None) - self.trader.takeOrderType = 5 + self.trader.takeProfitType = 5 with pytest.raises(ValueError, match="Invalid type of take profit type provided."): self.trader.get_take_profit()