How to use Leverage and Margin in PineScriptEn route to being absolutely the best and most complete trading platform out there, TradingView has just closed 2 gaps in their PineScript language.
It is now possible to create and backtest a strategy for trading with leverage.
Backtester now produces Margin Calls - so recognizes mid-trade drawdown and if it is too big for the broker to maintain your trade, some part of if will be instantly closed.
New additions were announced in official blogpost , but it lacked code examples, so I have decided to publish this script. Having said that - this is purely educational stuff.
█ LEVERAGE
Let's start with the Leverage. I will discuss this assuming we are always entering trades with some percentage of our equity balance (default_qty_type = strategy.percent_of_equity), not fixed order quantity.
If you want to trade with 1:1 leverage (so no leverage) and enter a trade with all money in your trading account, then first line of your strategy script must include this parameter:
default_qty_value = 100 // which stands for 100%
Now, if you want to trade with 30:1 leverage, you need to multipy the quantity by 30x, so you'd get 30 x 100 = 3000:
default_qty_value = 3000 // which stands for 3000%
And you can play around with this value as you wish, so if you want to enter each trade with 10% equity on 15:1 leverage you'd get default_qty_value = 150.
That's easy. Of course you can modify this quantity value not only in the script, but also afterwards in Script Settings popup, "Properties" tab.
█ MARGIN
Second newly released feature is Margin calculation together with Margin Calls. If the market goes against your trades and your trading account cannot maintain mid-trade drawdown - those trades will be closed in full or partly. Also, if your trading account cannot afford to open more trades (pyramiding those trades), Margin mechanism will prevent them from being entered.
I will not go into details about how Margin calculation works, it was all explainged in above mentioned blogpost and documentation .
All you need to do is to add two parameters to the opening line of your script:
margin_long = 1./30*50, margin_short = 1./30*50
Whereas "30" is a leverage scale as in 30:1, and "50" stands for 50% of Margin required by your broker. Personally the Required Margin number I've met most often is 50%, so I'm using value 50 here, but there are literally 1000+ brokers in this world and this is individual decision by each of them, so you'd better ask yourself.
--------------------
Please note, that if you ever encounter a strategy which triggers Margin Call at least once, then it is probably a very bad strategy. Margin Call is a last resort, last security measure - all the risks should be calculated by the strategy algorithm before it is ever hit. So if you see a Margin Call being triggred, then something is wrong with risk management of the strategy. Therefore - don't use it!
Margin
BitcoinNinjas NINJASIGNALS V4 (Strategy)BitcoinNinjas NINJASIGNALS V4 (Strategy)
(for Cryptocurrencies, Forex, GunBot, ProfitTrailer, Autoview, CryptoHopper, manual or automated trading, and more)
This is version 4 of our Ninja Signals trading script, with accompanying backtesting strategy.
BitcoinNinjas NINJASIGNALS V4 (Script)
•Allows users to easily set automated buy/long and sell/short alerts on TradingView for use with automatic and manual trading of cryptocurrencies, Forex securities, and more (alerts are compatible with automatic trading software such as GunBot, ProfitTrailer, Autoview, CryptoHopper, and more).
•Synthesizes many powerful indicators [e.g., Relative Strength Index (RSI), Stochastic RSI, Money Flow Index (MFI), Moving Average Convergence Divergence (MACD), etc.) into one powerful script to generate very precise buy and sell signals in virtually all market conditions.
•Features user-defined adjustable calibration settings, allowing traders to customize the script to fit any currency / security on any exchange available through TradingView.com, simply by adjusting settings.
•Buy/Long arrows, Sell/Short arrows, & EMA trendline can be customized or hidden, if desired.
•Complete with backtesting strategy version of script which allows users to test various trading strategies based on the alerts the script generates (see information and screenshots below).
•Backtesting strategy features a user-defined adjustable date range, so traders can estimate performance of the script over specific periods of time, such as the last week, month, or year.
•Script and backtesting strategy feature many user-adjustable settings including stop loss and take profit alerts, an ‘only sell for profit’ option (Gunbot-specific), many different buy and sell filters, and more. Simply adjust the script settings and the backtesting results will automatically refresh.
•Backtesting strategy allows for pyramid buying to test various average down / dollar cost average trading strategies. Simply adjust the number of pyramid buys and the quantity of each buy.
•Fully compatible with margin and futures trading for any currency / security on TradingView.com.
DISCLAIMER: By using our BitcoinNinjas ‘Ninja Signals’ planning script, you agree to the BitcoinNinjas 'Terms of Use'. No sharing, copying, reselling, modifying, or any other forms of use are authorized for our documents, script / strategy, and the information published with them. This informational planning script / strategy is strictly for individual use and educational purposes only. This is not financial or investment advice. Investments are always made at your own risk and are based on your personal judgement. BitcoinNinjas is not responsible for any losses you may incur. Please invest wisely.
DMT 369 DRAGRONFLY STRATSuccessful traders trade with a fixed plan and without emotion, but this a lot harder than many new traders think. Many never master this skill and suffer continual drawdowns on their accounts as they overtrade high leverage positions in volatile markets.
ĐΜŦ Autobot resolves this issue by taking the human element out of the equation, allowing full automation of trades using TradingView alerts to trigger your favourite trading bot, such as Alertatron or 3Commas.
Being a Trend Reversal Indicator based on Volatility & Average True Range, ĐΜŦ Autobot is designed to identify spots in the market that offer suitable scalp and swing trade opportunities.
Due to popular demand we have expanded our ĐΜŦ Autobot product line to include the new ĐΜŦ Autobot Dragonfly 3-6-9 Edition which combines DMT with 3-6-9 Vortex mathematics, our Titan indicator and a multi-ladder scalping strategy to ensure you maintain a preferable average entry when price action moves against your position.
Indicator View
It its default state the DMT Autobot Dragonfly indicator displays key signal information, such as:
• Support & resistance range lines
• Titan Body Small & Large Time Frame lines
• Long & Short entry positions
• Long & Short position ladders
• Profit targets
Dragonfly displays a range between resistance (upper line) and support (lower line) on the chart.
Once the price is granted support in the range the lower line will turn green. As price action develops it will make repeated attempts to test support. If support holds price will attempt to test the resistance line (red).
When resistance is broken and the price is above the upper line, the line will turn blue confirming the bullish momentum and provide a potential buy opportunity.
Price action will make attempts to test the upper line as support and will keep rising while support is granted.
Once support is lost the upper line will become red once more. As price action develops it will make repeated attempts to test resistance. If resistance holds, the price will attempt to test the support line (green).
When support is broken and the price goes below the lower line, the line will turn red confirming the bearish momentum and provide a potential selling opportunity.
Price action will make attempts to test the lower line as resistance and will keep dropping while resistance is granted.
Titan Body
The Titan Body Small & Large time frame options in the indicator add additional trendlines to the chart to provide further clarity and confirmation to the Support & Resistance range indication.
Once price is granted support by the Small Time Frame trend line the line will turn green. As price action develops it will make repeated attempts to test the Small Time Frame support. Once the price is below the Small Time Frame trend line, the line will turn red and can act as resistance in a trend reversal.
When price is granted support by the Large Time Frame trend line the line will turn cyan. As price action develops it will make repeated attempts to test the Large Time Frame support. Once the price is below the Large Time Frame trend line, the line will turn orange and can act as resistance in a trend reversal.
The Titan Body enabled and customized in the indicator’s style settings,
Alert indicators
DMT Autobot Dragonfly Edition generates signals that can be used to scalp trade a volatile asset.
Signals are enabled and customized in the indicator’s input settings Additional options can be found in the options, but it is recommended that these are left at the default, as shown below. The indicator generates many
Entry and Profit levels can be disabled or customized in the indicator’s style settings,
Tradingview Alerts
Using Tradingview alerts, DMT Autobot Dragonfly signals can be used to trigger a trading bot.
To trigger a long or short position, set the Tradingview Alert Condition to DMT 369 Dragonfly and select the long or short option.
It is recommended that long or short positions are configured to trigger Once Per Bar Close
Ladders can also be triggered using alerts. To trigger a ladder order, set the Tradingview Alert Condition to DMT 369 Dragonfly and select the appropriate Long or Short ADD option that is to be triggered by the relevant values defined in the indicator’s configuration.
It is recommended that ladder orders are configured to trigger Once Per Bar,
To trigger a take profit order, set the Tradingview Alert Condition to DMT 369 Dragonfly and select the Long or Short TP option that is to be triggered by the relevant values defined in the indicator’s configuration.
Take profit orders can be configured as Once Per Bar Close or Once Per Minute.
If you wish to trigger a take profit signal immediately when the indicator’s defined take profit value is achieved, then use the Once Per Bar option.
Selecting Once Per Bar Close to generate a take profit signal is a gamble as the candle may close far away from the defined profit target – positive or negative.
While stops can be used, they are not applicable to the recommended ladder strategy.
Ladder Strategy
The DMT Autobot Dragonfly indicator always turns an underwater position into a win by utilizing a ladder strategy.
By using the recommended defaults, the indicator will trigger ladder orders at 3%, 6% & 9% using increasing order sizes,
Order sizes increase exponentially to ensure a good average price is maintained. If you are not using DMT Autobot Dragonfly signals to trigger ladder or take profit orders, please ensure your trading bot is configured to recalculate the new ladder entry and profit target based on the new average position entry price as each ladder is filled.
If you are using DMT Autobot Dragonfly on a leveraged asset, please ensure the leverage position is configured suitably so that your position is not liquidated if the price rapidly moves against you.
If u are looking for more information or access to the script please private msg me in trading view chat thx for support
Companion::DivergentCompanion::Divergent is a combined indicators strategy optimized for Bitcoin Markets and tested on Bitfinex.
Mainly, it is an Ichimoku based strategy.
Used indicators:
- Ichimoku (displayed on chart): trendline analysis;
- Double Hull MA (displayed on chart): trendline analysis;
- MACD (not displayed): confirmative/momentum detection;
- CCI (not displayed): confirmative/momentum detection;
- ATR: used toghether with Ichimoku to determine Stop Loss/Take Profit levels;
- VWMA: For implementing trailing stop orders based on volumes.
What the script does:
- determines trendlines combining mulitple indicators;
- automaticlally calculates Take profit and Stop Loss levels;
- permits automation generating Autoview signals;
- supports for margin trading. Spot trading will be added in the future.
It can be used on 1D or 1H timeframes but it can be adapted for other time frames tweaking the parameters. I used it a lot on Bitfinex on 1H timeframes. Please check parameters: if you will use the strategy on D or higher timeframes, the "Legacy Chikou analysis" option should be checked.
BACKTESTING
Backtest is not leveraged. Defaults are set as follow:
Capital: 10000
Percent of equity used for trades: 10%
Commission: 0.18% this is Bitfinex commission on orders
Change them accordingly on how you trade to get a more realistic backtest results.
KundaliniThe Kundalini is a technical indicator. Based on algorithm calculations, this indicator extrapolates the previous price for the next bar. Plus addition Multi time frame ATR volatility Reading environment for higher conditions
Here is how Dominator is calculated:
1. The study estimates the price projected for the next bar. The estimated price is based on the algorithm method.
2. The study extrapolates this value to find a projected price change for the next bar.
The resulting extrapolated value is shown as a histogram on a lower subgraph. By default, sections of the histogram where the extrapolated value is increasing are shown in green; sections corresponding to the decreasing value are shown in red.
Note: Value projection is purely mathematical as all calculations are based on algorithm averaging of previous values.
Overlay True
The strategy includes 3 different adjustable levels for the ladder , plus automatic adjustable stop loss and takes profit calculated from your average entry price after each ladder adds.
Adjustable BAcktest Window.
1 long signals
3 ladder long add signals
1 short signals
3 ladder short add signals
1 dynamic stop calculated from your average entry price
1 dynamic take profit calculated from your average entry price
Please Private Msg me if you like more info about the script Full pdf available or if you need access to it
thx for your time and support
Dominator Ladder StrategyThe Dominator is a technical indicator. Based on algorithm calculations, this indicator extrapolates the previous price for the next bar.
Here is how Dominator is calculated:
1. The study estimates the price projected for the next bar. The estimated price is based on the algorithm method.
2. The study extrapolates this value to find a projected price change for the next bar.
The resulting extrapolated value is shown as a histogram on a lower subgraph. By default, sections of the histogram where the extrapolated value is increasing are shown in green; sections corresponding to the decreasing value are shown in red.
Note: Value projection is purely mathematical as all calculations are based on algorithm averaging of previous values.
Note: lower subgraph it's just for you to understand and view the waves during the Strategy process Study it's not included in this strategy.
Overlay True
The strategy includes 3 different adjustable levels for the ladder , plus automatic adjustable stop loss and takes profit calculated from your average entry price after each ladder adds.
Adjustable BAcktest Window.
1 long signals
3 ladder long add signals
1 short signals
3 ladder short add signals
1 dynamic stop calculated from your average entry price
1 dynamic take profit calculated from your average entry price
DMT Autobot StrategyDMT its a Modified homemade Trend Reversal Indicator base on Volatility & Average true range
You have to have a defined trading plan and you also have to believe it. For this, it is necessary to have coordination and harmony between the conscious and subconscious part of the individual, That is why it is so difficult for most retail traders to be profitable
ĐΜŦ is designed to identify spots in the market that offer some of the most suitable buy and sell scalping trading opportunities plus swing trading over runs.
ĐΜŦ is comprised of three inputs, which are helping to identify the volatility of a security. To determine the level of volatility there are three ranges included in the equation
Input 1 - Current Day's Range
Input 2 - How High has the security risen from the previous day's close
Input 3 - How low has the security dropped from the previous day's close
One of the greatest challenges for new traders is avoiding drawdowns on their account. Drawdowns are what kills a trader's ability to consistently earn over the long haul and creates enormous emotional pain and turmoil.
Drawdowns are a result of two factors:
(1) over-leverage and
(2) extremely volatile stocks. One could argue that if you get to number 1 right, the volatility is irrelevant; however, these two elements are not always mutually exclusive.
HOW TO USE
Buy and sell signals for entry
and 1 take profit levels
1 adjustable stop loss level for each direction.
easy to set up with Autobot service and alert system trading
[B] hamster-bot ZZ Breakout reversal strategyAttention! This is a beta version of the strategy script >> <<
A backtest should only be done if you understand how the options work. Otherwise, do a test in the release version
Hull Suite strategy + alerts hamster-botThis is a trading strategy on the Hull Suite indicator. 3 Hull variations: HMA, THMA (3HMA), EHMA. The strategy is always in position according to the trend of the indicator.
Leverage Strategy and a few words on risk/opportunityHello traders,
I started this script as a joke for someone... finally appears it could be used for educational content
Let's talk about leverage and margin call
Margin Call
A margin call is the broker's demand that an investor deposit additional money or securities so that the account is brought up to the minimum value, known as the maintenance margin.
A margin call usually means that one or more of the securities held in the margin account has decreased in value below a certain point.
Leverage
A leverage is a system which allows the trader to open positions much larger than his own capital. ... “Leverage” usually refers to the ratio between the position value and the investment needed,
Strat
The strategy simulates long/short positions on a 4h high/low breakout based on the chart candle close.
The panel below shows the strategy equity curve. Activating the margin call option will show when the account would be margin called giving the settings
Casino
I'm not doing any financial recommendation here.
I made this strategy so that people include more risk management metrics into their strategy.
From the code, we see it's fairly easy to calculate a leveraged position size and a margin call flag - when that flag is hit, the system stops trading.
I simplified things to the extreme here but my point is that the leverage is a double-edge sword gift.
Assuming we always take the same position sizing, increasing the leverage speed up how fast a margin could be ..... called. (bad joke? feel free to tell me). Not saying it will, saying it introduces more risk by design.
Then one could say "I'll just turn off that stupid margin call option". And that's when someone starts backtesting with unrealistic market conditions.
Finally...
When I backtest I always assume the worst in every scenario possible (because I'm French), I always try to minimize the risk first (also because I'm French), keeping as close from 0 as possible (French again)
Then I add the "opportunity" component, looking to catch the maximum of opportunity while keeping the risk low.
It's like a Rubix cube puzzle - decreasing the risk is one side of the equation but whenever I try to catch more opportunity... my risks increases.
Then I update my risk... and now the opportunity decreases... (#wut #wen #simple)
Completely removing the risk from a trading strategy isn't something I wouldn't dare doing.
Trading involves risk. Being obsessed by decreasing the risk is what I do BEST :)
Dave
bee ZZBreakdown trading system ( TS ) based on the ZZ indicator ( zig-zag ) using SAR (stop and reverse). The system calculates the long level and short level, depending on the direction of the breakdown - we enter the long or short position. The strategy is always in position (in the market), the strategy being in the long side reverses the position at the short level, and accordingly, on the contrary, it is in short at the long level, thereby fixing profit / loss. The strategy has proved itself to be highly volatile. Strategy tested on BitMEX exchange. It is possible to get acquainted with the results of the strategy by running the script by history.
BTC strategy for margin tradingAlmost identical to the one I published before, but this one includes short orders as well.
I didn't spend much time backtesting, so there may be a different set of parameters that gives better results. Please let me know if you find something!
TB! -=Old Fasion=- [STRATEGY]This is the Strategy version of;
A Good Old Fasion sma/rma trading done as it should be done!
Great for hedging
- Bitfinex
- Poloniex
- Bitmex
- Deribit
No repaint, no false alerts or any other kind of nonsense.
With this strategy version you can determine the most optimal settings.
Those optimal setting you copy into the alert edition and of you go, sending alerts to GunBot, Haasbot, Dragonbot, Trexen, Autoview or whatever makes you happy.
Trading Strat. BITMEX:XBTUSD V2 (by dkukolev) alphaTrading strategy on BitMex XBTUSD , 5 min and 15 min timeframes. Alpha edit.
Trading Strat. BITMEX:ETHUSD V2 (by dkukolev)Trading strategy on BitMex ETHUSD, 5 min and 15 min timeframes.
AMAAwesome oscillator plus MA make a greats result. Avg. position time is 48 hours. Only position reversal. Good trading on ETH and XBT Swap Bitmex. Also working with other params for CFD.
Heikin Ashi Margin Scalping script for BitmexA script made for a lot of trades (scalping) and good solid profits on the Tested and it generates very attractive profits. Test it for yourself.
- Made for BITCOIN / US DOLLAR PERPETUAL INVERSE SWAP CONTRACT XBTUSD on Bitmex.
- Only 40% of these trades are profitable, but within this 40 percent, it catches all the spikes and lows. And therefore a lot more profit then loss. The most loss is generated at the moment BTC is falling still and there is not a lot of volatility.
- I use it to create alerts and sent these to my bot, so i don't have to do manual trading.
You can ask for access and try this strategy for yourself for 5 days. When you are convinced and want to have the script with alerts to be shared with you, I ask for a small donation of 0.02 BTC. This allows me to create other scripts and to improve this script.
I only sell this script to 50 people, so that it remains exclusive.
Bitmex Scalping PRO V2 [PlungerMen]Hello!
Bitmex Scalping PRO V2 is a upgrade version of a Bitmex Scalping Pro
BitMex Scalping PRO V2 can use for every coin
BitMex Scalping PRO V2 is available for all frames
This Script is perfectly functional and works well by me and the best way to use this script is to use it with “Bitmex Long Short" script, both compliment for each other. the "Bitmex Long Short" script is Free, you can find it by searching “Bimex”
If you want to be more accurate and more efficient, more comfortable when you do not want to see too many other indicators, you can register for our Professional edition.
- The Professional Edition supports Level 1 and Level 2 commands ( display at chart : LONG+, long-, SHORT,+,short- ), which are very effective in allocating funds and optimizing your profits
Besides that,You will be supported by personal preferences, profit maximization
- Register for a Professional version will be used 2 Script, Bitcoin -3.33% -3.27% Scalping Pro and Bitmex Long Short Pro
- We will invite you to the signal channel Telgram with the announcement of the bottom and the peak of the BTC -3.33% -3.27% 0.60% -0.13% ,the big variable variable has exists
**We hope you enjoy this script. Your support will help us develop more good quality scripts in the future to serve the community **
**Remember, Like this script and posivite feedback if you are satisfied**
if you have any questions, post a comment ... below here
*********** Guide:
+ option for all frames : Click setting and input high and low for time inteval
+ hide wave trend : Click setting -> click Style --> Up trend Fill or Down trend fill
******
New features: this time we add two lines that can help traders trader safer. When the red line cross above the green line means we are in the downtrend and when the green line cross above the red line, which means we are in a uptrend. This new features will help traders do a safer trade at small time frame.
We have the Script free for the user pass, search keyword " Bitmex Scalping PlungerMen"
-->> 0.2 eth/1 month will be used 2 Script: Bitmex Scalping Pro and Bitmex Long Short Pro <--