Пример #1
0
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)
Пример #2
0
    def close_position(self):
        try:

            data = {'longUnits': 'ALL'}
            order_close = positions.PositionClose(accountID=self.account_id,
                                                  instrument=self.ccy,
                                                  data=data)

            self.client.request(order_close)
            resp_close = order_close.response
            return float(resp_close['longOrderFillTransaction']['price'])

        except Exception as err:

            if ('does not exist' in str(err)) == True:

                try:
                    data = {'shortUnits': 'ALL'}
                    order_close = positions.PositionClose(
                        accountID=self.account_id,
                        instrument=self.ccy,
                        data=data)

                    self.client.request(order_close)
                    resp_close = order_close.response
                    return float(
                        resp_close['shortOrderFillTransaction']['price'])
                except Exception as err:
                    print("position not closed: " + str(err))
                    return -1
Пример #3
0
 def close(self, instrument):
     data_short = {"shortUnits": "ALL"}
     data_long = {"longUnits": "ALL"}
     if self.is_buy(instrument) == True:
         close_posit = positions.PositionClose(accountID=self.id,
                                               instrument=instrument,
                                               data=data_long)
         self.client.request(close_posit)
         print("Closing all long positions ", instrument)
     if self.is_buy(instrument) == False:
         close_posit = positions.PositionClose(accountID=self.id,
                                               instrument=instrument,
                                               data=data_short)
         self.client.request(close_posit)
         print("Closing all Short positions ", instrument)
Пример #4
0
def oanda_close_positions(side):
    # API取得
    api = API(access_token=token)

    # 注文内容
    if side == "BUY":
        order_data = {"shortUnits": "ALL"}
    if side == "SELL":
        order_data = {"longUnits": "ALL"}

    while True:
        # 注文実行
        try:
            r = positions.PositionClose(accountID,
                                        instrument=currency,
                                        data=order_data)
            api.request(r)
            print_log("\nすべての建玉を決済しました\n決済価格は平均 {}円です".format(
                str(data["forming"]["close_price"])))
            return order_data

        except V20Error as e:
            print_log("OANDAのAPIで問題発生" + str(e))
            print_log("20秒待機してやり直します")
            time.sleep(20)
Пример #5
0
 def close_buy_position(self):
     try:
         data = {"longUnits": "ALL"}
         positon = positions.PositionClose(accountID=self.oanda_account_id,
                                           instrument="USD_JPY",
                                           data=data)
         response = self.api.request(positon)
         result = response["longOrderFillTransaction"]
         print('close_buy_position response', json.dumps(response,
                                                         indent=2))
         # ポジション決済情報をDBに登録
         params = {
             'position_id': int(result["id"]),
             'date': self.date,
             'instrument': result["instrument"],
             'units': result["units"],
             'price': result["price"],
             'pl': result["pl"],
             'account_balance': result["accountBalance"],
         }
         PositionLog = position_log.PositionLog()
         PositionLog.put_item(params)
     except requests.exceptions.ConnectionError as e_HTTP:
         print(response.text)
         print(e_HTTP)
     except Exception as e:
         print(e)
         raise OandaApiError(e)
def close_order_short(pair):
    d = {
        "XAG_USD": 41,
        "XAU_USD": 1,
        "CORN_USD": 300,
        "BCO_USD": 28,
        "NATGAS_USD": 493,
        "SUGAR_USD": 9150,
        "WHEAT_USD": 204,
        "XCU_USD": 360,
        "XPT_USD": 1,
        "SOYBN_USD": 109
    }
    u = d.get(pair)
    ordr = PositionCloseRequest(shortUnits=u)
    r = positions.PositionClose(accountID=accountID,
                                instrument=pair,
                                data=ordr.data)

    try:
        response = api.request(r)
    except V20Error as e:
        print("V20Error:{}".format(e))
    else:
        print("Respose: {}\n{}".format(r.status_code,
                                       json.dumps(response, indent=2)))
