Persistent Storage in Gunbot Custom Strategies
Gunbot frequently executes custom strategy code for each trading pair. One of the challenges encountered in this environment is maintaining variable persistence across different execution cycles.
Understanding Variable Persistence​
Within custom strategies, standard JavaScript variables are reset with each strategy execution. This reset poses a challenge for strategies that require continuity in data handling across multiple trading 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
will persist across strategy executions for that specific pair and even across Gunbot restarts, as it is saved as part of the pair's ledger file.
Best Practices and Limitations​
While customStratStore
allows for data persistence, it is important to be aware of its limitations. Unexpected Gunbot terminations or corrupt ledger files could potentially 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, it is advisable to minimize dependence on persistent storage for critical decision-making data. Use it for supplementary information or non-critical state management.