leprechaun

package module
v0.0.0-...-1132767 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2020 License: GPL-3.0 Imports: 20 Imported by: 0

README

leprechaun-bot

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrCancelled is sent by the bot goroutine when it recieces a signal from
	// the cancel channel
	ErrCancelled = errors.New("the trading session has been cancelled")
	// ErrInvalidAPICredentials is returned for an invalid API key ID or key Secret
	ErrInvalidAPICredentials = errors.New("invalid API credentials")
	// ErrChannelsNotInitialized is returned when the UI does not instatiate all necessary channels
	ErrChannelsNotInitialized = errors.New("unable to start multiplexing. Initialize channels first")
	// ErrInvalidPurchaseUnit is returned when the user wants to buy lower than the minimum trading volume
	ErrInvalidPurchaseUnit = errors.New("the purchase amount you specified is lower than the minimum trading volume")
)

Errors

View Source
var (
	// ErrInsufficientBalance tells the user his fiat balance is low or below specfied purchase unit.
	ErrInsufficientBalance = errors.New("your fiat balance is insufficient")
	// ErrNetworkFailed represents a generic network error.
	ErrNetworkFailed = errors.New("network error. check your connection status")
	// ErrConnectionTimeout represents a connection timeout
	ErrConnectionTimeout = errors.New("your internet connection timed out")
)

Custom errors

View Source
var (
	DefaultSnoozeTimes     []int32
	DefaultSupportedAssets = []string{"XBT", "ETH", "XRP", "LTC"}
	DefaultCurrencyName    = "Naira"
	DefaultCurrencyCode    = "NGN"
)

Default vars

View Source
var ErrNoSavedSettings = errors.New("could not find any saved settings")

ErrNoSavedSettings is returned by the load settigs function when it can't find any saved settings on file.

View Source
var (

	// Logger for bot-related operations.
	Logger *log.Logger
)

Functions

func GetStats

func GetStats(asset string) (string, error)

GetStats returns the statistics for a given asset

func NewPurchase

func NewPurchase(purchase Record) error

NewPurchase adds a new purchase record to file. Only 100 most recent records are saved to file. (see the `recordStack.append` function)

func NewSale

func NewSale(asset, orderID, timestamp string, purchasePrice, purchaseVolume, salePrice, saleVolume float64) error

NewSale saves a sale's profits to record

func SetConfig

func SetConfig(cfg *Configuration)

SetConfig sets the package wide Configuration values for early access. (to be used by the UI.)

func SetLogger

func SetLogger(logger *log.Logger)

SetLogger sets the logger object specific for leprechaun's bot activities. TODO: use the slog-backend format and move this log to the main.go file or a seperate log file.

func Snooze

func Snooze() error

Snooze pauses Leprechaun's main loop for some time between each trading round

Types

type AssetStats

type AssetStats struct {
	Asset                 string
	AllTimePurchaseVolume string
	AllTimeSalesVolume    string
	AllTimeSalesCost      string
	AllTimePurchasesCost  string
	AllTimeProfit         string
}

AssetStats holds all time stats for an asset

type Bot

type Bot struct {
	// contains filtered or unexported fields
}

Bot is our trading bot

func NewBot

func NewBot() *Bot

NewBot create a new trading bot object

func (*Bot) Channels

func (bot *Bot) Channels() *Channels

Channels returns a struct holding all chans for communicating with the bot.

func (*Bot) InitChannels

func (bot *Bot) InitChannels(chans *Channels)

InitChannels sets the channels that the bot goroutine uses to communicate with the UI.

func (*Bot) Run

func (bot *Bot) Run(settings *Configuration) error

Run runs the main trading loop.

func (*Bot) Shutdown

func (bot *Bot) Shutdown()

Shutdown stops the program.

type Channels

type Channels struct {
	// Log sends messages of Leprechaun's activities from the bot to the UI.
	LogChan chan string
	// Cancel delivers a signal for Leprechaun to stop running from the user to the bot through the UI.
	CancelChan chan struct{}
	// Stopped sends a signal from the bot to the UI after it has stopped.
	// To facilitate graceful exiting.
	StoppedChan chan struct{}
	// Error is for sending bot-side errors to the UI.
	ErrorChan chan error
	// PurchaseChan channel notifies the UI that a purchase has been made so it can update its displayed records
	PurchaseChan chan struct{}
	// SaleChan channel notifies the UI that a sale has been made so it can update its displayed records.
	SaleChan chan struct{}
}

Channels for communicating with the UI.

var (
	UIChans *Channels
)

