How to hide/show Collections levels with python?
The operator that toggles the collection visibility in the outliner is bpy.ops.outliner.item_openclose(). Unfortunately it depends on the cursor position to determine the collection that should be toggled. While we could position the cursor with bpy.context.window.cursor_warp() the x and y coordinates of the collection in the UI remain unknown. It's therefore not realistically possible to perform this operation in a script or add-on.

I could get it to work with manually determined coordinates to position the cursor on the arrow icon in front of the collection.

import bpy


context = bpy.context.copy()

for area in bpy.context.screen.areas:
    if area.type == 'OUTLINER':
        for region in area.regions:
            if region.type == 'WINDOW':
                context['area'] = area
                context['region'] = region
                break
        break

# Places the cursor directly on the arrow icon for the first collection with
# my screen resolution and UI layout.
bpy.context.window.cursor_warp(2150,1250)
bpy.ops.outliner.item_openclose(context, 'INVOKE_DEFAULT')