예제 #1
0
파일: api.py 프로젝트: aliensmart/oanda_tut
 def get_trades(self):
     """
         Get all open trades
     """
     r = trades.OpenTrades(accountID=self.id)
     open_trades = self.client.request(r)['trades']
     return open_trades
예제 #2
0
파일: oanda.py 프로젝트: adamstreu/forex
def get_most_recent_transaction(account):
    client = 'client=oandapyV20.API(access_token=env['client'])'
    client = oandapyV20.API(access_token=client)
    r = trades.OpenTrades(accountID=account)
    client.request(r)
    _id = int(r.response['lastTransactionID'])
    return _id
예제 #3
0
def get_most_recent_transaction():
    env = yaml.safe_load(open('/seq/seq3/configs/env.yaml', 'r'))
    accountid = env['accountid_long']
    client = oandapyV20.API(access_token=env['client'])
    r = trades.OpenTrades(accountID=accountid)
    client.request(r)
    _id = int(r.response['lastTransactionID'])
    return _id
예제 #4
0
 def get_open_trades(self):
     r = trades.OpenTrades(self.account_id)
     try:
         rv = RUNNING_ENV.api.request(r)
     except V20Error as err:
         logging.error(r.status_code, err)
     else:
         logging.info(json.dumps(rv, indent=2))
         return rv.get('trades')
예제 #5
0
 def test__open_trades(self, mock_get):
     """get the open trades information for an account."""
     tid = "_v3_accounts_accountID_opentrades"
     resp, data = fetchTestData(responses, tid)
     r = trades.OpenTrades(accountID)
     mock_get.register_uri('GET',
                           "{}/{}".format(api.api_url, r),
                           text=json.dumps(resp))
     result = api.request(r)
     self.assertTrue(result == resp)
예제 #6
0
    def get_trade_position(self, instrument):
        req = trades.OpenTrades(accountID=self.account_id)
        response = self.oanda.request(req)

        trade_list = response["trades"]

        order_flag = False
        if len(trade_list) > 0:
            order_flag = True

        return order_flag
예제 #7
0
def check_position(trade_account):
    oanda = oandapyV20.API(environment=trade_account["env"],
                           access_token=trade_account["accessToken"])
    req = trades.OpenTrades(accountID=trade_account["accountId"])
    response = oanda.request(req)

    trade_list = response["trades"]

    order_flag = False
    if len(trade_list) > 0:
        order_flag = True

    return order_flag
예제 #8
0
def open_trades():
    result = {}
    r = trades.OpenTrades(account_id)
    client.request(r)

    response = r.response
    if response is not None:
        oTrades = response.get("trades", [])
        for t in oTrades:
            _instrument = t["instrument"]
            result[_instrument] = t

    return result
예제 #9
0
 def get_open_trades(self) -> list:
     """
     Get all open trades from the account
     :return: list of open trades
     """
     r = trades.OpenTrades(self.account_id)
     try:
         rv = RUNNING_ENV.api.request(r)
     except V20Error as err:
         logging.error(r.status_code, err)
     else:
         logging.info(json.dumps(rv, indent=2))
         return rv.get('trades')
예제 #10
0
def open_trades_request(accountID: str = account) -> Union[pd.DataFrame, bool]:
    """Request open trades data.

    Parameters
    ----------
    accountID : str, optional
        Oanda account ID, by default cfg.OANDA_ACCOUNT

    Returns
    -------
    Union[pd.DataFrame, bool]
        Open trades data or False
    """
    if accountID == "REPLACE_ME":
        console.print("Error: Oanda account credentials are required.")
        return False

    if client is None:
        return False

    try:
        request = trades.OpenTrades(accountID)
        response = client.request(request)
        if "trades" in response and len(response["trades"]) > 0:
            df_trades = pd.DataFrame.from_dict(response["trades"])
            df_trades = df_trades[[
                "id",
                "instrument",
                "initialUnits",
                "currentUnits",
                "price",
                "unrealizedPL",
            ]]
            df_trades = df_trades.rename(
                columns={
                    "id": "ID",
                    "instrument": "Instrument",
                    "initialUnits": "Initial Units",
                    "currentUnits": "Current Units",
                    "price": "Entry Price",
                    "unrealizedPL": "Unrealized P/L",
                })
        else:
            df_trades = pd.DataFrame()
        return df_trades
    except V20Error as e:
        logger.exception(str(e))
        d_error = json.loads(e.msg)
        console.print(d_error["errorMessage"], "\n")
        return False
