Ejemplo n.º 1
0
def call_order_list(account_id, account_token, instrument, debug=False):
    trade_list = []

    if debug:
        account_id, client = use_our_token()

    else:
        client = account_token

    params = {"instrument": instrument}

    try:
        r = orders.OrderList(accountID=account_id, params=params)

        client.request(r)
        # print(r.response)
        # print('\n')

        for num, res in enumerate(r.response['orders']):
            # print(f"order {instrument!r} no.{num} has trade ID : {res['tradeID']}")

            trade_list.append(res['tradeID'])

        return trade_list

    except V20Error as ex:
        error_msg = ex.msg.split('"errorMessage":')[1].split(',')[0]
        print(f"Error : {error_msg}")

        return error_msg
Ejemplo n.º 2
0
 def updateids(self, instrument, granularity):
     df = self.getids()
     csvID = self.getid(granularity, instrument)
     params = {"instrument": instrument}
     o = orders.OrderList(self.accountID, params=params)
     t = trades.TradesList(self.accountID, params=params)
     self.client.request(o)
     self.client.request(t)
     orderlist = [x['id'] for x in o.response['orders']]
     tradelist = [x['id'] for x in t.response['trades']]
     if csvID[0] in orderlist:
         return
     elif csvID[0] in tradelist:
         return
     else:
         for x in tradelist:
             p = {'id': x}
             t = trans.TransactionDetails(self.accountID, p['id'])
             self.client.request(t)
             orderID = t.response['transaction']['orderID']
             if orderID == csvID[0]:
                 if csvID[1] == 0:
                     df.loc[granularity, instrument]['Consolidating'] = x
                 elif csvID[1] == 1:
                     df.loc[granularity, instrument]['Trending'] = x
                 df.to_csv("Data/tradeid.csv",
                           sep=',',
                           encoding='utf-8',
                           index_label="Granularity")
                 return
Ejemplo n.º 3
0
    def get_OrderList(self, ticker):
        """
        可以获得特定ticker的 Pending Order
        """
        r = orders.OrderList(accountID=self.accountID,
                             params={"instrument": ticker})

        return self.client.request(r)
Ejemplo n.º 4
0
 def test__orders_list(self, mock_get):
     """get the orders information for an account."""
     uri = 'https://test.com/v3/accounts/{}/orders'.format(accountID)
     resp = responses["_v3_accounts_accountID_orders"]['response']
     text = json.dumps(resp)
     mock_get.register_uri('GET', uri, text=text)
     r = orders.OrderList(accountID)
     result = api.request(r)
     self.assertTrue(
         len(result['orders']) == 1
         and result['orders'][0]['instrument'] == "EUR_USD")
 def isorderpending(self):
     csvID = self.getcsvID()
     orderList = orders.OrderList(accountID=self.accountID,
                                  params=self.params)
     self.client.request(orderList)
     try:
         orderIDList = [x['id'] for x in orderList.response['orders']]
         if csvID in orderIDList:
             return True
         return False
     except Exception:
         print("isorderpending error")
Ejemplo n.º 6
0
 def test__orders_list(self, mock_get):
     """get the orders for an account."""
     tid = "_v3_accounts_accountID_orders_list"
     resp, data = fetchTestData(responses, tid)
     r = orders.OrderList(accountID)
     mock_get.register_uri('GET',
                           "{}/{}".format(api.api_url, r),
                           text=json.dumps(resp))
     result = api.request(r)
     self.assertTrue(
         len(result['orders']) == len(resp['orders']) and
         result['orders'][0]['instrument'] ==
         resp['orders'][0]['instrument'])
Ejemplo n.º 7
0
def list_orders(accountID, other_args: List[str]):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="list",
        description="List order history",
    )
    parser.add_argument(
        "-s",
        "--state",
        dest="state",
        action="store",
        default="ALL",
        required=False,
        help="Select state for order list. ",
    )
    parser.add_argument(
        "-c",
        "--count",
        dest="count",
        action="store",
        default=20,
        required=False,
        help="the number of orders to retrieve ",
    )
    ns_parser = parse_known_args_and_warn(parser, other_args)
    if not ns_parser:
        return

    parameters = {}
    parameters["state"] = ns_parser.state.upper()
    parameters["count"] = ns_parser.count

    try:
        request = orders.OrderList(accountID, parameters)
        response = client.request(request)

        df = pd.DataFrame.from_dict(response["orders"])
        df = df[["id", "instrument", "units", "price", "state", "type"]]
        print(df)
        print("")

    except KeyError:
        print("No orders were found\n")
    except V20Error as e:
        # pylint: disable=W0123
        d_error = eval(e.msg)
        print(d_error["errorMessage"], "\n")
 def canorder(self):
     csvID = self.getcsvID()
     tradeList = trades.TradesList(accountID=self.accountID,
                                   params=self.params)
     orderList = orders.OrderList(accountID=self.accountID,
                                  params=self.params)
     self.client.request(tradeList)
     self.client.request(orderList)
     try:
         tradeIDList = [x['id'] for x in tradeList.response['trades']]
         orderIDList = [x['id'] for x in orderList.response['orders']]
         if csvID not in tradeIDList:
             if csvID not in orderIDList:
                 return True
         return False
     except Exception:
         print("ordernow error")
