GRID Trading Optimized for Directional MarketsGRID trading is a popular trading strategy in Forex and Commodity markets.
It it however a tricky strategy when markets become directional.
This Directional GRID system adjusts its trading strategy and direction based on Overbought and Oversold RSI conditions on 2 timeframes.
It uses the short timeframe (chart) to trigger adjustments, so it delays buying/selling of all the levels, until it becomes overbought/sold
And it used the longer timeframe to trigger trading direction long/short.
This makes it far less likely to ever get "underwater", and builds in extra profit potential during market extremes.
I have coded it when i was trading SLV, but it could be optimized for any market using a "TradingView Strategy Input Optimizer".
Backtest based on a 25k max capital investment during 6 months.
Check the NET Profit (50%) result, and compare against the Buy & Hold (13.5%) return.
Losing trades are the ones that are currently open..
Av Bars in trades is the time between direction changes, as Position Adjustments are done more frequently.
Contact me for Trading Automation As A Service.
Portfolio management
Bond Yeild CurveBond Yeild Curve
A bond yeild curve is a line that plot the interest rate of bonds of each maturity dates.
The slope of the curve give the future of economy cycle.
if the slope could be normal (positive), flat or even inverted.
This indicator aquired data of bond yeild provided by TradingView.
How to use it.
Select the country of the bond / another country to compare.
Select the maturity of bond (this indicator set 2Y, 5Y, 10Y and 20Y as default).
You can toggle to 3 different data set; Yeild, Spread (10Y-2Y) and Yeild Curve.
In case that you select the "Yeild Curve", you can customize the desired past period to compare.
How we can get the benefit.
- If the current spread is greater than 1.0, it suppose that the economy of that country probably is ok.
- if the current spread is between 0 - 1.0, it suppose to be flatted and probably turn to invert and the economy cound be in a recession soon.
- if the current spread is below 0, it suppose to be inverted and economy is in recession.
when knowing the state of economy, it would help us to manage our investment.
When you select "Yeild"
When you select "Spread"
When you select "Yeild Curve"
I'm new for this.
if any idea, correction and suggestion, i do appreciate it.
LCDT Trade Entry ToolLCDT Trade Entry Tool
Enter the Offset for the X Axis for the Entry Tool.
Enter the Offset for the Y Axis for the Entry Tool.
Enter the Price for your Stop Loss in $.
Enter your desired Risk Amount in $.
Enter the max amount of of Capital per Trade in $.
There are toggle buttons in the setup to reveal/remove more data in the label that pops up, as well as a toggle to make the text larger.
SuperTrend Multiple Risk Management SystemThis is an improved SuperTrend strategy that makes use of multiple types of risk management options.
We have for example :
1. Take profit and stop loss levels based on support and resistence created with RSI and Pivot Lines(dynamic)
For example, if we have an oversold level and a pivot low , we can take that low point for support.(or resistence for short)
If instead we have an overbought level and a pivot high, we can take that high point for resistence.(orsupport for short)
2. Take profit and stop loss levels based on swing low and swing high points calculated with highest high and lowest low function(dynamic)
For example we take the lowest point in the last 100 candles. We calculate the distance from the current point to that one, and we apply this value as a take profit point. Same for stop loss
3. Take profit and stop loss levels based on % movements(fixed)
For example we have a tp or sl of 10%. If either of them make a movement of 10% from the entry point, they will get triggered.
4. Break even stop loss once the asset moves certain % in our direction.
For example we have a long breakeven of 5%. If the asset moves 5% in our direction, we move the stop loss on the entry point so if the trade pullback and crosses with this point it will exit from the trade.
Notes:
All the exits from the strategy are happening at the end of the candle close, since we are checking if inside the current candle we cross with either high or low of the candles parts the set prices from any of the above options.
At the same time we can combine multiple of them into one, and we can either exit based on which one was hit first, or use a quantity reduction of the trade and exit multiple times when we hit any of the levels.
This tool is for educational purpose only.
Its main purpose is to show the difference between having a risk management or without.
For example on this scenario of BTC USD 4h, I found out that the drawdawn was reduced by more than half when using different type of risk management, compared to not use one at all, while at the same time increasing the profits by a huge margin.
Signals Pirate™ Market ScreenerSignalsPirate™ Market Screener provides users with the ability to quickly and easily check the current trend of up to 40 different assets on any timeframe! With a simple ‘Bullish’ or ‘Bearish’ trend easily defined using accurate and reliable calculations, this tool could massively cut down the amount of time your TA takes!
The main Input options are 'Reactivity' and 'Depth', which allow for a dynamic trend following strategy that works on all time frames and assets. Using these values the strategy will print the bundles main ‘Buy’ and ‘Sell’ signals to try and identify the trend early and accurately. Their main functions are to dynamically calculate volatility and current trend direction – but we’ve gone more in-depth below!
Reactivity:
Reactivity controls how quickly the Algo reacts to changes in trend. This part of the bundle takes into account the Average True Range (ATR) to gauge current market volatility and direction of the trend. Lowering the reactivity value will generate quicker reaction times of the algorithm as it will lower the threshold of volatility required for a signal to be generated. Therefore, it’ll show trades more frequently.
Depth:
Depth controls the position of the signals according to the trend swing. Calculated using a variation of the Average Direction Index (ADX) to measure the changes in prices over a given period, when running parallel to the Reactivity volatility filter the trend can be identified quickly and accurately on any given time frame or asset. Higher Depth will allow for less frequent and slower entries. In contrast, lower Depth will give more frequent and earlier entries.
The default settings are the best settings we’ve found so far but you can change them to build your own unique trading strategy. We’d recommend experimenting with these values to find the best results for the asset you are trading, and your own personal trading and investing style.
Direction for use:
1. Use on any asset class and time frame and add the tickers of any asset you want included in the screener.
2. Fine tune the Reactivity (volatility) and Depth (trend sensitivity).
3. Consider longing assets that appear in the ‘Bullish List’ after candle close, and consider shorting assets that appear in the ‘Bearish List’ after candle close.
4. Exit positions once an asset has switched from one list to the other.
As mentioned previously, this Market Sceener uses a trend base system that dynamically operates to function with superior accuracy regardless of what you’re trading. But with the level of customisation available, this can easily be fine tuned to accommodate scalping, reversal trading, or even long term investing.
We hope you love this Screener, and it takes your trading and investing to the next level. Please let us know if you have any questions or queries regarding the logic behind the bundle, or if you have any suggestions for improvements etc. We love your feedback and are constantly striving to continuously improve!
Accumulation/Distribution Bands & Signals (BTC, 1D, BITSTAMP) This is an accumulation/distribution indicator for BTC/USD (D) based on variations of 1400D and 120D moving averages and logarithmic regression. Yellow plot signals Long Term Accumulation, which is based on 1400D (200W) ALMA, orange plot signals Mid Term Accumulation and is based on 120D ALMA, and finally the red plot signals Long Term Distribution that's based on log regression. It should be noted that for red plot to work BTC 1D BITSTAMP graph must be used, because the function of the logarithmic regression was modified according to the x axis of the BITSTAMP data.
Signal bands have different coefficients; long term accumulation (yellow) and and the log regression (red) plots have the highest coefficients and mid term accumulation (orange) has the lowest coefficients. Coefficients are 6x, 3x and 1.5x for the red (sell) and yellow (buy) plots and 1x, 2x and 3x for the orange (buy) plot. Selling coefficient for the yellow and the orange plots are respectively 2x and 1x. Buy and sell signals are summed up accordingly and plotted at the top of the highest band.
Acknowledgement: Credits for the logarithmic regression function are due @memotyka9009 and Benjamin Cowen
Overnight Gap AnalysisThere is a wide range of opinion on holding positions overnight due to gap risk. So, out of curiosity, I coded this analysis as a strategy to see what the result of only holding a position overnight on an asset would be. The results really surprised me. The script backtests 10+ years, and here are the findings:
Holding a position for 1 hour bar overnight on QQQ since January 2010 results in a 545% return. QQQ's entire return holding through the same period is 643%
The max equity drawdown on holding that position overnight is lower then the buy/hold drawdown on the underlying asset.
It doesn't matter if the last bar of the day is green or red, the results are similar.
It doesn't matter if it is a bull or bear market. Filtering the script to only trade when the price is above the 200-day moving average actually reduces its return from 545% to 301%, though it does also reduce drawdown.
I see similar patterns when applying the script to other index ETFs. Applying it to leveraged index ETFs can end up beating buy/hold of the underlying index.
Since this script holds through the 1st bar of the day, this could also speak to a day-opening price pattern
The default inputs are for the script to be applied to 1 hour charts only that have 7 bars on the chart per day. You can apply it to other chart types, but must follow the instructions below for it to work properly.
What the script is doing :
This script is buying the close of the last bar of the day and closing the trade at the close of the next bar. So, all trades are being held for 1 bar. By default, the script is setup for use on a 1hr chart that has 7 bars per day. If you try to apply it to a different timeframe, you will need to adjust the count of the last bar of the day with the script input. I.e. There are 7 bars per day on an hour chart on US Stocks/ETFs, so the input is set to 7 by default.
Other ways this script can be used :
This script can also test the result of holding a position over any 1 bar in the day using that same input. For instance, on an hour chart you can input 6 on the script input, and it will model buying the close of the 6th bar of the day while selling on the close of the next bar. I used this out of curiosity to model what only holding the last bar of the day would result in. On average, you lose money on the last bar every day.
The irony here is that the root cause of this last bar of the day losing may be people selling their positions at the end of day so that they aren't exposed to overnight gap risk.
Disclaimer: This is not financial advice. Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
Position & Lot Size CalculatorBuilt with love "Position & Lot Size Calculator"
This indiator will help you to calculate your position size for managing the risk
Features :
1. Click-able Price Entry & SL (Easier Interface)
How to use it :
1. After add the indicator, set the Entry & SL Price with click price line in the chart
2. Set the risk and another parameter
Regards,
Hanabil
Strategy - Cryptosystem NNFX wayFirst script done!
This is my version of the No-Nonsense Forex (NNFX) Strategy
This strategy shows you the entry and exit signal with a standard 1.5 x ATR for Stop Loss and 1 x ATR for Taking Profit. You can adjust the settings to your needs.
This strategy uses 5 indicators:
1. Average True Range for SL and TP placement, there is a nuance where you can add the 1XATR Rule;
2. SMA used to filter longs and shorts;
3. SSL Channel for 1st Confirmation;
4. DPO for 2nd Confirmation;
5. Waddah Attar Explosion as a volume indicator.
There is no exit indicator because I coded 2 trades (2x0.5). TP1 will be at 1xATR and TP2 will automatically trail behind with 1.5XATR. You can see the red trailing line on the charts.
Other exits can be: When SSL gives opposite signal or when price crosses and closes your baseline.
I used this system for 1D timeframe.
Hopefully this can be usefull for your tradingstyle.
Would be great if you guys leave a like.
Thanks!
Risk AssistAs the profit level increases, the amount of profit taking required to avoid risk asymptotically reaches zero.
This indicator displays the % of the established position required to exit in order to ensure the trade is not a loss if the stop is hit.
Values in green (at or below 100%) indicate a winning position.
Values in red (above 100%) indicate a losing position.
Alert Examples:
If you are intent on "selling half" to avoid risk, you can set an alert on the value of this indicator for 50.
If you are intent on "selling a 3rd" to avoid risk, you can set an alert on the value of this indicator for 33.3.
Money Management_V2 [javadmhs]Hi every one
you can use this indicator in your trades for money and risk management.
Very easy to use. Just enter the requested information of your trade and see the amount of money you need to enter into a transaction. Also you can see your pnl%.
Risk = The amount of money that if you lose, does not matter to you. This will be a percentage of your total capital.
Balance = your total capital.
Leverage = If you trade in future, you can use this. set it 1 in spot.
Commision = The amount of exchange fee.
Usable Cap = The amount of money you should enter into a transaction, depending on your risk.
PNL% = Amount of profit and loss.
You Can use this for Short and Long.
Let me know if you see a problem.
Leverage CalculatorThis script is intended to be used as a risk management calculator.
It will calculate the best leverage to use based on the maximum percentage of loss you are willing to incur on your trading portfolio.
Also calculates the order value and order qty based on your inputs.
Please note this calculator does not take into account any trading fees imposed by the exchange you are using.
*** Only risking 1% to 5% of your portfolio is considered good risk management ***
*** Not financial advice ***
------ Settings Inputs -----------------------------------------------------------------------------------------------------
"Portfolio Size" -- enter your portfolio balance
"% Willing to lose on this trade" -- enter the percent of your portfolio you are willing to lose if the stop loss is hit
"Entry Price" -- enter the price at which you will enter the trade
"Stop Loss Price" -- enter the price at which your stop loss will be set
----------------------------------------------------------------------------------------------------------------------------
------ Outputs -------------------------------------------------------------------------------------------------------------
"Portfolio" -- displays the portfolio balance entered in settings
"max loss on trade" -- displays the % loss entered in settings and the corresponding amount of your portfolio
"Entry Price" -- displays the entry price entered in settings
"Stop Loss Price" -- displays the stop loss price entered in settings
"Stop Loss %" -- displays the calculated percentage loss from the entry price
"Leverage calc" -- displays the calculated leverage based on your max loss and stop loss settings
"Order Value" -- displays the value of the order based on the calculated leverage
"Order Qty" -- displays the calculated order qty based on the calculated leverage
Crypto Spot Market Bot | BacktestHello Friends.
This script is only for long positions.
How does the algorithm work ?
The Relative Momentum Index
Relative Strength İndex
Average Directional Movement İndex
Momentum
When rsi and adx produce signals in the same direction, the rmi indicator confirms the signal. After the Confirmed Signal, the buy-side transaction is entered , the closed according to the % of profit taking and stoploss specified on the algorithm in the entered transaction.
In the spot market, it is possible to make money even in a down trend
All shared charts run within a 1-hour time frame.
Note : The shared backtest results have been shared as of 9/9/2021 by calculating 50% balance and 2 pyramiding methods in an account of 1000 dollars. Keep in mind that this algorithm will want to try to average down in possible worst-case scenarios. 2% - %3take profit levels will provide consecutive gains in the spot market.
How should the adjustments be made?
Value variables should be made according to formula a and formula b values and backtest results. You can increase the frequency of transactions by lowering the adx and rsi values.
Overview :
SHAD helperDisplays lines and labels for prices following the SHAD strategy.
SHAD strategy consists in selling half the position every time price doubles, thus this indicator displays values for x2, x4, x8 and x16 of current closing price.
You can also see "/2" (-50%) and "/4 " (-75%) values.
You can edit display colors and labels text size in the indicator's settings
D-VaR position sizingThe D-VaR position sizing method was created by David Varadi. It's based on the concept of Value at Risk (VaR) - a widely used measure of the risk of loss in a portfolio based on the statistical analysis of historical price trends and volatilities. You can set the Percent Risk between 1 (lower) and 1.5 (higher); as well as, cap the % of Equity used in the position. The indicator plots the % of equity recommended based on the parameters you set.
Abz BTC InvestorInvestor indicator:
This indicator is intended to be used on a chart showing Bitcoin's historical price action. By viewing years of Bitcoin's history, it's possible to better see Bitcoin's current price within a long term context of the price rage.
Purpose and possible usage:
I built the indicator to make it easier for me and for friends and family to make better informed decisions about our Bitcoin investments. The indicator shows the historic range of the asset and indicates where Bitcoin is oversold (below the bottom line) and overbought (above the top purple line):
- Above the top purple line, I'll look to take some profits or consider hedging to protect my long term position's growth
- Below the bottom purple line, I'll look to dollar cost average into a long term position
I think the idea for this came from idea listening to the YouTuber Birb talking about how well Bitcoin tracked between the 200 day moving average (bottom navy moving average) and 5x that value (top moving average).
Hope you find it useful.
Best wishes,
Abzorba
Period Dollar Cost Average BacktesterHere is a simple script to calculate the profits and other dollar cost average strategy statistics. This strategy was created to avoid asset price volatility, so the pump and dump scheme does not affect the portfolio. By dividing the investment amount into periods, the investor doesn’t need to analyze the market, fundamental analysis, or anything. The goal is to increase the asset holdings and avoid fast and robust price movements.
This indicator has some configurations.
Amount to buy: the amount to buy at each time
Broker fee %: the fee percentage that the broker has for spot trade
Frequency: the frequency of the investments. Example: 1 Day means that every day, it will buy an amount of the asset
Starting Date: when the indicator will start the investment simulation
Ending Date: when the indicator will end the investment simulation
InfoCell With/Height: it relates to the panel for view purposes. Change the values to fit better on your screen.
This indicator has three lines:
Total Invested (green): total amount invested at the end of the period
Total Net Profit (pink): total profit by converting the amount of the asset bought at the latest closing price
Holding Profits (yellow): the amount that would be in the portfolio if the investor had invested all the capital in a signal trade at the beginning of the period.
The statistics panel has some information to help you understand buying the asset in one or more trades. So, besides those three lines that were mentioned above, here are the other statistics:
Entry Price: The price of the asset when the first investment was made
Gross Profit: Total amount of profit, not excluding the losses
Gross Losses: Total amount of losses, not excluding the profits
Profit Factor: The Gross Profit divided by the Gross Loss. A value above 1 means it’s profitable.
Profit/Trades: Net profit per trade. This includes the broker fees.
Recovery Factor: The Net profit divided by the relative drawdown. The higher the recovery factor, the faster the recovery of a loss
Total Asset Bought: The amount of the asset that was bought at the end of the investment plan
Absolute Drawdown: The total amount of losses that made the account balance go below its initial value
Relative Drawdown: The max drawdown that occurred, no matter the account balance amount
Total Trades: number of times the investment was made in the selected period
Total Fee: total Fee that was spent on the total investment
Total Winning Trades: the total amount of winning trades. A trade is considered a winner if the net profit is up compared with the latest investment.
Total Losing Trades: the total amount of losing trades. A trade is considered a loser if the net profit is down compared to the latest investment.
Max consecutive wins: the max amount of consecutive winning trades
Max consecutive losses: the max amount of consecutive losing trades
The chart above uses the default configuration of the indicator. Placed on the BTCUSD market, taking the time range of January 1st, 2018 to January 1st, 2022, 4 years. Buying a BTC amount with 10 USDT every day in that period would generate a more than 500% profit. Compared to the profit amount by just holding the count, which was close to 350% profit, the dollar cost average by period would be much more profitable.
Portfolio Performance - Effects of RebalancingFunction:
- Can be used to evaluate the performance of a portfolio containing 2 assets over a set time interval
- Shows the % return of the portfolio over the time interval defined by the user
- Includes a threshold rebalancing algorithm to show the effects that rebalancing has on the portfolio over the long term
- Created to evaluate of the performance of portfolios containing different weightings of stocks and bonds over time assuming that the user would rebalance the portfolio when asset weights crossed a threshold
Instructions:
- To be used with dividends adjustments turned on
- Add this script to a symbol. e.g. AMEX:SPY
- Click the chart to define the entry time and the exit time. i.e. the time interval
- Define the initial investment of the portfolio. Default setting is $100,000
- Define the second asset to be included in the portfolio. e.g. BATS:AGG
- The strategy comes pre-populated with a portfolio that has a weight of 80% asset 1 and 20% asset 2. i.e. 80% AMEX:SPY and 20% BATS:AGG if the symbols mentioned above were chosen
- The 7 lines show the weighted % return of each portfolio over the time period defined by the user
- Each line (except the blue) is the return based on a different rebalancing threshold. The default settings are 1%, 2.5%, 5%, 10%, 15%, 20%, 30%
- The blue line is the % return of a portfolio that was made up of 100% asset 1 over the time interval. i.e. 100% AMEX:SPY
- Asset weights and rebalancing thresholds are adjustable via the settings
- Each plot can be turned on and turned off via a tick box in the settings
Smart RebalanceThis script is based on the portfolio rebalancing strategy. It's designed to work with cryptocurrencies, but it can work with any market.
How portfolio rebalance works?
Let's assume your initial capital is $1000, and you want to distribute it into 4 coins. This script takes the USDT as the stable coin for the initial money, so in case you want other currency, the pairs must be with that fiat as the quote.
Following our example, you would take BTC, ETH, BNB, and FTT. After selecting the coins, it's time to choose how much allocation is on each. Let's put 25% on each. This way, $250 of our capital on each coin.
After selecting the coins and their allocation, you choose the price change ratio for rebalancing. Let's use 1%. Next, you start to watch the markets. The first thing that happens, following our example, is the BTCUSDT price moving 1% up.
That amount hit the ratio of 1% for the rebalance. Hence, you sell 1% of BTC for USDT and redistribute to the other coins, buying 0.25% of each currency to rebalance the portfolio.
Next, ETHUSDT goes 1% down, time to rebalance again. This time, you need to take 0.33% of each other coin and buy ETH, so this way, it's all divided as the chosen allocation.
Why use rebalancing?
Looks easy, right? It is, but very time demanding. Demands even more if you raise the number of coins you want to distribute. Having a system to do that automatically is a must to work efficiently. Rebalancing spreads the risk among multiple currencies. This way, you earn small when it goes up, but you lose small when it goes down.
What this script helps with portfolio rebalance?
This indicator will not buy/sell for you but will help you choose the best markets for your rebalancing. Which coin will work best in that period? Do I need to have more than 8 coins? How much must be my ratio? Those questions you can answer using this indicator.
What this script has?
Start and End dates
The script will work for a certain period. All calculations will be done in that period.
Coin Ratio %
The amount of price movement of each asset that will be used to calculate the rebalancing
Initial Capital and Broker Fee
The amount of capital to be used on the rebalancing and the broker fee you want to use the strategy. The cost will be applied on every trade, buying or selling the coins.
Assets, allocations, and colors
It's possible to select from 2 to 10 assets to be used on the portfolio. Each purchase must have the allocation %. Suppose the sum of the allocations is different from 100%. In that case, a warning message will appear on the chart instead of the statistics.
Panel and tooltips
There is a panel with a summary of the results
Set allocations automatically
There is an option to make the indicator use the daily asset volume from the day before to determine the allocation percentage of each asset. This option is better if you are unsure how much allocation you want to use on each coin.
Use this indicator as a backtest for your rebalancing strategy. The selected market on the chart will not affect the calculation on this indicator, but the time frame will. The higher the time frame, the higher the coin ratio % must be.
About the code
The code is written to use arrays to store the values of each asset, making the calculations on each candle inside the time range. The for-loops are used to reduce the code length and make it easy to change the analysis of all assets. Finally, the script has some comments on the code.
Portfolio Performance - 2 AssetsFunction:
- Can be used to evaluate the performance of portfolios containing 2 assets over a set time interval
- Created to evaluate of the performance of portfolios containing different weightings of stocks and bonds over time
- Shows the % return of each portfolio over the time interval defined by the user
- Capable of showing the risk adjusted % return of each portfolio over the time interval defined by the user (setting turned off by default)
Instructions:
- To be used with dividends adjustments turned on
- Add this script to a symbol. e.g. NASDAQ:BND
- Click the chart to define the entry time and the exit time. i.e. the time interval
- Define the second asset to be included in the portfolio. e.g. AMEX:VOO
- The strategy comes pre-populated with 6 portfolios with the most common stock/bond weightings (100% stocks/0% bonds, 80% stocks/20% bonds, 60% stocks/40% bonds, et cetera)
- The 6 lines show the weighted % return of each portfolio over the time period defined by the user
- All asset weights are adjustable via the settings
- Each plot can be turned on and turned off via a tick box in the settings
- There are 6 plots that show the risk adjusted returns of each portfolio (setting turned off by default)
TradingPortfolioLibrary "TradingPortfolio"
Simple functions for portfolio management. A portfolio is essentially
a float array with 3 positions that gets passed around
into these functions that ensure it gets properly updated as trading ensues.
An example usage:
import hugodanielcom/TradingPortfolio/XXXX as portfolio
var float my_portfolio = portfolio.init(0.0, strategy.initial_capital) // Initialize the portfolio with the strategy capital
if close < 10.0
portfolio.buy(my_portfolio, 10.0, close) // Buy when the close is below 10.0
plot(portfolio.total(my_portfolio), title = "Total portfolio value")
get_balance(portfolio) Gets the number of tokens and fiat available in the supplied portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The tokens and fiat in a tuple
set_balance(portfolio, new_crypto, new_fiat) Sets the portfolio number of tokens and fiat amounts. This function overrides the current values in the portfolio and sets the provided ones as the new portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
new_crypto : The new amount of tokens in the portfolio.
new_fiat : The new amount of fiat in the portfolio
Returns: The tokens and fiat in a tuple
init(crypto, fiat) This function returns a clean portfolio. Start by calling this function and pass its return value as an argument to the other functions in this library.
Parameters:
crypto : The initial amount of tokens in the portfolio (defaults to 0.0).
fiat : The initial amount of fiat in the portfolio (defaults to 0.0).
Returns: The portfolio (a float )
crypto(portfolio) Gets the number of tokens in the portfolio
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of tokens in the portfolio
fiat(portfolio) Gets the fiat in the portfolio
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of fiat in the portfolio
retained(portfolio) Gets the amount of reatined fiat in the portfolio. Retained fiat is not considered as part of the balance when buying/selling, but it is considered as part of the total of the portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of retained fiat in the portfolio
retain(portfolio, fiat_to_retain) Sets the amount of fiat to retain. It removes the amount from the current fiat in the portfolio and marks it as retained.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
fiat_to_retain : The amount of fiat to remove and mark as retained.
Returns: void
total(portfolio, token_value) Calculates the total fiat value of the portfolio. It multiplies the amount of tokens by the supplied value and adds to the result the current fiat and retained amount.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
token_value : The fiat value of a unit (1) of token
Returns: A float that corresponds to the total fiat value of the portfolio (retained amount included)
ratio(portfolio, token_value) Calculates the ratio of tokens / fiat. The retained amount of fiat is not considered, only the active fiat being considered for trading.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
token_value : The fiat value of a unit (1) of token
Returns: A float between 1.0 and 0.0 that corresponds to the portfolio ratio of token / fiat (i.e. 0.6 corresponds to a portfolio whose value is made by 60% tokens and 40% fiat)
can_buy(portfolio, amount, token_value) Asserts that there is enough balance to buy the requested amount of tokens.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to assert that can be bought
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true if there is capacity to buy the amount of tokens provided.
can_sell(portfolio, amount) Asserts that there is enough token balance to sell the requested amount of tokens.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to assert that can be sold
Returns: A boolean value, true if there is capacity to sold the amount of tokens provided.
buy(portfolio, amount, token_value) Adjusts the portfolio state to perform the equivalent of a buy operation (as in, buy the requested amount of tokens at the provided value and set the portfolio accordingly).
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to buy
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true the requested amount of tokens was "bought" and the portfolio updated. False if nothing was changed.
sell(portfolio, amount, token_value) Adjusts the portfolio state to perform the equivalent of a sell operation (as in, sell the requested amount of tokens at the provided value and set the portfolio accordingly).
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to sell
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true the requested amount of tokens was "sold" and the portfolio updated. False if nothing was changed.
Portfolio IndexPortfolio Index Indicator
Compare a selected asset against a 3 assets portfolio.
Inputs :
- Equity : Default 10000, Initial capital for the portfolio
- %Holding : % of Holding for each Portfolio Element
- Asset in the chart as compared asset
Output :
- Delta between selected asset and portfolio