예제 #11
0
    def close_trade(self, currency):
        try:

            req = trades.OpenTrades(accountID=self.account_id)
            response = self.oanda.request(req)
            trade_id = response["trades"][0]["id"]


            req = trades.TradeClose(accountID=self.account_id, tradeID=trade_id)
            response = self.oanda.request(req)
            return response

        except:
            raise
예제 #12
0
def close_position(trade_account):
    try:
        oanda = oandapyV20.API(environment=trade_account["env"],
                               access_token=trade_account["accessToken"])
        req = trades.OpenTrades(accountID=trade_account["accountId"])
        response = oanda.request(req)
        trade_id = response["trades"][0]["id"]

        req = trades.TradeClose(accountID=trade_account["accountId"],
                                tradeID=trade_id)
        response = oanda.request(req)
        return response

    except:
        raise
예제 #13
0
def get_open_trades(accountID, other_args):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="trades",
        description="Gets information about open trades.",
    )
    ns_parser = parse_known_args_and_warn(parser, other_args)
    if not ns_parser:
        return

    try:
        request = trades.OpenTrades(accountID)
        response = client.request(request)
        try:
            df = pd.DataFrame.from_dict(response["trades"])
            df = df[
                [
                    "id",
                    "instrument",
                    "initialUnits",
                    "currentUnits",
                    "price",
                    "unrealizedPL",
                ]
            ]
            df = df.rename(
                columns={
                    "id": "ID",
                    "instrument": "Instrument",
                    "initialUnits": "Initial Units",
                    "currentUnits": "Current Units",
                    "price": "Entry Price",
                    "unrealizedPL": "Unrealized P/L",
                }
            )

            print(df.to_string(index=False))
            print("")

        except KeyError:
            print("No trades were found")
            print("")
    except V20Error as e:
        msg_length = len(e.msg)
        msg = e.msg[17 : msg_length - 2]
        print(msg)
        print("")
예제 #14
0
 def get_open_trade(self) -> list:
     req = trades.OpenTrades(self.account_id)
     try:
         resp = self.client.request(req)
         logger.info(f'action=get_open_trade resp={resp}')
     except V20Error as e:
         logger.error(f'action=get_open_trade error={e}')
         raise
     trades_list = []
     for trade in resp['trades']:
         trades_list.insert(0, Trade(
             trade_id=trade['id'],
             side=constants.BUY if float(trade['currentUnits']) > 0 else constants.SELL,
             units=float(trade['currentUnits']),
             price=float(trade['price'])
         ))
     return trades_list
예제 #15
0
def open_trades():
    result = {}
    r = trades.OpenTrades(account_id)
    client.request(r)

    response = r.response
    if response is not None:
        oTrades = response.get("trades", [])
        for t in oTrades:
            _instrument = t["instrument"]
            if _instrument not in result:
                result[_instrument] = {}
            if int(t["currentUnits"]) > 0:
                result[_instrument]["long"] = t
            else:
                result[_instrument]["short"] = t

    return result
예제 #16
0
def main():
    global pairs
    try:
        r = trades.OpenTrades(accountID=account_id)
        open_trades = client.request(r)['trades']
        
        curr_ls = []
        for i in range(len(open_trades)):
            curr_ls.append(open_trades[i]['instrument'])
        pairsNotInPosition = [i for i in pairs if i not in curr_ls]

        for currency in pairsNotInPosition:
            print("analyzing currency not in position: ",currency)
            data = oanda.getCandles(currency, candle_count, granularity)
          
            data = indicators.ema_n(data, 50)
            data = indicators.ema_n(data, 100)
            data = indicators.ema_n(data, 150)
            data = indicators.atr_talib(data, 14)
          
            data["angle50"] = indicators.slope(data["ema50"], 5)
            data["angle100"] = indicators.slope(data["ema100"], 5)
            data["angle150"] = indicators.slope(data["ema150"], 5)

            data["concavity50"] = indicators.slope(data["angle50"], 5)
            data["concavity100"] = indicators.slope(data["angle100"], 5)

            data = data.dropna()
            signal, close = signalIntoPosition(data)
            if signal == "Buy":
                market_order(currency,pos_size, account_id, close, data["ATR"].iloc[-1])
                print(colored("New long position initiated for " + str(currency), 'green'))

            elif signal == "Sell":
                market_order(currency,-1*pos_size, account_id, close, data["ATR"].iloc[-1])
                print(colored("New short position initiated for " + str(currency), 'red'))
            show_data = data.tail(4).drop(["open", "high", "low", "volume"], axis = 1)
            print(colored(show_data.to_string() + "\n\n", 'yellow'))
            print("======================\n")

    except ValueError as error:
        print(format(error))
