Skip to main content

17 posts tagged with "Tools"

View All Tags

Gunbot Quant: A Standalone, Open-Source Tool for Algorithmic Traders

@boekenbox
@boekenbox
Gunbot Quant: A Standalone, Open-Source Tool for Algorithmic Traders

Most screeners are great at showing you what just moved; very few are built to help you systematically trade what matters next.

If you’re running algos, you don’t really need another page of top gainers or a rainbow of indicators for screenshot flexing. You need a way to define your ideal market conditions once, reuse them reliably, and pipe the results into batched, honest backtests without wrestling multiple tools, fragile copy-paste rituals, or “close enough” parameters that mysteriously underperform in production.

That is the core of Gunbot Quant: a standalone, open-source tool that links saved screener setups directly to batched backtesting runs. And if you use Gunbot DeFi, it can hand those exact tested configs and strategies to your live bot in one click. The trading bot integration offers a repeatable loop from “scan like an algo trader” to “prove it” to “run it,” all in one place you control.

I’ll be upfront: Gunbot Quant isn’t claiming to be the only good screener. There are excellent screeners out there, and if all you want is to eyeball opportunities, you’ll be well-served. The difference here is not a promise that these filters are magically better. The difference is architecture and intent: saved, composable scans that speak the same language as the backtester; caching and compiled computations so re-runs are fast; and reporting that answers the questions systematic traders actually ask before putting capital at risk. The screener is good, but the workflow from saved scan → batch test → live parity → monitoring, is the point.

Free and open-source

Gunbot Quant is free. There’s nothing to sell here - use it, fork it, improve it. Pull requests welcome.


What it is

Gunbot Quant is a research and deployment workflow for algorithmic traders that runs on your machine, talks to multiple data sources, and treats your trading like a reproducible experiment rather than a weekend of tab-surfing.

Gunbot Quant Screenshot

You define a scan once, with liquidity guardrails, a handful of momentum, volatility, and trend metrics, and any heuristics you care about. Save it with a clear name, and reuse it every time that strategy archetype comes up. When you hit “go,” the screener assembles a candidate set that fits your rules, and the backtester runs that strategy (or a portfolio of strategies) across all those candidates in one sweep. The reports give you risk-adjusted results, portfolio roll-ups, and exit-reason diagnostics so you can tell the difference between a pretty equity curve and a setup that earned its keep. You can also cross-check assumptions against the public backtesting archive.

If you run Gunbot, you can send the exact tested configuration to live trading in a click; if you don’t, you can still use everything else: the scan, the tests, the reports, as your independent research layer.

This matters because it keeps you structured. You don’t “think” you ran the same parameters live that you tested: you know you did. You don’t “hope” your live pair is still the best place to run that setup: you can benchmark it against the rest of the market and see where it stands. And you don’t rebuild your screeners from scratch every time a regime changes: you pull up the saved scan for that regime and batch test again, which means your process gets better with time instead of noisier.

The real win

Plenty of solid screeners exist. The edge here is that saved screener setups flow straight into batched backtests with the same parameters and symbol normalization. Define once, reuse often, compare over time.


Screener: a research starting point you can save and reuse

A screener for algos is less about colorful dashboards and more about not wasting your backtest compute budget.

Gunbot Quant pulls from any CCXT-compatible crypto exchange and from Yahoo Finance for equities and ETFs. It does the boring but essential work of normalizing symbols so “the thing you tested” is “the thing you can trade.” Think of the process as a funnel: start with a wide net of higher-volume assets, then apply increasingly specific filters.

You can filter by liquidity using trading volume so you don’t get lured into thin books that betray your fills. You can look at price relative to different SMAs to avoid testing trend followers in chop or mean-reverters in one-way markets. You can measure momentum with rate-of-change windows that match your timeframe. You can gate by normalized volatility with ATR percentage so you don’t hand a grid strategy a dead pair or throw a breakout strategy at a coin that whipsaws itself to pieces. Oscillators like RSI and Stoch RSI are available when your logic needs them, and there’s room for pragmatic heuristics, volatility “consistency,” recent volume concentration, and spike filters that keep obviously unsuitable candidates out of the queue.

Saving is the point. Instead of a one-off filter you forget next month, you keep a named, versionable scan like “TrendCandidates-Daily-HighADX” or “LowVol-MeanRev-4h.” When market tone shifts, you run the same scan and you get a fresh ranked list that passes the same gates as last time. That simple act is what makes a process feel systematic rather than improvised.

Symbols & exchanges

Markets naming gets messy across platforms. The app normalizes symbols so your research symbol matches the live tradable pair on your exchange.

Available screener metrics

The metrics are chosen to provide a holistic view of an asset's character, covering volume, momentum, trend, volatility, and risk.

CategoryMetric"Why" this metric is useful
Volumeavg_vol_30d_quoteChecks that the asset has sustained liquidity, which is critical for executing trades at expected prices.
rel_vol_10d_quoteIdentifies assets with recent spikes in interest, which can precede significant price moves.
Momentumroc_*p familyMeasures the strength of price movement over different time horizons, important for trend-following strategies.
Trendprice_vs_sma*Quickly determines if an asset is in a short-term or long-term uptrend or downtrend.
sma50_vs_sma200Identifies major trend shifts (Golden/Death Crosses), a cornerstone of classical technical analysis.
adx_14pDistinguishes between a strong trend (good for trend-following) and a ranging market (good for mean-reversion).
Volatilityatr_pct_14pNormalizes volatility as a percentage of price, allowing for fair comparison between assets of different prices. Helps filter out assets that are too flat or too erratic.
Oscillatorrsi_14p, stochrsi_*Identifies potential overbought or oversold conditions, forming the basis for mean-reversion strategies.
Heuristicsvolatility_consistency, max_daily_spike_pct, volume_concentration_pctThese are risk management metrics. They help filter out assets that may look good on paper but are prone to unpredictable spikes, flash crashes, or "pump and dump" volume patterns.

Backtesting engine: fast, batched, reproducible

The backtester is where you prove ideas, and its job is to keep up with how you actually work. You can take a saved screener result, run a strategy (or a few variants) across a slate of symbols in one go, and get a report you can trust without babysitting the process. Launch runs directly from any saved scan or from an explicit symbol list; the engine keeps the plumbing aligned: timeframes, warm-ups, symbol normalization, so the numbers you compare are apples-to-apples. Each run writes out the artifact set you expect: per-trade ledger, equity and drawdown series, exit-reason attribution, and a portfolio roll-up when you test more than one market.

Speed comes from deliberate engineering. Historical data is cached locally in columnar Parquet, so repeat runs don’t waste time refetching or reparsing; indicator math is JIT-compiled with Numba so multi-symbol sweeps complete in minutes rather than afternoons; and the engine avoids recomputation when your only change is a filter or a parameter tweak. In practice, scanning ten candidates and retesting a few strategy variants becomes a rhythm you can run before coffee gets cold, not a weekend project.

Reproducibility is treated as a first-class feature. Each report records which screener produced the candidates (name, saved definition, timestamp), which strategy configuration or alias you ran, the exact parameter set, the data window, and the fee/slippage model in force. If you prefer working from the command line, scenario files let you declare a base config and then define small, explicit overrides for symbols, strategies, or params, which makes A/B (or A/B/C) testing read like a lab notebook instead of a pile of screenshots.

The engine covers two common shapes of systematic trading without forcing one into the other. For straightforward directional systems, trend followers, mean-reverters, breakouts, you run fixed historical windows and get the risk-aware picture you need: return, Sharpe/Sortino, drawdown depth and duration, hit-rate and average trade characteristics, plus the exit-reason breakdown that shows whether profits come from the logic you intended or from a stop doing too much of the work. For inventory-carrying or market-neutral styles such as grids, a continuous evaluation path tracks compounding and inventory effects explicitly.

Candle-open execution

By default, included Gunbot strategies generally enter and exit on candle open. That keeps the strategies aligned with what’s realistically executable as a backtest and avoids intra-bar fantasy fills.


Strategy library: familiar archetypes, easy to tinker

The built-in library covers the archetypes most traders actually use, so you can focus on where and how to trade rather than reinventing entry signals.

  • For Mean-Reversion Traders: If you believe prices revert to an average, you’ll recognize the RSI_Reversion (buys oversold, uses ATR stop), BB_Reversion (fades outer band excursions), and Stochastic_Reversion. There’s also a combo that requires oscillator agreement and exits at fixed ATR multiples for tighter risk management.
  • For Trend Followers: If you believe trends persist, the library offers an EMACross, a MACD_Cross, a Supertrend_Follower (where the indicator line doubles as a trailing stop), and a Heikin-Ashi approach that smooths price action to reduce noise.
  • For Volatility and Breakout Traders: If you trade changes in market energy, you have a classic Donchian_Breakout and a Keltner_Squeeze_Breakout to separate real expansions from random noise.
  • For Market-Neutral Approaches: The continuous Grid_Strategy is designed to profit from volatility regardless of direction, with its own per-pair compounding logic.
  • For Hybrid and Adaptive Systems: There’s a “buy the dip in an uptrend” model that gates mean-reversion entries behind a slow-MA trend filter, and the self-optimizing Dynamic_Momentum_Optimizer that retunes itself to recent conditions.

In practice, traders often keep a small roster of systems that match their personality. Gunbot Quant makes it straightforward to test a few variants of each, bump a parameter for sensitivity, tighten a stop, and see differences play out in a single report.

Strategy library scope

The included strategies are not 1:1 emulations of existing Gunbot strategies. Gunbot’s native strategies are often quite complex and combine stateful behaviors that aren’t efficient to backtest generically. The library here is a clean suite of common and less-common technical approaches (i had some fun with the dynamic optimizer strat) that are transparent, auditable, and easy to benchmark.


For strategy developers: a look inside a Gunbot Quant JS file

The strategies are written in vanilla JavaScript for compatibility with Gunbot’s custom strategy runtime. They’re designed to be self-contained and readable, which makes them good templates for customization.

Here is the annotated structure of a typical strategy, rsi_reversion.js:

/*
* Gunbot Quant Strategy: RSI_Reversion
* A brief summary of the logic and a table of configurable parameters.
* This header is read by the UI to populate help text.
*/

// Gunbot requires this to be initialized. It's a persistent, per-pair data store.
gb.data.pairLedger.customStratStore = gb.data.pairLedger.customStratStore || {};

/* -------------------------------------------------------------------------
* STATE INITIALISATION: The strategy's memory.
* ------------------------------------------------------------------------- */
const store = gb.data.pairLedger.customStratStore;
if (typeof store.state !== "string") store.state = "IDLE"; // "IDLE" | "IN_POSITION"
if (typeof store.stopPrice !== "number") store.stopPrice = 0;
// ... other state variables as needed

/* -------------------------------------------------------------------------
* INDICATOR IMPLEMENTATIONS: Self-contained TA functions.
* ------------------------------------------------------------------------- */
const indicator_helpers = {
rsi: function (source, length) { /* ... RSI calculation logic ... */ },
atr: function (high, low, close, length) { /* ... ATR calculation logic ... */ }
};

/* -------------------------------------------------------------------------
* ORDER HANDLERS: Wrappers for Gunbot's buy/sell methods.
* ------------------------------------------------------------------------- */
const buyMarket = async function (amount, exchange, pair) { /* ... gb.method.buyMarket call ... */ };
const sellMarket = async function (amount, exchange, pair) { /* ... gb.method.sellMarket call ... */ };

/* -------------------------------------------------------------------------
* STATE RECONCILIATION: Syncs strategy state with Gunbot's reality.
* ------------------------------------------------------------------------- */
function reconcileState() {
// Checks gb.data.gotBag and gb.data.openOrders to see if we are in a position,
// then updates store.state accordingly. This corrects state after manual trades or restarts.
}

