// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © algomojo // Algomojo Trading Strategy Carry Forward Strategy/Intraday Strategy with Target/Stoploss // Strategy Name : Halftrend Strategy Version 1.0 // Code Date : 17th Dec 2021 // Coded by Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo) //////////////////////////////////////////////////////////////////////////////////////////////////////////// //Trading Block Description //Block 1 : API Controls + Algomojo Input Controls //Block 2 : Autotrading API data configuration //Block 3 : Backtesting Controls & Target and Stoploss Controls //Block 4 : Trading Strategy and Controls (write your trading strategy in the block //Block 5 : Intraday Function and Buy and Sell Signal Mapping (Signal Mapping is required) /////////////////////////////////////////////////////////////////////////////////////////////////////////// //@version=5 strategy('Halftrend Algomojo Trading Strategy with Target/Stoploss', shorttitle='Halftrend Algomojo', overlay=true,process_orders_on_close=true) import algomojo/automation/14 //Block 1 : API Controls + Algomojo Input Controls //Enter Your Algomojo API Key and API Secret Key am_client_id = input.string(title='Client ID', defval='ZZ0011', group='AlgoControls') am_api_key = input.string(title='API Key', defval='xxxxx', group='AlgoControls') am_api_secret = input.string(title='API Secret Key', defval='xxxxx', group='AlgoControls') am_broker = input.string(title='Broker', defval='ALICEBLUE', options=['ALICEBLUE', 'ANGELONE', 'FIRSTOCK', 'FYERS','MASTERTRUST','SAMCO','TRADEJINI','UPSTOX','ZEBU','ZERODHA'], group='AlgoControls') am_strategy = input.string(title='Strategy Name', defval='Halftrend Strategy', group='AlgoControls') am_symbol = input.string(title='Trading Symbol', defval='RELIANCE-EQ', group='AlgoControls') am_exchange = input.string(title='Exchange', defval='NSE', options=['NSE', 'NFO', 'MCX', 'BSE'], group='AlgoControls') am_quantity = input.int(title='Quantity', defval=1, group='AlgoControls') am_OrderType = input.string(title='Order Type', defval='MARKET', group='AlgoControls') am_Product = input.string(title='Product', defval='NORMAL', options=['NORMAL', 'INTRADAY', 'DELIVERY', 'MARGIN'], group='AlgoControls') am_Mode = input.string(title='Algo Mode', defval='ENABLE', options=['ENABLE', 'LONGONLY', 'SHORTONLY'], group='AlgoControls') ////////////////////////////////////////Block 1 Module Ends//////////////////////////////////////////////////////////////////////// //Block 2 : Autotrading API data configuration [BE,SX,BSR,SE,BX,SSR] = automation.algomodule(am_client_id, am_api_key,am_api_secret,am_broker,am_strategy,am_symbol,am_exchange,am_quantity,am_OrderType, am_Product) ////////////////////////////////////////Block 2 Module Ends//////////////////////////////////////////////////////////////////////// //Block 3 : Backtesting Controls & Live Automation Purpose FromMonth = input.int(defval=9, title='From Month', minval=1, maxval=12, group='Backtesting') FromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group='Backtesting') FromYear = input.int(defval=2018, title='From Year', minval=999, group='Backtesting') ToMonth = input.int(defval=1, title='To Month', minval=1, maxval=12, group='Backtesting') ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31, group='Backtesting') ToYear = input.int(defval=9999, title='To Year', minval=999, group='Backtesting') start = timestamp(FromYear, FromMonth, FromDay, 00, 00) finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) window() => time >= start and time <= finish ? true : false highlighting = input.bool(title='Highlighter On/Off ?', defval=true, group='Intraday Controls') barcoloring = input.bool(title='Bar Coloring On/Off ?', defval=true, group='Intraday Controls') intraday = input.bool(title='Intraday On/Off ?', defval=false, group='Intraday Controls') marketSession = input.session(title='Market session', defval='0915-1500', confirm=false, group='Intraday Controls') risk = input.bool(title='Stoploss/Target On/Off', defval=false, group='Stoploss/Target Controls') type = input.string(title='Type', defval='FIXED', options=['FIXED', 'PERCENTAGE', 'VOLATILITY'], group='Stoploss/Target Controls') stoploss = input.float(defval=10.0, title='Stoploss', group='Stoploss/Target Controls') target = input.float(defval=20.0, title='Target', group='Stoploss/Target Controls') TickSz = input.float(defval=0.05, title='TickSize', group='Stoploss/Target Controls') ATRMultiplier = input.float(title='ATR Multiplier', step=0.1, defval=1.5, group='Stoploss/Target Controls') ATRLength = input.int(title='ATR Period', defval=20, group='Stoploss/Target Controls') iATR = ta.atr(ATRLength) var longCondition = false var shortCondition = false ////////////////////////////////////////Block 3 Module Ends//////////////////////////////////////////////////////////////////////// //Block 4 : Trading Strategy amplitude = input(title='Amplitude', defval=2) channelDeviation = input(title='Channel Deviation', defval=2) showArrows = input(title='Show Arrows', defval=true) showChannels = input(title='Show Channels', defval=true) var int trend = 0 var int nextTrend = 0 var float maxLowPrice = nz(low[1], low) var float minHighPrice = nz(high[1], high) var float up = 0.0 var float down = 0.0 float atrHigh = 0.0 float atrLow = 0.0 float arrowUp = na float arrowDown = na atr2 = ta.atr(100) / 2 dev = channelDeviation * atr2 highPrice = high[math.abs(ta.highestbars(amplitude))] lowPrice = low[math.abs(ta.lowestbars(amplitude))] highma = ta.sma(high, amplitude) lowma = ta.sma(low, amplitude) if nextTrend == 1 maxLowPrice := math.max(lowPrice, maxLowPrice) if highma < maxLowPrice and close < nz(low[1], low) trend := 1 nextTrend := 0 minHighPrice := highPrice minHighPrice else minHighPrice := math.min(highPrice, minHighPrice) if lowma > minHighPrice and close > nz(high[1], high) trend := 0 nextTrend := 1 maxLowPrice := lowPrice maxLowPrice if trend == 0 if not na(trend[1]) and trend[1] != 0 up := na(down[1]) ? down : down[1] arrowUp := up - atr2 arrowUp else up := na(up[1]) ? maxLowPrice : math.max(maxLowPrice, up[1]) up atrHigh := up + dev atrLow := up - dev atrLow else if not na(trend[1]) and trend[1] != 1 down := na(up[1]) ? up : up[1] arrowDown := down + atr2 arrowDown else down := na(down[1]) ? minHighPrice : math.min(minHighPrice, down[1]) down atrHigh := down + dev atrLow := down - dev atrLow ht = trend == 0 ? up : down var color buyColor = color.blue var color sellColor = color.red htColor = trend == 0 ? buyColor : sellColor htPlot = plot(ht, title='HalfTrend', linewidth=2, color=htColor) atrHighPlot = plot(showChannels ? atrHigh : na, title='ATR High', style=plot.style_circles, color=color.new(sellColor, 0)) atrLowPlot = plot(showChannels ? atrLow : na, title='ATR Low', style=plot.style_circles, color=color.new(buyColor, 0)) fill(htPlot, atrHighPlot, title='ATR High Ribbon', color=color.new(sellColor, 90)) fill(htPlot, atrLowPlot, title='ATR Low Ribbon', color=color.new(buyColor, 90)) buySignal = not na(arrowUp) and trend == 0 and trend[1] == 1 sellSignal = not na(arrowDown) and trend == 1 and trend[1] == 0 plotshape(showArrows and buySignal ? atrLow : na, title='Arrow Up', style=shape.triangleup, location=location.absolute, size=size.tiny, color=color.new(buyColor, 0)) plotshape(showArrows and sellSignal ? atrHigh : na, title='Arrow Down', style=shape.triangledown, location=location.absolute, size=size.tiny, color=color.new(sellColor, 0)) alertcondition(buySignal, title='Alert: HalfTrend Buy', message='HalfTrend Buy') alertcondition(sellSignal, title='Alert: HalfTrend Sell', message='HalfTrend Sell') ////////////////////////////////////////Block 4 Module Ends//////////////////////////////////////////////////////////////////////// //Block 5 : Intraday Function and Buy and Sell Signal Mapping //Remove the comments to do the long/short signal mapping //buySignal = longCondition //sellSignal = shortCondition barInSession(sess) => time(timeframe.period, sess) != 0 bool intradaySession = barInSession(marketSession) buy = buySignal sell = sellSignal buy1 = buy[1] sell1 = sell[1] //assign signals if(not intraday) longCondition := buySignal shortCondition := sellSignal if(intraday) longCondition := buySignal and intradaySession shortCondition := sellSignal and intradaySession //Block 4 : Execution Controls if(am_Mode=="ENABLE") if longCondition and strategy.position_size == 0 and window() strategy.entry('BUY', strategy.long, alert_message=BE,comment='BUY') if longCondition and strategy.position_size < 0 and window() strategy.entry('BUY', strategy.long, alert_message=BSR,comment='BUY') if shortCondition and strategy.position_size == 0 and window() strategy.entry('SELL', strategy.short, alert_message=SE,comment='SELL') if shortCondition and strategy.position_size > 0 and window() strategy.entry('SELL', strategy.short, alert_message=SSR,comment='SELL') if(am_Mode=="LONGONLY") if longCondition and strategy.position_size == 0 and window() strategy.entry('BUY', strategy.long, alert_message=BE,comment='BUY') if shortCondition and strategy.position_size > 0 and window() strategy.close('BUY', alert_message=BX,comment='BUY EXIT') if(am_Mode=="SHORTONLY") if shortCondition and strategy.position_size == 0 and window() strategy.entry('SELL', strategy.short, alert_message=SE,comment='SHORT') if longCondition and strategy.position_size < 0 and window() strategy.close('SELL', alert_message=SX,comment='SHORT EXIT') if(intraday) longsquareOff = not intradaySession and strategy.position_size > 0 strategy.close(id='BUY', when=longsquareOff, comment='Square-off',alert_message=BX) shortsquareOff = not intradaySession and strategy.position_size < 0 strategy.close(id='SELL', when=shortsquareOff, comment='Square-off',alert_message=SX) ////////////////////////////////////////Block 4 Module Ends//////////////////////////////////////////////////////////////////////// buycount = ta.barssince(buySignal) sellcount = ta.barssince(sellSignal) color1 = buycount[1] < sellcount[1] ? color.green : buycount[1] > sellcount[1] ? color.red : na barcolor(barcoloring ? color1 : na) long_stop_level = ta.valuewhen(buy1, open - stoploss, 0) long_profit_level = ta.valuewhen(buy1, open + target, 0) short_stop_level = ta.valuewhen(sell1, open + stoploss, 0) short_profit_level = ta.valuewhen(sell1, open - target, 0) if(type=="PERCENTAGE") long_stop_level := ta.valuewhen(buy1, open, 0) * (100-stoploss)/100 long_profit_level := ta.valuewhen(buy1, open, 0) * (100+target)/100 long_stop_level := TickSz * math.round(long_stop_level/TickSz) long_profit_level := TickSz * math.round(long_profit_level/TickSz) short_stop_level := ta.valuewhen(sell1, open, 0) * (100+stoploss)/100 short_profit_level := ta.valuewhen(sell1, open, 0) * (100-target)/100 short_stop_level := TickSz * math.round(short_stop_level/TickSz) short_profit_level := TickSz * math.round(short_profit_level/TickSz) if(type=="VOLATILITY") long_stop_level := ta.valuewhen(buy1, open - iATR*ATRMultiplier, 0) long_profit_level := ta.valuewhen(buy1, open + iATR*ATRMultiplier, 0) short_stop_level := ta.valuewhen(sell1, open + iATR*ATRMultiplier, 0) short_profit_level := ta.valuewhen(sell1, open - iATR*ATRMultiplier, 0) if(risk) if(strategy.position_size>0) strategy.exit('TP/SL', 'BUY', stop=long_stop_level, limit=long_profit_level,alert_message=BX) if(strategy.position_size<0) strategy.exit('TP/SL', 'SELL', stop=short_stop_level, limit=short_profit_level,alert_message=SX) plot(strategy.position_size <= 0 or not risk ? na : long_stop_level, color=color.new(color.red, 0), style=plot.style_circles, linewidth=2) plot(strategy.position_size <= 0 or not risk ? na : long_profit_level, color=color.new(color.green, 0), style=plot.style_circles, linewidth=2) plot(strategy.position_size >= 0 or not risk ? na : short_stop_level, color=color.new(color.red, 0), style=plot.style_circles, linewidth=2) plot(strategy.position_size >= 0 or not risk ? na : short_profit_level, color=color.new(color.green, 0), style=plot.style_circles, linewidth=2)