Channels

func (*Channels) BotStopped

func (c *Channels) BotStopped(channel chan struct{})

BotStopped set the cahnnel through which the bot informs the UI it has stopped.

func (*Channels) Cancel

func (c *Channels) Cancel(channel chan struct{})

Cancel sets the channel with which to stop the bot

func (*Channels) Error

func (c *Channels) Error(channel chan error)

Error sets the channel through which the bot sends error messages to the UI.

func (*Channels) Log

func (c *Channels) Log(channel chan string)

Log sets the log channel

func (*Channels) Purchase

func (c *Channels) Purchase(channel chan struct{})

Purchase sets the channel through which the bot alerts the UI to new Purchase events.

func (*Channels) Sale

func (c *Channels) Sale(channel chan struct{})

Sale sets the channel through which the bot alerts the UI to new Sale events.

type Client

type Client struct {
	Pair string
	// The client inherits all methods of `*luno.Client`
	*luno.Client
	// contains filtered or unexported fields
}

Client handles all operations for a specified currency pair. It extends `luno.Client`

func (*Client) AccountID

func (cl *Client) AccountID() (ID map[string]string, err error)

AccountID returns map[string]string{"asset":asset_account_id, "fiat":fiat_accont_id}

func (*Client) CheckBalanceSufficiency

func (cl *Client) CheckBalanceSufficiency() (canPurchase bool, err error)

CheckBalanceSufficiency determines whether the client has purchasing power

func (*Client) CheckOrder

func (cl *Client) CheckOrder(orderID string) (orderDetails luno.GetOrderResponse, err error)

CheckOrder tries to confirm if an order is still pending or not

func (*Client) ConfirmOrder

func (cl *Client) ConfirmOrder(rec *Record)

ConfirmOrder checks if an order placed on the exchange has been executed

func (*Client) CurrentPrice

func (cl *Client) CurrentPrice() (price float64, err error)

CurrentPrice retrieves the ask price for the client's asset.

func (*Client) Emit

func (cl *Client) Emit() (signal SIGNAL, err error)

Emit emits a BUY, SELL or WAIT signal based on data from `analyze()`

func (*Client) FeeInfo

func (cl *Client) FeeInfo() (info luno.GetFeeInfoResponse, err error)

FeeInfo retrieves taker/maker fee information for this client

func (*Client) PendingOrders

func (cl *Client) PendingOrders() (pendingOrders interface{})

PendingOrders retrieves unexecuted orders still in the order book.

func (*Client) PreviousPrices

func (cl *Client) PreviousPrices(num, interval int) (prices []float64, err error)

PreviousPrices retrieves historic price data from the exchange. The price is determined from executed trades `interval` minutes apart, parameter `num` specifies the number of prices to be retrieved. For example: num=10, interval=5 gets prices over the last 50 minutes.

func (*Client) Purchase

func (cl *Client) Purchase(price float64, volume float64) (rec Record, err error)

Purchase buys a specified amount of a specified asset on the exchange

func (*Client) PurchaseQuote

func (cl *Client) PurchaseQuote() (rec Record, err error)

PurchaseQuote buys an asset using the qoute technique

func (*Client) Sell

func (cl *Client) Sell(rec *Record) (sold bool)

Sell places a bid order on the excahnge to sell `volume` worth of Client.asset in exhange for fiat currency.

func (*Client) SellQuote

func (cl *Client) SellQuote()

SellQuote sells an asset using the quote technique.

func (*Client) StopPendingOrder

func (cl *Client) StopPendingOrder(orderID string) (ok bool)

StopPendingOrder tries to remove a pending order from the order book

func (Client) String

func (cl Client) String() (s string)

Returns a string representation of a Client struct

func (*Client) TopOrders

func (cl *Client) TopOrders() (orders map[string]luno.OrderBookEntry)

TopOrders retrieves the top ask and bid orders on the exchange

func (*Client) UpdateOrderDetails

func (cl *Client) UpdateOrderDetails(rec Record) (updated Record, err error)

UpdateOrderDetails updates order details

type Configuration

type Configuration struct {
	Name                 string
	SupportedAssets      []string
	ExitOnInitFailed     bool
	APIKeyID             string
	APIKeySecret         string
	PurchaseUnit         float64
	AssetsToTrade        []string
	EmailAddress         string
	ProfitMargin         float64
	LedgerDatabase       string
	SnoozeTimes          []int32
	SnoozePeriod         int32
	Verbose              bool
	AdjustedPurchaseUnit float64
	Android              bool
	CurrencyCode         string
	CurrencyName         string
	RandomSnooze         bool
	AppDir               string
	DataDir              string
	LogDir               string
	// contains filtered or unexported fields
}