/* -------------------------------------------------------------------------
* TRADING DECISION: The core logic function.
* ------------------------------------------------------------------------- */
async function decideTrade() {
reconcileState(); // Always sync first.

// 1. Read parameters from Gunbot's config (`whatstrat` object)
const rsiPeriod = parseFloat(whatstrat.GQ_RSI_REVERSION_PERIOD || 14);
// ...

// 2. Calculate indicators
const rsiValues = indicator_helpers.rsi(candlesClose, rsiPeriod);
const rsi = rsiValues[iLast];
// ...

// 3. (Optional) GUI enhancements
const sidebar = [];
sidebar.push({ label: 'RSI Value', value: rsi.toFixed(2) });
gb.data.pairLedger.sidebarExtras = sidebar;

// 4. Implement strategy logic using an IF/ELSE block for states
if (store.state === "IDLE") {
const wantToEnter = rsi < rsiOversold;
if (wantToEnter) {
await buyMarket(costQuote, exchangeName, pairName);
}
} else if (store.state === "IN_POSITION") {
const wantToExit = rsi > rsiOverbought || ask < store.stopPrice;
if (wantToExit) {
await sellMarket(quoteBalance, exchangeName, pairName);
}
}
}

/* -------------------------------------------------------------------------
* DRIVER: The entry point called by Gunbot on every tick.
* ------------------------------------------------------------------------- */
await decideTrade();

Optional Gunbot handoff and benchmarking

Everything above is fully useful even if you never touch Gunbot. If you do, the loop gets tight in a satisfying way: after a batch test, you can push the winning configuration directly to your Gunbot instance. The tool handles the annoying parts: mapping your research symbol to your Gunbot notation, creating the pair and strategy, and sending the exact parameters you just tested.

Once you’re live, the benchmarking tools are built to answer a simple question: is this still the best place to run this setup? You can take your live strategy and compare it against the rest of the eligible market with the same logic. If the rankings start to show a better candidate, you can rotate before lag turns into losses.


CLI for repeatable experiments

If you prefer to script your life, the command-line interface is there. You define a base configuration and then declare a list of scenarios that override only what’s different.

Example: design a CLI scenario to test two RSI_Reversion configurations against a default EMACross on BTCUSDT.

  1. Open gunbot_quant/config/scenarios.py.
  2. Add a new dictionary to the SCENARIOS list:
{
"name": "Multi_RSI_vs_EMACross_BTC",
"params": {
"EXCHANGE": "binance",
"TIMEFRAME": "4h",
"BACKTEST_START_DATE": get_date_relative_to_now(days=365),
"SYMBOL_SELECTION_METHOD": "EXPLICIT_LIST",
"SYMBOLS": ["BTCUSDT"],
"STRATEGIES": [
{
"name": "RSI_Reversion",
"alias": "RSI_Sensitive_Config",
"params": {
"GQ_RSI_REVERSION_PERIOD": 10,
"GQ_RSI_REVERSION_OVERSOLD": 25
}
},
{
"name": "RSI_Reversion",
"alias": "RSI_Conservative_Config",
"params": {
"GQ_RSI_REVERSION_PERIOD": 21,
"GQ_RSI_REVERSION_OVERSOLD": 35,
"GQ_RSI_REVERSION_ATR_MULT": 3.0
}
},
"EMACross"
]
}
}
  1. Run the scenario from your terminal:
python -m gunbot_quant.cli.main run Multi_RSI_vs_EMACross_BTC

The engine will produce a single report comparing the three tests, so you can see which configuration performed best. All reports can be viewed in the GQ frontend. This explicit approach is useful for long-term, systematic research.


Limitations

No tool can promise you winners. The screener will not divine tomorrow’s breakout, and the backtester is not a time machine: it’s a disciplined mirror that shows you what would have happened under the rules you gave it. Liquidity filters reduce but do not eliminate execution risk; risk-adjusted metrics illuminate quality but don’t guarantee persistence.

Backtesting history is limited by exchange candle data availability. Some exchanges are more generous than others.

:::warning Avoid overfitting by convenience Batch testing makes it easy to try hundreds of variations. Don’t let that become parameter fishing. Lock a baseline, evaluate on multiple markets/regimes, and only promote changes that improve risk-adjusted metrics and drawdown behavior, not just headline returns. :::


Wrap-up

Gunbot Quant is a straightforward way to do saved, algo-first market screeners combined with batched backtests, and, if you want, to let those exact tested configurations go live in one click in Gunbot.

It runs locally, it’s open-source under the MIT license, and it’s extensible. If you’re the kind of trader who prefers a repeatable edge over a lucky screenshot, this might be useful to you.

GitHub: https://github.com/GuntharDeNiro/gunbot-quant

StepGrid Strategy: Fee-aware Grid Trading in Spot Markets

@boekenbox
@boekenbox
StepGrid Strategy: Fee-aware Grid Trading in Spot Markets

StepGrid: Turning Volatility Into Structured, Fee-Aware Profits

Grid bots have been around for years, but most of them share the same weakness: they buy and sell at fixed price intervals without caring about the actual cost of the position that is building underneath. When the market comes back up, a classic grid may close parts of its bag at a loss because the bot never looks at fees or at how many units remain.

StepGrid was designed to fix that flaw. It keeps a running “unit cost” line that represents a full-position break-even, including trading fees, and it refuses to hit the market below that line unless a slice of the position can be closed at a genuine profit. In practice, this small upgrade changes the entire character of a grid. Profits are harvested earlier, losing partials disappear, and the trader gains a predictable exit, even when the grid has stacked twenty or forty buys during a deep drawdown.

How StepGrid Thinks About a Trade

The moment StepGrid fires its first buy, it stamps that execution price as a reference. From there it watches both directions:

  • Downward: Each time price falls by one grid step, the bot checks that it still has room under MAX_BUY_COUNT. If so, it spends another TRADING_LIMIT.
  • Upward: When price rises by one grid step, the bot arms a trailing sell. If the trailer finishes above the calculated unit-cost line, the bot can unload part or all of the bag.

Because unit cost is recalculated after every fill, the break-even line keeps sliding lower while the position deepens. Eventually the market will revisit that line. When it does, StepGrid has two options. If the move is sharp and a full close is cheaper than fees, it sells everything. If the move is hesitant, it can sell a fraction, provided PROTECT_PARTIAL_SELL confirms that the slice alone is green.

Choosing a Step Size

Most users leave AUTO_STEP_SIZE set to true. The bot then measures Average True Range over the last ATR_PERIOD candles, multiplies it by 1.5, and compares the result with two times the fee percentage. The larger of those two values becomes today’s step. The advantage is obvious: when volatility expands, StepGrid widens its ladder. When the market goes quiet, steps tighten and more trades fire.

Manual spacing still has its place. Event traders often disable auto stepping, enter a STEP_SIZE that matches the expected headline move, and turn ENFORCE_STEP on. Enforcement forces every buy and sell to respect those exact levels, which keeps position size predictable in news-driven spikes.

Position Sizing and Capital Risk

Grid strategies live or die on exposure management. StepGrid makes that explicit by linking three parameters:

  1. TRADING_LIMIT – the capital per buy.
  2. MAX_BUY_COUNT – the maximum number of buys.
  3. KEEP_QUOTE – the amount of quote the bot must leave untouched for fees or withdrawals.

Multiply the first two and you know the worst-case bag size. That figure should sit well below your total account, ten to twenty percent is a common ceiling. Raise MAX_BUY_COUNT because you fear a long winter and you must lower TRADING_LIMIT to keep risk constant. The math never changes.

A Typical Cycle in Practice

Consider a trader who runs USDT-BTC with a two-thousand-USDT account, a TRADING_LIMIT of 1000 USDT, and MAX_BUY_COUNT set to twenty.

  • Phase one: The market dips five percent. StepGrid logs three buys, each at a fresh low. Unit cost has moved down with the bag and now sits roughly two percent under the first order.
  • Phase two: Price finds a floor, drifts sideways, then rallies. As soon as it has climbed a full step, the bot arms a trailing sell. Volatility is still high, so the step is wide; the trailer finishes well above fees.
  • Phase three: The trailing stop hits and closes one-third of the position, an amount chosen automatically by the bot because the bag is already in profit territory.
  • Phase four: Unit cost recalculates. With fewer coins left, it rises a little. Price pushes higher again and this time the bot sees that a full exit at break-even plus fees is within reach. It sells the rest. The cycle ends green and resets.

During that entire sequence the trader never touched a button. The only manual decision was where to put TRADING_LIMIT and MAX_BUY_COUNT on day one.

When to Change the Defaults

Most StepGrid setups work out-of-the-box, but three scenarios often require tweaks:

  • Extremely tight spreads with maker rebates: Lower MIN_VOLUME_TO_SELL so the bot can realize tiny gains without tripping exchange minimums.
  • Illiquid altcoins: Turn ENFORCE_STEP on. This reduces the chance that a thin order book drags a trailer into a worse-than-step fill.
  • Long-term accumulation: Disable SELL_ENABLED or enable FOREVER_BAGS. StepGrid will buy dips forever and never calculate a full exit, effectively dollar-cost averaging with grid precision.

Backtesting: Proof Before Money

Gunbot Pro owners can replay trades with BF_SINCE and BF_UNTIL. Deep testing builds tick-level candles so StepGrid behaves as if it were live. Two passes, one in a trending month, one in a ranging month, are enough to check whether your parameters keep drawdown inside plan and still let the bot exit profitably. If the backtest shows prolonged underwater periods or too many skipped sells, the first levers to pull are wider step size and a lower maximum buy count.

Final Thoughts

StepGrid will not outperform every strategy in every market. No robot does. What it offers is transparency and predictability: you always know your worst-case size, your dynamic break-even, and the exact rules that fire each order. That clarity is rare in grid trading and it frees the operator to focus on the higher-level decision, picking the pairs and deciding how much capital to commit. Get those calls right and StepGrid will handle the rest, one step at a time.

Gunbot Xmas 2024 Trading Tournament – Watch Live

@boekenbox
@boekenbox
Gunbot Xmas 2024 Trading Tournament \u2013 Watch Live

The Gunbot Xmas 2024 Trading Tournament is happening right now, and it’s been a blast to watch so far. Running from 27 December 2024 to 26 January 2025, this event brings together some of the most creative minds in the Gunbot community. If you love trading, bots, or just seeing clever ideas in action, this is for you.

Where to Watch?

You can catch it live right here:

Or hop over to YouTube to join the chat.

What’s This Tournament About?

This isn’t just a regular competition. It’s a chance for Gunbot traders to show off how they use the platform in all sorts of clever ways. We’re seeing strategies that range from straightforward builder setups to custom-coded logic that’s built from scratch. It’s good to see what people are building, and no two approaches are the same.

Here’s a quick overview of the kinds of strategies that are competing:

  • Builder Strategies – Using Gunbot’s built-in tools to craft smart, adaptive setups.
  • Native + Tweaked Logic – Taking a default strategy and supercharging it with personal touches through autoconfig.
  • Custom Code – Completely unique trading algorithms written specifically for this tournament.

The variety here is what makes it so cool. If you're a new trader or a seasoned dev, there’s something to learn from these setups.


What’s on the Line?

The tournament isn’t just about pride (though there’s a lot of that, too). The winner of the official category gets:

  • 1268 USDT
  • 2.06 SOL

And here’s a fun twist: the prize pool comes from the contributions of the losers from the last competition. Talk about motivation to win!

This tournament is also the finals for the Gunbot Community Cup 2024, so there’s plenty of history and rivalry behind it.


How Are Winners Picked?

The leaderboard is not based only on who makes the most money. It uses a performance metric that accounts for consistency, risk, and overall efficiency. If you’re curious about how it all works, there’s a great write-up here: Comparing Trading Bot Performance, this post got updated with the full code for the metric.


Why Tune In?

Honestly, it’s just fun to watch. The Gunbot community is a tight-knit group, and events like this are a reminder of how much creativity and innovation people bring to the table. If you're watching for inspiration or just for the drama, it’s worth checking out.

So grab a snack, drop into the livestream, and see what’s happening. Who knows? You might walk away with an idea for your next setup.

Join the livestream on YouTube and join the chat while you’re there. See you in the comments!

Gunbot Monitor: Simplifying Multi-Bot Management

@boekenbox
@boekenbox
Gunbot Monitor: Simplifying Multi-Bot Management

Managing multiple trading bots across different servers and exchanges can be a challenge. Gunbot Monitor is built for power users who need an efficient way to centralize control, monitor performance, and streamline bot management. While Gunbot’s core interface is reliable, Gunbot Monitor provides a unified view that saves time and boosts productivity for users running many instances at once.

A Centralized Dashboard for All Your Bots

