Persistent Storage in Gunbot Custom Strategies
Gunbot executes custom strategy code repeatedly for each trading pair, so you need a way to persist values across cycles.
Understanding Variable Persistence
Within custom strategies, standard JavaScript variables are reset with each execution. This matters when you need continuity across cycles, such as tracking a custom state or accumulating data over time.
Variable persistence refers to the ability of a variable to retain its value between separate executions or sessions of a program.
Implementing Persistent Storage
Persistent storage for custom strategies in Gunbot can be achieved using the gb.data.pairLedger.customStratStore object. This object, which is initially undefined, must be explicitly initialized before it can be used for data storage:
// Initialize customStratStore within the pairLedger object if it doesn't exist
gb.data.pairLedger.customStratStore = gb.data.pairLedger.customStratStore || {};
// Now you can store and retrieve data from customStratStore
gb.data.pairLedger.customStratStore.myPersistentVariable = 'some value';
let retrievedValue = gb.data.pairLedger.customStratStore.myPersistentVariable;
This code snippet sets up a dedicated storage area within the pair's ledger. Data stored in customStratStore persists across strategy executions for that specific pair and across Gunbot restarts, because it is saved as part of the pair's ledger file.
Best Practices and Limitations
While customStratStore allows for data persistence, be aware of its limitations. Unexpected Gunbot terminations or corrupt ledger files could lead to data loss.
Gunbot's built-in strategies typically avoid heavy reliance on persistently stored data, preferring to derive state from exchange-provided information (like open orders or trade history) or re-calculate indicators from market data whenever possible. Similarly, when building custom strategies, minimize dependence on persistent storage for critical decision-making data. Use it for supplementary information or non-critical state management.