How can I get a message from Binance API when my order is filled - api

I created a limit buy order.
If this buy order is filled so I open the long position, I want to create another order immediately.
So basically, I want to get a message from the Binance server when my order event is filled.
Is there any function to do so?
I am using WebSocket via the python-binance library, so it would be perfect if there is that functionality in the python-binance library.
Thank you.

You can do it by checking the order status. Below code will do the trick.
# Post a new sell order
params = {
'symbol': 'BTCUSDT',
'side': 'SELL',
'type': 'LIMIT',
'timeInForce': 'GTC',
'quantity': 0.001,
'price': sell_price
}
sell_response = spot_client.new_order(**params)
oid = sell_response['orderId']
loop_sell = True
while (loop_sell):
order_check = spot_client.get_order("BTCUSDT", orderId=oid)
order_status = order_check['status']
if order_status == "FILLED":
print("Sell Order Filled")
break
time.sleep(10)

Binance does not currently offer notifications when orders are created, canceled, or fulfilled through API.
You can do it through user streams. Below pointer may help you
https://dev.binance.vision/t/new-order-notification/2261

Related

Most Recent Coins added to CoinGecko

I am trying to get the most recently added coin added to Coingecko. Any ideas which API to use or how to achieve this.
Ideally I am trying to get this in near realtime.
Thanks
I don't think Coingecko provides a direct API to retrieve recently added coins. For your development purposes, you can definitely try web scraping.
https://www.coingecko.com/en/coins/recently_added
You can read the name of the latest coins directly from https://www.coingecko.com/en/coins/recently_added and then use CoinGecko API to search info by name.
In Python:
import requests
# get all coins listed on CoinGecko
coins = requests.get('https://api.coingecko.com/api/v3/coins/list').json()
# extract the name of the latest coins
r = requests.get('https://www.coingecko.com/it/monete/recently_added')
for line in r.text.splitlines():
if '<td class="py-0 coin-name" data-sort=' in line:
name = line[len('<td class="py-0 coin-name" data-sort=')+1:-2]
print(name)
# then search coin in the list retrieved above
for coin in coins:
if coin['name'] == name:
r = requests.get('https://api.coingecko.com/api/v3/coins/'+coin['id'])
print(r.json())

How to adjust the stock of a product tracked by lots in Odoo via API

OK so I have been banging my head at this problem for way too long by now.
I want to sync stock levels of a product that is tracked with lots between the webshop and Odoo. For this reason I need to be able to make a stock adjustment of a lot via the API (in this case in python).
I have found this possible way of doing it:
odoo(
'stock.move',
'create',
[{
"name": "Webshop stock adjustment",
"company_id": 1,
"location_id": 8, # warehouse
"location_dest_id": 14, # virtual location
"product_id": batch["product_id"][0],
"product_uom": 1,
"lot_ids": [batch["id"]], # I am searching for the id by the lot name beforehand
"product_uom_qty": 1,
"quantity_done": 1,
"state": "done"
}]
)
This, however, results in two moves! One move which has the correct lot, and another one without a specified lot. The latter move is faulty of course, as the product is tracked with lots. This results in a fault lot entry, where I can't change the quantity by hand, as the field is invalid. Worse, it results in wrong stock levels.
You can see the problematic bookings here
I have tried to just create a stock.move.line, like so:
odoo(
'stock.move.line',
'create',
[{
"company_id": 1,
"display_name": "Webshop adjustment", # does not appear
"location_id": location_id,
"location_dest_id": location_dest_id,
"product_id": batch["product_id"][0],
"product_uom_id": 1,
"lot_id": batch["id"],
"product_uom_qty": quantity,
"qty_done": quantity,
"state": "done" # has no effect
}]
)
However that results in a line with no effect: Line
I have also tried to find the stock adjustment wizard, but the only one I found in the code as opposed to the UI, doesn't have a field for lots..
I'd be happy for any input on how to solve this problem!
Meanwhile I managed to solve this problem reliably. I needed to implement a function for that, rather than mucking around with the external API.
The function here is expecting vals with the format below. It reduces whatever batch needs to go first.
[{
'sku': sku,
'qty': quantity
},]
#api.model
def reduce_lots(self, vals):
log(vals)
for product_req in vals:
product = self.env['product.product'].search(
[['default_code','=', product_req['sku']]]
)
if len(product) == 0:
continue
lots = self.env['stock.quant'].search(
['&',('product_id', '=', product[0]['id']),('on_hand', '=', True)],
order='removal_date asc'
)
move = self.env['stock.move'].create({
'name': product_req['order'],
'location_id': 8, # Our Warehouse
'location_dest_id': 14, # Virtual Location, Customer. If you need to increase stock, reverse the two numbers.
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': product_req['qty'],
})
move._action_confirm()
move._action_assign()
product_req['lots'] = []
for line in move.move_line_ids:
line.write({'qty_done': line['product_uom_qty']})
product_req['lots'].append({
'_qty': line['product_uom_qty'],
'_lot_id': line.lot_id.name,
'_best_before': line.lot_id.removal_date
})
move._action_done()
return vals

