gominitrader

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2023 License: BSD-2-Clause Imports: 17 Imported by: 0

README

GPT3 Forex Trader Bot

Version Go

This bot is a forex trading solution that uses strategies generated by GPT3 to trade the markets. It currently utilizes Capital.com as its main broker. The bot is built with Golang, utilizing a concurrent implementation to maximize efficiency. Utilizes GPT generated strategies for trading decisions Concurrent implementation for maximum efficiency Uses Capital.com as the main broker

Example Usage

package main

import (
	"log"
	"os"

	gominitrader "github.com/menesesghz/go-minitrader"
)

func main() {
	capitalClient, err := gominitrader.NewCapitalClient("your@email.com", "<API_TOKEN>", "<API_TOKEN_PASSWORD>", true)
	if err != nil {
		log.Fatal(err)
	}

	// Trade the USD/JPY currency pair with a 2% stop loss and a 0.35% upperbound profit target using 15-minute intervals and the GPTStrategy.
	minitraderUSDJPY := gominitrader.NewMinitrader(
		"USDJPY", 25, 2, 0.35, gominitrader.MINUTE_15, gominitrader.GPTStrategy,
	)

	// Trade the USD/CAD currency pair with a 2% stop loss and a 0.35% upperbound profit target using 15-minute intervals and the GPTStrategy.
	minitraderUSDCAD := gominitrader.NewMinitrader(
		"USDCAD", 25, 2, 0.35, gominitrader.MINUTE_15, gominitrader.GPTShortTermStrategy,
	)

	// Trade the USD/MXN currency pair with a 2% stop loss and a 0.35% upperbound profit target using 15-minute intervals and the GPTShortTermStrategy.
	minitraderUSDMXN := gominitrader.NewMinitrader(
		"USDMXN", 50, 2, 0.35, gominitrader.MINUTE_15, gominitrader.GPTShortTermStrategy,
	)

	minitraderPool, _ := gominitrader.NewMinitraderPool(capitalClient, minitraderUSDJPY, minitraderUSDCAD, minitraderUSDMXN)
	minitraderPool.Start()
}

The previous code is a main Go program that trades forex using the go-minitrader package. It establishes a new client connection to Capital.com, which serves as the designated broker for the bot's trades.

Then, it sets up three different instances of the minitrader for the currency pairs USD/JPY, USD/CAD, and USD/MXN with the same stop loss (2%) and upperbound profit target (0.35%), but with different trade sizes (25 for USD/JPY, 50 for USD/MXN, and default of 25 for USD/CAD) and different strategies (GPTStrategy for USD/JPY, GPTShortTermStrategy for USD/CAD and USD/MXN).

Finally, the program creates a new pool of minitraders, adds the three instances to it and starts the trading process by calling the Start() method.

Features To Be Implemented

  1. Backtesting Engine: The aim of this feature is to develop a backtesting engine that would allow testing the performance of the trading strategies before applying them on real trades.

  2. Telegram Bot Integration: This feature aims to integrate the trading bot with the Telegram Bot API to allow for easy monitoring and control of trades.

  3. Pull Historical Data from Trading View: To improve the performance of the trading strategies, it is necessary to access a larger data set. This feature aims to pull historical data from Trading View, which has a higher data limit compared to Capital.com API's limit of 10 requests per second.

Note

It is important to underline that this is a alpha version, all the strategies haven't been backtested. Only trade with funds that you can afford to lose. This bot is provided as-is and no guarantees or warranties are made regarding its performance. Use at your own risk.

Documentation

Overview

GPT Response: Sure, here's an example of a short-term trading strategy that uses Moving Averages to make buy and sell decisions:

{... CODE ...}

This strategy makes use of two moving averages with different time frames, 20 and 50 candles, to determine the trend of the market. If the short-term moving average crosses above the long-term moving average, it signals a buy opportunity. If the short-term moving average crosses below the long-term moving average, it signals a sell opportunity.

Index

Constants

View Source
const CAPITAL_DEBUG_DOMAIN_NAME = "https://demo-api-capital.backend-capital.com"
View Source
const CAPITAL_DOMAIN_NAME = "https://api-capital.backend-capital.com"

Variables

View Source
var TimeframeMinuteMap = map[Timeframe]int{
	MINUTE:    1,
	MINUTE_5:  5,
	MINUTE_15: 15,
	MINUTE_30: 30,
	HOUR:      60,
	HOUR_4:    240,
	DAY:       1440,
	WEEK:      10080,
}

Functions

This section is empty.

Types

type AccountResponse

