-
Notifications
You must be signed in to change notification settings - Fork 175
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Encapsulate Trailing and Stop #43
base: master
Are you sure you want to change the base?
Changes from 10 commits
37af02d
322cba1
abaa863
1f7f093
3184406
45aa480
fdd9e96
aa9dea7
48dab27
7ad843b
3f5ad32
d424266
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,7 +7,7 @@ | |
QLabel, QLayout, QMainWindow, QSpinBox, | ||
QTabWidget) | ||
|
||
from algobot.enums import BACKTEST, LIVE, OPTIMIZER, SIMULATION, STOP, TRAILING | ||
from algobot.enums import BACKTEST, LIVE, OPTIMIZER, SIMULATION, OrderType | ||
from algobot.graph_helpers import create_infinite_line | ||
from algobot.helpers import ROOT_DIR | ||
from algobot.interface.config_utils.credential_utils import load_credentials | ||
|
@@ -73,7 +73,7 @@ def __init__(self, parent: QMainWindow, logger: Logger = None): | |
} | ||
|
||
self.lossTypes = ("Trailing", "Stop") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should probably leverage the actual enum values? let's not use integers but actual strings? what do you think? :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could work - trying to think of how would be best to handle semantics vs presentation There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Well, as long as the enums stay the same, we can just replace the value. |
||
self.takeProfitTypes = ('Stop',) | ||
self.takeOrderTypes = ('Stop',) | ||
inverse marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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, 'takeProfitType', self.takeProfitOptimizerTypes, settings) | ||
self.helper_get_optimizer(tab, self.takeProfitDict, 'takeOrderType', self.takeProfitOptimizerTypes, settings) | ||
self.get_strategy_intervals_for_optimizer(settings) | ||
|
||
settings['strategies'] = {} | ||
|
@@ -282,26 +282,26 @@ 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?') | ||
inverse marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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) | ||
self.takeProfitDict[optimizerType, 'end'] = end = get_default_widget(QSpinBox, 1, 0) | ||
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): | ||
|
@@ -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 "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: | ||
|
@@ -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, 'takeProfitType'].currentText() == "Trailing": | ||
takeProfitType = TRAILING | ||
if dictionary[tab, 'takeOrderType'].currentText() == "Trailing": | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should probably use the to_str method() |
||
takeOrderType = OrderType.TRAILING | ||
else: | ||
takeProfitType = 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() | ||
} | ||
|
||
|
@@ -381,21 +381,22 @@ 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 | ||
loss_type = dictionary[tab, "lossType"].currentText() | ||
loss_strategy = OrderType.TRAILING if loss_type == "Trailing" else OrderType.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): | ||
""" | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ | |
from typing import Dict, List, 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, OrderType) | ||
from algobot.helpers import get_label_string, parse_strategy_name | ||
from algobot.strategies.strategy import Strategy | ||
|
||
|
@@ -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.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. | ||
|
@@ -172,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]): | ||
""" | ||
|
@@ -224,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 == TRAILING: | ||
elif self.lossStrategy == OrderType.TRAILING: | ||
self.stopLoss = self.shortTrailingPrice * (1 + self.lossPercentageDecimal) | ||
elif self.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 == TRAILING: | ||
elif self.lossStrategy == OrderType.TRAILING: | ||
self.stopLoss = self.longTrailingPrice * (1 - self.lossPercentageDecimal) | ||
elif self.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. | ||
|
@@ -246,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 == STOP: | ||
if self.lossStrategy == OrderType.STOP: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should probably deprecate this function and add a kwarg for suffix in the to_str method |
||
return 'Stop Loss' | ||
elif self.lossStrategy == TRAILING: | ||
elif self.lossStrategy == OrderType.TRAILING: | ||
return 'Trailing Loss' | ||
elif self.lossStrategy is None: | ||
return 'None' | ||
|
@@ -320,28 +320,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(stopType: Union[int, None]) -> str: | ||
""" | ||
Returns stop type in string format instead of integer enum. | ||
:return: Stop type in string format. | ||
""" | ||
if stopType == STOP: | ||
return 'Stop' | ||
elif stopType == TRAILING: | ||
return 'Trailing' | ||
elif stopType 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 TRAILING | ||
elif string.lower() == 'stop': | ||
return STOP | ||
|
||
@staticmethod | ||
def get_trend_string(trend) -> str: | ||
""" | ||
|
@@ -432,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 == 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 == STOP: | ||
if self.takeOrderType == OrderType.STOP: | ||
self.takeProfitPoint = self.buyLongPrice * (1 + self.takeProfitPercentageDecimal) | ||
else: | ||
raise ValueError("Invalid type of take profit type provided.") | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Still could be improved but it's a step in the right direction. by improvements we could use real enums and get read of the whole
from_str
but that would require a lot more mapping ;)Like mapping the UI element to string -> enum value :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nice