Skip to content

Commit

Permalink
Merge pull request #513 from mraniki/dev
Browse files Browse the repository at this point in the history
🎨 and ♻️ ccxt execute_order refactoring
  • Loading branch information
mraniki authored Sep 9, 2024
2 parents 5a1ceaf + aec490b commit a6df6bb
Show file tree
Hide file tree
Showing 18 changed files with 200 additions and 140 deletions.
9 changes: 8 additions & 1 deletion cefi/handler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,12 @@
from .ccxt import CcxtHandler
from .degiro import DegiroHandler
from .ibkr import IbHandler
from .oanda import OandaHandler

__all__ = ["CapitalHandler", "CcxtHandler", "DegiroHandler", "IbHandler"]
__all__ = [
"CapitalHandler",
"CcxtHandler",
"DegiroHandler",
"IbHandler",
"OandaHandler",
]
10 changes: 3 additions & 7 deletions cefi/handler/client.py → cefi/handler/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@
class CexClient:
"""
CEX Object to support CEFI
exchange and trading
via CCXT library
https://github.com/ccxt/ccxt
exchange and trading platform
Args:
None
Expand Down Expand Up @@ -89,8 +87,7 @@ async def get_bid(self, instrument):

async def get_account_balance(self):
"""
return account balance of
a given ccxt exchange
return account balance
Args:
None
Expand All @@ -103,7 +100,6 @@ async def get_account_balance(self):
async def get_account_position(self):
"""
Return account position.
of a given exchange
Args:
None
Expand Down Expand Up @@ -236,7 +232,7 @@ async def replace_instrument(self, instrument):

async def get_instrument_decimals(self, instrument):
"""
Get the number of decimal places for the token.
Returns:
int: The number of decimal places for the token.
Expand Down
2 changes: 1 addition & 1 deletion cefi/handler/capitalcom.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from capitalcom.client_demo import Client as DemoClient
from loguru import logger

from .client import CexClient
from ._client import CexClient


class CapitalHandler(CexClient):
Expand Down
98 changes: 66 additions & 32 deletions cefi/handler/ccxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,12 @@
import ccxt
from loguru import logger

from .client import CexClient
from ._client import CexClient


class CcxtHandler(CexClient):
"""
CEX client
via CCXT library
https://github.com/ccxt/ccxt
Library: https://github.com/ccxt/ccxt
Args:
None
Expand Down Expand Up @@ -65,9 +63,7 @@ async def get_quote(self, instrument):
"""
try:
instrument = await self.replace_instrument(instrument)

ticker = self.client.fetch_ticker(instrument)
quote = ticker["ask"]
quote = self.client.fetch_ticker(instrument)["ask"]
logger.debug("Quote: {}", quote)
return quote
except Exception as e:
Expand All @@ -87,11 +83,7 @@ async def get_bid(self, instrument):
"""
try:
instrument = await self.replace_instrument(instrument)

ticker = self.client.fetch_ticker(instrument)
quote = ticker["bid"]
logger.debug("Quote: {}", quote)
return quote
return await self.client.fetch_ticker(instrument)["bid"]
except Exception as e:
logger.error("{} Error {}", self.name, e)

Expand Down Expand Up @@ -163,40 +155,82 @@ async def execute_order(self, order_params):
"""
try:
action = order_params.get("action")
instrument = await self.replace_instrument(order_params.get("instrument"))
action = order_params["action"]
instrument = await self.replace_instrument(order_params["instrument"])
quantity = order_params.get("quantity", self.trading_risk_amount)
logger.debug("quantity {}", quantity)
amount = await self.get_order_amount(
quantity=quantity,
instrument=instrument,
is_percentage=self.trading_risk_percentage,
)
params = {
"stopLoss": {
"triggerPrice": order_params.get("stop_loss"),
# "price": order_params.get("action") * 0.98,
},
"takeProfit": {
"triggerPrice": order_params.get("take_profit"),
# "price": order_params.get("action") * 0.98,
},
"stopLoss": {"triggerPrice": order_params.get("stop_loss")},
"takeProfit": {"triggerPrice": order_params.get("take_profit")},
}
logger.debug("amount {}", amount)
pre_order_checks = await self.pre_order_checks(order_params)
logger.debug("pre_order_checks {}", pre_order_checks)

if amount and pre_order_checks:
if order := self.client.create_order(
if amount and await self.pre_order_checks(order_params):
order = self.client.create_order(
symbol=instrument,
type=self.ordertype,
side=action,
amount=amount,
params=params,
):
return await self.get_trade_confirmation(order, instrument, action)
)
return await self.get_trade_confirmation(order, instrument, action)
return f"Error executing {self.name}"

