Использование переменной из функции в цикле for - Golang - PullRequest
0 голосов
/ 27 июня 2018

Я все еще учусь кодировать на Голанге, и это может быть простой вопрос, но я искал в Интернете и на сайте Go и не смог решить его. У меня есть следующий код ниже. При запуске он по существу запустит функцию option_quote, которая выведет "Ask" и "Bid" опции. Прямо сейчас for - это просто бесконечный цикл.

Однако я хочу выполнить новое действие, если определенные критерии удовлетворены на основе переменной c_bid, которая находится внутри функции option_quote.

Моя цель такова:

Программа продолжит цикл по функции 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"`
}

1 Ответ

0 голосов
/ 27 июня 2018

Вы можете попробовать вернуть результаты из функции 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"`
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...