manifold

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

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

Go to latest
Published: Aug 19, 2024 License: MIT Imports: 9 Imported by: 0

README

Manifold Markets API Client Library

This is a Go client library for interacting with the Manifold Markets API. The library aims to provide a convenient way to interact with the endpoints offered by the Manifold API.

Installation

To install the library, use go get:

go get github.com/e74000/manifold

Usage

To use this library, you'll need to create a new Client instance and authenticate it with your API key.

Example
package main

import (
    "fmt"
    "log"
    "github.com/e74000/manifold"
)

func main() {
    client := manifold.NewClient("your-api-key")

    // Get information about the authenticated user
    user, err := client.User.Me()
    if err != nil {
        log.Fatalf("Failed to retrieve user info: %v", err)
    }
    fmt.Printf("Authenticated user: %s\n", user.Username)

    // Create a new binary market
    market, err := client.Market.CreateBinary("Will it rain tomorrow?", 50, nil, nil, nil, nil)
    if err != nil {
        log.Fatalf("Failed to create market: %v", err)
    }
    fmt.Printf("Created market: %s\n", market.Question)
}

Contributing

Please feel free to contribute!

License

This library is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorGETFailed             = errors.New("GET failed")
	ErrorPOSTFailed            = errors.New("POST failed")
	ErrorFailedToParseResponse = errors.New("failed to parse response")
)

Functions

This section is empty.

Types

type Answer

type Answer struct {
	ID                    string   `json:"id"`                              // Unique identifier for the answer
	Index                 int      `json:"index"`                           // Index of the answer in the list
	ContractID            string   `json:"contractId"`                      // ID of the associated contract
	UserID                string   `json:"userId"`                          // ID of the user who created the answer
	Text                  string   `json:"text"`                            // Text of the answer
	CreatedTime           int64    `json:"createdTime"`                     // Timestamp when the answer was created
	Color                 *string  `json:"color,omitempty"`                 // Color associated with the answer (optional)
	PoolYes               float64  `json:"poolYes"`                         // Pool of "yes" votes
	PoolNo                float64  `json:"poolNo"`                          // Pool of "no" votes
	Prob                  float64  `json:"prob"`                            // Current probability of the answer
	TotalLiquidity        float64  `json:"totalLiquidity"`                  // Total liquidity for the answer
	SubsidyPool           float64  `json:"subsidyPool"`                     // Subsidy pool for the answer
	IsOther               *bool    `json:"isOther,omitempty"`               // Indicates if this is an "other" answer (optional)
	Resolution            *string  `json:"resolution,omitempty"`            // Resolution of the answer (optional)
	ResolutionTime        *int64   `json:"resolutionTime,omitempty"`        // Timestamp when the answer was resolved (optional)
	ResolutionProbability *float64 `json:"resolutionProbability,omitempty"` // Probability at the time of resolution (optional)
	ResolverID            *string  `json:"resolverId,omitempty"`            // ID of the user who resolved the answer (optional)
	ProbChanges           struct {
		Day   float64 `json:"day"`   // Probability change over the last day
		Week  float64 `json:"week"`  // Probability change over the last week
		Month float64 `json:"month"` // Probability change over the last month
	} `json:"probChanges"` // Changes in probability over different time periods
	LoverUserID *string `json:"loverUserId,omitempty"` // ID of a user associated with the answer (optional)
}

Answer represents a possible answer in a market.

type AnyTxnType

type AnyTxnType struct {
	Category string `json:"category"` // Category of the transaction
}

AnyTxnType represents the generic type of transaction.

type ApiAnswer

type ApiAnswer struct {
	Answer

	Probability float64            `json:"probability"` // Current probability of the answer
	Pool        map[string]float64 `json:"pool"`        // Pool of funds associated with the answer
}

ApiAnswer represents the API's version of an answer, with adjusted fields.

type Bet

type Bet struct {
	ID               string      `json:"id"`                         // Unique identifier for the bet
	UserID           string      `json:"userId"`                     // ID of the user who placed the bet
	ContractID       string      `json:"contractId"`                 // ID of the associated contract
	AnswerID         *string     `json:"answerId,omitempty"`         // ID of the associated answer for multi-binary contracts (optional)
	CreatedTime      int64       `json:"createdTime"`                // Timestamp when the bet was placed
	UpdatedTime      *int64      `json:"updatedTime,omitempty"`      // Timestamp when the bet was last updated (optional)
	Amount           float64     `json:"amount"`                     // Amount of the bet
	LoanAmount       *float64    `json:"loanAmount,omitempty"`       // Loan amount associated with the bet (optional)
	Outcome          string      `json:"outcome"`                    // Outcome chosen for the bet
	Shares           float64     `json:"shares"`                     // Number of shares bought/sold
	ProbBefore       float64     `json:"probBefore"`                 // Probability before the bet
	ProbAfter        float64     `json:"probAfter"`                  // Probability after the bet
	Fees             Fees        `json:"fees"`                       // Fees associated with the bet
	IsApi            *bool       `json:"isApi,omitempty"`            // Indicates if the bet was placed via API (optional)
	IsRedemption     bool        `json:"isRedemption"`               // Indicates if the bet is a redemption
	ReplyToCommentID *string     `json:"replyToCommentId,omitempty"` // ID of the comment the bet replies to (optional)
	BetGroupID       *string     `json:"betGroupId,omitempty"`       // ID of the group associated with the bet (optional)
	LimitProps       *LimitProps `json:"limitProps,omitempty"`       // Limit order properties (optional)
}