except Exception as e:
logger.error("{} Error {}", self.name, e)
return f"Error executing {self.name}"

# async def execute_order(self, order_params):
# """
# Execute order

# Args:
# order_params (dict):
# action(str)
# instrument(str)
# quantity(int)

# Returns:
# trade_confirmation(dict)

# """
# try:
# action = order_params.get("action")
# instrument = await self.replace_instrument(order_params.get("instrument"))
# quantity = order_params.get("quantity", self.trading_risk_amount)
# logger.debug("quantity {}", quantity)
# amount = await self.get_order_amount(
# quantity=quantity,
# instrument=instrument,
# is_percentage=self.trading_risk_percentage,
# )
# params = {
# "stopLoss": {
# "triggerPrice": order_params.get("stop_loss"),
# # "price": order_params.get("action") * 0.98,
# },
# "takeProfit": {
# "triggerPrice": order_params.get("take_profit"),
# # "price": order_params.get("action") * 0.98,
# },
# }
# logger.debug("amount {}", amount)
# pre_order_checks = await self.pre_order_checks(order_params)
# logger.debug("pre_order_checks {}", pre_order_checks)

# if amount and pre_order_checks:
# if order := self.client.create_order(
# symbol=instrument,
# type=self.ordertype,
# side=action,
# amount=amount,
# params=params,
# ):
# return await self.get_trade_confirmation(
# order, instrument, action)
# return f"Error executing {self.name}"

# except Exception as e:
# logger.error("{} Error {}", self.name, e)
# return f"Error executing {self.name}"
9 changes: 4 additions & 5 deletions cefi/handler/ctrader.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@
# from ctrader_open_api import Client
# from loguru import logger

# from .client import CexClient
# from ._client import CexClient


# class CtraderHandler(CexClient):
# """
# CEX client
# via openApiPy library
# https://github.com/spotware/openApiPy
# Library: https://github.com/spotware/openApiPy and
# https://ctraderacademy.com/ctrader-api/

# Args:
# None
Expand Down Expand Up @@ -57,7 +56,7 @@

# async def get_account_balance(self):
# """
# return account balance
# return account balance

# Args:
# None
Expand Down
2 changes: 1 addition & 1 deletion cefi/handler/degiro.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from degiro_connector.trading.models.order import Action, Order, OrderType, TimeType
from loguru import logger

from .client import CexClient
from ._client import CexClient


class DegiroHandler(CexClient):
Expand Down
5 changes: 2 additions & 3 deletions cefi/handler/etoro.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@

# """

#
#
# from loguru import logger

# from .client import CexClient
# from ._client import CexClient


# class EtoroHandler(CexClient):
Expand All @@ -34,7 +34,6 @@
# super().__init__(**kwargs)



# async def get_quote(self, instrument):
# """
# Return a quote for a instrument
Expand Down
2 changes: 1 addition & 1 deletion cefi/handler/fxcm.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

# from loguru import logger

# from .client import CexClient
# from ._client import CexClient


# class FxcmHandler(CexClient):
Expand Down
2 changes: 1 addition & 1 deletion cefi/handler/ibkr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from ib_insync import IB, IBC, Contract, Order
from loguru import logger

from .client import CexClient
from ._client import CexClient


class IbHandler(CexClient):
Expand Down
5 changes: 2 additions & 3 deletions cefi/handler/metatrader.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@

# from loguru import logger

# from .client import CexClient
# from ._client import CexClient


# class MetatraderHandler(CexClient):
# """
# library:
# library:

# Args:
# None
Expand All @@ -34,7 +34,6 @@
# super().__init__(**kwargs)



# async def get_quote(self, instrument):
# """
# Return a quote for a instrument
Expand Down
5 changes: 2 additions & 3 deletions cefi/handler/ninjatrader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

# from loguru import logger

# from .client import CexClient
# from ._client import CexClient


# class NinjatraderHandler(CexClient):
Expand All @@ -33,7 +33,6 @@
# super().__init__(**kwargs)



# async def get_quote(self, instrument):
# """
# Return a quote for a instrument
Expand All @@ -50,7 +49,7 @@

# async def get_account_balance(self):
# """
# return account balance
# return account balance

# Args:
# None
Expand Down
Loading

0 comments on commit a6df6bb

Please sign in to comment.