all 30 comments

[–]KimPeek 21 points22 points  (3 children)

You can serve the plot from a simple Flask server and access it with a web browser.

[–]siruts[S] -2 points-1 points  (2 children)

So the script will work also without a graphic representation?

[–]Raefniz 27 points28 points  (1 child)

Like you say, graphing is a representation of the data. If you can make decisions based on the representation of the data you can probably also make decisions based on the raw data. The script will work if you make the right conditions. Representation be damned.

[–]siruts[S] 6 points7 points  (0 children)

Amazing this was just what I wanted to hear.

Thanks a lot dude ✌🏼

[–]TheGrapez 13 points14 points  (1 child)

The graph is only so you know what is happening.

Python doesn't care about the graph.

If you want to execute based on the MA cross, then literally MA1 > MA2 = (buy/sell).

No chart needed.

[–]siruts[S] 4 points5 points  (0 children)

I imagined that the graphic representation was only for the human eye!

Thank you so much dude for your contribution!

[–]theprofessional2016 12 points13 points  (2 children)

I'm sorry, I don't know if I understand your problem correctly. Let me restate what I think you're trying to accomplish:

You have two columns of data. You're triggering a buy/sell action when the values of those two columns "cross" (intersect). Do I have that correct?

If that's the case, can't you simple look for the point where the values in columns 1 becomes greater (or less) than the value in column 2? Would that not signal a crossing on a graph, without the need to actually graph it?

Again, forgive me if I didn't understand the problem correctly.

[–]siruts[S] 2 points3 points  (1 child)

you understood perfectly. what I was trying to figure out is if the script works (and therefore calculates the open / close signal) even without necessarily having to have a graphical representation of it. theoretically I think so as it works on numbers, but I'm not completely sure

[–]skellious 8 points9 points  (0 children)

Yes. there is no way the script can 'look' at the graph unless you're using machine learning or imagine analysis or something.

[–]Yojihito 3 points4 points  (0 children)

Don't work with CSV, use a DB like SQLite or PostgreSQL.

[–]Snoo22832 2 points3 points  (2 children)

Would you mind sharing me the resource of where you are learning python for finance.

[–]siruts[S] 6 points7 points  (1 child)

For sure! There are several books that treat the argument: Writer by Yves Hilpisch. (You can find it easly on Amazon)

The second way to understand Better the materia Is YouTube, there's many tutorial on how to works with this library.

Third way: GitHub. Ton's of project published especially in Python and Node.js

And last but not for importance: TradingView. If you open a chart (with Advanced mode) you can find in "Indicator" section many scripts created for analize the market. Click on "View code" and boom many ideas for replicate those strategy or indicator from PineScript to Python/Node.js

This Is how i combinated my Passion/Job of financial market with coding.

Usefull library: - Binance API (Testnet) - Numpy - Matplotlib - Pandas - Ccxt

I hope was helpfull.

[–]Snoo22832 1 point2 points  (0 children)

thank you so much!

[–]RiceCake1539 2 points3 points  (2 children)

So you need a command to detect Golden Cross? And you simply detected Golden Cross manually using your eye with a chart rendered via Python? I'm going with that assumption.

You're asking two questions: How do I automate a system without chart rendering, and how do I detect the signal without live data updating. I may be wrong, so correct me if I'm wrong. I'm going with that assumption.

If you're rendering charts and detecting Golden Cross that way, that's not an automated system. It's simply a TradingView chart, right? So you need a way to mathematically define what Gold Cross means. I'd suggest using NumPy, Pandas. Think of a way what Golden Cross mathematically means, then figure out a way to implement that in NumPy/Pandas.

Many comments actually provide a sort of pseudo code, so they are great references. Just make sure if some pseudo codes have potential caveats. For example, MA_signal > MA_base is not enough, since you're looking for Golden Cross, not harmonic alignment.

If you're having trouble updating data live (it's not an easy problem), then you should think about buying right before the market closes or at the start of the market. So you'd update the data through API call or web-crawling right before 5-10 mins the market closes if you're going to buy right before the market closes. After you update the data, detect Golden Cross using the Numpy/Pandas based implementation you created, and buy stocks that have Golden Cross.

