Giter VIP home page Giter VIP logo

joshyattridge / smart-money-concepts Goto Github PK

View Code? Open in Web Editor NEW
117.0 12.0 72.0 1.53 MB

Recognized as the premier algorithmic trading tool for Python, this Python package seamlessly integrates Inner Circle Trader (ICT) methods, providing a comprehensive suite of indicators meticulously crafted to analyze the concept of smart money in financial markets.

Home Page: https://pypi.org/project/smartmoneyconcepts/

License: MIT License

Python 100.00%
circle concepts crypto forex ict inner liquidity money ob smart

smart-money-concepts's Introduction

Smart Money Concepts (smc) BETA

The Smart Money Concepts Python Indicator is a sophisticated financial tool developed for traders and investors to gain insights into market sentiment, trends, and potential reversals. This indicator is inspired by Inner Circle Trader (ICT) concepts like Order blocks, Liquidity, Fair Value Gap, Swing Highs and Lows, Break of Structure, Change of Character, and more. Please Take a look and contribute to the project.

alt text

Installation

pip install smartmoneyconcepts

Usage

from smartmoneyconcepts import smc

Prepare data to use with smc:

smc expects properly formated ohlc DataFrame, with column names in lowercase: ["open", "high", "low", "close"] and ["volume"] for indicators that expect ohlcv input.

Indicators

Fair Value Gap (FVG)

smc.fvg(ohlc, join_consecutive=False)

A fair value gap is when the previous high is lower than the next low if the current candle is bullish. Or when the previous low is higher than the next high if the current candle is bearish.

parameters:
join_consecutive: bool - if there are multiple FVG in a row then they will be merged into one using the highest top and the lowest bottom

returns:
FVG = 1 if bullish fair value gap, -1 if bearish fair value gap
Top = the top of the fair value gap
Bottom = the bottom of the fair value gap
MitigatedIndex = the index of the candle that mitigated the fair value gap

Swing Highs and Lows

smc.swing_highs_lows(ohlc, swing_length = 50)

A swing high is when the current high is the highest high out of the swing_length amount of candles before and after. A swing low is when the current low is the lowest low out of the swing_length amount of candles before and after.

parameters:
swing_length: int - the amount of candles to look back and forward to determine the swing high or low

returns:
HighLow = 1 if swing high, -1 if swing low
Level = the level of the swing high or low

Break of Structure (BOS) & Change of Character (CHoCH)

smc.bos_choch(ohlc, swing_highs_lows, close_break = True)

These are both indications of market structure changing

parameters:
swing_highs_lows: DataFrame - provide the dataframe from the swing_highs_lows function
close_break: bool - if True then the break of structure will be mitigated based on the close of the candle otherwise it will be the high/low.

returns:
BOS = 1 if bullish break of structure, -1 if bearish break of structure
CHOCH = 1 if bullish change of character, -1 if bearish change of character
Level = the level of the break of structure or change of character
BrokenIndex = the index of the candle that broke the level

Order Blocks (OB)

smc.ob(ohlc, swing_highs_lows, close_mitigation = False)

This method detects order blocks when there is a high amount of market orders exist on a price range.

parameters:
swing_highs_lows: DataFrame - provide the dataframe from the swing_highs_lows function
close_mitigation: bool - if True then the order block will be mitigated based on the close of the candle otherwise it will be the high/low.

returns:
OB = 1 if bullish order block, -1 if bearish order block
Top = top of the order block
Bottom = bottom of the order block
OBVolume = volume + 2 last volumes amounts
Percentage = strength of order block (min(highVolume, lowVolume)/max(highVolume,lowVolume))

Liquidity

smc.liquidity(ohlc, swing_highs_lows, range_percent = 0.01)

Liquidity is when there are multiply highs within a small range of each other. or multiply lows within a small range of each other.

parameters:
swing_highs_lows: DataFrame - provide the dataframe from the swing_highs_lows function
range_percent: float - the percentage of the range to determine liquidity

returns:
Liquidity = 1 if bullish liquidity, -1 if bearish liquidity
Level = the level of the liquidity
End = the index of the last liquidity level
Swept = the index of the candle that swept the liquidity

Previous High And Low

smc.previous_high_low(ohlc, time_frame = "1D")

This method returns the previous high and low of the given time frame.

parameters:
time_frame: str - the time frame to get the previous high and low 15m, 1H, 4H, 1D, 1W, 1M

returns:
PreviousHigh = the previous high
PreviousLow = the previous low

Contributing