예제 #17
0
def main():
    global pairs
    try:
        r = trades.OpenTrades(accountID=account_id)
        open_trades = client.request(r)['trades']
        curr_ls = []
        for i in range(len(open_trades)):
            curr_ls.append(open_trades[i]['instrument'])
        pairs = [i for i in pairs if i not in curr_ls]
        for currency in pairs:
            print("analyzing ",currency)
            data = candles(currency)
            ohlc_df = stochastic(data,14,3,3)
            ohlc_df = SMA(ohlc_df,100,200)
            signal = trade_signal(ohlc_df,currency)
            if signal == "Buy":
                market_order(currency,pos_size,3*ATR(data,120))
                print("New long position initiated for ", currency)
            elif signal == "Sell":
                market_order(currency,-1*pos_size,3*ATR(data,120))
                print("New short position initiated for ", currency)
    except:
        print("error encountered....skipping this iteration")
    
if lastVal=="" or lastVal==None:
    lastVal=closedVal
    
print("Last Amount - ",lastVal)
print("Closed Amount - ",closedVal)
print("Present Timestamp - ",timestamp)
print("flgLastbuy - ",flgLastbuy)
print("flgLastsell - ",flgLastsell)
print("LastTranID - ",LastTranID)

flgOrderPresent=False

print("-------------------Check Open Order--------------------------")
##Check open order###############################################
r=trades.OpenTrades(accountID=accountID)
#api.request(r)
try:
    rv = api.request(r)  
    print("Tran ID - " + rv['lastTransactionID'])
    print("ID - " + rv['trades'][0]['id'])
    print("Status - " + rv['trades'][0]['state'])
    flgOrderPresent=True
except IndexError as err:
    print("ERROR: {}".format(err))
else:
    print(json.dumps(rv, indent=4))

print("----------------EMA20 Calculation----------------------------")
###EMA calculation
##Formule =D80*2/(20+1)+F79*(1-2/(20+1)) --- Col no D row is 80
예제 #19
0
def open_trades():
    result = {}
    r = trades.OpenTrades(account_id)
    client.request(r)

    return r.response
예제 #20
0
def open_trades(accountID, token):
    client = oandapyV20.API(access_token=token)
    r = trades.OpenTrades(accountID=accountID)
    request = client.request(r)
    return request
예제 #21
0
def main():
    r = orders.OrderList(accountID=ACCOUNT_ID)
    open_orders = api.request(r)['orders']
    for order in open_orders:
        r = orders.OrderCancel(accountID=ACCOUNT_ID, orderID=order['id'])
        api.request(r)

    r = positions.OpenPositions(accountID=ACCOUNT_ID)
    open_positions = api.request(r)['positions']

    for pair in pairs:
        try:
            l_s, entry_price, amt_owned = get_position_details(
                open_positions, pair)
            if l_s != '':
                print('\n', pair, l_s)
                logging.error(f'\n--- {pair} {l_s} ---')
            df = create_df(pair)
            if l_s != '':
                print(df.tail())
                logging.error(f'\n{df.tail()}')
            signal = trade_signal(pair, df, l_s, entry_price)
            if l_s != '':
                print(f'signal: {signal}')
                logging.error(f'signal: {signal}')

            if (signal == 'buy'
                    or signal == 'sell') and len(open_positions) < max_trades:
                payload = {
                    'order': {
                        'type': 'LIMIT',
                        'instrument': pair,
                        'units': calculate_qty(df, signal, pair),
                        'price': calculate_price(df, pair, signal),
                        'TimeInForce': 'GTC',
                    }
                }
                r = orders.OrderCreate(accountID=ACCOUNT_ID, data=payload)
                api.request(r)
                print(
                    f'\nNew {signal} position initiated for {pair} \n***************************************\n'
                )
                logging.error(
                    f'\nNew {signal} position initiated for {pair} \n***************************************\n'
                )

            elif signal == 'close':
                r = trades.OpenTrades(accountID=ACCOUNT_ID)
                open_trades = api.request(r)['trades']
                for trade in open_trades:
                    if trade['instrument'] == pair:
                        r = trades.TradeClose(accountID=ACCOUNT_ID,
                                              tradeID=trade['id'])
                        api.request(r)
                print(
                    f'\nAll positions closed for {pair} \n***************************************\n'
                )
                logging.error(
                    f'\nAll positions closed for {pair} \n***************************************\n'
                )
        except:
            print(f'error encountered... skipping {pair}')
            logging.error(f'error encountered... skipping {pair}')
