Skip to content

Creating Strategies

Fiore edited this page Nov 5, 2018 · 3 revisions

Golang Crypto Trading Bot

Creating Strategies

In this section you will see a brief overview of the Strategy and StrategyModels implementation, to let you create your own strategies.

The StrategyModel object

Use this object to create a custom model for different strategies.

//StrategyModel represents a strategy model used by strategies.
type StrategyModel struct {
	Name     string       // The name of the strategy
	Setup    StrategyFunc // Runs at first setup of the strategy, once.
	TearDown StrategyFunc // Runs when terminating the strategy, once.
	OnUpdate StrategyFunc // Runs at every markets update. Put your logic here.
	OnError  func(error)  // Runs if any error occurs in any other function.
}

You can use it as follows:

  • in Setup pass a function which initializes the status of the strategy.
  • in TearDown pass a function which clears the used resources by the strategy.
  • in OnUpdate pass a function with your strategy logic.
  • in OnError handle all errors returned from the other functions.

The Strategy interface and implementations

This objects sets when retrieve data using strategy models:

type Strategy interface {
    // Name returns the name of the strategy, often from the StrategyModel which is binded to it.
    Name() string                       
    // Apply applies the strategy when called, using the specified wrapper.                      
    Apply([]exchanges.ExchangeWrapper, []*environment.Market) 
}

The most common implementation is the IntervalStrategy which is based on polling data (from REST or websocket cache) basing on intervals of time.

type IntervalStrategy struct {
	Model    StrategyModel // see StrategyModel section.
	Interval time.Duration // interval of time used to poll data.
}

an example of this strategy is the watchStrategy:

// Watch5Min prints out the info of the market every 5 minutes.
var Watch5Min = strategies.IntervalStrategy{
	Model: strategies.StrategyModel{
		Name: "Watch5Min",
		Setup: func(wrappers []exchanges.ExchangeWrapper, markets []*environment.Market) error {
			fmt.Println("Watch5Min starting")
			return nil
		},
		OnUpdate: func(wrappers []exchanges.ExchangeWrapper, markets []*environment.Market) error {
			_, err := wrappers[0].GetMarketSummary(markets[0]) // example call, just as an example
			if err != nil {
				return err
			}
			fmt.Println(markets) // prints info about markets
			return nil
		},
		OnError: func(err error) {
			fmt.Println(err)
		},
		TearDown: func(wrappers []exchanges.ExchangeWrapper, markets []*environment.Market) error {
			fmt.Println("Watch5Min exited")
			return nil
		},
	},
	Interval: time.Minute * 5, // Polls every 5 minutes
}