go - 在 for 循环中使用函数中的变量 - Golang

标签 go

我仍在学习使用 Golang 编写代码,这可能是一个简单的问题,但我已经在网上和 Go 网站上进行了搜索,但无法解决它。我在下面有以下代码。运行时,它本质上将运行 option_quote 函数,该函数将打印出选项的 “Ask”“Bid”。现在 for 只是一个无限循环。

但是,如果基于 option_quote 函数中的 c_bid 变量满足某些条件,我想执行新操作。

我的目标是:

程序将继续循环遍历option_quote 函数以获得期权的当前价格。如果期权的当前价格大于或等于特定值,则执行不同的操作。

有点像

for c_bid > target_price {
    continue getting looping through quotes
}
if target_price >= c_bid {
    close_trade
}

我目前的代码:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

var json_stock_response Json

//endless loop
func main() {
    for {
        option_quote()
    }
}

//This function is used to get the quotes
func option_quote() {

    url := "https://api.tradier.com/v1/markets/quotes"

    payload := strings.NewReader("symbols=AAPL180629C00162500")

    req, _ := http.NewRequest("POST", url, payload)

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Add("accept", "application/json")
    req.Header.Add("Authorization", "Bearer XXX")
    req.Header.Add("Cache-Control", "no-cache")
    req.Header.Add("Postman-Token", "9d669b80-0ed2-4988-a225-56b2f018c5c6")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    //parse response into Json Data
    json.Unmarshal([]byte(body), &json_stock_response)

    //fmt.Println(res)
    // This will print out only the "Ask" value
    var option_symbol string = json_stock_response.Quotes.Quote.Symbol
    var c_bid float64 = json_stock_response.Quotes.Quote.Bid
    var c_ask float64 = json_stock_response.Quotes.Quote.Ask

    fmt.Println("Option:", option_symbol, "Bid:", c_bid, "Ask:", c_ask)
}

//Structure of the Json Response back from Traider when getting an option             quote

type Json struct {
    Quotes struct {
        Quote struct {
            Symbol           string      `json:"symbol"`
            Description      string      `json:"description"`
            Exch             string      `json:"exch"`
            Type             string      `json:"type"`
            Last             float64     `json:"last"`
            Change           float64     `json:"change"`
            ChangePercentage float64     `json:"change_percentage"`
            Volume           int         `json:"volume"`
            AverageVolume    int         `json:"average_volume"`
            LastVolume       int         `json:"last_volume"`
            TradeDate        int64       `json:"trade_date"`
            Open             interface{} `json:"open"`
            High             interface{} `json:"high"`
            Low              interface{} `json:"low"`
            Close            interface{} `json:"close"`
            Prevclose        float64     `json:"prevclose"`
            Week52High       float64     `json:"week_52_high"`
            Week52Low        float64     `json:"week_52_low"`
            Bid              float64     `json:"bid"`
            Bidsize          int         `json:"bidsize"`
            Bidexch          string      `json:"bidexch"`
            BidDate          int64       `json:"bid_date"`
            Ask              float64     `json:"ask"`
            Asksize          int         `json:"asksize"`
            Askexch          string      `json:"askexch"`
            AskDate          int64       `json:"ask_date"`
            OpenInterest     int         `json:"open_interest"`
            Underlying       string      `json:"underlying"`
            Strike           float64     `json:"strike"`
            ContractSize     int         `json:"contract_size"`
            ExpirationDate   string      `json:"expiration_date"`
            ExpirationType   string      `json:"expiration_type"`
            OptionType       string      `json:"option_type"`
            RootSymbol       string      `json:"root_symbol"`
        } `json:"quote"`
    } `json:"quotes"`
}

最佳答案

您可以尝试从 option_quote 函数返回一个结果,这里是一个例子:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

var json_stock_response Json

//endless loop
func main() {
    var target_price = 1.0
    for {
        bid, ask := option_quote()

        fmt.Println("Bid:", bid, "Ask:", ask)
        if bid <= target_price {
            fmt.Printf("Closing trade, bid is: %f\n", bid)
            break
        }
    }
}

//This function is used to get the quotes
func option_quote() (bid, ask float64) {

    url := "https://api.tradier.com/v1/markets/quotes"

    payload := strings.NewReader("symbols=AAPL180629C00162500")

    req, _ := http.NewRequest("POST", url, payload)

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Add("accept", "application/json")
    req.Header.Add("Authorization", "Bearer XXX")
    req.Header.Add("Cache-Control", "no-cache")
    req.Header.Add("Postman-Token", "9d669b80-0ed2-4988-a225-56b2f018c5c6")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    //parse response into Json Data
    json.Unmarshal([]byte(body), &json_stock_response)

    var c_bid float64 = json_stock_response.Quotes.Quote.Bid
    var c_ask float64 = json_stock_response.Quotes.Quote.Ask

    return c_bid, c_ask
}

//Structure of the Json Response back from Traider when getting an option             quote

type Json struct {
    Quotes struct {
        Quote struct {
            Symbol           string      `json:"symbol"`
            Description      string      `json:"description"`
            Exch             string      `json:"exch"`
            Type             string      `json:"type"`
            Last             float64     `json:"last"`
            Change           float64     `json:"change"`
            ChangePercentage float64     `json:"change_percentage"`
            Volume           int         `json:"volume"`
            AverageVolume    int         `json:"average_volume"`
            LastVolume       int         `json:"last_volume"`
            TradeDate        int64       `json:"trade_date"`
            Open             interface{} `json:"open"`
            High             interface{} `json:"high"`
            Low              interface{} `json:"low"`
            Close            interface{} `json:"close"`
            Prevclose        float64     `json:"prevclose"`
            Week52High       float64     `json:"week_52_high"`
            Week52Low        float64     `json:"week_52_low"`
            Bid              float64     `json:"bid"`
            Bidsize          int         `json:"bidsize"`
            Bidexch          string      `json:"bidexch"`
            BidDate          int64       `json:"bid_date"`
            Ask              float64     `json:"ask"`
            Asksize          int         `json:"asksize"`
            Askexch          string      `json:"askexch"`
            AskDate          int64       `json:"ask_date"`
            OpenInterest     int         `json:"open_interest"`
            Underlying       string      `json:"underlying"`
            Strike           float64     `json:"strike"`
            ContractSize     int         `json:"contract_size"`
            ExpirationDate   string      `json:"expiration_date"`
            ExpirationType   string      `json:"expiration_type"`
            OptionType       string      `json:"option_type"`
            RootSymbol       string      `json:"root_symbol"`
        } `json:"quote"`
    } `json:"quotes"`
}

关于go - 在 for 循环中使用函数中的变量 - Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51066786/

相关文章:

go - 在go-zookeeper中创建后,节点数据为空

pointers - [Golang]指针类型、指针类型和结构体类型调用方法有什么不同?

去解析字符串到时间

Golang Oauth2 获取 token 范围

javascript - Golang 后端到 javascript JSON Parse

golang - 编码 PKCS8 私钥?

http - 如何在 Go/Revel 中获取客户端 IP 地址

go - 使用正在运行的 shell 修改 golang Docker 容器

go - 如何解码 PEM 编码的 PKIX 公钥?

go - net/http : is it possible to have http. HandleFunc 自定义参数?