With Gunbot Monitor, you can oversee all your bots from one interface, no matter how many servers or exchanges you’re using. Instead of logging into each bot individually, the dashboard gives you a real-time overview of every running instance in one place. This simplicity allows you to focus more on strategy and less on repetitive tasks.

Dashboard showing multiple instances


Profit and Loss at a Glance

Tracking the financial performance of your bots is easy with Gunbot Monitor. You can instantly view the total profit and loss (PNL) across all your active instances, providing a quick snapshot of how your entire bot fleet is performing. No more switching between multiple screens to gather data, everything you need is right in front of you.

Total PNL across all instances


Advanced Metrics for Evaluating Performance

Gunbot Monitor doesn’t stop at basic stats. You also get advanced metrics like ROI, risk/reward ratios, and capital efficiency, all in one place. These insights help you fine-tune risk management and evaluate how effectively your capital is being used across your bots. Armed with this data, you can make better, data-driven decisions while building on the full Gunbot feature set.

ROI, Risk/Reward ratio, and Capital Efficiency


Full Remote Control of Your Bots

Managing your bots has never been easier. With Gunbot Monitor, you can start, stop, modify, and edit each instance directly from the dashboard. There’s no need to log into each bot separately, remote access lets you make adjustments quickly, all with the same security features as Gunbot’s local interface.


Modify Pairs Remotely

Need to adjust your trading pairs? With Gunbot Monitor, you can enable, disable, or delete pairs remotely from any location. This feature makes it easy to tweak settings without logging into each instance, speeding up the process of managing multiple pairs.

Control bots remotely with security features


Granular View of Trading Pairs

If you run multiple trading pairs, Gunbot Monitor shows a detailed breakdown of how each pair performs. Expand any instance to see real-time stats for individual pairs, giving you the granular insights needed to fine-tune performance at the pair level.

Detailed breakdown of individual pairs


Strong Security for Local and Remote Access

Security is a priority with Gunbot Monitor. It uses password protection and two-factor authentication (2FA) for both local and remote access, keeping your bots protected. Each instance has its own authentication, keeping unauthorized users out and your trading safe.

Local authentication setup


Real-Time Alerts and Notifications

Staying informed is critical in trading. Gunbot Monitor sends real-time notifications via email or Telegram when something needs your attention, such as when a bot goes offline or a software update is available. This helps you react quickly and keep your bots running smoothly.

Notification settings for bot instances


How to Get Gunbot Monitor

Gunbot Monitor is available for a one-time purchase of $59. Once you have it, all future updates are included. Simplify your bot management and take control of your trading with Gunbot Monitor.

Purchase Gunbot Monitor here


Gunbot Monitor is designed for power users who need detailed control over many Gunbot instances. From advanced performance tracking to remote management capabilities, this tool centralizes the controls you need to optimize your trading strategies. If you're managing bots across different exchanges or tweaking individual pairs, Gunbot Monitor streamlines the entire process, letting you focus on making smarter trading decisions.

Comparing Trading Bot performance with the 'Daily Realized PnL per $1k' Metric

@boekenbox
@boekenbox
Comparing Trading Bot performance with the 'Daily Realized PnL per $1k' Metric

For everyone using a trading bot, the ability to optimize strategies and fine-tune their trading approach is important. One of the metrics that can help with this is Daily Realized PnL per $1k. If you've checked out the 'Compare Pairs' table on the main dashboard on one of the latest Gunbot alpha builds, you've probably noticed this new metric already. But what does it mean, and why is it useful?

In this post, we'll look at how this metric works, why it's useful for comparing different trading pairs and strategies, and how you can use it for better trading decisions. Let’s go straight to the math that makes this metric useful.

What is "Daily Realized PnL per $1k"?

Daily Realized PnL per $1k tells you how much profit or loss you're making each day for every $1,000 of capital invested in a specific trading strategy or pair. Unlike abstract metrics like percentages or cumulative profit and loss, this value gives you a tangible dollar value that makes comparing different pairs and strategies much easier.

The goal here is to provide a standardized view of your trading performance. By converting performance into a common measure based on a $1,000 capital base, this metric allows traders to get a clear, apples-to-apples comparison between different pairs and strategies, helping you understand what's really working and what isn't.

Breaking Down the Metric

Let’s break this down step-by-step:

  • Daily Realized PnL: The profit or loss made on trades that have already been closed, calculated daily. The "realized" part means that it only includes the profit or loss from trades that are completed, not the potential value from open trades. This gives you a realistic snapshot of your trading performance based on actual outcomes.
  • Per $1,000: This means we normalize the results to represent the profit or loss for every $1,000 invested. This normalization allows for easy comparisons, even if different trading strategies have varying capital allocations or operate with different base amounts. It’s an effective way to get to the core of how well your capital is working for you.

With Daily Realized PnL per $1k, you get a value that can be easily compared across different trading strategies, irrespective of the initial investment amount or market volatility. This makes it a handy metric for evaluating efficiency and performance without getting bogged down by the complexities of various capital inputs.

How is This Metric Calculated?

The calculation is based on multiple formulas that standardize the performance:

  • Average Capital Utilized:

    Average Capital Utilized = Total Weighted Capital Utilized / Total Duration

  • Effective Capital Utilized:

    Effective Capital Utilized = (Average Capital Utilized + Maximum Capital Utilized) / 2

  • Total Duration in Days:

    Total Duration in Days = Total Duration from first to last trade. This value is capped to use full days only, no fractional values are used.

  • Adjusted Daily Net Profit:

    Adjusted Daily Net Profit = Total Net Profit / Total Duration in Days

  • Adjusted Daily Net Profit per $1,000:

    Daily Realized PnL per $1k = (Adjusted Daily Net Profit / Effective Capital Utilized) * 1000

Where:

  • Total Weighted Capital Utilized: The cumulative amount of capital utilized during trading, weighted by the time it was held.
  • Total Duration: The total time period of trading activities, in days.
  • Daily Net Profit: The sum of profits from closed trades over the day. This value only includes realized gains and losses, providing an accurate picture of true profitability.
  • Effective Capital Utilized: This represents the average amount of capital actively used during trading and takes into account both the average and maximum capital that was utilized throughout the trading period. By using this figure, we account for capital fluctuations and provide a balanced view of efficiency.

This set of formulas allows you to get a consistent dollar value for your performance, making it easy to compare the efficiency of different trading strategies, even if the actual capital involved varies.

Example Calculation

Let’s walk through a quick example to make it clearer. Suppose your Daily Net Profit from closed trades is $50, and during the day, your Effective Capital Utilized is $5,000. Plugging in these numbers:

Daily Realized PnL per $1k = (50 / 5000) * 1000 = 10

This means you’re making $10 per $1,000 of capital used, per day. This straightforward calculation makes it easy to see how well your strategy is performing, without dealing with abstract percentages or complex ratios.

Why is This Metric Useful for Traders?

1. Standardization Across Strategies

If you're trading multiple pairs or running different strategies, they can have widely varying performance metrics. For instance, trading a highly volatile pair like BTC/USDT might yield different returns compared to a less volatile pair like LTC/USDT. But the question is, how can you compare them effectively?

That’s where Daily Realized PnL per $1k becomes useful. It standardizes performance into a common unit that is relatable. Instead of comparing abstract performance percentages, you can see how much profit or loss each strategy would have generated if you had invested $1,000. This standardization is important when you want to choose the best-performing pair or strategy without being confused by differences in investment amounts, risk profiles, or market volatility.

2. Realistic Money Value

Many traders find it hard to wrap their heads around percentages or highly abstract metrics - they don’t always feel real. However, when you see a value like “$8 per day per $1,000,” it’s a lot more intuitive. It lets you understand the performance of a strategy in a practical, tangible way. You can immediately gauge how well a strategy might scale with more capital or whether it’s underperforming compared to others.

For example, if Strategy A yields $15/day per $1k and Strategy B yields $8/day per $1k, it’s easy to see which one is more efficient in generating profits. This helps make faster decisions when adjusting your trading approach.

3. Capital Efficiency Analysis

One key insight offered by this metric is understanding how effectively your capital is being used. The function that calculates Daily Realized PnL per $1k takes into account both the average capital utilized and the maximum capital utilized throughout your trading period. This means the metric shows how much profit you made and how efficiently you used the available capital to make it.

For example, if you’re using $10,000 but only making a small profit each day, your Daily Realized PnL per $1k will reflect that inefficiency. On the other hand, if you’re making high returns on smaller capital allocations, this metric will highlight that strength.

This efficiency measure is important when you’re balancing your risk-reward ratio. For instance, if you find that Strategy C has a high daily PnL per $1k but consistently ties up a significant amount of capital, you may want to reconsider if it's the best use of your funds or if other strategies could offer better capital efficiency. It helps you decide whether reallocating your capital might yield better results overall.

Practical Example: Comparing Strategies

Let’s walk through an example. Imagine you’re comparing two trading strategies:

  • Strategy A:

    • Average capital utilized: $5,000
    • Daily net profit: $50
  • Strategy B:

    • Average capital utilized: $2,000
    • Daily net profit: $25

Without standardization, it looks like Strategy A is more profitable. But let's use Daily Realized PnL per $1k to really see the difference:

  • Strategy A: (50 / 5000) * 1000 = 10 per day per $1k
  • Strategy B: (25 / 2000) * 1000 = 12.50 per day per $1k

In this case, Strategy B is more efficient at generating profit relative to the capital invested, despite having a lower absolute profit. By using this metric, you can immediately see which strategy is giving you better returns on a per-$1,000 basis, helping you make better decisions on where to allocate your funds.

Another scenario might involve different timeframes or trading styles, such as swing trading versus day trading. This metric is still valuable for comparing these differing styles on a level playing field. For example, even if a swing trade takes longer, you can normalize the profit generated to see how it measures up against quicker, higher-frequency trades in terms of profitability per $1,000 of capital utilized.

Where to Find "Daily Realized PnL per $1k" in Gunbot

You can find the Daily Realized PnL per $1k metric in the 'Compare Pairs' table on the main dashboard of the Gunbot interface. This table helps you evaluate how your different trading pairs perform in real time.

When you look at the 'Compare Pairs' table, you’ll see a breakdown of all your active pairs along with various performance indicators. The Daily Realized PnL / $1k column provides that tangible dollar-value perspective, allowing you to see which pairs are most effectively generating profits relative to their allocated capital. It takes away the guesswork and lets you make evidence-based decisions that are rooted in actual performance metrics. You can also compare real Gunbot performance against live shared runs.

How to Use This Metric for Better Decision-Making

  • Identify Strong Performers: Use Daily Realized PnL per $1k to highlight which trading pairs or strategies are making the most profit on a standardized capital basis. This makes it easy to spot which strategies are outperforming the rest.
  • Reallocate Capital: Consider shifting your capital towards strategies that show consistently high Daily Realized PnL per $1k. This helps keep your money working as efficiently as possible. Reallocating to strong performers means maximizing your portfolio's potential.
  • Track Over Time: Pay attention to how the Daily Realized PnL per $1k changes over time. Sudden drops might indicate a strategy that needs attention or adjustments. It also provides a way to evaluate changes you make to a strategy and their impact over time.

For instance, if you notice that your Daily Realized PnL per $1k has been decreasing for a particular trading pair, this could indicate a shift in market conditions, inefficiency in your current approach, or the need to reconfigure your trading settings. By tracking these changes, you gain insights that help you adapt and stay ahead.

Common Challenges with Traditional Trading Metrics

If you've spent any time trading or looking at crypto trading bots, you know that the metrics people use to measure success aren’t always as straightforward as they seem. We’ve got staples like Return on Investment (ROI), Sharpe Ratio, Max Drawdown, Win Rate, and Profit Factor. Sure, they provide insight, but they can also be pretty confusing. Often, these metrics don’t tell the whole story, and if you're not careful, you might end up making decisions based on half the picture. Let’s break down some of these metrics and see why the Daily Realized PnL per $1k might be a more user-friendly option.

1. Return on Investment (ROI)

  • Time Frame Confusion: ROI gives you a percentage return, but it doesn’t tell you over what period that return happened. So, if you see a 10% ROI, was that from a single month or a whole year? Without a timeline, it’s hard to gauge how fast or slow things are really moving.
  • Capital Efficiency Ambiguity: ROI doesn’t say much about how well the capital was used during that time. For example, did the strategy tie up a ton of capital for a small return? When using crypto trading bots, this could mean missing out on more efficient opportunities.