Ejemplo n.º 9
0
def order_history_request(
        order_state: str,
        order_count: int,
        accountID: str = account) -> Union[pd.DataFrame, bool]:
    """Request the orders list from Oanda.

    Parameters
    ----------
    order_state : str
        Filter orders by a specific state ("PENDING", "CANCELLED", etc.)
    order_count : int
        Limit the number of orders to retrieve
    accountID : str, optional
        Oanda account ID, by default cfg.OANDA_ACCOUNT
    """
    if accountID == "REPLACE_ME":
        console.print("Error: Oanda account credentials are required.")
        return False
    parameters: Dict[str, Union[str, int]] = {}
    parameters["state"] = order_state
    parameters["count"] = order_count

    if client is None:
        return False

    try:
        request = orders.OrderList(accountID, parameters)
        response = client.request(request)

        df_order_list = pd.DataFrame.from_dict(response["orders"])
        df_order_list = df_order_list[[
            "id", "instrument", "units", "price", "state", "type"
        ]]
        return df_order_list
    except KeyError:
        logger.exception("No orders were found")
        console.print("No orders were found\n")
        return False
    except V20Error as e:
        logger.exception(str(e))
        d_error = json.loads(e.msg)
        console.print(d_error["errorMessage"], "\n")
        return False
Ejemplo n.º 10
0
        },
        "timeInForce": "GTC",
        "instrument": "EUR_USD",
        "units": "-100",
        "type": "LIMIT",
        "positionFill": "DEFAULT"
    }
}
# r = orders.OrderCreate(accountID, data=data)
# client.request(r)
# create_order = pd.Series(r.response['orderCreateTransaction'])
# print(create_order)
"""
# 2 Get a list of open orders for an account
"""
r = orders.OrderList(accountID)
client.request(r)
account_orders_list = pd.Series(r.response['orders'][0])
print(account_orders_list)
"""
# 3 List all Pending Orders in an Account, before you cancel an order (pending order == open order)
use OrdersPending(), in lieu of the above OrderList() to cancel open orders
"""
r = orders.OrdersPending(accountID)
client.request(r)
res = r.response['orders']
last_order_id = res[0][
    'id']  # also used directly below to get details for a single order
# print(res)

display_all_pending_orders = pd.Series(
Ejemplo n.º 11
0
    def get_account_orders(cls):
        """
		Get all orders fro the account.
		"""
        r = orders.OrderList(cls.account_id)
        return cls.client.request(r)
Ejemplo n.º 12
0
def order_list(accountID, token):
    client = oandapyV20.API(access_token=token)
    r = orders.OrderList(accountID)
    request = client.request(r)
    return request
Ejemplo n.º 13
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}')
Ejemplo n.º 14
0
 def list_orders(self):
     endpoint = orders.OrderList(self.account_id)
     self.send_request(endpoint)
     return endpoint.response
Ejemplo n.º 15
0
 def orders(self):
     r = orders.OrderList(self.account_id)
     return self.api.request(r)
Ejemplo n.º 16
0
def get_order_list(account_ID: str) -> List[Dict]:
    """ Retrieve a list of open orders
    """
    r = orders.OrderList(account_ID)
    resp = client.request(r)
    return resp["orders"]
Ejemplo n.º 17
0
def OrdersOrderList(access_token, accountID):
    'Get a list of orders for an account'
    r = orders.OrderList(accountID)
    client = API(access_token=access_token)
    client.request(r)
    return readable_output(Munch(r.response)), Munch(r.response)
Ejemplo n.º 18
0
# and current_pl() < daily_take_profit and current_pl() > daily_stop_loss
while time.time() <= timeout:
    try:
        current_time = time.strftime('%Y-%m-%d %H:%M:%S')
        print("\n----- passthrough at ",
              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']
Ejemplo n.º 19
0
    def get_OrderList(self, ticker):
        
        r = orders.OrderList(accountID=self.accountID,
                             params={"instrument": ticker})

        return self.client.request(r)
Ejemplo n.º 20
0
accountID = config_trading['DataOandaAccount']
access_token = config_trading['DataOandaToken']

# Telegram Config
TOKEN = config_trading['DataTgrChatID']
chatid = config_trading['DataTgrToken']
# tb = telebot.TeleBot(TOKEN)

# Do Not Touch
pairs_traded = '%s,%s' % (str(instrument_1), str(instrument_2))
pairs_traded_dict = {instrument_1, instrument_2}

api = API(access_token=access_token, environment="practice")

stream = PricingStream(accountID=accountID, params={"instruments": pairs_traded})
orders_list = orders.OrderList(accountID)
trades_list = trades.TradesList(accountID)

current_holding = 0
df_x_ = 0
df_y_ = 0

def get_src_cls(source_name):
    return getattr(sys.modules[__name__], source_name)


class EGCointegration(Strategy):

    def __init__(self, x, y, on, col_name, is_cleaned=True):
        if is_cleaned is not True:
            x, y = EGCointegration.clean_data(x, y, on, col_name)
Ejemplo n.º 21
0
def listOrder():
    r = orders.OrderList(accountID)
    api.request(r)
    print(r.response)