Loop a Power BI API call to pull an unknown number of records to avoid rate limit?

I am attempting to connect to Palo Alto's Cortex XDR to pull events into Power BI for analysis on Mean Time to Resolution, totals per analyst, etc. 
I am able to authenticate and pull the last 100 events. According to the documentation, there is no way to pull more than 100 per query. 
This is the query being ran. 
let
body = "{ ""request_data"": {}}",
GetJson = Web.Contents("https://api-{company}.xdr.us.paloaltonetworks.com/public_api/v1/incidents/get_incidents/",
[
Headers = [#"Content-Type" = "application/json",
#"x-xdr-auth-id" = "{API ID}",
#"Authorization" = "{API KEY}"
],
Content = Text.ToBinary(body)
]
),
FormatAsJson = Json.Document(GetJson),
#"Converted to Table" = Record.ToTable(FormatAsJson),
Value = #"Converted to Table"{0}[Value],
incidents = Value[incidents],
Result = Table.FromRecords(incidents)
in
Result
 When looking at the documentation, I notice it has a way to query specific ranges of incidents (not exceeding 100) and attempted to plug that in but was not able to pull the designated events. 
Is there a way to loop the API pull to ingest all the events without knowing the total (will be ever increasing)?

Shopify API - Can't find orders created by another application

I'm trying to find all of my store's orders, and found out that I can only received list of manually created orders, but not orders created by another applications throughout APIs.
Here my current orders list:
And here my code to find all orders
temp = ShopifyAPI::Order.find(:all, :params=>{:status => 'any', :fields => 'name'})
or find single order with order_id
order = ShopifyAPI::Order.find(show_params['order_id'])
The 1st line of code return only 1 order (#1013) created by me
[#<ShopifyAPI::Order:0x0000000c6ae170 #attributes={"name"=>"#1013"}, #prefix_options={}, #persisted=true>]
The 2nd line of code raised error:
#<ActiveResource::ResourceNotFound: Failed. Response code = 404. Response message = Not Found (Not Found).>
Note that all of my other orders except #1013 created by 3rd-application:
What should I do now to find all my orders?
Thank in advance.
P/s: I use 2020-01 api version.
By default, read_orders scope grants you access to get orders created not earlier than 60 days ago.
You have to request read_all_orders scope to be able to fetch all orders now.

Coinbase work with ethereum in stead of bitcoin

I am trying to create an ether buy and sell bot on coinbase. They have a truly wonderfull description on their developer page. There is one thing I am missing.
Somehow all functions automatically refer to bitcoin and not to ether. I assume there is a setting to change that in the code but I am not finding or succeeding in this. All examples on their developer page are with bitcoin. For example:
buy_price = client.get_buy_price(currency = 'EUR')
This returns: amount, base and currency. So I noticed I can change the currency. Now I tried to change the base with
buy_price = client.get_buy_price(currency = 'EUR', base = 'ETH')
It still returns BTC (bitcoin) as base.
Hope someone can help me out here.
Try this:
buy_price = client.get_buy_price(currency_pair = 'ETH-USD')
From https://developers.coinbase.com/api/v2#get-exchange-rates
EDIT: the Python API seems not to work. But the raw GET request works, so here's a replacement function for you:
import urllib.request
import json
def myGetBuyPrice(crypto, fiat):
ret = (urllib.request.urlopen("https://api.coinbase.com/v2/prices/"+crypto+"-"+fiat+"/buy").read()).decode("utf-8")
return json.loads(ret)["data"]
print myGetBuyPrice("ETH", "USD")