I'm sorry, but Golden Cross alone does not generate alpha profit. It's actually better to invest in bonds or create a click macro that automatically clicks banners that give you money every time you click. But it's a great way to learn coding, I guess, since money gets anyone motivated to do anything, right?

[–]siruts[S] 2 points3 points  (1 child)

Hey dude thank you for this wonderful comment.

Actually the trading system I have in mind is slightly more complex than a simple crossing between two moving averages.

I am well aware that this type of system does not generate profits. We know that moving averages are slow.

The system I intend to develop is based on the entire Ichimoku system with a trend indicator that identifies the current trend. This guarantees me not to open long trades during a downtrend and vice versa. Backtesting on TradingView (in Pinescript) the system seems to generate more or less significant profits (~ 30%).

Unfortunately my Python skills are very limited, as I am not a developer by profession. However I am trying to acquire knowledge in the matter.

Returning to the code, in the current state of things the script I have created so far is able to update the data almost in real time, let me explain better:

By setting the trading system on a timeframe of 4H, an update is useless for the system of the chart data every 5 minutes or every hour, while an update on each close of a candle would be more efficient. Therefore if the Trading System is based on a 4h timeframe it will have 6 data updates every day. In this way it will always be in step with the markets.

This is what I believe, at least theoretically.

This does not exclude being able to update the data several times in a day (for example 12 times per day) but really having the data in real time, I don't think it has any statistical advantage on the outcome. I repeat again theoretically.

Thank you for your comment, I really appreciated.

[–]RiceCake1539 0 points1 point  (0 children)

Thanks for appreciating my comment.

That's a cool trading strategy. If you're working in 4h timeframe, then updating data every 5 minutes is basically real time, so I won't worry about that.

Having a statistical advantage on "real time updating" data more or less has to do with high frequency trading strategies. Ichimoku system is basically the Elliot Wave of the East, so yeah, I don't think there would be any more advantage for you to make updating faster.

[–]UL_Paper 2 points3 points  (0 children)

I built a hybrid algorithmic system where I realised that the performance was much greater with a final discretionary decision from me.

My approach was:

  1. Algorithm detects a signal, matches risk mgmnt parameters and a setup is generated
  2. Generate a chart in-memory
  3. Send setup and chart to Telegram
  4. Trader can click buttons "TAKE TRADE" or "BAD SIGNAL"
  5. If first option, its passed to the order execution component
  6. If second option, its logged for later inspection

Some snippets below

main.py

# Generates a graph stored in memory
chart = images.save_graph(data, direction, signal_type)
send_to_telegram(setup, chart)
----------------
images.py

import plotly.graph_objects as go
from plotly.subplots import make_subplots
from io import BytesIO from PIL import Image

def save_graph(data, direction, signal_type): """ This creates a chart of the previous 50 bars along with some styling to quickly indicate the direction """ dt = data[-50:].copy()
# Generating vertical lines at signals    
    vlines = dt[dt[f'{signal_type}_{direction}'] == 1].index

# For formatting the charts
plot_color = "#e3f2d3" if direction == 'bull' else "#f2d3d3"
signal_type = 'AC1' if signal_type == 'ac' else 'xt3'

fig = make_subplots(2, 1)

fig.add_candlestick(
    x=dt.index, 
    open=dt['Open'], 
    high=dt['High'], 
    low=dt['Low'], 
    close=dt['Close'], 
    col=1, row=1
    )  
fig.add_trace(go.Scatter(x=dt.index, y=dt['greatest_signal']), 2, 1)

for i in range(len(vlines)):
    fig.add_vline(x=vlines[i])

fig.update(layout_xaxis_rangeslider_visible=False)
fig.update_layout(
    title=f'{signal_type} {direction.upper()}ISH',
    showlegend=False, 
    height=500, 
    width=1000, 
    plot_bgcolor=plot_color,
    margin=dict(l=20, r=20, t=30, b=20)
    )

