Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: add the explanation on how to read/write strategy fields #1746

Merged
merged 1 commit into from
Sep 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions doc/topics/rw-strategy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
## Print/Modify Strategy Fields

The following utility functions are commonly used in the `elliottwave` and `drift` strategies. You can refer to their implementations in `pkg/strategy` for further details.

To handle output or modification of strategy fields, BBGO offers a utility that simplifies parameter serialization, similar to how JSON fields are marshaled. This utility adopts JSON-like tag syntax with additional tags for specific behaviors.

For example:

```go
type Strategy struct {
// The Debug field will be serialized to JSON with "debug" as the key.
Debug bool `json:"debug"`
}
```

This utility is located in `github.com/c9s/bbgo/pkg/dynamic`, and the style configuration can be found in `github.com/c9s/bbgo/pkg/style`.

To output the configuration, use `dynamic.PrintConfig`, which only serializes fields that can be marshaled into JSON:

```go
import (
"io"
"github.com/c9s/bbgo/pkg/dynamic"
"github.com/c9s/bbgo/pkg/interact"
"github.com/jedib0t/go-pretty/v6/table"
)

func (s *Strategy) Print(f io.Writer, pretty bool, withColor ...bool) {
var tableStyle *table.Style
if pretty {
tableStyle = style.NewDefaultTableStyle()
}
dynamic.PrintConfig(s, f, tableStyle, len(withColor) > 0 && withColor[0], dynamic.DefaultWhiteList()...)
}
```

We can now register a command to allow users to interact with the strategy:

```go
import (
"bytes"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/interact"
)

...
bbgo.RegisterCommand("/config", "Show latest config", func(reply interact.Reply) {
var buffer bytes.Buffer
s.Print(&buffer, false)
reply.Message(buffer.String())
})
```

To dump all strategy fields, you can use `dynamic.ParamDump`. If certain fields should be excluded, simply add the `ignore: "true"` tag to the field definition.

To make fields modifiable, use the `modifiable: "true"` tag and call `bbgo.RegisterModifier(s)` to enable editing. This will automatically add `/modify` commands to the strategy.
Loading