# Path: quantrocket/houston.py
# CANNOT_CONNECT_TO_HOUSTON_ERROR_LOCAL = """{error}
# 
# Could not connect to houston at {scheme}://{netloc}
# 
# Please verify that houston is running and bound to port {port} by checking the output of:
# 
#     docker ps
# 
# The output should resemble:
# 
#     quantrocket/houston ... 0.0.0.0:{port}->80/tcp ... quantrocket_houston_1
#     ...
# 
# If not running you can deploy it with:
# 
#     docker-compose -p quantrocket up -d
# """
# CANNOT_CONNECT_TO_HOUSTON_ERROR_CLOUD = """{error}
# 
# Could not connect to houston at {scheme}://{netloc}
# 
# Please verify that the URL is correct and houston is running.
# """
#     DEFAULT_TIMEOUT = 120
# def _get_force_timeout():
#     def __init__(self):
#     def base_url(self):
#     def _set_base_url(self):
#     def request(self, method, url, *args, **kwargs):
#     def raise_for_status_with_json(response):
# def ping():
# def _cli_ping():
# class Houston(requests.Session):
# 
# Path: quantrocket/exceptions.py
# class NoAccountData(NoData):
#     pass
# 
# Path: quantrocket/cli/utils/output.py
# def json_to_cli(func, *args, **kwargs):
#     """
#     Converts a JSON response to a more appropriate CLI response.
# 
#     If JSON is preferred, the response will be returned as-is. Otherwise:
# 
#     - If the JSON is a list of scalars, the output will be simplified to a
#     string of newline-separated values suitable for the command line (unless
#     simplify_lists is False).
# 
#     - If the JSON is empty, nothing will be returned.
# 
#     - YAML will be returned.
#     """
#     exit_code = 0
#     simplify_list = kwargs.pop("simplify_list", True)
#     try:
#         json_response = func(*args, **kwargs)
#     except requests.exceptions.HTTPError as e:
#         # use json response from service, if available
#         json_response = getattr(e, "json_response", {}) or {"status": "error", "msg": repr(e)}
#         exit_code = 1
#     if not json_response:
#         return None, exit_code
#     if os.environ.get("QUANTROCKET_CLI_OUTPUT_FORMAT", "").lower() == "json":
#         return json.dumps(json_response), exit_code
#     if simplify_list and isinstance(json_response, list) and not any([
#         isinstance(item, (dict, list, tuple, set)) for item in json_response]):
#         return "\n".join([str(item) for item in json_response]), exit_code
#     return yaml.safe_dump(json_response, default_flow_style=False).strip(), exit_code
# 
# Path: quantrocket/cli/utils/files.py
# def write_response_to_filepath_or_buffer(filepath_or_buffer, response):
#     """
#     Writes the response content to the filepath or buffer.
#     """
#     if hasattr(filepath_or_buffer, "write"):
#         if six.PY3 and filepath_or_buffer is sys.stdout:
#             # Write bytes to stdout (https://stackoverflow.com/a/23932488)
#             filepath_or_buffer = filepath_or_buffer.buffer
#         mode = getattr(filepath_or_buffer, "mode", "w")
#         for chunk in response.iter_content(chunk_size=1024):
#             if chunk:
#                 if "b" not in mode and six.PY3:
#                     chunk = chunk.decode("utf-8")
#                 filepath_or_buffer.write(chunk)
#         if filepath_or_buffer.seekable():
#             filepath_or_buffer.seek(0)
#     else:
#         with open(filepath_or_buffer, "wb") as f:
#             for chunk in response.iter_content(chunk_size=1024):
#                 if chunk:
#                     f.write(chunk)
# 
# Path: quantrocket/cli/utils/parse.py
# def dict_strs_to_dict(*dict_strs):
#     """
#     Parses a list of key:value strings into a dict. Used to go from CLI->Python.
#     """
#     d = {}
#     for dict_str in dict_strs:
#         try:
#             k, v = dict_str.split(":", 1)
#         except ValueError:
#             raise ValueError("can't parse string '{0}': must have format 'key:value'".format(
#                 dict_str))
#         d[k] = v
#     return d
# 
# def dict_to_dict_strs(d):
#     """
#     Parses a dict to a list of key:value strings. Used to go from Python->HTTP.
#     """
#     return ["{0}:{1}".format(k,v) for k,v in d.items()]


import sys
import requests
from quantrocket.houston import houston
from quantrocket.exceptions import NoAccountData
from quantrocket.cli.utils.output import json_to_cli
from quantrocket.cli.utils.files import write_response_to_filepath_or_buffer
from quantrocket.cli.utils.parse import dict_strs_to_dict, dict_to_dict_strs
        params["sec_types"] = sec_types
    if exchanges:
        params["exchanges"] = exchanges
    if sids:
        params["sids"] = sids
    if symbols:
        params["symbols"] = symbols
    if include_zero:
        params["include_zero"] = include_zero
    if fields:
        params["fields"] = fields

    output = output or "csv"

    if output not in ("csv", "json"):
        raise ValueError("Invalid ouput: {0}".format(output))

    response = houston.get("/account/portfolio.{0}".format(output), params=params)

    houston.raise_for_status_with_json(response)

    # Don't write a null response to file
    if response.content[:4] == b"null":
        return

    filepath_or_buffer = filepath_or_buffer or sys.stdout

    write_response_to_filepath_or_buffer(filepath_or_buffer, response)

def _cli_download_account_portfolio(*args, **kwargs):