Bet represents a bet placed in a contract.

type BetService

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

BetService provides methods for interacting with bets, including retrieving bets, creating new bets, and canceling existing bets.

func (*BetService) Bets

func (s *BetService) Bets(userID *string, username *string, contractID *string, contractSlug *string, limit *int, before *string, after *string, beforeTime *time.Time, afterTime *time.Time, kinds *string, order *string) ([]Bet, error)

Bets retrieves a list of bets based on various filtering criteria.

Parameters:

  • userID: Filter bets by the ID of the user who placed them. Optional.
  • username: Filter bets by the username of the user who placed them. Optional.
  • contractID: Filter bets by the ID of the contract. Optional.
  • contractSlug: Filter bets by the slug of the contract. Optional.
  • limit: Limits the number of results returned. Must be between 0 and 1000. Optional.
  • before: Only return bets placed before this cursor (e.g., a timestamp or ID). Optional.
  • after: Only return bets placed after this cursor (e.g., a timestamp or ID). Optional.
  • beforeTime: Only return bets placed before this timestamp. Optional.
  • afterTime: Only return bets placed after this timestamp. Optional.
  • kinds: Filter bets by their kind (e.g., "open-limit"). Optional.
  • order: Sort results in "asc" or "desc" order based on placement time. Optional.

Returns:

  • []Bet: A slice of bets matching the specified criteria.
  • error: An error object if the request fails or if input validation fails.

func (*BetService) Cancel

func (s *BetService) Cancel(id string) error

Cancel cancels an existing bet.

Parameters:

  • id: The ID of the bet to cancel. Required.

Returns:

  • error: An error object if the request fails or if the response cannot be parsed.

func (*BetService) Create

func (s *BetService) Create(amount float64, contractID string, outcome *string, limitProb *float64, expiresAt *time.Time, dryRun *bool) (*Bet, error)

Create places a new bet on a contract.

Parameters:

  • amount: The amount of the bet. Required.
  • contractID: The ID of the contract on which the bet is being placed. Required.
  • outcome: The outcome of the bet (e.g., "YES" or "NO"). Optional.
  • limitProb: Probability threshold for a limit order. Must be between 0 and 1. Optional.
  • expiresAt: Expiration time for a limit order. Only valid if limitProb is set. Optional.
  • dryRun: If true, simulates the bet without placing it. Optional.

Returns:

  • *Bet: The created bet object.
  • error: An error object if the request fails, input validation fails, or the response cannot be parsed.

type Client

type Client struct {
	BaseURL    string       // The base URL for the Manifold API.
	APIKey     string       // The API key used for authentication with the Manifold API.
	HTTPClient *http.Client // The HTTP client used to perform requests.

	User    *UserService    // Service for user-related API calls.
	Group   *GroupService   // Service for group-related API calls.
	Market  *MarketService  // Service for market-related API calls.
	Bet     *BetService     // Service for bet-related API calls.
	Comment *CommentService // Service for comment-related API calls.
	Mana    *ManaService    // Service for mana-related API calls.
}

Client represents the Manifold API client, used to interact with various services such as users, groups, markets, and more. It manages API requests and provides access to all the available services.

func NewClient

func NewClient(apiKey string) *Client

NewClient creates a new instance of the Manifold API client.

Parameters:

  • apiKey: The API key used for authenticating with the Manifold API.

Returns:

  • *Client: A pointer to the newly created Client instance, pre-configured with services.

func (*Client) GET

func (c *Client) GET(endpoint string, params map[string]string) ([]byte, error)

GET performs a GET request to the Manifold API.

Parameters:

  • endpoint: The API endpoint to send the GET request to (relative to BaseURL).
  • params: A map of query parameters to include in the request. Optional.

Returns:

  • []byte: The response body as a byte slice.
  • error: An error object if the request fails or if the response cannot be read.

func (*Client) POST

func (c *Client) POST(endpoint string, body interface{}) ([]byte, error)

POST performs a POST request to the Manifold API.

Parameters:

  • endpoint: The API endpoint to send the POST request to (relative to BaseURL).
  • body: The body to include in the POST request. Must be serializable to JSON. Optional.

Returns:

  • []byte: The response body as a byte slice.
  • error: An error object if the request fails or if the response cannot be read.

type Comment

