Modified the position handling to fix a pricing bug, so that locally handled Portfolio values match those of OANDA (up to slippage).
This commit is contained in:
+2
-1
@@ -38,12 +38,13 @@ class StreamingForexPrices(PriceHandler):
|
|||||||
|
|
||||||
def connect_to_stream(self):
|
def connect_to_stream(self):
|
||||||
pairs_oanda = ["%s_%s" % (p[:3], p[3:]) for p in self.pairs]
|
pairs_oanda = ["%s_%s" % (p[:3], p[3:]) for p in self.pairs]
|
||||||
|
pair_list = ",".join(pairs_oanda)
|
||||||
try:
|
try:
|
||||||
requests.packages.urllib3.disable_warnings()
|
requests.packages.urllib3.disable_warnings()
|
||||||
s = requests.Session()
|
s = requests.Session()
|
||||||
url = "https://" + self.domain + "/v1/prices"
|
url = "https://" + self.domain + "/v1/prices"
|
||||||
headers = {'Authorization' : 'Bearer ' + self.access_token}
|
headers = {'Authorization' : 'Bearer ' + self.access_token}
|
||||||
params = {'instruments' : pairs_oanda, 'accountId' : self.account_id}
|
params = {'instruments' : pair_list, 'accountId' : self.account_id}
|
||||||
req = requests.Request('GET', url, headers=headers, params=params)
|
req = requests.Request('GET', url, headers=headers, params=params)
|
||||||
pre = req.prepare()
|
pre = req.prepare()
|
||||||
resp = s.send(pre, stream=True, verify=False)
|
resp = s.send(pre, stream=True, verify=False)
|
||||||
|
|||||||
+56
-42
@@ -127,50 +127,64 @@ class Portfolio(object):
|
|||||||
self.backtest_file.write(out_line)
|
self.backtest_file.write(out_line)
|
||||||
|
|
||||||
def execute_signal(self, signal_event):
|
def execute_signal(self, signal_event):
|
||||||
side = signal_event.side
|
# Check that the prices ticker contains all necessary
|
||||||
currency_pair = signal_event.instrument
|
# currency pairs prior to executing an order
|
||||||
units = int(self.trade_units)
|
execute = True
|
||||||
time = signal_event.time
|
tp = self.ticker.prices
|
||||||
|
for pair in tp:
|
||||||
|
if tp[pair]["ask"] is None or tp[pair]["bid"] is None:
|
||||||
|
execute = False
|
||||||
|
|
||||||
# If there is no position, create one
|
# All necessary pricing data is available,
|
||||||
if currency_pair not in self.positions:
|
# we can execute
|
||||||
if side == "buy":
|
if execute:
|
||||||
position_type = "long"
|
side = signal_event.side
|
||||||
|
currency_pair = signal_event.instrument
|
||||||
|
units = int(self.trade_units)
|
||||||
|
time = signal_event.time
|
||||||
|
|
||||||
|
# If there is no position, create one
|
||||||
|
if currency_pair not in self.positions:
|
||||||
|
if side == "buy":
|
||||||
|
position_type = "long"
|
||||||
|
else:
|
||||||
|
position_type = "short"
|
||||||
|
self.add_new_position(
|
||||||
|
position_type, currency_pair,
|
||||||
|
units, self.ticker
|
||||||
|
)
|
||||||
|
|
||||||
|
# If a position exists add or remove units
|
||||||
else:
|
else:
|
||||||
position_type = "short"
|
ps = self.positions[currency_pair]
|
||||||
self.add_new_position(
|
|
||||||
position_type, currency_pair,
|
|
||||||
units, self.ticker
|
|
||||||
)
|
|
||||||
|
|
||||||
# If a position exists add or remove units
|
if side == "buy" and ps.position_type == "long":
|
||||||
|
add_position_units(currency_pair, units)
|
||||||
|
|
||||||
|
elif side == "sell" and ps.position_type == "long":
|
||||||
|
if units == ps.units:
|
||||||
|
self.close_position(currency_pair)
|
||||||
|
# TODO: Allow units to be added/removed
|
||||||
|
elif units < ps.units:
|
||||||
|
return
|
||||||
|
elif units > ps.units:
|
||||||
|
return
|
||||||
|
|
||||||
|
elif side == "buy" and ps.position_type == "short":
|
||||||
|
if units == ps.units:
|
||||||
|
self.close_position(currency_pair)
|
||||||
|
# TODO: Allow units to be added/removed
|
||||||
|
elif units < ps.units:
|
||||||
|
return
|
||||||
|
elif units > ps.units:
|
||||||
|
return
|
||||||
|
|
||||||
|
elif side == "sell" and ps.position_type == "short":
|
||||||
|
add_position_units(currency_pair, units)
|
||||||
|
|
||||||
|
order = OrderEvent(currency_pair, units, "market", side)
|
||||||
|
self.events.put(order)
|
||||||
|
print("Balance: ", self.balance)
|
||||||
else:
|
else:
|
||||||
ps = self.positions[currency_pair]
|
print("Unable to execute order as price data was insufficient.")
|
||||||
|
|
||||||
if side == "buy" and ps.position_type == "long":
|
|
||||||
add_position_units(currency_pair, units)
|
|
||||||
|
|
||||||
elif side == "sell" and ps.position_type == "long":
|
|
||||||
if units == ps.units:
|
|
||||||
self.close_position(currency_pair)
|
|
||||||
# TODO: Allow units to be added/removed
|
|
||||||
elif units < ps.units:
|
|
||||||
return
|
|
||||||
elif units > ps.units:
|
|
||||||
return
|
|
||||||
|
|
||||||
elif side == "buy" and ps.position_type == "short":
|
|
||||||
if units == ps.units:
|
|
||||||
self.close_position(currency_pair)
|
|
||||||
# TODO: Allow units to be added/removed
|
|
||||||
elif units < ps.units:
|
|
||||||
return
|
|
||||||
elif units > ps.units:
|
|
||||||
return
|
|
||||||
|
|
||||||
elif side == "sell" and ps.position_type == "short":
|
|
||||||
add_position_units(currency_pair, units)
|
|
||||||
|
|
||||||
order = OrderEvent(currency_pair, units, "market", side)
|
|
||||||
self.events.put(order)
|
|
||||||
|
|
||||||
@@ -212,7 +212,7 @@ class TestPortfolio(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertTrue(rpu)
|
self.assertTrue(rpu)
|
||||||
self.assertEqual(ps.units, Decimal("7000"))
|
self.assertEqual(ps.units, Decimal("7000"))
|
||||||
self.assertEqual(self.port.balance, Decimal("99988.84"))
|
self.assertEqual(self.port.balance, Decimal("99988.83"))
|
||||||
|
|
||||||
def test_close_position_long(self):
|
def test_close_position_long(self):
|
||||||
position_type = "long"
|
position_type = "long"
|
||||||
@@ -265,7 +265,7 @@ class TestPortfolio(unittest.TestCase):
|
|||||||
cp = self.port.close_position(currency_pair)
|
cp = self.port.close_position(currency_pair)
|
||||||
self.assertTrue(cp)
|
self.assertTrue(cp)
|
||||||
self.assertRaises(ps) # Key doesn't exist
|
self.assertRaises(ps) # Key doesn't exist
|
||||||
self.assertEqual(self.port.balance, Decimal("100026.64"))
|
self.assertEqual(self.port.balance, Decimal("100026.63"))
|
||||||
|
|
||||||
def test_close_position_short(self):
|
def test_close_position_short(self):
|
||||||
position_type = "short"
|
position_type = "short"
|
||||||
@@ -312,13 +312,13 @@ class TestPortfolio(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertTrue(rpu)
|
self.assertTrue(rpu)
|
||||||
self.assertEqual(ps.units, Decimal("7000"))
|
self.assertEqual(ps.units, Decimal("7000"))
|
||||||
self.assertEqual(self.port.balance, Decimal("99988.84"))
|
self.assertEqual(self.port.balance, Decimal("99988.83"))
|
||||||
|
|
||||||
# Close the position
|
# Close the position
|
||||||
cp = self.port.close_position(currency_pair)
|
cp = self.port.close_position(currency_pair)
|
||||||
self.assertTrue(cp)
|
self.assertTrue(cp)
|
||||||
self.assertRaises(ps) # Key doesn't exist
|
self.assertRaises(ps) # Key doesn't exist
|
||||||
self.assertEqual(self.port.balance, Decimal("99962.80"))
|
self.assertEqual(self.port.balance, Decimal("99962.77"))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -83,11 +83,11 @@ class Position(object):
|
|||||||
ticker_cp = self.ticker.prices[self.currency_pair]
|
ticker_cp = self.ticker.prices[self.currency_pair]
|
||||||
ticker_qh = self.ticker.prices[self.quote_home_currency_pair]
|
ticker_qh = self.ticker.prices[self.quote_home_currency_pair]
|
||||||
if self.position_type == "long":
|
if self.position_type == "long":
|
||||||
remove_price = ticker_cp["ask"]
|
|
||||||
qh_close = ticker_qh["bid"]
|
|
||||||
else:
|
|
||||||
remove_price = ticker_cp["bid"]
|
remove_price = ticker_cp["bid"]
|
||||||
qh_close = ticker_qh["ask"]
|
qh_close = ticker_qh["ask"]
|
||||||
|
else:
|
||||||
|
remove_price = ticker_cp["ask"]
|
||||||
|
qh_close = ticker_qh["bid"]
|
||||||
self.units -= dec_units
|
self.units -= dec_units
|
||||||
self.update_position_price()
|
self.update_position_price()
|
||||||
# Calculate PnL
|
# Calculate PnL
|
||||||
@@ -99,11 +99,9 @@ class Position(object):
|
|||||||
ticker_cp = self.ticker.prices[self.currency_pair]
|
ticker_cp = self.ticker.prices[self.currency_pair]
|
||||||
ticker_qh = self.ticker.prices[self.quote_home_currency_pair]
|
ticker_qh = self.ticker.prices[self.quote_home_currency_pair]
|
||||||
if self.position_type == "long":
|
if self.position_type == "long":
|
||||||
remove_price = ticker_cp["ask"]
|
|
||||||
qh_close = ticker_qh["bid"]
|
|
||||||
else:
|
|
||||||
remove_price = ticker_cp["bid"]
|
|
||||||
qh_close = ticker_qh["ask"]
|
qh_close = ticker_qh["ask"]
|
||||||
|
else:
|
||||||
|
qh_close = ticker_qh["bid"]
|
||||||
self.update_position_price()
|
self.update_position_price()
|
||||||
# Calculate PnL
|
# Calculate PnL
|
||||||
pnl = self.calculate_pips() * qh_close * self.units
|
pnl = self.calculate_pips() * qh_close * self.units
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ class TestStrategy(object):
|
|||||||
self.invested = False
|
self.invested = False
|
||||||
|
|
||||||
def calculate_signals(self, event):
|
def calculate_signals(self, event):
|
||||||
if event.type == 'TICK':
|
if event.type == 'TICK' and event.instrument == self.pairs[0]:
|
||||||
if self.ticks % 5 == 0:
|
if self.ticks % 5 == 0:
|
||||||
if self.invested == False:
|
if self.invested == False:
|
||||||
signal = SignalEvent(self.pairs[0], "market", "buy", event.time)
|
signal = SignalEvent(self.pairs[0], "market", "buy", event.time)
|
||||||
|
|||||||
+2
-2
@@ -47,8 +47,8 @@ if __name__ == "__main__":
|
|||||||
events = queue.Queue()
|
events = queue.Queue()
|
||||||
equity = settings.EQUITY
|
equity = settings.EQUITY
|
||||||
|
|
||||||
# Trade "Cable"
|
# Pairs to include in streaming data set
|
||||||
pairs = ["GBPUSD"]
|
pairs = ["EURUSD", "GBPUSD"]
|
||||||
|
|
||||||
# Create the OANDA market price streaming class
|
# Create the OANDA market price streaming class
|
||||||
# making sure to provide authentication commands
|
# making sure to provide authentication commands
|
||||||
|
|||||||
Reference in New Issue
Block a user