예제 #22
0
              time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
              '-----')
        logging.error(f'\n######## PASSTHROUGH AT {current_time} ########')
        main()
        time.sleep(60 - ((time.time() - starttime) % 60.0))

    except KeyboardInterrupt:
        print('\n\nKeyboard exception received. Exiting.')

        r = orders.OrderList(accountID=ACCOUNT_ID)
        open_orders = api.request(r)['orders']
        for order in open_orders:
            r = orders.OrderCancel(accountID=ACCOUNT_ID, orderID=order['id'])
            api.request(r)

        r = trades.OpenTrades(accountID=ACCOUNT_ID)
        open_trades = api.request(r)['trades']
        for trade in open_trades:
            r = trades.TradeClose(accountID=ACCOUNT_ID, tradeID=trade['id'])
            api.request(r)
        exit()

    except:
        r = orders.OrderList(accountID=ACCOUNT_ID)
        open_orders = api.request(r)['orders']
        for order in open_orders:
            r = orders.OrderCancel(accountID=ACCOUNT_ID, orderID=order['id'])
            api.request(r)

        r = trades.OpenTrades(accountID=ACCOUNT_ID)
        open_trades = api.request(r)['trades']
예제 #23
0
    def get_all_open_trades(self):
        r = trades.OpenTrades(accountID=self.accountID)

        return self.client.request(r)
예제 #24
0
def main():
    global pairs
    try:
        r = trades.OpenTrades(accountID=account_id)
        open_trades = client.request(r)['trades']

        curr_ls = []
        for i in range(len(open_trades)):
            curr_ls.append(open_trades[i]['instrument'])
        pairsNotInPosition = [i for i in pairs if i not in curr_ls]

        for currency in pairsNotInPosition:
            positions_sl.pop(currency, None)
            print("analyzing currency not in position: ", currency)
            data = oanda.getCandles(currency, candle_count, granularity)
            renkobars, brick_size = indicators.renko_bars(
                data, atr_n, currency)
            scaledRenko = formatters.merge_renko_timeframe(renkobars, data)
            scaledRenko = indicators.obv_talib(scaledRenko)
            scaledRenko = indicators.sma(scaledRenko, rolling_sma_n)
            scaledRenko["obv_slope"] = indicators.slope(
                scaledRenko["obv"], regression_slope_n)
            scaledRenko["sma_slope"] = indicators.slope(
                scaledRenko["sma"], regression_slope_n)
            scaledRenko = scaledRenko.dropna()
            signal, close, bar_num = signalIntoPosition(scaledRenko)
            if signal == "Buy":
                market_order(currency, pos_size, account_id, brick_size, close,
                             bar_num)
                f.write("BUY" + currency + "\n" + scaledRenko.to_string() +
                        "\n")
                print(
                    colored("New long position initiated for " + str(currency),
                            'green'))
            elif signal == "Sell":
                market_order(currency, -1 * pos_size, account_id, brick_size,
                             close, bar_num)
                f.write("SELL" + currency + "\n" + scaledRenko.to_string() +
                        "\n")
                print(
                    colored(
                        "New short position initiated for " + str(currency),
                        'red'))

            show_data = scaledRenko.tail(20)
            print(colored(show_data.to_string() + "\n\n", 'yellow'))

        for positions in open_trades:
            id = positions['id']
            currency = positions['instrument']
            units = int(positions['currentUnits'])
            print("analyzing currency already in position: ", currency)
            data = oanda.getCandles(currency, candle_count, granularity)
            renkobars, brick_size = indicators.renko_bars(
                data, atr_n, currency)
            scaledRenko = formatters.merge_renko_timeframe(renkobars, data)
            scaledRenko = indicators.sma(scaledRenko, rolling_sma_n)
            scaledRenko["sma_slope"] = indicators.slope(
                scaledRenko["sma"], regression_slope_n)
            scaledRenko = scaledRenko.dropna()
            show_data = scaledRenko.tail(20)
            print(colored(show_data.to_string() + "\n\n", 'yellow'))
            signal, new_sl = signal_edit_sl(scaledRenko, units > 0, currency,
                                            brick_size)

            if signal == "Edit":
                order_edit(id, account_id, new_sl, currency)
                print(colored("Edited stop loss for " + currency, 'cyan'))

    except ValueError as error:
        print(format(error))
