Skip to content

Commit

Permalink
Merge pull request freqtrade#82 from gcarq/feature/handle-process-sig…
Browse files Browse the repository at this point in the history
…nals

handle SIGINT, SIGTERM and SIGABRT process signals
  • Loading branch information
shusso authored Oct 28, 2017
2 parents 0c33e91 + 4139b0b commit 29de164
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
24 changes: 21 additions & 3 deletions freqtrade/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import traceback
from datetime import datetime
from typing import Dict, Optional
from signal import signal, SIGINT, SIGABRT, SIGTERM

from jsonschema import validate

Expand Down Expand Up @@ -223,6 +224,23 @@ def init(config: dict, db_url: Optional[str] = None) -> None:
else:
update_state(State.STOPPED)

# Register signal handlers
for sig in (SIGINT, SIGTERM, SIGABRT):
signal(sig, cleanup)


def cleanup(*args, **kwargs) -> None:
"""
Cleanup the application state und finish all pending tasks
:return: None
"""
telegram.send_msg('*Status:* `Stopping trader...`')
logger.info('Stopping trader and cleaning up modules...')
update_state(State.STOPPED)
persistence.cleanup()
telegram.cleanup()
exit(0)


def app(config: dict) -> None:
"""
Expand Down Expand Up @@ -251,10 +269,10 @@ def app(config: dict) -> None:
time.sleep(exchange.EXCHANGE.sleep_time)
old_state = new_state
except RuntimeError:
telegram.send_msg('*Status:* Got RuntimeError: ```\n{}\n```'.format(traceback.format_exc()))
telegram.send_msg(
'*Status:* Got RuntimeError:\n```\n{}\n```'.format(traceback.format_exc())
)
logger.exception('RuntimeError. Trader stopped!')
finally:
telegram.send_msg('*Status:* `Trader has stopped`')


def main():
Expand Down
8 changes: 8 additions & 0 deletions freqtrade/persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ def init(config: dict, db_url: Optional[str] = None) -> None:
Base.metadata.create_all(engine)


def cleanup() -> None:
"""
Flushes all pending operations to disk.
:return: None
"""
Trade.session.flush()


class Trade(Base):
__tablename__ = 'trades'

Expand Down
10 changes: 9 additions & 1 deletion freqtrade/rpc/telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
logging.getLogger('telegram').setLevel(logging.INFO)
logger = logging.getLogger(__name__)

_updater = None
_updater: Updater = None
_CONF = {}


Expand Down Expand Up @@ -61,6 +61,14 @@ def init(config: dict) -> None:
)


def cleanup() -> None:
"""
Stops all running telegram threads.
:return: None
"""
_updater.stop()


def authorized_only(command_handler: Callable[[Bot, Update], None]) -> Callable[..., Any]:
"""
Decorator to check if the message comes from the correct chat_id
Expand Down

0 comments on commit 29de164

Please sign in to comment.