Example:

Imagine Trader A and Trader B both report a 15% ROI. Trader A achieved this in six months, while Trader B took two years. On the surface, they look the same, but with the time frame in mind, Trader A is clearly more efficient. It’s these kinds of details that get lost with ROI.

2. Sharpe Ratio

  • Complex Calculations: The Sharpe Ratio gets a bit math-heavy, and for most of us, understanding the deeper statistical stuff isn’t exactly easy. Especially if you're juggling multiple automated trading strategies, it can get overwhelming.
  • Volatility Misinterpretation: A lower Sharpe Ratio might make you think a strategy’s risky, even if it’s actually right in line with your own risk tolerance. This number alone doesn’t really tell the whole story.

Example:

Say you’re comparing two strategies with Sharpe Ratios of 1.2 and 0.8. It seems like 1.2 is better, but without knowing the details, like what kind of volatility you’re looking at, it’s hard to decide which is actually the right fit for you.

3. Max Drawdown

  • Overemphasis on Worst Cases: Max Drawdown tells you the worst loss from a peak, which can be intimidating. Sometimes, it’s just a blip on the radar, but this number can scare traders away from potentially solid strategies.
  • Lack of Frequency Insight: Max Drawdown doesn’t tell you how often these big drops happen. So, a strategy could have one bad moment or it could have them all the time, but you won’t know from this number alone.

Example:

Take a strategy with a max drawdown of 20%. That sounds risky, right? But what if this drawdown happened only once in five years and the strategy recovered quickly? You might miss out on a strong performer if you just look at this metric without more context.

4. Win Rate

  • False Sense of Security: High win rates can be deceiving. Just because a strategy wins often doesn’t mean it’s profitable. Big losses can easily wipe out those small wins.
  • Neglecting Profit-Loss Ratio: The size of wins versus losses matters, but win rate alone doesn’t give you that context. You could have a high win rate but still end up losing money if your losses are big enough.

Example:

A strategy with a 70% win rate might sound like a dream, but if the average loss is three times the average win, you’re in trouble. It’s easy to focus on the win rate and forget about the bigger picture.

5. Profit Factor

  • Abstract Ratio: Profit Factor is the ratio of gross profits to gross losses. For people wanting concrete answers, this can feel a bit too abstract and not immediately useful.
  • Impact of Outliers: Sometimes, one big win or loss can skew this number. Without understanding what’s behind it, users might get the wrong impression of how stable a strategy is.

Example:

A Profit Factor of 1.5 suggests profitability, but if it’s based on just one big win, it might not reflect the strategy’s typical performance. It’s these outliers that can really distort things.

Why "Daily Realized PnL per $1k" Is Easier to Work With

It’s more down-to-earth, and provides comparable data after a relatively short time of running a strategy. Do note that results get more realistic once a trading pair has seen some serious moves downwards, and significant capital got invested - because this allows the metric to factor in a more realistic use of capital.

  1. Straightforward Measurement:

    • It’s in dollars, per $1,000 invested daily. Simple. You know exactly how much you’re making or losing each day, without any complicated math.
  2. Time Frame Clarity:

    • By reporting daily, there’s no guessing about the time frame. You can see how fast the strategy’s moving and get a real sense of its performance.
  3. Capital Efficiency Visibility:

    • This metric standardizes performance per $1,000, so you can compare strategies without worrying about the total capital involved. It makes things more apples-to-apples.
  4. Focus on Realized Gains:

    • Only closed trades are considered, so you’re looking at actual profits or losses. This avoids the ups and downs of unrealized positions, giving you a clear picture.

As JS function

Updated 08/29/2025

Updated to support futures short positions. Handles negative order amounts, uses signed position size, absolute exposure deltas for capital utilization, and always accrues realized PnL.

function returnOnThousand(orders) {
if (!Array.isArray(orders) || orders.length === 0) {
return 0
}

// Sort orders by time to ensure chronological order
orders.sort((a, b) => a.time - b.time);

// Initialize variables
let positionSize = 0; // signed: long > 0, short < 0
let capitalUtilized = 0; // notional exposure tied up in open positions
let totalNetProfit = 0; // realized PnL
let totalWeightedCapitalUtilized = 0; // Sum of (Capital Utilized * Duration)
let totalDuration = 0; // Total time in milliseconds
let previousTime = orders[0].time; // Time of the first order
let maxCapitalUtilized = 0; // Maximum capital utilized

for (let i = 0; i < orders.length; i++) {
const order = orders[i];
const currentTime = order.time;

// Calculate duration since the previous order
const duration = currentTime - previousTime;

// Accumulate the weighted capital utilized
totalWeightedCapitalUtilized += capitalUtilized * duration;

// Accumulate total duration
totalDuration += duration;

// Update previousTime for the next iteration
previousTime = currentTime;

// Extract and normalize fields
const signedAmount = Number(order.amount) || 0; // may be negative for shorts on some exchanges
const qty = Math.abs(signedAmount);
const rate = Number(order.rate) || 0;
const pnl = Number(order.pnl) || 0;

// Always add realized PnL regardless of side
if (Number.isFinite(pnl)) {
totalNetProfit += pnl;
}

// Update signed position: buy increases, sell decreases
const side = order.type === "buy" ? 1 : -1;
const prevAbsPos = Math.abs(positionSize);
positionSize += side * qty;
const newAbsPos = Math.abs(positionSize);

// Update capital utilized by change in absolute exposure, priced at trade rate
const deltaExposureUnits = newAbsPos - prevAbsPos; // positive if exposure increased
capitalUtilized += deltaExposureUnits * rate;

// Ensure capitalUtilized doesn't go negative due to rounding errors
capitalUtilized = Math.max(capitalUtilized, 0);

// Update the maximum capital utilized
maxCapitalUtilized = Math.max(maxCapitalUtilized, capitalUtilized);
}

// Handle the last time interval (assuming capital utilized remains the same after the last order)
const endTime = orders[orders.length - 1].time;
const finalDuration = endTime - previousTime;
totalWeightedCapitalUtilized += capitalUtilized * finalDuration;
totalDuration += finalDuration;

// Calculate average capital utilized
const averageCapitalUtilized = totalWeightedCapitalUtilized / (totalDuration || 1);

// Effective Capital Utilized: incorporate both average and max capital utilized
const effectiveCapitalUtilized = (averageCapitalUtilized + maxCapitalUtilized) / 2;

// Convert totalDuration from milliseconds to days
const millisecondsInDay = 24 * 60 * 60 * 1000;
const totalDurationInDays = Math.ceil(totalDuration / millisecondsInDay) || 1;

// Adjusted Daily Net Profit
const adjustedDailyNetProfit = totalNetProfit / totalDurationInDays;

// Adjusted Daily Net Profit per 1,000 of Effective Capital Utilized
const adjustedDailyNetProfitPerThousand =
effectiveCapitalUtilized > 0
? (adjustedDailyNetProfit / effectiveCapitalUtilized) * 1000
: 0;

const finalResult = adjustedDailyNetProfitPerThousand.toFixed(2);

// Return the calculated metrics
return !isNaN(finalResult) ? finalResult : 0
}

Conclusion

The Daily Realized PnL per $1k metric helps you make sense of trading bot results, especially when you work with multiple pairs and strategies. By converting abstract performance into a concrete dollar value, it makes comparisons much clearer, helps identify more efficient strategies, and ultimately allows you to make smarter trading decisions.

It also helps you track capital efficiency, so you can see whether profits are coming from efficient capital use or from tying up too much money. It’s about maximizing returns while keeping your capital working effectively.

Next time you’re in the Gunbot dashboard, take a closer look at the 'Compare Pairs' table. Use the Daily Realized PnL / $1k column to optimize your strategies and check that you’re getting strong returns from your capital. New or experienced, you can use this metric to make more informed decisions. When you are ready to scale from testing to production, compare Gunbot plans and pick what fits your setup.

Launching our Backtesting Archive

@boekenbox
@boekenbox
Launching our Backtesting Archive

We’re excited to announce the launch of the backtesting archive on Gunbot.com! This tool is designed for traders who want to optimize their Gunbot strategies by analyzing detailed historical trading data. With the backtesting archive, you can look closely at backtest reports, compare different strategies, and gain valuable insights to improve your trading methods.

Easy-to-Use Viewer for Backtest Reports

The backtesting archive provides a dedicated viewer for Gunbot-generated backtest reports. This intuitive interface makes it easy to analyze your backtesting results in detail. Each backtest includes a download option that has all needed settings to run your crypto trading bot in the exact same way.

Chart viewer

Visualize and Compare Results

Our detailed charts allow you to visualize all your backtesting results at a glance. The overview table lets you easily compare performance metrics across various strategies and timeframes to identify what works best.

Overview viewer

Contribute to the Backtesting Archive

Join the Community Effort

The Gunbot backtesting archive will thrive on contributions from traders like you. By sharing your backtesting results, you help build a richer, more diverse database that benefits the entire community.

How to Submit Your Data

Contributing is simple. You can submit your backtesting results in two ways:

Each submission goes through a review process for quality and accuracy. While it might take some time, your valuable insights will soon be part of this collective resource.

What’s Inside a Backtest Report?

Here’s a sneak peek at the kind of data you can look at in the backtesting archive:

  • Pair: BTC-SOL
  • Exchange: Binance
  • Fee Percentage: 0.1%
  • Time Period: From June 7, 2024, to February 24, 2056

Key Performance Metrics

  • Starting Funds: 0.1 BTC
  • Realized PnL: 0.003594 BTC
  • ROI: 3.59%
  • Sharpe Ratio: 0.56
  • Sortino Ratio: 9.72
  • Realized Profit: 0.005393 BTC
  • Realized Loss: -0.001798 BTC
  • Average PnL %: 1.78%
  • Average Profit %: 1.93%
  • Average Loss %: -5.66%
  • Volume: 0.663889 BTC
  • Buy Volume: 0.339088 BTC
  • Sell Volume: 0.324801 BTC
  • Buys: 47
  • Sells: 51
  • Trades with Profit: 50
  • Trades with Loss: 1
  • Fees Paid: 0.000663 BTC

Strategy Settings

Review the detailed settings used in backtests, such as:

  • Initial Funds: 0.1 BTC
  • Buy Method: channelmaestro
  • Sell Method: channelmaestro
  • Profit Target %: 7.5
  • Use Auto Gain: true
  • Buy Enabled: true
  • Sell Enabled: true

These settings allow you to see exactly how strategies are configured and how they perform under different conditions.

Bonus: Guide to Mass Backtest Runs with Gunbot on Linux

This guide will help you set up and run a mass backtest script for Gunbot on a Linux system.

Prerequisites

  1. Gunbot: Make sure you have Gunbot installed and configured.
  2. Python 3.10: Make sure Python 3.10 is installed.
  3. Required Python Libraries: Install the necessary Python libraries by running:
    pip install subprocess time os signal shutil json re itertools multiprocessing

Script Setup

  1. Download the Script: Save the provided script as mass_backtest.py in your working directory.
  2. Set Up Working Directories: Make sure you have the following directory structure:
    /home/user/dev/backtesting-runs/
    ├── 1/
    ├── 2/
    └── 3/
    Each directory should contain:
    • A complete Gunbot installation
    • A unique GUI port set for each instance
    • A config.js file with "BACKFESTER": true in the bot section and preconfigured starting balances for simulator.

Configuration

Modify Paths

Adjust the paths in the script if your directory structure is different.

Trading Pairs and Months

Customize the trading_pairs and months variables according to your needs.

Pair Overrides and Trading Limit

The script will override the configuration for each pair for proper backtesting. It updates:

  • BF_SINCE and BF_UNTIL: The start and end timestamps for the backtest period.
  • TRADING_LIMIT: Calculated as the available balance divided by 30.
  • MIN_VOLUME_TO_SELL: Set as 30% of the trading limit.
  • Other strategy-specific settings.

These overrides keep each backtest on consistent parameters.

Using RAM Disk

Importance of RAM Disk

Using a RAM disk can significantly speed up the backtesting process by reducing read/write times. The script copies necessary files to the RAM disk, performs the backtest, and then copies the results back to the main storage.

