Skip to content

Commit

Permalink
Fixed order managers logging - minor bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
powprashant committed Oct 28, 2023
1 parent e4e480e commit 914fb79
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 14 deletions.
26 changes: 21 additions & 5 deletions src/common/order_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,18 @@ def __init__(self, client: IClientManager, config) -> None:
self.live_feed_mgr = None
self.target_achieved = False
self.exchange_type = "D"
if "SL_FACTOR" in self.config:
self.sl_factor = self.config["SL_FACTOR"]
else:
self.sl_factor = 1.65

def set_exchange_type(self, exch_type: str) -> str:
self.exchange_type = exch_type

def place_short(self, strikes: dict, tag: str) -> None:
for item in ["ce", "pe"]:
# strikes["%s_ltp" % item] # Market Order if price =0.0
# Market Order if price =0.0, we place a limit order instead with 0.5 less
# to increase the chances of execution
price = self.square_off_price(rate=strikes[f"{item}_ltp"]) - 0.5
scrip_code = strikes[f"{item}_code"]
textinfo = f"""client.place_order(OrderType='S',
Expand All @@ -49,8 +54,17 @@ def place_short(self, strikes: dict, tag: str) -> None:
if order_status["Message"] == "Success":
self.logger.debug("%s_done", item)
time.sleep(2)
pending_orders = self.get_sl_pending_orders(tag)
if len(pending_orders) > 0:
self.logger.warning(
"%s orders not executed ! Waiting for another 1 min",
json.dumps(pending_orders, indent=2),
)
time.sleep(60)
else:
self.logger.info("All short orders executed !")

def aggregate_sl_orders(self, tag: str, sl_factor=1.65):
def aggregate_sl_orders(self, tag: str, sl_factor: float = 1.65):
sl_details = None
response = self.client.get_tradebook()
if response:
Expand Down Expand Up @@ -112,9 +126,10 @@ def aggregate_sl_orders(self, tag: str, sl_factor=1.65):
# so we need to aggregate them based on scrip code
# This is done to reduce brokerage when sl hits, we want one sl order to
# be executed, instead of multiple orders
def place_short_stop_loss_v2(self, tag: str, retries: int = 0) -> None:
while retries < 3:
sl_details = self.aggregate_sl_orders(tag)
def place_short_stop_loss_v2(self, tag: str, retries_count: int = 3) -> None:
retries = 0
while retries < retries_count:
sl_details = self.aggregate_sl_orders(tag, self.sl_factor)
if sl_details is None:
self.logger.info(
"No fully executed Orders found for %s waiting for 2 seconds", tag
Expand Down Expand Up @@ -159,6 +174,7 @@ def place_short_stop_loss_v2(self, tag: str, retries: int = 0) -> None:
self.logger.error("Failed to place stop loss for %d", scrip_code)
time.sleep(0.5)

## Make it generic, remove following logging, as those doesn't belong here
self.logger.info("Collecting Maximum Premium of :%f INR", max_premium)
self.logger.info("Maximum Loss of :%f INR", max_loss)

Expand Down
24 changes: 15 additions & 9 deletions tests/strategy_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,23 @@ def __init__(
order_manager: order_manager.OrderManager,
strikes_manager: strikes_manager.StrikesManager,
):
index_option = self.order_manager.config["INDEX_OPTION"]
## select the index based on the config
if index_option == "NIFTY":
index_option = StrangleStrategy.NIFTY_INDEX
elif index_option == "BANKNIFTY":
self.index = StrangleStrategy.BANKNIFTY_INDEX
else:
raise Exception("Invalid index option")
super().__init__(
"Strangle",
[StrangleStrategy.NIFTY_INDEX, strikes["ce_code"], strikes["pe_code"]],
[self.index, strikes["ce_code"], strikes["pe_code"]],
)
self.strikes_manager = strikes_manager
self.order_manager = order_manager
self.feed_manager = feed_manager

## This should be managed by base, by currently putting it here
## This should be managed by base, but currently putting it here

self.strikes = strikes
self.set_mtm_target(self.order_manager.config["target_profit"])
Expand Down Expand Up @@ -78,7 +86,7 @@ def get_leg_pnl(self, _code: int, avg: float, qty: int, ltp: float):
def entry(self, ohlcvt: dict) -> bool:
if self.is_in_position(): ## Already in a trade
return False
if StrangleStrategy.NIFTY_INDEX == ohlcvt["code"]:
if self.index == ohlcvt["code"]:
if self.user_data["nifty_index"]["low"] == -1.0:
self.user_data["nifty_index"]["low"] = ohlcvt["l"]
if self.user_data["nifty_index"]["high"] == -1.0:
Expand All @@ -94,11 +102,9 @@ def entry(self, ohlcvt: dict) -> bool:
and ohlcvt["c"] > self.user_data["nifty_index"]["low"]
):
## Unsubscribe from the nifty index feed
self.feed_manager.unsubscribe(
scrip_codes=[StrangleStrategy.NIFTY_INDEX]
)
## Reove the nifty index from the scrip codes
self.unmonitor(StrangleStrategy.NIFTY_INDEX)
self.feed_manager.unsubscribe(scrip_codes=[self.index])
## Remove the nifty index from the scrip codes
self.unmonitor(self.index)
## we are ready to take the trade
self.logger.info("Ready to take the trade at %f", ohlcvt["c"])
## Log some stats
Expand Down Expand Up @@ -212,7 +218,7 @@ def order_placed(self, order: dict, subsList: dict, user_data: dict):
def start(self):
self.feed_manager.monitor(
scrip_codes=[
StrangleStrategy.NIFTY_INDEX,
self.index,
self.strikes["ce_code"],
self.strikes["pe_code"],
],
Expand Down

0 comments on commit 914fb79

Please sign in to comment.