Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V20 Friendly #59

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions data/streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,15 @@ def invert_prices(self, pair, bid, ask):
def connect_to_stream(self):
pairs_oanda = ["%s_%s" % (p[:3], p[3:]) for p in self.pairs]
pair_list = ",".join(pairs_oanda)

print(pair_list)
print(self.account_id)
print(self.access_token)

try:
requests.packages.urllib3.disable_warnings()
s = requests.Session()
url = "https://" + self.domain + "/v1/prices"
url = "https://" + self.domain + "/v3/accounts/" + self.account_id +'/pricing/stream'
headers = {'Authorization' : 'Bearer ' + self.access_token}
params = {'instruments' : pair_list, 'accountId' : self.account_id}
req = requests.Request('GET', url, headers=headers, params=params)
Expand All @@ -70,15 +75,15 @@ def stream_to_queue(self):
"Caught exception when converting message into json: %s" % str(e)
)
return
if "instrument" in msg or "tick" in msg:
self.logger.debug(msg)
if "instrument" in msg:
#self.logger.debug(msg)
getcontext().rounding = ROUND_HALF_DOWN
instrument = msg["tick"]["instrument"].replace("_", "")
time = msg["tick"]["time"]
bid = Decimal(str(msg["tick"]["bid"])).quantize(
instrument = msg["instrument"].replace("_", "")
time = msg["time"]
bid = Decimal(str(msg["bids"][1]["price"])).quantize(
Decimal("0.00001")
)
ask = Decimal(str(msg["tick"]["ask"])).quantize(
ask = Decimal(str(msg["asks"][1]["price"])).quantize(
Decimal("0.00001")
)
self.prices[instrument]["bid"] = bid
Expand Down
63 changes: 40 additions & 23 deletions execution/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
except ImportError:
import http.client as httplib
import logging
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
import urllib3
urllib3.disable_warnings()
from oandapyV20.contrib.requests import MarketOrderRequest
import oandapyV20.endpoints.orders as orders
import oandapyV20
import json



class ExecutionHandler(object):
Expand Down Expand Up @@ -55,21 +54,39 @@ def obtain_connection(self):

def execute_order(self, event):
instrument = "%s_%s" % (event.instrument[:3], event.instrument[3:])
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + self.access_token
}
params = urlencode({
"instrument" : instrument,
"units" : event.units,
"type" : event.order_type,
"side" : event.side
})
self.conn.request(
"POST",
"/v1/accounts/%s/orders" % str(self.account_id),
params, headers
)
response = self.conn.getresponse().read().decode("utf-8").replace("\n","").replace("\t","")
self.logger.debug(response)
if event.order_type == 'market':
if event.side == 'buy':
mktOrder = MarketOrderRequest(
instrument=instrument,
units= event.units,
#type= event.order_type,
#side= event.side
)
if event.side == 'sell':
mktOrder = MarketOrderRequest(
instrument=instrument,
units= (event.units*-1),
#type= event.order_type,
#side= event.side
)
else:
Print('Order Type Not Supported ' + self.order_type)
return

accountID = self.account_id
access_token = self.access_token

api = oandapyV20.API(access_token=access_token)

r = orders.OrderCreate(accountID, data=mktOrder.data)
try:
#Try and execute order
rv = api.request(r)
except oandapyV20.exceptions.V20Error as err:
print(r.status_code, err)
else:
print(json.dumps(rv, indent=2))

#response = self.conn.getresponse().read().decode("utf-8").replace("\n","").replace("\t","")
self.logger.debug(json.dumps(rv, indent=2))

6 changes: 3 additions & 3 deletions settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
DOMAIN = "practice"
STREAM_DOMAIN = ENVIRONMENTS["streaming"][DOMAIN]
API_DOMAIN = ENVIRONMENTS["api"][DOMAIN]
ACCESS_TOKEN = os.environ.get('OANDA_API_ACCESS_TOKEN', None)
ACCOUNT_ID = os.environ.get('OANDA_API_ACCOUNT_ID', None)
ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', None)
ACCOUNT_ID = os.environ.get('ACCOUNT_ID', None)

BASE_CURRENCY = "GBP"
BASE_CURRENCY = "USD"
EQUITY = Decimal("100000.00")
2 changes: 1 addition & 1 deletion trading/trading.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def trade(events, strategy, portfolio, execution, heartbeat):
equity = settings.EQUITY

# Pairs to include in streaming data set
pairs = ["EURUSD", "GBPUSD"]
pairs = ["GBPUSD"]

# Create the OANDA market price streaming class
# making sure to provide authentication commands
Expand Down