doutang7707 2018-06-29 00:02
浏览 14

遍历提供特定值的API,并且仅当新值高于当前分配的值时才更新变量

I have the following code and could use some assistance. The code below will constantly print out the "bid" and "ask" price of a specific Stock Option that I define in the string. If the price reaches my "Profit Target" then it will close the trade for a profit. If the price reaches my "Stop-loss" then it will close the trade for a loss. This works out well.

What I am now trying to do is create a "Trailing Stop" once my "Profit Target" is reached. I am trying to accomplish this by creating another function (might not be needed) where it will be constantly checking the "bid" and "ask", but it will only assign the value to the variable IF the "bid" or "ask" is higher than the current high for the variable. This way I can then incorporate it into the Main function and close the transfer if the current price of the stock option is say 20% lower than the "high bid" or "high ask" of the day.

Would this require to run another script "concurrently" that is writing the variable? Essentially, I am trying to get Go to create a new variable that only gets updated with the price if the current bid and ask are higher than the price that is currently associated with the high bid and high ask variable.

I hope this makes sense. Any direction of documentation I could look at to help me accomplish this would be an idea.

package main

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

//Used for structure
var jsonStockResponse QUOTE
var closeTradeResponse CLOSERESPONSE
var jsonHighStockResponse QUOTE

//Values to Modify based on Trade
var targetPrice = 0.97       //Target Profit Price
var stopLossPrice = 0.25     //Close Trade for a Loss if price reaches this point
var trailingStopPrice = 30.0 //Trailing Stop once Target Price is reach. This is a Percentage number

//Values to Modify when "Closing a Trade"//
//Modify the String below with required information and place into the Functions "optionQuote" and "closeTrade"
//Will look like this -- "class=option&symbol=SPY&duration=day&side=sell_to_close&quantity=1&type=market&option_symbol=SPY180629P00267000" --
// Apple Example Option -- AAPL180629C00162500
// SPY Example Option -- SPY180629P00267000

//loop
func main() {
    for {
        bid, ask := optionQuote()
        fmt.Println("Bid:", bid, "Ask:", ask)
        if ask >= targetPrice {
            //closeTrade()
            fmt.Printf("Closing trade for a profit, bid is: %f
", bid)
            break
        } else if bid < stopLossPrice {
            //closeTrade()
            fmt.Printf("Closing trade for a loss, bid is: %f
", bid)
            break
        }
    }
}

//This function is used to get the quotes
func optionQuote() (bid, ask float64) {
    url := "https://api.com/v1/markets/quotes"
    payload := strings.NewReader("symbols=SPY180629P00267000")
    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 ")

    res, _ := http.DefaultClient.Do(req)
    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

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

    var cBid = jsonStockResponse.Quotes.Quote.Bid
    var cAsk = jsonStockResponse.Quotes.Quote.Ask

    return cBid, cAsk
}

func optionHighPrice() (bidH, askH float64) {
    url := "https://api.com/v1/markets/quotes"
    payload := strings.NewReader("symbols=SPY180629P00267000")
    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 ")

    res, _ := http.DefaultClient.Do(req)
    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

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

    var hBid = jsonHighStockResponse.Quotes.Quote.Bid
    var hAsk = jsonHighStockResponse.Quotes.Quote.Ask

    return hBid, hAsk
}

//This function is used to close Trade
func closeTrade() {
    url := "https://api.com/v1/accounts/orders"

    payload := strings.NewReader("class=option&symbol=SPY&duration=day&side=sell_to_close&quantity=1&type=market&option_symbol=SPY180629P00267000")

    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 ")

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

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

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

type QUOTE 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"`
}

type CLOSERESPONSE struct {
    Order struct {
        ID        int    `json:"id"`
        Status    string `json:"status"`
        PartnerID string `json:"partner_id"`
    } `json:"order"`
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测