type Comment struct {
	ID               string          `json:"id"`                         // Unique identifier for the comment
	ReplyToCommentID *string         `json:"replyToCommentId,omitempty"` // Optional ID of the comment being replied to
	UserID           string          `json:"userId"`                     // ID of the user who made the comment
	Text             *string         `json:"text,omitempty"`             // Deprecated: Use Content instead
	Content          json.RawMessage `json:"content"`                    // Content of the comment, potentially rich text or JSON
	CreatedTime      int64           `json:"createdTime"`                // Timestamp when the comment was created
	UserName         string          `json:"userName"`                   // Full name of the user who made the comment
	UserUsername     string          `json:"userUsername"`               // Username of the user who made the comment
	UserAvatarURL    *string         `json:"userAvatarUrl,omitempty"`    // Optional URL to the user's avatar
	Likes            *int            `json:"likes,omitempty"`            // Deprecated: Number of likes (still used, but no longer maintained)
	Hidden           *bool           `json:"hidden,omitempty"`           // Optional flag indicating if the comment is hidden
	HiddenTime       *int64          `json:"hiddenTime,omitempty"`       // Optional timestamp when the comment was hidden
	HiderID          *string         `json:"hiderId,omitempty"`          // Optional ID of the user who hid the comment
	Pinned           *bool           `json:"pinned,omitempty"`           // Optional flag indicating if the comment is pinned
	PinnedTime       *int64          `json:"pinnedTime,omitempty"`       // Optional timestamp when the comment was pinned
	PinnerID         *string         `json:"pinnerId,omitempty"`         // Optional ID of the user who pinned the comment
	Visibility       string          `json:"visibility"`                 // Visibility status of the comment (e.g., "public", "private")
	EditedTime       *int64          `json:"editedTime,omitempty"`       // Optional timestamp when the comment was last edited
	IsApi            *bool           `json:"isApi,omitempty"`            // Optional flag indicating if the comment was posted via API
}

Comment represents a user comment associated with a bet, contract, or other entities. Comments may include replies, visibility settings, and status indicators (e.g., pinned, hidden).

type CommentService

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

CommentService provides methods for interacting with comments on contracts, including retrieving, posting text, HTML, and Markdown comments.

func (*CommentService) Comment

func (s *CommentService) Comment(id string, content string) error

Comment posts a json TipTap comment on a contract.

Parameters:

  • id: The ID of the contract to comment on. Required.
  • content: The text content of the comment. Required.

Returns:

  • error: An error object if the request fails or if the response cannot be parsed.

func (*CommentService) CommentHTML

func (s *CommentService) CommentHTML(id string, content string) error

CommentHTML posts an HTML comment on a contract.

Parameters:

  • id: The ID of the contract to comment on. Required.
  • content: The HTML content of the comment. Required.

Returns:

  • error: An error object if the request fails or if the response cannot be parsed.

func (*CommentService) CommentMarkdown

func (s *CommentService) CommentMarkdown(id string, content string) error

CommentMarkdown posts a Markdown-formatted comment on a contract.

Parameters:

  • id: The ID of the contract to comment on. Required.
  • content: The Markdown content of the comment. Required.

Returns:

  • error: An error object if the request fails or if the response cannot be parsed.

func (*CommentService) Comments

func (s *CommentService) Comments(contractID *string, contractSlug *string, limit *int, offset *int, userID *string) ([]Comment, error)

Comments retrieves a list of comments for a specific contract.

Parameters:

  • contractID: Filter comments by the ID of the contract. Optional.
  • contractSlug: Filter comments by the slug of the contract. Optional.
  • limit: Limits the number of results returned. Must be between 0 and 1000. Optional.
  • offset: Skips the specified number of comments before returning results. Must be 0 or greater. Optional.
  • userID: Filter comments by the ID of the user who posted them. Optional.

Returns:

  • []Comment: A slice of comments matching the specified criteria.
  • error: An error object if the request fails or if input validation fails.

type ContractMetric

type ContractMetric struct {
	ID               int                      `json:"id"`                         // Unique identifier for the metric
	ContractID       string                   `json:"contractId"`                 // ID of the associated contract
	From             map[string]PeriodMetrics `json:"from,omitempty"`             // Profit and investment metrics from specific periods (optional)
	HasNoShares      bool                     `json:"hasNoShares"`                // Indicates if the user holds no shares
	HasShares        bool                     `json:"hasShares"`                  // Indicates if the user holds shares
	HasYesShares     bool                     `json:"hasYesShares"`               // Indicates if the user holds "yes" shares
	Invested         float64                  `json:"invested"`                   // Amount invested by the user
	Loan             float64                  `json:"loan"`                       // Loan amount associated with the contract
	MaxSharesOutcome *string                  `json:"maxSharesOutcome,omitempty"` // Outcome with the maximum shares (optional)
	Payout           float64                  `json:"payout"`                     // Payout amount for the contract
	Profit           float64                  `json:"profit"`                     // Profit made from the contract
	ProfitPercent    float64                  `json:"profitPercent"`              // Profit percentage from the contract
	TotalShares      map[string]float64       `json:"totalShares"`                // Total shares held by the user
	UserID           string                   `json:"userId"`                     // ID of the user associated with the metric
	UserUsername     string                   `json:"userUsername"`               // Username of the user
	UserName         string                   `json:"userName"`                   // Full name of the user
	UserAvatarURL    string                   `json:"userAvatarUrl"`              // URL to the user's avatar image
	LastBetTime      int64                    `json:"lastBetTime"`                // Timestamp of the last bet made by the user
	AnswerID         *string                  `json:"answerId,omitempty"`         // ID of the associated answer (optional)
	ProfitAdjustment *float64                 `json:"profitAdjustment,omitempty"` // Profit adjustment for the contract (optional)
}

ContractMetric represents a metric related to a contract.

type DisplayUser