# Path: quantrocket/houston.py
# CANNOT_CONNECT_TO_HOUSTON_ERROR_LOCAL = """{error}
# 
# Could not connect to houston at {scheme}://{netloc}
# 
# Please verify that houston is running and bound to port {port} by checking the output of:
# 
#     docker ps
# 
# The output should resemble:
# 
#     quantrocket/houston ... 0.0.0.0:{port}->80/tcp ... quantrocket_houston_1
#     ...
# 
# If not running you can deploy it with:
# 
#     docker-compose -p quantrocket up -d
# """
# CANNOT_CONNECT_TO_HOUSTON_ERROR_CLOUD = """{error}
# 
# Could not connect to houston at {scheme}://{netloc}
# 
# Please verify that the URL is correct and houston is running.
# """
#     DEFAULT_TIMEOUT = 120
# def _get_force_timeout():
#     def __init__(self):
#     def base_url(self):
#     def _set_base_url(self):
#     def request(self, method, url, *args, **kwargs):
#     def raise_for_status_with_json(response):
# def ping():
# def _cli_ping():
# class Houston(requests.Session):
# 
# Path: quantrocket/exceptions.py
# class NoAccountData(NoData):
#     pass
# 
# Path: quantrocket/cli/utils/output.py
# def json_to_cli(func, *args, **kwargs):
#     """
#     Converts a JSON response to a more appropriate CLI response.
# 
#     If JSON is preferred, the response will be returned as-is. Otherwise:
# 
#     - If the JSON is a list of scalars, the output will be simplified to a
#     string of newline-separated values suitable for the command line (unless
#     simplify_lists is False).
# 
#     - If the JSON is empty, nothing will be returned.
# 
#     - YAML will be returned.
#     """
#     exit_code = 0
#     simplify_list = kwargs.pop("simplify_list", True)
#     try:
#         json_response = func(*args, **kwargs)
#     except requests.exceptions.HTTPError as e:
#         # use json response from service, if available
#         json_response = getattr(e, "json_response", {}) or {"status": "error", "msg": repr(e)}
#         exit_code = 1
#     if not json_response:
#         return None, exit_code
#     if os.environ.get("QUANTROCKET_CLI_OUTPUT_FORMAT", "").lower() == "json":
#         return json.dumps(json_response), exit_code
#     if simplify_list and isinstance(json_response, list) and not any([
#         isinstance(item, (dict, list, tuple, set)) for item in json_response]):
#         return "\n".join([str(item) for item in json_response]), exit_code
#     return yaml.safe_dump(json_response, default_flow_style=False).strip(), exit_code
# 
# Path: quantrocket/cli/utils/files.py
# def write_response_to_filepath_or_buffer(filepath_or_buffer, response):
#     """
#     Writes the response content to the filepath or buffer.
#     """
#     if hasattr(filepath_or_buffer, "write"):
#         if six.PY3 and filepath_or_buffer is sys.stdout:
#             # Write bytes to stdout (https://stackoverflow.com/a/23932488)
#             filepath_or_buffer = filepath_or_buffer.buffer
#         mode = getattr(filepath_or_buffer, "mode", "w")
#         for chunk in response.iter_content(chunk_size=1024):
#             if chunk:
#                 if "b" not in mode and six.PY3:
#                     chunk = chunk.decode("utf-8")
#                 filepath_or_buffer.write(chunk)
#         if filepath_or_buffer.seekable():
#             filepath_or_buffer.seek(0)
#     else:
#         with open(filepath_or_buffer, "wb") as f:
#             for chunk in response.iter_content(chunk_size=1024):
#                 if chunk:
#                     f.write(chunk)
# 
# Path: quantrocket/cli/utils/parse.py
# def dict_strs_to_dict(*dict_strs):
#     """
#     Parses a list of key:value strings into a dict. Used to go from CLI->Python.
#     """
#     d = {}
#     for dict_str in dict_strs:
#         try:
#             k, v = dict_str.split(":", 1)
#         except ValueError:
#             raise ValueError("can't parse string '{0}': must have format 'key:value'".format(
#                 dict_str))
#         d[k] = v
#     return d
# 
# def dict_to_dict_strs(d):
#     """
#     Parses a dict to a list of key:value strings. Used to go from Python->HTTP.
#     """
#     return ["{0}:{1}".format(k,v) for k,v in d.items()]


# Path: quantrocket/account.py
import sys
import requests
from quantrocket.houston import houston
from quantrocket.exceptions import NoAccountData
from quantrocket.cli.utils.output import json_to_cli
from quantrocket.cli.utils.files import write_response_to_filepath_or_buffer
from quantrocket.cli.utils.parse import dict_strs_to_dict, dict_to_dict_strs

        params["sec_types"] = sec_types
    if exchanges:
        params["exchanges"] = exchanges
    if sids:
        params["sids"] = sids
    if symbols:
        params["symbols"] = symbols
    if include_zero:
        params["include_zero"] = include_zero
    if fields:
        params["fields"] = fields

    output = output or "csv"

    if output not in ("csv", "json"):
        raise ValueError("Invalid ouput: {0}".format(output))

    response = houston.get("/account/portfolio.{0}".format(output), params=params)

    houston.raise_for_status_with_json(response)

    # Don't write a null response to file
    if response.content[:4] == b"null":
        return

    filepath_or_buffer = filepath_or_buffer or sys.stdout

    write_response_to_filepath_or_buffer(filepath_or_buffer, response)

def _cli_download_account_portfolio(*args, **kwargs):

    return json_to_cli(download_account_portfolio, *args, **kwargs)