Пример #7
0
def close_positions(instrument, side=None, ratio=1.0):
    logging.info(f"Received request to close position for {instrument}")
    temp = o_positions.get(instrument, {})
    if len(temp) == 0:
        logging.warning(
            f"Symbol {instrument} not in open positions list:\n{o_positions}")
        return
    l_units = abs(int(temp["long"]["units"]) * ratio)
    s_units = abs(int(temp["short"]["units"]) * ratio)
    if side == 'long':
        s_units = 0
    elif side == 'short':
        l_units = 0

    data = {
        "longUnits": str(l_units) if l_units > 0 else "NONE",
        "shortUnits": str(s_units) if s_units > 0 else "NONE"
    }
    logging.info(
        f"Closing position for symbol {instrument} with payload:\n{data}")
    r = positions.PositionClose(account_id, instrument, data)
    try:
        client.request(r)
    except oandapyV20.exceptions.V20Error as e:
        log.warning(e)
    else:
        time.sleep(1)
        logging.info(
            f"Position closed for symbol {instrument}, response:\n{r.response}"
        )
        return r.response
Пример #8
0
def close_positions(instrument, side=None, force=True):
    if force is True:
        _pos = open_positions()
    else:
        _pos = o_positions
    temp = _pos.get(instrument, {})
    if len(temp) == 0:
        return
    l_units = abs(int(temp["long"]["units"]))
    s_units = abs(int(temp["short"]["units"]))
    if side == 'long':
        s_units = 0
    elif side == 'short':
        l_units = 0

    data = {
        "longUnits": str(l_units) if l_units > 0 else "NONE",
        "shortUnits": str(s_units) if s_units > 0 else "NONE"
    }
    r = positions.PositionClose(account_id, instrument, data)
    try:
        client.request(r)
    except oandapyV20.exceptions.V20Error as e:
        log.warning(e)
    else:
        return r.response
Пример #9
0
 def position_close_short(self, pair="AUD_USD", unit=1000):
     client = API(access_token=self.access_token, environment='live')
     ordr = PositionCloseRequest(shortUnits=unit)
     r = position.PositionClose(self.accountID,
                                instrument=pair,
                                data=ordr.data)
     rv = client.request(r)
Пример #10
0
    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))
Пример #11
0
def close_position(direction, pair):

    # Get Units to close based on direction of original trade
    if direction == 'buy':
        units = 'longUnits'
        return_fields = [
            'longOrderCreateTransaction', 'longOrderFillTransaction'
        ]
    else:
        units = 'shortUnits'
        return_fields = [
            'shortOrderCreateTransaction', 'shortOrderFillTransaction'
        ]
    # Request Parameters
    data = {units: "ALL"}
    client = oandapyV20.API(access_token=oanda_api)
    r = positions.PositionClose(accountID=oanda_account,
                                instrument=pair,
                                data=data)
    # Attempt Request and return response
    try:
        client.request(r)
        # print(r.response)
        return r.response
    except:
        return r.response
Пример #12
0
    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)
Пример #13
0
def PositionsPositionClose(access_token, accountID, instrument, data=None):
    'Closeout the open Position regarding instrument in an Account.'
    r = positions.PositionClose(accountID=accountID,
                                instrument=instrument,
                                data=data)
    client = API(access_token=access_token)
    client.request(r)
    return readable_output(Munch(r.response)), Munch(r.response)
Пример #14
0
def short_position(instrument):
    # long  or  short
    data = {
        "shortUnits": "ALL"
    }
    # ドル円の買いポジションすべてを決済
    r = positions.PositionClose(accountID = accountID, data = data, instrument=instrument)
    api.request(r)
Пример #15
0
 def close_trade(self, instrument_index, longunits, shortunits):
     self.position["longUnits"] = longunits
     self.position["shortUnits"] = shortunits
     close = positions.PositionClose(
         accountID=account_id,
         instrument=self.instruments[instrument_index],
         data=position)
     self.oanda20.request(close)
Пример #16
0
 def oanda_closepositions(self, market_positions, market, price, short_flag):    # closing all for now but could change the number
     if short_flag:
         data = {'shortUnits':'ALL'}
     else:
         data = {'longUnits':'ALL'}
     request = positions.PositionClose(accountID=self.oanda_account_id, data=data, instrument=market) # ...
     rv = self.oanda.request(request)
     return rv
