遍历提供特定值的API,并仅在新值高于当前分配的值

时间:2018-06-29 00:02:59

标签: go trading algorithmic-trading

我有以下代码,可能需要一些帮助。下面的代码将不断打印出我在字符串中定义的特定股票期权的“出价”和“出价”价格。如果价格达到我的“获利目标”,那么它将平仓以获取利润。如果价格达到我的“止损”,那么它将平仓亏损。效果很好。

我现在想做的是一旦达到我的“利润目标”,就创建一个“追踪止损”。我正在尝试通过创建另一个函数(可能不需要)来实现此目的,该函数将不断检查“出价”和“询问”,但只会将值赋给变量“出价”或“询问”高于该变量的当前高位。这样,如果股票期权的当前价格比当天的“高买价”或“高卖价”低20%,我就可以将其合并到Main函数中并关闭转移。

这是否需要“同时”运行另一个正在写入变量的脚本?本质上,我正在尝试让Go创建一个新变量,该变量仅在当前出价和要价高于当前与高出价和高要价变量关联的价格时才用价格更新。

我希望这是有道理的。为了帮助我完成此任务,我可以参考任何文档方向的想法。

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\n", bid)
            break
        } else if bid < stopLossPrice {
            //closeTrade()
            fmt.Printf("Closing trade for a loss, bid is: %f\n", 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 个答案:

没有答案