Пример #1
0
 def log_order(self, contract, quantity, price, action, avg=0):
     curr_date, curr_dt = get_datetime_for_logging()
     log_str = f"Placed {action} order {quantity} {contract.strike}{contract.right}{contract.lastTradeDateOrContractMonth}"
     if action == "SELL":
         log_str += f" ({round(avg, 2)} average)"
     log_str += f" for {round(price * 100, 2)} each, {self._nope_value} | {self._underlying_price} | {curr_dt}\n"
     with open(f"logs/{curr_date}-trade.txt", "a") as f:
         f.write(log_str)
Пример #2
0
            async def fetch_and_report():
                try:
                    self.set_nope_value()
                except Exception as e:
                    log_exception(e, "set_nope_value")

                curr_date, curr_dt = get_datetime_for_logging()
                with open(f"logs/{curr_date}.txt", "a") as f:
                    f.write(f'NOPE @ {self._nope_value} | Stock Price @ {self._underlying_price} | {curr_dt}\n')
Пример #3
0
    def exit_positions(self):
        portfolio = self.get_portfolio()
        trades = self.get_trades()
        curr_date, curr_dt = get_datetime_for_logging()
        if self._nope_value > self.config["nope"]["long_exit"]:
            held_calls = self.get_held_contracts(portfolio, 'C')
            existing_call_order_ids = self.get_existing_order_ids(trades, 'C', 'SELL')
            remaining_calls = list(filter(lambda c: c['contract'].conId not in existing_call_order_ids, held_calls))

            if len(remaining_calls) > 0:
                remaining_calls.sort(key=lambda c: c['contract'].conId)
                remaining_call_contracts = [c['contract'] for c in remaining_calls]
                qualified_contracts = self.ib.qualifyContracts(*remaining_call_contracts)
                tickers = self.ib.reqTickers(*qualified_contracts)
                tickers.sort(key=lambda t: t.contract.conId)
                for idx, ticker in enumerate(tickers):
                    price = midpoint_or_market_price(ticker)
                    if not util.isNan(price):
                        quantity = remaining_calls[idx]['position']
                        order = LimitOrder("SELL", quantity, price,
                                           algoStrategy="Adaptive",
                                           algoParams=[TagValue(tag='adaptivePriority', value='Normal')],
                                           tif="DAY")
                        call_contract = ticker.contract
                        self.wait_for_trade_submitted(self.ib.placeOrder(call_contract, order))
                        with open(f"logs/{curr_date}-trade.txt", "a") as f:
                            f.write(f'Sold {quantity} {call_contract.strike}C{call_contract.lastTradeDateOrContractMonth} ({remaining_calls[idx]["avg"]} average) for {price * 100} each, {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
                    else:
                        with open("logs/errors.txt", "a") as f:
                            f.write(f'Error selling call at {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
        if self._nope_value < self.config["nope"]["short_exit"]:
            held_puts = self.get_held_contracts(portfolio, 'P')
            existing_put_order_ids = self.get_existing_order_ids(trades, 'P', 'SELL')
            remaining_puts = list(filter(lambda c: c['contract'].conId not in existing_put_order_ids, held_puts))

            if len(remaining_puts) > 0:
                remaining_puts.sort(key=lambda c: c['contract'].conId)
                remaining_put_contracts = [c['contract'] for c in remaining_puts]
                qualified_contracts = self.ib.qualifyContracts(*remaining_put_contracts)
                tickers = self.ib.reqTickers(*qualified_contracts)
                tickers.sort(key=lambda t: t.contract.conId)
                for idx, ticker in enumerate(tickers):
                    price = midpoint_or_market_price(ticker)
                    if not util.isNan(price):
                        quantity = remaining_puts[idx]['position']
                        order = LimitOrder("SELL", quantity, price,
                                           algoStrategy="Adaptive",
                                           algoParams=[TagValue(tag='adaptivePriority', value='Normal')],
                                           tif="DAY")
                        put_contract = ticker.contract
                        self.wait_for_trade_submitted(self.ib.placeOrder(put_contract, order))
                        with open(f"logs/{curr_date}-trade.txt", "a") as f:
                            f.write(f'Sold {quantity} {put_contract.strike}P{put_contract.lastTradeDateOrContractMonth} ({remaining_puts[idx]["avg"]} average) for {price * 100} each, {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
                    else:
                        with open("logs/errors.txt", "a") as f:
                            f.write(f'Error selling put at {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
Пример #4
0
 def enter_positions(self):
     portfolio = self.get_portfolio()
     trades = self.get_trades()
     curr_date, curr_dt = get_datetime_for_logging()
     if self._nope_value < self.config["nope"]["long_enter"]:
         held_calls = self.get_total_position(portfolio, 'C')
         existing_order_quantity = self.get_total_buys(trades, 'C')
         total_buys = held_calls + existing_order_quantity
         if total_buys < self.config["nope"]["call_limit"]:
             contracts = self.find_eligible_contracts(self.SYMBOL, 'C')
             # TODO: Implement contract selection from eligible candidiates
             contract_to_buy = contracts[self.config["nope"]["call_strike_offset"]]
             qualified_contracts = self.ib.qualifyContracts(contract_to_buy)
             tickers = self.ib.reqTickers(*qualified_contracts)
             if len(tickers) > 0:
                 price = midpoint_or_market_price(tickers[0])
                 call_contract = qualified_contracts[0]
                 if not util.isNan(price):
                     quantity = self.config["nope"]["call_quantity"]
                     order = LimitOrder('BUY', quantity, price,
                                        algoStrategy="Adaptive",
                                        algoParams=[TagValue(tag='adaptivePriority', value='Normal')],
                                        tif="DAY")
                     self.wait_for_trade_submitted(self.ib.placeOrder(call_contract, order))
                     with open(f"logs/{curr_date}-trade.txt", "a") as f:
                         f.write(f'Bought {quantity} {call_contract.strike}C{call_contract.lastTradeDateOrContractMonth} for {price * 100} each, {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
                 else:
                     with open("logs/errors.txt", "a") as f:
                         f.write(f'Error buying call at {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
     elif self._nope_value > self.config["nope"]["short_enter"]:
         held_puts = self.get_total_position(portfolio, 'P')
         existing_order_quantity = self.get_total_buys(trades, 'P')
         total_buys = held_puts + existing_order_quantity
         if total_buys < self.config["nope"]["put_limit"]:
             contracts = self.find_eligible_contracts(self.SYMBOL, 'P')
             # TODO: Implement contract selection from eligible candidates
             contract_to_buy = contracts[-self.config["nope"]["put_strike_offset"] - 1]
             qualified_contracts = self.ib.qualifyContracts(contract_to_buy)
             tickers = self.ib.reqTickers(*qualified_contracts)
             if len(tickers) > 0:
                 price = midpoint_or_market_price(tickers[0])
                 put_contract = qualified_contracts[0]
                 if not util.isNan(price):
                     quantity = self.config["nope"]["put_quantity"]
                     order = LimitOrder('BUY', quantity, price,
                                        algoStrategy="Adaptive",
                                        algoParams=[TagValue(tag='adaptivePriority', value='Normal')],
                                        tif="DAY")
                     self.wait_for_trade_submitted(self.ib.placeOrder(put_contract, order))
                     with open(f"logs/{curr_date}-trade.txt", "a") as f:
                         f.write(f'Bought {quantity} {put_contract.strike}P{put_contract.lastTradeDateOrContractMonth} for {price * 100} each, {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
                 else:
                     with open("logs/errors.txt", "a") as f:
                         f.write(f'Error buying put at {self._nope_value} | {self._underlying_price} | {curr_dt}\n')
Пример #5
0
 def console_log(self, s):
     if self.config["debug"]["verbose"]:
         _, curr_dt = get_datetime_for_logging()
         print(
             s,
             f"| {self._nope_value} | {self._underlying_price} | {curr_dt}")