type AccountResponse struct {
	AccountID   string `json:"accountId"`
	AccountName string `json:"accountName"`
	Status      string `json:"status"`
	AccountType string `json:"accountType"`
	Preferred   bool   `json:"preferred"`
	Balance     struct {
		Balance    float64 `json:"balance"`    // maps to Equity
		Deposit    float64 `json:"deposit"`    // maps to Funds
		ProfitLoss float64 `json:"profitLoss"` // maps to P&L
		Available  float64 `json:"available"`  // maps to Available
	} `json:"balance"`
	Currency string `json:"currency"`
}

type AccountsResponse

type AccountsResponse struct {
	Accounts []AccountResponse `json:"accounts"`
}

type AuthenticationTransport

type AuthenticationTransport struct {
	http.RoundTripper
	X_SECURITY_TOKEN string
	CST              string
}

func (*AuthenticationTransport) RoundTrip

func (t *AuthenticationTransport) RoundTrip(req *http.Request) (*http.Response, error)

type BidAskPrice

type BidAskPrice struct {
	Bid float64
	Ask float64
}

type Candle

type Candle struct {
	Volume    int64
	Timestamp int64
	Open      BidAskPrice
	High      BidAskPrice
	Low       BidAskPrice
	Close     BidAskPrice
}

type Candles

type Candles []Candle

func (*Candles) MarshalCapitalPrices

func (candles *Candles) MarshalCapitalPrices(capitalPrices []CapitalPrice) error

type CapitalClientAPI

type CapitalClientAPI struct {
	CAPITAL_EMAIL            string
	CAPITAL_API_KEY          string
	CAPITAL_API_KEY_PASSWORD string
	CapitalDomainName        string
	HttpClient               *http.Client
}

func NewCapitalClient

func NewCapitalClient(capitalEmail string, capitalApiKey string, capitalApiKeyPassword string, debug bool) (client *CapitalClientAPI, err error)

func (*CapitalClientAPI) CreateNewSession

func (capClient *CapitalClientAPI) CreateNewSession() (newSessionResponse NewSessionResponse, headerTokens http.Header, err error)

func (*CapitalClientAPI) CreateWorkingOrder

func (capClient *CapitalClientAPI) CreateWorkingOrder(epic string, direction Signal, orderType OrderType, targetPrice float64, orderSize float64) (createWorkingOrder WorkingOrderResponse, err error)

func (*CapitalClientAPI) DeleteWorkingOrder

func (capClient *CapitalClientAPI) DeleteWorkingOrder(dealReference string) (deleteWorkingResponse WorkingOrderResponse, err error)

func (*CapitalClientAPI) GetAllAccounts

func (capClient *CapitalClientAPI) GetAllAccounts() (AccountsResponse, error)

func (*CapitalClientAPI) GetAllWorkingOrders

func (capClient *CapitalClientAPI) GetAllWorkingOrders() (workingOrdersResponse WorkingOrdersResponse, err error)

func (*CapitalClientAPI) GetEncriptionKey

func (capClient *CapitalClientAPI) GetEncriptionKey() (EncriptionResponse, error)

func (*CapitalClientAPI) GetEncryptedPassword

func (capClient *CapitalClientAPI) GetEncryptedPassword(encriptionResponse EncriptionResponse) (string, error)

func (*CapitalClientAPI) GetHistoricalPrices

func (capClient *CapitalClientAPI) GetHistoricalPrices(epic string, resolution Timeframe, numberOfCandles int) (pricesResponse PricesResponse, err error)

func (*CapitalClientAPI) GetMarketsDetails

func (capClient *CapitalClientAPI) GetMarketsDetails(epics []string) (MarketsDetailsResponse, error)

func (*CapitalClientAPI) GetPositionOrderConfirmation

func (capClient *CapitalClientAPI) GetPositionOrderConfirmation(dealReference string) (confirmation PositionOrderConfirmationResponse, err error)

func (*CapitalClientAPI) GetPositions

func (capClient *CapitalClientAPI) GetPositions() (positionsResponse PositionsResponse, err error)

func (*CapitalClientAPI) GetPreferredAccount

func (capClient *CapitalClientAPI) GetPreferredAccount() (AccountResponse, error)

func (*CapitalClientAPI) GetWatchLists

func (capClient *CapitalClientAPI) GetWatchLists() (WatchListsResponse, error)

type CapitalClientUnathenticated

type CapitalClientUnathenticated struct{}

func (*CapitalClientUnathenticated) Error

func (err *CapitalClientUnathenticated) Error() string

type CapitalPrice