예제 #25
0
from oandapyV20.exceptions import V20Error
from oandapyV20.endpoints.pricing import PricingStream
import oandapyV20.endpoints.instruments as instruments
import oandapyV20.endpoints.orders as orders
import oandapyV20.endpoints.trades as trades

# OANDAのデモ口座へのAPI接続
api = API(access_token=access_token, environment="practice")

import time

ps = PricingStream(accountID=accountID, params={'instruments': 'EUR_USD'})
profit = 0.0001
loss = 0.0020
units = 10000
opentrades_req = trades.OpenTrades(accountID=accountID)

if __name__ == '__main__':
    while True:
        bt = api.request(opentrades_req)
        for s in api.request(ps):
            keys = s.keys()
            if ('bids' in keys) and ('asks' in keys):
                bid = float(s['bids'][0]['price'])
                ask = float(s['asks'][0]['price'])

                #-----------------#
                price = bid
                direct = -1
                #-----------------#
예제 #26
0
def main():
    global pairs
    try:
        r = trades.OpenTrades(accountID=account_id)
        open_trades = client.request(r)['trades']

        curr_ls = []
        for i in range(len(open_trades)):
            curr_ls.append(open_trades[i]['instrument'])
        pairsNotInPosition = [i for i in pairs if i not in curr_ls]

        for currency in pairsNotInPosition:
            print("analyzing currency not in position: ", currency)
            data = candles(currency)
            renkobars = renko_DF(data)
            renkobars = data.merge(renkobars.loc[:, ["date", "bar_num"]],
                                   how="outer",
                                   on="date")
            renkobars["bar_num"].fillna(method='ffill', inplace=True)
            renkobars["obv"] = OBV(renkobars)
            renkobars["obv_slope"] = slope(renkobars["obv"], 5)
            renkobars = SMA10(renkobars)
            renkobars["sma_slope"] = slope(renkobars["sma_10"], 5)

            #LONG:
            # 1.When green renko Above 10sma
            # 2.Confirm bias with increase in OBV in correlation with price
            # 3.(Optional) Stop loss 2 bars below entry point, min take profit 3 renko bars
            # 4.Exit position when Renko goes belows SMA
            signal = signalIntoPosition(renkobars)
            if signal == "Buy":
                market_order(currency, pos_size, account_id)
                print("New long position initiated for ", currency)
            elif signal == "Sell":
                market_order(currency, -1 * pos_size, account_id)
                print("New short position initi#ated for ", currency)

        for positions in open_trades:
            currency = positions['instrument']
            print("analyzing currency already in position: ", currency)
            units = int(positions['currentUnits'])
            data = candles(currency)
            renkobars = renko_DF(data)
            renkobars = data.merge(renkobars.loc[:, ["date", "bar_num"]],
                                   how="outer",
                                   on="date")
            renkobars["bar_num"].fillna(method='ffill', inplace=True)
            renkobars = SMA10(renkobars)
            renkobars["sma_slope"] = slope(renkobars["sma_10"], 5)
            #print(renkobars)

            signal = signalOutOfPosition(renkobars, isLong=units > 0)
            if signal == "Buy":
                market_order(currency, pos_size, account_id)
                print("New long position initiated for ", currency)
            elif signal == "Sell":
                market_order(currency, -1 * pos_size, account_id)
                print("New short position initi#ated for ", currency)
    except ValueError as error:
        print(format(error))
    except:
        print("error")
