Skip to content

Commit

Permalink
📝 updated docstring
Browse files Browse the repository at this point in the history
  • Loading branch information
mraniki committed Aug 7, 2023
1 parent e55aa9d commit 4a59d9d
Show file tree
Hide file tree
Showing 4 changed files with 248 additions and 22 deletions.
5 changes: 5 additions & 0 deletions tt/plugins/default_plugins/ __init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""
Plugins location
"""

119 changes: 108 additions & 11 deletions tt/plugins/default_plugins/cex_exchange_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@


class CexExchangePlugin(BasePlugin):
"""CEX Plugin"""
"""
Class CexExchangePlugin to support CEX Exchange
Args:
None
Returns:
None
"""
name = os.path.splitext(os.path.basename(__file__))[0]
def __init__(self):
super().__init__()
Expand All @@ -34,7 +43,17 @@ def should_handle(self, message):
return self.enabled

async def handle_message(self, msg):
"""Handles incoming messages"""
"""
Handles incoming messages
to route to the respective function
Args:
msg (str): The incoming message
Returns:
None
"""
if not self.enabled:
return

Expand Down Expand Up @@ -69,7 +88,18 @@ async def handle_message(self, msg):


class CexExchange():
"""CEX Object"""
"""
CEX Object to support CEX
via CCXT library to be reviewed
to be stored in different file/package
Args:
None
Returns:
None
"""
def __init__(self):
if settings.cex_name:
client = getattr(ccxt, settings.cex_name)
Expand All @@ -86,25 +116,61 @@ def __init__(self):
self.commands = settings.ccxt_commands

async def get_info(self):
"""info_message"""
"""
info_message
"""
exchange_name = self.cex.id
account_info = self.cex.uid
#account_info = self.cex.fetchAccounts().get('main')
# account_info = self.cex.fetchAccounts().get('main')
# method not implemented yet
return f"💱 {exchange_name}\n🪪 {account_info}"

async def get_help(self):
"""
Get the help information for the current instance.
Returns:
A string containing the available commands.
"""
return (f"{self.commands}\n")

async def get_quote(self, symbol):
"""return main asset balance."""
"""
return main asset balance.
Args:
symbol
Returns:
quote
"""

return f"🏦 {self.cex.fetchTicker(symbol).get('last')}"

async def get_trading_asset_balance(self):
"""return main asset balance."""
"""
return main asset balance.
Args:
None
Returns:
balance
"""
return self.cex.fetchBalance()[f"{settings.trading_asset}"]["free"]

async def get_account_balance(self):
"""return account balance."""
"""
return account balance.
Args:
None
Returns:
balance
"""
raw_balance = self.cex.fetch_free_balance()
filtered_balance = {k: v for k, v in
raw_balance.items()
Expand All @@ -118,19 +184,50 @@ async def get_account_balance(self):
return balance

async def get_account_position(self):
"""return account position."""
"""
return account position.
Args:
None
Returns:
position
"""
open_positions = self.cex.fetch_positions()
open_positions = [p for p in open_positions if p['type'] == 'open']
position = "📊 Position\n" + str(open_positions)
position += str(await self.cex.fetch_balance({'type': 'margin',}))
return position

async def get_account_pnl(self):
"""return account pnl."""
"""
return account pnl.
Args:
None
Returns:
pnl
"""

return 0

async def execute_order(self, order_params):
"""Execute order."""
"""
Execute order
Args:
order_params (dict):
action(str)
instrument(str)
quantity(int)
Returns:
trade_confirmation(dict)
"""

action = order_params.get('action')
instrument = order_params.get('instrument')
quantity = order_params.get('quantity', settings.trading_risk_amount)
Expand Down
123 changes: 113 additions & 10 deletions tt/plugins/plugin_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,34 @@


class PluginManager:
"""🔌 Plugin Manager """
"""
🔌 Plugin Manager use to load, start and
dispatch message to the plugins
Args:
plugin_directory (str): Directory of plugins
Returns:
None
"""

def __init__(self, plugin_directory=None):
self.plugin_directory = plugin_directory or settings.plugin_directory
self.plugins = []

def load_plugins(self):
""" Load plugins from directory """
"""
🔌Load plugins from directory
Returns:
None
Raises:
Exception
"""
package = importlib.import_module(self.plugin_directory)
logger.debug("Loading plugins from: {}", package)
for _, plugin_name, _ in pkgutil.iter_modules(package.__path__):
Expand All @@ -27,7 +48,17 @@ def load_plugins(self):
logger.warning("Error loading plugin {}: {}", plugin_name, e)

def load_plugin(self, module, plugin_name):
""" Load a plugin from a module """
"""
Load a plugin from a module
Args:
module (Module): Module
plugin_name (str): Plugin name
Returns:
None
"""
logger.debug("plugin_name: {}", plugin_name)
for name, obj in module.__dict__.items():
if (isinstance(obj, type)
Expand All @@ -38,18 +69,44 @@ def load_plugin(self, module, plugin_name):
logger.debug("Plugin loaded: {}", name)

async def start_all_plugins(self):
""" Start all plugins """
"""
Start all plugins
Start the scheduler
Returns:
None
"""

for plugin in self.plugins:
await self.start_plugin(plugin)
scheduler.start()

async def start_plugin(self, plugin):
""" Start a plugin """
"""
Start a plugin
Args:
plugin (Plugin): Plugin
Returns:
None
"""
await plugin.start()

async def process_message(self, message):
""" Send message to plugins """
"""
Send message to plugins
Args:
message (str): Message
Returns:
None
"""
for plugin in self.plugins:
try:
if plugin.should_handle(message):
Expand All @@ -63,6 +120,18 @@ async def process_message(self, message):
class BasePlugin:
"""
⚡ Base Plugin Class
use to be inherited by Talky Plugins
especially the scheduling, notification and
message handling.
Args:
None
Returns:
None
"""
def __init__(self):
self.enabled = False
Expand All @@ -78,6 +147,16 @@ async def send_notification(self, message):
pass

def should_handle(self, message):
"""
Returns True if the plugin should handle the message
Args:
message (str): Message
Returns:
bool
"""
return (not message.startswith(settings.bot_ignore)
if self.enabled else False)

Expand All @@ -86,8 +165,19 @@ async def plugin_notify_schedule_task(
user_name=None,
frequency=8,
function=None):
"""Handles task notification
every X hours. Defaulted to 8 hours"""
"""
Handles task notification
every X hours. Defaulted to 8 hours
Args:
user_name (str): User name
frequency (int): Frequency
function (function): Function
Returns:
None
"""

if function:
self.scheduler.add_task(
name=user_name,
Expand All @@ -104,8 +194,21 @@ async def plugin_notify_cron_task(
user_hours="6,12,18",
user_timezone="UTC",
function=None):
"""Handles task cron scheduling for notification
Monday to Friday at 6AM, 12PM and 6PM UTC"""
"""
Handles task cron scheduling for notification
Monday to Friday at 6AM, 12PM and 6PM UTC
Args:
user_name (str): User name
user_day_of_week (str): Day of week
user_hours (str): Hours
user_timezone (str): Timezone
function (function): Function
Returns:
None
"""
if function:
self.scheduler.add_task(
name=user_name,
Expand Down
Loading

0 comments on commit 4a59d9d

Please sign in to comment.