type DisplayUser struct {
	ID        string  `json:"id"`                  // Unique identifier for the user
	Name      string  `json:"name"`                // Full name of the user
	Username  string  `json:"username"`            // Username of the user
	AvatarURL *string `json:"avatarUrl,omitempty"` // URL to the user's avatar image (optional)
}

DisplayUser represents a simplified view of a user, often used for display purposes.

type Fees

type Fees struct {
	CreatorFee   float64 `json:"creatorFee"`   // Fee taken by the creator
	PlatformFee  float64 `json:"platformFee"`  // Fee taken by the platform
	LiquidityFee float64 `json:"liquidityFee"` // Fee taken for liquidity
}

Fees represents the fees associated with a bet or a fill.

type Fill

type Fill struct {
	MatchedBetID string  `json:"matchedBetId"`     // ID of the matched bet (null if matched by pool)
	Amount       float64 `json:"amount"`           // Amount of the fill
	Shares       float64 `json:"shares"`           // Shares bought/sold in the fill
	Timestamp    int64   `json:"timestamp"`        // Timestamp when the fill occurred
	Fees         Fees    `json:"fees"`             // Fees associated with the fill
	IsSale       *bool   `json:"isSale,omitempty"` // Indicates if this was a sale (optional)
}

Fill represents a record of a transaction that partially or fully fills a bet order.

type FullMarket

type FullMarket struct {
	LiteMarket

	Answers               *[]ApiAnswer `json:"answers,omitempty"`               // List of possible answers (optional)
	ShouldAnswersSumToOne *bool        `json:"shouldAnswersSumToOne,omitempty"` // Indicates if answers should sum to one (optional)
	AddAnswersMode        *string      `json:"addAnswersMode,omitempty"`        // Mode for adding answers ("ANYONE", "ONLY_CREATOR", "DISABLED") (optional)
	Options               *[]struct {
		Text  string `json:"text"`  // Text of the option
		Votes int    `json:"votes"` // Number of votes for the option
	} `json:"options,omitempty"` // List of options and their votes (optional)
	TotalBounty     *float64        `json:"totalBounty,omitempty"`   // Total bounty for the market (optional)
	BountyLeft      *float64        `json:"bountyLeft,omitempty"`    // Bounty left for the market (optional)
	Description     json.RawMessage `json:"description"`             // Detailed description of the market
	TextDescription string          `json:"textDescription"`         // Text-based description of the market
	CoverImageUrl   *string         `json:"coverImageUrl,omitempty"` // URL to the market's cover image (optional)
	GroupSlugs      *[]string       `json:"groupSlugs,omitempty"`    // List of group slugs associated with the market (optional)
}

FullMarket represents a comprehensive view of a market, extending LiteMarket.

type Group

type Group struct {
	ID                string          `json:"id"`                          // Unique identifier for the group
	Slug              string          `json:"slug"`                        // Slug for the group (usually URL-friendly)
	Name              string          `json:"name"`                        // Name of the group
	About             json.RawMessage `json:"about,omitempty"`             // Detailed information about the group (optional)
	CreatorID         string          `json:"creatorId"`                   // ID of the group creator
	CreatedTime       int64           `json:"createdTime"`                 // Timestamp when the group was created
	AnyoneCanJoin     *bool           `json:"anyoneCanJoin,omitempty"`     // Indicates if anyone can join the group (optional)
	TotalMembers      int             `json:"totalMembers"`                // Total number of members in the group
	PostIDs           []string        `json:"postIds"`                     // List of post IDs associated with the group
	CachedLeaderboard *Leaderboard    `json:"cachedLeaderboard,omitempty"` // Cached leaderboard data for the group (optional)
	BannerURL         *string         `json:"bannerUrl,omitempty"`         // URL to the group's banner image (optional)
	PrivacyStatus     string          `json:"privacyStatus"`               // Privacy status of the group (e.g., "public", "private")
	ImportanceScore   float64         `json:"importanceScore"`             // Importance score of the group
}

Group represents a group with various attributes.

type GroupService

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

GroupService provides methods for interacting with groups, including retrieving a list of groups, getting details of a specific group by slug or ID.

func (*GroupService) Group

func (s *GroupService) Group(slug string) (*Group, error)

Group retrieves the details of a specific group using its slug.

Parameters:

  • slug: The slug of the group to retrieve. Required.

Returns:

  • *Group: A pointer to the retrieved group object.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*GroupService) Groups

func (s *GroupService) Groups(beforeTime *time.Time, availableToUserID *string) ([]Group, error)

Groups retrieves a list of groups based on optional filtering criteria.

Parameters:

  • beforeTime: Only return groups created before this timestamp. Optional.
  • availableToUserID: Filter groups that are available to the specified user ID. Optional.

Returns:

  • []Group: A slice of groups matching the specified criteria.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*GroupService) ID

func (s *GroupService) ID(id string) (*Group, error)

ID retrieves the details of a specific group using its ID.

Parameters:

  • id: The ID of the group to retrieve. Required.

Returns:

  • *Group: A pointer to the retrieved group object.
  • error: An error object if the request fails or if the response cannot be parsed.

type Leaderboard

type Leaderboard struct {
	TopTraders  []Trader `json:"topTraders"`  // List of top traders in the group
	TopCreators []Trader `json:"topCreators"` // List of top content creators in the group
}

