Package: async_v20
async_v20: Asynchronous OANDA v20 clientA foreign exchange clientDocumentationhttp://async-v20.readthedocs.io/DisclaimerLosses can exceed investment.async_v20 and its creator has no affiliation with OANDA. And is not endorsed by OANDA in any manner.async_v20 is in Beta stage and has not been tested on a live OANDA accountUse at own riskFeaturesExposes the entire v20 APINo*args, **kwargsIn client methods. Therefore no need to guess what arguments a method takesSerialize objects directly intopandasSeriesorDataFrameobjectsConstructconcurrenttrading algorithmsinstallationREQUIRES:python >= 3.6https://www.python.org/$ pip install async_v20async_v20is built withaiohttp.
It is therefore recommended to also installcchardetandaiodnsas peraiohttpdocumentation$pipinstallcchardet$pipinstallaiodnsWhy async_v20?There are many OANDA clients for python already available so why create another?
The main driver for creating async_v20 was to facilitate better risk management,
by allowing user’s to concurrently monitor account status and trade currency’s.An unintended consequence of async_v20 is the ability to create clear segregation
between implementation ideas.A simple example might contain a coroutine for the following:Monitoring overall account statusWatching price stream and triggering buy/sell signalsMonitoring individual trades and closing movements against held positionsA synchronous implementation would require considerable effort to determine which
task communicates with the server next. async_v20 removes this burden by usingaiohttpFurther goals of async_v20 has been to lower the barrier of entry for algorithmic trading
by providing a complete and simple to use interface.Getting startedCreating an AccountTo useasync_v20you must have an account withOANDACreate an accounthttps://www.oanda.com/account/loginCreate an APItokenhttps://www.oanda.com/demo-account/tpa/personal_tokenSetting up environmentInstallasync_v20as perinstallationCreate a newenvironment variablewith the name ‘OANDA_TOKEN’ and value as thetokengenerated from aboveNote:It is considered best practice use avirtual environmentIt is not required to store the token in anenvironment variable. The token can be passed to OandaClientUsing async_v20Once an account has been created as percreate-accountand the environment is configured as persetting-up-environmentwe are ready to begin.Lets first take a look at this code example, then go though it line by line.importasynciofromasync_v20importOandaClientasyncdefget_account():asyncwithOandaClient()asclient:returnawaitclient.account()loop=asyncio.get_event_loop()account=loop.run_until_complete(get_account())# pandas Seriesprint(account.series())# HTTP response stateprint(account)# JSON data in python dictionary formatprint(account.dict())First we need to importasynciothis allows us to run ourcoroutineimportasyncioWe then importOandaClientwhich provides us the means to interact with OANDAfromasync_v20importOandaClientBecauseOandaClientreturnscoroutineswe useasync def. This allows the use of theawaitsyntaxasyncdefget_account():OandaClientis acontext manager, we useasync withto instantiate a
client instance. Doing so will automatically close thehttp sessionwhen we’re doneasyncwithOandaClient()asclient:We then create andrunthecoroutineby callingclient.account()returnawaitclient.account()Now we have defined ourcoroutinewe need to execute it.
To do so we need an event loop. Achieved usingasyncio.get_event_loop()loop=asyncio.get_event_loop()The value returned by executing theaccount()coroutineis accessed through the event loop.account=loop.run_until_complete(get_account())async_v20objects have aseries()method that returns apandas.Series.
By defaultasync_v20.DateTime’s will be converted intopandas.Timestamp’s.print(account.series())OutputsaliasPrimarybalance97801.9commission0created_by_user_id1234567created_time2017-08-1115:04:31.639182352+00:00currencyAUDfinancing-3.5596hedging_enabledFalseid123-123-1234567-123last_margin_call_extension_timeNonelast_transaction_id6360margin_available97801.9margin_call_enter_timeNonemargin_call_extension_countNonemargin_call_margin_used0margin_call_percent0margin_closeout_margin_used0margin_closeout_nav97801.9margin_closeout_percent0margin_closeout_position_value0margin_closeout_unrealized_pl0margin_rate0.02margin_used0nav97801.9open_position_count0open_trade_count0orders[]pending_order_count0pl-2194.53position_value0positions[]resettable_pl-2194.53resettabled_pl_timeNonetrades[]unrealized_pl0withdrawal_limit97801.9dtype:objectChangelog8.0.0b0 (01/01/2019)Added guaranteedStopLossOrderRestriction to Instrument definitionAdded unixTime attribute to orderBook definitionAdded tags attribute to Instrument definitionAdded guaranteed to StopLossOrder definitionReplaced ellipsis (…) with sentinel objectAdded fullVWAP to Transaction definitionUnknownValue Exception is now replaced with UnknownKeywordArgument Warning
in order to make the client more robust to breaking changes from OANDAChecked many class definitions against updated OANDA documentation7.0.1b0OandaClient.close is now a coroutine7.0.0b0All OrderRequests now require aninstrumentas there first parameter.
This is to allow correct rounding of decimal numbers to the instruments specification.guaranteed: boolhas been added to Transaction definition.Default SinceTransactionID value is now limited to the passed 900 transactions.OandaClient.account()method will useget_account_details()method when defaultSinceTransactionIDhas expired.OandaClient.get_pricingnow accepts anInstrumentNameforinstruments6.2.2b0guaranteed: boolhas been added to Order definition.6.2.1b0Array class lazy instantiates objectsModel objects with same attributes now compare equal (proving equal DateTime format)Improved repr of Array objectsImproved implementation ofget_instrument/s,get_idAll Array objects haveget_instrumentandget_instruments. Returns either the first or all matching objectsRemoved Model class_templateattribute as it was obsoleteAddedget(self, name, default=None)method to Model to allow for dict like key access.6.2.0b0Changedget_transactionsmethod toget_transaction(API call can only return one transaction)Removed default parameter argument forget_transaction.(transaction_id) it is a required parameter.Made OandaClient.hosts a protected member. Now OandaClient._hostsArray.get_instruments()returns an Array of the same type this is when there is a one to many relationship
between the instrument and objects the array contains.Array.get_instrument()Returns the single object
when there is a one to one relationship. Both methods are mutually exclusiveAll objects now lazy instantiate attribute instances.Large refactoring of async_v20.definitions.base6.1.0b0Changed incorrect naming _i_ds to _idsFixed OrderRequest formatting when a OrderRequest instance is passed that defines an instrument.6.0.2b0Fixed InvalidFormatRequest Error when OrderRequest does not define aninstrumentattribute6.0.1b0Fixed incorrect handling of stream response when endpoint returned status 4006.0.0b0Added health API and initialization checkFixed stream_transactions. Now returns correct typeChanged streaming responses keys. Where stream_pricing() returned ‘PRICE’ or ‘HEARTBEAT’
response now contains ‘price’ or ‘heartbeat’. Like wise stream_transactions() now returns
‘transaction’ or ‘heartbeat’. This has been done to standardise access to the transaction
stream response and ‘heartbeat’ objects. Due to the different types these objects may take.Added async_v20.exceptions moduleAdded logging to modules5.0.3b0Added default argument to Array.get_id & Array.get_instrumentRemoved default value from get_candles(count)5.0.2b0Fixed bug in rest implementation. Positions now update correctly5.0.1b0OandaClient.datetime_format is read onlyOandaClient._instruments is no longer a protected attribute. It is now OandaClient.instruments5.0.0b0DateTime’s create pandas.Timestamp’sModel.dict argumentdatetimeis nowdatetime_format. Argument behaviour now
specifies the representation of times. EitherRFC3339orUNIX. Correspondingjsonargument
changes the representation of UNIX times to either astrornumpy.int64Response.json() acceptsdatetime_formatargument string4.0.0b0Changed get_positions to get_position (as method can only close one position)_in_context accepts negative units3.0.0b0Array.get_instrument() works with ArrayInstrumentOandaClient.initialize() gets account instrumentsOandaClient hasformat_order_requestattributeasync_v20.definitions.primitives.Unit has been removedPriceValue and Decimal number has additional methodformat(precision, min_, max_)2.3.0b0Updated limit_replace_order() method to expose all argumentsTransactionID, TradeID & OrderID get stored as integers and cast to strings when creating JSON
representationsAdded documentation for order API methods2.2.5b2Fixed get_candles default value2.2.5b1RejectTransactions have no required argumentsAPI methods now apply default valuesAdded undocumented attributesPath class has been removed in favour of helper function. Allowing for more useful
error message on failure.2.2.5b0PriceComponent accepts all combinations of ‘M’ ‘A’ ‘B’2.2.4b3Added attributes to TradeSummary:margin_used2.2.4b1Added attributes to TradeReduce:guaranteed_execution_fee2.2.4b0Added attributes to Transaction:guaranteed_execution_feegain_quote_home_conversion_factorloss_quote_home_conversion_factorAdded attributes to TradeOpen:priceguaranteed_execution_fee2.2.3b0Added ‘margin_used’ to Position object.
(OANDA added new attribute, causing error)Added TimeoutError to stream2.2.2b0Added get_position_book and get_order_book API calls2.2.1b0series() method converts both UNIX and RFC3339 time’s to pandas.Timestamp ‘s2.2.0b0Initialization doesn’t freeze after failureOrder methods exposes all arguments2.1.0b0Beta release. At present time client is considered feature full
with 100% test coverage_fields attribute stored on instance not classRESTful account() method addedclose_all_trades() method addedAdded replace() method to ModelSimplified Endpoint decorator (No serial requests)Changes close_trades to close_trade (Method can only close one trade)Response parser checks HTTP status firstAdded tests2.0.1a0typeargument is set automatically for subclass that define itimplementation improvements2.0.0a0async_v20 objects are now immutable (greatly reducing complexity)Objects now have a reprremoved inflection as a dependencyHigher test coverage1.1.6a0Issue with object serialization not working with lists of Type[str, float, int]1.1.5a4Argument passing1.1.5a3Fix long description on PyPI1.1.5a0method signatures were offset buy 1 argument due to handling of
‘self’ parameter. Methods now displaying correct signature1.1.4a0Fixed incorrect annotation on:PUTPositionsInstrumentCloseGETPositionsInstrument1.1.3a0Fixed incorrect annotation on Interface methodsFixed argument passing bug caused by false’y evaluation1.1.2a5Added Travis CIAdded Codecov1.1.2a4Additional documentation1.1.2a1OandaClient.initialize() method is now exposedOandaClient is now also a context manager. To automatically close the http sessionAdditional documentation1.1.1a1Floating point numbers are rounded to the correct accuracy required for correct
serialization.1.1.0a1Model.series() returns data in more specific types instead of all ‘str’OandaClient methods now have correct signature instead of args, kwargs1.0.1a1Fixed code examples in bin directory