BinanceTradingBot | crypto trading bot , using Binance exchange | Cryptocurrency library
kandi X-RAY | BinanceTradingBot Summary
Support
Quality
Security
License
Reuse
- This method will check if the price of item is available
- buy and create position
- Determines the decline of the data
- Get position
- Retrieves a sell position
- Update the trailer based on the current exit price
- Send message to telegram
- Running the sell operator
- Determines if the indicator is above the given threshold
- Updates the account
- This will sell the price
- Process a new candlestick event
- Runs position event handler
- Populate the real time data
- Runs exit strategy
- Get the list of available positions
- Initialization method
- Retrieves the buy position
- Demonstrates how to run a chat
- Updates the balance of the account
- Read properties from the classpath
- Step 1
- Runs BuyerInStrategy
- Runs sell instructions
- Triggers sell position
- Retrieve sell position
BinanceTradingBot Key Features
BinanceTradingBot Examples and Code Snippets
Trending Discussions on Cryptocurrency
Trending Discussions on Cryptocurrency
QUESTION
COIN LIST is an array of crypto coins(["BTCUSDT",...]). I try to get the price using getPriceAction and RSI from getRSI and these two functions are working when I try to console DATA. But when I try to print the response after the completion of the loop. It prints the empty array and the length is 0 of this array. I want to store the DATA object (consisting of SYMBOL, closing price and RSI) as an element in the response array
import { COIN_LIST } from "./COIN_LIST.js";
import { getPriceAction } from "./PRICE_ACTION.js";
import { getRSI } from "./RSI.js";
async function main() {
try {
let response = await [];
await COIN_LIST.forEach((element, i) => {
setTimeout(() => {
let data = { symbol: element };
getPriceAction(element, "4h").then((res) => {
data.closingPrice = res;
getRSI(res).then((res) => {
data.RSI = res.reverse();
data.closingPrice = data.closingPrice.reverse();
response.push(data);
console.log(data)
});
});
}, i * 1000);
});
console.log(response);
} catch (error) {
console.log(error.message);
}
}
main();
ANSWER
Answered 2022-Apr-16 at 02:43After the completion of the loop, the promises didn't get resolved yet, that's why it print an empty array. One way to achieve what you need is using await for(...)
, or wait for all promises to be resolved, and then print the results.
import { COIN_LIST } from "./COIN_LIST.js";
import { getPriceAction } from "./PRICE_ACTION.js";
import { getRSI } from "./RSI.js";
async function main() {
try {
let response = []; //---> don't need that `await`
const promises = []; //---> array of promises
COIN_LIST.forEach((element, i) => {
setTimeout(() => {
let data = { symbol: element };
const promise = getPriceAction(element, "4h").then((res) => {
data.closingPrice = res;
getRSI(res).then((res) => {
data.RSI = res.reverse();
data.closingPrice = data.closingPrice.reverse();
response.push(data);
console.log(data)
});
});
promises.push(promise) //---> save the reference to a promise
}, i * 1000);
});
await Promise.all(promises) //---> await for all promises to be resolved, then print the result
console.log(response);
} catch (error) {
console.log(error.message);
}
}
main();
QUESTION
I am trying to connect my Metamask wallet to my Java Spring-Boot backend. I was trying to follow the example here. I am able to autogenerate the nonce and receive the wallet ID without a problem. I am trying to verify the signed nonce from the Wallet on the server to make sure that the sender is indeed who they say they are. However, I am unable to find any documentation on Web3J to do this.
Is web3j not the right package to use for this? The example shows how to do the verification on NodeJS based on javascript but I don't find any example on how to do this on Java.
My understanding is that the public key is the wallet ID itself and that the message is the nonce signed by the private key of the wallet which is not shared for obvious reasons. According to this, I would need to "decrypt" the message using the public key and see if the decrypted message is same as the nonce that the backend sent to Metamask to sign. Is this correct?
Here is my code to create and send the nonce to UI:
public User findUserByPublicAddress(String publicWalletId) {
User u = userRepository.findByPublicWalletId(publicWalletId);
if(u == null) {
u = new User("", "", "", null, publicWalletId, "");
String nonce = StringUtil.generateRandomAlphaNumericString();
u.setNonce(nonce);
userRepository.saveAndFlush(u);
}
return u;
}
Here, I see if the user is already in my system and if they are not, then I just create a temporary user with a random nonce generated and saved in the DB. This nonce is sent to the UI for Metamask to sign. However, I am not sure how to do the verification part of it.
ANSWER
Answered 2022-Apr-03 at 03:03I was able to figure this out finally. My initial understanding was incorrect. I was not supposed to attempt to decrypt the message to retrieve the nonce. Rather I needed to use the nonce to see if I can retrieve the public key of the private key used to sign the message and see if that public key retrieved matches the wallet ID.
The algorithm:- Receive the signed message and the wallet ID from the client
- Retrieve the nonce sent to the client with the same wallet ID
- Generate the hash of the nonce
- Generate the signature data from the message. This basically retrieves the V, R and S and. R and S are the outputs of the ECDSA Signature and V is the Recovery ID.
- Using the ECDSA Signature and Hash of the Nonce, generate the possible public Key that was used to sign the message. At max, one will be able to generate 4 possible public keys for this message.
- Check if any of the generated keys match public wallet ID that the client sent. If it matches, then we have a positive match. Generate the JWT and respond to the client. If not, we know that the nonce was not signed by the Metamask wallet we expected.
Here is a sample code for UI (JavaScript and HTML):
web3.eth.sign(
web3.utils.sha3(nonce),
window.userWalletAddress)
.then((message) => {
console.log(message)
data['message'] = message // BODY
var xmlReq = new XMLHttpRequest();
xmlReq.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
response = this.responseText
console.log(response)
}
};
xmlReq.open("POST", "/api/users/login", true)
xmlReq.setRequestHeader('Content-Type', 'application/json')
xmlReq.send(JSON.stringify(data))
})
The web3.eth.sign() takes the message to be signed and takes the wallet ID that is signing it. This is then sent to the backend. In the backend:
public User signin(UserLoginDTO loginDetails, HttpServletResponse response) {
try {
// Get the wallet ID and signed message from the body stored in the DTO
String publicWalletId = loginDetails.getPublicWalletId();
String message = loginDetails.getMessage();
// Find the nonce from the DB that was used to sign this message
User user = userRepository.findByPublicWalletId(publicWalletId);
String nonce = user.getNonce();
// Generate the HASH of the Nonce
byte[] nonceHash = Hash.sha3(nonce.getBytes()) // org.web3j.crypto.Hash
// Generate the Signature Data
byte[] signatureBytes = Numeric.hexStringToByteArray(message); // org.web3j.utils.Numeric
byte v = (byte) ((signatureBytes[64] < 27) ? (signatureBytes[64] + 27) : signatureBytes[64]);
byte[] r = Arrays.copyOfRange(signatureBytes, 0, 32);
byte[] s = Arrays.copyOfRange(signatureBytes, 32, 64);
SignatureData signatureData = new SignatureData(v, r, s); // org.web3j.crypto.Sign.SignatureData
// Generate the 4 possible Public Keys
List recoveredKeys = new ArrayList<>();
for(int i = 0; i < 4; i++) {
BigInteger r = new BigInteger(1, signatureData.getR());
BigInteger s = new BigInteger(1, signatureData.getS());
ECDSASignature ecdsaSignature = new ECDSASignature(r, s);
BigInteger recoveredKey = Sign.recoverFromSignature((byte)i, ecdsaSignature, nonceHash);
if(recoveredKey != null) {
recoveredKeys.add("0x" + Keys.getAddressFromKey(recoveredKey)); // org.web3j.crypto.Keys
}
}
// Check if one of the generated Keys match the public wallet ID.
for(String recoveredKey : recoveredKeys) {
if(recoveredKey.equalsIgnoreCase(publicWalletId)) {
// Add Code here to create the JWT and add that to your HttpServletResponse. Not shown here.
return user;
}
}
throw new CustomException("Message Sign Invalid", HttpStatus.UNAUTHORIZED);
}
catch (Exception ex) {
// Custom Error Handling.
}
}
QUESTION
status: 400, error code: -1013, error message: Filter failure: PRICE_FILTER
I am trying to create a new order to sell all SCRT
that are on my account and I cannot figure out what is the problem.
The filters for SCRTBUSD
are:
{'filterType': 'PRICE_FILTER', 'minPrice': '0.00100000', 'maxPrice': '1000.00000000', 'tickSize': '0.00100000'}
The code I am using:
client = Spot(key=key, secret=secret)
account = client.account()
for asset in account['balances']:
if asset['asset'] == 'SCRT':
quantity = asset['free']
break
# price = client.ticker_price('SCRTBUSD')['price']
price = client.avg_price('SCRTBUSD')['price']
params = {
"symbol": 'SCRTBUSD',
"side": "SELL",
"type": "LIMIT",
"timeInForce": "GTC",
"quantity": quantity,
"price": round(float(price) * float(quantity), 8)
}
try:
response = client.new_order(**params)
except ClientError as error:
print(f"Found error. status: {error.status_code}, error code: {error.error_code}, error message: {error.error_message}")
The final price (round(float(price) * float(quantity), 8)
) is 30.68230251
.
I have also thought that maybe by "price" they mean a price for 1 BUSD
and I put the "price": float(price)
and I have got the same error.
I tried both avg_price and ticker_price. Any ideas on how to set the right price?
ANSWER
Answered 2022-Mar-16 at 20:14tickSize
for SCRTBUSD
is: 0.001.
Therefore, you have to round the quantity to the next 0.001. For example:
round(30.68230251, 3)
For more information about the tickSize
, check the exchangeInfo on the Binance API documentation.
QUESTION
How does one parse the data in an SPL token account? It contains a binary blob and I'd like to get the token type and number of tokens.
An acceptable language is solana-cli, web3.js, or solana.py. I'm looking for any solution.
ANSWER
Answered 2022-Mar-15 at 03:45The RPC give a great way to parse the data by default. You can use getParsedAccountInfo
in web3.js.
Let's take the token account at 9xqnnfeonbsEGSPgF5Wd7bf9RqXy4KP22bdaGmZbHGwp
import { Connection, PublicKey, ParsedAccountData, clusterApiUrl } from '@solana/web3.js';
(async () => {
const connection = new Connection(clusterApiUrl('mainnet-beta'));
const tokenAccount = await connection.getParsedAccountInfo(new PublicKey('9xqnnfeonbsEGSPgF5Wd7bf9RqXy4KP22bdaGmZbHGwp'));
console.log((tokenAccount.value?.data as ParsedAccountData).parsed);
})();
/**
{
info: {
isNative: false,
mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
owner: 'Ccyrkw1FdRVsfnt7qptyUXqyffq3i59GSPN1EULqZN6i',
state: 'initialized',
tokenAmount: {
amount: '738576212',
decimals: 6,
uiAmount: 738.576212,
uiAmountString: '738.576212'
}
},
type: 'account'
}
**/
Here we can see the output of the tokenAccount has a mint of EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
(USDC) owned by address Ccyrkw1FdRVsfnt7qptyUXqyffq3i59GSPN1EULqZN6i
with an amount of 738.576212
. That's all the data we need from a token account.
QUESTION
I'm having issues with plotting the Coral Trend indicator colour code, into my 15min 21EMA security function. Since the Coral Trend indicator colour code has a mutable variable, I cannot resolve it. This is next level coding for me, haha.
I will post
- the code
- a screenshot
- the problem
- the solution I tried
The code:
//@version=5
indicator(title='CT Indi', shorttitle='', overlay=true)
sm = input(21, title='Smoothing Period')
cd = input(0.4, title='Constant D')
di = (sm - 1.0) / 2.0 + 1.0
c1 = 2 / (di + 1.0)
c2 = 1 - c1
c3 = 3.0 * (cd * cd + cd * cd * cd)
c4 = -3.0 * (2.0 * cd * cd + cd + cd * cd * cd)
c5 = 3.0 * cd + 1.0 + cd * cd * cd + 3.0 * cd * cd
i1 = 0.0
i1 := c1 * request.security(syminfo.tickerid, "15", close) + c2 * nz(i1[1])
i2 = 0.0
i2 := c1 * i1 + c2 * nz(i2[1])
i3 = 0.0
i3 := c1 * i2 + c2 * nz(i3[1])
i4 = 0.0
i4 := c1 * i3 + c2 * nz(i4[1])
i5 = 0.0
i5 := c1 * i4 + c2 * nz(i5[1])
i6 = 0.0
i6 := c1 * i5 + c2 * nz(i6[1])
bfr = -cd * cd * cd * i6 + c3 * i5 + c4 * i4 + c5 * i3
bfrC = bfr > nz(bfr[1]) ? color.white : bfr < nz(bfr[1]) ? #056656 : na
plot(request.security(syminfo.tickerid, "1", ta.ema(close, 315)), title='15m 21 EMA', color=bfrC, linewidth=2)
The screenshot:
The problem:
As can be seen in the screenshot on the 15min timeframe (right bottom): the 21 EMA is plotted and changes colour according to the rules in the code. This is great! Now I want to take it to other timeframes (especially lower ones). On the top and left bottom we find the 5min and 10min chart. The 15min 21 EMA is plotted there, but the colour changes is not the same as on the 15min timeframe. It takes over the information of the current timeframe (thus here 5min and 10min). How do I get to cycle a mutable variable in to a security function in to a colour boolean?
The solution I tried:
So I thought if I would take the line that creates the colour switch, and put it into a security function as well, things would work:
plot(request.security(syminfo.tickerid, "1", ta.ema(close, 315)), title='15m 21 EMA', color=request.security(syminfo.tickerid, "15", bfrC), linewidth=2)
But then I get the 'Cannot use a mutable variable as an argument.....' comment. Seems like a function() =>
should be used. But how do I use this for that colour boolean?
UPDATE
When I copy this code from the answers into Pinescript I get a regular 21 EMA for the specific time frame, and the colouring is not as wanted (15min).
I made some progress on my own. But I'm stuck on spaces in between. Here is the code:
//@version=5
indicator(title='CT Indi', shorttitle='', overlay=true)
sm = input(21, title='Smoothing Period')
cd = input(0.4, title='Constant D')
di = (sm - 1.0) / 2.0 + 1.0
c1 = 2 / (di + 1.0)
c2 = 1 - c1
c3 = 3.0 * (cd * cd + cd * cd * cd)
c4 = -3.0 * (2.0 * cd * cd + cd + cd * cd * cd)
c5 = 3.0 * cd + 1.0 + cd * cd * cd + 3.0 * cd * cd
i1_func() =>
i1 = 0.0
i1 := c1 * request.security(syminfo.tickerid, "15", close) + c2 * nz(i1[1])
i2_func() =>
i2 = 0.0
i2 := c1 * i1_func() + c2 * nz(i2[1])
i3_func() =>
i3 = 0.0
i3 := c1 * i2_func() + c2 * nz(i3[1])
i4_func() =>
i4 = 0.0
i4 := c1 * i3_func() + c2 * nz(i4[1])
i5_func() =>
i5 = 0.0
i5 := c1 * i4_func() + c2 * nz(i5[1])
i6_func() =>
i6 = 0.0
i6 := c1 * i5_func() + c2 * nz(i6[1])
bfr = -cd * cd * cd * request.security(syminfo.tickerid, "15", i6_func()) + c3 * request.security(syminfo.tickerid, "15", i5_func()) + c4 * request.security(syminfo.tickerid, "15", i4_func()) + c5 * request.security(syminfo.tickerid, "15", i3_func())
b1 = bfr > nz( bfr[1] )
b2 = bfr < nz( bfr[1] )
bfrC = b1 ? color.white : b2 ? #056656 : na
plot(request.security(syminfo.tickerid, "1", ta.ema(close, 315)), title='15m 21 EMA', color=bfrC, linewidth=2)
ANSWER
Answered 2022-Feb-28 at 20:23You have to use the request.security()
function in global scope, and only then use it.
You can do something like this:
//@version=5
indicator(title='CT Indi', shorttitle='', overlay=true)
myTickerClose = request.security(syminfo.tickerid, "15", close)
sm = input(21, title='Smoothing Period')
cd = input(0.4, title='Constant D')
di = (sm - 1.0) / 2.0 + 1.0
c1 = 2 / (di + 1.0)
c2 = 1 - c1
c3 = 3.0 * (cd * cd + cd * cd * cd)
c4 = -3.0 * (2.0 * cd * cd + cd + cd * cd * cd)
c5 = 3.0 * cd + 1.0 + cd * cd * cd + 3.0 * cd * cd
i1 = 0.0
i1 := c1 * myTickerClose + c2 * nz(i1[1])
i2 = 0.0
i2 := c1 * i1 + c2 * nz(i2[1])
i3 = 0.0
i3 := c1 * i2 + c2 * nz(i3[1])
i4 = 0.0
i4 := c1 * i3 + c2 * nz(i4[1])
i5 = 0.0
i5 := c1 * i4 + c2 * nz(i5[1])
i6 = 0.0
i6 := c1 * i5 + c2 * nz(i6[1])
bfr = -cd * cd * cd * i6 + c3 * i5 + c4 * i4 + c5 * i3
bfrC = bfr > nz(bfr[1]) ? color.white : bfr < nz(bfr[1]) ? #056656 : na
ema21 = ta.ema(myTickerClose, 21)
plot(ema21, title='15m 21 EMA', color=bfrC, linewidth=2)
QUESTION
I am working with the Binance API. I am connecting to their API and trying to assess if Binance has a list of assets on their platform or not. The list of assets is seen below:
assets = ['tribe', 'pax']
I pass this through to their API by inserting the name of the assets into the SOCKET link:
SOCKET = f"wss://stream.binance.com:9443/ws/{asset}usdt@ticker"
I know the asset does exist on their website if on_message is called, because then I have accomplished a consistent connection with their API and it will keep printing messages unless I close the connection (which I do). However, if no message is received in n time I know they do not have the asset I am looking for. In this case Binance does have tribe, but not pax. I want to close the connection if the asset is not on their website after n time, how do I do this?
import ssl
import websocket
def on_open(ws):
print('connection: successful')
def on_close(ws, *args):
print('connection: lost')
print("---------------------------------------------------")
ws.close()
def on_message(ws, message):
print("message received")
print()
ws.close()
def on_error(ws, message):
print(message)
print()
assets = ['tribe', 'pax']
for asset in assets:
print(asset)
SOCKET = f"wss://stream.binance.com:9443/ws/{asset}usdt@ticker"
ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message,
on_error=on_error)
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
I have attempted to write:
if on_message == False:
ws.close()
however this does not work because on_message is not even being called as far as my knowledge goes.
Here is the Binance API documentation: https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams Here is the websocket-client documentation: https://websocket-client.readthedocs.io/en/latest/examples.html
ANSWER
Answered 2021-Sep-21 at 14:37Try this:-
import websocket
import ssl
import time
from threading import Thread
class Binance():
def __init__(self, asset, timeout=5):
self.url = f'wss://stream.binance.com:9443/ws/{asset}usdt@ticker'
self.ws = None
self.mr = False
self.timeout = timeout
def start(self):
self.ws = websocket.WebSocketApp(self.url, on_message=self.on_message)
Thread(target=self.monitor).start()
self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
def on_message(self, ws, message):
self.mr = True
print(message)
def stop(self):
if self.ws:
self.ws.close()
self.ws = None
def monitor(self):
while True:
time.sleep(self.timeout)
if not self.mr:
self.stop()
break
self.mr = False
def runner(asset):
Binance(asset).start()
for asset in ['pax', 'tribe']:
Thread(target=runner, args=(asset,)).start()
QUESTION
I am looking to work with ETH tokens on the Polygon network. My aim is to build a simple payment splitting application. Primarily to split royalties from Opensea. The issue I have come across is that Opensea doesn't seem to pay royalties in Matic token, instead, royalties are paid in ETH (plus other tokens).
I understand how to handle the network native, Matic, as well as ERC20 tokens. My main question is, what token type is ETH on the Polygon network? Is it an ERC20 (or similar) used to represent ETH on Polygon or does it have a special token type and privileges by virtue of Polygon being a layer two solution for Ethereum?
I'm sorry if this is a basic question, I tried to find answers online but because of the keywords all of the results were about bridging ETH to Polygon.
ANSWER
Answered 2022-Feb-11 at 10:55Opensea uses WETH token on Polygon, which is an ERC-20 token representing the Ethereum mainnet ETH.
Please note, the "purple" Polygon ETH you see on OpenSea, is actually WETH (Wrapped Ether) on the blockchain level of Polygon.
Source: https://support.opensea.io/hc/en-us/articles/4403264773523-How-do-I-find-my-funds-on-Polygon-
QUESTION
I am having an issue related to validating cryptocurrency wallet addresses, specifically USDT.
USDT can be validated either as a BTC or ETH address, depending on the network type.
Basically it goes like that:
- If cryptocurrency is USDT and chain type is ERC20, validate the address against ETH address format.
- If cryptocurrency is USDT and wallet type is OMNI, validate the address against BTC address format.
I haven't managed to find a specific validation for USDT:TRC20 addresses and I am not sure how to validate them.
ANSWER
Answered 2021-Oct-15 at 06:32trc20 address features:
An encoded Mainnet address begins with T and is 34 bytes in length.
information source : https://medium.com/tron-foundation/tron-developer-guide-account-2446633a750
QUESTION
General NFT question, but don't flame me, I really tried to find the answer.
Could NFT be created from the same image or copy of this image?
For example, take this NFT Lion Cat that I created: https://rarible.com/token/0x60f80121c31a0d46b5279700f9df786054aa5ee5:1200950?
Can someone download the image and create an NFT from it?
I mean, isn't it part of the idea that this is original content by me and I have the copyrights for it?
In the Image area, you got the RAW image that proves you took this picture, nobody but the photographer has this RAW image. But to create this image NFT I didn't have to provide it.
ANSWER
Answered 2022-Feb-06 at 09:02Could NFT be created from the same image or copy of this image?
Can someone download the image and create an NFT from it?
Yes to both questions. It is technically possible to create multiple NFTs that all represent the same image. They can be placed in the same collection, as well as across multiple collections.
As NFTs basically contain links to this image, it's not possible to prevent someone from creating a link to a public resource, i.e. from creating another NFT representing the same image.
I mean, isn't it part of the idea that this is original content by me and I have the copyrights for it?
The ERC-721 standard mostly defines just the technical specifications. But it doesn't really cover the licensing, ownership/authorship of the underlying resource, and other non-technical topics.
An NFT only proves ownership of the token - not copyrights of the image. Also, it proves ownership by an address - not by a person. Because there can be zero to multiple people holding a private key to the same address (holding the NFT representing the image).
QUESTION
import mplfinance as mpf
import talib as ta
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
test=df
WMA20 = ta.WMA(test['close'], timeperiod=20)
WMA60 = ta.WMA(test['close'], timeperiod=60)
WMA100 = ta.WMA(test['close'], timeperiod=100)
WMA200 = ta.WMA(test['close'], timeperiod=200)
# Set buy signals if current price is higher than 50-day MA
test['Buy'] = (test['close'] > WMA20) & (test['close'].shift(1) <= WMA20)
#plot
tcdf =test[['close']]
tcdf=tcdf.reset_index()
tcdf['date'] = tcdf['date'].apply(lambda x: x.value)
for i in range(len(test['Buy'])):
if test['Buy'][i]==True:
apd = mpf.make_addplot(tcdf.iloc[i],type='scatter',markersize=20,marker='o')
mpf.plot(test,addplot=apd, type='candle',volume=True)
I run this code and get this eror ---> 33 mpf.plot(test,addplot=apd, type='candle',volume=True) ValueError: x and y must be the same size
how I can fix it
tcdf:
date close
0 1597622400000000000 16.560
1 1597708800000000000 16.120
2 1597795200000000000 15.834
3 1597881600000000000 17.842
4 1597968000000000000 16.387
5 1598054400000000000 18.936
6 1598140800000000000 18.170
7 1598227200000000000 18.074
8 1598313600000000000 17.023
9 1598400000000000000 17.322
10 1598486400000000000 17.649
11 1598572800000000000 18.294
test:
time open high low close volume year month day hour Day_of_week Buy BelowMA
date
2020-08-17 00:00:00 15.499 16.956 15.228 16.560 1297237.309 2020 8 17 0 0 False False
2020-08-18 00:00:00 16.560 17.578 16.010 16.120 968575.523 2020 8 18 0 1 False False
2020-08-19 00:00:00 16.119 17.080 15.465 15.834 987213.085 2020 8 19 0 2 False False
2020-08-20 00:00:00 15.825 17.949 15.807 17.842 915874.788 2020 8 20 0 3 False False
2020-08-21 00:00:00 17.842 19.854 16.361 16.387 2428489.231 2020 8 21 0 4 False False
2020-08-22 00:00:00 16.368 19.191 15.623 18.936 1969925.069 2020 8 22 0 5 False False
2020-08-23 00:00:00 18.935 19.757 17.715 18.170 1223037.344 2020 8 23 0 6 False False
2020-08-24 00:00:00 18.187 19.467 17.900 18.074 835648.518 2020 8 24 0 0 False False
2020-08-25 00:00:00 18.068 18.261 16.132 17.023 1116590.644 2020 8 25 0 1 False False
2020-08-26 00:00:00 17.023 18.040 16.837 17.322 1003044.736 2020 8 26 0 2 False False
2020-08-27 00:00:00 17.324 18.200 16.420 17.649 1141649.079 2020 8 27 0 3 False False
... .
I dont know why I get this eror
this line for error real number
tcdf['date'] = tcdf['date'].apply(lambda x: x.value)
when it is not exist i get error must be real number, not Timestamp
ANSWER
Answered 2022-Jan-28 at 12:35The problem is you are calling make_addplot()
with only one data point at a time. There is also no need for the date index in the make_addplot()
call; only the data.
Also, the length of data (number of rows) passed into make_addplot()
must be the same as the length (number of rows) pass into plot()
.
make_addplot()
should not be within the loop.
Try replacing this part of the code:
tcdf =test[['close']]
tcdf=tcdf.reset_index()
tcdf['date'] = tcdf['date'].apply(lambda x: x.value)
for i in range(len(test['Buy'])):
if test['Buy'][i]==True:
apd = mpf.make_addplot(tcdf.iloc[i],type='scatter',markersize=20,marker='o')
with the following:
tcdf = test['close'].copy()
for i in range(len(test['Buy'])):
if not test['Buy'].iloc[i]:
tcdf.iloc[i] = float('nan')
apd = mpf.make_addplot(tcdf,type='scatter',markersize=20,marker='o')
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install BinanceTradingBot
You can use BinanceTradingBot like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the BinanceTradingBot component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page