Leaderboard represents the cached leaderboard for a group.

type LimitProps

type LimitProps struct {
	OrderAmount float64 `json:"orderAmount"`         // Amount of the order
	LimitProb   float64 `json:"limitProb"`           // Probability limit for the order
	IsFilled    bool    `json:"isFilled"`            // Indicates if the order is filled
	IsCancelled bool    `json:"isCancelled"`         // Indicates if the order is cancelled
	Fills       []Fill  `json:"fills"`               // List of fills associated with the order
	ExpiresAt   *int64  `json:"expiresAt,omitempty"` // Expiration time of the order (optional)
}

LimitProps represents properties specific to limit orders.

type LiteMarket

type LiteMarket struct {
	ID                    string             `json:"id"`                              // Unique identifier for the market
	CreatorID             string             `json:"creatorId"`                       // ID of the market creator
	CreatorUsername       string             `json:"creatorUsername"`                 // Username of the market creator
	CreatorName           string             `json:"creatorName"`                     // Full name of the market creator
	CreatedTime           int64              `json:"createdTime"`                     // Timestamp when the market was created
	CreatorAvatarURL      *string            `json:"creatorAvatarUrl,omitempty"`      // URL to the creator's avatar image (optional)
	CloseTime             *int64             `json:"closeTime,omitempty"`             // Timestamp when the market closes (optional)
	Question              string             `json:"question"`                        // Question posed by the market
	Slug                  string             `json:"slug"`                            // Slug for the market (usually URL-friendly)
	URL                   string             `json:"url"`                             // URL to the market
	OutcomeType           string             `json:"outcomeType"`                     // Type of outcome for the market (e.g., "BINARY", "MULTIPLE")
	Mechanism             string             `json:"mechanism"`                       // Mechanism used in the market (e.g., "CPMM")
	Pool                  map[string]float64 `json:"pool,omitempty"`                  // Pool of funds in the market (optional)
	Probability           *float64           `json:"probability,omitempty"`           // Current probability for the market (optional)
	P                     *float64           `json:"p,omitempty"`                     // Additional probability field (optional)
	TotalLiquidity        *float64           `json:"totalLiquidity,omitempty"`        // Total liquidity in the market (optional)
	Value                 *float64           `json:"value,omitempty"`                 // Value of the market (optional)
	Min                   *float64           `json:"min,omitempty"`                   // Minimum value for the market (optional)
	Max                   *float64           `json:"max,omitempty"`                   // Maximum value for the market (optional)
	Volume                float64            `json:"volume"`                          // Total volume of the market
	Volume24Hours         float64            `json:"volume24Hours"`                   // Volume in the last 24 hours
	IsResolved            bool               `json:"isResolved"`                      // Indicates if the market is resolved
	Resolution            *string            `json:"resolution,omitempty"`            // Resolution of the market (optional)
	ResolutionTime        *int64             `json:"resolutionTime,omitempty"`        // Timestamp when the market was resolved (optional)
	ResolutionProbability *float64           `json:"resolutionProbability,omitempty"` // Probability at the time of resolution (optional)
	UniqueBettorCount     int                `json:"uniqueBettorCount"`               // Number of unique bettors in the market
	LastUpdatedTime       *int64             `json:"lastUpdatedTime,omitempty"`       // Timestamp when the market was last updated (optional)
	LastBetTime           *int64             `json:"lastBetTime,omitempty"`           // Timestamp of the last bet (optional)
	MarketTier            *string            `json:"marketTier,omitempty"`            // Tier of the market (optional)
}

LiteMarket represents a basic view of a market with essential fields.

type ManaService

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

func (*ManaService) Managram

func (s *ManaService) Managram(toIDs []string, amount float64, message *string) error

Managram sends a Managram to one or more users.

Parameters:

  • toIDs: A list of user IDs to send the Managram to. Required.
  • amount: The amount of Mana to send. Required.
  • message: An optional message to include with the Managram. Optional.

Returns:

  • error: An error object if the request fails or if the response cannot be parsed.

func (*ManaService) Managrams

func (s *ManaService) Managrams(toID *string, fromID *string, limit *int, before *time.Time, after *time.Time) ([]Txn, error)

Managrams retrieves a list of Managram transactions based on optional filtering criteria.

Parameters:

  • toID: Filter transactions by the recipient's user ID. Optional.
  • fromID: Filter transactions by the sender's user ID. Optional.
  • limit: Limits the number of results returned. Must be between 0 and 1000. Optional.
  • before: Only return transactions before this timestamp. Optional.
  • after: Only return transactions after this timestamp. Optional.

Returns:

  • []Txn: A slice of transactions matching the specified criteria.
  • error: An error object if the request fails or if the response cannot be parsed.

type MarketService

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

MarketService provides methods for managing markets, including retrieving market data, creating new markets, adding liquidity or bounties, resolving markets, and more.

func (*MarketService) AddBounty

func (s *MarketService) AddBounty(id string, amount float64) (*Txn, error)

AddBounty adds a bounty to a market.

Parameters:

  • id: The ID of the market to add the bounty to. Required.
  • amount: The amount of the bounty. Must be greater than zero. Required.

Returns:

  • *Txn: A pointer to the transaction object representing the added bounty.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) AddLiquidity

