### Clone and Build GoCryptoTrader on Windows Source: https://github.com/thrasher-corp/gocryptotrader/wiki/Installation-Guide This script clones the GoCryptoTrader repository, builds the executable, and copies the example configuration file to the user's AppData directory. It requires Git and Go 1.11+ with Go Modules enabled. ```bash git clone https://github.com/thrasher-/gocryptotrader.git cd gocryptotrader go build copy config_example.json %APPDATA%\GoCryptoTrader\config.json ``` -------------------------------- ### Clone and Build GoCryptoTrader on Linux/OSX Source: https://github.com/thrasher-corp/gocryptotrader/wiki/Installation-Guide This script clones the GoCryptoTrader repository, builds the executable, creates a configuration directory, and copies the example configuration file. It requires Git and Go 1.11+ with Go Modules enabled. ```bash git clone https://github.com/thrasher-/gocryptotrader.git cd gocryptotrader go build mkdir ~/.gocryptotrader cp config_example.json ~/.gocryptotrader/config.json ``` -------------------------------- ### Install GoCryptoTrader Executable Source: https://github.com/thrasher-corp/gocryptotrader/wiki/Installation-Guide This command builds the GoCryptoTrader project, outputting an executable file. It assumes you are in the project's root directory and have Go installed. ```bash go install ``` -------------------------------- ### Build and Run GoCryptoTrader with Default Config Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/config/README.md This example demonstrates how to copy a default configuration file, build the GoCryptoTrader application, and run it with the default configuration. This is useful for initial setup and testing. ```shell cd ~/go/src/github.com/thrasher-corp/gocryptotrader cp config_example.json config.json # Test config go build ./gocryptotrader ``` -------------------------------- ### Install gRPC Protobuf Compiler Plugins Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/backtester/btrpc/README.md Installs necessary gRPC and Protobuf compiler plugins required for the GoCryptoTrader Backtester. This command downloads and installs binaries like protoc-gen-grpc-gateway, protoc-gen-openapiv2, protoc-gen-go, and protoc-gen-go-grpc into your GOBIN directory. ```bash go install \ github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \ github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \ google.golang.org/protobuf/cmd/protoc-gen-go \ google.golang.org/grpc/cmd/protoc-gen-go-grpc ``` -------------------------------- ### Clone and Build GoCryptoTrader on Windows Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/README.md This snippet provides the commands to clone the GoCryptoTrader repository, build the application, create a configuration directory in the AppData folder, and copy the example configuration file for Windows systems. ```bash git clone https://github.com/thrasher-corp/gocryptotrader.git cd gocryptotrader go build mkdir %AppData%\GoCryptoTrader copy config_example.json %APPDATA%\GoCryptoTrader\config.json ``` -------------------------------- ### Bash: REST API via gRPC Gateway Examples Source: https://context7.com/thrasher-corp/gocryptotrader/llms.txt These bash commands demonstrate how to interact with the GoCryptoTrader REST API, which is proxied through gRPC Gateway. It shows how to start the GoCryptoTrader with the gRPC proxy enabled and how to make GET and POST requests to retrieve system information and ticker data, respectively. ```bash # Start GoCryptoTrader with gRPC proxy enabled ./gocryptotrader -grpcproxy # Get system info via REST curl -X GET "https://localhost:9053/v1/getinfo" \ -H "Authorization: Basic YWRtaW46UGFzc3dvcmQ=" \ --cacert cert.pem # Get ticker via REST curl -X POST "https://localhost:9053/v1/getticker" \ -H "Authorization: Basic YWRtaW46UGFzc3dvcmQ=" \ -H "Content-Type: application/json" \ --cacert cert.pem \ -d '{ "exchange": "Binance", "pair": { "base": "BTC", "quote": "USDT" }, "asset_type": "spot" }' ``` -------------------------------- ### Subscription Template Example Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/exchanges/subscription/README.md An example of a Go text/template used for configuring exchange subscriptions. It demonstrates iterating over asset-pair mappings, batching pairs, and using provided directives for separators and batch size. ```gohtml {{- range $asset, $pairs := $.AssetPairs }} {{- range $b := batch $pairs 30 -}} {{- $.S.Channel -}} : {{- $b.Join -}} {{ $.PairSeparator }} {{- end -}} {{- $.BatchSize -}} 30 {{- $.AssetSeparator }} {{- end }} ``` -------------------------------- ### GoCryptoTrader Documentation Template Example Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/cmd/documentation/README.md An example of a Go template file (`.tmpl`) used by the GoCryptoTrader documentation generator. This template defines sections like 'header', 'contributions', and 'donations', and includes a placeholder for coding examples. The `{{define "template_name" -}} ... {{end}}` syntax is used to define template blocks, which are then rendered by the documentation tool. ```go-template {{define "example_definition_created_by_documentation_tool" -}} {{template "header" .}} ## Current Features for documentation #### A concise blurb about the package or tool system + Coding examples import "github.com/thrasher-corp/gocryptotrader/something" testString := "aAaAa" upper := strings.ToUpper(testString) // upper == "AAAAA" {{template "contributions"}} {{template "donations"}} {{end}} ``` -------------------------------- ### Setup and Get Rates with CurrencyConverterAPI (Go) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/currency/forexprovider/currencyconverterapi/README.md Demonstrates how to set up the CurrencyConverterAPI client with configuration settings and retrieve currency exchange rates. It requires the 'base' and 'currencyconverter' packages. The output is a map of currency pairs to their rates and an error object. ```go import ( "time" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/currencyconverter" ) c := currencyconverter.CurrencyConverter{} // Define configuration newSettings := base.Settings{ Name: "CurrencyConverter", Enabled: true, Verbose: false, RESTPollingDelay: time.Duration(1000000000), APIKey: "key", APIKeyLvl: "keylvl", PrimaryProvider: true, } c.Setup(newSettings) mapstringfloat, err := c.GetRates("USD", "EUR,CHY") // Handle error ``` -------------------------------- ### Running GoCryptoTrader Backtester with Strategy Plugin Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/backtester/plugins/strategies/example/README.md Demonstrates the command-line flags required to run the GoCryptoTrader Backtester with a custom strategy plugin. This allows external strategies to be loaded and executed by the backtester. ```bash ./backtester -strategypluginpath="path/to/strategy/example.so" ``` ```bash ./backtester --strategypluginpath="./plugins/strategies/example/example.so" ``` -------------------------------- ### GoCryptoTrader Documentation Configuration Example Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/cmd/documentation/README.md An example JSON configuration file for the GoCryptoTrader documentation tool. This file specifies the GitHub repository API endpoint, allows for exclusion of specific files and directories, and enables features like root README generation, license file creation, and contributor list updates. The `referencePathToRepo` setting is crucial for correct path resolution. ```json { "githubRepo": "https://api.github.com/repos/thrasher-corp/gocryptotrader", "exclusionList": { "Files": null, "Directories": [ "_templates", ".git", "web" ] }, "rootReadmeActive": true, "licenseFileActive": true, "contributorFileActive": true, "referencePathToRepo": "../../" } ``` -------------------------------- ### Clone and Build GoCryptoTrader on Linux/macOS Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/README.md This snippet shows the commands to clone the GoCryptoTrader repository, navigate into the directory, build the application, create a configuration directory, and copy the example configuration file for Linux and macOS systems. ```bash git clone https://github.com/thrasher-corp/gocryptotrader.git cd gocryptotrader go build mkdir ~/.gocryptotrader cp config_example.json ~/.gocryptotrader/config.json ``` -------------------------------- ### GoCryptoTrader gctscript Example Configuration Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/gctscript/README.md An example JSON configuration for the gctscript package. This demonstrates how to enable the script functionality, set a script timeout, allow script imports, specify scripts to auto-load on startup, and configure debug mode. ```Shell Script "gctscript": { "enabled": true, "timeout": 600000000, "allow_imports": true, "auto_load": [], "debug": false }, ``` -------------------------------- ### Bash: gctcli Command-Line Client Examples Source: https://context7.com/thrasher-corp/gocryptotrader/llms.txt This set of bash commands demonstrates how to build and use the gctcli command-line interface to interact with the GoCryptoTrader bot. It covers various operations like getting system info, tickers, order books, account balances, submitting and managing orders, and controlling bot subsystems. ```bash # Build and run the CLI client cd cmd/gctcli go build ./gctcli --help # Get system information ./gctcli getinfo # Get ticker for a specific pair ./gctcli getticker --exchange=Binance --pair=BTC-USDT --asset=spot # Get orderbook ./gctcli getorderbook --exchange=Binance --pair=BTC-USDT --asset=spot # Get account balances ./gctcli getaccountbalances --exchange=Binance --asset=spot # Submit a limit order ./gctcli submitorder \ --exchange=Binance \ --pair=BTC-USDT \ --side=BUY \ --type=LIMIT \ --price=50000 \ --amount=0.001 \ --asset=spot # Get order details ./gctcli getorder --exchange=Binance --orderid=12345 --pair=BTC-USDT # Cancel an order ./gctcli cancelorder --exchange=Binance --orderid=12345 --pair=BTC-USDT # Get all orders ./gctcli getorders --exchange=Binance --pair=BTC-USDT --asset=spot # Get portfolio summary ./gctcli getportfoliosummary # Get historical candles ./gctcli gethistoriccandles \ --exchange=Binance \ --pair=BTC-USDT \ --start="2024-01-01T00:00:00Z" \ --end="2024-01-02T00:00:00Z" \ --interval=1h # Enable/disable subsystems ./gctcli enablesubsystem --subsystem=ordermanager ./gctcli disablesubsystem --subsystem=ordermanager # Shutdown the bot ./gctcli shutdown ``` -------------------------------- ### Setup SMSGlobal Communications in Go Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/communications/smsglobal/README.md This Go code snippet demonstrates how to initialize and set up the SMSGlobal communication client. It requires importing the necessary packages, creating an instance of SMSGlobal, defining its configuration including credentials and contact lists, and then calling the Setup method. The Connect method is then called to establish a connection, with error handling advised. ```go import ( "github.com/thrasher-corp/gocryptotrader/communications/smsglobal" "github.com/thrasher-corp/gocryptotrader/config" ) s := new(smsglobal.SMSGlobal) // Define SMSGlobal configuration commsConfig := config.CommunicationsConfig{SMSGlobalConfig: config.SMSGlobalConfig{ Name: "SMSGlobal", Enabled: true, Verbose: false, Username: "username", Password: "password", Contacts: []config.SMSContact{}}} // Add actual contacts here s.Setup(commsConfig) err := s.Connect // Handle error ``` -------------------------------- ### Example Strategy Implementation (Conceptual) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/backtester/eventhandlers/strategies/README.md Illustrates a conceptual implementation of a strategy adhering to the Handler interface. It demonstrates accessing pricing data, checking for data availability, and returning a signal event. The 'AppendWhy' function is shown for logging decision rationale. ```go package rsi // Example strategy package import ( "errors" "github.com/thrasher-corp/gocryptotrader/backtester/data" "github.com/thrasher-corp/gocryptotrader/backtester/portfolio" signal "github.com/thrasher-corp/gocryptotrader/backtester/signal" "github.com/thrasher-corp/gocryptotrader/common" ) var _ strategies.Handler = (*Strategy)(nil) // Strategy holds the strategy's configuration and runtime data type Strategy struct { LastSignal signal.Event Why string Config StrategyConfig } // StrategyConfig holds configuration for the strategy type StrategyConfig struct { RSIValue int } // OnSignal executes the strategy logic for a single data event func (s *Strategy) OnSignal(d data.Handler, _ portfolio.Handler) (signal.Event, error) { if d.HasDataAtTime(d.Latest().GetTime()) == false { s.AppendWhy(common.Now().String() + " Data has no value at this time.") return signal.Event{}, errors.New("no data at time") } // ... RSI calculation logic using d.Indicate() ... // Example: If RSI is below a threshold, signal BUY // rsiValue := ... // calculated RSI // if rsiValue < s.Config.RSIValue { // s.AppendWhy("RSI is low, signalling BUY") // s.LastSignal = signal.Event{Signal: signal.Buy, Timestamp: d.Latest().GetTime()} // return s.LastSignal, nil // } // Example: If RSI is above a threshold, signal SELL // if rsiValue > (100 - s.Config.RSIValue) { // s.AppendWhy("RSI is high, signalling SELL") // s.LastSignal = signal.Event{Signal: signal.Sell, Timestamp: d.Latest().GetTime()} // return s.LastSignal, nil // } ss.AppendWhy("No signal generated") return signal.Event{Signal: signal.DoNothing, Timestamp: d.Latest().GetTime()}, nil } // AppendWhy appends the reasoning for the signal func (s *Strategy) AppendWhy(why string) { s.Why = s.Why + why + "\n" } ``` -------------------------------- ### SQLBoiler Installation (Shell) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/database/README.md Shell commands to install SQLBoiler and its PostgreSQL and SQLite drivers using Go's package management. These are prerequisites for generating database models with SQLBoiler. ```shell go install github.com/thrasher-corp/sqlboiler ``` ```shell go install github.com/thrasher-corp/sqlboiler/drivers/sqlboiler-psql ``` ```shell go install github.com/thrasher-corp/sqlboiler-sqlite3 ``` -------------------------------- ### Go Program for String Manipulation Example Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/cmd/documentation/README.md A simple Go code snippet demonstrating basic string manipulation. It converts a given string to its uppercase equivalent using the `strings.ToUpper` function from the standard `strings` package. This example is typically used within documentation templates to illustrate Go syntax and standard library usage. ```go import "github.com/thrasher-corp/gocryptotrader/something" testString := "aAaAa" upper := strings.ToUpper(testString) // upper == "AAAAA" ``` -------------------------------- ### Build and Run GoCryptoTrader with Custom Config Path Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/config/README.md This example shows how to use a custom configuration file by copying the default configuration to a new file and then running GoCryptoTrader with the `-config` flag specifying the custom file path. This allows for flexible configuration management. ```shell cd ~/go/src/github.com/thrasher-corp/gocryptotrader cp config_example.json custom.json # Test config go build ./gocryptotrader -config custom.json ``` -------------------------------- ### Setup Default Websocket Connection in GoCryptoTrader Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/exchange/websocket/README.md This Go code demonstrates how to set up the default websocket manager and its associated parameters within an exchange wrapper. It initializes the websocket manager and configures buffer limits and timeouts. ```go package main import ( "github.com/thrasher-corp/gocryptotrader/exchange/websocket" exchange "github.com/thrasher-corp/gocryptotrader/exchanges" "github.com/thrasher-corp/gocryptotrader/exchanges/request" ) type Exchange struct { exchange.Base } // In the exchange wrapper this will set up the initial pointer field provided by exchange.Base func (e *Exchange) SetDefault() { e.Websocket = websocket.NewManager() e.WebsocketResponseMaxLimit = exchange.DefaultWebsocketResponseMaxLimit e.WebsocketResponseCheckTimeout = exchange.DefaultWebsocketResponseCheckTimeout e.WebsocketOrderbookBufferLimit = exchange.DefaultWebsocketOrderbookBufferLimit } ``` -------------------------------- ### Get Loaded Orderbook - GoCryptoTrader Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/exchanges/orderbook/README.md This example shows how to retrieve a pre-loaded orderbook directly from the orderbook package. It is useful when an exchange's orderbook is being managed by a separate routine. ```go ob, err := orderbook.Get(...) if err != nil { // Handle error } ``` -------------------------------- ### Setup and Connect Slack Bot in Go Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/communications/slack/README.md This Go code snippet demonstrates how to initialize and set up the Slack client using configuration from the GoCryptoTrader config package. It shows how to define the Slack configuration, including the target channel and verification token, and then connect the bot. Error handling for the connection is also indicated. ```go import ( "github.com/thrasher-corp/gocryptotrader/communications/slack" "github.com/thrasher-corp/gocryptotrader/config" ) s := new(slack.Slack) // Define slack configuration commsConfig := config.CommunicationsConfig{SlackConfig: config.SlackConfig{ Name: "Slack", Enabled: true, Verbose: false, TargetChannel: "targetChan", VerificationToken: "slackGeneratedToken", }} s.Setup(commsConfig) err := s.Connect // Handle error ``` -------------------------------- ### Setup and Fetch Rates using Open Exchange Rates Package (Go) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/currency/forexprovider/openexchangerates/README.md This Go code snippet demonstrates how to initialize and configure the Open Exchange Rates forex provider. It shows the necessary imports, setting up provider configuration, and fetching currency exchange rates between specified currencies. Ensure you have the necessary API keys and have enabled the provider in your GoCryptoTrader configuration. ```go import ( "time" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/openexchangerates" ) c := openexchangerates.OXR{} // Define configuration newSettings := base.Settings{ Name: "openexchangerates", Enabled: true, Verbose: false, RESTPollingDelay: time.Duration(0), APIKey: "key", APIKeyLvl: "keylvl", PrimaryProvider: true, } c.Setup(newSettings) mapstringfloat, err := c.GetRates("USD", "EUR,CHY") // Handle error ``` -------------------------------- ### Exchange Data CSV File Format Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/cmd/dbseed/README.md This example shows the expected format for a CSV file used to import exchange data. The file should contain one exchange name per line. No header row is expected. An example includes 'binance' and 'btc markets'. ```csv exchange binance, btc markets, ``` -------------------------------- ### Setup and Fetch Rates with Exchangeratesapi.io (Go) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/currency/forexprovider/exchangeratesapi.io/README.md This code snippet demonstrates how to initialize and configure the Exchangeratesapi.io forex provider in GoCryptoTrader. It shows setting up the provider with custom settings and then fetching currency exchange rates for specified currencies. Dependencies include the base and exchangerates packages from the GoCryptoTrader library. ```go import ( "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/exchangerates" ) c := exchangerates.ExchangeRates{} // Define configuration newSettings := base.Settings{ Name: "ExchangeRates", Enabled: true, Verbose: false, RESTPollingDelay: time.Duration, APIKey: "key", APIKeyLvl: "keylvl", PrimaryProvider: true, } c.Setup(newSettings) mapstringfloat, err := c.GetRates("USD", "EUR,CHY") // Handle error ``` -------------------------------- ### Setup and Connect SMTP Service (Go) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/communications/smtpservice/README.md This code snippet demonstrates how to initialize and set up the SMTPservice with configuration details and then establish a connection. It requires importing the smtpservice and config packages. The configuration includes enabling the service, setting connection details like host, port, account credentials, and the recipient list. ```go import ( "github.com/thrasher-corp/gocryptotrader/communications/smtpservice" "github.com/thrasher-corp/gocryptotrader/config" ) s := new(smtpservice.SMTPservice) // Define SMTPservice configuration commsConfig := config.CommunicationsConfig{SMTPservice: config.SMTPConfig{ Name: "SMTPservice", Enabled: true, Verbose: false, Host: "host", Port: "port", AccountName: "name", AccountPassword: "password", RecipientList: "something@something.com,somethingelse@something.com" }} s.Setup(commsConfig) err := s.Connect // Handle error ``` -------------------------------- ### GoCryptoTrader Order Event Type Custom Functions Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/backtester/eventtypes/order/README.md This Go code snippet outlines the custom functions available for the Order Event Type in GoCryptoTrader's backtester. These functions allow for setting and retrieving order amounts, checking if an event is an order, getting the order status, setting and retrieving the order ID, getting the limit price, and checking for leveraged orders. These are essential for managing trade order logic within the backtesting framework. ```go func SetAmount(float64) func GetAmount() float64 func IsOrder() bool func GetStatus() order.Status func SetID(id string) func GetID() string func GetLimit() float64 func IsLeveraged() bool ``` -------------------------------- ### Setup and Fetch Rates with GoCryptoTrader Fixer.io Package Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/currency/forexprovider/fixer.io/README.md This Go code snippet demonstrates how to initialize and configure the Fixer.io forex provider within the GoCryptoTrader framework. It shows setting up provider configurations, including API keys and polling delays, and then making a call to fetch currency exchange rates between specified currencies. Ensure the 'time' package is imported for duration settings. ```go import ( "time" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/fixer.io" ) c := fixer.Fixer{} // Define configuration newSettings := base.Settings{ Name: "Fixer", Enabled: true, Verbose: false, RESTPollingDelay: time.Second, APIKey: "key", APIKeyLvl: "keylvl", PrimaryProvider: true, } c.Setup(newSettings) mapstringfloat, err := c.GetRates("USD", "EUR,CHY") // Handle error ``` -------------------------------- ### Get Account Balances via REST API Source: https://context7.com/thrasher-corp/gocryptotrader/llms.txt Retrieves account balances for a specified exchange and asset type. Requires exchange details and asset type. Uses Basic Authentication. ```curl curl -X POST "https://localhost:9053/v1/getaccountbalances" \ -H "Authorization: Basic YWRtaW46UGFzc3dvcmQ=" \ -H "Content-Type: application/json" \ --cacert cert.pem \ -d '{ "exchange": "Binance", "asset_type": "spot" }' ``` -------------------------------- ### Get Deposit Address (gctcli) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/docs/MULTICHAIN_TRANSFER_SUPPORT.md Obtains a deposit address for a specific cryptocurrency and transfer chain on a designated exchange. This function is crucial for initiating deposits via the gctcli. ```shell ./gctcli getcryptocurrencydepositaddress --exchange=binance --cryptocurrency=usdt --chain=sol { "address": "GW3oT9JpFyTkCWPnt6Yw9ugppSQwDv4ZMG1vabC8WmHS" } ``` -------------------------------- ### Enable Live Testing for Exchange Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/exchanges/mock/README.md This Go code snippet demonstrates how to configure and enable live testing for an exchange. It loads configuration, sets API credentials, and initializes the exchange for live API calls. This file is compiled when the 'mock_test_off' build tag is present. ```go //+build mock_test_off // This will build if build tag mock_test_off is parsed and will do live testing // using all tests in (exchange)_test.go package your_current_exchange_name import ( "os" "testing" "log" "github.com/thrasher-corp/gocryptotrader/config" "github.com/thrasher-corp/gocryptotrader/exchanges/sharedtestvalues" ) var mockTests = false func TestMain(m *testing.M) { cfg := config.GetConfig() cfg.LoadConfig("../../testdata/configtest.json") your_current_exchange_nameConfig, err := cfg.GetExchangeConfig("your_current_exchange_name") if err != nil { log.Fatal("your_current_exchange_name Setup() init error", err) } your_current_exchange_nameConfig.API.AuthenticatedSupport = true your_current_exchange_nameConfig.API.Credentials.Key = apiKey your_current_exchange_nameConfig.API.Credentials.Secret = apiSecret s.SetDefaults() s.Setup(&your_current_exchange_nameConfig) log.Printf(sharedtestvalues.LiveTesting, s.Name, s.API.Endpoints.URL) os.Exit(m.Run()) } ``` -------------------------------- ### Get Status of Running GCTScripts Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/gctscript/README.md Command to retrieve the status of all currently running GCT scripts. The output lists each script's UUID, name, and next scheduled run time. ```shell gctcli script status ``` -------------------------------- ### Get Available Transfer Chains (gctcli) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/docs/MULTICHAIN_TRANSFER_SUPPORT.md Retrieves a list of supported blockchain transfer chains for a given cryptocurrency and exchange. This command uses the gctcli tool to interact with the GoCryptoTrader backend. ```shell ./gctcli getavailabletransferchains --exchange=binance --cryptocurrency=usdt { "chains": [ "erc20", "trx", "sol", "omni" ] } ``` -------------------------------- ### Generate GoCryptoTrader Documentation Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/cmd/documentation/README.md This Go program automatically generates and regenerates documentation for the GoCryptoTrader codebase. It can be run from the `gocryptotrader/cmd/documentation/` directory using `go run documentation.go`. The `-v` flag enables verbose output for deeper insights into the process. The tool requires a configuration JSON file and manages directory traversal, template finding, and contributor list updates. ```go go run documentation.go go run documentation.go -v ``` -------------------------------- ### Configure Script Autoloading Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/gctscript/README.md This configuration entry allows scripts to be automatically loaded when the GoCryptoTrader bot starts. Scripts are expected to be located in a 'scripts' folder within the GoCryptoTrader data directory. ```shell "auto_load": ["one","two"] ``` -------------------------------- ### Run Documentation Generator (Console) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/docs/ADD_NEW_EXCHANGE.md This console command shows how to execute the documentation generation tool. It requires navigating to the documentation directory and running the `documentation.go` script using `go run`. ```bash cd gocryptotrader\cmd\documentation go run documentation.go ``` -------------------------------- ### Backtesting Engine in Go Source: https://context7.com/thrasher-corp/gocryptotrader/llms.txt Sets up and runs a backtest using historical data and custom strategies. Loads configuration from a file, executes the backtest, and generates a report with performance metrics. Requires backtester configuration and Go packages. ```go package main import ( "log" "github.com/thrasher-corp/gocryptotrader/backtester/engine" "github.com/thrasher-corp/gocryptotrader/backtester/config" ) func main() { // Load backtest configuration cfg, err := config.ReadStrategyConfigFromFile("strategy.strat") if err != nil { log.Fatal(err) } // Create backtest instance bt := &engine.BackTest{} // Set up backtest with config err = bt.SetupFromConfig(cfg) if err != nil { log.Fatal(err) } // Execute backtest err = bt.Run() if err != nil { log.Fatal(err) } // Generate report report, err := bt.Reports.GenerateReport() if err != nil { log.Fatal(err) } log.Printf("Backtest completed!") log.Printf("Total trades: %d", report.TotalTrades) log.Printf("Winning trades: %d", report.WinningTrades) log.Printf("Losing trades: %d", report.LosingTrades) log.Printf("Final value: %f", report.FinalValue) log.Printf("Total profit/loss: %f", report.TotalProfitLoss) log.Printf("Sharpe ratio: %f", report.SharpeRatio) log.Printf("Max drawdown: %f%%", report.MaxDrawdown) } ``` -------------------------------- ### Define Currency Conversion Rates in Go Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/contrib/spellcheck/exclude_lines.txt Shows the definition of conversion rates for specific currencies. This example includes a rate for 'currency.MIS' and a placeholder for 'currency.SHFT', essential for financial calculations and conversions within the trading platform. ```go currency.MIS: 0.002, SHFT = NewCode("SHFT") currency.SHFT: 84, ``` -------------------------------- ### Setup and Fetch Rates with Currencylayer Package Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/currency/forexprovider/currencylayer/README.md This Go code snippet demonstrates how to set up the Currencylayer client and fetch currency exchange rates. It requires the 'base' and 'currencylayer' packages from GoCryptoTrader. The function takes a base currency and a comma-separated string of target currencies, returning a map of currency pairs to their rates and an error if the operation fails. ```go import ( "time" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base" "github.com/thrasher-corp/gocryptotrader/currency/forexprovider/currencylayer" ) c := currencylayer.CurrencyLayer{} // Define configuration newSettings := base.Settings{ Name: "CurrencyLayer", Enabled: true, Verbose: false, RESTPollingDelay: time.Duration(0), APIKey: "key", APIKeyLvl: "keylvl", PrimaryProvider: true, } c.Setup(newSettings) mapstringfloat, err := c.GetRates("USD", "EUR,CHY") // Handle error ``` -------------------------------- ### Add Single Exchange to dbseed Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/cmd/dbseed/README.md This Go command example shows how to add a single new exchange to the GoCryptoTrader configuration using the dbseed tool. The `--name` flag specifies the name of the exchange to be added. ```bash dbseed exchange add --name=newexchange ``` -------------------------------- ### Initialize and Use Exmo Exchange (GoCryptoTrader) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/exchanges/exmo/README.md Demonstrates how to obtain an Exmo exchange instance from the GoCryptoTrader bot and perform public and private API calls using wrapper functions. It highlights fetching ticker and order book data, and retrieving account information. Ensure API keys are configured for private calls. ```go var e exchange.IBotExchange for i := range bot.Exchanges { if bot.Exchanges[i].GetName() == "Exmo" { e = bot.Exchanges[i] } } // Public calls - wrapper functions // Fetches current ticker information tick, err := e.UpdateTicker(...) if err != nil { // Handle error } // Fetches current orderbook information ob, err := e.UpdateOrderbook(...) if err != nil { // Handle error } // Private calls - wrapper functions - make sure your APIKEY and APISECRET are // set and AuthenticatedAPISupport is set to true // Fetches current account information accountInfo, err := e.GetAccountInfo() if err != nil { // Handle error } ``` -------------------------------- ### gRPC: Get Historical Trades Source: https://context7.com/thrasher-corp/gocryptotrader/llms.txt Fetches historical trade data for a given exchange, currency pair, asset type, and time range. This function uses the GoCryptoTrader gRPC client and logs a summary of the retrieved trades. ```go import ( "context" "log" "time" gctrpc "github.com/thrasher-corp/gocryptotrader/engine/rpc" ) // Get historical trade data func GetHistoricalTrades(client gctrpc.GoCryptoTraderServiceClient) { resp, err := client.GetHistoricTrades(context.Background(), &gctrpc.GetHistoricTradesRequest{ Exchange: "Binance", Pair: &gctrpc.CurrencyPair{ Base: "BTC", Quote: "USDT", }, AssetType: "spot", Start: time.Now().Add(-1 * time.Hour).Unix(), End: time.Now().Unix(), }) if err != nil { log.Fatal(err) } log.Printf("Retrieved %d trades", len(resp.Trades)) for _, trade := range resp.Trades[:10] { log.Printf("Time: %d Price: %f Amount: %f Side: %s", trade.Timestamp, trade.Price, trade.Amount, trade.Side) } } ``` -------------------------------- ### Execute GCTScript by Name and Path Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/gctscript/README.md Command to start or execute a specific GCT script by its name. An optional path override can be provided. The output includes the script's execution status and confirmation message. ```shell gctcli script execute gctcli script execute "timer.gct" "~/gctscript" ``` -------------------------------- ### Update Configuration and Build GoCryptoTrader Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/docs/ADD_NEW_EXCHANGE.md This command builds the GoCryptoTrader executable and then runs it with a specified configuration file (e.g., `config_example.json`). It's crucial to ensure this process does not interfere with existing NTP client or encrypted config settings. This step verifies the integration of the new exchange configuration. ```console go build && gocryptotrader.exe --config=config_example.json ``` -------------------------------- ### Integrate GoCryptoTrader with PostgreSQL (Go) Source: https://context7.com/thrasher-corp/gocryptotrader/llms.txt Demonstrates how to connect to a PostgreSQL database, initialize the GoCryptoTrader database instance, insert trade data, and query trade history. This requires the `database` and `trade` repositories, along with the PostgreSQL driver. ```go package main import ( "context" "database/sql" "log" "time" "github.com/thrasher-corp/gocryptotrader/database" "github.com/thrasher-corp/gocryptotrader/database/repository/trade" _ "github.com/lib/pq" ) func main() { // Connect to PostgreSQL database db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres password=secret dbname=gocryptotrader sslmode=disable") if err != nil { log.Fatal(err) } defer db.Close() // Initialize database instance dbInstance := database.DB dbInstance.SetPostgresConnection(db) dbInstance.SetConnected(true) // Insert trade data err = trade.Insert(trade.Data{ ExchangeName: "Binance", Base: "BTC", Quote: "USDT", AssetType: "spot", Price: 50000.0, Amount: 0.5, Side: "BUY", Timestamp: time.Now(), }) if err != nil { log.Fatal(err) } log.Println("Trade data inserted successfully") // Query trade data trades, err := trade.GetTradesInRange(context.Background(), "Binance", "spot", "BTC", "USDT", time.Now().Add(-24*time.Hour), time.Now()) if err != nil { log.Fatal(err) } log.Printf("Retrieved %d trades in the last 24 hours", len(trades)) for _, t := range trades { log.Printf("Trade: Price=%f Amount=%f Side=%s Time=%s", t.Price, t.Amount, t.Side, t.Timestamp) } } ``` -------------------------------- ### Get Binance Account Information in Go Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/docs/ADD_NEW_EXCHANGE.md Retrieves Binance user account information using an authenticated request. It formats the symbol and sets up the necessary parameters for the authenticated HTTP request, returning the account details. ```go // GetAccount returns binance user accounts func (e *Exchange) GetAccount(ctx context.Context) (*Account, error) { type response struct { Response Account } var resp response return &resp.Account, e.SendAuthHTTPRequest(ctx, exchange.RestSpotSupplementary, http.MethodGet, accountInfo, url.Values{}, spotAccountInformationRate, &resp) } ``` -------------------------------- ### Go: Using strings.Builder for Multi-Part Path Construction Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/docs/CODING_GUIDELINES.md Illustrates the use of strings.Builder for efficient construction of multi-part strings, such as API paths. This should be used only after benchmarking with testing.B to confirm performance benefits for realistic input sizes. ```go // path construction with strings.Builder example (use after benchmarking) // var sb strings.Builder // sb.WriteString("/api/v1/") // sb.WriteString(id) // path := sb.String() ``` -------------------------------- ### Get Ticker by Exchange and Pair (Go) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/exchanges/ticker/README.md Shows how to retrieve a loaded ticker using the ticker package directly. This function is useful when you have an exchange orderbook routine already set up and need to access ticker information. ```go tick, err := ticker.GetTicker(...) if err != nil { // Handle error } ``` -------------------------------- ### Seed Default Exchange List in dbseed Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/cmd/dbseed/README.md This Go command example shows how to seed the default list of exchanges into the GoCryptoTrader database using the dbseed tool. This is a convenient way to populate known exchanges without manual input. ```bash dbseed exchange default ``` -------------------------------- ### Strategy Plugin Execution Command Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/backtester/plugins/strategies/README.md This command demonstrates how to run a custom strategy plugin with the GoCryptoTrader Backtester. It requires specifying the path to the compiled strategy plugin file using the -strategypluginpath flag. The backtester will then load and execute the strategy for all events. ```bash ./backtester -strategypluginpath="path/to/strategy/example.so" ``` -------------------------------- ### Enable Mock Testing for Exchange Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/exchanges/mock/README.md This Go code snippet sets up mock testing for an exchange by utilizing the mock package. It configures the exchange and initializes a mock HTTP client using a VCR server, redirecting requests to recorded responses. This file is compiled when the 'mock_test_off' build tag is NOT present. ```go //+build !mock_test_off // This will build if build tag mock_test_off is not parsed and will try to mock // all tests in _test.go package your_current_exchange_name import ( "os" "testing" "log" "github.com/thrasher-corp/gocryptotrader/config" "github.com/thrasher-corp/gocryptotrader/exchanges/mock" "github.com/thrasher-corp/gocryptotrader/exchanges/sharedtestvalues" ) const mockfile = "../../testdata/http_mock/your_current_exchange_name/your_current_exchange_name.json" var mockTests = true func TestMain(m *testing.M) { cfg := config.GetConfig() cfg.LoadConfig("../../testdata/configtest.json") your_current_exchange_nameConfig, err := cfg.GetExchangeConfig("your_current_exchange_name") if err != nil { log.Fatal("your_current_exchange_name Setup() init error", err) } your_current_exchange_nameConfig.API.AuthenticatedSupport = true your_current_exchange_nameConfig.API.Credentials.Key = apiKey your_current_exchange_nameConfig.API.Credentials.Secret = apiSecret s.SetDefaults() s.Setup(&your_current_exchange_nameConfig) serverDetails, newClient, err := mock.NewVCRServer(mockfile) if err != nil { log.Fatalf("Mock server error %s", err) } s.HTTPClient = newClient s.API.Endpoints.URL = serverDetails log.Printf(sharedtestvalues.MockTesting, s.Name, s.API.Endpoints.URL) os.Exit(m.Run()) } ``` -------------------------------- ### Suppress Linter with Explanation (Go) Source: https://github.com/thrasher-corp/gocryptotrader/blob/master/docs/CODING_GUIDELINES.md This Go code example shows how to sparingly use the `//nolint:linter-name` comment to suppress a specific linter warning. A clear comment explaining the reason for suppression must always accompany the `nolint` directive. ```go extension := "strat" //nolint:misspell // its shorthand for strategy ``` -------------------------------- ### Get Current and Max Leverage Source: https://context7.com/thrasher-corp/gocryptotrader/llms.txt Retrieves the current and maximum leverage allowed for a specific futures position. This function requires the exchange, asset type, and currency pair. It logs both the current and maximum leverage values. A gRPC client is necessary for this operation. ```go func GetLeverage(client gctrpc.GoCryptoTraderServiceClient) { resp, err := client.GetLeverage(context.Background(), &gctrpc.GetLeverageRequest{ Exchange: "Binance", AssetType: "usdtmarginedfutures", Pair: &gctrpc.CurrencyPair{ Base: "BTC", Quote: "USDT", }, }) if err != nil { log.Fatal(err) } log.Printf("Current Leverage: %fx", resp.Leverage) log.Printf("Max Leverage: %fx", resp.MaximumLeverage) } ```