· 10 months ago · Nov 21, 2024, 09:45 PM
1// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
2// © Maurizio-Ciullo
3
4
5//=============================================================================//
6// www.tv-hub.org - Boilerplate / Template Strategy
7// Version: 1.0
8
9// Description: This is a boilerplate strategy for TradingView PineScript developers
10// to connect their strategies with the TV-Hub trading platform. The script provides
11// a customizable input settings system that generates trade commands to be executed
12// via automated alerts. Developers could use the entire section (or parts of it)
13// between the code comments "Tv-Hub Input Settings" and "End TV-Hub Input Settings"
14
15// To use the trade commands in your alerts, set the following placeholder
16// in the alert message window on TradingView: {{strategy.order.alert_message}}
17
18// Remark: The actual strategy "Parabolic SAR + Regression Channels + Supertrend"
19// is just for demonstration purpose.
20
21// License: MIT License at https://opensource.org/licenses/MIT
22//=============================================================================//
23
24
25//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
26
27//==============================================================================//
28//======================= Paste Your Initial Strategy Inputs ============================//
29//==============================================================================//
30
31//@version=5
32strategy("[tv-hub.org] Boilerplate / Template", shorttitle="TV-Hub Boilerplate / Template Strategy", overlay=true, max_bars_back=1000, max_lines_count=500, calc_on_every_tick = true,
33 //max_bars_back=5000, // Serve Per Caricare Più Storico Per Il Trailing Stop
34 pyramiding=0,
35 initial_capital=1000,
36 commission_type=strategy.commission.percent,
37 commission_value=0.1,
38 slippage=3,
39 default_qty_type=strategy.percent_of_equity,
40 precision=2,
41 default_qty_value=23)
42
43//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
44
45
46//==========================================================================//
47//======================= TV-Hub Input Settings ============================//
48//==========================================================================//
49
50// Strategy Settings
51pair_cur = syminfo.ticker // Fetches the current asset symbol (e.g., BTCUSDT)
52exchange = syminfo.prefix // Gets the exchange prefix (e.g., Binance, Bybit)
53price = math.round_to_mintick(close) // Rounds the close price to nearest tick value
54
55//==== Basic Settings ==========
56// These are the key connection settings required for the strategy to communicate
57// with the TV-Hub platform via webhooks. Traders need to set their API details
58// to enable automated trade execution.
59
60token = input.string("", '⚙️ Access-Key', group="𝙒𝙚𝙗𝙝𝙤𝙤𝙠 𝙏𝙫-𝙃𝙪𝙗 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨", tooltip="Enter your Tv-Hub Access-Key")
61apiName = input.string("", "⚙️ API Key Name", group="𝙒𝙚𝙗𝙝𝙤𝙤𝙠 𝙏𝙫-𝙃𝙪𝙗 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨", tooltip="Enter your API key name")
62exchangeName = input.string("Bybit", "⚙️ Exchange", options=["Bybit", "Bybit-Testnet", "Binance", "Binance-Futures", "Binance-Futures-Testnet", "Bitmex", "Bitmex-Testnet", "OKX"], group="𝙒𝙚𝙗𝙝𝙤𝙤𝙠 𝙏𝙫-𝙃𝙪𝙗 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨", tooltip="Select Exchange")
63
64// ================ Order Type Settings ===============
65
66orderType = input.string("Market", "⚙️ Order-Type", options=["Market", "Limit"], group="Order Type 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨", tooltip="Select the order type. 'Market' orders are executed immediately at the current market price, while 'Limit' orders are placed at a specified price or better.")
67enableBestPrice = input.bool(true, "Use best price (Best Bid/Ask)", inline="121", tooltip="When using limit orders, enabling this option allows TV-Hub to place the order at the current best bid or ask price. If this option is not active, the strategy will set the entry price instead.", group="Order Type 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
68enableOrderChasing = input.bool(false, "Enable order chasing", inline="122", tooltip="When limit orders and ‘Use best price’ are enabled, you can activate order chasing. With each update step, TV-Hub will place the order at the current best price from the order book. By default, updates occur every 20 seconds, up to 180 times. You can adjust this interval from 1 to 300 seconds. Note: The total number of updates remains constant, so shorter intervals result in a shorter chasing period (e.g., a 1-second interval gives 3 minutes of chasing). Be cautious of rate limiting when using low intervals, as exchanges may impose restrictions. If the order is not filled within the chasing period, it will be executed as a market order.", group="Order Type 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
69orderChasingInterval = input.float(title="", step=1, defval=20, minval=1, inline="122", group="Order Type 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
70setOrderType = ',"isMarket":true'
71
72if (orderType == "Limit")
73 // Set the order type to limit if the user selects "Limit" in the settings
74 setOrderType := ',"isLimit":true'
75
76 // Check if "Use Best Price" is enabled
77 if enableBestPrice
78 // If enabled, set the limit price type to "bestPrice" which means TV-Hub will use the current best bid/ask
79 setOrderType += ',"limitPriceType":"bestPrice"'
80
81 // If order chasing is enabled, update the order every x seconds and switch to a market order if not filled
82 if enableOrderChasing
83 // You can remove the option "updateLimitOrderBuyMarketAfterNotFilled":true if you want the order to be canceled after chasing
84 setOrderType += ',"chaseLimitOrder":true,"updateLimitOrderBuyMarketAfterNotFilled":true,"updateLimitOrderTimeInterval":' + str.tostring(orderChasingInterval)
85 else
86 // If "Best Price" is not enabled, the strategy must set a specific limit price.
87 // In this case, the limit price is set to the close price, but strategy developers can use their own custom logic here.
88 setOrderType += ',"limitPriceType":"fixedPrice","price":' + str.tostring(close, format.mintick)
89
90// ============== Risk Management Settings===============
91// These settings govern how position sizing is determined, including
92// whether to use fixed sizes or percentages based on available wallet
93// funds. Users can also define the type of margin and leverage for each trade.
94
95unitsType = input.string("Use Fixed Size (USD)", "⚙️ Units Type", options=["Use Fixed Size (USD)", "Use Absolute Value (BTC, ETH)", "Use Percent (Available)", "Use Percent (Wallet)", "Risk"], group="𝙍𝙞𝙨𝙠 𝙈𝙖𝙣𝙖𝙜𝙚𝙢𝙚𝙣𝙩", tooltip="Select the units type. Then, use the field below to set the trade size based on the chosen units type.")
96units = input.float(10.00, step=1, title="⚙️ Position Size", tooltip="Set your position size based on the selected units type. For ‘Use Fixed Size’, enter the size in the quote asset (e.g., USDT). For ‘Use Absolute Value’, enter the size in the base asset (e.g., BTC, ETH). For all other options, enter a percentage value.", group="𝙍𝙞𝙨𝙠 𝙈𝙖𝙣𝙖𝙜𝙚𝙢𝙚𝙣𝙩")
97Currency = syminfo.basecurrency + syminfo.currency
98margin = input.string("CROSSED", "⚙️ Margin Type ", options=["CROSSED", "ISOLATED"], group="𝙍𝙞𝙨𝙠 𝙈𝙖𝙣𝙖𝙜𝙚𝙢𝙚𝙣𝙩")
99Leverage = input.float(title="⚙️ Leverage ", step=1, defval=10, maxval=125, minval=1, group="𝙍𝙞𝙨𝙠 𝙈𝙖𝙣𝙖𝙜𝙚𝙢𝙚𝙣𝙩")
100
101unitsTypeValue = "absolute"
102if (unitsType == "Use Percent (Available)")
103 unitsTypeValue := "percentBalance"
104if (unitsType == "Use Percent (Wallet)")
105 unitsTypeValue := "percentWallet"
106if (unitsType == "Risk")
107 unitsTypeValue := "risk"
108
109unitsTypeKey = unitsTypeValue == "absolute" ? 'units' : 'unitsPercent'
110
111fixedprice = unitsType == "Use Fixed Size (USD)" ? ',"useFixedSize":true,"fixedQuoteSize":"' + str.tostring(units) + '"' : na
112if (unitsType == "Use Fixed Size (USD)")
113 unitsTypeKey := "fixedQuoteSize"
114
115// ================ Take Profit Settings ===============
116// These settings allow users to define the target take profit and stop loss
117// percentages for their trades. Multiple levels of take profits can be defined
118// with distribution sizing, while stop loss ensures risk is managed.
119
120takeProfitType = input.string("Percent", "⚙️ Take-Profit Type", options=["Percent", "Absolute"], group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨", tooltip="Select the take-profit type. 'Percent' means each target is calculated as a percentage of the entry price, while 'Absolute' requires manually calculated target prices in absolute values to be provided by the strategy.")
121enableTakeProfit = input.bool(true, "Enable Take Profit", inline="221", tooltip="Enable take profit. If ‘Percent’ is selected as the take-profit type, you must provide the percentage distance between each take-profit (TP) step. If ‘Absolute’ is selected, this field can be left empty, and the strategy will calculate the target prices at runtime.", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
122takeProfitDistance = input.float(title="", step=0.1, defval=0.3, minval=0.01, inline="221", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
123targetAmountInPercent = input.bool(true, "Distribution Size", inline="333", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
124sizePerTarget = input.float(90, minval=1, maxval=100, title="", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨", inline="333", tooltip="Set the size distribution in percent for each take profit (TP). The total size across all enabled TPs should not exceed 100%. For example, if 2 TPs are enabled, set 50% for each (TP1 = 50%, TP2 = 50%) to equal 100%.")
125
126TP1 = input.bool(true, "TP1", inline="222", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
127TP2 = input.bool(false, "TP2", inline="222", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
128TP3 = input.bool(false, "TP3", inline="222", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
129TP4 = input.bool(false, "TP4", inline="222", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
130TP5 = input.bool(false, "TP5", inline="222", group="𝙏𝙖𝙠𝙚 𝙋𝙧𝙤𝙛𝙞𝙩 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨")
131
132// The 'takeProfitDistance' represents the percentage distance between the entry price and each take profit (TP) level.
133// Each TP is calculated as a multiple of the base distance.
134// For example, if 'takeProfitDistance' is set to 1%, TP1 will be 1% above the entry price,
135// TP2 will be 2% above the entry price, and so on.
136// The calculations below multiply the base distance to determine the target percentage for each TP level.
137ATP5 = takeProfitDistance * 5
138ATP4 = takeProfitDistance * 4
139ATP3 = takeProfitDistance * 3
140ATP2 = takeProfitDistance * 2
141ATP1 = takeProfitDistance * 1
142
143TP11 = enableTakeProfit and TP1 ? '{"idx":1,"amount":"' + str.tostring(sizePerTarget) + '","takeProfitPercent":"' + str.tostring(ATP1) + '"}' : na
144TP22 = enableTakeProfit and TP2 ? '{"idx":2,"amount":"' + str.tostring(sizePerTarget) + '","takeProfitPercent":"' + str.tostring(ATP2) + '"}' : na
145TP33 = enableTakeProfit and TP3 ? '{"idx":3,"amount":"' + str.tostring(sizePerTarget) + '","takeProfitPercent":"' + str.tostring(ATP3) + '"}' : na
146TP44 = enableTakeProfit and TP4 ? '{"idx":4,"amount":"' + str.tostring(sizePerTarget) + '","takeProfitPercent":"' + str.tostring(ATP4) + '"}' : na
147TP55 = enableTakeProfit and TP5 ? '{"idx":5,"amount":"' + str.tostring(sizePerTarget) + '","takeProfitPercent":"' + str.tostring(ATP5) + '"}' : na
148
149comma1 = not TP1 ? na : ","
150comma2 = TP2 ? "," : na
151comma3 = TP3 ? "," : na
152comma4 = TP4 ? "," : na
153
154//=== Example: Dynamic Take-Profit Calculation for Long Trades ===//
155// This block demonstrates how the strategy can handle take-profit (TP) calculations dynamically for long trades.
156// In this example, the take profits are based on the closing price and a fixed percentage above the entry price.
157// If the take-profit type is set to 'Absolute', each TP level is calculated by adding a fixed percentage to the
158// close price (e.g., TP1 = 1% above close, TP2 = 2%, etc.).
159//
160// The example generates JSON commands with specific target prices for each TP level, which can be sent to TV-Hub.
161// These target prices are calculated as absolute values.
162//
163// Strategy developers can modify this section to apply their own logic for target calculation,
164// such as using volatility-based targets, custom risk-reward ratios, or other price levels.
165// This example focuses only on long trades, and similar logic can be applied to short trades by adjusting the formula.
166
167if (takeProfitType == "Absolute")
168 ATP5 := math.round_to_mintick(close + 0.05 * close) // TP5 is 5% above the close price
169 ATP4 := math.round_to_mintick(close + 0.04 * close) // TP4 is 4% above the close price
170 ATP3 := math.round_to_mintick(close + 0.03 * close) // TP3 is 3% above the close price
171 ATP2 := math.round_to_mintick(close + 0.02 * close) // TP2 is 2% above the close price
172 ATP1 := math.round_to_mintick(close + 0.01 * close) // TP1 is 1% above the close price
173
174 // JSON commands for each take profit level with the calculated absolute target prices
175 TP11 := enableTakeProfit and TP1 ? '{"idx":1,"amount":"' + str.tostring(sizePerTarget) + '","price":"' + str.tostring(ATP1) + '"}' : na
176 TP22 := enableTakeProfit and TP2 ? '{"idx":2,"amount":"' + str.tostring(sizePerTarget) + '","price":"' + str.tostring(ATP2) + '"}' : na
177 TP33 := enableTakeProfit and TP3 ? '{"idx":3,"amount":"' + str.tostring(sizePerTarget) + '","price":"' + str.tostring(ATP3) + '"}' : na
178 TP44 := enableTakeProfit and TP4 ? '{"idx":4,"amount":"' + str.tostring(sizePerTarget) + '","price":"' + str.tostring(ATP4) + '"}' : na
179 TP55 := enableTakeProfit and TP5 ? '{"idx":5,"amount":"' + str.tostring(sizePerTarget) + '","price":"' + str.tostring(ATP5) + '"}' : na
180
181TakeProfit = str.tostring(TP11) + str.tostring(comma1) + str.tostring(TP22) + str.tostring(comma2) + str.tostring(TP33) + str.tostring(comma3) + str.tostring(TP44) + str.tostring(comma4) + str.tostring(TP55)
182TPSSET = enableTakeProfit ? ',"targets":[' + str.tostring(TakeProfit) + '],"targetType":"' + str.lower(takeProfitType) + '","targetAmountInPercent":' + str.tostring(targetAmountInPercent) + '' : na
183
184// ============ Stop Loss Settings ======================
185
186stopLossType = input.string("Percent", "⚙️ Stop-Loss Type", options=["Percent", "Absolute"], group="𝙎𝙩𝙤𝙥 𝙇𝙤𝙨𝙨 𝙖𝙣𝙙 𝙏𝙧𝙖𝙞𝙡𝙞𝙣𝙜 𝙎𝙩𝙤𝙥", tooltip="Select the stop-loss type. 'Percent' calculates the stop-loss as a percentage of the entry price, while 'Absolute' requires a manually calculated stop-loss price to be provided by the strategy.")
187SL = input.bool(true, "Enable Stop-Loss", inline="223", tooltip="If enabled, the stop-loss will be applied. When 'Percent' is selected as the stop-loss type, you must provide the stop-loss percentage. If 'Absolute' is selected, the field can be left empty, and the strategy will calculate the stop-loss price at runtime.", group="𝙎𝙩𝙤𝙥 𝙇𝙤𝙨𝙨 𝙖𝙣𝙙 𝙏𝙧𝙖𝙞𝙡𝙞𝙣𝙜 𝙎𝙩𝙤𝙥")
188stopLossPercentValue = input.float(title="", step=0.1, defval=0.3, minval=0.01, inline="223", group="𝙎𝙩𝙤𝙥 𝙇𝙤𝙨𝙨 𝙖𝙣𝙙 𝙏𝙧𝙖𝙞𝙡𝙞𝙣𝙜 𝙎𝙩𝙤𝙥")
189stoploss = SL ? ',"stopLossPercent":' + str.tostring(stopLossPercentValue) + ',"stopLossType":"' + str.lower(stopLossType) + '"' : na
190
191//=== Example: Dynamic Stop-Loss Calculation for Long Trades ===//
192// This block demonstrates how to calculate the stop-loss dynamically for long trades.
193// If the stop-loss type is set to 'Absolute', the stop-loss price is calculated as
194// 2% below the current close price (i.e., stopLossPrice = close - 2% of the close).
195//
196// The example generates a JSON field for the stop-loss, using the calculated stop-loss
197// price if enabled.
198//
199// Strategy developers can modify this section to implement their own stop-loss logic,
200// such as using volatility-based stop-losses, custom thresholds, or more complex price calculations.
201if (stopLossType == "Absolute")
202 stopLossPrice = math.round_to_mintick(close - 0.02 * close) // For long trades, stop-loss is 2% below the close price
203
204 // JSON stop-loss field, using the calculated stop-loss value
205 stoploss := SL ? ',"stopLoss":' + str.tostring(stopLossPercentValue) + ',"stopLossType":"' + str.lower(stopLossType) + '"' : na
206
207// ==== Trailing Stop Settings ====
208trailing = input.bool(false, "Enabled Trailing", inline="break", group="𝙎𝙩𝙤𝙥 𝙇𝙤𝙨𝙨 𝙖𝙣𝙙 𝙏𝙧𝙖𝙞𝙡𝙞𝙣𝙜 𝙎𝙩𝙤𝙥")
209stopValue = input.float(title="", step=0.1, defval=0.3, minval=0.01, maxval=100, inline="break", group="𝙎𝙩𝙤𝙥 𝙇𝙤𝙨𝙨 𝙖𝙣𝙙 𝙏𝙧𝙖𝙞𝙡𝙞𝙣𝙜 𝙎𝙩𝙤𝙥", tooltip="When trailing is activated, a trailing stop order is executed. The stop-loss will be automatically updated by the exchange as the price moves in your favor based on the threshold percentage provided. For example, if the trailing threshold is 3% and the price rises by 3% from your entry, the exchange will begin adjusting your stop-loss. Note: your leverage does not affect the trailing stop; it is based purely on the price movement in percentage terms.")
210enableBreakEven = input.bool(false, "Enabled Break Even", tooltip="When this option is active, TV-Hub will execute a regular stop-loss order and monitor it. Once the price reaches the defined threshold, the stop-loss will automatically move to your entry price (break even). Note: This feature is not supported on all exchanges. Please refer to the documentation for exchange compatibility.", group="𝙎𝙩𝙤𝙥 𝙇𝙤𝙨𝙨 𝙖𝙣𝙙 𝙏𝙧𝙖𝙞𝙡𝙞𝙣𝙜 𝙎𝙩𝙤𝙥")
211setBreakEven = enableBreakEven ? ',"stopLossToBreakEven":true,"cancelAllDcaOrders":true' : na
212trailingSet = trailing ? ',"useTrailingStopLoss":true,"trailingStopLossPercent":"' + str.tostring(stopValue) + '"' + str.tostring(setBreakEven) + '' : na
213
214// ================== DCA Settings ===============
215
216enableDca = input(false, "Enable DCA (Order-Mesh)", inline = "dca" , tooltip = "Enable DCA (Dollar Cost Averaging) to build an order mesh that captures price wicks or allows DCA. Set the percentage range from your entry/first order and specify the number of trades. The system will evenly distribute your initial order size across the number of orders. Refer to the docs (chapter 1.6) for detailed examples.",group = " 𝙐𝙨𝙚 𝘿𝘾𝘼 (𝙊𝙧𝙙𝙚𝙧-𝙈𝙚𝙨𝙝)")
217dcaPercent = input.float(title='', step=0.1, defval=0.4, minval = 0.1 , inline = "dca" , group = " 𝙐𝙨𝙚 𝘿𝘾𝘼 (𝙊𝙧𝙙𝙚𝙧-𝙈𝙚𝙨𝙝)" )
218dcaOrderCount = input.float(step=1, defval=3, minval = 1, maxval = 10 , title = "⚙️ Enter DCA Orders" , inline = "grid", group = " 𝙐𝙨𝙚 𝘿𝘾𝘼 (𝙊𝙧𝙙𝙚𝙧-𝙈𝙚𝙨𝙝)" , tooltip = "Specify the number of DCA (Dollar Cost Averaging) orders to be placed. These orders will be evenly distributed within the defined price range." )
219setDca = enableDca ? ',"useDca":"true","dcaOrderCount":"' + str.tostring(dcaOrderCount) + '","dcaPercent":' + str.tostring(dcaPercent) + '' : na
220
221// === Advance Settings =====
222
223closeCurrentPosition = input.bool(true, "Close Current Position", tooltip="If enabled, any open position in the opposite direction will be closed. This is useful for flipping positions (e.g., from LONG to SHORT) before opening a new trade.", group="𝘼𝙙𝙫𝙖𝙣𝙘𝙚𝙙 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨" )
224closeSet = closeCurrentPosition ? ',"closeCurrentPosition":true' : na
225
226preventPyramiding = input.bool(false, "Prevent Pyramiding", tooltip="If enabled, new signals in the same direction will be ignored if a position is already open. This prevents pyramiding (adding to an existing position).", group="𝘼𝙙𝙫𝙖𝙣𝙘𝙚𝙙 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨" )
227pyramidingSet = preventPyramiding ? ',"preventPyramiding":true' : na
228
229cancelPendingOrders = input.bool(true, "Cancel Pending Orders", tooltip="If enabled, all pending orders (limit and stop-loss orders) will be canceled before executing the new trade.", group="𝘼𝙙𝙫𝙖𝙣𝙘𝙚𝙙 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨" )
230canSet = cancelPendingOrders ? ',"cancelAllOrders":true' : na
231
232hedge = input(false, "Hedge Mode" , "Enable hedge mode to allow opening both long and short positions simultaneously. This feature is available on Binance-Futures and requires hedge mode to be activated in your Binance account settings." , group = "𝘼𝙙𝙫𝙖𝙣𝙘𝙚𝙙 𝙎𝙚𝙩𝙩𝙞𝙣𝙜𝙨" )
233hedgeset = hedge ? ',"hedgeMode":true' : na
234
235//================== Automated Command Construction =================//
236// When an alert triggers, this section generates a command in JSON format.
237// The command is sent to the TV-Hub platform, where it gets executed based on
238// the provided trade settings like leverage, margin, take profit, and stop loss.
239// The command includes the asset pair, position size (in units or percent),
240// trade direction (buy/sell), risk parameters, and advanced options such as
241// closing positions and handling DCA orders.
242
243buy_command = '{"pair":"' + str.tostring(Currency) + '","' + str.tostring(unitsTypeKey) + '":"' + str.tostring(units) + '","unitsType":"' + str.tostring(unitsTypeValue) + '","exchange":"' + str.tostring(exchangeName) + '","apiKey":"' + str.tostring(apiName) + '","token":"' + str.tostring(token) + '","isBuy":true' + str.tostring(setOrderType) + ',"leverage":"' + str.tostring(Leverage) + '","marginType":"' + str.tostring(margin) + '"' + str.tostring(stoploss) + '' + str.tostring(trailingSet) + '' + str.tostring(setDca) + ' ' + str.tostring(TPSSET) + ' ' + str.tostring(closeSet) + '' + str.tostring(pyramidingSet) + '' + str.tostring(canSet) + '' + str.tostring(hedgeset) + '' + str.tostring(fixedprice) + ',"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '"}'
244sell_command = '{"pair":"' + str.tostring(Currency) + '","' + str.tostring(unitsTypeKey) + '":"' + str.tostring(units) + '","unitsType":"' + str.tostring(unitsTypeValue) + '","exchange":"' + str.tostring(exchangeName) + '","apiKey":"' + str.tostring(apiName) + '","token":"' + str.tostring(token) + '","isSell":true' + str.tostring(setOrderType) + ',"leverage":"' + str.tostring(Leverage) + '","marginType":"' + str.tostring(margin) + '"' + str.tostring(stoploss) + '' + str.tostring(trailingSet) + '' + str.tostring(setDca) + ' ' + str.tostring(TPSSET) + ' ' + str.tostring(closeSet) + '' + str.tostring(pyramidingSet) + '' + str.tostring(canSet) + '' + str.tostring(hedgeset) + '' + str.tostring(fixedprice) + ',"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '"}'
245close_command = '{"pair":"' + str.tostring(Currency) + '","exchange":"' + str.tostring(exchangeName) + '","apiKey":"' + str.tostring(apiName) + '","token":"' + str.tostring(token) + '","isClose":true,"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '"}'
246
247// For debugging purposes: To execute one of the trade commands,
248// uncomment the lines below. Create an alert on TradingView
249// and leave the message window empty.
250//if barstate.islast
251 //alert(buy_command, alert.freq_once_per_bar)
252
253//==============================================================================//
254//======================= End TV-Hub Input Settings ============================//
255//==============================================================================//
256
257//==============================================================================//
258// The following strategy is just for demonstration purpose.
259// Start to build your own trade logic here.
260//=========================|====|====|====|====|====|===========================//
261//=========================v====v====v====v====v====v===========================//
262
263//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
264
265
266//==============================================================================//
267//======================= Paste Your Strategy ============================//
268//==============================================================================//
269
270
271// Entry Exit Long / Short
272
273entry_long = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
274if (entry_long) // and strategy.opentrades == 0
275 strategy.entry('long', strategy.long, alert_message = "Open Long Position", comment = buy_command)
276
277entry_short = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
278if (entry_short) // and strategy.opentrades == 0
279 strategy.entry('short', strategy.short, alert_message = "Open Short Position", comment = sell_command)
280
281
282// Exit long has no condition, the code below is just to understand how to usa close command !!!
283
284// if exit_long
285// strategy.close(id='long', alert_message = "Close Long Position", comment = close_command)
286
287// if exit_short
288// strategy.close(id='short', alert_message = "Close Short Position", comment = close_command)
289
290
291// When creating an alert, remeber to cancell all the code in Message and simply paste: {{strategy.order.comment}}
292
293// Nome Alert: [tv-hub.org] Boilerplate ... Over-The-Clouds ETH/USDT.P BYBIT 4H
294// Commento Alert: {{strategy.order.comment}}
295// Webhook Classico Più Sicuro Ma Più Lento: https://alerts.tv-hub.org
296// Webhook Nuovo Meno Sicuro Ma Più Veloce: https://alerts.tv-hub.org/api/ExecuteTradeSignalClassic