func (s *MarketService) AddLiquidity(id string, amount float64) (*Txn, error)

AddLiquidity adds liquidity to a market.

Parameters:

  • id: The ID of the market to add liquidity to. Required.
  • amount: The amount of liquidity to add. Must be greater than zero. Required.

Returns:

  • *Txn: A pointer to the transaction object representing the added liquidity.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Answer

func (s *MarketService) Answer(id string, text string) error

Answer submits an answer to a market.

Parameters:

  • id: The ID of the market to answer. Required.
  • text: The answer text to submit. Required.

Returns:

  • error: An error object if the request fails or if the response cannot be parsed.

func (*MarketService) AwardBounty

func (s *MarketService) AwardBounty(id string, amount float64, commentID string) (*Txn, error)

AwardBounty awards a bounty to a specific comment on a market.

Parameters:

  • id: The ID of the market to award the bounty for. Required.
  • amount: The amount of the bounty to award. Must be greater than zero. Required.
  • commentID: The ID of the comment to award the bounty to. Required.

Returns:

  • *Txn: A pointer to the transaction object representing the awarded bounty.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Close

func (s *MarketService) Close(id string, closeTime *time.Time) error

Close closes a market, setting a specific close time if provided.

Parameters:

  • id: The ID of the market to close. Required.
  • closeTime: The time when the market should close. Must be in the future if provided. Optional.

Returns:

  • error: An error object if the request fails or if input validation fails.

func (*MarketService) CreateBinary

func (s *MarketService) CreateBinary(question string, initialProb int, description *string, closeTime *time.Time, visibility *string, extraLiquidity *int) (*LiteMarket, error)

CreateBinary creates a binary market.

Parameters:

  • question: The question the market is based on. Required.
  • initialProb: The initial probability (between 1 and 99) of the market outcome. Required.
  • description: A description of the market. Optional.
  • closeTime: The time when the market will close. Must be in the future. Optional.
  • visibility: The visibility of the market ("public" or "unlisted"). Optional.
  • extraLiquidity: The extra liquidity to add to the market. Optional.

Returns:

  • *LiteMarket: A pointer to the created market object.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) CreateBountiedQuestion

func (s *MarketService) CreateBountiedQuestion(question string, totalBounty int, description *string, closeTime *time.Time, visibility *string) (*LiteMarket, error)

CreateBountiedQuestion creates a bountied question market.

Parameters:

  • question: The question the market is based on. Required.
  • totalBounty: The total bounty amount for the question. Must be greater than zero. Required.
  • description: A description of the market. Optional.
  • closeTime: The time when the market will close. Must be in the future. Optional.
  • visibility: The visibility of the market ("public" or "unlisted"). Optional.

Returns:

  • *LiteMarket: A pointer to the created market object.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) CreatePoll

func (s *MarketService) CreatePoll(question string, answers []string, description *string, closeTime *time.Time, visibility *string) (*LiteMarket, error)

CreatePoll creates a poll market.

Parameters:

  • question: The question the poll is based on. Required.
  • answers: The possible answers for the poll. Must include at least two answers. Required.
  • description: A description of the poll. Optional.
  • closeTime: The time when the poll will close. Must be in the future. Optional.
  • visibility: The visibility of the poll ("public" or "unlisted"). Optional.

Returns:

  • *LiteMarket: A pointer to the created poll object.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) CreatePseudoNumeric

func (s *MarketService) CreatePseudoNumeric(question string, min, max, initialValue int, isLogScale bool, description *string, closeTime *time.Time, visibility *string, extraLiquidity *int) (*LiteMarket, error)

CreatePseudoNumeric creates a pseudo-numeric market.

Parameters:

  • question: The question the market is based on. Required.
  • min: The minimum value for the market. Required.
  • max: The maximum value for the market. Required.
  • initialValue: The initial value for the market, between min and max. Required.
  • isLogScale: Whether the market uses a logarithmic scale. Required.
  • description: A description of the market. Optional.
  • closeTime: The time when the market will close. Must be in the future. Optional.
  • visibility: The visibility of the market ("public" or "unlisted"). Optional.
  • extraLiquidity: The extra liquidity to add to the market. Optional.

Returns:

  • *LiteMarket: A pointer to the created market object.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Group

func (s *MarketService) Group(id string, groupID string, remove *bool) error

Group adds or removes a market from a group.

Parameters:

  • id: The ID of the market to group. Required.
  • groupID: The ID of the group to add or remove the market from. Required.
  • remove: If true, removes the market from the group; otherwise, adds the market to the group. Optional.

Returns:

  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Market

func (s *MarketService) Market(id string) (*FullMarket, error)

Market retrieves the details of a specific market using its ID.

Parameters:

  • id: The ID of the market to retrieve. Required.

Returns:

  • *FullMarket: A pointer to the retrieved market object.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*MarketService) Markets

func (s *MarketService) Markets(limit *int, sort *string, order *string, before *string, userID *string, groupID *string) ([]LiteMarket, error)

Markets retrieves a list of markets based on various filtering criteria.