Пример #17
0
def sell_order(inst):
    """ Places an order to close positions for FX with Oanda API """
    data = {"longUnits": "ALL"}
    r = positions.PositionClose(accountID=account_id,
                                instrument=inst,
                                data=data)
    client.request(r)
    print(r.response)
Пример #18
0
    def close_all(shortlong, instrument):
        if shortlong == 'short':
            data = {"shortUnits": "ALL"}
        elif shortlong == 'long':
            data = {"longUnits": "ALL"}

        r = positions.PositionClose(accountID=accountID,
                                    instrument=instrument,
                                    data=data)
        client.request(r)
Пример #19
0
 def test__positionclose(self, mock_put):
     """close single instrument's position long side."""
     tid = "_v3_accounts_accountID_position_close"
     resp, data = fetchTestData(responses, tid)
     r = positions.PositionClose(accountID, instrument="EUR_USD", data=data)
     mock_put.register_uri('PUT',
                           "{}/{}".format(api.api_url, r),
                           text=json.dumps(resp))
     result = api.request(r)
     self.assertTrue(resp == result)
Пример #20
0
def do_close_long():
    try:
        r = positions.PositionClose(config.account_id, 'sber',
                                    {"longUnits": "ALL"})
        resp = oanda.request(r)
        print(resp)
        pl = resp.get('longOrderFillTransaction').get('pl')
        real_profits.append(float(pl))
        print(time, 's: Closed. Profit = ', pl, ' price = ',
              resp.get('longOrderFillTransaction').get('price'))
    except:
        print('No long units to close')
Пример #21
0
def close_position(instrument):
    client = 'client=oandapyV20.API(access_token=env['client'])'
    account_id = '101-001-7518331-001'
    client = oandapyV20.API(access_token=client)
    data =  {
              "shortUnits": "ALL"
            }
    r = positions.PositionClose(accountID=account_id,
                                 instrument=instrument, 
                                 data = data)
    client.request(r)
    print(r.response)
Пример #22
0
    def close_positions(self, ticker, value='ALL'):
        client = oandapyV20.API(access_token=self.access_token)
        positions_ = self.get_positions(ticker)
        if positions_["short"] == 0 and positions_['long'] == 0:
            #print("No position to be closed")
            return -1
            pass
        else:
            if positions_["short"] != 0 and positions_["long"] == 0:
                data = {"shortUnits": value}
            elif positions_['short'] == 0 and positions_['long'] != 0:
                data = {"longUnits": value}
            else:
                data = {"shortUnits": value, "longUnits": value}

            r = positions.PositionClose(accountID=self.account_ID,
                                        instrument=ticker,
                                        data=data)
            client.request(r)

            if positions_["short"] != 0 and positions_["long"] == 0:
                rr = r.response["shortOrderFillTransaction"]
            if positions_["short"] == 0 and positions_["long"] != 0:
                rr = r.response["longOrderFillTransaction"]
            price = rr.get("price")
            unit = rr.get("units")
            instrument = rr.get("instrument")
            t_time = rr.get('time')
            #print(time,datetime.datetime.strptime(time.split('.')[0], "%Y-%m-%dT%H:%M:%S").timetuple())
            unixtime = time.mktime(
                datetime.datetime.strptime(
                    t_time.split('.')[0], "%Y-%m-%dT%H:%M:%S").timetuple())
            margin = self.get_nav()['marginAvailable']
            accountBalance = self.get_nav()['balance']
            #print(value)
            if value == 'ALL':
                #print('1')
                close = [
                    t_time, unixtime, unit, instrument, price, margin,
                    accountBalance,
                    self.get_nav()['nav'], 'CloseAll'
                ]
            else:
                #print('0')
                close = [
                    t_time, unixtime, unit, instrument, price, margin,
                    accountBalance,
                    self.get_nav()['nav'], 'Close'
                ]
            self.trade_history.append(close)
            #print("")
            return 1