Check Available RAM Disk Volume

Before running the script, make sure you have sufficient space in your RAM disk (/dev/shm). Check the available volume with the following command:

df -h /dev/shm

Make sure you have enough space to handle the data for your backtests. If necessary, adjust your system's RAM disk size in your system settings.

Running the Script

  1. Navigate to the Script Directory:
    cd /path/to/your/script
  2. Run the Script:
    python3 mass_backtest.py

Script Workflow

Initial Setup

The script starts by clearing any existing temporary backtesting directories in the RAM disk (/dev/shm). It then loads or initializes the task queue with all trading pairs and date ranges.

Managing Tasks

The task queue manages which trading pairs and date ranges need to be processed. The script uses a worker directory queue to handle different working directories where backtests will be run.

Running Backtests

The script launches multiple worker processes to perform backtests concurrently. Each worker:

  • Copies necessary files to the RAM disk
  • Executes the backtest using Gunbot
  • Monitors the output for completion
  • Terminates the process upon completion
  • Copies the backtesting results back to the main storage
  • Marks the task as done and updates the completed tasks file

Completion

The script waits for all worker processes to finish. It periodically saves the state of the task queue to a file, allowing you to resume if the script is interrupted.

Increasing Process Count

To increase the number of processes running backtests concurrently:

  1. Create Enough Working Directories:

    • You need one working directory per process. For example, if you want to run 5 processes concurrently, you should have 5 working directories:
      /home/pim/dev/backtesting-runs/
      ├── 1/
      ├── 2/
      ├── 3/
      ├── 4/
      └── 5/
    • Each directory must have a complete Gunbot installation with a unique GUI port and a config.js file.
  2. Update the Number of Processes:

    • Open the mass_backtest.py script.
    • Locate the section where the processes are started:
      processes = []
      for _ in range(3): # 3 processes
      p = Process(target=worker, args=(task_queue, working_directory_queue))
      p.start()
      processes.append(p)
    • Change the number 3 to the desired number of processes. For example, to run 5 processes concurrently, change it to:
      processes = []
      for _ in range(5): # 5 processes
      p = Process(target=worker, args=(task_queue, working_directory_queue))
      p.start()
      processes.append(p)
  3. Update the Working Directories List:

    • Update the working_directories list at the beginning of the script to match the number of processes. For example, if you want to run 5 processes, you need 5 working directories. You should update the range to range(1, 6) to match the folder count:
      working_directories = [os.path.join(base_working_directory, str(i)) for i in range(1, 6)] # 5 working directories
    • The number 6 here is one more than the actual count because the range function in Python is inclusive of the start value but exclusive of the end value. So, range(1, 6) creates a list from 1 to 5.

Considerations

  • System Resources: Make sure your system has enough CPU and RAM to handle the increased process count. Running too many processes can lead to resource contention and slow down the overall performance.
  • RAM Disk Space: Verify that your RAM disk (/dev/shm) has enough space to accommodate the additional processes.

Monitoring Progress

  • Console Logs: The script prints logs to the console, showing the progress of each backtest.
  • Completion Reports: Backtesting reports are saved back to the respective working directories.

Script source

mass_backtest.py

import subprocess
import time
import os
import signal
import shutil
import json
import re
from multiprocessing import Process, Queue, current_process
from queue import Empty

# Define the base working directory
base_working_directory = '/home/user/dev/backtesting-runs'
working_directories = [os.path.join(base_working_directory, str(i)) for i in range(1, 4)] # 3 working directories
command = ['./gunthy-linux']

# Static list of pairs and timeframes to use
trading_pairs = [
"USDT-BTC", "USDT-ETH", "USDT-BNB", "USDT-SOL", "USDT-XRP", "USDT-DOGE", "USDT-ADA", "USDT-TRX",
"USDT-AVAX", "USDT-SHIB", "USDT-DOT", "USDT-LINK", "USDT-BCH", "USDT-NEAR", "USDT-MATIC", "USDT-LTC",
"USDT-UNI", "USDT-PEPE", "BTC-ETH", "BTC-BNB", "BTC-SOL", "BTC-XRP", "BTC-DOGE", "BTC-ADA", "BTC-TRX",
"BTC-AVAX", "BTC-DOT", "BTC-LINK", "BTC-BCH", "BTC-NEAR", "BTC-MATIC", "BTC-LTC", "BTC-UNI", "BNB-SOL",
"BNB-XRP", "BNB-ADA", "BNB-TRX", "BNB-AVAX", "BNB-DOT", "BNB-LINK", "BNB-BCH", "BNB-NEAR", "BNB-MATIC",
"BNB-LTC", "ETH-BNB", "ETH-XRP", "ETH-SOL", "ETH-ADA", "ETH-TRX", "ETH-AVAX"
]

months = [
(1704067200000, 1706659199000), # Jan 2024
(1706659200000, 1709251199000), # Feb 2024
(1709251200000, 1711843199000), # Mar 2024
(1711843200000, 1714435199000), # Apr 2024
(1714435200000, 1717027199000), # May 2024
(1717027200000, 1719619199000), # Jun 2024
]

def transform_pair(pair):
if pair.endswith('BTC'):
return f"BTC-{pair[:-3]}"
elif pair.endswith('ETH'):
return f"ETH-{pair[:-3]}"
elif pair.endswith('USDT'):
return f"USDT-{pair[:-4]}"
elif pair.endswith('BNB'):
return f"BNB-{pair[:-3]}"
return pair

def clear_ramdisk():
ramdisk_base = '/dev/shm/'
for item in os.listdir(ramdisk_base):
item_path = os.path.join(ramdisk_base, item)
if os.path.isdir(item_path) and item.startswith('backtesting_'):
shutil.rmtree(item_path)
print(f"Cleared RAM disk directory: {item_path}")

def delete_folders(working_directory):
json_folder = os.path.join(working_directory, 'json')
backtesting_folder = os.path.join(working_directory, 'backtesting')

if os.path.exists(json_folder):
shutil.rmtree(json_folder)
print(f"Deleted folder: {json_folder}")
if os.path.exists(backtesting_folder):
shutil.rmtree(backtesting_folder)
print(f"Deleted folder: {backtesting_folder}")

def read_config(working_directory):
config_path = os.path.join(working_directory, 'config.js')
with open(config_path, 'r') as file:
config_data = file.read()
config_data = re.sub(r'^module\.exports\s*=\s*', '', config_data)
config_data = re.sub(r';\s*$', '', config_data)
return json.loads(config_data)

def write_config(config, working_directory):
config_path = os.path.join(working_directory, 'config.js')
config_data = json.dumps(config, indent=4)
with open(config_path, 'w') as file:
file.write(config_data)

def ensure_pair_config(config, pair):
exchange = 'binance'
if exchange not in config['pairs']:
config['pairs'][exchange] = {}

config['pairs'][exchange] = {}
if pair not in config['pairs'][exchange]:
config['pairs'][exchange][pair] = {
"strategy": "channelmaestro",
"enabled": True,
"override": {
"INITIAL_FUNDS": "500",
"BUY_METHOD": "channelmaestro",
"SELL_METHOD": "channelmaestro",
"COMPOUND_RATIO": "1",
"COMPOUND_PROFITS_SINCE": "0",
"USE_STOP_AFTER_PROFIT": False,
"PROFIT_TARGET_PCT": "7.5",
"USE_AUTO_GAIN": True,
"GAIN_PARTIAL": "0.5",
"GAIN": "2",
"BUY_ENABLED": True,
"SELL_ENABLED": True,
"STOP_AFTER_SELL": False,
"MIN_VOLUME_TO_SELL": 10,
"MAX_INVESTMENT": "999999999999999",
"PERIOD": "5",
"PERIOD_MEDIUM": "15",
"PERIOD_LONG": "30",
"IGNORE_TRADES_BEFORE": "0",
"BF_SINCE": 0,
"BF_UNTIL": 0,
"USE_EXPERIMENTS": False
}
}

def update_config(config, pair, start, end):
if not config['bot']['BACKFESTER']:
config['bot']['BACKFESTER'] = True

base, quote = pair.split('-')[0], pair.split('-')[1]
balance = float(config['bot']['simulatorBalances']['binance'][base])

trading_limit = balance / 30
min_volume_to_sell = trading_limit * 0.3

ensure_pair_config(config, pair)

config['pairs']['binance'][pair]['override']['BF_SINCE'] = start
config['pairs']['binance'][pair]['override']['BF_UNTIL'] = end
config['pairs']['binance'][pair]['override']['TRADING_LIMIT'] = trading_limit
config['pairs']['binance'][pair]['override']['MIN_VOLUME_TO_SELL'] = min_volume_to_sell
config['pairs']['binance'][pair]['override']['INITIAL_FUNDS'] = balance

def copy_to_ram(working_directory, ram_directory):
print(f"Copying {working_directory} to {ram_directory}")
if os.path.exists(ram_directory):
shutil.rmtree(ram_directory)
shutil.copytree(working_directory, ram_directory)

def copy_backtesting_reports_from_ram(working_directory, ram_directory):
print(f"Copying backtestingReports from {ram_directory} back to {working_directory}")
ram_backtesting_reports = os.path.join(ram_directory, 'backtestingReports')
main_backtesting_reports = os.path.join(working_directory, 'backtestingReports')
if os.path.exists(ram_backtesting_reports):
if os.path.exists(main_backtesting_reports):
shutil.rmtree(main_backtesting_reports)
shutil.copytree(ram_backtesting_reports, main_backtesting_reports)