This project is still in BETA so please feel free to contribute to the project. By creating your own indicators or improving the existing ones. If you are stuggling to find something to do then please check out the issues tab for requested changes.

  1. Fork it (https://github.com/joshyattridge/smartmoneyconcepts/fork).
  2. Study how it's implemented.
  3. Create your feature branch (git checkout -b my-new-feature).
  4. Commit your changes (git commit -am 'Add some feature').
  5. Push to the branch (git push origin my-new-feature).
  6. Create a new Pull Request.

smart-money-concepts's People

Contributors

joshyattridge avatar rafalsza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

smart-money-concepts's Issues

Questions regarding BOS/CHOCH function

Hi team,
Could you please help with some questions about bos_choch function:

  1. What does mean BrokenIndex and what its value means ? (some position(candle) number; it doesn't equal the candle number in the data frame)
  2. How can we show all Level values, not only when we have BOS or CHOCH ?
  3. As I understand and can see from testing the BOS or CHOCH, the price is showing for the candle that starts the breaking price and not closes. How we can show the BOS or CHOCH but on the candle that closes the breaking.
    I know that the decision is made based on the swing highs and lows but can we somehow show BOS or CHOCH on the candle which closes the price breaking even if this candle is not a swing high or low ?

Consecutive FVG

Add a boolean parameter to the FVG function called join_consecutive.

If this is set to true then any FVG that follow after each other will be joined together.
So instead of having multiple small FVGs in a row they will be joined together and the top/bottom will be adjusted to cover all of them.

Sessions Indicator

Create An Indicator that will determine if the candle is in a certain session.

This function must follow the sessions on https://www.babypips.com/learn/forex/forex-trading-sessions and it must account for the different time zones the data is in.

Parameters:

  • Type: the type of session (Sydney, Tokyo, London, New York and custom)
  • Custom Start: the starting time of the custom session
  • Custom End: the ending time of the custom session

Retuned values:

  • InSession = 0 or 1 - if the candle is in the session or not
  • Top = the highest high during the current session
  • Bottom = the lowest low during the current session

Installation error (Failed building wheel for zigzag)

Thank you very much for your effort on this. It was a highly anticipated package for me. I am trying to install via pip however end up with an error:

ERROR: Failed building wheel for zigzag
Failed to build zigzag
ERROR: Could not build wheels for zigzag, which is required to install pyproject.toml-based projects

Do you have any suggestions?
Thank you in advance

Multiple orderblocks

Hi,
Thanks for a great starting point on building SMC concepts using Python. I am currently trying to use your library/code to find order blocks and I was wondering if you are planning to change the ob function so it returns multiple order blocks?
For instance when I run the code on FLOWUSDT (Bybit perpetual contract) 4H candle data it detects the following order block
image

However, when I use the most popular order-block indicator on TW there are more OB's being displayed
image

image

I'm still getting familiar with your codebase, if I am successful in understanding it properly I can try to contribute a PR.

index 0 is out of bounds for axis 0 with size 0

import ccxt
import pandas as pd
from smartmoneyconcepts import smc

exchange = ccxt.binanceusdm(
    {
        "apiKey": "1",
        "secret": "1",
        "enableRateLimit": True,
    }
)

# exchange.verbose = True
exchange.options["warnOnFetchOpenOrdersWithoutSymbol"] = False

klines = exchange.fetch_ohlcv("POLYX/USDT", "1h", limit=100)

# 转为 df
df = pd.DataFrame(
    klines, columns=["timestamp", "open", "high", "low", "close", "volume"]
)

swing_highs_lows = smc.swing_highs_lows(df, 50)
print(swing_highs_lows)

# fvg_data = smc.fvg(df)
# df = pd.concat([df, fvg_data], axis=1)

# swing_highs_lows = smc.swing_highs_lows(df)
# print(swing_highs_lows)

# print(df)

Unit Testing

Create a python script to perform unit tests on all of the functions.

FVG - Liquidity

First of all, thank you for all your efforts for the SMC Python adaptation. I am experimenting with testing this package and applying it to different strategies. However, I am having problems calculating data related to FVG and Liquidity. No matter what threshold value I enter for Liquidity, I cannot get results on the chart or as data. I also get the following error on FVG. These might be simple questions with straightforward solutions. Unfortunately, my experience with Python is at the beginner level. Thank you in advance for your support.

line 129, in
fig = add_FVG(fig)
line 39, in add_FVG
fvg_data = smc.fvg(df)
smartmoneyconcepts\smc.py", line 35, in wrap
return func(*args, **kwargs)
smartmoneyconcepts\smc.py", line 87, in fvg
mask = np.zeros(len(ohlc), dtype=np.bool)
numpy_init_.py", line 338, in getattr
raise AttributeError(former_attrs[attr])
AttributeError: module 'numpy' has no attribute 'bool'.
np.bool was a deprecated alias for the builtin bool. To avoid this error in existing code, use bool by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use np.bool_ here.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations. Did you mean: 'bool_'?

#----------------Binance Data Fecth---------------------------------
bars = exchange.fetch_ohlcv('LINK/USDT', timeframe='4h', limit=1000)
df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']).astype(float)
df['timestamp']=pd.to_datetime(df['timestamp'], unit='ms')

#----------------Bar Plot------------------------------------------
fig = go.Figure(
    data=[
        go.Candlestick(
            x=df["timestamp"],
            open=df["open"],
            high=df["high"],
            low=df["low"],
            close=df["close"],
        )
    ]
)
#----------------FVG Plot------------------------------------------
def add_FVG(fig):
    fvg_data = smc.fvg(df)
    # plot a rectangle for each fvg
    for i in range(len(fvg_data["FVG"])):
        if fvg_data["FVG"][i] != 0:
            x1 = (
                fvg_data["MitigatedIndex"][i]
                if fvg_data["MitigatedIndex"][i] != 0
                else len(df) - 1
            )
            fig.add_shape(
                # filled Rectangle
                type="rect",
                x0=df.index[i],
                y0=fvg_data["Top"][i],
                x1=df.index[x1],
                y1=fvg_data["Bottom"][i],
                line=dict(
                    width=0,
                ),
                fillcolor="yellow",
                opacity=0.5,
            )
    return fig
#----------------Highs & Lows------------------------------------------
def add_highs_lows(fig):
    highs_lows_data = smc.highs_lows(df,0.005)

    # remove from highs_lows_data
    indexs = []
    levels = []
    for i in range(len(highs_lows_data)):
        if highs_lows_data["HighsLows"][i] != 0:
            indexs.append(i)
            levels.append(highs_lows_data["Levels"][i])
    
    # plot these lines on a graph
    for i in range(len(indexs) - 1):
        fig.add_trace(
            go.Scatter(
                x=[df["timestamp"][indexs[i]], df["timestamp"][indexs[i + 1]]],
                y=[levels[i], levels[i+1]],
                mode="lines",
                line=dict(
                    color="green" if highs_lows_data["HighsLows"][indexs[i]] == -1 else "red",
                ),
            )
        )

    return fig
#----------------Plot Liquidity------------------------------------------
def add_liquidity(fig):
    liquidity_data = smc.liquidity(df)

    # draw a line horizontally for each liquidity level
    for i in range(len(liquidity_data["Liquidity"])):
        if liquidity_data["Liquidity"][i] != 0:
            fig.add_trace(
                go.Scatter(
                    x=[df["timestamp"][i], df["timestamp"][liquidity_data["End"][i]]],
                    y=[liquidity_data["Level"][i], liquidity_data["Level"][i]],
                    mode="lines",
                    line=dict(
                        color="orange",
                    ),
                )
            )
        if liquidity_data["Swept"][i] != 0:
            # draw a red line between the end and the swept point
            fig.add_trace(
                go.Scatter(
                    x=[
                        df["timestamp"][liquidity_data["End"][i]],
                        df["timestamp"][liquidity_data["Swept"][i]],
                    ],
                    y=[
                        liquidity_data["Level"][i],
                        (
                            df["high"][liquidity_data["Swept"][i]]
                            if liquidity_data["Liquidity"][i] == 1
                            else df["low"][liquidity_data["Swept"][i]]
                        ),
                    ],
                    mode="lines",
                    line=dict(
                        color="red",
                    ),
                )
            )
    return fig

fig = add_FVG(fig)
fig = add_highs_lows(fig)
fig = add_liquidity(fig)
fig.show()

Previous Candle High/Low

Create a new function to get the previous candles High and low.
You will be able to pass the timeframe of the previous candle like 1m,1H,1D,1W
This function will then get the high and low of that previous candle like the previous days high and low.
The function will then return the following data:
High - the pip the high is at.
HighBreach - When the high was breached if it has.
Low - the pip the low is at.
LowBreach - When the low was breached if it has.

very long waiting time for VOB

def add_VOB(fig):

    start_time = time.time()
    ob_data = smc.vob(df)
    volumized_ob_time = time.time() - start_time
    logger.debug(
        "volumized_ob processing time (for ohlc length={}): {:.2f} seconds",
        len(ob_data),
        volumized_ob_time,
    )
2024-02-23 12:48:40.440 | DEBUG    | __main__:add_VOB:194 - volumized_ob processing time (for ohlc length=1000): 5.01 seconds

Test Chart Clean up

The current chart produced by the tests is a bit messy and hard to understand.
This task is to clean up this chart make it look pretty and easy to read.
Then add the chart image to README.md file

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.