@staticmethod
def generate(filename):

    def update_response(d: ApiDefinition, m: Callable):
        if GeneratorUtils.response_is_list(d):
            return f'''
            if {request_id(d, m)} in self._req_state:
                req_state = {current_request_state(d, m)}
                if req_state.response is None:
                    req_state.response = []
                req_state.response.append({response_instance(d, m)})'''
        else:
            return f'''
            if {request_id(d, m)} in self._req_state:
                req_state = {current_request_state(d, m)}
                if req_state is not None:
                    req_state.response = {response_instance(d, m)}'''

    def call_response_cb(d: ApiDefinition, m: Callable):
        if (d.callback_methods is not None):
            return f'self.call_response_cb({request_id(d, m)})'
        else:
            return ''

    def call_response_cb_if_done(d: ApiDefinition, m: Callable):
        if d.has_done_flag:
            return f'''
        if (done):
            {call_response_cb(d, m)}'''
        elif (not GeneratorUtils.response_is_list(d)):
            return f'''
        {call_response_cb(d, m)}'''
        else:
            return ''

    def callback_method(d: ApiDefinition, m: Callable):
        if (d.subscription_flag_name is not None):
            return f'''

    def {GeneratorUtils.method_declaration(m)}:
        {GeneratorUtils.doc_string(m)}
        is_subscription: bool = False
        with self._lock:
            is_subscription = {request_id(d, m)} in self._subscriptions
            {update_response(d, m)}
        if is_subscription:
            self.call_streaming_cb({request_id(d, m)}, {streaming_instance(d, m)})
            return
        {call_response_cb_if_done(d, m)}'''
        elif (not d.is_subscription):
            return f'''
    def {GeneratorUtils.method_declaration(m)}:
        {GeneratorUtils.doc_string(m)}
        with self._lock:
            {update_response(d, m)}
        {call_response_cb_if_done(d, m)}'''
        else:
            return f'''

    def {GeneratorUtils.method_declaration(m)}:
        {GeneratorUtils.doc_string(m)}
        self.call_streaming_cb({request_id(d, m)}, {streaming_instance(d, m)})'''

    def done_method(d: ApiDefinition):
        return f'''

    def {GeneratorUtils.method_declaration(d.done_method)}:
        {GeneratorUtils.doc_string(d.done_method)}
        {call_response_cb(d, d.done_method)}'''
    with open(filename, 'w') as f:
        f.write(f'''
from ibapi.wrapper import EWrapper
from ib_tws_server.asyncio.ib_writer import IBWriter
from ib_tws_server.asyncio.request_state import *
from ib_tws_server.asyncio.subscription_generator import SubscriptionGenerator
from ib_tws_server.error import *
from ib_tws_server.gen.client_responses import *
from ib_tws_server.ib_imports import *
from threading import Lock
from typing import Dict, List

class AsyncioWrapper(EWrapper):
    _lock: Lock
    _req_state: Dict[str, RequestState]
    _subscriptions: Dict[int, SubscriptionGenerator]
    _expecting_disconnect: bool
    _writer: IBWriter

    def __init__(self, lock: Lock, req_state: Dict[str, RequestState], subscriptions: Dict[int, SubscriptionGenerator]):
        self._lock = lock
        self._req_state = req_state
        self._subscriptions = subscriptions
        EWrapper.__init__(self)
        self._expecting_disconnect = False

    def connectionClosed(self):
        if self._expecting_disconnect:
            # Wake up writer
            self._writer.queue.put(lambda *a, **k: None)
        else:
            raise ConnectionError("Unexpected disconnect")

    def call_response_cb(self, id: RequestId, res=None):
        cb = None
        with self._lock:
            if not id in self._req_state:
                return

            s = self._req_state[id]
            cb = s.cb
            if res is None:
                res = s.response
            del self._req_state[id]

        if cb is not None:
            cb(res)

    def error(self, reqId: int, errorCode: int, errorString: str):
        cb = None
        if reqId is not None:
            with self._lock:
                if reqId in self._req_state:
                    s = self._req_state[reqId]
                    cb = s.cb
                    del self._req_state[reqId]
        if cb is not None:
            cb(IbError(errorString, errorCode))
        else:
            super().error(reqId, errorCode, errorString)
        
    def call_streaming_cb(self, id: RequestId, res: any):
        cb = None
        loop = None
        with self._lock:
            if id in self._subscriptions:
                s = self._subscriptions[id]
                cb = s.add_to_queue
                loop = s._loop
        if loop is not None:
            loop.call_soon_threadsafe(cb, res)
''')
        for d in REQUEST_DEFINITIONS:
            if (d.request_method is not None):
                if (d.callback_methods is not None):
                    for m in d.callback_methods:
                        f.write(callback_method(d, m))
                    if (d.done_method is not None):
                        f.write(done_method(d))
