Skip to content

Commit

Permalink
Merge pull request #97 from kieran-mackle/development
Browse files Browse the repository at this point in the history
Some tidy ups
  • Loading branch information
kieran-mackle authored Mar 12, 2024
2 parents fd10c4d + 6712df9 commit 31283a7
Show file tree
Hide file tree
Showing 7 changed files with 162 additions and 204 deletions.
6 changes: 1 addition & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,7 @@
<a href="https://pepy.tech/project/autotrader">
<img src="https://pepy.tech/badge/autotrader/month" alt="Monthly downloads" >
</a>

<a>
<img src="https://github.com/kieran-mackle/AutoTrader/actions/workflows/tests.yml/badge.svg" alt="Build Status" >
</a>


<a href='https://autotrader.readthedocs.io/en/latest/?badge=latest'>
<img src='https://readthedocs.org/projects/autotrader/badge/?version=latest' alt='Documentation Status' />
</a>
Expand Down
2 changes: 1 addition & 1 deletion autotrader/autobot.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ def __init__(
# Build strategy instantiation arguments
strategy_inputs = {
"parameters": params,
# "data": self._strat_data,
"instrument": self.instrument,
"broker": self._broker,
"notifier": self._notifier,
}

# Instantiate Strategy
Expand Down
58 changes: 33 additions & 25 deletions autotrader/autotrader.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
from ast import literal_eval
from threading import Thread
from scipy.optimize import brute
from autotrader.comms.tg import Telegram
from autotrader.strategy import Strategy
from autotrader.autoplot import AutoPlot
from autotrader.autobot import AutoTraderBot
from autotrader.brokers.broker import Broker
from datetime import datetime, timedelta, timezone
from typing import Callable, Optional, Literal, Union
from autotrader.brokers.ccxt import Broker as CCXTBroker
from autotrader.brokers.virtual import Broker as VirtualBroker
from autotrader.utilities import (
read_yaml,
Expand Down Expand Up @@ -107,7 +109,7 @@ def __init__(self) -> None:

# Communications
self._notify = 0
self._notification_provider = ""
self._notification_provider: Literal["telegram"] = ""
self._notifier = None
self._order_summary_fp = None

Expand Down Expand Up @@ -196,7 +198,7 @@ def configure(
feed: Optional[str] = None,
home_dir: Optional[str] = None,
notify: Optional[int] = 0,
notification_provider: Optional[str] = None,
notification_provider: Optional[Literal["telegram"]] = "telegram",
execution_method: Optional[Callable] = None,
account_id: Optional[str] = None,
environment: Optional[Literal["paper", "live"]] = "paper",
Expand Down Expand Up @@ -856,7 +858,7 @@ def scan(
self._scan_mode = True
self._scan_index = scan_index

def run(self) -> Union[None, Broker]:
def run(self) -> Union[None, Broker, VirtualBroker, CCXTBroker]:
"""Performs essential checks and runs AutoTrader."""
# Create logger
self.logger = get_logger(
Expand Down Expand Up @@ -1004,29 +1006,35 @@ def run(self) -> Union[None, Broker]:
self._global_config_dict = global_config

# Create notifier instance
if "telegram" in self._notification_provider.lower():
# Use telegram
if "TELEGRAM" not in self._global_config_dict:
self.logger.error(
"Please configure your telegram bot in keys.yaml."
)
sys.exit()

else:
# Check keys provided
required_keys = ["api_key", "chat_id"]
for key in required_keys:
if key not in self._global_config_dict["TELEGRAM"]:
self.logger.error(
f"Please provide {key} under TELEGRAM in keys.yaml."
)
sys.exit()
if self._notify > 0:
if "telegram" in self._notification_provider.lower():
# Use telegram
if "TELEGRAM" not in self._global_config_dict:
self.logger.error(
"Please configure your telegram bot in keys.yaml. At "
+ "a minimum, you must specify the api_key for your bot. You can "
+ "also specify your chat_id. If you do not know it, then send your "
+ "bot a message before starting AutoTrader again, and it will "
+ "be inferred."
)
sys.exit()

tg_module = importlib.import_module(f"autotrader.comms.tg")
self._notifier = tg_module.Telegram(
api_token=self._global_config_dict["TELEGRAM"]["api_key"],
chat_id=self._global_config_dict["TELEGRAM"]["chat_id"],
)
else:
# Check keys provided
required_keys = ["api_key"]
for key in required_keys:
if key not in self._global_config_dict["TELEGRAM"]:
self.logger.error(
f"Please define {key} under TELEGRAM in keys.yaml."
)
sys.exit()

# Instantiate notifier
self._notifier = Telegram(
api_token=self._global_config_dict["TELEGRAM"]["api_key"],
chat_id=self._global_config_dict["TELEGRAM"].get("chat_id"),
logger_kwargs=self._logger_kwargs,
)

# Check data feed requirements
if self._feed is None:
Expand Down
37 changes: 21 additions & 16 deletions autotrader/brokers/ccxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,32 +81,37 @@ def place_order(self, order: Order, **kwargs) -> None:
"""Place an order."""
order()

# Check order meets limits
limits: dict = self.api.markets.get(order.instrument, {}).get("limits", {})
if limits.get("amount") is not None:
if order.size < limits["amount"]["min"]:
# Order too small
self._logger.warning(f"Order below minimum size: {order}")
return None

# Add order params
self._add_params(order)

# Submit order to broker
if order.order_type == "modify":
placed_order = self._modify_order(order)
elif order.order_type in [
"close",
"reduce",
]:
raise NotImplementedError(
f"Order type '{order.order_type}' has not "
+ "been implemented for the CCXT interface yet."
)

else:
# Regular order
side = "buy" if order.direction > 0 else "sell"

# Submit the order
placed_order = self.api.create_order(
symbol=order.instrument,
type=order.order_type,
side=side,
amount=abs(order.size),
price=order.order_limit_price,
params=order.ccxt_params,
)
try:
placed_order = self.api.create_order(
symbol=order.instrument,
type=order.order_type,
side=side,
amount=abs(order.size),
price=order.order_limit_price,
params=order.ccxt_params,
)
except Exception as e:
placed_order = e

return placed_order

Expand Down
2 changes: 1 addition & 1 deletion autotrader/comms/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class Notifier(ABC):
@abstractmethod
def __init__(self, *args, **kwargs) -> None:
def __init__(self, logger_kwargs: dict = None, *args, **kwargs) -> None:
pass

@abstractmethod
Expand Down
Loading

0 comments on commit 31283a7

Please sign in to comment.