Build completely custom trading strategies, using JavaScript. For spot and futures trading.
Use built-in trading methods, candle and indicator data to get started quickly.
For advanced usage it's possible to install and use your own additional javascript modules.
A strategy runs as an async function, executed once every time a trading pair 'cycles' in Gunbot.
Custom strategies are available in Gunbot Ultimate.
Technical info
To get a better idea of what you can and can't do, here's a few facts:
Gunbot takes care of the exchange connection, collecting data and making it available to a strategy
You save strategies in your own .js files inside the Gunbot root folder
There is no Gunbot specific syntax, strategy code is plain JavaScript
Strategy code has access to a single outside object: gb, which contains a number of trading methods and lots of data to work with
There are basically no restrictions to what you can do with the provided trading methods, but of course exchange defined restrictions apply (API usage rate limits, open orders limits, etc.)
There are no protections against double orders, or any kind of other unwanted behavior
Make sure to use JavaScript code compatible with Node v14.4.0
Using console.log() logs to the main Gunbot console logs. Expect to console log all the things
Code runs inside an async function, you can use the awaitkeyword to collect additional data like candle data for a different period
A strategy does not have to return anything, but you can use return statements to easily stop your code at a certain point
A strategy can use custom JavaScript modules. Save these in a folder named user_modules inside your Gunbot folder.
Custom code can be very risky!
Because external modules can be used, be extremely careful when running strategy code you did not write yourself. In theory a malicious actor can gain access over your whole system.
Strategy examples
Coding a strategy can be as difficult as you want it to be.
Even with very basic JavaScript code it's possible to create complex strategies.
The following examples show a few possible ways to code simple strategies. They are silly in functionality, and are not usable for actual trading. Each next example requires a bit more JavaScript knowledge.
Some examples can lead to immediate large trades. Use them to learn, not to trade.
Example 1
Trade USDT-BTC
Invest 100 USDT per trade, allow max 1 buy order
Market buy when price is below lowBB and fastSma is below ema1 (using readily available indicator data)
After the buy order fills, place a sell order 1% above the break even price
Do nothing until this sell order fills
// check if there are any open orders for this pair, // wait until they get filled before doing anything elseif (gb.data.openOrders.length>0){// print a message to the console logsconsole.log('There is an open order, waiting...')// stop doing thingsreturn}// balance "settings": invest 100 USDT, convert into quote amount // needed for calling the buy methodvar baseAmount =100var buyAmount = baseAmount /gb.data.bid// check if no bag is held yet AND price, // lowBB and moving average criteria are trueif (!gb.data.gotBag &&gb.data.bid <gb.data.lowBB &&gb.data.fastSma <gb.data.ema1 ){// conditions are true, fire a market buy order // using the amount calculated in buyAmountgb.method.buyMarket(buyAmount,gb.data.pairName)}// place a limit sell order if we have a bagelseif ( gb.data.gotBag ) {// fire the sell order, pass in the amount, price and pair name. // price is calculated as breakEven * 1.01gb.method.sellLimit(gb.data.quoteBalance,gb.data.breakEven *1.01,gb.data.pairName)}
Example 2
Keep the basic workings from example 1
Additionally calculate a Hull Moving Average (HMA) using the last 50 candle close prices as input
Place the sell order 1% above bid price, at the moment bid goes above HMA
// check if there are any open orders for this pair, // wait until they get filled before doing anything elseif (gb.data.openOrders.length>0) {// print a message to the console logsconsole.log('There is an open order, waiting...')// stop doing thingsreturn}// balance "settings": invest 100 USDT, convert into // quote amount needed for calling the buy methodvar baseAmount =100var buyAmount = baseAmount /gb.data.bid// define a variable to save the Hull Moving Average tovar hma// get indicator data from tulind// use candlesClose data as input, calculate a 50 period Hull Moving Averagegb.method.tulind.indicators.hma.indicator([gb.data.candlesClose], [50],function (err, results) {// tulind returns an array with hma values, // assign the most recent value to the hma variable// notation is a bit awkward, the ".length -1" part // makes it select the very last value hma = results[0][results[0].length-1]});// check if no bag is held yet AND price, // lowBB and moving average criteria are trueif (!gb.data.gotBag &&gb.data.bid <gb.data.lowBB &&gb.data.fastSma <gb.data.ema1) {// conditions are true, fire a market buy order // using the amount calculated in buyAmountgb.method.buyMarket(buyAmount,gb.data.pairName)}// place a limit sell order if we have a bag// make sure the sell method is only called when bid > hmaelseif (gb.data.gotBag &&gb.data.bid > hma) {// fire the sell order, pass in the amount, price and pair name. // price is calculated as bid * 1.01gb.method.sellLimit(gb.data.quoteBalance,gb.data.bid *1.01,gb.data.pairName)}
Example 3
Trade USDT-BTC
Invest 100 USDT per trade, allow max 1 buy order
Code a bit more readable, assigning variables for everything used in conditionals
Buy when a 50 period ema has crossed over a 200 period ema, AND within at most 2 candles later the candle open price is above ema1
Place a sell order 5% above break even
// check if there are any open orders for this pair, //wait until they get filled before doing anything elseif (gb.data.openOrders.length>0) {// print a message to the console logsconsole.log('There is an open order, waiting...')// stop doing thingsreturn}// balance "settings": invest 100 USDT, convert into // quote amount needed for calling the buy methodvar baseAmount =100var buyAmount = baseAmount /gb.data.bid// needed variables for conditional logic// some are left undefined, to set them later when the values can be calculated// emaCrossup is intentionally set false, // only to be set true when a recent crossup is detectedvar gotBag =gb.data.gotBagvar bid =gb.data.bidvar ema50var ema200var emaCrossup =false// get indicator data from tulind// use candlesClose data as input, calculate a 50// and 200 period Exponential Moving Averagegb.method.tulind.indicators.ema.indicator([gb.data.candlesClose], [50],function (err, results) {// tulind returns an array with ema value, // save full array to be able to look for crosses later ema50 = results[0]});gb.method.tulind.indicators.ema.indicator([gb.data.candlesClose], [200],function (err, results) {// tulind returns an array with ema value, // save full array to be able to look for crosses later ema200 = results[0]});// figure out if there was a crossover of ema50 > ema200 in the last two candles// do this in two conditionals, once for the most recent candle // and once for the previous candle// if true, save the result in the emaCrossup variableif ( ema50[ema50.length-1] > ema200[ema200.length-1] && ema50[ema50.length-2] < ema200[ema200.length-2]) { emaCrossup =true}elseif ( ema50[ema50.length-2] > ema200[ema200.length-2] && ema50[ema50.length-3] < ema200[ema200.length-3]) { emaCrossup =true}// buy if there is no bag, and there was a recent ema crossup // and bid price is above ema50if (!gotBag && bid > ema50[ema50.length-1] && emaCrossup) {// conditions are true, fire a market buy order using the amount calculated in buyAmountgb.method.buyMarket(buyAmount,gb.data.pairName)}// place a limit sell order if we have a bag// make sure the sell method is only called when elseif (gotBag) {// fire the sell order, pass in the amount, price and pair name. Price is calculated as bid * 1.01gb.method.sellLimit(gb.data.quoteBalance,gb.data.breakEven *1.05,gb.data.pairName)}
Example 4
Trade USDT-BTC and USDT-XRP
Assume you already have BTC and XRP
Sell 1 BTC when news about BTC tagged "bearish" appears on cryptopanic.com, containing the keyword "Korea", then place a buy order 5% below the current price
Sell 10000 XRP whenever news about XRP tagged "bearish" appears with the keyword "sec"
Do all of this in a single strategy running on a single pair in Gunbot
// require the Cryptopanic module// install https://www.npmjs.com/package/cryptopanic in an outside folder, // then copy the modules to the 'user_modules' folder inside the Gunbot root folderconst_=gb.method.require(gb.modulesPath +'/cryptopanic')// make a connection to Cryptopanicconstcp=newCryptopanic({ auth_token:'<API_TOKEN>' })// creata variables to store status of detected FUDlet koreaFudlet secFud// get data from Cryptopanic and do a simple check if any of the BTC news includes 'Korea', and if there is XRP news that included 'SEC'
// this is not a complete solution, for example it does not consider if news is old or has already been tradedcp.currencies(['BTC','XRP']).filter('bearish').fetchPosts().then((articles) => {// loop trough articles, search if specific strings exist and save resultarticles.forEach(article => {// convert article object to string to easily search its contentsconstarticleString=JSON.stringify(article)if (articleString.indexOf('Korea') >-1&&articleString.indexOf('BTC') >-1) { koreaFud =true }if (articleString.indexOf('SEC') >-1&&articleString.indexOf('XRP') >-1) { secFud =true } });// fire BTC orders if Korea FUD detectedif (koreaFud) {// first sell 1 BTC in a market ordergb.method.sellMarket(1,'USDT-BTC') // wait for the promise to resolve, then check if the order filled before placing a limit buy 5% below current price
.then((result) => {if (result.info.status ==='FILLED') {gb.method.buyLimit(1,gb.data.bid *0.95,'USDT-BTC') } }) }// sell XRP if SEC FUD detectedif (secFud) {gb.method.sellMarket(10000,'USDT-XRP') } })
Only collect data and allow trades in first minute of the hour
Calculate TD Sequential using an external module, transform input data to the needed format
Place buy order when bid price > ema1, using 3m data AND TD Sequential on hourly chart has a buy setup index of 8 or higher
Sell when TD sequential has a sell setup index of at least 11 and price is above break even
Use the lodash module to simplify some code
// strategy uses two external modules: 'lodash' and 'tdsequential'// install them with npm in an outside folder, and copy the modules to the 'user_modules' folder inside the Gunbot root folder
const_=gb.method.require(gb.modulesPath +'/lodash')constTDSequential=gb.method.require(gb.modulesPath +'/tdsequential')// don't do anything unless current minute is first of the hourconstcurrentMinute=newDate(Date.now()).getMinutes();if (currentMinute !=0) {return}// get 300 60m candles, and persistently save them // to Gunbot pair ledger - for no real reason except showing that you can do thisif (_.isNil(gb.data.pairLedger.customStratStore)){// create custom strategy storegb.data.pairLedger.customStratStore = {}}gb.data.pairLedger.customStratStore.myCandles =awaitgb.method.getCandles(300,60,gb.data.pairName)// balance "settings": invest 100 USDT, convert into quote amount needed for calling the buy methodconstbaseAmount=100constbuyAmount= baseAmount /gb.data.bid// to calculate TD Sequential, first transform the collected candle data to the format required by this modulelet candles_60m_transformed = []gb.data.pairLedger.customStratStore.myCandles.close.forEach(function (item, index) {let temp = {}temp.time =item.timestamptemp.close =item.valuetemp.high =gb.data.pairLedger.customStratStore.myCandles.high[index].valuetemp.low =gb.data.pairLedger.customStratStore.myCandles.low[index].valuetemp.open =gb.data.pairLedger.customStratStore.myCandles.open[index].valuetemp.volume =gb.data.pairLedger.customStratStore.myCandles.volume[index].valuecandles_60m_transformed.push(temp)});// calculate TD Sequential and only use the most recent valueconsttdSequentialData=_.last(TDSequential(candles_60m_transformed))// define trading conditionsconstbuyConditions=tdSequentialData.buySetupIndex >=8&&gb.data.bid >gb.data.ema1 &&!gb.data.gotBagconstsellConditions=tdSequentialData.sellSetupIndex >=11&&gb.data.bid >gb.data.breakEven &&gb.data.gotBag// place orders if conditions are trueif (buyConditions) {gb.method.buyMarket(buyAmount,gb.data.pairName)}elseif (sellConditions) {gb.method.sellMarket(gb.data.quoteBalance,gb.data.pairName)}
"real" strategy examples
The following examples are more or less ready made strategies you can build upon.
Note that every custom strategy will require testing on your side. Do not blindly use these examples.
One aspect that's absent in the examples is checking if referenced data is actually defined before firing orders, in some cases this will be an important aspect of a custom strategy. Also consider adding error handling to your code, especially for trading methods that have less chance to succeed than simple market orders.
// forced short wait time between runs that do something// mostly to reduce risk of double orders in case the exchange doesn't update balances immediatelylet enoughTimePassed =falseif (_.isNil(gb.data.pairLedger.customStratStore)) {gb.data.pairLedger.customStratStore = {}if (_.isNil(gb.data.pairLedger.customStratStore.timeCheck)) {gb.data.pairLedger.customStratStore.timeCheck =Date.now() }else {if (Date.now() -gb.data.pairLedger.customStratStore.timeCheck >8000) { enoughTimePassed =true } }}constsetTimestamp=function () {gb.data.pairLedger.customStratStore.timeCheck =Date.now()}if (enoughTimePassed) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// collect indicator datalet rsi10let rsi20gb.method.tulind.indicators.rsi.indicator([gb.data.candlesClose], [10],function (err, results) { rsi10 = results[0] });gb.method.tulind.indicators.rsi.indicator([gb.data.candlesClose], [20],function (err, results) { rsi20 = results[0] }); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// trading conditionsconstentryConditions= ( rsi10[rsi10.length-1] > rsi20[rsi20.length-1] && rsi10[rsi10.length-2] < rsi20[rsi20.length-2] )constexitConditions= (gb.data.gotBag && rsi10[rsi10.length-1] < rsi20[rsi20.length-1] && rsi10[rsi10.length-2] > rsi20[rsi20.length-2] ) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// order handlingconstbuyAmount=parseFloat(gb.data.pairLedger.whatstrat.TRADING_LIMIT) /gb.data.bidif (entryConditions) {gb.method.buyMarket(buyAmount,gb.data.pairName)setTimestamp() }elseif (exitConditions) {gb.method.sellMarket(gb.data.quoteBalance,gb.data.pairName)setTimestamp() }}
// require external modulesconst_=gb.method.require(gb.modulesPath +'/lodash')// forced short wait time between runs that do something// mostly to reduce risk of double orders in case the exchange doesn't update balances immediatelylet enoughTimePassed =falseif (_.isNil(gb.data.pairLedger.customStratStore)) {gb.data.pairLedger.customStratStore = {}if (_.isNil(gb.data.pairLedger.customStratStore.timeCheck)) {gb.data.pairLedger.customStratStore.timeCheck =Date.now() }else {if (Date.now() -gb.data.pairLedger.customStratStore.timeCheck >8000) { enoughTimePassed =true } }}////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// functions used in strategy constsetTimestamp=function () {gb.data.pairLedger.customStratStore.timeCheck =Date.now()}constclearTrailingTargets=function () {if (!_.isNil(gb.data.pairLedger.customStratStore.sellTrailingTarget)) {deletegb.data.pairLedger.customStratStore.sellTrailingTarget }if (!_.isNil(gb.data.pairLedger.customStratStore.buyTrailingTarget)) {deletegb.data.pairLedger.customStratStore.buyTrailingTarget }}if (enoughTimePassed) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// start price trailing after hitting stochRsi targetconstbuyAmount=parseFloat(gb.data.pairLedger.whatstrat.TRADING_LIMIT) /gb.data.bid// handle buy trailing, start trailing after stochRsi target hitsif (_.isNil(gb.data.pairLedger.customStratStore.buyTrailingTarget) &&gb.data.stochRsi <0.1&&!gb.data.gotBag) {// set initial trailing stopgb.data.pairLedger.customStratStore.buyTrailingTarget =spotData.ask *1.005 } else if (!_.isNil(gb.data.pairLedger.customStratStore.buyTrailingTarget) && gb.data.pairLedger.customStratStore.buyTrailingTarget > gb.data.ask * 1.005) {
// update trailing stopgb.data.pairLedger.customStratStore.buyTrailingTarget =spotData.ask *1.005 }// handle sell trailing, start trailing after stochRsi target hitsif (_.isNil(gb.data.pairLedger.customStratStore.sellTrailingTarget) &&gb.data.stochRsi >0.9&&gb.data.gotBag) {// set initial trailing stopgb.data.pairLedger.customStratStore.sellTrailingTarget =gb.data.bid *0.995 } else if (!_.isNil(gb.data.pairLedger.customStratStore.sellTrailingTarget) && gb.data.pairLedger.customStratStore.sellTrailingTarget < gb.data.bid * 0.995) {
// update trailing stopgb.data.pairLedger.customStratStore.sellTrailingTarget =gb.data.bid *0.995 } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// fire orders when hitting a trailing stop, remove trailing stop after placing orderif (!_.isNil(gb.data.pairLedger.customStratStore.buyTrailingTarget) ?spotData.ask >gb.data.pairLedger.customStratStore.buyTrailingTarget :false) {gb.method.buyMarket(buyAmount,gb.data.pairName)clearTrailingTargets()setTimestamp() }elseif (!_.isNil(gb.data.pairLedger.customStratStore.sellTrailingTarget) ?spotData.bid <gb.data.pairLedger.customStratStore.sellTrailingTarget :false) {gb.method.sellMarket(gb.data.quoteBalance,gb.data.pairName)clearTrailingTargets()setTimestamp() }}
How to create and run a custom strategy
To create a new custom strategy, use custom as buy and sell method:
Then specify the filename with your strategy logic and place that file with your strategy logic in your Gunbot root folder - next to the executable file
The data tab gives you control over how pre calculated indicator data is generated. These are indicators you can access in your strategy. You are not limited to using these indicators, this is just easily accessible data.
To run the strategy, simply assign it to a trading pair like you would with any other Gunbot strategy.
It's recommended to disable the global cancel orders option when running a custom strategy.
Trading methods
A strategy can use a number of methods to place or cancel orders, or fetch additional OHLCV data.
Trading methods can be called as function, without waiting for it's return value.
Alternatively, when calling a method you can wait for its Promise to resolve. This way you can create a promise chain using the then() method.
Built in modules
The require module allow you to use additional javascript modules, like those freely available on NPM.
With tulind you can easily calculate your own indicator values.
Available data
A strategy can use all available pair data in Gunbot, easily accessible with unique property names.
Indicators mentioned in the list below are pre calculated using the indicator settings in your Gunbot strategy. Some indicators don't have configurable strategy parameters and just use the generally accepted standard inputs for the indicator.
Storing data
The strategy code runs once every time Gunbot processes the pair. This means that any variable you assign inside the strategy gets reinitialized every time the code runs.
To store variables in a more persistent way, use this object:
gb.data.pairLedger.customStratStore
By default customStratStore is undefined, you need to create it before storing anything in there.
Data saved here generally stays available, and persists between bot restarts. However, there is no guarantee the data stays intact - if for example the process gets killed it is possible the pair ledger gets reinitialized on next run. Gunbot native strategies are coded so that they depend as little as possible on internal persistently stored data, working with exchange provided data as much as possible possible. Consider doing the same when coding custom strategies.
Visualize strategy targets
To easily monitor a custom strategy, trading targets can be visualized as lines on the chart in the GUI.
If you set any of the following targets to a price, it's automatically drawn on the chart.
Just like with every other strategy in Gunbot you can use pair overrides to control individual parameters of a strategy for a specific pair. This example shows how you can refer to an override value:
// Set custom pair overrides in config.js// These show up in the GUI on the chart overview sidebar, and in the pair editor"pairs": {"binance": {"USDT-BTC": {"strategy":"custom","enabled":true,"override": {"USER_SETTING":true,"USER_TARGET":"2" } } } }// Refer to them like this in your strategy codeconstuserSetting=gb.data.pairLedger.whatstrat.USER_SETTINGconstuserTarget=parseFloat(gb.data.pairLedger.whatstrat.USER_TARGET)
The whatstrat object is a merged object of all parameters in a Gunbot strategy and pair overrides, where pair overrides always take precedence over strategy values. Always make sure to parseFloat() inputs where you expect a number, because the GUI saves these as string value.
Parameters saved as pair override do not have to be known parameters in Gunbot, you can create your own settings this way.