@staticmethod
def generate(filename):

    def update_response(d: ApiDefinition, m: Callable):
        if GeneratorUtils.response_is_list(d):
            return f'
            if {request_id(d, m)} in self._req_state:
                req_state = {current_request_state(d, m)}
                if req_state.response is None:
                    req_state.response = []
                req_state.response.append({response_instance(d, m)})'
        else:
            return f'
            if {request_id(d, m)} in self._req_state:
                req_state = {current_request_state(d, m)}
                if req_state is not None:
                    req_state.response = {response_instance(d, m)}'

    def call_response_cb(d: ApiDefinition, m: Callable):
        if (d.callback_methods is not None):
            return f'self.call_response_cb({request_id(d, m)})'
        else:
            return 

    def call_response_cb_if_done(d: ApiDefinition, m: Callable):
        if d.has_done_flag:
            return f'
        if (done):
            {call_response_cb(d, m)}'
        elif (not GeneratorUtils.response_is_list(d)):
            return f'
        {call_response_cb(d, m)}'
        else:
            return 

    def callback_method(d: ApiDefinition, m: Callable):
        if (d.subscription_flag_name is not None):
            return f'

    def {GeneratorUtils.method_declaration(m)}:
        {GeneratorUtils.doc_string(m)}
        is_subscription: bool = False
        with self._lock:
            is_subscription = {request_id(d, m)} in self._subscriptions
            {update_response(d, m)}
        if is_subscription:
            self.call_streaming_cb({request_id(d, m)}, {streaming_instance(d, m)})
            return
        {call_response_cb_if_done(d, m)}'
        elif (not d.is_subscription):
            return f'
    def {GeneratorUtils.method_declaration(m)}:
        {GeneratorUtils.doc_string(m)}
        with self._lock:
            {update_response(d, m)}
        {call_response_cb_if_done(d, m)}'
        else:
            return f'

    def {GeneratorUtils.method_declaration(m)}:
        {GeneratorUtils.doc_string(m)}
        self.call_streaming_cb({request_id(d, m)}, {streaming_instance(d, m)})'

    def done_method(d: ApiDefinition):
        return f'

    def {GeneratorUtils.method_declaration(d.done_method)}:
        {GeneratorUtils.doc_string(d.done_method)}
        {call_response_cb(d, d.done_method)}'
    with open(filename, 'w') as f:
        f.write(f'
from ibapi.wrapper import EWrapper
from ib_tws_server.asyncio.ib_writer import IBWriter
from ib_tws_server.asyncio.request_state import *
from ib_tws_server.asyncio.subscription_generator import SubscriptionGenerator
from ib_tws_server.error import *
from ib_tws_server.gen.client_responses import *
from ib_tws_server.ib_imports import *
from threading import Lock
from typing import Dict, List

class AsyncioWrapper(EWrapper):
    _lock: Lock
    _req_state: Dict[str, RequestState]
    _subscriptions: Dict[int, SubscriptionGenerator]
    _expecting_disconnect: bool
    _writer: IBWriter

    def __init__(self, lock: Lock, req_state: Dict[str, RequestState], subscriptions: Dict[int, SubscriptionGenerator]):
        self._lock = lock
        self._req_state = req_state
        self._subscriptions = subscriptions
        EWrapper.__init__(self)
        self._expecting_disconnect = False

    def connectionClosed(self):
        if self._expecting_disconnect:
            # Wake up writer
            self._writer.queue.put(lambda *a, **k: None)
        else:
            raise ConnectionError("Unexpected disconnect")

    def call_response_cb(self, id: RequestId, res=None):
        cb = None
        with self._lock:
            if not id in self._req_state:
                return

            s = self._req_state[id]
            cb = s.cb
            if res is None:
                res = s.response
            del self._req_state[id]

        if cb is not None:
            cb(res)

    def error(self, reqId: int, errorCode: int, errorString: str):
        cb = None
        if reqId is not None:
            with self._lock:
                if reqId in self._req_state:
                    s = self._req_state[reqId]
                    cb = s.cb
                    del self._req_state[reqId]
        if cb is not None:
            cb(IbError(errorString, errorCode))
        else:
            super().error(reqId, errorCode, errorString)
        
    def call_streaming_cb(self, id: RequestId, res: any):
        cb = None
        loop = None
        with self._lock:
            if id in self._subscriptions:
                s = self._subscriptions[id]
                cb = s.add_to_queue
                loop = s._loop
        if loop is not None:
            loop.call_soon_threadsafe(cb, res)
')
        for d in REQUEST_DEFINITIONS:
            if (d.request_method is not None):
                if (d.callback_methods is not None):
                    for m in d.callback_methods:
                        f.write(callback_method(d, m))
                    if (d.done_method is not None):
                        f.write(done_method(d))