type CapitalPrice struct {
	SnapshotTime    string `json:"snapshotTime"`
	SnapshotTimeUTC string `json:"snapshotTimeUTC"`
	OpenPrice       struct {
		Bid float64 `json:"bid"`
		Ask float64 `json:"ask"`
	} `json:"openPrice"`
	ClosePrice struct {
		Bid float64 `json:"bid"`
		Ask float64 `json:"ask"`
	} `json:"closePrice"`
	HighPrice struct {
		Bid float64 `json:"bid"`
		Ask float64 `json:"ask"`
	} `json:"highPrice"`
	LowPrice struct {
		Bid float64 `json:"bid"`
		Ask float64 `json:"ask"`
	} `json:"lowPrice"`
	LastTradedVolume int `json:"lastTradedVolume"`
}

type ConfirmationStatus

type ConfirmationStatus string
const (
	DELETED ConfirmationStatus = "DELETED"
)

type CreateWorkingOrderBody

type CreateWorkingOrderBody struct {
	Epic      string    `json:"epic"`
	Direction Signal    `json:"direction"`
	Type      OrderType `json:"type"`
	Size      float64   `json:"size"`
	Level     float64   `json:"level"`
}

type EncriptionResponse

type EncriptionResponse struct {
	EncryptionKey string `json: "encryptionKey"`
	TimeStamp     int    `json: "timeStamp"`
}

type MarketsDetailsResponse

type MarketsDetailsResponse struct {
	MarketDetails []struct {
		Instrument struct {
			Epic                     string  `json:"epic"`
			Expiry                   string  `json:"expiry"`
			Name                     string  `json:"name"`
			LotSize                  int     `json:"lotSize"`
			Type                     string  `json:"type"`
			GuaranteedStopAllowed    bool    `json:"guaranteedStopAllowed"`
			StreamingPricesAvailable bool    `json:"streamingPricesAvailable"`
			Currency                 string  `json:"currency"`
			MarginFactor             float64 `json:"marginFactor"`
			MarginFactorUnit         string  `json:"marginFactorUnit"`
			OpeningHours             string  `json:"openingHours"`
			Country                  string  `json:"country"`
		} `json:"instrument"`
		DealingRules struct {
			MinStepDistance struct {
				Unit  string  `json:"unit"`
				Value float64 `json:"value"`
			} `json:"minStepDistance"`
			MinDealSize struct {
				Unit  string  `json:"unit"`
				Value float64 `json:"value"`
			} `json:"minDealSize"`
			MaxDealSize struct {
				Unit  string  `json:"unit"`
				Value float64 `json:"value"`
			} `json:"maxDealSize"`
			MinSizeIncrement struct {
				Unit  string  `json:"unit"`
				Value float64 `json:"value"`
			} `json:"minSizeIncrement"`
			MinGuaranteedStopDistance struct {
				Unit  string  `json:"unit"`
				Value float64 `json:"value"`
			} `json:"minGuaranteedStopDistance"`
			MinStopOrProfitDistance struct {
				Unit  string  `json:"unit"`
				Value float64 `json:"value"`
			} `json:"minStopOrProfitDistance"`
			MaxStopOrProfitDistance struct {
				Unit  string  `json:"unit"`
				Value float64 `json:"value"`
			} `json:"maxStopOrProfitDistance"`
			MarketOrderPreference   string `json:"marketOrderPreference"`
			TrailingStopsPreference string `json:"trailingStopsPreference"`
		} `json:"dealingRules"`
		Snapshot struct {
			MarketStatus        string  `json:"marketStatus"`
			UpdateTime          string  `json:"updateTime"`
			DelayTime           int     `json:"delayTime"`
			Bid                 float64 `json:"bid"`
			Offer               float64 `json:"offer"`
			DecimalPlacesFactor int     `json:"decimalPlacesFactor"`
			ScalingFactor       int     `json:"scalingFactor"`
		} `json:"snapshot"`
	} `json:"marketDetails"`
}

type Minitrader

type Minitrader struct {
	Epic                 string
	Timeframe            Timeframe
	Status               MinitraderStatus
	MarketStatus         MinitraderMarketStatus
	Strategy             Strategy
	InvestmentPercentage float64
	StopLossPercentage   float64
	ProfitPercentage     float64
	// contains filtered or unexported fields
}

func NewMinitrader

func NewMinitrader(epic string, investmentPercentage float64, stopLossPercentage float64, profitPercentage float64, timeframe Timeframe, strategy Strategy) *Minitrader

func (*Minitrader) Effect

func (minitrader *Minitrader) Effect(signal Signal, price float64) error

func (*Minitrader) Start

func (minitrader *Minitrader) Start(waitGroup *sync.WaitGroup)

type MinitraderMarketStatus