Parameters:

  • limit: Limits the number of results returned. Must be between 0 and 1000. Optional.
  • sort: Sorts the results based on one of the allowed sorting options (e.g., "created-time", "updated-time"). Optional.
  • order: Specifies the order of the results, either "asc" or "desc". Optional.
  • before: Retrieves markets created before this cursor. Optional.
  • userID: Filters markets created by a specific user ID. Optional.
  • groupID: Filters markets associated with a specific group ID. Optional.

Returns:

  • []LiteMarket: A slice of markets matching the specified criteria.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Positions

func (s *MarketService) Positions(id string) ([]ContractMetric, error)

Positions retrieves the positions for a specific market using its ID.

Parameters:

  • id: The ID of the market to retrieve positions for. Required.

Returns:

  • []ContractMetric: A slice of contract metrics representing the positions.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*MarketService) ResolveBinary

func (s *MarketService) ResolveBinary(id string, outcome string, probabilityInt *int) (*LiteMarket, error)

ResolveBinary resolves a binary market.

Parameters:

  • id: The ID of the market to resolve. Required.
  • outcome: The outcome of the market ("YES", "NO", "MKT", "CANCEL"). Required.
  • probabilityInt: The probability integer (0-100) if the outcome is "MKT". Optional.

Returns:

  • *LiteMarket: A pointer to the resolved market object.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) ResolveFreeResponse

func (s *MarketService) ResolveFreeResponse(id string, outcome string, resolutions []Resolution) (*LiteMarket, error)

ResolveFreeResponse resolves a free response or multiple choice market.

Parameters:

  • id: The ID of the market to resolve. Required.
  • outcome: The outcome of the market ("MKT", "CANCEL"). Required.
  • resolutions: A slice of resolutions with percentages for each outcome if outcome is "MKT". Optional.

Returns:

  • *LiteMarket: A pointer to the resolved market object.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) ResolveNumeric

func (s *MarketService) ResolveNumeric(id string, outcome string, value *float64, probabilityInt *int) (*LiteMarket, error)

ResolveNumeric resolves a numeric market.

Parameters:

  • id: The ID of the market to resolve. Required.
  • outcome: The outcome of the market ("CANCEL"). Required.
  • value: The final value of the market. Optional.
  • probabilityInt: The probability integer (0-100) if applicable. Optional.

Returns:

  • *LiteMarket: A pointer to the resolved market object.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Search

func (s *MarketService) Search(term string, sort *string, filter *string, contractType *string, topicSlug *string, creatorID *string, limit *int, offset *int) ([]LiteMarket, error)

Search searches for markets based on various criteria.

Parameters:

  • term: The search term. Required.
  • sort: Sorts the results based on one of the allowed sorting options (e.g., "newest", "score"). Optional.
  • filter: Filters results based on their state (e.g., "open", "closed"). Optional.
  • contractType: Filters results based on the type of contract (e.g., "BINARY", "POLL"). Optional.
  • topicSlug: Filters results based on a topic slug. Optional.
  • creatorID: Filters results based on the creator's user ID. Optional.
  • limit: Limits the number of results returned. Must be between 0 and 1000. Optional.
  • offset: Skips the specified number of results before returning. Must be 0 or greater. Optional.

Returns:

  • []LiteMarket: A slice of markets matching the specified criteria.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Sell

func (s *MarketService) Sell(id string, outcome *string, shares *float64, answerID *string) (*Bet, error)

Sell sells shares in a market.

Parameters:

  • id: The ID of the market to sell shares in. Required.
  • outcome: The outcome to sell shares in ("YES" or "NO"). Optional.
  • shares: The number of shares to sell. Must be greater than zero. Optional.
  • answerID: The ID of the specific answer to sell shares in for multiple choice markets. Optional.

Returns:

  • *Bet: A pointer to the bet object representing the sale.
  • error: An error object if the request fails or if input validation fails.

func (*MarketService) Slug

func (s *MarketService) Slug(slug string) (*FullMarket, error)

Slug retrieves the details of a market using its slug.

Parameters:

  • slug: The slug of the market to retrieve. Required.

Returns:

  • *FullMarket: A pointer to the retrieved market object.
  • error: An error object if the request fails or if the response cannot be parsed.

type PeriodMetrics

type PeriodMetrics struct {
	Profit        float64 `json:"profit"`        // Profit during the period
	ProfitPercent float64 `json:"profitPercent"` // Profit percentage during the period
	Invested      float64 `json:"invested"`      // Amount invested during the period
	PrevValue     float64 `json:"prevValue"`     // Previous value before the period
	Value         float64 `json:"value"`         // Current value after the period
}

PeriodMetrics represents the profit and investment metrics for a specific period.

type ProfitCached

type ProfitCached struct {
	Daily   float64 `json:"daily"`   // Daily profit
	Weekly  float64 `json:"weekly"`  // Weekly profit
	Monthly float64 `json:"monthly"` // Monthly profit
	AllTime float64 `json:"allTime"` // All-time profit
}

ProfitCached holds cached profit data for different time periods.

type Resolution

type Resolution struct {
	Answer int `json:"answer"` // Index of the selected answer in the resolution
	Pct    int `json:"pct"`    // Percentage allocated to the answer
}

Resolution represents the outcome of a resolution process, typically associated with a market or contract. It details the answer selected and the percentage allocated to it.

type Trader

type Trader struct {
	UserID string  `json:"userId"` // ID of the user
	Score  float64 `json:"score"`  // Score of the user on the leaderboard
}