Configuration object holds settings for Leprechaun.

func (*Configuration) DefaultSettings

func (c *Configuration) DefaultSettings(appDir string) error

DefaultSettings updates the Configuration struct to their default values.

func (*Configuration) ExportAPIVars

func (c *Configuration) ExportAPIVars(keyID, keySecret string) (err error)

ExportAPIVars sets the api key id and key secret environment variables

func (*Configuration) ImportAPIVars

func (c *Configuration) ImportAPIVars() (keyID, keySecret string, err error)

ImportAPIVars gets the values of the key id and key secret environment varaibles.

func (*Configuration) LoadConfig

func (c *Configuration) LoadConfig(appDir string) (err error)

LoadConfig returns previously saved settings from file. If settings have not been saved it returns an error.

func (*Configuration) Save

func (c *Configuration) Save() error

Save the config struct to a json file.

func (*Configuration) SetAppDir

func (c *Configuration) SetAppDir(dir string)

SetAppDir uses the platform-aware values from `gioui.org/app`

func (*Configuration) TestConfig

func (c *Configuration) TestConfig(appDir string) error

TestConfig is my custom settings for testing purposes.

func (*Configuration) Update

func (c *Configuration) Update(copy *Configuration, isDefault bool) (err error)

Update the config struct with user defined values and disregard invalid values

type Ledger

type Ledger struct {
	// contains filtered or unexported fields
}

Ledger object stores records of purchased assets in a sql database.

func NewLedger

func NewLedger() (l *Ledger)

NewLedger creates a new ledger object

func (*Ledger) AddRecord

func (l *Ledger) AddRecord(rec Record) (err error)

AddRecord adds a `Record` to the database.

func (*Ledger) AllRecords

func (l *Ledger) AllRecords() (records []Record, err error)

AllRecords returns all purchase records stored in the ledger.

func (*Ledger) GetRecordByID

func (l *Ledger) GetRecordByID(id string) (rec Record, err error)

GetRecordByID returns a record from the database with the `id` provided.

func (*Ledger) Save

func (l *Ledger) Save() (err error)

Save closese the database. Must be called by any external user of the ledger.

func (*Ledger) ViableRecords

func (l *Ledger) ViableRecords(asset string, price float64) (records []Record, err error)

ViableRecords checks the database for any records whose prices are lower (beyond a certain `margin`) than the value of `price`.

type PricePosition

type PricePosition struct {
	// contains filtered or unexported fields
}

PricePosition indicates whether the current price is above or below the moving average.

type Record

type Record struct {
	Asset     string
	Cost      float64
	ID        string
	Price     float64
	SaleID    string
	Sold      bool
	Status    string
	Timestamp string
	Volume    float64
}

Record holds details of an asset sale or purchase

func GetPurchases

func GetPurchases() ([]Record, error)

GetPurchases returns a list of past asset purchases made by leprechaun.

func NewRecord

func NewRecord(asset string, price float64, timestamp string,
	volume float64, id string) (rec Record)

NewRecord creates a new `Record` object

func (Record) String

func (rec Record) String() string

type RecordStack

type RecordStack struct {
	// contains filtered or unexported fields
}

RecordStack holds a FIFO stack of at most 100 `Record` elements.

type SIGNAL

type SIGNAL string

SIGNAL are signals emited by the Emit function that tell the bot what to do

var (
	// WaitSignal tells Leprechaun to wait
	WaitSignal SIGNAL = "WAIT"
	// BuySignal tells Leprechaun to wait
	BuySignal SIGNAL = "BUY"
	// SellSignal tells Leprechaun to wait
	SellSignal SIGNAL = "SELL"
)

type SaleEntry

type SaleEntry struct {
	Asset          string
	OrderID        string
	Timestamp      string
	PurchasePrice  float64
	PurchaseVolume float64
	PurchaseCost   float64
	SalePrice      float64
	SaleVolume     float64
	SaleCost       float64
	Profit         float64
}

SaleEntry records the profit made from the sale of an asset

func GetSales

func GetSales() (records []*SaleEntry, err error)

GetSales returns historical records that have been saved to file.

func (*SaleEntry) String

func (entry *SaleEntry) String() string

type SaleRecordStack

type SaleRecordStack struct {
	// contains filtered or unexported fields
}

SaleRecordStack holds a FIFO stack of at most 100 `SaleEntry` elements.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL