I would like to ask you for help. I´m trying to change python code from sending limit/market order to OCO order through api to binance. I can make limit order, market order, stop loss limit order. I can´t figure out how to place OCO order...
When I used limit order I was sending order_type=ORDER_TYPE_LIMIT then I used order = client.create_order() and it was working. When I wanted to send market order I used order_type=ORDER_TYPE_MARKET but when I want to make OCO order the only option that I found that should work is:
order = client.create_oco_order() without order_type but here I´m getting error 1013 Stop loss is not supported for this symbol...
I checked https://api.binance.com/api/v1/exchangeInfo
and there is this "orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,
So I can´t use order_type. There is not ORDER_TYPE_OCO and ocoAllowed is true so I should be able to send oco order. But I´m getting "error 1013: Stop loss orders are not supported for this symbol. order failed".
What I want is to set "price" as limit sell order to take profit highier when price will get there and to set stop loss "stopPrice" lower if price will go down...at once. This is how OCO should works.
Can somebody please give me an advice how to do it? I´m not python guru I´m just changing one code that I found and what I understand is if oco is allowed stop loss should be allowed too. Thanks
so that all interested have a precise answer about the solution of this problem, I include the code with the comments.
I'll use an OCO sell order as an example in BTCUSDT.
Imagine I have 1 BTC. The current price is at 30157.85 and I want to sell 1 BTC much higher at 32000.07
But the price does not rise and begins to fall, so I place my stopPrice at 29283.03 where the limit sell order will be opened at the price 29000.00
This means that I will sell at 32000.07 or 29000.00 USDT. The order is written as follows:
order= client.order_oco_sell(
symbol= 'BTCUSDT',
quantity= 1.00000,
price= '32000.07',
stopPrice= '29283.03',
stopLimitPrice= '29000.00',
stopLimitTimeInForce= 'FOK')
Note that the OCO order requires the stopLimitTimeInForce parameter. I have used the value 'FOK' but I leave you here the description of the different values that you can use: https://help.bybit.com/hc/en-us/articles/360039749233-What-are-time-in-force-TIF-GTC-IOC-FOK-
Note well that the price, stopPrice, stopLimitPrice and stopLimitTimeInForce parameters are strings and not float or decimal.
Related
Let's say I want to buy 0.072 coins of 'XMRUSDT'. And executed buy order like following:
buy_market = client.create_order(symbol='XMRUSDT', side='BUY', type='MARKET', quantity=0.072)
and
print(buy_market['executedQty']) # prints 0.072.
But if check on binance app, actually 0.071928 coins was bought not 0.072.
So when my bot decided to sell, it have to sell 0.071 not 0.072.(bceause of lot size). So 0.000928 coins being left unsellable. This issue happens all the time.
This issue happens all the time, so on my portfolio coins being left is being unsellable being stacked continuously.
Is there any way to solve this problem?
Thanks
It’a not a Python or python_binance problem. It happens so, because your tokens are not sold in one batch. When you create a buy/sell order, binance finds matching orders by rate and sells your tokens in small portions.
What you can do, is increase your bot precision to lower the amount of your leftovers
I am trying to repay a loan using the binance python API. I retrieve the loan size from the acct dictionary and input that as the quoteOrderQty in the auto repay margin order.
When I run closeLong() the loan is not paid off completely, a small balance remains in the base and a small USDT debt remains in the quote. What am I doing wrong here?
acct = client.get_isolated_margin_account()
def quoteDebt():
quoteLoan = round(Decimal(acct['assets'][1]['quoteAsset']['borrowed']),2)
print("USDT Debt: "+str(quoteLoan))
return quoteLoan
def closeLong():
client.create_margin_order(
symbol=sym,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
sideEffectType= 'AUTO_REPAY',
isIsolated='TRUE',
quoteOrderQty=quoteDebt())
print("Closed Long")
I've had the same issue. I believe it's that interest is compounded continuously, so a tiny amount of interest is incurred between you checking how much is owed and you repaying it. I hacked around this by looping indefinitely: the first loop repays the principal, the second the interest on that, the third the interest on that, and by the 4th or 5th loop the interest rounds down to 0. I'd much prefer if there were a repay_all() API call available, of course, but I'm not aware of anything like that.
Same issue here, not nice from Binance to not enable us to fully repay automatically through API. If you can lock some extra amount on this, ideal solution for me is to buy the borrowed asset on spot account, fees are paid from BNB, which is less vs. isolated margin account, transfer the asset to isolated margin account a repay (2 step approach). You need to have the reserve though, as you can't transfer all money out of margin account, when in position, as it will get liquidated.
If you try to repay isolated account directly, 0.1% fee is deducted, so the loan is not fully repaid. If buy from spot, you can pay fee as 0.075% in BNB and get the full amount of asset you asked for (as fees are paid in BNB). No tiny amounts remaining.
Ideal approach for you, is based on frequency of trades. High frequency trading - fees matters, trades are small and you can allocate extra funds to this. Low frequency trading - fees does not matter that much, you might want to go all-in, not having extra funds, and you might do this manually as well ("Close all positions" in UI), for those tiny amounts...
I'm searching for a way to apply an arbitrage algorithm across multiple exchanges, multiple currencies. and multiple trading amounts. I've seen examples of using BellmanFord and FloydWarshall, but the one's I've tried all seem to be assuming the graph data set is made up of prices for multiple currencies on one single exchange. I've tried tinkering and making it support prices across multiple exchanges but I haven't found any success.
One article I read said that I use BellmanFord and simply put only the best exchange's price in the graph (as opposed to all the exchange's prices). While it sounds like that should work, I feel like that could be missing out on value that way. Is this the right way to go about it?
And regarding multiple amounts, should I just make one graph per trade amount? So say I want to run the algorithm for $100 and for $1000, do I just literally populate the graph twice once for each set of data? The prices will be different at $100 than for $1000 so one exchange that has the best price at $100 may be different then that of the $1000 amount.
Examples:
The graph would look like this:
rates = [
[1, 0.23, 0.26, 17.41],
[4.31, 1, 1.14, 75.01],
[3.79, 0.88, 1, 65.93],
[0.057, 0.013, 0.015, 1],
]
currencies = ('PLN', 'EUR', 'USD', 'RUB')
REFERENCES:
Here is the code I've been using, but this assumes one exchange and one single trade quantity
Here is where someone mentions you can just include the best exchange's price in the graph in order to support multiple exchanges
Trying for accuracy over speed, there's a way to represent the whole order book of each exchange inside of a linear program. For each bid, we have a real-valued variable that represents how much we want to sell at that price, ranging between zero and the amount bid for. For each ask, we have a real-valued variable that represents how much we want to buy at that price, ranging between zero and the amount asked for. (I'm assuming that it's possible to get partial fills, but if not, you could switch to integer programming.) The constraints say, for each currency aside from dollars (or whatever you want more of), the total amount bought equals the total amount sold. You can strengthen this by requiring detailed balance for each (currency, exchange) pair, but then you might leave some opportunities on the table. Beware counterparty risk and slippage.
For different amounts of starting capital, you can split dollars into "in-dollars" and "out-dollars" and constrain your supply of "in-dollars", maximizing "out-dollars", with a one-to-one conversion with no limit from in- to out-dollars. Then you can solve for one in-dollars constraint, adjust the constraint, and use dual simplex to re-solve the LP faster than from scratch.
I have recently started using bt for backtesting, and after looking into the documentation, https://pmorissette.github.io/bt/bt.html, there does not seem to be a way to get the total portfolio value at each date, even though it can be easily plotted by calling the .plot() method.
I may have overlooked on my part since I am pretty new to this. Great if someone can point me in the right direction.
The library bt has various useful methods that you could use in your backtesting:
Then, assuming that res = bt.run(backtest)
You can do:
res.prices will tell you in a percentage format how your portfolio value is changing
res.backtest_list[0].strategy.outlays will tell you the outlays, which are the total dollar amount spent(gained) by a purchase(sale) of securities
res.backtest_list[0].positions will tell you the number of shares purchased
res.get_security_weights() will tell you the weight of your security in a percentage format
I'm currently trying to gain market betas from tickers gained through yahoo finance datasreader. I was wondering if there is a way to calculate each stocks market beta, and put it in a dataframe?
This is what I have for my code so far:
import pandas_datareader.data as pdr
Tickers=['SBUX','TLRY']
SD='2005-01-31'
ED='2018-12-31'
TickerW=pdr.datareader(Tickers,'yahoo',SD,ED)
TickerW.head()
Okay, to make sure we're on the same page, we use the formula and definition of market beta from here: https://www.investopedia.com/terms/b/beta.asp
Beta = Covariance(Stock Returns, Market Returns) / Variance(Market Returns)
So first of all, we need the tickers for the market as well as the tickers for the stock. Which ticker you use here depends a lot on what market you want to compare against: Total stock market? Just the S&P 500? Maybe some other international equity index? There's no 100% right answer here, but a good way to pick is think about who the "movers" of your stock are, and what other stocks they hold. (Check out Damodaran's course on valuation, free on the interwebs if you google it).
So now your question becomes: How do I compute the covariance and variance of stock returns?
First, the pandas tickers have a bunch of information. The one we want is the "Adjusted Close". That's the daily closing price of the stock, retroactively adjusted for any "special" events like stock splits, reverse splits, and dividends. Because let's say a stock trades for $1000 a pop one day, but then undergoes a 1 for 2 stock split, so now instead of 1 share for $1000, you have 2 shares for $500 each. In a "raw" price chart, it would appear as if your stock just lost 50% value in a single day when in reality nothing happened. The Adjusted Close time series takes care of that to make sure that only "real" changes to the stock's value are reflected.
You can get that by calling prices = TickerW['Adj. Close'] or whatever key yahoo finance uses these days. By just looking at the TickerW dataframe you should be able to figure that out on your own :)
Next, we'd be changing prices into returns. That's just prices.shift(1) / prices (or maybe the other way round :D consult the documentation and try it out yourself). (Nerd note: Instead of these returns, it is mathematically more sound to use the logarithmic returns, because they have certain reasonable properties. If you want, throw a "log" around the returns.
Finally, we now have a series of returns (or log returns). One series for the stock returns, one for the market returns (e.g. from SPY, for the S&P 500). Now we just need to use them in the formula for beta.
Well, the way to go here is to do what I just did: Hit up google for "pandas covariance between two series" and that gets us to https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cov.html
So basically, cov = stock_returns.cov(market_returns) and var = market_returns.var and then beta = cov / var.
I'd say that should be enough info to send you on your way. Good luck.