def close(self, pair_to_close): print("Close existing position...") r = positions.PositionDetails(accountID=accountID, instrument=pair_to_close) try: openPos = api.request(r) except V20Error as e: print("V20Error: {}".format(e)) else: toClose = {} for P in ["long", "short"]: if openPos["position"][P]["units"] != "0": toClose.update({"{}Units".format(P): "ALL"}) print("prepare to close: %s", json.dumps(toClose)) r = positions.PositionClose(accountID=accountID, instrument=pair_to_close, data=toClose) rv = None try: if toClose: rv = api.request(r) print("close: response: %s", json.dumps(rv, indent=2)) except V20Error as e: print("V20Error: {}".format(e))
def exit(BuySell, currency): posit = positions.PositionDetails(accountID=account_id, instrument=currency) client.request(posit) open_pos = posit.response["position"] long_short = {} long_short["long"] = open_pos["long"]["units"] long_short["short"] = open_pos["short"]["units"] if BuySell == "S": try: data_short = {"shortUnits": "ALL"} close_posit = positions.PositionClose(accountID=account_id, instrument=currency, data=data_short) client.request(close_posit) print("All Short positions closed for ", currency) except: print(" Error Closing Trade short for .", currency) if BuySell == "B": try: data_long = {"longUnits": "ALL"} close_posit = positions.PositionClose(accountID=account_id, instrument=currency, data=data_long) client.request(close_posit) print("All long positions closed for ", currency) except: print(" Error Closing Trade. ", currency)
def close(self): logger.info("Close existing positions ...") r = positions.PositionDetails(accountID=self.accountID, instrument=self.pt.instrument) try: openPos = self.client.request(r) except V20Error as e: logger.error("V20Error: %s", e) else: toClose = {} for P in ["long", "short"]: if openPos["position"][P]["units"] != "0": toClose.update({"{}Units".format(P): "ALL"}) logger.info("prepare to close: {}".format(json.dumps(toClose))) r = positions.PositionClose(accountID=self.accountID, instrument=self.pt.instrument, data=toClose) rv = None try: if toClose: rv = self.client.request(r) logger.info("close: response: %s", json.dumps(rv, indent=2)) except V20Error as e: logger.error("V20Error: %s", e)
def current_long_short_units(): client = oandapyV20.API(access_token=access_token) r = positions.PositionDetails(accountID=accountID, instrument='EUR_USD') client.request(r) resp = r.response long_units = int(resp['position']['long']['units']) short_units = int(resp['position']['short']['units']) return long_units + short_units
def test__positiondetails(self, mock_get): """get the details of a single instrument's position.""" tid = "_v3_accounts_accountID_positiondetails" resp, data = fetchTestData(responses, tid) r = positions.PositionDetails(accountID, instrument="EUR_USD") mock_get.register_uri('GET', "{}/{}".format(api.api_url, r), text=json.dumps(resp)) result = api.request(r) self.assertTrue(resp == result)
def get_open_positions(client, account_id, instrument): try: position_data = positions.PositionDetails(account_id, instrument) position_data = client.request(position_data) position = float(position_data['position']['long']['units']) + \ float(position_data['position']['short']['units']) print("Position: " + str(position) + " " + instrument) except Exception: position = 0 print("Position: " + str(position) + " " + instrument) return position
def is_buy(self, instrument): all_positions = positions.PositionDetails(accountID=self.id, instrument=instrument) self.client.request(all_positions) open_pos = all_positions.response["position"] long_short = {} long_short["long"] = open_pos["long"]["units"] long_short["short"] = open_pos["short"]["units"] if long_short["long"] != "0" and long_short["short"] == "0": return True if long_short["short"] != "0" and long_short["long"] == "0": return False return None
def get_positions(self, ticker): position = {} client = oandapyV20.API(access_token=self.access_token) r = positions.PositionDetails(accountID=self.account_ID, instrument=ticker) try: rqt = client.request(r) position['long'] = float(rqt['position']['long']['units']) position['short'] = float(rqt['position']['short']['units']) position['unrealizedPL'] = float(rqt['position']['unrealizedPL']) position['pl'] = float(rqt['position']['pl']) except V20Error: position['long'] = 0.0 position['short'] = 0.0 position['unrealizedPL'] = 0.0 position['pl'] = 0.0 return position # current open position
def countOpenTrades(BuySell, currency): counter = 0 posit = positions.PositionDetails(accountID=account_id, instrument=currency) client.request(posit) open_pos = posit.response["position"] long_short = {} long_short["long"] = open_pos["long"]["units"] long_short["short"] = open_pos["short"]["units"] if BuySell == "S": if long_short["short"] != 0: counter += 1 if BuySell == "B": if long_short["long"] != 0: counter += 1 return counter
def checkOrder(flag, chart_ins): p = positions.PositionDetails(accountID=accountID, instrument=chart_ins) rv = api.request(p) #print(rv) #注文状況を確認して通っていたら以下を実行 if debug == 1: flag["order"]["exist"] = False flag["order"]["count"] = 0 flag["position"]["exist"] = True flag["position"]["side"] = flag["order"]["side"] flag["position"]["price"] = flag["order"]["price"] return flag if rv["position"]["long"]["units"] != "0": flag["order"]["exist"] = False flag["order"]["count"] = 0 flag["position"]["exist"] = True flag["position"]["side"] = "BUY" flag["position"]["price"] = float( rv["position"]["long"]["averagePrice"]) * float( rv["position"]["long"]["units"]) print(rv["position"]["long"]["averagePrice"]) elif rv["position"]["short"]["units"] != "0": flag["order"]["exist"] = False flag["order"]["count"] = 0 flag["position"]["exist"] = True flag["position"]["side"] = "SELL" flag["position"]["price"] = -1 * float( rv["position"]["short"]["averagePrice"]) * float( rv["position"]["short"]["units"]) print(rv["position"]["short"]["averagePrice"]) #注文が通っていなければキャンセルする else: flag["order"]["exist"] = False flag["order"]["count"] = 0 flag["position"]["exist"] = False flag["position"]["count"] = 0 flag["position"]["side"] = "" flag["position"]["price"] = 0 return flag
def is_buy(self, instrument): """ Check if there is an open position for the instrument return True if there is a long position return False if there is a short position return None if no position is open """ all_positions = positions.PositionDetails(accountID=self.id, instrument=instrument) self.client.request(all_positions) open_pos = all_positions.response["position"] long_short = {} long_short["long"] = open_pos["long"]["units"] long_short["short"] = open_pos["short"]["units"] if long_short["long"] != "0" and long_short["short"] == "0": return True if long_short["short"] != "0" and long_short["long"] == "0": return False return None
import oandapyV20.endpoints.orders as orders import oandapyV20.endpoints.positions as positions ########### Account Setup ########### from mlinc.v20conf import account_id, account_key api = oandapyV20.API(access_token=account_key) ########## Position Details ############ # Input to create Take Profit instrument = "USD_JPY" long_short = 'short' TP = "113.3" # Get order fill ID r = positions.PositionDetails(accountID=account_id, instrument=instrument) api.request(r) Position = r.response tr_id = str(r.response['position'][long_short]['tradeIDs']) #format string: remove [''] tr_id = tr_id[2:-2] ########### Take Profit Order Creation ############### take_profit = { "order": { "timeInForce": "GTC", "price": TP, "type": "TAKE_PROFIT", "tradeID": tr_id } }
if (float(r_ic.response['candles'][1]['mid']['l']) < float(r_ic.response['candles'][0]['mid']['l'])) & (float(r_ic.response['candles'][1]['mid']['c']) < float(r_ic.response['candles'][0]['mid']['c'])): if r_ic.response['candles'][1]['time'][:16] != str1_product_list[product]: if float(r_ad.response['account']['marginAvailable']) >= 50000: #print('aa') #order_price = str(1)#float(r_ic.response['candles'][1]['mid']['c'])*2 data = {"order": {"instrument": product,"units": "1","type": "MARKET","positionFill": "DEFAULT"}}#"price": order_price,"timeInForce": "GTC", r_oc = orders.OrderCreate(accountID, data=data) client.request(r_oc) print(r_ic.response['instrument']) print(r_ic.response['candles'][1]['time'][:16]) print(str1_product_list[product]) #print (r_oc.response) str1_product_list[product] = r_ic.response['candles'][1]['time'][:16] if float(r_ad.response['account']['marginAvailable']) < 50000: r_op = positions.PositionDetails(accountID, instrument = product)# client.request(r_op) if float(r_op.response['position']['short']['units']) > 0: r_pc = positions.PositionClose(accountID, instrument = product, data = {'shortUnits':'1'}) client.request(r_pc) str1_product_list[product] = r_ic.response['candles'][1]['time'][:16] print(r_pc.response) if (float(r_ic.response['candles'][1]['mid']['h']) > float(r_ic.response['candles'][0]['mid']['h'])) & (float(r_ic.response['candles'][1]['mid']['c']) > float(r_ic.response['candles'][0]['mid']['c'])): if r_ic.response['candles'][1]['time'][:16] != str1_product_list[product]: if float(r_ad.response['account']['marginAvailable']) >= 50000: #print('aa') #order_price = str(1)#float(r_ic.response['candles'][1]['mid']['c'])*2 data = {"order": {"instrument": product,"units": "-1","type": "MARKET","positionFill": "DEFAULT"}}#"price": order_price,"timeInForce": "GTC", r_oc = orders.OrderCreate(accountID, data=data)
# http://www.algo-fx-blog.com/fx-api-oanda-v20-python-positions-management/ import pandas as pd import oandapyV20 import oandapyV20.endpoints.positions as positions import os, sys sys.path.append(os.getcwd()) from basic import accountID, access_token, api # 講座のすべてのポジションをリストとして取得 r = positions.PositionList(accountID=accountID) print(api.request(r)) # 通貨を指定してポジションを取得 r = positions.PositionDetails(accountID=accountID, instrument="EUR_GBP") print(api.request(r)) # ポジションを保有していない場合はエラー # すべてのポジションを決済する data = {"longUnits": "ALL"} # ドル円の買い注文全ての保有ポジションを決済する r = positions.PositionClose(accountID=accountID, data=data, instrument="USD_JPY") print(api.request(r))
# positions.PositionClose(accountID) - ポジションを決済する # positions.PositionDetails(accountID) - ポジションの詳細を取得する import oandapyV20.endpoints.positions as positions #--------------------------- # ポジションを決済する #--------------------------- position_data = {'longUnits': 'ALL'} # position_data = { 'longUnits': '1000' } p = positions.PositionClose(accountID=accountID, data=position_data, instrument='USD_JPY') api.request(p) p.response #--------------------------- # ポジションの詳細を取得する #--------------------------- p = positions.PositionDetails(accountID=accountID, instrument='USD_JPY') api.request(p) p.response
def PositionsPositionDetails(access_token, accountID, instrument): 'Get the details of a single instrument’s position in an Account. The position may be open or not.' r = positions.PositionDetails(accountID=accountID, instrument=instrument) client = API(access_token=access_token) client.request(r) return readable_output(Munch(r.response)), Munch(r.response)
def tradeCloseDecide(chart_ins): p = positions.PositionDetails(accountID=accountID, instrument=chart_ins) rv = api.request(p) r = trades.TradeClose(accountID, tradeID=rv["lastTransactionID"]) rv = api.request(r) print(rv)
def positions_details(accountID, token, instrument): client = oandapyV20.API(access_token=token) r = positions.PositionDetails(accountID=accountID, instrument=instrument) request = client.request(r) return request
def position_details(self, instrument): endpoint = positions.PositionDetails(self.account_id, instrument) self.send_request(endpoint) return endpoint.response