Skip to content
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

💄 PnL code structure alignement #442

Merged
merged 4 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 6 additions & 17 deletions cefi/handler/capitalcom.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"""

import asyncio
from datetime import datetime, timedelta

from capitalcom.client import Client, DirectionType
from capitalcom.client_demo import Client as DemoClient
Expand Down Expand Up @@ -194,34 +193,24 @@ async def get_account_position(self):
except Exception as e:
logger.error(f"{self.name} Error {e}")

async def get_account_pnl(self, period=None):
async def calculate_pnl(self, period=None):
"""
Return account pnl.
no pnl info available via openapi endpoint

Args:
None

Returns:
pnl
"""
today = datetime.now().date()
if period is None:
start_date = today
elif period == "W":
start_date = today - timedelta(days=today.weekday())
elif period == "M":
start_date = today.replace(day=1)
elif period == "Y":
start_date = today.replace(month=1, day=1)

end_date = datetime.now()
formatted_end_date = end_date.strftime("%Y-%m-%dT%H:%M:%S")
logger.debug("{} {}", start_date, formatted_end_date)
# end_date = datetime.now()
# formatted_end_date = end_date.strftime("%Y-%m-%dT%H:%M:%S")
# logger.debug("{} {}", start_date, formatted_end_date)
# history = self.client.account_activity_history(
# fr=start_date, to=formatted_end_date, detailed=True
# )
# logger.debug("History: {}", history)
# no pnl info available via openapi endpoint

return 0

async def pre_order_checks(self, order_params):
Expand Down
44 changes: 44 additions & 0 deletions cefi/handler/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

"""

from datetime import datetime, timedelta

from loguru import logger


Expand All @@ -22,6 +24,23 @@ class CexClient:
Returns:
None

Methods:
get_quote(self, instrument)
get_offer(self, instrument)
get_bid(self, instrument)
get_account_balance(self)
get_account_position(self)
calculate_pnl(self, period=None)
get_account_pnl(self, start_date)
execute_order(self, order_params)
get_trading_asset_balance(self)
get_order_amount(self, quantity, instrument, is_percentage)
pre_order_checks(self, order_params)
replace_instrument(self, instrument)
get_instrument_decimals(self, instrument)
get_trade_confirmation(self, order_params)
Comment on lines +27 to +41
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code_clarification): Consider documenting method purposes in the class docstring.

While listing methods in the class docstring provides an overview, including a brief description of each method's purpose or functionality could enhance readability and maintainability.



"""

def __init__(self, **kwargs):
Expand Down Expand Up @@ -61,6 +80,7 @@ def __init__(self, **kwargs):
self.mapping = kwargs.get("mapping", None)
self.balance_limit = kwargs.get("balance_limit", True)
self.balance_limit_value = kwargs.get("balance_limit_value", 10)
self.is_pnl_active = kwargs.get("is_pnl_active", False)

except Exception as error:
logger.error("Client initialization error {}", error)
Expand Down Expand Up @@ -130,6 +150,30 @@ async def get_account_pnl(self, period=None):
Returns:
pnl
"""
today = datetime.now().date()
if period is None:
start_date = today
elif period == "W":
start_date = today - timedelta(days=today.weekday())
elif period == "M":
start_date = today.replace(day=1)
elif period == "Y":
start_date = today.replace(month=1, day=1)
else:
return 0
return self.calculate_pnl(start_date) if self.is_pnl_active else 0

async def calculate_pnl(self, period=None):
"""
Calculate the PnL for a given period.

Parameters:
period (str): The period for which
to calculate PnL ('W', 'M', 'Y', or None).

Returns:
pnl: The calculated PnL value.
"""

async def execute_order(self, order_params):
"""
Expand Down
11 changes: 8 additions & 3 deletions cefi/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ async def get_positions(self):
_info.append(f"{client.name}:\n{await client.get_account_position()}")
return "\n".join(_info)

async def get_pnls(self):
async def get_pnls(self, **kwargs):
"""
Return account pnl.

Expand All @@ -236,9 +236,14 @@ async def get_pnls(self):
Returns:
pnl
"""
_info = ["📊\n"]
_info = ["🏆\n"]
for client in self.clients:
_info.append(f"{client.name}:\n{await client.get_account_pnl()}")
client_name = f"{client.name}:\n"
account_pnl = await client.get_account_pnl(
period=kwargs.get("period", None)
)
client_info = f"{client_name}{account_pnl}"
_info.append(client_info)
return "\n".join(_info)

async def submit_order(self, order_params):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ async def test_get_positions(CXTrader):
async def test_get_pnls(CXTrader):
"""Test pnl"""
result = await CXTrader.get_pnls()
assert "📊" in result
assert "🏆" in result


@pytest.mark.asyncio
Expand Down