-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmargin.go
More file actions
58 lines (55 loc) · 2.36 KB
/
Copy pathmargin.go
File metadata and controls
58 lines (55 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"context"
"fmt"
"github.com/antihax/optional"
"github.com/gate/gateapi-go/v7"
)
// MarginDemo uses the current isolated-margin borrow/repay contract, replacing removed P2P loan APIs.
func MarginDemo(ctx context.Context, client *gateapi.APIClient) error {
pair, currency := "BTC_USDT", "USDT"
market, _, err := client.MarginUniApi.GetUniCurrencyPair(ctx, pair)
if err != nil {
return fmt.Errorf("get margin market: %v", err)
}
if market.Status != "enabled" {
return fmt.Errorf("margin market %s is not enabled", pair)
}
amount, err := positiveAmount("minimum quote borrow amount", market.QuoteMinBorrowAmount)
if err != nil {
return err
}
// Repay-all is scoped to a pair/currency, not a loan ID. Refuse pre-existing debt to protect it.
loans, _, err := client.MarginUniApi.ListUniLoans(ctx, &gateapi.ListUniLoansOpts{
CurrencyPair: optional.NewString(pair), Currency: optional.NewString(currency), Limit: optional.NewInt32(1),
})
if err != nil {
return fmt.Errorf("check existing margin debt: %v", err)
}
if len(loans) != 0 {
return fmt.Errorf("use an isolated demo account without existing %s debt in %s", currency, pair)
}
borrowable, _, err := client.MarginUniApi.GetUniBorrowable(ctx, currency, pair)
if err != nil {
return fmt.Errorf("get margin borrowing capacity: %v", err)
}
capacity, err := parseAmount("borrowable amount", borrowable.Borrowable)
if err != nil {
return err
}
if capacity.LessThan(amount) {
return fmt.Errorf("insufficient margin collateral; fund the demo account first")
}
request := gateapi.CreateUniLoan{CurrencyPair: pair, Currency: currency, Amount: amount.String(), Type: "borrow"}
if _, err = client.MarginUniApi.CreateUniLoan(ctx, request); err != nil {
// A transport error can follow a successful borrow; do not automatically repeat a financial write.
return fmt.Errorf("borrow outcome requires checking %s/%s loan history before retrying: %v", pair, currency, err)
}
// Keep borrowed funds available for repayment; the old sell/lend flow used removed loan APIs.
request.Type, request.RepaidAll = "repay", true
if _, err = client.MarginUniApi.CreateUniLoan(ctx, request); err != nil {
return fmt.Errorf("repay failed; inspect and repay %s/%s debt including accrued interest: %v", pair, currency, err)
}
logger.Printf("borrowed and repaid %s %s in %s", amount.String(), currency, pair)
return nil
}