def launch_and_kill_process(command, working_directory, ram_directory):
copy_to_ram(working_directory, ram_directory)
process = subprocess.Popen(command, cwd=ram_directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(f"Process {process.pid} started in {ram_directory}.")

last_output_time = time.time()

try:
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
last_output_time = time.time()
print(output.strip())
if 'Backtesting report created successfully' in output:
break
if 'Backtester completed the job: your data will be available soon on your GUI' in output:
time.sleep(3)
break
if time.time() - last_output_time > 8:
print(f"No log output for 8 seconds, restarting process {process.pid}")
os.kill(process.pid, signal.SIGTERM)
process.wait()
process = subprocess.Popen(command, cwd=ram_directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
last_output_time = time.time()
finally:
if process.poll() is None:
os.kill(process.pid, signal.SIGTERM)
print(f"Process {process.pid} in {ram_directory} has been terminated.")
copy_backtesting_reports_from_ram(working_directory, ram_directory)
delete_folders(ram_directory)

def run_backtest(pair, start, end, working_directory, ram_directory, queue):
config = read_config(working_directory)
update_config(config, pair, start, end)
write_config(config, working_directory)
launch_and_kill_process(command, working_directory, ram_directory)
time.sleep(1) # Wait for 1 second before the next run
queue.put(working_directory) # Indicate that this working directory is free

def save_queue(task_queue, filename='task_queue.json'):
with open(filename, 'w') as file:
tasks = []
while not task_queue.empty():
tasks.append(task_queue.get())
json.dump(tasks, file)
for task in tasks:
task_queue.put(task)

def load_queue(filename='task_queue.json'):
task_queue = Queue()
if os.path.exists(filename):
with open(filename, 'r') as file:
tasks = json.load(file)
for task in tasks:
task_queue.put(tuple(task))
else:
for pair in trading_pairs:
for start, end in months:
task_queue.put((pair, start, end))
return task_queue

def worker(task_queue, working_directory_queue, completed_tasks_filename='completed_tasks.json'):
completed_tasks = []

if os.path.exists(completed_tasks_filename):
with open(completed_tasks_filename, 'r') as file:
completed_tasks = json.load(file)

while True:
try:
pair, start, end = task_queue.get(timeout=5) # timeout added to allow graceful shutdown
except Empty:
break

if (pair, start, end) in completed_tasks:
continue

working_directory = working_directory_queue.get()
ram_directory = os.path.join('/dev/shm', f'backtesting_{current_process().pid}')

print(f"Worker {current_process().pid} processing {pair} from {start} to {end} in {working_directory}")
run_backtest(pair, start, end, working_directory, ram_directory, working_directory_queue)

completed_tasks.append((pair, start, end))
with open(completed_tasks_filename, 'w') as file:
json.dump(completed_tasks, file)

if __name__ == "__main__":
clear_ramdisk()

task_queue = load_queue()
working_directory_queue = Queue()
save_queue(task_queue)

for wd in working_directories:
working_directory_queue.put(wd)

processes = []
for i in range(3): # 3 processes
p = Process(target=worker, args=(task_queue, working_directory_queue))
p.start()
processes.append(p)
time.sleep(0.5) # Introduce a small time offset of 0.5 seconds before starting the next process

for p in processes:
p.join()

save_queue(task_queue)

Conclusion

The new backtesting archive on Gunbot.com helps you refine strategies with better data. By using and contributing to this resource, you can improve your trading methods and share useful findings with the Gunbot community. Start with the backtesting archive and keep improving from there.

Meet Gunbot Guru: Your AI Assistant for All Things Gunbot

@boekenbox
@boekenbox
Meet Gunbot Guru: Your AI Assistant for All Things Gunbot

Gunbot Guru is designed to help users navigate the complexities of Gunbot, if you are a beginner trying to understand the basics or an experienced trader looking to automate and customize your strategies.

With access to all documentation and definitions for creating valid autoconfig jobs and custom strategies, Gunbot Guru is here to improve your trading experience by providing instant, detailed assistance.

Visit Gunbot Guru

Why Gunbot Guru Exists

Gunbot Guru exists to bridge the gap between complex crypto trading bot configurations and user accessibility. While Gunbot offers a reliable suite of tools and features for cryptocurrency trading, understanding and using these features can be difficult, especially for new users. Gunbot Guru simplifies this process by providing clear, concise answers and step-by-step guidance. If you need a full product map while using it, browse the full feature overview.

This is not a human support replacement. We hope it mainly improves the experience of interacting with documentation.

OpenAI's Custom GPTs for Free Users

Recently, OpenAI opened up access to custom GPTs for their free users, making it easier for everyone to create and use specialized AI assistants like Gunbot Guru. Using the latest GPT-4o architecture, Gunbot Guru is designed to provide accurate and detailed responses based on the most current data available. However, as with any AI, it is experimental, and we cannot guarantee that it always provides correct information. Always double-check critical details and consult official documentation or support channels when needed.

What Users Can Do with Gunbot Guru

  • Setup Assistance: Get help with initial setup, including connecting to exchanges and configuring trading pairs.
  • Strategy Development: Learn how to code custom trading strategies in JavaScript.
  • AutoConfig Jobs: Understand and resolve common issues with AutoConfig jobs, or even create them from scratch.
  • General Inquiries: Ask any questions about Gunbot functionalities, settings, and best practices.
  • Probably Much More?: The cases above were tested, Gunbot Guru can probably handle way more topics.

Technological Advancements

The capabilities of Gunbot Guru are made possible by recent advancements in AI technology. Just a year ago, creating a custom AI that could understand and interact with users on such a detailed level was not feasible. With the latest GPT-4o architecture, OpenAI has enabled us to develop specialized assistants that can provide custom support and information. This is an experimental GPT, and while it strives to provide accurate information, it's important to double-check critical details and consult official documentation or support channels when needed.

Getting Started with Gunbot Guru

If you're new to Gunbot, Gunbot Guru can help clear up any doubts you have. Here’s an example of a step-by-step guide on how to set up your first trading pair using Gunbot Guru:

Example Interaction: Setting Up a Trading Pair

Question: "How do I set up my first trading pair on Gunbot?"

Answer: To set up your first trading pair on Gunbot, follow these steps:

  1. Select Market Type: Choose 'spot' as your market type in the Gunbot wizard. This can be changed later if needed.
  2. Connect to an Exchange:
    • Select your exchange from the list.
    • Enter your API credentials (API key and secret).
    • Click 'update exchange settings' to save your input.
  3. Add a Trading Pair:
    • In the Gunbot interface, select the 'add pair' button.
    • Choose your preferred trading pair from the list. For example, you can select USDT-BTC.
  4. Configure the Trading Pair:
    • Choose the 'stepgrid' strategy for both buying and selling. This strategy is suitable for frequent, smaller trades.
    • Set the trading limit. For example, if you have 2500 USDT and want to distribute it over 50 buy orders, set the trading limit to 50 (2500 / 50 = 50 USDT per trade).
    • Restrict the maximum investment to 2500 USDT to make sure the crypto trading bot does not exceed this limit.
  5. Optional: Activate Telegram Notifications:
    • You can activate Telegram notifications to get immediate updates on your trades. This step is optional and can be done later.
  6. Select Interface Mode:
    • Gunbot offers two interface modes: Basic Interface and Advanced Interface. Choose the mode that best fits your experience level. The Basic Interface is recommended for new users.
  7. Start Trading:
    • Once your pair is set up, click the 'start bot' button to begin trading.
  8. Monitor Trades:
    • Use the Gunbot interface to monitor your trades in real-time. The interface provides essential information such as break-even points and target goals.

For more detailed guidance, refer to the Gunbot documentation and support pages.

Advanced Use Cases

For seasoned Gunbot users, Gunbot Guru can solve even complex tasks with detailed prompts. Here’s how you can use Gunbot Guru for advanced use cases:

Example Interaction: Coding a Custom JS Strategy

Question: "Can you provide a sample JS script for a custom trading strategy?"

Answer: Here is a simple example of a custom trading strategy script in JavaScript for Gunbot:

// Check if there are any open orders for this pair, wait until they get filled before doing anything else
if (gb.data.openOrders.length > 0){
console.log('There is an open order, waiting...')
return
}

// Balance "settings": invest 100 USDT, convert into quote amount needed for calling the buy method
var baseAmount = 100
var buyAmount = baseAmount / gb.data.bid

// Check if no bag is held yet AND price, lowBB, and moving average criteria are true
if (
!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 buyAmount
gb.method.buyMarket(buyAmount, gb.data.pairName)
}
// Place a limit sell order if we have a bag
else if ( gb.data.gotBag ) {
// Fire the sell order, pass in the amount, price, and pair name.
// Price is calculated as breakEven * 1.01
gb.method.sellLimit(gb.data.quoteBalance, gb.data.breakEven * 1.01, gb.data.pairName)
}

For more examples and detailed explanations, refer to the Gunbot documentation here.

Example Interaction: Resolving Common AutoConfig Job Issues

Question: "What are common issues with AutoConfig jobs and how can I resolve them?"

Answer: Here are some common issues with AutoConfig jobs in Gunbot and how you can resolve them:

  1. Jobs Not Running

    • Check that AutoConfig is enabled in your Gunbot setup. You can enable it through the browser interface on the AutoConfig page.
    • Check that each job you want to run is enabled. Each job has an option to enable or disable it.
    • Verify the schedule format of the job. AutoConfig jobs use a cron-like schedule format. If the schedule is not correctly formatted, the job will not run. Use tools like crontab-generator.org to generate the correct schedule format.
  2. Configuration Conflicts

    • When scheduling multiple jobs, avoid conflicts from simultaneous configuration changes. Only the first job to finish will apply its changes if they run concurrently. The others will wait for another chance.
  3. Undefined Data Errors

    • Use filters to check if the data exists before using it in an expression. For example, add a filter that checks if the data has a value greater than 0 before using it in a calculation.
  4. Manual Changes During Fast Schedules

    • Avoid making manual setting changes through the browser while AutoConfig jobs are running, especially when using very fast schedules. This keeps the trading bot configuration consistent.
  5. High API Usage

    • Limit the duration and frequency of ticker data collection jobs. Do not permanently run ticker collection jobs while running other AutoConfig jobs. High API usage can slow down Gunbot performance.
  6. Incorrect Pair Data

    • Check that the pair data you are referencing exists and is correctly formatted. Check the JSON file and check that the data points you want to use are available and have the correct data type. Prefer number and boolean types over arrays.

Proof of example interactions: Gunbot Guru Session

Conclusion

Gunbot Guru is an AI assistant that can improve your Gunbot workflow. New and experienced users can use it for basic setup help, advanced coding, and anything in between.

Visit Gunbot Guru

Introducing the Gunbot Dev Community

@boekenbox
@boekenbox
Introducing the Gunbot Dev Community

Gunbot has come a long way from offering preset trading bots to becoming a flexible platform that lets developers create their own custom trading strategies and automation setups. This shift has helped create a small and enthusiastic community of developers who are now offering their custom setups to Gunbot users. We're happy to announce the first three community-developed offers, with more to come.

With or without extensions made by community devs, Gunbot remains the most versatile crypto trading bot on the market. Offering a wide range of built-in strategies that are ready to use right out of the box. If you use these community-developed setups or stick with the built-in options, Gunbot provides a reliable trading solution for all users.

Broxynet-V1

The Broxynet-V1 strategy suite, as described by its developer @Steven0_0Smith, includes multiple trading modes, Accumulator, Gribz, Calm, Normal, and Aggressive, catering to both novice traders and seasoned Gunbot users.

  • Accumulator: Reinvest profits to buy and hold your favorite cryptocurrencies.
  • Gribz Mode: A grid-style trading approach with dual sell levels.
  • Calm, Normal, and Aggressive Modes: Customizable settings to protect against market downtrends.

Broxynet-V1's active Trading Panel provides real-time data on buy and sell triggers, current pair state, and trading mode.

More details about Broxynet

Quanta exoTrader

According to its developer @flightcommander, Quanta exoTrader offers a data science approach to trading.

  • Data Science Core: High probability entry and exit points.
  • Adaptive Trading Algorithm: Adjusts to market volatility in real-time.
  • Risk Management Tools: Multi-timeframe trend protection and custom risk thresholds.

Quanta exoTrader is said to be ideal for traders who want a sophisticated, data-driven strategy that adapts to market conditions.

More details about Quanta-exoTrader

ChannelMaestro

ChannelMaestro, described by its developer @boekenbox, is an all-around trading strategy designed for simplicity and effectiveness. With minimal settings required, it can be deployed in under 10 seconds.

  • Simple Configuration: Easy to start trading with just a few settings.
  • Single Setting Funds Management: Integrated stop losses and automatic trade size adjustments.
  • Multi-Timeframe Analysis: Analyzes different timeframes to make informed trading decisions.

ChannelMaestro is said to be perfect for traders who prefer a straightforward approach without the need for extensive configuration.

More details about ChannelMaestro

Conclusion

The Gunbot community is growing, thanks to the creativity and hard work of our developers. Setups like Broxynet-V1, Quanta exoTrader, and ChannelMaestro give users more choices for their trading strategies. These first community-developed setups are available for purchase, with the developers getting the proceeds. More community strategies and extensions are on the way, providing even more ways to customize your Gunbot experience.

If you use these community setups or stick with Gunbot's built-in strategies, you have a solid tool for your trading needs. The future of Gunbot trading is looking better than ever with help from our dedicated community.

Beyond Basic Crypto Trading Bots: Using AutoConfig for Custom Automation

@boekenbox
@boekenbox
Beyond Basic Crypto Trading Bots: Using AutoConfig for Custom Automation

As a bot trader, you need to adapt strategies quickly when market conditions change. Manually managing trading bots can give you precision, but it’s a constant grind that leaves you vulnerable to missed opportunities.

That’s where Gunbot's AutoConfig comes in, a feature built for advanced automation and real-time optimization. AutoConfig fine-tunes strategies, responding to market shifts, and lets you create advanced trading routines that would otherwise require intensive manual oversight.

The Limits of Manual Bot Management

Manual bot management is straightforward, but it's labor-intensive:

  1. Pair Selection: You need to constantly identify promising crypto pairs based on market conditions.
  2. Strategy Assignment: Each pair requires specific strategies that align with current trends.
  3. Parameter Tuning: Frequent tweaking of strategy settings is essential as the market changes.
  4. Trade Monitoring: You must oversee trades, stepping in to make adjustments as needed.

All these tasks demand constant attention, creating risks of lost opportunities or delayed responses when the market moves fast.

What AutoConfig Does for You

AutoConfig allows you to automate these processes, handling pair management, strategy settings, and more in real time and in a rules based manner. By setting up AutoConfig, you can keep your bot aligned with your trading objectives without having to watch over every detail.

Why AutoConfig Stands Out:

  • High Efficiency: Reduces the need for manual adjustments, freeing up time for broader strategy work.
  • Real-Time Adaptability: Automatically keeps strategies optimized to current market conditions.
  • Advanced Customization: Set up complex, multi-step trading actions based on specific market signals.

AutoConfig’s Capabilities

To help traders with automating their repetitive (and often slow) manual bot management, AutoConfig offers a suite of tools to help automating various aspects of running a crypto trading bot.

Dynamic Pair Management

Beyond simple pair addition and removal, AutoConfig can evaluate pairs based on more complex indicators such as historical performance, correlation with other assets, allowing for a highly optimized and strategic portfolio composition.

Detailed Strategy Optimization

AutoConfig supports deeper strategy customization with conditional logic and multi-variable scenarios. It can automatically adjust strategies based on market conditions, performance metrics, and predefined goals.

Extensive Workflow Automation

AutoConfig can orchestrate detailed trading workflows, offering a reliable framework for setting pre-trade conditions and post-trade actions that streamline trading strategies and improve decision-making:

Pre-Trade Conditions

Before executing trades, AutoConfig can assess a variety of market indicators and internal parameters to confirm that all conditions align with strategic requirements. This includes checking for price stability, market sentiment analysis, or even external economic events that could impact price movements. By setting such pre-trade conditions, traders can fine-tune when and how their trading strategies are deployed, reducing the risk of entering or exiting positions under unfavorable conditions.

Post-Trade Actions

After a trade is executed, AutoConfig could orchestrate a series of post-trade actions that are important for maintaining strategy efficacy and preparing for future trades. This includes adjusting future trading parameters based on the outcome of the trade, rebalancing the portfolio to maintain risk levels, or even triggering conditional orders based on new market conditions. These actions keep the trading strategy dynamic so it can adapt based on previous outcomes and evolving market insights.

Practical Applications of AutoConfig

  • Dynamic Risk Management: AutoConfig can adjust risk exposure based on volatility, scaling back in high-risk environments or increasing positions during stable periods.
  • Custom Strategy Adjustments: Use JavaScript or other scripting to fine-tune strategies in real-time, based on performance data.
  • Market Sentiment-Based Adjustments: Integrate external data sources to monitor sentiment shifts and adjust trading strategies accordingly.

Implementing AutoConfig

Setting up AutoConfig requires a detailed configuration that matches your specific trading strategies and goals. To get started or improve their current setups, we provide detailed guides that walk you through the necessary steps:

These resources will help you script conditions, define action triggers, and set performance metrics for evaluating the effectiveness of your strategies.

Final Takeaways

Gunbot's AutoConfig goes beyond standard bot capabilities, enabling traders to design, automate, and refine strategies on their own terms. It’s not a one-size-fits-all tool; it’s a flexible platform for building and customizing trading automation that aligns with your specific goals.

AutoConfig offers tools to control every aspect of your trading automation, letting you actively shape your trading environment in real-time. If you're aiming for efficiency, adaptability, or deeper control, AutoConfig equips you to stay responsive to market conditions and build a more effective trading system.

Display Custom Metrics in Gunbot with AutoConfig Hack (UPDATED, NO LONGER A HACK)

@boekenbox
@boekenbox
Display Custom Metrics in Gunbot with AutoConfig Hack (UPDATED, NO LONGER A HACK)

This guide shows how to use AutoConfig to display custom metrics next to your trading chart. Although displaying custom metrics is usually reserved for custom strategies, we will use a simple AutoConfig setup to place custom metrics right next to your trading chart.

Update

The feedback on this article has been overwhelmingly positive, and we've taken note of the technical challenges some of you faced with setting custom metrics for strategies like stepgridhybrid.

Thanks to your input, starting from version 28.5.6_beta, we are officially supporting this feature in AutoConfig, allowing for the customization of metrics in the strategy stats sidebar.

Getting Custom Metrics with AutoConfig 🔓

AutoConfig is primarily used for configuration automation, but we'll demonstrate how to use it for improving the Gunbot frontend too. By creating an AutoConfig job that alters nothing in the Gunbot config, you can have it write data to the internal memory of the bot and display custom metrics in the right sidebar, next to the chart. These metrics can include a title, value, and tooltip text.

Note: This article assumes you are familiar with your bot and basic steps like enabling AutoConfig itself.

Time Since Last Buy & Sell: A Complex Example ⏰

Let's examine an example of how to display the time since last buy and sell for the USDT-BTC pair. This complex example iterates over order data to calculate the final values. Keep in mind that the JavaScript code must be on a single line, within double quotes, and have a leading space to be evaluated.

autoconfig.json example

{
"customMetrics": {
"pairs": {
"exclude": "",
"include": "USDT-BTC",
"exchange": "binance"
},
"filters": {
"alwaysPasses": {
"type": "custom",
"target": " true"
}
},
"overrides": {},
"setPairVariable": {
"setMetrics": " (function setMetrics(data) {const orders = data.pair.orders; const lastBuyTime = orders.filter(order => order.type === 'buy').map(order => Date.now() - order.time).sort((a, b) => b - a)[0];const timeSinceLastBuy = new Date(lastBuyTime).toISOString().substr(11, 8);const lastSellTime = orders.filter(order => order.type === 'sell').map(order => Date.now() - order.time).sort((a, b) => b - a)[0];const timeSinceLastSell = new Date(lastSellTime).toISOString().substr(11, 8);data.pair.sidebarExtras = [{label: 'Time since last sell (hh:mm:ss)', value: timeSinceLastSell, tooltip: 'lolol'}, {label: 'Time since last buy (hh:mm:ss)', value: timeSinceLastBuy, tooltip: 'lolol'}]; return true;})(this)"
},
"clearOverrides": false,
"schedule": "*/15 * * * * *",
"type": "manageOverrides",
"debug": true,
"enabled": true
}
}

Pairs Section: This section specifies the target pair for the job. In this case, it is set to "USDT-BTC" on the "binance" exchange. Alternatively you can set the value for include to -to match all pairs on an exchange, or USDT- to match all USDT pairs.

Filters Section: The "alwaysPasses" filter is defined as a custom filter that will always evaluate to true. This lets the job continue to the next step, regardless of the input.

Overrides Section: This section is empty in the provided configuration. It can be used to override certain settings or parameters on the pair level if needed.

setPairVariable Section: This section contains a JavaScript code snippet wrapped in a self-invoking function. It sets the custom metrics for the pair. The code extracts information from the "data" object, specifically the "orders" property of the pair. It calculates the time since the last buy and sell orders for the pair and formats them as "hh:mm:ss" (hours:minutes:seconds). The results are then assigned to the "sidebarExtras" property of the pair, which includes an array of objects with labels, values, and tooltips. Finally, it returns true to indicate that the execution was successful.

The result

Custom metrics show next to the chart Your new metrics show on the sidebar next to the chart.

Tip: don't bother manually typing JS code that is minified to fit on a single line. Just search for an online tool to minify your code, so you can write it without formatting concerns. ChatGPT is also good at minifying code to match the formatting requirements to place it in the autoconfig.json file.

Simpler Job Examples for Custom Metrics 🎯

Let's look at some simpler job examples that display the last stochRSI value (data.pair.STOCHRSI), ATR value (data.pair.atr), with an empty element between the other metrics for formatting purposes.

autoconfig.json example

{
"customMetrics": {
"pairs": {
"exclude": "",
"include": "USDT-BTC",
"exchange": "binance"
},
"filters": {
"alwaysPasses": {
"type": "custom",
"target": " true"
}
},
"overrides": {},
"setPairVariable": {
"setMetrics": " (function setMetrics(data) { data.pair.sidebarExtras = [{label: 'StochRSI', value: data.pair.STOCHRSI, tooltip: 'Stochastic RSI value', persist: true}, {label: '', value: '', tooltip: '', persist: true}, {label: 'ATR', value: data.pair.atr, tooltip: 'Average True Range', persist: true}]; return true; })(this)"
},
"clearOverrides": false,
"schedule": "*/15 * * * * *",
"type": "manageOverrides",
"debug": true,
"enabled": true
}
}

This would result in the following custom metrics display:

  • StochRSI
  • Empty Space
  • ATR

Breaking Down the Metrics Calculation and Setting 🔍

The key to understanding and customizing your metrics lies in dissecting the parts that calculate and set the values. This will be different for every metric that you want to implement.

In our complex example,

  1. We begin by filtering orders and calculating the time difference between now and each order's timestamp.
  2. We sort the resulting array in descending order based on the calculated time difference.
  3. The first element of the sorted array represents the most recent order, and we extract its time using new Date(lastBuyTime).toISOString().substr(11, 8).

Tip: you can use JavaScript to modify your data. For example add .toFixed(2) to change a floating point number with many decimal points to a string with just two decimals.

By understanding how metrics are calculated and set, you can customize your dashboard with informative data points matched to your trading needs.

Understanding the Quanta G-Type Strategy for Effective Market Making

@boekenbox
@boekenbox
Understanding the Quanta G-Type Strategy for Effective Market Making

Gunbot offers a range of custom strategies designed for diverse trading styles and market conditions. Among these, the Quanta G-Type strategy stands out for its unique approach to market making. This guide explains how Quanta G-Type works and where it fits in market making.

This guide looks at the key features of the Quanta G-Type strategy

Key Features of Quanta G-Type

Quanta G-Type is a geometric market maker hybrid strategy built by a Gunbot community member. It's built as a 'custom strategy', meaning it is available to Gunbot Ultimate users who can run custom coded strategies. It is designed to adapt to large market price movements, which makes it useful if you focus on market making. The strategy effectively handles different market scenarios, including sideward movements, price pumps, and dumps.

Quanta G in action

Strategy Mechanics

  • Sidewards Market: In a stable market, Quanta G-Type engages in spread trading.
  • Price Pump: During a price increase, the strategy focuses on the decumulation of assets.
  • Price Dump: Conversely, in a declining market, it aims at the accumulation of assets.

These mechanisms help keep the strategy effective across various market conditions, making it versatile for different trading needs.

Is Quanta G-Type Right for You?

Quanta G-Type is built for longer-term market engagement. It works best if you are comfortable managing inventory over time and tuning a strategy with several moving parts. Track its performance over time before you rely on it in live market conditions. If you want alternatives to benchmark against, compare more trading strategies.

Profit Generation and Risks

The strategy generates profits through spread profits, accumulation of spread derivative, and inventory swing. However, it is important to select a viable long-term coin, as the strategy's success is closely tied to the coin's longevity and market performance.

Operational Features

Quanta G-Type includes features such as auto compounding and advanced inventory management. It supports different trading modes, each matched to specific market conditions. The auto-setup process is streamlined, but users must be mindful of key operational considerations.

Getting Started with Quanta G-Type

Starting with the Quanta G-Type strategy involves a series of steps, including setting up the strategy parameters and optionally running simulation tests. These simulation runs are important to understand the strategy's dynamics before implementing it in live trading scenarios. Do read the strategy documentation when setting it up.

Customization and Overrides

The strategy offers a range of customization options through basic and advanced overrides. Key parameters like BUY_INTERVAL, SELL_INTERVAL, and ORDER_DEPTH can be adjusted to suit individual trading preferences and goals.

Conclusion

The Quanta G-Type strategy is a reliable solution for market makers in the cryptocurrency domain. It offers a balanced approach to handling different market conditions, focusing on long-term asset management.

Decoding Gunbot Metrics: A Deep Look at ROE

@boekenbox
@boekenbox
Decoding Gunbot Metrics: A Deep Look at ROE

Today we're going to explain an important yet often misunderstood concept: Return on Equity, commonly known as ROE. By the end of this article, you'll understand what ROE is, why it's useful and how it can guide your trading decisions.

Tip: Understanding ROE will enable you to make better decisions when configuring your Gunbot trading strategies.

What is ROE?

ROE stands for Return On Equity. It represents the percentage gain or loss on the current assets held in your portfolio, inclusive of trading fees paid. In other words, ROE helps you assess the profitability of your spot position at any given time.

Note

Gunbot includes the cost of trading fees in its ROE calculation. This provides a more accurate measure of profitability.

Here's where things get interesting: Gunbot analyzes the whole order history to calculate the current profit or loss on a position. Even with complex order sequences involving multiple buy and partial sell orders, Gunbot keeps track, so you always have a clear view of your position's profitability.

The Importance of ROE in Trading

ROE shows whether a position is making or losing money and gives you real-time information for trade decisions. On futures platforms, this kind of data is common. For spot exchanges, it is much less common.

So how does Gunbot use ROE? Through two common settings: GAIN and STOP_LIMIT.

1. GAIN

The GAIN setting lets you set a take-profit target at a designated ROE percentage. When your position reaches this specified ROE, Gunbot automatically triggers a sell order, locking in your gains.

2. STOP_LIMIT

On the flip side, the STOP_LIMIT option sets a stop-loss when a specific negative ROE value is exceeded. This feature allows you to limit potential losses by triggering an automatic sell order when the market moves against you.

The Added Value of ROE in Gunbot

By providing an precise view of your ROE, Gunbot puts you firmly in control of your trading decisions. This ability to quickly know your current ROE, something typically reserved for futures trading platforms, gives you an edge on spot exchanges.

Tip

The combination of GAIN and STOP_LIMIT settings in Gunbot offers a tactical approach to maximize profits and minimize losses based on accurate ROE data.

Trading is about making the right moves and understanding why they are the right moves. Gunbot gives you metrics like ROE to support that process.

💎 In a Nutshell:

Gunbot's ROE metric brings futures platform advantages to spot exchanges, allowing you to understand your spot position's profitability accurately. By using settings like GAIN and STOP_LIMIT, you can turn this information into strategic actions.

Detailed Guide: Run Gunbot on a Linux VPS with PM2

@boekenbox
@boekenbox
Detailed Guide: Run Gunbot on a Linux VPS with PM2

This guide explains how to set up Gunbot, a cryptocurrency trading automation tool, on a Linux Virtual Private Server (VPS) using PM2. Running Gunbot on a VPS keeps your trading bot online 24/7, independent of your personal computer, minimizing the risk of downtime.

This guide looks at how to run Gunbot on a budget-friendly VPS using PM2.

Benefits of PM2

PM2 is a process manager for Node.js applications that simplifies managing Gunbot:

  • Process Management: Easily start, stop, and restart Gunbot.
  • Logging and Monitoring: Automatically handles logs and simplifies log management.
  • Startup Scripts: Restarts Gunbot automatically after a server reboot.

Setting Up Your VPS

Before proceeding, set up your Linux VPS following your provider's guidelines. Ubuntu is recommended for its simplicity and broad support. For a broader walkthrough beyond this PM2-focused flow, see the official Linux installation guide.

Connect to your server via SSH using a tool compatible with your operating system:

Installing Gunbot and PM2

Download the latest stable Gunbot release (gunthy-linux.zip) and upload it to your VPS using your SSH client. Then, unzip it:

unzip gunthy_linux.zip

Next, install Node.js, npm, and PM2:

sudo apt update
sudo apt install nodejs npm -y
npm install pm2@latest -g

Start Gunbot using PM2 (replace myGunbotProcess with your chosen name):

pm2 start gunthy-linux --name myGunbotProcess

Configuring Firewall

Allow access to Gunbot's default port (5000) using Ubuntu's firewall (UFW):

sudo ufw allow 5000

Check your VPS provider's firewall settings if issues persist.

Managing Logs with PM2

Use PM2 commands to manage logs easily:

# View all process logs
pm2 logs

# View logs for a specific process
pm2 logs myGunbotProcess

# Clear all logs
pm2 flush

Set up automatic log rotation to prevent logs from growing too large:

pm2 install pm2-logrotate

Automatically Restarting Gunbot on System Reboot

Configure PM2 to automatically restart Gunbot after reboot:

pm2 startup
pm2 save

Updating Gunbot

To update Gunbot, follow these steps:

  1. Stop Gunbot:
pm2 stop your-process-name
  1. Upload and replace the existing gunthy-linux file.
  2. Restart Gunbot:
pm2 restart your-process-name

Always review Gunbot’s official upgrade instructions when updates are available.

Running Multiple Gunbot Instances

To run multiple Gunbot instances on a single server:

  1. Duplicate your Gunbot folder for each instance.
  2. Modify config.js in each folder to have unique settings (instructions for multiple instances):
nano config.js
  1. Start each Gunbot instance with a unique name:
pm2 start gunthy-linux --name "another-process-name"

Save your configuration for automatic restarts:

pm2 startup
pm2 save

Using Gunbot with PM2 on a Linux VPS provides a reliable, always-on environment suitable for automated cryptocurrency trading. Affordable VPS options like Hetzner Cloud or Contabo can be enough for many Gunbot setups.

Decoding Gunbot Metrics: Break Even vs. Unit Cost

@boekenbox
@boekenbox
Decoding Gunbot Metrics: Break Even vs. Unit Cost

Have you ever wondered about the differences between break even and unit cost metrics in Gunbot? This article will clear up any confusion and help you make an informed decision on which metric to choose when using strategies like stepgridscalp. Let's get into it.

Tip: Understanding these metrics will enable you to make better decisions when configuring your Gunbot trading strategies.

The Basics of Break Even and Unit Cost Metrics 📊

Both break even and unit cost metrics share a common goal: to analyze spot order history and determine at which price it becomes profitable to start selling. They both account for trading fees as configured in Gunbot's exchange settings. However, there are some key differences:

  • Unit Cost: Represents the average cost of remaining balance that can be sold, considering even partial sell orders. Selling above the unit cost guarantees a profit on every single sell order.
  • Break Even: Represents the price at which the remaining balance can be sold for the entire order group (since opening the position) to be profitable. This means that some individual sell orders might report a loss, but the total group of orders should be profitable.

Choosing between break even and unit cost is a matter of personal preference, but unit cost is generally considered the safer choice.

Note: Market orders may lead to slippage and cause losses if an order fills at a much worse rate than the minimum target.

The strategy gain target is set as a percentage above the unit cost or break even, with the option to use 'dynamic exit logic' to automatically switch between break even and unit cost based on market data.

Example to Illustrate the Differences 🧐

Let's look at two fictional scenarios to better understand the distinction between break even and unit cost metrics.

Example: Unit Cost vs. Break Even

Imagine you bought several items at different prices and now want to sell them for profit:

  • Unit Cost: You calculate the average cost of all unsold items and set your selling price above that number. This way, each sale guarantees a profit.
  • Break Even: Your goal is to cover the total cost of all items, including previous sales, fees, and profits. You don't mind selling some items at a loss as long as the entire group of transactions is profitable.

In Unit Cost mode, you'll only see positive profitable orders whereas in Break Even mode, you may see notifications of sells done at a loss (as it's working on the entire position).

Both break even and unit cost have their advantages and disadvantages, so choose the metric that best aligns with your trading goals and risk tolerance.

Summer Sizzlers: 50% Off on Everything Gunbot!

@boekenbox
@boekenbox
Summer Sizzlers: 50% Off on Everything Gunbot!

Crypto markets might be cold, but this summer promotion gives you 50% off everything Gunbot. If you're a new or existing user, you can use it to improve your automated trading setup at a lower cost.

🔥 The Hottest Deal for New Users

If you've been considering Gunbot, this summer promotion gives new users a 50% discount on any plan. It's a lower-cost way to start with automated trading.

What You Get with Gunbot 🤖

  • Trading automation running from your own device
  • A wide range of trading strategies
  • Customizable settings for personalized trading
  • Frequent updates and improvements to stay ahead of market trends
  • An engaged community to learn from and share ideas with

Quick Tip: New Gunbot users can use the 50% discount to start automated trading at a lower cost.

☀️ Existing Users: Upgrade Your Trading Experience

Existing users can also get a 50% discount when upgrading. You can add features and strategies without paying full price.

Upgrade offer: Existing Gunbot users can upgrade to any plan with a 50% discount.

So what are you waiting for? Use the power of Gunbot's automated trading tools and make the most of your summer investments. With these incredible discounts, it's the perfect opportunity to heat up your crypto returns! 🔥📈

Monitoring and Tracking Performance

@boekenbox
@boekenbox
Monitoring and Tracking Performance

Having a clear overview of your Gunbot strategies' performance is essential for continuous improvement. The better you understand what is happening, the better you will be able to improve what the trading bot is doing for you. we'll introduce you to some of the tools and techniques that can help you monitor and track your trading performance effectively.

Visualize Trades on the Trading Chart 📊

A picture is worth a thousand words, and that's especially true when it comes to analyzing trading data. Gunbot allows you to visualize all trades directly on the trading chart. This makes it easy to spot trends, entry and exit points, and overall strategy performance at a glance. Use these visual cues to assess your trading decisions and make necessary adjustments along the way.

Each arrow symbolizes a trade

tip

By closely examining the trading chart, you can quickly identify patterns and trends in your trading performance.

Monitor Open Positions with ROE % 🔍

One key metric to keep an eye on is the Return on Equity (ROE) percentage, which represents your unrealized Profit and Loss (PNL) for open positions. Gunbot provides this feature so you can easily track how your current trades are performing. A positive ROE % indicates a profitable position, while a negative value suggests a loss. Pay attention to this metric as you make future trading decisions.

tip

Because most trading strategies sell when a position is in profit, it is common to see mostly negative ROE values in the overview for active trading pairs. Pairs spend a lot of time in the red, until they are green and sell.

Review Dashboard Statistics 📉

Gunbot's dashboard offers detailed historical statistics such as cumulative PNL, the number of trades executed, and other valuable metrics. Use these stats to gain insights into long-term trends and the overall success of your trading strategies. Regularly review these numbers to stay informed and make data-driven adjustments to your approach.

Detailed stats on the dashboard

info

Your dashboard holds the key to understanding your trading performance. Analyze the provided data to uncover hidden gems of information that can strengthen your strategies.

Improve Performance Through Systematic Analysis 🧠

Now that you have the tools to monitor and track your Gunbot trading performance, it's time to put them into action. Use the provided statistics and ROE % to identify areas of improvement in your strategy. Experiment with different parameters and settings in Gunbot to see how they impact your performance.

When making adjustments, consider these steps:

  1. Identify patterns and trends in your trading data (e.g., recurring losses or profits).
  2. Determine potential causes for these trends by analyzing trade entries, exits, and other factors.
  3. Implement changes to your strategy based on your findings.
  4. Track the results of your changes over time and make further adjustments as needed.

It's important to remember that trading is a dynamic process, so be prepared to adapt and refine your strategies continuously.

Final Thoughts 💡

Mastering your Gunbot strategies requires ongoing monitoring and tracking of your trading performance. By using the trading chart, ROE %, and dashboard statistics, you can see what is working, spot weak areas, and adjust your setup with evidence instead of guesses.

Customizing Gunbot: Making it Work for You

@boekenbox
@boekenbox
Customizing Gunbot: Making it Work for You

Learn how to tailor Gunbot to your visual trading preferences with these tips on interface and chart personalization.

info

Customize Gunbot for an optimized trading experience. Make it work for you by adjusting the interface, notifications, and strategy KPIs.

Personalizing the Interface 🎨

Gunbot's chart interface can be fine-tuned to suit your needs. To save your preferred chart layout, click on the cloud save icon in the chart top bar. You can save as many layouts as you need. Load chart layouts by selecting the Load Chart Layout option.

Save your custom chart layout

Managing Notification Settings 🔔

Trade notifications appear in Gunbot's GUI whenever trades are made. Some users may find them distracting or unnecessary. If you prefer not to receive these notifications, you can disable them on the profile page. Simply navigate to the profile page and toggle off the trade notifications option.

Using Chart Timescale Marks 📈

Chart timescale marks offer valuable information about past events in your trading strategy. They help you understand the historical performance of specific strategies. However, if you don't want timescale marks cluttering your chart, disable them on the profile page.

The marks and notifications on the bottom of the screen can be disabled

Visualizing Your Custom Strategy 🧠

If you're using a custom strategy, you can draw custom elements on the chart to better visualize your approach. This makes it easier to analyze and refine your trading strategy over time. For detailed instructions on visualizing strategy targets, check out Gunbot's documentation.

tip

Efficiently tailor Gunbot by personalizing the interface, managing notifications, using chart timescale marks, and visualizing your custom strategy.

Customizing Gunbot can make your trading workflow smoother and easier to manage. Try different personalization options to find the combination that works for you. The goal is to create an environment that fits your trading preferences and supports your decision-making process.