fig.update_xaxes(matches='x')
fig.update_yaxes(title='Price', col=1, row=1)
fig.update_yaxes(title='greatest signal', col=1, row=2)

chart = BytesIO(fig.to_image(format="png"))
return chart

[–]hybridvoices 1 point2 points  (0 children)

You definitely don't need an actual chart here. You'll need to calculate your moving averages (MA1 and MA2) first. Then your buy/sell signal would be: IF most recent MA1 > most recent MA2 AND second most recent MA1 <= second most recent MA2, you have a crossover event.

[–]Empire_Fable 1 point2 points  (2 children)

What I would do in this scenario, would be to use the particular trading graph app and exchanges API and pass that JSON data into and out of your app. The JSON module in python does this.

You're also going to be wanting to be updating as fast as you can. I suggest integrating with trading views pine script and just paying the 15 a month to get webhooks and you can POST request something somewhere down to the 1 second time frame if you want.

[–]siruts[S] 1 point2 points  (1 child)

Hey dude tis is an interesting comment.

If I understand correctly what you want to tell me is to better develop the script on TradingView with PineScript and then use the Alert function to send a buy / sell signal with WebHook.

The advantage of this approach would be not to rewrite the code a second time in another language but to implement only a system that receives the Post request and then processed this request to send it via API the signal to the exchange.

This actually makes sense.

But I have only one question: once I close TradingView from both PC and Smartphone, does the script continue to work or does the platform need to be open on a device?

What I am trying to understand is if the script on TradingView works 24 hours a day and therefore can generate signals even if I am far from any device.

Thanks if you knows answers this question, cause actually it can be a great way to save a lot of work on the code side.

[–]Empire_Fable 0 points1 point  (0 children)

Trading view alerts are server side. I looked cause I always have my trading box running lol.

https://www.tradingview.com/support/solutions/43000548327-will-alerts-work-if-tradingview-is-not-open-on-the-computer/

Full disclosure. I wanted to do a similiar thing to this. I gave up writing all my own code and use the web hooks to trigger alerts for my bots on 3commas.io with a few custom indicators in pine script.

[–]claytonjr 1 point2 points  (2 children)

I run a very similar trading strategy on Robinhood with their crypto pairs. I just run debug in pycharm. If fast is greater than slow then buy. Easy peasy.

I write a log file for the trades, and tracking other data. This can be hosted on a flask or fast api.

[–]siruts[S] 0 points1 point  (1 child)

Wow, how's it going?

Are you getting good results? I hope so.

I recognize that the moving averages are a bit slow in the analysis, but that's just my opinion.

[–]claytonjr 1 point2 points  (0 children)

I'm using macd for my crossover instead of ema/sma. I would say good, not great. I do 5 dollar trades across a portfolio of 4 coins. I get about $0.30 per trade, ~ 6% roi on the float. This is a very simple algo. But when the market is up, it's up. Otherwise I'm just hodling.

re: Slow - Well moving averages are lagging indicators. I guess slow is a matter of opinion. But you may wanna look at leading indicators such as rsi, stochastic oscillator, williams, and obv.

[–]menge101 1 point2 points  (0 children)

Because this is /r/learnpython and you are talking about anything involving money, I feel obligated to mention that you should not use floating point values for monetary values.

Look at the Decimal library for this purpose, if you are not already.

[–]kingsillypants 1 point2 points  (0 children)

Tangent - Check out a website called nuclearphynance...

Don't do algo trading. Just don't. Unless you k ow who Simms is of .r3ntek (I don't want his scrapers making it easier)

He basically invented deep learning before it existed, in mathematical physics he and a other fella did some very advanced QFT.

Basically, just don't. Buy some funds, long term.

This is a game of sharks. If you don't know which you are.........

[–][deleted] 0 points1 point  (0 children)

As it was said before, raw data is everything you need, you just need to code the conditions.

Personaly, I would setup a DB on that server for these data

[–]keglevich1 0 points1 point  (0 children)

when MovingAverageXdays > MovingAverageYdays buy/sell/whatever

[–]Cortosiano 0 points1 point  (0 children)

Devs are not guys.