Skip to content Skip to sidebar Skip to footer

How Do I Convert A Vb Delegate Into A Python Event Handler?

I have to rewrite the following VB code that is subscribing to a delegate (event), into python, using python.net. Imports MtApi Public Class Form1 Private apiClient As MtApiCl

Solution 1:

As closely related to this answer in a similar question, the issue was in over-complicating the delegate code. We simply don't need the OnTick class and also realizing that the QuoteUpdatedHandler() need 4 arguments, so we replace the printTick(...) with that.

(Of course if you do want to make somethng a little more complicated or elegant, you do want to create this in a class.)

Then the equivalent Python code to for the VB delegate, become:

...
defQuoteUpdatedHandler(source, sym, bid, ask) :
    qstr = '{}: {:.5f} {:.5f}'.format(sym,bid,ask)
    print(qstr)

...
mtc = mt.MtApiClient()

print('Connecting...')
res = mtc.BeginConnect('127.0.0.1', 8222);

# VB: AddHandler mtc.QuoteUpdated, AddressOf QuoteUpdatedHandler# Because we want the "AddressOf" of the function, we don't use the invoking "()"
mtc.QuoteUpdated += QuoteUpdatedHandler

print('ok')

# Now run in a loop and wait for the events:while1:
    passtry: 
        time.sleep(0.1)
    except KeyboardInterrupt:
        print('\n  Break!')
        breakif (mtc.IsConnected()) :
    mtc.PlaySound("tick")
    mtc.BeginDisconnect()
print('\n  Done!')

sys.exit(2)

Post a Comment for "How Do I Convert A Vb Delegate Into A Python Event Handler?"