API client initialization, authentication, and error handling.
class API:
"""Main client for OANDA REST-V20."""
def __init__(
self,
access_token: str,
environment: str = "practice", # "practice" | "live"
headers: dict = None,
request_params: dict = None
): ...
def request(self, endpoint) -> dict:
"""Execute API request. Raises V20Error on failure."""
def close(self):
"""Close session."""
def __enter__(self): ...
def __exit__(self, exc_type, exc_val, exc_tb): ...from oandapyV20 import API
# Basic
api = API(access_token="token", environment="practice")
response = api.request(endpoint)
api.close()
# Context manager (auto-close)
with API(access_token="token") as api:
response = api.request(endpoint)
# Custom headers
api = API(
access_token="token",
headers={"User-Agent": "MyApp/1.0"}
)class V20Error(Exception):
"""API error (HTTP status >= 400)."""
code: int # HTTP status code
msg: str # Error message
class StreamTerminated(Exception):
"""Stream manually terminated."""from oandapyV20.exceptions import V20Error, StreamTerminated
try:
response = api.request(endpoint)
except V20Error as e:
print(f"API Error {e.code}: {e.msg}")
# Streaming
stream = PricingStream(accountID=account_id, params={"instruments": "EUR_USD"})
try:
for update in api.request(stream):
if condition:
stream.terminate("reason")
except StreamTerminated:
print("Stream stopped")TRADING_ENVIRONMENTS = {
"practice": {
"stream": "https://stream-fxpractice.oanda.com",
"api": "https://api-fxpractice.oanda.com"
},
"live": {
"stream": "https://stream-fxtrade.oanda.com",
"api": "https://api-fxtrade.oanda.com"
}
}