def cancel_all_OrdersPending(self, ordertype, long_short=None): """ 撤销全部挂单 ordertype: LIMIT,STOP,MARKET_IF_TOUCHED, buy_sell: LONG, SHORT """ rv = self.get_OrdersPending() rv = [ dict(id=i.get('id'), units=i.get('units')) for i in rv['orders'] if i['type'] in ordertype and i.get('units') ] if long_short is 'LONG': idsToCancel = [ order.get('id') for order in rv if float(order['units']) > 0 ] elif long_short is 'SHORT': idsToCancel = [ order.get('id') for order in rv if float(order['units']) < 0 ] elif long_short is None: idsToCancel = [order.get('id') for order in rv] for orderID in idsToCancel: r = orders.OrderCancel(accountID=self.accountID, orderID=orderID) rv = self.client.request(r)
def cancel_pending_order(order_id): """ Cancels the selected pending order. """ order_cancel = (orders.OrderCancel(accountID=accID, orderID=order_id)) client.request(order_cancel) return order_cancel.response
def cancel_pending_orders(self, date=None): """ Cancels the pending limit orders. If a date specified, cancels the orders before that date. Returns the IDs of the canceled orders. """ # Retrieving orders. r = orders.OrdersPending(self.accountID) pending_orders = self.client.request(r) limit_orders = [ order for order in pending_orders['orders'] if order['type'] == 'LIMIT' ] if date: orders_id = [ x['id'] for x in limit_orders if parser.parse(x['createTime']).replace(tzinfo=None) <= date ] else: orders_id = [x['id'] for x in limit_orders] # Canceling orders. for _id in orders_id: r = orders.OrderCancel(self.accountID, orderID=_id) self.client.request(r) print('{} order(s) canceled.'.format(len(orders_id))) return orders_id
def cancel_pending_order_request(orderID: str, accountID: str = account) -> Union[str, bool]: """Request cancellation of a pending order. Parameters ---------- orderID : str The pending order ID to cancel. 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 if client is None: return False try: request = orders.OrderCancel(accountID, orderID) response = client.request(request) order_id = response["orderCancelTransaction"]["orderID"] return order_id except V20Error as e: d_error = json.loads(e.msg) console.print(d_error["errorMessage"], "\n") return False
def oanda_cancel(self, market, orderid): request = orders.OrderCancel(accountID=self.oanda_account_id, orderID=orderid) try: cancel_result = self.oanda.request(request) except V20Error as e: cancel_result = 'unknown order' return cancel_result
def cancel_pending_order(accountID, other_args: List[str]): parser = argparse.ArgumentParser( add_help=False, prog="cancel", description="Cancel Pending Order ", ) parser.add_argument( "-i", "--id", dest="orderID", action="store", type=str, help="The pending order ID to cancel ", ) if other_args: if "-" not in other_args[0]: other_args.insert(0, "-i") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return try: request = orders.OrderCancel(accountID, ns_parser.orderID) response = client.request(request) order_id = response["orderCancelTransaction"]["orderID"] print(f"Order {order_id} canceled.") print("") except V20Error as e: # pylint: disable=W0123 d_error = eval(e.msg) print(d_error["errorMessage"], "\n")
def cancelorder(self): csvID = self.getid(self.granularity, self.instrument) orderID = csvID[0] orderCancel = orders.OrderCancel(accountID=self.accountID, orderID=orderID) self.client.request(orderCancel) self.resetid(self.granularity, self.instrument) print("\n", orderCancel.response, "\n")
def cancel_single_order(account_ID: str, order_ID: str) -> None: """ Cancel a single open order. Args: account_ID (str): [description] order_ID (str): [description] """ r = orders.OrderCancel(accountID=account_ID, orderID=order_ID) client.request(r)
def cancel_all_TAKE_PROFIT_order(self): rv = get_OrdersPending() idsToCancel = [ order.get('id') for order in rv['orders'] if order.get('type') == "TAKE_PROFIT" ] for orderID in idsToCancel: r = orders.OrderCancel(accountID=accountID, orderID=orderID) rv = self.client.request(r)
def cancel_all_TSTOrder(self, ticker, ordertype): rv = self.get_OrderList(ticker) idsToCancel = [order.get('id') for order in rv['orders'] if order['type'] in ordertype] for orderID in idsToCancel: r = orders.OrderCancel(accountID=self.accountID, orderID=orderID) rv = self.client.request(r)
def cancel_stop_loss(self, product_code, order_id): req = orders.OrderCancel(accountID=self.account_id, orderID=order_id) try: resp = self.client.request(req) logger.info(f'action=send_order resp={resp}') return True except V20Error as e: logger.error(f'action=send_order error={e}') return False
def cancel_all_orders(account_ID: str) -> None: """ Cancel all open orders Args: accountID (String): account ID """ order_list = get_order_list(account_ID) for order in order_list: r = orders.OrderCancel(accountID=account_ID, orderID=order["id"]) client.request(r)
def cancel_all_TSTOrder(self, ticker, ordertype): """ 撤销全部 止盈, 止损, 追踪止损 ordertype: TAKE_PROFIT, STOP_LOSS, TRAILING_STOP_LOSS """ rv = self.get_OrderList(ticker) idsToCancel = [ order.get('id') for order in rv['orders'] if order['type'] in ordertype ] for orderID in idsToCancel: r = orders.OrderCancel(accountID=self.accountID, orderID=orderID) rv = self.client.request(r)
def test__order_cancel(self, mock_get): """cancel an order.""" orderID = "2307" tid = "_v3_accounts_accountID_order_cancel" resp, data = fetchTestData(responses, tid) r = orders.OrderCancel(accountID, orderID=orderID) mock_get.register_uri('PUT', "{}/{}".format(api.api_url, r), text=json.dumps(resp)) result = api.request(r) result = result["orderCancelTransaction"] self.assertTrue(result['orderID'] == orderID and result['reason'] == "CLIENT_REQUEST" and result['type'] == "ORDER_CANCEL")
def cancel_all_pending_orders(): r = orders.OrdersPending(accountID) api.request(r) pending_orders = r.response pending_orders_ids = [i["id"] for i in pending_orders["orders"]] for i in pending_orders_ids: r = orders.OrderCancel(accountID=accountID, orderID=i) api.request(r) return print("All orders were cancelled") #fire_up(acc_id= accountID, access_t= access_token) # DATA FEED FUNCTIONAL, DATA HAVE TO BE CHACKED THO #cancel_all_pending_orders() #aktualizovane 12.4. na mac cesty
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}')
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'] for order in open_orders: r = orders.OrderCancel(accountID=ACCOUNT_ID, orderID=order['id']) api.request(r)
'instrument': 'USD_JPY', 'units': '+10000', 'type': 'STOP' } } o = orders.orderCreate(accountID, data=order_data) api.request(o) o.response #--------------------------- # 保留中のオーダー情報を取得する #--------------------------- c = orders.OrderPending(accountID) api.request(c) c.response #--------------------------- # オーダーの詳細を取得する #--------------------------- c = orders.OrderDetails(accountID, orderID='133') api.request(c) c.response #--------------------------- # オーダーをキャンセルする #--------------------------- c = orders.OrderCancel(accountID, orderID='18') api.request(c) c.response
api.request(r) # In[6]: # ドル円が109.650で1万通貨売りの指値注文をAPI経由でやってみる data = { "order": { "price": "112.800", "instrument": "USD_JPY", "units": "-10000", "type": "LIMIT", "positionFill": "DEFAULT" } } # In[7]: # 全てのペンディング注文を取得する r = orders.OrdersPending(accountID) api.request(r) # In[8]: # 注文をキャンセル r = orders.OrderCancel(accountID=accountID, orderID=13) api.request(r) # In[ ]: # In[ ]:
} } r = orders.OrderReplace(accountID=accountID, orderID=last_order_id, data=replacement_order_data) client.request(r) print(r.response) # store lastTransactionID here because it will be used below for cancellation last_order_id = r.response['lastTransactionID'] """ # 6 Cancel a pending Order in an Account. """ client.request(r) r = orders.OrderCancel(accountID=accountID, orderID=last_order_id) # taken from above print(r.response) """ # 7 Execute A Market Order """ market_order_data = { "order": { "units": "100", "instrument": "GBP_USD", "timeInForce": "FOK", "type": "MARKET", "positionFill": "DEFAULT" }, } r = orders.OrderCreate(accountID, data=market_order_data)
def cancel_pending_order(cls, order_id): """ Cancel a specific pending order by informed order_id """ r = orders.OrderCancel(accountID=cls.account_id, orderID=order_id) print cls.client.request(r)
} }) res = api.request(deal_order) limit_time = 5 start = time.time() at = api.request(opentrades_req) while len(at['trades']) <= len(bt['trades']) and not ( time.time() - start) > limit_time: at = api.request(opentrades_req) if (time.time() - start) > limit_time: #注文が通らなかった print('注文が通らなかった') r = orders.OrdersPending(accountID) api.request(r) cancel_req = orders.OrderCancel( accountID=accountID, orderID=r.response['orders'][0]['id']) api.request(cancel_req) time.sleep(5) break #注文が通った print('注文が通った', price) bt = at #指値が通るのを待つ limit_time = 60 * 60 * 4 start = time.time() at = api.request(opentrades_req) while len(at['trades']) >= len(bt['trades']) and not ( time.time() - start) > limit_time: at = api.request(opentrades_req)
def cancel_order(self, order_id): logging.info(f'Cancelling order id: {order_id}') r = orders.OrderCancel(accountID=self.account_id, orderID=order_id) RUNNING_ENV.api.request(r) logging.info(r.response)
def OrdersOrderCancel(access_token, accountID, orderID): 'Cancel a pending Order in an Account.' r = orders.OrderCancel(accountID=accountID, orderID=orderID) client = API(access_token=access_token) client.request(r) return readable_output(Munch(r.response)), Munch(r.response)
def cancel_order(self, order_id): endpoint = orders.OrderCancel(self.account_id, order_id) self.send_request(endpoint) return endpoint.response
def cancel(accountID, orderID): r = orders.OrderCancel(accountID, orderID) api.request(r) print (r.response) return (r.response)
def cancel_orders(orderIDs): for i in orderIDs: r = orders.OrderCancel(account_id, i) client.request(r)
def cancel_order(accountID, token, orderID): client = oandapyV20.API(access_token=token) r = orders.OrderCancel(accountID=accountID, orderID=orderID) request = client.request(r) return request