I want to detect multiple type of flag patterns from the Stock market the first one that I want to identify is the Bull Flag Pattern. I have tried some formula's but they all missed the point and gave me lot of stock name which did not have the pattern.
In the recent way I did
find the continuous rise and then check that the following values are lying between the mean of the continuous rise.
I'm also wondering if I plot this data in graph using matplot or plotly and then apply machine learning to it will that be a solution or not.
The code to get the data is as below
from pprint import print
from nsepy import get_history
from datetime import date
from datetime import datetime, timedelta
import matplotlib
from nsetools import Nse
nse = Nse()
old_date=date.today()-timedelta(days=30)
for stock in nse.get_stock_codes():
print("Stock",stock)
stock_data = get_history(symbol=stock,
start=date(old_date.year,old_date.month,old_date.day),
end=date(datetime.now().year,datetime.now().month,datetime.now().day)))
Any help will be useful. Thanks in advance.
Bull flag pattern matcher for your pattern day trading code
Pseudocode:
Get the difference between the min() and max() close price over the last n=20 timeperiods, here called flag_width. Get the difference between the min() and max() close price over the last m=30 timeperiods, here called poll_height.
When the relative gain percentage between poll_height and flag_width is over some massive threshold like (thresh=0.90) then you can say there is a tight flag in the last n=20 timeperiods, and a tall flag pole on period -20 to -30.
Another name for this could be: "price data elbow" or "hokey stick shape".
macd does a kind of 12,26 variation on this approach, but using 9,12,26 day exponential moving average.
Code Jist:
#movingMax returns the maximum price over the last t=20 timeperiods
highest_close_of_flag = movingMax(closeVector, 20);
lowest_close_of_flag = movingMin(closeVector, 20);
#movingMin returns the minimum price over the last t=20 timeperiods
highest_close_of_poll = movingMax(closeVector, 30);
lowest_close_of_poll = movingMin(closeVector, 30);
#We want poll to be much longer than the flag is wide.
flag_width = highest_close_of_flag - lowest_close_of_flag;
poll_height = highest_close_of_poll - lowest_close_of_poll;
# ((new-old)/old) yields percentage gain between.
bull_flag = (poll_height - flag_width ) ./ flag_width;
#Filter out bull flags who's flagpole tops go too high over the flapping flag
bull_flag -= (highest_close_of_poll -highest_close_of_flag ) ./ highest_close_of_flag;
thresh = 0.9;
bull_flag_trigger = (bull_flag > thresh);
bull_flag_trigger interpretation
A whale (relatively speaking) bought a green candle flagpole by aggressively hitting bids, or covering a prior naked short position via market options from timeperiod -30 to -20. The fish fought over the new higher price in a narrow horizontal band from timeperiod -20 to 0 at the top of the range.
The bull flag pattern is one of the most popular false flags, because it's so good, which means the other end of your trade spent money to paint that structure, so that you would happily scoop up their unwanted distribution of scrip at a much higher price, and now you're bag-holding a scrip at an unrealistic price that nobody wants to buy. You are playing a game of Chess/Checkers against very strong AI designed by corporations who pull trillions of dollars per year out of this constant sum game, and your losses are their gains make your time.
Drawbacks to this approach:
This approach doesn't take into account other desirable properties of a bull flags, such as straightness of the poll, high volume in the poll or flag, gain in trading range in the poll, the squareness/triangularness/resonant sloped-ness of the flag, or 10 other variations on what cause people with lots of money to a pattern day trade on appearance of this arbitrary structure. This is financial advice, you will lose all of your money to other people who can write better AI code in skyscrapers who get $1*10^9 annual pay packages in exchange for isolated alpha with math proofs and code demos.
Bull Flag Pattern is a pattern that is visible after plotting the chart. This pattern is hard to find at the data level.
According to me finding pattern in an image using Deep Learning(object detection) is a better choice. By doing so you can find other types of patterns also such as Bearish Flag, etc.
Related
As far as I am aware the only way to create a new futures order is with client.futures_create_order(). The issue is this requires you to give it the exact amount of contracts you would like to buy. I am using BUSD to make all my trades, so I am wondering if there is any way to give it a BUSD amount or a percentage of the BUSD I have, instead of the amount of order contracts? If the answer is no then is there any way to calculate how many contracts to buy with a specified amount of BUSD or a percentage of the BUSD you have in your wallet.
I am currently using client.futures_create_order() to execute trades. I am using Binance hedge mode so to place a Long I use, side = 'BUY',positionSide: 'LONG'. Then to sell I keep the positionSide as 'LONG' but switch the side to 'SELL' and opposite for shorts. One of the requirements of using the create order is listing the amount of order contracts you want to buy or sell. But I would like to use 5% of my BUSD account balance per trade. I found a way to pull the price of the symbol I want to trade and then calculate how much 5% of my account balance is into BUSD then finally multiply it by the symbol price to get the number of order contracts to buy. But even that comes with its own issues, one being rounding. If I am buying DOGE Binance wont let me buy less than one contract so would need it to round to the nearest whole number. But if I am buying BTC obviously rounding to a whole number isn't helpful. Even if we can some how get around this issue there is one more. I am making more than one trade at a time, so lets say I place a Long with 5% of my BUSD balance which at the time lets say is $5. Within the time of buying and selling my account balance will change. So when it goes to place the sell order it again uses 5% but now that only $4.5 so there is still $0.5 in the trade open. If using a percentage isn't possible, being able to use a fixed amount of BUSD would still be a huge benefit over using a contract amount.
for people that are having this issue I figured out a solution, it's not perfect but it works for me.
FIL3MIN_original_quantity=None
#app.route('/test', methods = ['POST'])
def test():
data = json.loads(request.data)
side = data['order_action']
positionSide = data['positionSide']
command = data['command']
global FIL3MIN_original_quantity
if command == "FIL3MINBUY":
key = "https://api.binance.com/api/v3/ticker/price?symbol=FILBUSD"
hey = requests.get(key)
hey = hey.json()
sym_price =(f"{hey['price']}")
ticker_price = float(sym_price)
acc_balance = client.futures_account_balance()[8]
balance_value = acc_balance['balance']
balance_value = float(balance_value)
BUSD_quantity = balance_value * 0.02
quantitys = BUSD_quantity/ticker_price
quantityss =quantitys*20
quantityss = round(quantityss, 1)
executed_order = client.futures_create_order(symbol='FILBUSD',side=side,positionSide=positionSide,
type=ORDER_TYPE_MARKET, quantity=quantityss)
FIL3MIN_original_quantity = executed_order['origQty']
if executed_order: return {"code": "success", "message": "order executed BUY",
"amount bought": FIL3MIN_original_quantity}
else: return{"code": "error","message": "order failed"}
if command == "FIL3MINSELL":
if FIL3MIN_original_quantity == None:return("No open position to close")
else:executed_order2 = client.futures_create_order(symbol='FILBUSD',side=side,positionSide = positionSide ,
type=ORDER_TYPE_MARKET, quantity=FIL3MIN_original_quantity)
FIL3MIN_original_quantity=None
if executed_order2: return {"code": "success","message": "order executed SELL"}
else:return {"code": "error","message": "order failed"}
I know this looks like a complete mess but it works for me. to simplify what is going on the progragam first looks at the message it is give in which looks something like this.
place the buy order.
{"passphrase": "abc123","order_action": "BUY","positionSide": "LONG", "command": "FIL3MINBUY"}
place the sell order.
{"passphrase": "abc123","order_action": "SELL","positionSide": "LONG", "command": "FIL3MINSELL"}
from that line of code it receives form trading view it then calculated the current price of the symbol which in this case is FILBUSD. Then gets my current BUSD account balance to figure out what 2% is. It then converts 2% of BUSD into the amount of contracts then rounds it. Next it places the buy order and remembers the amount of contracts that were bought and stores it in FIL3MIN_original_quantity. Then once it receives the sell order from trading view it pulls the amount of contracts and places the sell order.
I want to get ppg value to max30105.
But i can't find ppg value in code.
Just i find heart rate.
How to get ppg value?
#!/usr/bin/env python
# NOTE! This code should not be used for medical diagnosis. It's
# for fun/novelty use only, so bear that in mind while using it.
import time
from max30105 import MAX30105, HeartRate
max30105 = MAX30105()
max30105.setup(leds_enable=2)
max30105.set_led_pulse_amplitude(1, 0.2)
max30105.set_led_pulse_amplitude(2, 12.5)
max30105.set_led_pulse_amplitude(3, 0)
max30105.set_slot_mode(1, 'red')
max30105.set_slot_mode(2, 'ir')
max30105.set_slot_mode(3, 'off')
max30105.set_slot_mode(4, 'off')
def display_heartrate(beat, bpm, avg_bpm):
print("{} BPM: {:.2f} AVG: {:.2f}".format("<3" if beat else " ",
bpm, avg_bpm))
hr = HeartRate(max30105)
print("""
NOTE! This code should not be used for medical diagnosis. It's
for fun/novelty use only, so bear that in mind while using it.
This example shows a readout of your heart rate in BPM (beats per
minute) and heartbeats detected using a heart emoticon <3.
It's best to hold the sensor against your fingertip (the fleshy side)
using a piece of wire or a rubber band looped through the mounting
holes on the breakout, as the sensor is very sensitive to small
movements and it's hard to hold your finger against the sensor with
even pressure.
If you're using your MAX30105 Breakout with Breakout Garden, then
we'd recommend using one of our Breakout Garden Extender Kits with
some female-to-female jumper jerky.
https://shop.pimoroni.com/products/breakout-garden-extender-kit
""")
delay = 10
print("Starting readings in {} seconds...\n".format(delay))
time.sleep(delay)
try:
hr.on_beat(display_heartrate, average_over=4)
except KeyboardInterrupt:
pass
In this code, can get heartrate.
But, I want get PPG value.
I using this library.
https://github.com/pimoroni/max30105-python
I've been analyzing library.
Thanks.
I got a little problem with ccxt on Python. I'm (trying) to code a trading bot which takes my custom tradingview signal. So I've been tinkering a little test code which opens a trade on testnet.binance with all my balance avalaible on BTC/USDT and with a certain leverage.
However, I have a problem with the leverage. Indeed, the code mentions a leverage of 10 and when I run the code locally, the UI mentions a leverage 'Isolated x10' but does not take it into account in the position size (see pictures). I have an approximate balance of 2600 USDT and a trade value of 2600 USDT.
Position through the code
Doing it manually via the UI and with 100% of my balance as well I do get a value of 26000 USDT in 'Isolated x10' which is expected.
Position through the UI
Do you have any idea why it takes into account the leverage but does not apply it to the position?
Here is the code:
import ccxt
import config
binaance = ccxt.binance({
'enableRateLimit': True,
'options': {
'defaultType': 'future',
},
'apiKey': config.API_KEY,
'secret': config.API_SECRET,
'passphrase': config.PASSPHRASE,
})
binaance.set_sandbox_mode(True)
markets = binaance.load_markets()
symbol = 'BTC/USDT'
market = binaance.market(symbol)
binaance.fapiPrivate_post_leverage({
'symbol': 'BTCUSDT',
'leverage': 10,
})
def trade_crypto(request):
free_balance = float(binaance.fetch_balance().get('USDT').get('free'))
last_price = float(binaance.fetchTicker('BTC/USDT').get('last'))
amount = free_balance / last_price
order = binaance.create_market_buy_order('BTC/USDT', amount)
return order
Thank you for what you are doing here ! It helps a lot.
[Edit 1 after #Sam answer]
Hey #Sam, first of all, thank you a lot for your answer.
I didn't checked the margin on the right so thanks for that ! I was so sure that my amout calculations was right that I was not looking there. If I understood correctly the order has engaged 10% of my capital (260 USDT) to obtain 10x leverage with a trade value of 2600 USDT. So I made a change in the calculation which is:
leverage = 10
amount = (free_balance / last_price) * leverage
Result = (2600 / 38900) * 10 = approximately 0.6 btc
But then I got ''Insufficient Funds'' which is expected because it is trying to order with 26 000 USDT from my available balance, but the account only have 2 600.
So how to take in account the fact that the trade value must be 10x the value of my balance (=26 000 USDT) while engaging only 2600 USDT (which is possible trough the user interface)?
In this picture Buying trough the UI, we can see that with 10x leverage I can put my 2600 USDT available balance with a trade value of approximately 26 000 USD. I can't reproduce this behavior code wise.. Hope you or someone else can enlighten me aha.
Ps : I may not have mentioned it, but it concerns trading on futures perpetual contracts
[Edit 2 after finding answer]
I finaly found the mistake. I had to multiply my 'amount' settings by the leverage to get the price in BTC with leverage and put only 99% of this amount because apparently, it can't put 100% of my balance (or maybe it can but I didn't found how to do it. Because with my method, the last price can vary and therefore change the amount which can't be bought or sold with my total balance).
I still have to find a way to put 100% of my balance (perhaps with a parameter that would not take into account the last price).
code modifications:
amount = ((free_balance / last_price) * 10 ) * 0.99
It is taking it into account, you can see that your margin is about 260 USDT and your size is 2600, you would need to place an order for 26000 USDT to use 10x leverage.
You're making an order for about 0.06 BTC, it's going to buy 0.06 BTC for you. At 10x leverage, that's going to cost you about 260 USDT, if you want to use your full 2600 USDT, you need to make an order for 0.6 BTC if you want to use the full amount of USDT that you have.
I'm trying to create a new futures order with a little money in order to test my bot but gives me errors:
order=client.futures_create_order(symbol=sym,side=f'{signal}',type='MARKET',positionSide= "LONG",quantity=str(coinQuantity),leverage=10)
error=binance.exceptions.BinanceAPIException: APIError(code=-4164): Order's notional must be no smaller than 5.0 (unless you choose reduce only)
I really don't know what notional means in here and what is restricting me,I did this change:
order=client.futures_create_order(symbol=sym,side=f'{signal}',type='MARKET',positionSide= "LONG",quantity=str(coinQuantity),leverage=10,reduceOnly='true')
but also this time it gives me this error:binance.exceptions.BinanceAPIException: APIError(code=-1106): Parameter 'reduceOnly' sent when not required.
coinQuantity is 0.001 and symbol is 'ETHUSDT'.
python 3.7.9
The new update from binance will not let trades in futures to be made using api less than 5 dollars(and that was what notional was meant!) so I needed to make my trade a bit bigger than 5 dollars like 5.01. and positionSide(and reduceOnly) parameter was absolutely unnecessary ,since it is only needed for hedge mood.
The new update.
The quantity parameter is not calculated in USDT, you need to set quantity of asset you are trading with. For example, let's say that 1 BAT = 0.423 USDT at the moment, and you want to trade with 5 USDT, so:
5 / 0,423 = 11.82
That means that your quantity parameter should be at least 11.82.
I have a list of very long strings, and I want to know if theres any way to separate every string´s element by a certain number of words like the image on the bottom.
List = [“End extreme poverty in all forms by 2030”,
“End hunger, achieve food security and improved nutrition and promote sustainable agriculture”,
“Ensure healthy lives and promote well-being for all at all ages”,
“Ensure inclusive and equitable quality education and promote lifelong learning opportunities for all”,
“Promote sustained, inclusive and sustainable economic growth, full and productive employment and decent work for all”]
Print(list)
Out:
“End extreme poverty in all forms by 2030”,
“End hunger, achieve food security and improved
nutrition and promote sustainable agriculture”,
“Ensure healthy lives and promote well-being for all at all ages”,
“Ensure inclusive and equitable quality education and promote
lifelong learning opportunities for all”,
“Promote sustained, inclusive and sustainable economic growth,
full and productive employment and decent work for all”]
the final result is kinda like the image
You can use textwrap:
import textwrap
print(textwrap.fill(List[1], 50))
End hunger, achieve food security and improved
nutrition and promote sustainable agriculture
If you want to break it in terms of number of words, you can:
Split the string into a list of words:
my_list = my_string.split()
Then you can break it into K chunks using numpy:
import numpy as np
my_chunks = np.array_split(my_list , K) #K is number of chunks
Then, to get a chunk back into a string, you can do:
my_string = " ".join(my_chunk[0])
Or to get all of them to strings, you can do:
my_strings = list(map(" ".join, my_chunks))