# 策略使用案例

## A. 案例1：帶有 AlertCondition() + Alert 手動設定的 MACD 腳本

要建立一個警報，需要定義觸發它的條件。這個條件可以基於各種因素，如價格、指標或自訂邏輯。以下使用 Pine Script 語言，以 MACD 技術指標作為範例。

```javascript
//@version=5
indicator('MACD Sample Script 1', overlay=true)

// Calculate MACD
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)

// Define the golden cross condition
goldenCross = ta.crossover(macdLine, signalLine)

// Define the death cross condition
deathCross = ta.crossunder(macdLine, signalLine)

// Use the alertcondition function to generate alerts
alertcondition(condition=goldenCross, title="MACD Golden Cross", message="")
alertcondition(condition=deathCross, title="MACD Death Cross", message="")
```

在這個例子中，我們首先使用 `ta.macd()` 函數計算 MACD 指標，該函數接受輸入序列（在本例中為收盤價）和 MACD 的參數（12、26、9）。然後我們分別使用 `ta.crossover()` 和 `ta.crossunder()` 函數定義了黃金交叉和死亡交叉的條件。當 MACD 線穿過信號線**上方**時，發生黃金交叉；而當 MACD 線穿過信號線**下方**時，發生死亡交叉。

***

## B. 案例2：帶有 Alert() 訊息嵌入的 MACD 腳本

不使用 `alertcondition()`，我們使用 `alert()` 函數在滿足條件時直接生成警報。

```javascript
//@version=5
indicator('MACD Sample Script 2', overlay=true)

// Calculate MACD
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)

// Define the golden cross condition
buySignal = ta.crossover(macdLine, signalLine)

// Define the death cross condition
sellSignal = ta.crossunder(macdLine, signalLine)

// Function to generate custom JSON payload
get警報訊息(action, instrument, signalToken, orderType, orderPriceOffset, investmentType, amount) =>
    str = '{'
    str := str + '"action": "' + action + '", '
    str := str + '"instrument": "' + instrument + '", '
    str := str + '"signalToken": "' + signalToken + '", '
    str := str + '"timestamp": "' + str.tostring(timenow) + '", '
    str := str + '"orderType": "' + orderType + '", '
    str := str + '"orderPriceOffset": "' + str.tostring(orderPriceOffset) + '", '
    str := str + '"investmentType": "' + investmentType + '", '
    str := str + '"amount": "' + str.tostring(amount) + '"'
    str := str + '}'
    str

var ALERTGRP_CRED = "BitFrog Alert - Credential"
signalToken = input("", "Signal Token", inline = "11", group = ALERTGRP_CRED)

var ALERTGRP_ENTER = "BitFrog Alert - ENTER Signal"

enterOrderType = input.string("market", "Order Type", options = ["market", "limit"], inline = "21", group = ALERTGRP_ENTER)
enterOrderPriceOffset = input.float(0, "Order Price Offset", minval = 0, maxval = 100, step = 0.01, inline = "21", group = ALERTGRP_ENTER)

enterInvestmentType = input.string("percentage_balance", "Investment Type", options = ["margin", "contract", "percentage_balance", "percentage_investment"], inline = "31", group = ALERTGRP_ENTER)
enterAmount = input.float(100, "Amount", minval = 0.01, inline = "31", group = ALERTGRP_ENTER)

var ALERTGRP_EXIT = "BitFrog Alert - EXIT Signal"

exitOrderType = input.string("market", "Order Type", options = ["market", "limit"], inline = "41", group = ALERTGRP_EXIT)
exitOrderPriceOffset = input.float(0, "Order Price Offset", minval = 0, maxval = 100, step = 0.01, inline = "41", group = ALERTGRP_EXIT)

exitInvestmentType = input.string("percentage_position", "Investment Type", options = ["percentage_position"], inline = "51", group = ALERTGRP_EXIT)
exitAmount = input.float(100, "Amount", minval = 0.01, maxval = 100, step = 0.01, inline = "51", group = ALERTGRP_EXIT)

if buySignal
    buy警報訊息 = get警報訊息(action = 'open_long', instrument = syminfo.ticker, signalToken = signalToken, orderType = enterOrderType, orderPriceOffset = enterOrderPriceOffset, investmentType = enterInvestmentType, amount = enterAmount)
    alert(buy警報訊息, freq = alert.freq_once_per_bar)

if sellSignal
    sell警報訊息 = get警報訊息(action='close'/action='open_short', instrument = syminfo.ticker, signalToken = signalToken, orderType = exitOrderType, orderPriceOffset = exitOrderPriceOffset, investmentType = exitInvestmentType, amount = exitAmount)
    alert(sell警報訊息, freq = alert.freq_once_per_bar)
```

`get警報訊息` 函數是為了生成一個客製化的 JSON 負載，來按照 BitFrog 訊息規格的格式發送警報。輸入包括 `signalToken`、`enterOrderType`、`enterOrderPriceOffset`、`enterInvestmentType`、`enterAmount`、`exitOrderType`、`exitOrderPriceOffset`、`exitInvestmentType` 和 `exitAmount`。這些輸入用於指定警報的訂單類型、價格偏移量、投資類型和金額。

然後，程式碼使用 `buySignal` 和 `sellSignal` 條件來檢查買入和賣出信號。如果發生買入信號，它透過呼叫帶有適當參數的 `get警報訊息` 函數生成買入警報訊息。警報訊息包括行動（`'open_long'`）、交易工具（當前的股票符號）、信號令牌和指定的輸入變數的資訊。同樣，如果發生賣出信號，它會使用 `get警報訊息` 函數生成賣出警報訊息，並使用 `alert()` 函數發送訊息。

> **作為使用者**，如果你想從 MACD 黃金交叉／死亡交叉切換到另一種邏輯，你需要做的就是更換 `buySignal` 和 `sellSignal` 的定義，其他所有的東西都可以直接複用。說得更直白一些，**如果你想改變買賣信號的判斷依據，只需要修改買賣信號的定義就行了，其他的都不用改**。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.bitfrog.io/zh-tw/jiao-yi-zhi-nan/ce-le-jiao-yi/ce-le-shi-yong-an-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
