Skip to main content

Add Your Own Logs to Custom Strategies

Custom log files in Gunbot custom strategies provide enhanced insights into your trading bot's activities. This guide details the process of implementing custom logs, enabling you to create log content tailored to your specific requirements.

Info

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 are executed 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​

Utilize Node.js's built-in fs module to interact with the file system. This module offers various methods for file operations. 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. Remember to 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.

Conclusion​

Custom logs in Gunbot empower you to track and analyze your trading bot's performance effectively. By recording detailed information about your strategy's operations, you can gain valuable insights for debugging, optimization, and performance review. Experiment and adapt this logging approach to fit your unique trading strategy.