Add Your Own Logs to Custom Strategies
Custom log files let you record strategy activity in a separate file. This guide covers how to implement them.
Custom logs allow you to record specific events, variable states, or decision-making processes from your strategy into a separate file for later analysis and debugging.
Prerequisites
Before beginning, ensure you have a basic understanding of Node.js, specifically working with the file system (fs) module, as Gunbot strategies run in a Node.js environment.
Implementing Custom Logs
Follow these steps to add custom log files to your Gunbot custom strategy:
1. Access the File System Module
Use Node.js's built-in fs module to interact with the file system. You can access it within your strategy using gb.method.require('fs').
2. Create a Write Stream
Establish a write stream for appending data to your log file. The fs.createWriteStream method is suitable for this, allowing you to specify the log file path and options, such as the 'a' flag for appending.
3. Write to the Log File
With the write stream set up, you can begin logging data from your strategy. Use the write() method of the stream to append information to your log file as needed. Include timestamps or other relevant context in your log entries.
Example Code
The following JavaScript snippet demonstrates this process:
// Importing the file system module
const fs = gb.method.require('fs');
// Define the path for your custom log file
const customLogPath = './gunbot_logs/my-custom-strategy-log.txt';
// Setting up a write stream to the custom log file
// The {flags: 'a'} option ensures that new log entries are appended to the file
const logger = fs.createWriteStream(customLogPath, { flags: 'a' });
// Example of writing a log entry
let tradeDecision = 'buy';
let price = gb.data.bid;
logger.write(`\n[${new Date().toISOString()}] Strategy decided to ${tradeDecision} at price ${price}. Pair: ${gb.data.pairName}`);
// Important: If you create streams, ensure they are properly managed,
// though for simple append-logging, keeping a stream open might be acceptable
// for the strategy's lifecycle. For more complex scenarios, consider stream.end().
This example illustrates a basic implementation. You can extend this to suit more complex logging requirements, such as logging JSON objects or formatting messages differently.