Skip to main content

Use global AutoConfig variables (this.variables) in custom filters

ยท 7 min read

Gunbot's AutoConfig feature allows you to define and manipulate global variables that can be shared and accessed across different jobs and filters. Within a custom JavaScript filter (where filterType: "custom"), these global variables are accessible through the this.variables context object. This enables you to create sophisticated, stateful logic that can adapt based on conditions or counters set by other parts of your AutoConfig setup.

Use the AutoConfig wizard

Nearly every option that follows can be set without editing files by hand.
Click the โ‹ฎ (three-dots) menu โžœ AutoConfig, step through the wizard, and press Save; it will write a correct autoconfig.json for you.

Global AutoConfig Variables: A Primerโ€‹

Before diving into this.variables, it's essential to understand how global AutoConfig variables are managed:

  1. Setting Variables: You create or modify global variables as an action within an AutoConfig job, typically using the setVariable or resetVariable objects.
    // In an AutoConfig job definition
    "setVariable": {
    "marketPhase": "bullish",
    "pairsAddedToday": 0
    }
  2. Persistence: These global variables are automatically saved by Gunbot into a file named autoconfig-variables.json in your Gunbot user folder. This allows them to persist across Gunbot restarts.
  3. Accessibility: Once set, these variables become available to other AutoConfig jobs and, crucially, to custom JavaScript filters via this.variables.

The this.variables Context Objectโ€‹

When a custom JavaScript filter (filterType: "custom") executes, Gunbot provides a context object referred to as this. The variables property of this object (this.variables) holds all the global variables currently stored in autoconfig-variables.json.

Your script can then read these values to make informed decisions.

Using this.variables in a Custom Filter Scriptโ€‹

Accessing a global variable is as simple as calling it as a property of this.variables.

Consider this scenario:

  • One AutoConfig job (e.g., counterJob) increments a global variable pairsProcessedCount each time it processes a pair.
  • Another AutoConfig job (e.g., conditionalAdderJob) uses a custom filter that only allows adding new pairs if pairsProcessedCount is below a certain threshold.

counterJob (Conceptual - setting the variable):

// This job would likely be more complex, perhaps of type manageOverrides
// and its filter would determine when to increment the counter.
// For simplicity, let's assume it always increments if it runs.
{
"counterJob": {
"type": "manageOverrides", // Or any type that can have setVariable
"schedule": "*/1 * * * *", // Example schedule
// ... other necessary job parts ...
"filters": { /* ... some filter ... */ },
"setVariable": {
// Assuming 'pairsProcessedCount' is initialized elsewhere or defaults to 0 if not found
"pairsProcessedCount": " (this.variables.pairsProcessedCount || 0) + 1 " // Note: value is a string to be evaluated
}
}
}

(Note: The actual increment logic for setVariable might need careful crafting as the value part is evaluated. A safer way to increment might be via a custom script in a job that sets the variable.)

A more robust way to set/increment variables is often done by a dedicated job that perhaps uses a custom script itself to manage this logic for setVariable.

conditionalAdderJob (Reading the variable in a custom filter):

{
"conditionalAdderJob": {
"enabled": true,
"type": "addPairs",
"schedule": "*/5 * * * *",
"pairs": {
"exchange": "binance",
"include": "USDT-"
},
"filters": {
"checkProcessedCount": {
"filterType": "custom",
"script": "/* Using this.variables */ \n const maxPairsToProcess = 10; \n // Access the global variable, provide a default if it doesn't exist yet \n const currentCount = this.variables.pairsProcessedCount || 0; \n \n if (currentCount < maxPairsToProcess) { \n console.log('pairsProcessedCount (' + currentCount + ') is less than ' + maxPairsToProcess + '. Filter passes.'); \n return true; // Allow adding pairs \n } else { \n console.log('pairsProcessedCount (' + currentCount + ') reached limit of ' + maxPairsToProcess + '. Filter fails.'); \n return false; // Stop adding pairs \n }"
},
"standardVolumeFilter": {
"filterType": "minVolume24h",
"minVolume": 500000
}
},
"strategy": "spotgrid"
}
}

In the checkProcessedCount custom filter of conditionalAdderJob:

  • const currentCount = this.variables.pairsProcessedCount || 0;: This line retrieves the value of the global variable pairsProcessedCount. If the variable hasn't been set yet (e.g., on the very first run), this.variables.pairsProcessedCount would be undefined, so the || 0 provides a default starting value of 0.
  • The script then compares currentCount to maxPairsToProcess and returns true or false accordingly.

Practical Applicationsโ€‹

  1. Global Flags:

    • Set a global variable like this.variables.isMarketVolatile = true based on broad market indicators (e.g., VIX, BTC dominance changes) by one job.
    • Other jobs' custom filters can then check if (this.variables.isMarketVolatile) to adjust their behavior (e.g., use tighter stops, reduce trade size via overrides).
  2. Counters and Limits:

    • Limit the number of pairs added per day: An addPairs job increments this.variables.dailyAdds. Its custom filter checks if (this.variables.dailyAdds < 5). A separate job resets dailyAdds to 0 at midnight.
    • Track consecutive losses or wins for a system-wide risk adjustment.
  3. State Machines:

    • Define a global variable this.variables.currentSystemState = "phase1".
    • Different jobs or filter sets can activate based on the value of currentSystemState.
    • Actions within jobs can transition currentSystemState to "phase2", "cooldown", etc.
  4. Cross-Job Communication:

    • One job detects a strong trend for a specific asset (e.g., BTC) and sets this.variables.strongBTCTrend = true.
    • Other jobs adding altcoin pairs might have custom filters that become more lenient if this.variables.strongBTCTrend is true.

Important Notesโ€‹

  • Read-Only in Filters: While you can read this.variables in a custom filter, you generally cannot reliably modify global variables directly from within a filter script (e.g., this.variables.myVar = 'newValue'; in a filter script won't reliably update autoconfig-variables.json). Changes to global variables should be done through job actions like setVariable.
  • Data Types: Global variables can store strings, numbers, or booleans. When reading them in your script, ensure you handle the data type appropriately (e.g., use parseInt() or parseFloat() if you expect a number but it might be stored as a string).
  • Initialization: If a global variable might not exist when your filter first runs, provide a default value in your script using the || operator as shown in the example (e.g., this.variables.myCounter || 0).
  • Naming Conventions: Choose clear and descriptive names for your global variables to avoid confusion, especially if you use many of them.

this.variables transforms AutoConfig from a set of independent job runners into a more cohesive system where different automated processes can share state and influence each other's behavior. This opens the door to building highly adaptive and intelligent automation workflows within Gunbot.