type MinitraderMarketStatus string
const (
	TRADEABLE MinitraderMarketStatus = "TRADEABLE"
	CLOSED    MinitraderMarketStatus = "CLOSED"
)

type MinitraderPool

type MinitraderPool struct {
	Minitraders   []*Minitrader
	CapitalClient *CapitalClientAPI
	// contains filtered or unexported fields
}

func NewMinitraderPool

func NewMinitraderPool(capitalClient *CapitalClientAPI, minitraders ...*Minitrader) (*MinitraderPool, error)

func (*MinitraderPool) AuthenticateSession

func (pool *MinitraderPool) AuthenticateSession(sleepTime time.Duration)

func (*MinitraderPool) Pulse

func (pool *MinitraderPool) Pulse()

func (*MinitraderPool) Start

func (pool *MinitraderPool) Start()

func (*MinitraderPool) UpdateMarketStatus

func (pool *MinitraderPool) UpdateMarketStatus(sleepTime time.Duration)

func (*MinitraderPool) UpdateMinitradersData

func (pool *MinitraderPool) UpdateMinitradersData(sleepTime time.Duration)

type MinitraderStatus

type MinitraderStatus string
const (
	// healthy statuses
	NEW               MinitraderStatus = "NEW"
	RUNNING           MinitraderStatus = "RUNNING"
	HOLDING           MinitraderStatus = "HOLDING"
	SELL_ORDER_ACTIVE MinitraderStatus = "SELL_ORDER_ACTIVE"
	BUY_ORDER_ACTIVE  MinitraderStatus = "BUY_ORDER_ACTIVE"

	// error statuses
	ERROR_ON_UPDATE_CANDLES_DATA MinitraderStatus = "ERROR_ON_UPDATE_CANDLES_DATA"
	ERROR_ON_MAKING_ORDER        MinitraderStatus = "ERROR_ON_MAKING_ORDER"
	ERROR_ON_DELETING_ORDER      MinitraderStatus = "ERROR_ON_DELETING_ORDER"
)

type NewSessionBody

type NewSessionBody struct {
	Identifier        string `json:"identifier"`
	Password          string `json:"password"`
	EncryptedPassword bool   `json:"encryptedPassword"`
}

type NewSessionResponse

type NewSessionResponse struct {
	AccountType           string `json:"accountType"`
	CurrencyIsoCode       string `json:"currencyIsoCode"`
	CurrencySymbol        string `json:"currencySymbol"`
	CurrentAccountId      string `json:"currentAccountId"`
	StreamingHost         string `json:"streamingHost"`
	ClientId              string `json:"clientId"`
	TimezoneOffset        int    `json:"timezoneOffset"`
	HasActiveDemoAccounts bool   `json:"hasActiveDemoAccounts"`
	HasActiveLiveAccounts bool   `json:"hasActiveLiveAccounts"`
	TrailingStopsEnabled  bool   `json:"trailingStopsEnabled"`
	Accounts              []struct {
		AccountId   string `json:"accountId"`
		AccountName string `json:"accountName"`
		Preferred   bool   `json:"preferred"`
		AccountType string `json:"accountType"`
	} `json:"accounts"`
	AccountInfo struct {
		Balance    float64 `json:"balance"`
		Deposit    float64 `json:"deposit"`
		ProfitLoss float64 `json:"profitLoss"`
		Available  float64 `json:"available"`
	} `json:"accountInfo"`
}

type OrderType

type OrderType string
const (
	LIMIT OrderType = "LIMIT"
	STOP  OrderType = "STOP"
)

type PositionOrderConfirmationResponse

type PositionOrderConfirmationResponse struct {
	Date          string `json:"date"`
	Status        string `json:"status"`
	Reason        string `json:"reason"`
	DealStatus    string `json:"dealStatus"`
	Epic          string `json:"epic"`
	DealRef       string `json:"dealReference"`
	DealID        string `json:"dealId"`
	AffectedDeals []struct {
		ID     string `json:"dealId"`
		Status string `json:"status"`
	} `json:"affectedDeals"`
	Level          float64 `json:"level"`
	Size           float64 `json:"size"` // maps to QTY (quantity)
	Direction      string  `json:"direction"`
	GuaranteedStop bool    `json:"guaranteedStop"`
	TrailingStop   bool    `json:"trailingStop"`
}

type PositionsResponse