def main():
    global pairs
    try:
        r = trades.OpenTrades(accountID=account_id)
        open_trades = client.request(r)["trades"]
        curr_ls = []
        for i in range(len(open_trades)):
            curr_ls.append(open_trades[i]["instrument"])
        pairs = [i for i in pairs if i not in curr_ls]
        for currency in pairs:
            print(time.ctime())
            print("--------------------------")
            print("open positions: ", curr_ls)
            print("available currencies list: ", pairs)
            print("--------------------------")
            print("processing: ", currency)
            data = candles(currency, 300, "M5")
            data_RSI = generate_RSI(data, 10)
            data_ATR = get_atr_values(data_RSI, 5, 7, 55, 265)
            position_size = 20000
            signal = trade_signal(data_ATR, currency)
            print("ATR: ", round(data_ATR["iATR"][-1], 5))
            print("signal: ", signal)
            print("position size: ", position_size)
            print("..........................")

            # buy signals command
            if signal == "Buy":
                market_order_sl_price(currency,
                                      int(round(position_size * 0.75, 0)),
                                      round(data_ATR["c"][-1] - 0.00040, 5),
                                      round(0.00070 + data_ATR["c"][-1], 5))
                print("New long position initiated for ", currency)
                print("sl = ", round(data_ATR["c"][-1] - 0.00040, 5))
                print("tp = ", round(0.00070 + data_ATR["c"][-1], 5))

            if signal == "Strong_Buy":
                market_order_sl_price(currency,
                                      int(round(position_size * 1.2, 0)),
                                      round(data_ATR["c"][-1] - 0.00040, 5),
                                      round(0.00070 + data_ATR["c"][-1], 5))
                print("New long position initiated for ", currency)
                print("sl = ", round(data_ATR["c"][-1] - 0.00040, 5))
                print("tp = ", round(0.00070 + data_ATR["c"][-1], 5))

            # sell signals command
            if signal == "Sell":
                market_order_sl_price(currency,
                                      -1 * int(round(position_size * 0.75, 0)),
                                      round(data_ATR["c"][-1] + 0.00040, 5),
                                      round(data_ATR["c"][-1] - 0.00070, 5))
                print("New long position initiated for ", currency)
                print("sl = ", round(data_ATR["c"][-1] + 0.00040, 5))
                print("tp = ", round(data_ATR["c"][-1] - 0.00070, 5))

            if signal == "Strong_Sell":
                market_order_sl_price(currency,
                                      -1 * int(round(position_size * 1.2, 0)),
                                      round(data_ATR["c"][-1] + 0.00040, 5),
                                      round(data_ATR["c"][-1] - 0.00070, 5))
                print("New long position initiated for ", currency)
                print("sl = ", round(data_ATR["c"][-1] + 0.00040, 5))
                print("tp = ", round(data_ATR["c"][-1] - 0.00070, 5))

            print("##########################")

    except:
        print("error encountered....skipping this iteration")
        print("##########################")

    print("..........................")
    print("##### Next Iteration #####")
    print("..........................")
예제 #28
0
    def open_trades(self):
        r = trades.OpenTrades(accountID=self.account_id)
        request_data = self.send_request(r)

        return request_data.get("trades", [])
예제 #29
0
    else:
        price = float(rv["prices"][0]["closeoutBid"])
        st_ls = price + sl

    data = {
        "order": {
            "price": "",
            "stopLossOnFill": {
                "timeInForce": "GTC",
                "price": str(st_ls)
            },
            "timeInForce": "FOK",
            "instrument": str(instrument),
            "units": str(units),
            "type": "MARKET",
            "positionFill": "DEFAULT"
        }
    }
    return data


r = orders.OrderCreate(accountID=account_id,
                       data=market_order("USD_JPY", -100,
                                         3 * ATR(ohlc_df, 120)))
client.request(r)

#check trades
r = trades.OpenTrades(accountID=account_id)
client.request(r)
#client.request(r)['trades'][0]['currentUnits']
예제 #30
0
 def get_open_trades(self):
     r = trades.OpenTrades(accountID=self.account_num)
     open_trades = self.client.request(r)['trades']
     return open_trades