from typing import List

from internal_types.types import Instrument, Position, SecurityType
from strategy.buy_and_hold import BuyAndHold
from strategy.strategy import Strategy
from strategy.turtle_system_1 import TurtleSystem1
from trading_gateway.trading_gateway import BacktestGateway, TradingGateway
from utils.utils import log_sharpe_ratio, simple_sharpe_ratio


def main():
  trading_gateway: TradingGateway = \
    BacktestGateway('./csv/qqq_2023_02_01_15_min.csv', '2024-01-01', '2025-01-01')
  instr = Instrument('QQQ', SecurityType.EQUITY, 1)
  initial_balance = 1_000_000
  # strategy: Strategy = BuyAndHold(initial_balance, instr)
  strategy: Strategy = TurtleSystem1(initial_balance, instr)
  balance_history: List[float] = []

  # todo: use asyncio to run multiple strategies concurrently
  for quote in trading_gateway.next_quote():
    balance = strategy.net_liquid_value(quote.close)
    balance_history.append(balance)

    if balance <= 0:
      break

    strategy.process_quote(quote)

    # todo: handle strategy that trades multiple symbols
    pos_diff = strategy.desired_position() - strategy.curr_position()

    if pos_diff:
      # todo: order should be filled async
      # trading_gateway.submit_order(pos_diff)
      strategy.order_filled(Position(instr, quantity=pos_diff, price=quote.close))

  interval_sec = 15 * 60  # 15 minutes
  print(round(simple_sharpe_ratio(balance_history, interval_sec), 4))
  print(round(log_sharpe_ratio(balance_history, interval_sec), 4))
  print(round(balance_history[-1] / initial_balance - 1, 4) * 100, '%')


if __name__ == '__main__':
  # todo: asyncio
  main()
