def create_driver(self): if self.driver: raise Exception("Driver is already created.") else: # from selenium import webdriver # from selenium.webdriver import DesiredCapabilities logger.info("create driver.") connector = "" chrome_option = webdriver.ChromeOptions() # chrome_option.add_argument("--blink-settings=imagesEnabled=false") is_debug = bool(os.environ.get("IS_SELENIUM_DEBUG", False)) is_debug = True if is_debug: connector = "http://localhost:4444/wd/hub" else: connector = "http://selenium:4444/wd/hub" driver = webdriver.Remote( command_executor=connector, desired_capabilities=DesiredCapabilities.CHROME.copy(), options=chrome_option, keep_alive=True, ) return driver
def calc_loss(self, ask_or_bid, price): if not isinstance(price, decimal.Decimal): # TODO: priceをdecimal型にしておく logger.info("calc_limit: decimal型にしておけよ") price = decimal.Decimal(str(price)) if self.order_logic.ask_loss_rate is not None and ask_or_bid == "ask": return price * self.order_logic.ask_loss_rate elif self.order_logic.bid_loss_rate is not None and ask_or_bid == "bid": return 2 * price - (price * self.order_logic.bid_loss_rate) else: return None
async def notify(self, sign, close_time_or_every_second): if sign == "ask": pass elif sign == "bid": pass elif sign == "limit": logger.info(f"{close_time_or_every_second} detect limit.") elif sign == "loss": logger.info(f"{close_time_or_every_second} detect loss.") else: raise Exception()
def cleanup_driver(self): """ ブラウザタブを1つにし、ブランクページを開く。 これは、ブラウザ起動コスト削減するため、インスタンスを再利用するため。 """ driver = self.driver for handle in driver.window_handles: driver.switch_to.window(handle) if len(driver.window_handles) != 1: driver.close() driver.get("about:blank") logger.info("browser was cleaned up.")
async def exec(self, id: int): """ジョブを実行する。last_check_dateからさかのぼってエントリーを行う。Noneの場合は、本日分よりトレードを行う。""" tmp = await self.get(id=id) job = schemas.TradeJob.from_orm(tmp) import magnet.datastore.crud ohlc = magnet.datastore.crud.CryptoOhlcDaily(self.db) rep_result = crud.TradeResult(self.db) scheduler = [] def create_schedule(before, until): if before > until: raise Exception() diff = (until - before).days start_day = datetime.date.today() - datetime.timedelta(days=diff) for day_count in range(diff): yield start_day + datetime.timedelta(days=day_count) if job.job_type == "production": broker = brokers.instatiate(job.broker) broker.sleep_interval = 10 if job.last_check_date is None: scheduler = list(create_schedule(datetime.date.today(), datetime.date.today())) else: scheduler = list(create_schedule(job.last_check_date.date(), datetime.date.today())) elif job.job_type == "virtual": # 現在に対して仮想的にトレードを行う broker = brokers.instatiate(job.broker) broker.sleep_interval = 10 broker = broker # 仮想ブローカーにラップする if job.last_check_date is None: current_date = datetime.datetime.now().date() - datetime.timedelta(days=1) # 本日はすなわち昨日のクローズタイム - 1日 scheduler = [datetime.date.today()] raise NotImplementedError() elif job.job_type == "backtest": # 過去データに対してトレードを行う job = await self.reset_order_status(id=job.id) job = schemas.TradeJob.from_orm(job) rep_result.delete_by_job_name(job.name) broker = brokers.instatiate("backtest") broker.sleep_interval = 0 # 外部との通信はないので0 query = ohlc.select_close_date( provider=job.provider, market=job.market, product=job.product, periods=job.periods, until=datetime.date.today(), order_by="asc" ) scheduler = [datetime.datetime.combine(x.close_time, datetime.time()) for x in query][:-1] logger.info(f"{len(scheduler)}件のデータでバックテストを行います。") else: raise Exception() # broker.get_topic # broker.scheduler = scheduler # broker.trade_type = None broker.db = self.db broker.detect_signal = algorithms.detectors.get(job.detector_name) for dt in scheduler: # ジョブを更新しないと状態が更新されない # tmp = await self.get(id=id) # job = schemas.TradeJob.from_orm(tmp) job = await self.stop_and_reverse(job, broker, dt) return job
def output(self, input: schemas.CommonSchema): logger.info(input.detail) service.create(self.db, input)
def shutdown_event(): logger.info("shutdown fastapi app!!!!!!!")
async def startup_event(): logger.info("startup fastapi app!!!!!!!!")
app.include_router(magnet.ingester.views.router, prefix="/ingester") app.include_router(magnet.trader.views.router, prefix="/trader") app.include_router(magnet.develop.views.router, prefix="/develop") @app.on_event("startup") async def startup_event(): logger.info("startup fastapi app!!!!!!!!") @app.on_event("shutdown") def shutdown_event(): logger.info("shutdown fastapi app!!!!!!!") logger.info(f"[STARTUP EVENT]: {len(app.router.on_startup)}") for event in app.router.on_startup: logger.info(f"{event.__module__}.{event.__name__}") logger.info(f"[SHUTDOWN EVENT]: {len(app.router.on_shutdown)}") for event in app.router.on_shutdown: logger.info(f"{event.__module__}.{event.__name__}") def exec_pytest(): # ログイン時にscope=["me", "items"]を要求すると、最後の要素しか反映されない # pytestをpythonから起動するには?? # pytest.main(["--cov", "-s"]) # 対象のテストのみ実行するには? # pytest.main(["test_mod.py::test_func"]) # pytest.main(["test_mod.py::TestClass::test_func"])