type PositionsResponse struct {
	Positions []struct {
		Position struct {
			ContractSize   int       `json:"contractSize"`
			CreatedDate    time.Time `json:"createdDate"`
			CreatedDateUTC time.Time `json:"createdDateUTC"`
			DealID         string    `json:"dealId"`
			DealReference  string    `json:"dealReference"`
			Size           int       `json:"size"`
			Direction      string    `json:"direction"`
			Level          float64   `json:"level"`
			Currency       string    `json:"currency"`
			GuaranteedStop bool      `json:"guaranteedStop,omitempty"`
			ControlledRisk bool      `json:"controlledRisk,omitempty"`
		} `json:"position"`
		Market struct {
			InstrumentName       string    `json:"instrumentName"`
			Expiry               string    `json:"expiry"`
			MarketStatus         string    `json:"marketStatus"`
			Epic                 string    `json:"epic"`
			InstrumentType       string    `json:"instrumentType"`
			LotSize              int       `json:"lotSize"`
			High                 float64   `json:"high"`
			Low                  float64   `json:"low"`
			PercentageChange     float64   `json:"percentageChange"`
			NetChange            float64   `json:"netChange"`
			Bid                  float64   `json:"bid"`
			Offer                float64   `json:"offer"`
			UpdateTime           time.Time `json:"updateTime"`
			UpdateTimeUTC        time.Time `json:"updateTimeUTC"`
			DelayTime            int       `json:"delayTime"`
			StreamingPricesAvail bool      `json:"streamingPricesAvailable"`
			ScalingFactor        int       `json:"scalingFactor"`
		} `json:"market"`
	} `json:"positions"`
}

type PricesResponse

type PricesResponse struct {
	Prices []CapitalPrice
}

type Signal

type Signal string
const (
	BUY  Signal = "BUY"
	SELL Signal = "SELL"
	NONE Signal = "NONE"
)

func GPTShortTermStrategy

func GPTShortTermStrategy(candles Candles) (Signal, float64)

func GPTStrategy

func GPTStrategy(candles Candles) (Signal, float64)

type Strategy

type Strategy func(candles Candles) (Signal, float64)

type Timeframe

type Timeframe string
const (
	MINUTE    Timeframe = "MINUTE"
	MINUTE_5  Timeframe = "MINUTE_5"
	MINUTE_15 Timeframe = "MINUTE_15"
	MINUTE_30 Timeframe = "MINUTE_30"
	HOUR      Timeframe = "HOUR"
	HOUR_4    Timeframe = "HOUR_4"
	DAY       Timeframe = "DAY"
	WEEK      Timeframe = "WEEK"
)

type WatchListsResponse

type WatchListsResponse struct {
	Epics []string `json: "epics"`
	Name  string   `json: "name"`
}

type WorkingOrderResponse

type WorkingOrderResponse struct {
	DealReference string `json:"dealReference"`
}

type WorkingOrdersResponse

type WorkingOrdersResponse struct {
	WorkingOrders []struct {
		WorkingOrderData struct {
			DealID          string  `json:"dealId"`
			Direction       string  `json:"direction"`
			Epic            string  `json:"epic"`
			OrderSize       int     `json:"orderSize"`
			OrderLevel      int     `json:"orderLevel"`
			TimeInForce     string  `json:"timeInForce"`
			GoodTillDate    string  `json:"goodTillDate"`
			GoodTillDateUTC string  `json:"goodTillDateUTC"`
			CreatedDate     string  `json:"createdDate"`
			CreatedDateUTC  string  `json:"createdDateUTC"`
			GuaranteedStop  bool    `json:"guaranteedStop"`
			OrderType       string  `json:"orderType"`
			StopDistance    float64 `json:"stopDistance"`
			ProfitDistance  float64 `json:"profitDistance"`
			CurrencyCode    string  `json:"currencyCode"`
		} `json:"workingOrderData"`
		MarketData struct {
			InstrumentName           string  `json:"instrumentName"`
			Expiry                   string  `json:"expiry"`
			MarketStatus             string  `json:"marketStatus"`
			Epic                     string  `json:"epic"`
			InstrumentType           string  `json:"instrumentType"`
			LotSize                  int     `json:"lotSize"`
			High                     float64 `json:"high"`
			Low                      float64 `json:"low"`
			PercentageChange         float64 `json:"percentageChange"`
			NetChange                float64 `json:"netChange"`
			Bid                      float64 `json:"bid"`
			Offer                    float64 `json:"offer"`
			UpdateTime               string  `json:"updateTime"`
			UpdateTimeUTC            string  `json:"updateTimeUTC"`
			DelayTime                int     `json:"delayTime"`
			StreamingPricesAvailable bool    `json:"streamingPricesAvailable"`
			ScalingFactor            int     `json:"scalingFactor"`
		} `json:"marketData"`
	} `json:"workingOrders"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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