Help us shape the future of Go! Take the 2026 Go Developer Survey

projectx

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 16 Imported by: 2

README

projectx-api

Unofficial Go client for the ProjectX Gateway API.

Install

go get github.com/ryanrmg/projectx-api

Example

Basic

client := NewProjectXClient(
	"https://api.topstepx.com/api",
	"rtc.topstepx.com/hubs/",
	"username",
	"api-key",
)

accounts, err := client.Accounts.Search(
	ctx,
	AccountSearchRequest{OnlyActiveAccounts: true},
)

bars, err := client.Markets.History(
	ctx,
	BarHistoryRequest{
		ContractId:        "CON.F.US.MNQ.M26",
		Live:              false,
		EndTime:           time.Now().UTC().Format(time.RFC3339),
		StartTime:         time.Now().UTC().Add(-time.Duration(24*5) * time.Hour).Format(time.RFC3339),
		Unit:              2,
		UnitNumber:        5,
		Limit:             100,
		IncludePartialBar: false,
	},
)

contracts, err := client.Markets.AvailableContracts(
	ctx,
	AvailableContractRequest{Live: true},
)

Real Time

	// connect
	if err := client.Realtime.Connect(ctx); err != nil {
		t.Fatalf("connect error: %v", err)
	}

	// subscribe
	contract := "CON.F.US.MNQ.M26"
	if err := client.Realtime.SubscribeContractTrades(contract); err != nil {
		t.Fatalf("subscribe error: %v", err)
	}

	t.Log("subscribed — waiting for trade message...")

	trades := client.Realtime.TradesStream()

	for {
		select {

		case msg := <-trades:
			// do something with your message

	}

Environment

environment.sh

export PROJECTX_USERNAME=<your username>
export PROJECTX_API_KEY=<your apikey>

It is suggested to add these environment variables to a script and

$ source environment.sh

Documentation

Index

Constants

View Source
const (
	Bid   = 0
	Ask   = 1
	Https = "https://"
	Wss   = "wss://"

	CHAN_SIZE = 100
)
View Source
const (
	RecordSep = 0x1E
)

Variables

This section is empty.

Functions

func GatewayDepthCSVHeader added in v0.0.5

func GatewayDepthCSVHeader() string

func GatewayQuoteCSVHeader added in v0.0.5

func GatewayQuoteCSVHeader() string

func GatewayTradeCSVHeader added in v0.0.5

func GatewayTradeCSVHeader() string

func GatewayUserAccountCSVHeader added in v0.0.5

func GatewayUserAccountCSVHeader() string

func GatewayUserOrderCSVHeader added in v0.0.5

func GatewayUserOrderCSVHeader() string

func GatewayUserPositionCSVHeader added in v0.0.5

func GatewayUserPositionCSVHeader() string

func GatewayUserTradeCSVHeader added in v0.0.5

func GatewayUserTradeCSVHeader() string

func GetWsConn

func GetWsConn(negotiateUrl, wsUrl, token string) (net.Conn, error)

func ReadFullText

func ReadFullText(conn net.Conn) ([]byte, error)

readText reads a FULL text message (handles fragmentation)

func WriteTextFrame

func WriteTextFrame(conn net.Conn, payload []byte) error

send a masked text frame

Types

type APIError

type APIError struct {
	StatusCode int
	Body       string
}

func (*APIError) Error

func (e *APIError) Error() string

type Account

type Account struct {
	Id        int     `json:"id"`
	Name      string  `json:"name"`
	Balance   float64 `json:"balance"`
	CanTrade  bool    `json:"canTrade"`
	IsVisible bool    `json:"isVisible"`
}

type AccountResponse

type AccountResponse struct {
	Accounts     []Account `json:"accounts"`
	Success      bool      `json:"success"`
	ErrorCode    int       `json:"errorCode"`
	ErrorMessage string    `json:"errorMessage"`
}

type AccountSearchRequest

type AccountSearchRequest struct {
	OnlyActiveAccounts bool `json:"onlyActiveAccounts"`
}

type AccountService

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

func (*AccountService) Search

type AvailableContractRequest

type AvailableContractRequest struct {
	Live bool `json:"live"`
}

type AvailableContractResponse

type AvailableContractResponse struct {
	Contracts    []Contract `json:"contracts"`
	Success      bool       `json:"success"`
	ErrorCode    int        `json:"errorCode"`
	ErrorMessage string     `json:"errorMessage"`
}

type Bar

type Bar struct {
	Timestamp string  `json:"t"`
	Open      float64 `json:"o"`
	High      float64 `json:"h"`
	Low       float64 `json:"l"`
	Close     float64 `json:"c"`
	Volume    int64   `json:"v"`
}

type BarHistoryRequest

type BarHistoryRequest struct {
	ContractId        string `json:"contractId"`
	Live              bool   `json:"live"`
	StartTime         string `json:"startTime"`
	EndTime           string `json:"endTime"`
	Unit              int    `json:"unit"`       // second, minute, hour, day, week, month
	UnitNumber        int    `json:"unitNumber"` // number of units to aggregate
	Limit             int    `json:"limit"`
	IncludePartialBar bool   `json:"includePartialBar"`
}

type BasicOrderResponse

type BasicOrderResponse struct {
	Success      bool   `json:"success"`
	ErrorCode    int    `json:"errorCode"`
	ErrorMessage string `json:"errorMessage"`
}

type BasicPositionResponse

type BasicPositionResponse struct {
	Success      bool   `json:"success"`
	ErrorCode    int    `json:"errorCode"`
	ErrorMessage string `json:"errorMessage"`
}

type Bracket

type Bracket struct {
	Ticks int `json:"ticks"`
	Type  int `json:"type"`
}

type CancelOrderRequest

type CancelOrderRequest struct {
	AccountId int `json:"accountId"`
	OrderId   int `json:"orderId"`
}

type CloseContractRequest

type CloseContractRequest struct {
	AccountId  int    `json:"accountId"`
	ContractId string `json:"contractId"`
}

type Contract

type Contract struct {
	Id             string  `json:"id"`
	Name           string  `json:"name"`
	Description    string  `json:"description"`
	TickSize       float64 `json:"tickSize"`
	TickValue      float64 `json:"tickValue"`
	ActiveContract bool    `json:"activeContract"`
	SymbolId       string  `json:"symbolId"`
}

type GatewayDepth added in v0.0.5

type GatewayDepth struct {
	Timestamp     string  `json:"timestamp"`
	Type          int     `json:"type"`
	Price         float64 `json:"price"`
	Volume        int64   `json:"volume"`
	CurrentVolume int64   `json:"currentVolume"`
}

func (GatewayDepth) String added in v0.0.5

func (d GatewayDepth) String() string

func (GatewayDepth) ToCSVRow added in v0.0.5

func (d GatewayDepth) ToCSVRow() string

type GatewayQuote added in v0.0.5

type GatewayQuote struct {
	Symbol        string  `json:"symbol"`
	SymbolName    string  `json:"symbolName,omitempty"`
	LastPrice     float64 `json:"lastPrice,omitempty"`
	BestBid       float64 `json:"bestBid,omitempty"`
	BestAsk       float64 `json:"bestAsk,omitempty"`
	Change        float64 `json:"change,omitempty"`
	ChangePercent float64 `json:"changePercent,omitempty"`
	Open          float64 `json:"open,omitempty"`
	High          float64 `json:"high,omitempty"`
	Low           float64 `json:"low,omitempty"`
	Volume        int64   `json:"volume,omitempty"`
	LastUpdated   string  `json:"lastUpdated"`
	Timestamp     string  `json:"timestamp"`
}

func (GatewayQuote) String added in v0.0.5

func (q GatewayQuote) String() string

func (GatewayQuote) ToCSVRow added in v0.0.5

func (q GatewayQuote) ToCSVRow() string

type GatewayTrade

type GatewayTrade struct {
	SymbolId  string  `json:"symbolId"`
	Price     float64 `json:"price"`
	Timestamp string  `json:"timestamp"`
	Type      int     `json:"type"`
	Volume    int64   `json:"volume"`
}

func (GatewayTrade) String added in v0.0.5

func (t GatewayTrade) String() string

func (GatewayTrade) ToCSVRow added in v0.0.5

func (t GatewayTrade) ToCSVRow() string

type GatewayUserAccount added in v0.0.5

type GatewayUserAccount struct {
	Id        int     `json:"id"`
	Name      string  `json:"name"`
	Balance   float64 `json:"balance"`
	CanTrade  bool    `json:"canTrade"`
	IsVisible bool    `json:"isVisible"`
	Simulated bool    `json:"Simulated"`
}

func (GatewayUserAccount) String added in v0.0.5

func (a GatewayUserAccount) String() string

func (GatewayUserAccount) ToCSVRow added in v0.0.5

func (a GatewayUserAccount) ToCSVRow() string

type GatewayUserOrder added in v0.0.5

type GatewayUserOrder struct {
	Id                int     `json:"id"`
	AccountId         int     `json:"accountId"`
	ContractId        string  `json:"contractId"`
	SymbolId          string  `json:"symbolId"`
	CreationTimestamp string  `json:"creationTimestamp"`
	UpdateTimestamp   string  `json:"updateTimestamp"`
	Status            int     `json:"status"`
	Type              int     `json:"type"`
	Side              int     `json:"side"`
	Size              int     `json:"size"`
	LimitPrice        float64 `json:"limitPrice"`
	StopPrice         float64 `json:"stopPrice"`
	FillVolume        int     `json:"fillVolume"`
	FilledPrice       float64 `json:"filledPrice"`
	CustomTag         string  `json:"customTag"`
}

func (GatewayUserOrder) String added in v0.0.5

func (o GatewayUserOrder) String() string

func (GatewayUserOrder) ToCSVRow added in v0.0.5

func (o GatewayUserOrder) ToCSVRow() string

type GatewayUserPosition added in v0.0.5

type GatewayUserPosition struct {
	Id                int     `json:"id"`
	AccountId         int     `json:"accountId"`
	ContractId        string  `json:"contractId"`
	CreationTimestamp string  `json:"creationTimestamp"`
	Type              int     `json:"type"`
	Size              int     `json:"size"`
	AveragePrice      float64 `json:"averagePrice"`
}

func (GatewayUserPosition) String added in v0.0.5

func (p GatewayUserPosition) String() string

func (GatewayUserPosition) ToCSVRow added in v0.0.5

func (p GatewayUserPosition) ToCSVRow() string

type GatewayUserTrade added in v0.0.5

type GatewayUserTrade struct {
	Id                int     `json:"id"`
	AccountId         int     `json:"accountId"`
	ContractId        string  `json:"contractId"`
	CreationTimestamp string  `json:"creationTimestamp"`
	Price             float64 `json:"price"`
	ProfitAndLoss     float64 `json:"profitAndLoss"`
	Fees              float64 `json:"fees"`
	Side              int     `json:"side"`
	Size              int     `json:"size"`
	Voided            bool    `json:"voided"`
	OrderId           int     `json:"orderId"`
}

func (GatewayUserTrade) String added in v0.0.5

func (t GatewayUserTrade) String() string

func (GatewayUserTrade) ToCSVRow added in v0.0.5

func (t GatewayUserTrade) ToCSVRow() string

type HistoryResponse

type HistoryResponse struct {
	Bars         []Bar  `json:"bars"`
	Success      bool   `json:"success"`
	ErrorCode    int    `json:"errorCode"`
	ErrorMessage string `json:"errorMessage"`
}

type MarketService

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

func (*MarketService) AvailableContracts

func (s *MarketService) AvailableContracts(ctx context.Context, req AvailableContractRequest) ([]Contract, error)

func (*MarketService) History

func (s *MarketService) History(ctx context.Context, req BarHistoryRequest) ([]Bar, error)

func (*MarketService) SearchContractById

func (s *MarketService) SearchContractById(ctx context.Context, req SearchContractByIdRequest) ([]Contract, error)

func (*MarketService) SearchContracts

func (s *MarketService) SearchContracts(ctx context.Context, req SearchContractRequest) ([]Contract, error)

type ModifyOrderRequest

type ModifyOrderRequest struct {
	AccountId  int     `json:"accountId"`
	OrderId    int     `json:"orderId"`
	Size       int     `json:"size"`
	LimitPrice float64 `json:"limitPrice"`
	StopPrice  float64 `json:"stopPrice"`
	TrailPrice float64 `json:"trailPrice"`
}

type OpenOrder

type OpenOrder struct {
	ID                int64     `json:"id"`
	AccountID         int64     `json:"accountId"`
	ContractID        string    `json:"contractId"`
	CreationTimestamp time.Time `json:"creationTimestamp"`
	UpdateTimestamp   time.Time `json:"updateTimestamp"`

	Status int `json:"status"`
	Type   int `json:"type"`
	Side   int `json:"side"`
	Size   int `json:"size"`

	LimitPrice  *float64 `json:"limitPrice"`
	StopPrice   *float64 `json:"stopPrice"`
	FilledPrice *float64 `json:"filledPrice"`
}

type OpenOrderSearchRequest

type OpenOrderSearchRequest struct {
	AccountId int `json:"accountId"`
}

type OpenOrderSearchResponse

type OpenOrderSearchResponse struct {
	Orders       []OpenOrder `json:"orders"`
	Success      bool        `json:"success"`
	ErrorCode    int         `json:"errorCode"`
	ErrorMessage string      `json:"errorMessage"`
}

type Order

type Order struct {
	ID                int64     `json:"id"`
	AccountID         int64     `json:"accountId"`
	ContractID        string    `json:"contractId"`
	SymbolID          string    `json:"symbolId"`
	CreationTimestamp time.Time `json:"creationTimestamp"`
	UpdateTimestamp   time.Time `json:"updateTimestamp"`
	Status            int       `json:"status"`
	Type              int       `json:"type"`
	Side              int       `json:"side"`
	Size              int       `json:"size"`

	LimitPrice  *float64 `json:"limitPrice"`
	StopPrice   *float64 `json:"stopPrice"`
	FillVolume  int      `json:"fillVolume"`
	FilledPrice *float64 `json:"filledPrice"`

	CustomTag *string `json:"customTag"`
}

type OrderSearchRequest

type OrderSearchRequest struct {
	AccountId      int    `json:"accountId"`
	StartTimestamp string `json:"startTimestamp"`
	EndTimestamp   string `json:"endTimestamp"`
}

type OrderSearchResponse

type OrderSearchResponse struct {
	Orders       []Order `json:"orders"`
	Success      bool    `json:"success"`
	ErrorCode    int     `json:"errorCode"`
	ErrorMessage string  `json:"errorMessage"`
}

type OrderService

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

func (*OrderService) CancelOrder

func (s *OrderService) CancelOrder(ctx context.Context, req CancelOrderRequest) (bool, error)

func (*OrderService) ModifyOrder

func (s *OrderService) ModifyOrder(ctx context.Context, req ModifyOrderRequest) (bool, error)

func (*OrderService) OpenOrderSearch

func (s *OrderService) OpenOrderSearch(ctx context.Context, req OpenOrderSearchRequest) ([]OpenOrder, error)

func (*OrderService) OrderSearch

func (s *OrderService) OrderSearch(ctx context.Context, req OrderSearchRequest) ([]Order, error)

func (*OrderService) PlaceOrder

func (s *OrderService) PlaceOrder(ctx context.Context, req PlaceOrderRequest) (int, error)

type PartialCloseContractRequest

type PartialCloseContractRequest struct {
	AccountId  int    `json:"accountId"`
	ContractId string `json:"contractId"`
	Size       int    `json:"size"`
}

type PlaceOrderRequest

type PlaceOrderRequest struct {
	AccountId         int     `json:"accountId"`
	ContractId        string  `json:"contractId"`
	Type              int     `json:"type"`
	Side              int     `json:"side"`
	Size              int     `json:"size"`
	LimitPrice        float64 `json:"limitPrice"`
	StopPrice         float64 `json:"stopPrice"`
	TrailPrice        float64 `json:"trailPrice"`
	CustomTag         string  `json:"customTag"`
	StopLossBracket   Bracket `json:"stopLossBracket"`
	TakeProfitBracket Bracket `json:"takeProfitBracket"`
}

type PlaceOrderResponse

type PlaceOrderResponse struct {
	OrderId      int    `json:"orderId"`
	Success      bool   `json:"success"`
	ErrorCode    int    `json:"errorCode"`
	ErrorMessage string `json:"errorMessage"`
}

type PositionService

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

func (*PositionService) CloseContract

func (p *PositionService) CloseContract(ctx context.Context, req CloseContractRequest) (bool, error)

func (*PositionService) PartialCloseContract

func (p *PositionService) PartialCloseContract(ctx context.Context, req PartialCloseContractRequest) (bool, error)

func (*PositionService) SearchOpenContract

func (p *PositionService) SearchOpenContract(ctx context.Context, req SearchOpenContractRequest) (bool, error)

type ProjectXClient

type ProjectXClient struct {
	Accounts *AccountService
	Markets  *MarketService
	Orders   *OrderService
	Trades   *TradeService

	Realtime *RealtimeService
	// contains filtered or unexported fields
}

func NewProjectXClient

func NewProjectXClient(baseUrl, wsUrl, username, apiKey string) *ProjectXClient

func (*ProjectXClient) Post

func (c *ProjectXClient) Post(
	ctx context.Context,
	endpoint string,
	reqBody any,
	respBody any,
) error

func (*ProjectXClient) PostNoAuth

func (c *ProjectXClient) PostNoAuth(
	ctx context.Context,
	endpoint string,
	reqBody any,
	respBody any,
) error

type RealtimeService

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

func NewRealtimeService

func NewRealtimeService(c *ProjectXClient) *RealtimeService

func (*RealtimeService) Close added in v0.0.7

func (r *RealtimeService) Close()

func (*RealtimeService) Connect

func (r *RealtimeService) Connect(ctx context.Context) error

func (*RealtimeService) DepthStream

func (r *RealtimeService) DepthStream() <-chan GatewayDepth

func (*RealtimeService) QuotesStream

func (r *RealtimeService) QuotesStream() <-chan GatewayQuote

func (*RealtimeService) SubscribeAccounts

func (r *RealtimeService) SubscribeAccounts(contractId string) error

func (*RealtimeService) SubscribeContractMarketDepth

func (r *RealtimeService) SubscribeContractMarketDepth(contractId string) error

func (*RealtimeService) SubscribeContractQuotes

func (r *RealtimeService) SubscribeContractQuotes(contractId string) error

func (*RealtimeService) SubscribeContractTrades

func (r *RealtimeService) SubscribeContractTrades(contractId string) error

func (*RealtimeService) SubscribeOrders

func (r *RealtimeService) SubscribeOrders(contractId string) error

func (*RealtimeService) SubscribePositions

func (r *RealtimeService) SubscribePositions(contractId string) error

func (*RealtimeService) SubscribeTrades

func (r *RealtimeService) SubscribeTrades(contractId string) error

func (*RealtimeService) TradesStream

func (r *RealtimeService) TradesStream() <-chan GatewayTrade

func (*RealtimeService) UserAccountStream

func (r *RealtimeService) UserAccountStream() <-chan GatewayUserAccount

func (*RealtimeService) UserOrdersStream

func (r *RealtimeService) UserOrdersStream() <-chan GatewayUserOrder

func (*RealtimeService) UserPositionStream

func (r *RealtimeService) UserPositionStream() <-chan GatewayUserPosition

func (*RealtimeService) UserTradeStream

func (r *RealtimeService) UserTradeStream() <-chan GatewayUserTrade

type SearchContractByIdRequest

type SearchContractByIdRequest struct {
	ContractId string `json:"contractId"`
}

type SearchContractRequest

type SearchContractRequest struct {
	SearchText string `json:"searchText"`
	Live       bool   `json:"live"`
}

type SearchOpenContractRequest

type SearchOpenContractRequest struct {
	AccountId int `json:"accountId"`
}

type SubscribeMsg

type SubscribeMsg struct {
	Type      int      `json:"type"`
	Target    string   `json:"target"`
	Arguments []string `json:"arguments"`
}

type TradeSearchRequest

type TradeSearchRequest struct {
	AccountId      int    `json:"accountId"`
	StartTimestamp string `json:"startTimestamp"`
	EndTimestamp   string `json:"endTimestamp"`
}

type TradeSearchResponse

type TradeSearchResponse struct {
	Trades       []GatewayUserTrade `json:"trades"`
	Success      bool               `json:"success"`
	ErrorCode    int                `json:"errorCode"`
	ErrorMessage string             `json:"errorMessage"`
}

type TradeService

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

func (*TradeService) Search

type WebSocketHandshakeResponse

type WebSocketHandshakeResponse struct {
	NegotiateVersion    int           `json:"negotiateVersion"`
	ConnectionId        string        `json:"connectionId"`
	ConnectionToken     string        `json:"connectionToken"`
	AvailableTransports []interface{} `json:"availableTransports"`
}

Jump to

Keyboard shortcuts

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