open, high, low, close, hl2, hlc3, ohlc4, hlcc4, oc2)SMA, EMA, GMA, HARMONIC, TEMA, DEMA, ZLEMA WMA, VWMA, RMA, EHMA, THMA, HMA, DMA, ATR, H, L)SMA_KALMAN, EMA_KALMAN, GMA_KALMAN, HARMONIC_KALMAN, TEMA_KALMAN, DEMA_KALMAN, ZLEMA_KALMAN, WMA_KALMAN, VWMA_KALMAN, RMA_KALMAN, EHMA_KALMAN, THMA_KALMAN, HMA_KALMAN, DMA_KALMAN, ATR_KALMAN, H_KALMAN, L_KALMAN)zz, mrs, hideep, DonchianChannel, tv_ccs, riskturtle, tv_mapm, grid rsi divergence, tv_lsb, +1, closepositiondeleteorders, rebalance)XBTUSD"15s, 1m, 3m, 5m, 10m, 15m, 30m, 45m, 1h, 2h, 3h, 4h, 6h, 8h, 12h, 1d, 1w)true, false)true, false)true, false)0.00, 9999.99]0.00, 9999.99]BitMEX, FTX, Bybit, Binance, Huobi, Kucoin)settings_accounts)hamster-bot_" or "hb_" and then any of your text.0 (the id will be taken from the settings_program.json file)Trade any strategy with TradingView Alerts
{
"ticker": "{{ticker}}",
"side": "{{strategy.order.action}}",
"position": "{{strategy.market_position}}",
"prev_position": "{{strategy.prev_market_position}}",
"size": "{{strategy.position_size}}",
"prev_size": "{{strategy.prev_market_position_size}}"
}
Trend breakout reversal strategy. Based on the ZigZag indicator.
Script for TradingView strategy tester - https://www.tradingview.com/script/uYLTH0bg-hamster-bot-ZZ/
This is one script that allows you to configure 3 working completely different strategies, to select which you need to select the desired preset in the strategy settings
Script for TradingView strategy tester - https://www.tradingview.com/script/U4rB07gZ-hamster-bot-HiDeep-strategy/
TradingView pine script for strategy tester - hamster-bot-MRS-2-simplified-version
MRS - Mean Reversion Strategy
Countertrend Strategy mean reversion strategy
Настройка открывающих/закрывающих ордеров
id - id ордера нужно строго порядковый номер вводить без повтораtype - тип МА (SMA, EMA, GMA, HARMONIC, TEMA, DEMA, ZLEMA, WMA, VWMA, RMA, EHMA, THMA, HMA, DMA, ATR)source - источник цены (open, high, low, close, hl2, hlc3, ohlc4, hlcc4, oc2)len - длинаmultiplier - смещение. 1 это нет смещения, 0.99 это -1%, 1.01 это +1%lot_x - множитель лота (lot = basic_lot * lot_x). Для закрывающего ордера этот параметр на данный момент не используется - бот закрывает всю набраную позицию одним оредромorder_type - тип ордера ("limit" или "market")post_only - настройка post_onlyhidden - скрытая лимитка (только для битмекс)
Настройка лота MRS
в базовых настройках установить:
balance_percentage_ 100
risk_ 1
далее в настройках стратегии настраиваем открывающий ордер. Регулируем параметр
lot_x (lot = basic_lot * lot_x)
lot_x = 1 то размер ордера = 100% балансаlot_x = 0.5 то размер ордера = 50% балансаlot_x = 1.5 то размер ордера = 150% баланса
Ограничитель позиций hamster-bot.
в ограничителе участвует и считается только стратегия Envelope (MRS)
отображение работы ограничителя в интерфейсе:
[100 | (4/64)]
100 - число работающих ботов на данном API
4 - открыто позиций
64 - ограничитель позиций
Ограничитель задается для API. В файле с апи ключом в папке settings_account. нужно добавить параметр "open_positions_limiter": 64,
По умолчанию будет значение 0 - отключен ограничитель.
В настройках стратегии MRS новый параметр
"position_priority": 0,
по умолчанию 0 - не учувствует в ограничителе (не закрывается)
приоритет можно задавать от 0 до 5
5 - наименьший приоритет (закроется в первую очередь)
Алгоритм работы ограничителя:
1) Если число открытых позиций >= значения ограничителя то на парах на которых не открыта позиция снимаются открывающие ордера. Чтобы не открывать новых позиций.
2) если число открытых позиций больше чем задано в ограничителе (позиции могут и одновременно открыться) - тут начинает работать приоритет позиций. среди открытых позиций закроется позиция у которой приоритет 5 далее если все еще позиций больше открыто чем в ограничителе то закроется сначала позиция с приоритетом 4 и далее 3 ... 2... 1... .
3) Позиция с приоритетом 0 не будет закрываться. и не будет останавливать работу после того как число позиций превысит заданный лимит. (не учувствуют в ограничителе)
4) если у лишних позиций равный приоритет - закроется одна случайным образом.
a) ограничение действует на API ключ. (получается и на все субсчета если это ключ от FTX)
b) далее считаются учитываются только стратегии MRS (Envelope) у которых включен ограничитель позиций (приоритет в настройках стратегии не равен 0).
ColorBox
Закрывающая опция.
Простое закрытие по закрытию n-ой свечи.
Можно настроить чтобы позиция закрывалась на следующей или на 3й свече после входа.
Можно добавить условие на цвет свечи - чтобы закрытие было после 2й красной свечи.
Настраивается отдельно для Long и Short позиции.
"use_close_candle_long": true, - вкл для лонга
"close_candle_count_long": 1, - номер свечи после которой закрывать
"close_candle_color_long": "green", - условие на цвет для отключения оставить поле пустым ""
"use_close_candle_short": true,
"close_candle_count_short": 1,
"close_candle_color_short": "red",
pine script code for TradingView strategy tester
// © hamster-bot //@version=5 strategy(title = "[TV] Donchian Channel", overlay = true, commission_value = 0.1) //Settings needlong = input.bool(true, defval = true, title = "Long") needshort = input.bool(true, defval = true, title = "Short") tp = input.float(defval = 7.5, minval = 1, title = "Take-profit, %") tptype = input.string(defval = "3. Trailing", options = ["1. None", "2. Fix", "3. Trailing"], title = "TP type") sltype = input.string(defval = "2. Center", options = ["1. None", "2. Center"], title = "SL type") sizelong = input.float(100, defval = 100, minval = 1, maxval = 10000, title = "Lot long, %") sizeshort = input.float(100, defval = 100, minval = 1, maxval = 10000, title = "Lot short, %") pclen = input.int(50, minval = 1, title = "Price Channel Length") showll = input.bool(true, defval = true, title = "Show lines") timestamp_start = input.time(defval = timestamp("01 Jan 2014 00:00 +0000"), title = "Time Start", inline="time") timestamp_end = input.time(defval = timestamp("30 Dec 2050 23:59 +0000"), title = "Time End ", inline="time") truetime = time > timestamp_start and time < timestamp_end //Price Channel h = ta.highest(high, pclen) l = ta.lowest(low, pclen) center = (h + l) / 2 //Take-profit tpl = 0.0 tpl := tptype == "2. Fix" and strategy.position_size > 0 ? tpl[1] : h * (100 + tp) / 100 //Stop-loss tps = 0.0 tps := tptype == "2. Fix" and strategy.position_size < 0 ? tps[1] : l * (100 - tp) / 100 //Lines tplcol = showll and needlong and tptype != "1. None" ? color.lime : na pclcol = showll and needlong ? color.blue : na sllcol = showll and needlong and sltype != "1. None" ? color.red : na tpscol = showll and needshort and tptype != "1. None" ? color.lime : na pcscol = showll and needshort ? color.blue : na slscol = showll and needshort and sltype != "1. None" ? color.red : na plot(tpl, color = tplcol, title = "TP Long") plot(h, color = pclcol, title = "Channel High") plot(center, color = sllcol, title = "Close") plot(l, color = pcscol, title = "Channel Low") plot(tps, color = tpscol, title = "TP Short") //Background size = strategy.position_size //Trading lotlong = 0.0 lotlong := size != size[1] ? strategy.equity / close * sizelong / 100 : lotlong[1] lotshort = 0.0 lotshort := size != size[1] ? strategy.equity / close * sizeshort / 100 : lotshort[1] mo = 0 mo := strategy.position_size != 0 ? 0 : high >= center[1] and low <= center[1] ? 1 : mo[1] plotshape(mo == 1 ? 0 : 1, style=shape.xcross, location=location.top, size=size.small, color=color.orange, transp=0) if h > 0 longlimit = tptype == "1. None" ? na : tpl longstop = sltype == "1. None" ? na : center strategy.entry("Long", strategy.long, lotlong, stop = h, when = strategy.position_size <= 0 and needlong and truetime and mo) strategy.exit("TP Long", "Long", limit = longlimit, stop = longstop) shortlimit = tptype == "1. None" ? na : tps shortstop = sltype == "1. None" ? na : center strategy.entry("Short", strategy.short, lotshort, stop = l, when = strategy.position_size >= 0 and needshort and truetime and mo) strategy.exit("Exit Short", "Short", limit = shortlimit, stop = shortstop) if time > timestamp_end strategy.close_all() strategy.cancel("Long") strategy.cancel("Short")
pine script code for TradingView strategy tester
// © hamster-bot //@version=5 strategy(title = "[TV] Channel Close Strategy", overlay = true, commission_value = 0.1) len = input(10) timestamp_start = input.time(defval = timestamp("01 Jan 2014 00:00 +0000"), title = "Time Start", inline="time") timestamp_end = input.time(defval = timestamp("30 Dec 2050 23:59 +0000"), title = "Time End ", inline="time") truetime = time > timestamp_start and time < timestamp_end h = ta.highest(high, len) l = ta.lowest(low, len) plot(h) plot(l) if truetime if close > h[1] strategy.entry("Long", strategy.long) if close < l[1] strategy.entry("Short", strategy.short) if time > timestamp_end strategy.close_all() strategy.cancel("Short") strategy.cancel("Long")
pine script code for TradingView strategy tester
// © hb //@version=5 strategy('[TV] Long/Short-bot', overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=50, initial_capital=1000, currency='USD', commission_type=strategy.commission.percent, commission_value=0.05, process_orders_on_close=true) mode = input.string("Long", "", ["Long", "Short"]) // Variables int n = input.int(30, 'n') int auto_cancel = input.int(100, 'Auto cancel') float K = input.float(2.0, 'K', step=0.1) float m = input.float(0.0, 'm') timestamp_start = input.time(defval = timestamp("01 Jan 2014 00:00 +0000"), title = "Time Start", inline="time") timestamp_end = input.time(defval = timestamp("30 Dec 2050 23:59 +0000"), title = "Time End ", inline="time") truetime = time > timestamp_start and time < timestamp_end var bool entry_order = false var bool exit_order = false var int counter = na var float entry_price_short = na var float exit_price_short = na var float entry_price_long = na var float exit_price_long = na // Indicators float stdev = ta.stdev(close, n) float highest = ta.highest(close, n) float lowest = ta.lowest(close, n) float avg = (highest + lowest) / 2 // Trading logic if entry_order and strategy.position_size == 0 and truetime counter += 1 if counter == auto_cancel entry_order := false exit_order := false if strategy.position_size == 0 and strategy.position_size[1] != 0 entry_order := false exit_order := false if not entry_order and not na(avg) and truetime entry_order := true counter := 0 entry_price_short := avg - m * stdev entry_price_long := avg + m * stdev if mode == "Short" if close > entry_price_short strategy.entry('Short', strategy.short, stop=entry_price_short, comment='Entry short') else strategy.entry('Short', strategy.short, limit=entry_price_short, comment='Entry short') if mode == "Long" if close < entry_price_long strategy.entry('Long', strategy.long, stop=entry_price_long, comment='Entry Long') else strategy.entry('Long', strategy.long, limit=entry_price_long, comment='Entry Long') if entry_order and not exit_order and truetime exit_order := true exit_price_short := entry_price_short - m * stdev - stdev * K exit_price_long := entry_price_long + m * stdev + stdev * K if mode == "Short" strategy.exit('Take-profit', 'Short', limit=exit_price_short, comment='Exit short') if mode == "Long" strategy.exit('Take-profit', 'Long', limit=exit_price_long, comment='Exit Long') if time > timestamp_end strategy.close_all() strategy.cancel("Short") strategy.cancel("Long") strategy.cancel("Take-profit") // Graphics display_short = mode == "Short" ? display.all : display.none display_long = mode == "Long" ? display.all : display.none plot(highest, 'Highest line', color.new(color.orange, 0), 2, display=display.none) plot(lowest, 'Lowest line', color.new(color.orange, 0), 2, display=display.none) plot(avg, 'Avg line', color.new(color.navy, 0), 2, display=display.none) plot(entry_price_short, 'Entry price line short', color.new(color.red, 0), 1, offset=1, display=display_short) plot(exit_price_short, 'Exit price line short', color.new(color.green, 0), 1, offset=1, display=display_short) plot(entry_price_long, 'Entry price line long', color.new(color.green, 0), 1, offset=1, display=display_long) plot(exit_price_long, 'Exit price line long', color.new(color.red, 0), 1, offset=1, display=display_long) plot(stdev, 'Stdev', color.new(color.black, 0), style=plot.style_columns, display=display.none) plot(counter)
pine script code for TradingView strategy tester
//@version=5 strategy("[TV] MAPM", overlay=true, default_qty_value=10, default_qty_type = strategy.percent_of_equity, commission_value=0.1, initial_capital = 100, pyramiding=6, currency=currency.USD) group_entry = "Entry conditions" needlong = input.bool(true, title="Use Long", inline="dir", group=group_entry) needshort = input.bool(true, title="Short", inline="dir", group=group_entry) SignalFast = input.int(300, step=10, title="fast_len", inline="signal", group=group_entry) SignalSlow = input.int(600, step=10, title="slow_len", inline="signal", group=group_entry) group_trading = "Averaging" VolumePurchases = input.int(6,step=1,title="+entry count", inline="lot", group=group_trading) StepAddPurchases = input.float(2.5, step=0.1, title="step", inline="lot", group=group_trading) Martingale = input.float(1.6, minval = 1, step = 0.1,title="lot x", inline="lot", group=group_trading) group_exit = "Exit conditions" longProfitPerc = input.float(title="Take Profit (%) Long", minval=0.0, step=0.1, defval=1, inline="tp", group=group_exit) * 0.01 shortProfitPerc = input.float(title="Short", minval=0.0, step=0.1, defval=1, inline="tp", group=group_exit) * 0.01 ///////// Calculation indicator fastAverage = ta.ema(close, 8) slowAverage = ta.ema(close, 49) macd = fastAverage - slowAverage macdSignalF = ta.ema(macd,SignalFast) macdSignalS = ta.ema(macd,SignalSlow) timestamp_start = input.time(defval = timestamp("01 Jan 2014 00:00 +0000"), title = "Time Start", inline="time") timestamp_end = input.time(defval = timestamp("30 Dec 2050 23:59 +0000"), title = "Time End ", inline="time") truetime = time > timestamp_start and time < timestamp_end /////// Plot Data // plot(macdSignalF, style = plot.style_line, color=color.red) // plot(macdSignalS, style = plot.style_line, color=color.blue) ///////// Calculation of the updated value var x = 0.0 if strategy.opentrades>strategy.opentrades[1] x := x + 1 else if strategy.opentrades==0 x := 0 var EnterVolume = 0.0 if strategy.opentrades!=strategy.opentrades[1] and strategy.opentrades[1]==0 EnterVolume := strategy.position_size ///////// Calculation of reference price data entryPrice = strategy.opentrades==0? 0 : strategy.opentrades.entry_price(0) limitLong = strategy.position_avg_price * (1 + longProfitPerc) limitShort = strategy.position_avg_price * (1 - shortProfitPerc) SteplimitLong = entryPrice[0]*(1-StepAddPurchases*x/100) SteplimitShort = entryPrice[0]*(1+StepAddPurchases*x/100) ///////// Conditions for a long bool EntryLong = ta.crossover(macdSignalF, macdSignalS) and needlong and strategy.opentrades==0 and strategy.position_size==0 bool PurchasesLong = needlong and strategy.opentrades==x and strategy.position_size>0 and x<=VolumePurchases bool CancelPurchasesLong = strategy.position_size==0 and strategy.opentrades==0 bool TPLong = strategy.position_size>0 and strategy.opentrades!=0 ///////// Conditions for a Short bool EntryShort = ta.crossunder(macdSignalF, macdSignalS) and needshort and strategy.opentrades==0 and strategy.position_size==0 bool PurchasesShort = needshort and strategy.opentrades==x and strategy.position_size<0 and x<=VolumePurchases bool CancelPurchasesShort = strategy.position_size==0 and strategy.opentrades==0 bool TPShort = strategy.position_size<0 and strategy.opentrades!=0 plotshape(ta.crossover(macdSignalF, macdSignalS) ? 1 : na, style=shape.triangleup, location=location.belowbar, size=size.normal, color=color.green, transp=0) plotshape(ta.crossunder(macdSignalF, macdSignalS) ? 1 : na, style=shape.triangledown, location=location.abovebar, size=size.normal, color=color.red, transp=0) /////////Displaying the level of Take Profit plot(strategy.position_size>0 ? limitLong : na, color=color.fuchsia, style=plot.style_linebr, linewidth=1) plot(strategy.position_size<0 ? limitShort: na, color=color.fuchsia, style=plot.style_linebr, linewidth=1) /////////Displaying the level of add.purchases plot(strategy.position_size>0 ? SteplimitLong : na, color=color.green, style=plot.style_linebr, linewidth=1) plot(strategy.position_size<0 ? SteplimitShort: na, color=color.red, style=plot.style_linebr, linewidth=1) ///////// Entry Long + add.purchases + cancel purchases + Take profit Long if truetime switch EntryLong => strategy.entry("L", strategy.long) PurchasesLong => strategy.entry("+L", strategy.long, qty = EnterVolume*math.pow(Martingale,x), limit = SteplimitLong) CancelPurchasesLong => strategy.cancel("+L") switch TPLong => strategy.exit("TPL", qty_percent = 100, limit = limitLong) ///////// Entry Short + add.purchases + cancel purchases + Take profit Short switch EntryShort => strategy.entry("S", strategy.short) PurchasesShort => strategy.entry("+S", strategy.short, qty = -EnterVolume*math.pow(Martingale,x), limit = SteplimitShort) CancelPurchasesShort => strategy.cancel("+S") switch TPShort => strategy.exit("TPS", qty_percent = 100, limit = limitShort) if time > timestamp_end strategy.close_all() strategy.cancel("+L") strategy.cancel("+S")