Пример #23
0
def do_close_short():
    try:
        r = positions.PositionClose(config.account_id, 'EUR_USD',
                                    {"shortUnits": "ALL"})
        resp = oanda.request(r)
        print(resp)
        pl = resp.get('shortOrderFillTransaction').get('tradesClosed')[0].get(
            'realizedPL')
        real_profits.append(float(pl))
        print(time, 's: Closed. Profit = ', pl, ' price = ',
              resp.get('shortOrderFillTransaction').get('price'))
    except:
        print('No short units to close')
Пример #24
0
def close_all_positions(oanda_api=oanda_api, account_id=oanda_account):
    instruments = get_open_positions()
    client = oandapyV20.API(access_token=oanda_api)
    for pair in instruments:
        if pair[1] == 'long':
            data = {"longUnits": "ALL"}
        else:
            data = {"shortUnits": "ALL"}
        r = positions.PositionClose(account_id, instrument=pair[0], data=data)
        client.request(r)
        print('\nPositions closed: {}\n'.format(pair))
        print(r.response)
    return
def close_positions(accountID, token, instrument, units_type, quantity):
    if units_type == "short":
        data = create_position_close_data(shortUnits=quantity)
    elif units_type == "long":
        data = create_position_close_data(longUnits=quantity)
    else:
        return None
    client = oandapyV20.API(access_token=token)
    r = positions.PositionClose(accountID=accountID,
                                instrument=instrument,
                                data=data)
    request = client.request(r)
    return request
Пример #26
0
 def test_market_orders(self):
     token = open('../Account/Token.txt', 'r').read()
     accId = open('../Account/Account.txt', 'r').read()
     oanda = oandapyV20.API(environment="practice", access_token=token)
     mktOrder = MarketOrderRequest(instrument='EUR_USD', units=1)
     r = orders.OrderCreate(accId, data=mktOrder.data)
     resp = oanda.request(r)
     print resp
     r = positions.PositionClose(accId, 'EUR_USD', {"longUnits": "ALL"})
     resp = oanda.request(r)
     print resp
     r = AccountDetails(accId)
     balance = oanda.request(r).get('account').get('balance')
     self.assertTrue(balance > 0)
Пример #27
0
    def close_all_position(self, ticker, closetype='long'):
        """
        closetype: long, short
        """

        if closetype is 'long':
            d = dict(longUnits='ALL')
        elif closetype is 'short':
            d = dict(shortUnits='ALL')
        r = positions.PositionClose(accountID=self.accountID,
                                    instrument=ticker,
                                    data=d)

        return self.client.request(r)
Пример #28
0
def killSwitch(currency_pair):
    client = oandapyV20.API(access_token=token)
    data = {"longUnits": "ALL"}

    client_request = positions.PositionClose(accountID=accountID,
                                             instrument=currency_pair,
                                             data=data)
    try:
        rv = client.request(client_request)
    except V20Error as err:
        print("ERROR OCCURED DUE TO : {}".format(err))
    else:
        response = json.dumps(rv, indent=2)
        return response
Пример #29
0
    def close_position(self, symbol, side, qty):

        if side == "buy":
            data = {'longUnits': qty}

        elif side == "sell":
            data = {'shortUnits': qty}

        r = positions.PositionClose(accountID=ACCOUNT_ID,
                                    instrument=symbol,
                                    data=data)
        data = api.request(r)

        return data
Пример #30
0
 def test_market_orders(self):
     conf = Config.Config()
     token = conf.token
     accId = conf.account_id
     oanda = oandapyV20.API(environment="practice", access_token=token)
     mktOrder = MarketOrderRequest(instrument='EUR_USD', units=1)
     r = orders.OrderCreate(accId, data=mktOrder.data)
     resp = oanda.request(r)
     print(resp)
     r = positions.PositionClose(accId, 'EUR_USD', {"longUnits": "ALL"})
     resp = oanda.request(r)
     print(resp)
     r = AccountDetails(accId)
     balance = oanda.request(r).get('account').get('balance')
     self.assertTrue(balance > 0)