Trader represents a user and their score on the leaderboard.

type Txn

type Txn struct {
	ID          string                 `json:"id"`                    // Unique identifier for the transaction
	CreatedTime int64                  `json:"createdTime"`           // Timestamp when the transaction was created
	FromID      string                 `json:"fromId"`                // ID of the entity sending the transaction
	FromType    string                 `json:"fromType"`              // Type of the sender (e.g., "user", "contract")
	ToID        string                 `json:"toId"`                  // ID of the entity receiving the transaction
	ToType      string                 `json:"toType"`                // Type of the recipient (e.g., "user", "contract")
	Amount      float64                `json:"amount"`                // Amount of the transaction
	Token       string                 `json:"token"`                 // Token or currency type used in the transaction
	Category    string                 `json:"category"`              // Category of the transaction, derived from AnyTxnType
	Description *string                `json:"description,omitempty"` // Optional description of the transaction
	Data        map[string]interface{} `json:"data,omitempty"`        // Extra data related to the transaction, if any
	AnyTxnType                         // Embedding AnyTxnType to include its fields
}

Txn represents a transaction within the system. This can involve different entities, such as users or contracts, and may include various types of financial operations.

type User

type User struct {
	ID                   string       `json:"id"`                             // Unique identifier for the user
	CreatedTime          int64        `json:"createdTime"`                    // Timestamp when the user was created
	Name                 string       `json:"name"`                           // Full name of the user
	Username             string       `json:"username"`                       // Username of the user
	URL                  string       `json:"url"`                            // URL to the user's profile
	AvatarUrl            *string      `json:"avatarUrl,omitempty"`            // URL to the user's avatar image (optional)
	Bio                  *string      `json:"bio,omitempty"`                  // User's biography (optional)
	BannerUrl            *string      `json:"bannerUrl,omitempty"`            // URL to the user's banner image (optional)
	Website              *string      `json:"website,omitempty"`              // User's personal website (optional)
	TwitterHandle        *string      `json:"twitterHandle,omitempty"`        // User's Twitter handle (optional)
	DiscordHandle        *string      `json:"discordHandle,omitempty"`        // User's Discord handle (optional)
	IsBot                *bool        `json:"isBot,omitempty"`                // Indicates if the user is a bot (optional)
	IsAdmin              *bool        `json:"isAdmin,omitempty"`              // Indicates if the user is an admin (optional)
	IsTrustworthy        *bool        `json:"isTrustworthy,omitempty"`        // Indicates if the user is trustworthy (optional)
	IsBannedFromPosting  *bool        `json:"isBannedFromPosting,omitempty"`  // Indicates if the user is banned from posting (optional)
	UserDeleted          *bool        `json:"userDeleted,omitempty"`          // Indicates if the user has been deleted (optional)
	Balance              float64      `json:"balance"`                        // Current balance of the user
	TotalDeposits        float64      `json:"totalDeposits"`                  // Total deposits made by the user
	LastBetTime          *int64       `json:"lastBetTime,omitempty"`          // Timestamp of the user's last bet (optional)
	CurrentBettingStreak *int         `json:"currentBettingStreak,omitempty"` // User's current betting streak (optional)
	ProfitCached         ProfitCached `json:"profitCached"`                   // Cached profit data for the user
}

User represents a user in the system with various attributes.

type UserService

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

UserService provides methods for interacting with user data, including retrieving user details by username or ID, listing users, and getting the authenticated user's information.

func (*UserService) ID

func (s *UserService) ID(id string) (*User, error)

ID retrieves detailed information about a user by their ID.

Parameters:

  • id: The ID of the user to retrieve. Required.

Returns:

  • *User: A pointer to the retrieved user object.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*UserService) IDLite

func (s *UserService) IDLite(id string) (*DisplayUser, error)

IDLite retrieves basic information about a user by their ID.

Parameters:

  • id: The ID of the user to retrieve. Required.

Returns:

  • *DisplayUser: A pointer to the retrieved display user object, containing basic information.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*UserService) Me

func (s *UserService) Me() (*User, error)

Me retrieves information about the authenticated user.

Returns:

  • *User: A pointer to the authenticated user's object.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*UserService) User

func (s *UserService) User(username string) (*User, error)

User retrieves detailed information about a user by their username.

Parameters:

  • username: The username of the user to retrieve. Required.

Returns:

  • *User: A pointer to the retrieved user object.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*UserService) UserLite

func (s *UserService) UserLite(username string) (*DisplayUser, error)

UserLite retrieves basic information about a user by their username.

Parameters:

  • username: The username of the user to retrieve. Required.

Returns:

  • *DisplayUser: A pointer to the retrieved display user object, containing basic information.
  • error: An error object if the request fails or if the response cannot be parsed.

func (*UserService) Users

func (s *UserService) Users(limit *int, before *string) ([]User, error)

Users retrieves a list of users with optional pagination.

Parameters:

  • limit: Limits the number of results returned. Must be between 0 and 1000. Optional.
  • before: Retrieves users before this cursor (e.g., timestamp or ID). Optional.

Returns:

  • []User: A slice of users matching the specified criteria.
  • error: An error object if the request fails or if input validation fails.

Jump to

Keyboard shortcuts

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