├── .github
├── FUNDING.yml
├── dependabot.yml
└── workflows
│ ├── lint.yml
│ └── release.yml
├── .gitignore
├── .golangci.yml
├── .idea
├── .gitignore
├── copyright
│ ├── profiles_settings.xml
│ └── tvbit_bot.xml
├── dictionaries
│ └── s01082.xml
├── modules.xml
├── tvbit-bot.iml
├── vcs.xml
└── watcherTasks.xml
├── .pre-commit-config.yaml
├── Dockerfile
├── LICENSE
├── README.md
├── cmd
└── main.go
├── example
└── curl.txt
├── go.mod
├── go.sum
├── pkg
├── adapter
│ ├── controllers
│ │ ├── error.go
│ │ └── tv_controller.go
│ ├── gateway
│ │ ├── bybit_repository.go
│ │ └── tv_repository.go
│ └── interfaces
│ │ └── context.go
├── domain
│ └── tv.go
├── external
│ ├── bybit
│ │ ├── bybit.go
│ │ └── config.go
│ ├── cron.go
│ ├── http.go
│ ├── init.go
│ ├── logging
│ │ ├── config.go
│ │ └── log.go
│ ├── mysql
│ │ ├── config.go
│ │ └── mysql.go
│ └── router.go
└── usecase
│ ├── interfaces
│ └── repositories.go
│ └── tv_interactor.go
└── utils
└── convert.go
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: rluisr
2 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: gomod
4 | directory: "/"
5 | schedule:
6 | interval: daily
7 | time: "20:00"
8 | open-pull-requests-limit: 10
9 | - package-ecosystem: "github-actions"
10 | directory: "/"
11 | schedule:
12 | interval: "weekly"
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: lint
2 |
3 | on:
4 | push:
5 | pull_request:
6 |
7 | jobs:
8 | golangci:
9 | name: lint
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v2
13 | - name: golangci-lint
14 | uses: golangci/golangci-lint-action@v2
15 | with:
16 | version: latest
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: release
2 |
3 | on:
4 | push:
5 | tags:
6 | - '*'
7 |
8 | jobs:
9 | container_release:
10 | name: Container Release
11 | runs-on: ubuntu-latest
12 | steps:
13 | - name: Checkout
14 | uses: actions/checkout@v3
15 |
16 | - name: Docker meta
17 | id: meta
18 | uses: docker/metadata-action@v5
19 | with:
20 | images: ghcr.io/rluisr/tvbit-bot
21 |
22 | - name: Go Build Cache for Docker
23 | uses: actions/cache@v3
24 | with:
25 | path: go-build-cache
26 | key: ${{ runner.os }}-go-build-cache-${{ hashFiles('**/go.sum') }}
27 |
28 | #- name: Set up QEMU
29 | # uses: docker/setup-qemu-action@v2
30 |
31 | - name: Set up Docker Buildx
32 | uses: docker/setup-buildx-action@v2
33 |
34 | - name: Login to GitHub Container Registry
35 | uses: docker/login-action@v3
36 | with:
37 | registry: ghcr.io
38 | username: ${{ github.actor }}
39 | password: ${{ secrets.GITHUB_TOKEN }}
40 |
41 | - name: inject go-build-cache into docker
42 | uses: reproducible-containers/buildkit-cache-dance@v2.1.2
43 | with:
44 | cache-source: go-build-cache
45 |
46 | - name: Build and push
47 | id: docker_build
48 | uses: docker/build-push-action@v5
49 | with:
50 | context: .
51 | file: ./Dockerfile
52 | #platforms: linux/amd64,linux/arm64
53 | platforms: linux/amd64
54 | tags: ${{ steps.meta.outputs.tags }}
55 | labels: ${{ steps.meta.outputs.labels }}
56 | push: ${{ github.event_name != 'pull_request' }}
57 | cache-from: type=gha
58 | cache-to: type=gha,mode=max
59 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .env
2 | .envrc
3 | cmd/gin-bin
4 | .idea
--------------------------------------------------------------------------------
/.golangci.yml:
--------------------------------------------------------------------------------
1 | # This code is licensed under the terms of the MIT license https://opensource.org/license/mit
2 | # Copyright (c) 2021 Marat Reymers
3 |
4 | ## Golden config for golangci-lint v1.55.2
5 | #
6 | # This is the best config for golangci-lint based on my experience and opinion.
7 | # It is very strict, but not extremely strict.
8 | # Feel free to adapt and change it for your needs.
9 |
10 | run:
11 | # Timeout for analysis, e.g. 30s, 5m.
12 | # Default: 1m
13 | timeout: 3m
14 |
15 |
16 | # This file contains only configs which differ from defaults.
17 | # All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml
18 | linters-settings:
19 | errcheck:
20 | # Report about not checking of errors in type assertions: `a := b.(MyStruct)`.
21 | # Such cases aren't reported by default.
22 | # Default: false
23 | check-type-assertions: true
24 |
25 | exhaustive:
26 | # Program elements to check for exhaustiveness.
27 | # Default: [ switch ]
28 | check:
29 | - switch
30 | - map
31 |
32 | exhaustruct:
33 | # List of regular expressions to exclude struct packages and names from check.
34 | # Default: []
35 | exclude:
36 | # std libs
37 | - "^net/http.Client$"
38 | - "^net/http.Cookie$"
39 | - "^net/http.Request$"
40 | - "^net/http.Response$"
41 | - "^net/http.Server$"
42 | - "^net/http.Transport$"
43 | - "^net/url.URL$"
44 | - "^os/exec.Cmd$"
45 | - "^reflect.StructField$"
46 | # public libs
47 | - "^github.com/Shopify/sarama.Config$"
48 | - "^github.com/Shopify/sarama.ProducerMessage$"
49 | - "^github.com/mitchellh/mapstructure.DecoderConfig$"
50 | - "^github.com/prometheus/client_golang/.+Opts$"
51 | - "^github.com/spf13/cobra.Command$"
52 | - "^github.com/spf13/cobra.CompletionOptions$"
53 | - "^github.com/stretchr/testify/mock.Mock$"
54 | - "^github.com/testcontainers/testcontainers-go.+Request$"
55 | - "^github.com/testcontainers/testcontainers-go.FromDockerfile$"
56 | - "^golang.org/x/tools/go/analysis.Analyzer$"
57 | - "^google.golang.org/protobuf/.+Options$"
58 | - "^gopkg.in/yaml.v3.Node$"
59 |
60 | gocritic:
61 | # Settings passed to gocritic.
62 | # The settings key is the name of a supported gocritic checker.
63 | # The list of supported checkers can be find in https://go-critic.github.io/overview.
64 | settings:
65 | captLocal:
66 | # Whether to restrict checker to params only.
67 | # Default: true
68 | paramsOnly: false
69 | underef:
70 | # Whether to skip (*x).method() calls where x is a pointer receiver.
71 | # Default: true
72 | skipRecvDeref: false
73 |
74 | gomodguard:
75 | blocked:
76 | # List of blocked modules.
77 | # Default: []
78 | modules:
79 | - github.com/golang/protobuf:
80 | recommendations:
81 | - google.golang.org/protobuf
82 | reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules"
83 | - github.com/satori/go.uuid:
84 | recommendations:
85 | - github.com/google/uuid
86 | reason: "satori's package is not maintained"
87 | - github.com/gofrs/uuid:
88 | recommendations:
89 | - github.com/google/uuid
90 | reason: "gofrs' package is not go module"
91 |
92 | govet:
93 | # Enable all analyzers.
94 | # Default: false
95 | enable-all: true
96 | # Disable analyzers by name.
97 | # Run `go tool vet help` to see all analyzers.
98 | # Default: []
99 | disable:
100 | - fieldalignment # too strict
101 | # Settings per analyzer.
102 | settings:
103 | shadow:
104 | # Whether to be strict about shadowing; can be noisy.
105 | # Default: false
106 | strict: true
107 |
108 | nakedret:
109 | # Make an issue if func has more lines of code than this setting, and it has naked returns.
110 | # Default: 30
111 | max-func-lines: 0
112 |
113 | nolintlint:
114 | # Exclude following linters from requiring an explanation.
115 | # Default: []
116 | # Enable to require an explanation of nonzero length after each nolint directive.
117 | # Default: false
118 | require-explanation: true
119 | # Enable to require nolint directives to mention the specific linter being suppressed.
120 | # Default: false
121 | require-specific: true
122 |
123 | rowserrcheck:
124 | # database/sql is always checked
125 | # Default: []
126 | packages:
127 | - github.com/jmoiron/sqlx
128 |
129 | tenv:
130 | # The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures.
131 | # Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked.
132 | # Default: false
133 | all: true
134 |
135 |
136 | linters:
137 | disable-all: true
138 | enable:
139 | ## enabled by default
140 | - errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases
141 | - gosimple # specializes in simplifying a code
142 | - govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
143 | - ineffassign # detects when assignments to existing variables are not used
144 | - staticcheck # is a go vet on steroids, applying a ton of static analysis checks
145 | - typecheck # like the front-end of a Go compiler, parses and type-checks Go code
146 | - unused # checks for unused constants, variables, functions and types
147 | ## disabled by default
148 | - asasalint # checks for pass []any as any in variadic func(...any)
149 | - asciicheck # checks that your code does not contain non-ASCII identifiers
150 | - bidichk # checks for dangerous unicode character sequences
151 | - bodyclose # checks whether HTTP response body is closed successfully
152 | - dupl # tool for code clone detection
153 | - durationcheck # checks for two durations multiplied together
154 | - errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error
155 | - errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13
156 | - execinquery # checks query string in Query function which reads your Go src files and warning it finds
157 | - exhaustive # checks exhaustiveness of enum switch statements
158 | - exportloopref # checks for pointers to enclosing loop variables
159 | - forbidigo # forbids identifiers
160 | - gocheckcompilerdirectives # validates go compiler directive comments (//go:)
161 | - gochecknoinits # checks that no init functions are present in Go code
162 | - gochecksumtype # checks exhaustiveness on Go "sum types"
163 | - goconst # finds repeated strings that could be replaced by a constant
164 | - gocritic # provides diagnostics that check for bugs, performance and style issues
165 | - goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt
166 | - gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod
167 | - gomodguard # allow and block lists linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations
168 | - goprintffuncname # checks that printf-like functions are named with f at the end
169 | - gosec # inspects source code for security problems
170 | - loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap)
171 | - makezero # finds slice declarations with non-zero initial length
172 | - mirror # reports wrong mirror patterns of bytes/strings usage
173 | - musttag # enforces field tags in (un)marshaled structs
174 | - nakedret # finds naked returns in functions greater than a specified function length
175 | - nilerr # finds the code that returns nil even if it checks that the error is not nil
176 | - nilnil # checks that there is no simultaneous return of nil error and an invalid value
177 | - noctx # finds sending http request without context.Context
178 | - nolintlint # reports ill-formed or insufficient nolint directives
179 | - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL
180 | - perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative
181 | - predeclared # finds code that shadows one of Go's predeclared identifiers
182 | - promlinter # checks Prometheus metrics naming via promlint
183 | - protogetter # reports direct reads from proto message fields when getters should be used
184 | - reassign # checks that package variables are not reassigned
185 | - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint
186 | - rowserrcheck # checks whether Err of rows is checked successfully
187 | - sloglint # ensure consistent code style when using log/slog
188 | - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed
189 | - stylecheck # is a replacement for golint
190 | - tenv # detects using os.Setenv instead of t.Setenv since Go1.17
191 | - testableexamples # checks if examples are testable (have an expected output)
192 | - testifylint # checks usage of github.com/stretchr/testify
193 | - testpackage # makes you use a separate _test package
194 | - tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes
195 | - unconvert # removes unnecessary type conversions
196 | - unparam # reports unused function parameters
197 | - usestdlibvars # detects the possibility to use variables/constants from the Go standard library
198 | - wastedassign # finds wasted assignment statements
199 | - whitespace # detects leading and trailing whitespace
200 |
201 | ## you may want to enable
202 | #- decorder # checks declaration order and count of types, constants, variables and functions
203 | #- exhaustruct # [highly recommend to enable] checks if all structure fields are initialized
204 | #- gci # controls golang package import order and makes it always deterministic
205 | #- ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega
206 | #- godox # detects FIXME, TODO and other comment keywords
207 | #- goheader # checks is file header matches to pattern
208 | #- inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters
209 | #- interfacebloat # checks the number of methods inside an interface
210 | #- ireturn # accept interfaces, return concrete types
211 | #- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated
212 | #- tagalign # checks that struct tags are well aligned
213 | #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope
214 | #- wrapcheck # checks that errors returned from external packages are wrapped
215 | #- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event
216 |
217 | ## disabled
218 | #- containedctx # detects struct contained context.Context field
219 | #- contextcheck # [too many false positives] checks the function whether use a non-inherited context
220 | #- depguard # [replaced by gomodguard] checks if package imports are in a list of acceptable packages
221 | #- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
222 | #- dupword # [useless without config] checks for duplicate words in the source code
223 | #- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted
224 | #- forcetypeassert # [replaced by errcheck] finds forced type assertions
225 | #- goerr113 # [too strict] checks the errors handling expressions
226 | #- gofmt # [replaced by goimports] checks whether code was gofmt-ed
227 | #- gofumpt # [replaced by goimports, gofumports is not available yet] checks whether code was gofumpt-ed
228 | #- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase
229 | #- grouper # analyzes expression groups
230 | #- importas # enforces consistent import aliases
231 | #- maintidx # measures the maintainability index of each function
232 | #- misspell # [useless] finds commonly misspelled English words in comments
233 | #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity
234 | #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test
235 | #- tagliatelle # checks the struct tags
236 | #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers
237 | #- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines
238 |
239 | ## deprecated
240 | #- deadcode # [deprecated, replaced by unused] finds unused code
241 | #- exhaustivestruct # [deprecated, replaced by exhaustruct] checks if all struct's fields are initialized
242 | #- golint # [deprecated, replaced by revive] golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
243 | #- ifshort # [deprecated] checks that your code uses short syntax for if-statements whenever possible
244 | #- interfacer # [deprecated] suggests narrower interface types
245 | #- maligned # [deprecated, replaced by govet fieldalignment] detects Go structs that would take less memory if their fields were sorted
246 | #- nosnakecase # [deprecated, replaced by revive var-naming] detects snake case of variable naming and function name
247 | #- scopelint # [deprecated, replaced by exportloopref] checks for unpinned variables in go programs
248 | #- structcheck # [deprecated, replaced by unused] finds unused struct fields
249 | #- varcheck # [deprecated, replaced by unused] finds unused global variables and constants
250 |
251 |
252 | issues:
253 | # Maximum count of issues with the same text.
254 | # Set to 0 to disable.
255 | # Default: 3
256 | max-same-issues: 50
257 |
258 | exclude-rules:
259 | - source: "//noinspection"
260 | linters: [ gocritic ]
261 | - path: "_test\\.go"
262 | linters:
263 | - bodyclose
264 | - dupl
265 | - goconst
266 | - gosec
267 | - noctx
268 | - wrapcheck
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # デフォルトの無視対象ファイル
2 | /shelf/
3 | /workspace.xml
4 | # エディターベースの HTTP クライアントリクエスト
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/copyright/tvbit_bot.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/dictionaries/s01082.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | bybit
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/tvbit-bot.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/watcherTasks.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/golangci/golangci-lint
3 | rev: master
4 | hooks:
5 | - id: golangci-lint-full
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # syntax = docker/dockerfile:1.3-labs
2 |
3 | ARG APP_NAME="tvbit-bot"
4 |
5 | FROM golang:1 as builder
6 |
7 | WORKDIR /go/src/${APP_NAME}
8 | RUN go env -w GOMODCACHE=/root/.cache/go-build
9 |
10 | COPY go.mod go.sum ./
11 | RUN --mount=type=cache,target=/root/.cache/go-build go mod download
12 |
13 | COPY . .
14 | RUN --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 GOOS=linux go build -o /app cmd/main.go
15 |
16 | FROM gcr.io/distroless/static-debian12 as production
17 |
18 | LABEL maintainer="rluisr" \
19 | org.opencontainers.image.url="https://github.com/rluisr/tvbit-bot" \
20 | org.opencontainers.image.source="https://github.com/rluisr/tvbit-bot" \
21 | org.opencontainers.image.vendor="rluisr" \
22 | org.opencontainers.image.title="tvbit-bot" \
23 | org.opencontainers.image.description="TradingView webhook handler for Bybit." \
24 | org.opencontainers.image.licenses="AGPL"
25 |
26 | COPY --from=builder /app /app
27 | ENTRYPOINT ["/app"]
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | tvbit-bot
2 | ============
3 |
4 | [](https://github.com/rluisr/tvbit-bot/actions/workflows/release.yml)
5 | [](https://github.com/rluisr/tvbit-bot/actions/workflows/lint.yml)
6 |
7 | tvbit-bot is TradingView webhook handler for Bybit.
8 |
9 | tvbit = T(rading)V(iew) (By)bit
10 |
11 | Twitter [@rarirureluis](https://twitter.com/rarirureluis)
12 |
13 | Introduction
14 | -------------
15 |
16 | 1. Set an alert with webhook and a message as JSON like below:
17 |
18 | ```json
19 | {
20 | "name": "alert name, description or something",
21 | "symbol": "BTCUSDT",
22 | "type": "Market",
23 | "price": "0",
24 | // If type is "Limit" set it as an int greater than 0
25 | "side": "Buy",
26 | "qty": "0.014",
27 | "tp": "0",
28 | // see below
29 | "sl": "{{high}}"
30 | // see below
31 | }
32 | ```
33 |
34 | more details, see [curl.txt](example/curl.txt)
35 |
36 | ### TP and SL
37 |
38 | You have to set `tp` and `sl` as a string.
39 |
40 | - `{{high}}` is an embedded value of TradingView, Also you can set any other TradingView's embedded values.
41 | - Other methods, you can set as a percent like `"tp": "10%"` calculate from mark price.
42 | - `"tp": "+40", "sl": "-20"` means, `TP: mark price + 40` and `SL: mark price - 20`.
43 |
44 | see [tv.go](pkg/domain/tv.go)
45 | or [Bybit API Documentation](https://bybit-exchange.github.io/docs/linear/#:~:text=Transaction%20timestamp-,order,-How%20to%20Subscribe)
46 |
47 | Path
48 | -----
49 |
50 | | Path | Method | Description |
51 | |----------|--------|-------------------------|
52 | | /tv | POST | Create order |
53 |
54 |
55 | Setup
56 | -----
57 |
58 | You have to set environment variables
59 |
60 | - [bybit](pkg/external/bybit/config.go)
61 | - [mysql](pkg/external/mysql/config.go)
62 |
63 | ### Container
64 |
65 | `ghcr.io/rluisr/tvbit-bot:latest`
66 |
67 | ### MySQL
68 |
69 | tvbit-bot saves the order history to MySQL.
70 |
71 | Limitation
72 | ----------
73 |
74 | tvbit-bot does not support to close/cancel positions, recommend to use TP/SL.
75 |
76 | Welcome your PR.
77 |
78 | Twitter [@rarirureluis](https://twitter.com/rarirureluis)
79 |
--------------------------------------------------------------------------------
/cmd/main.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package main
20 |
21 | import (
22 | "fmt"
23 |
24 | "github.com/rluisr/tvbit-bot/pkg/external"
25 | "github.com/rluisr/tvbit-bot/pkg/external/mysql"
26 | )
27 |
28 | const (
29 | SOURCE = "tvbit-bot"
30 | )
31 |
32 | func main() {
33 | defer mysql.CloseConn()
34 |
35 | err := external.Init(SOURCE)
36 | if err != nil {
37 | panic(fmt.Errorf("failed to initialization %w", err))
38 | }
39 |
40 | go external.Cron()
41 |
42 | external.Run(SOURCE)
43 | }
44 |
--------------------------------------------------------------------------------
/example/curl.txt:
--------------------------------------------------------------------------------
1 | POST /tv
2 |
3 | TP/SL: price
4 | curl -s -XPOST -H "Content-Type: application/json" -d '{ "name": "test", "symbol": "BTCUSDT", "type": "Market", "price": 0, "side": "Sell", "qty": 0.03, "tp": "-1000", "sl": "+1000" }' http://localhost:3001/tv
5 |
6 | TP/SL: percent
7 | curl -s -XPOST -H "Content-Type: application/json" -d '{ "name": "test", "symbol": "BTCUSDT", "type": "Market", "price": "0", "side": "Buy", "qty": "0.01", "tp": "1%", "sl": "5%" }' http://localhost:3001/tv
8 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/rluisr/tvbit-bot
2 |
3 | go 1.21
4 |
5 | require (
6 | github.com/Netflix/go-env v0.0.0-20220526054621-78278af1949d
7 | github.com/gin-gonic/gin v1.9.1
8 | github.com/go-co-op/gocron/v2 v2.2.4
9 | github.com/hirokisan/bybit/v2 v2.29.0
10 | github.com/ic2hrmk/promtail v0.0.5
11 | github.com/shopspring/decimal v1.3.1
12 | go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.48.0
13 | go.opentelemetry.io/otel v1.23.1
14 | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.23.1
15 | go.opentelemetry.io/otel/sdk v1.23.1
16 | gorm.io/driver/mysql v1.5.4
17 | gorm.io/gorm v1.25.7
18 | gorm.io/plugin/opentelemetry v0.1.4
19 | )
20 |
21 | require (
22 | github.com/bytedance/sonic v1.10.2 // indirect
23 | github.com/cenkalti/backoff/v4 v4.2.1 // indirect
24 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
25 | github.com/chenzhuoyu/iasm v0.9.1 // indirect
26 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
27 | github.com/gabriel-vasile/mimetype v1.4.3 // indirect
28 | github.com/gin-contrib/sse v0.1.0 // indirect
29 | github.com/go-logr/logr v1.4.1 // indirect
30 | github.com/go-logr/stdr v1.2.2 // indirect
31 | github.com/go-playground/locales v0.14.1 // indirect
32 | github.com/go-playground/universal-translator v0.18.1 // indirect
33 | github.com/go-playground/validator/v10 v10.18.0 // indirect
34 | github.com/go-sql-driver/mysql v1.7.1 // indirect
35 | github.com/goccy/go-json v0.10.2 // indirect
36 | github.com/golang/protobuf v1.5.3 // indirect
37 | github.com/google/go-querystring v1.1.0 // indirect
38 | github.com/google/uuid v1.6.0 // indirect
39 | github.com/gorilla/websocket v1.5.1 // indirect
40 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 // indirect
41 | github.com/jinzhu/inflection v1.0.0 // indirect
42 | github.com/jinzhu/now v1.1.5 // indirect
43 | github.com/jonboulle/clockwork v0.4.0 // indirect
44 | github.com/json-iterator/go v1.1.12 // indirect
45 | github.com/klauspost/cpuid/v2 v2.2.6 // indirect
46 | github.com/leodido/go-urn v1.4.0 // indirect
47 | github.com/mattn/go-isatty v0.0.20 // indirect
48 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
49 | github.com/modern-go/reflect2 v1.0.2 // indirect
50 | github.com/pelletier/go-toml/v2 v2.1.1 // indirect
51 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
52 | github.com/robfig/cron/v3 v3.0.1 // indirect
53 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
54 | github.com/ugorji/go/codec v1.2.12 // indirect
55 | go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.23.1 // indirect
56 | go.opentelemetry.io/otel/metric v1.23.1 // indirect
57 | go.opentelemetry.io/otel/trace v1.23.1 // indirect
58 | go.opentelemetry.io/proto/otlp v1.1.0 // indirect
59 | golang.org/x/arch v0.7.0 // indirect
60 | golang.org/x/crypto v0.19.0 // indirect
61 | golang.org/x/exp v0.0.0-20240213143201-ec583247a57a // indirect
62 | golang.org/x/net v0.21.0 // indirect
63 | golang.org/x/sys v0.17.0 // indirect
64 | golang.org/x/text v0.14.0 // indirect
65 | google.golang.org/genproto/googleapis/api v0.0.0-20240213162025-012b6fc9bca9 // indirect
66 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240213162025-012b6fc9bca9 // indirect
67 | google.golang.org/grpc v1.61.1 // indirect
68 | google.golang.org/protobuf v1.32.0 // indirect
69 | gopkg.in/yaml.v3 v3.0.1 // indirect
70 | )
71 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/Netflix/go-env v0.0.0-20220526054621-78278af1949d h1:wvStE9wLpws31NiWUx+38wny1msZ/tm+eL5xmm4Y7So=
2 | github.com/Netflix/go-env v0.0.0-20220526054621-78278af1949d/go.mod h1:9XMFaCeRyW7fC9XJOWQ+NdAv8VLG7ys7l3x4ozEGLUQ=
3 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
4 | github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
5 | github.com/bytedance/sonic v1.10.2 h1:GQebETVBxYB7JGWJtLBi07OVzWwt+8dWA00gEVW2ZFE=
6 | github.com/bytedance/sonic v1.10.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
7 | github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=
8 | github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
9 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
10 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
11 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
12 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=
13 | github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
14 | github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0=
15 | github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
16 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
17 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
18 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
19 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
20 | github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
21 | github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
22 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
23 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
24 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
25 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
26 | github.com/go-co-op/gocron/v2 v2.2.4 h1:fL6a8/U+BJQ9UbaeqKxua8wY02w4ftKZsxPzLSNOCKk=
27 | github.com/go-co-op/gocron/v2 v2.2.4/go.mod h1:igssOwzZkfcnu3m2kwnCf/mYj4SmhP9ecSgmYjCOHkk=
28 | github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
29 | github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
30 | github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
31 | github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
32 | github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
33 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
34 | github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
35 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
36 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
37 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
38 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
39 | github.com/go-playground/validator/v10 v10.18.0 h1:BvolUXjp4zuvkZ5YN5t7ebzbhlUtPsPm2S9NAZ5nl9U=
40 | github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
41 | github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
42 | github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
43 | github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
44 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
45 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
46 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
47 | github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
48 | github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
49 | github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
50 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
51 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
52 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
53 | github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
54 | github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
55 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
56 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
57 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
58 | github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
59 | github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
60 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.0 h1:Wqo399gCIufwto+VfwCSvsnfGpF/w5E9CNxSwbpD6No=
61 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.0/go.mod h1:qmOFXW2epJhM0qSnUUYpldc7gVz2KMQwJ/QYCDIa7XU=
62 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 h1:/c3QmbOGMGTOumP2iT/rCwB7b0QDGLKzqOmktBjT+Is=
63 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1/go.mod h1:5SN9VR2LTsRFsrEC6FHgRbTWrTHu6tqPeKxEQv15giM=
64 | github.com/hirokisan/bybit/v2 v2.28.5 h1:NfyKf6KRmRx/pz3fWe4zQw+ZzCMqeOcHZhC5ChN9l5k=
65 | github.com/hirokisan/bybit/v2 v2.28.5/go.mod h1:u+BQHdXZQ/lZSV+6p6ZNiHTgAVEjAOq6Me/onG3lBOE=
66 | github.com/hirokisan/bybit/v2 v2.29.0 h1:eLVW4dD/HBKGb8eaxRSc9tcfW4eX1EJ6WNuiVlDB2Yg=
67 | github.com/hirokisan/bybit/v2 v2.29.0/go.mod h1:cRtDPA0uGcRWiAouCJxQlsx/Jx0/xrtHLwtWhO/sohk=
68 | github.com/ic2hrmk/promtail v0.0.5 h1:sU+PdDMONGuP4co2tosFeJJuQDwxOpbNUJv3yb866Qo=
69 | github.com/ic2hrmk/promtail v0.0.5/go.mod h1:MIkZC9eMW2duQsA1z3tRTBSc3WgMjTilq70AeyqvJMo=
70 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
71 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
72 | github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
73 | github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
74 | github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4=
75 | github.com/jonboulle/clockwork v0.4.0/go.mod h1:xgRqUGwRcjKCO1vbZUEtSLrqKoPSsUpK7fnezOII0kc=
76 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
77 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
78 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
79 | github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc=
80 | github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
81 | github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
82 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
83 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
84 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
85 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
86 | github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
87 | github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
88 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
89 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
90 | github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
91 | github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
92 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
93 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
94 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
95 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
96 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
97 | github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
98 | github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
99 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
100 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
101 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
102 | github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
103 | github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
104 | github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
105 | github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
106 | github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8=
107 | github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
108 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
109 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
110 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
111 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
112 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
113 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
114 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
115 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
116 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
117 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
118 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
119 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
120 | github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
121 | github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
122 | go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.48.0 h1:9fRyGkm/rbLuNNJsk9YY2c7Tpjf9tRjm1BAa48L3ypU=
123 | go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.48.0/go.mod h1:7eRxLMX2ua+Pwtw1lkj8L0i0aykVQ/CafXhARYY056k=
124 | go.opentelemetry.io/contrib/propagators/b3 v1.23.0 h1:aaIGWc5JdfRGpCafLRxMJbD65MfTa206AwSKkvGS0Hg=
125 | go.opentelemetry.io/contrib/propagators/b3 v1.23.0/go.mod h1:Gyz7V7XghvwTq+mIhLFlTgcc03UDroOg8vezs4NLhwU=
126 | go.opentelemetry.io/otel v1.23.1 h1:Za4UzOqJYS+MUczKI320AtqZHZb7EqxO00jAHE0jmQY=
127 | go.opentelemetry.io/otel v1.23.1/go.mod h1:Td0134eafDLcTS4y+zQ26GE8u3dEuRBiBCTUIRHaikA=
128 | go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.23.1 h1:o8iWeVFa1BcLtVEV0LzrCxV2/55tB3xLxADr6Kyoey4=
129 | go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.23.1/go.mod h1:SEVfdK4IoBnbT2FXNM/k8yC08MrfbhWk3U4ljM8B3HE=
130 | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.23.1 h1:cfuy3bXmLJS7M1RZmAL6SuhGtKUp2KEsrm00OlAXkq4=
131 | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.23.1/go.mod h1:22jr92C6KwlwItJmQzfixzQM3oyyuYLCfHiMY+rpsPU=
132 | go.opentelemetry.io/otel/metric v1.23.1 h1:PQJmqJ9u2QaJLBOELl1cxIdPcpbwzbkjfEyelTl2rlo=
133 | go.opentelemetry.io/otel/metric v1.23.1/go.mod h1:mpG2QPlAfnK8yNhNJAxDZruU9Y1/HubbC+KyH8FaCWI=
134 | go.opentelemetry.io/otel/sdk v1.23.1 h1:O7JmZw0h76if63LQdsBMKQDWNb5oEcOThG9IrxscV+E=
135 | go.opentelemetry.io/otel/sdk v1.23.1/go.mod h1:LzdEVR5am1uKOOwfBWFef2DCi1nu3SA8XQxx2IerWFk=
136 | go.opentelemetry.io/otel/trace v1.23.1 h1:4LrmmEd8AU2rFvU1zegmvqW7+kWarxtNOPyeL6HmYY8=
137 | go.opentelemetry.io/otel/trace v1.23.1/go.mod h1:4IpnpJFwr1mo/6HL8XIPJaE9y0+u1KcVmuW7dwFSVrI=
138 | go.opentelemetry.io/proto/otlp v1.1.0 h1:2Di21piLrCqJ3U3eXGCTPHE9R8Nh+0uglSnOyxikMeI=
139 | go.opentelemetry.io/proto/otlp v1.1.0/go.mod h1:GpBHCBWiqvVLDqmHZsoMM3C5ySeKTC7ej/RNTae6MdY=
140 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
141 | go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
142 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
143 | golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
144 | golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
145 | golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
146 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
147 | golang.org/x/exp v0.0.0-20231219180239-dc181d75b848 h1:+iq7lrkxmFNBM7xx+Rae2W6uyPfhPeDWD+n+JgppptE=
148 | golang.org/x/exp v0.0.0-20231219180239-dc181d75b848/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI=
149 | golang.org/x/exp v0.0.0-20240213143201-ec583247a57a h1:HinSgX1tJRX3KsL//Gxynpw5CTOAIPhgL4W8PNiIpVE=
150 | golang.org/x/exp v0.0.0-20240213143201-ec583247a57a/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc=
151 | golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
152 | golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
153 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
154 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
155 | golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
156 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
157 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
158 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
159 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
160 | google.golang.org/genproto v0.0.0-20231212172506-995d672761c0 h1:YJ5pD9rF8o9Qtta0Cmy9rdBwkSjrTCT6XTiUQVOtIos=
161 | google.golang.org/genproto v0.0.0-20231212172506-995d672761c0/go.mod h1:l/k7rMz0vFTBPy+tFSGvXEd3z+BcoG1k7EHbqm+YBsY=
162 | google.golang.org/genproto/googleapis/api v0.0.0-20240102182953-50ed04b92917 h1:rcS6EyEaoCO52hQDupoSfrxI3R6C2Tq741is7X8OvnM=
163 | google.golang.org/genproto/googleapis/api v0.0.0-20240102182953-50ed04b92917/go.mod h1:CmlNWB9lSezaYELKS5Ym1r44VrrbPUa7JTvw+6MbpJ0=
164 | google.golang.org/genproto/googleapis/api v0.0.0-20240213162025-012b6fc9bca9 h1:4++qSzdWBUy9/2x8L5KZgwZw+mjJZ2yDSCGMVM0YzRs=
165 | google.golang.org/genproto/googleapis/api v0.0.0-20240213162025-012b6fc9bca9/go.mod h1:PVreiBMirk8ypES6aw9d4p6iiBNSIfZEBqr3UGoAi2E=
166 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240102182953-50ed04b92917 h1:6G8oQ016D88m1xAKljMlBOOGWDZkes4kMhgGFlf8WcQ=
167 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240102182953-50ed04b92917/go.mod h1:xtjpI3tXFPP051KaWnhvxkiubL/6dJ18vLVf7q2pTOU=
168 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240213162025-012b6fc9bca9 h1:hZB7eLIaYlW9qXRfCq/qDaPdbeY3757uARz5Vvfv+cY=
169 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240213162025-012b6fc9bca9/go.mod h1:YUWgXUFRPfoYK1IHMuxH5K6nPEXSCzIMljnQ59lLRCk=
170 | google.golang.org/grpc v1.61.0 h1:TOvOcuXn30kRao+gfcvsebNEa5iZIiLkisYEkf7R7o0=
171 | google.golang.org/grpc v1.61.0/go.mod h1:VUbo7IFqmF1QtCAstipjG0GIoq49KvMe9+h1jFLBNJs=
172 | google.golang.org/grpc v1.61.1 h1:kLAiWrZs7YeDM6MumDe7m3y4aM6wacLzM1Y/wiLP9XY=
173 | google.golang.org/grpc v1.61.1/go.mod h1:VUbo7IFqmF1QtCAstipjG0GIoq49KvMe9+h1jFLBNJs=
174 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
175 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
176 | google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
177 | google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
178 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
179 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
180 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
181 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
182 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
183 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
184 | gorm.io/driver/mysql v1.5.4 h1:igQmHfKcbaTVyAIHNhhB888vvxh8EdQ2uSUT0LPcBso=
185 | gorm.io/driver/mysql v1.5.4/go.mod h1:9rYxJph/u9SWkWc9yY4XJ1F/+xO0S/ChOmbk3+Z5Tvs=
186 | gorm.io/driver/sqlite v1.5.0 h1:zKYbzRCpBrT1bNijRnxLDJWPjVfImGEn0lSnUY5gZ+c=
187 | gorm.io/driver/sqlite v1.5.0/go.mod h1:kDMDfntV9u/vuMmz8APHtHF0b4nyBB7sfCieC6G8k8I=
188 | gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
189 | gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
190 | gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
191 | gorm.io/plugin/opentelemetry v0.1.4 h1:7p0ocWELjSSRI7NCKPW2mVe6h43YPini99sNJcbsTuc=
192 | gorm.io/plugin/opentelemetry v0.1.4/go.mod h1:tndJHOdvPT0pyGhOb8E2209eXJCUxhC5UpKw7bGVWeI=
193 | nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
194 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
195 |
--------------------------------------------------------------------------------
/pkg/adapter/controllers/error.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package controllers
20 |
21 | type Error struct {
22 | Code int `json:"code"`
23 | Message string `json:"message"`
24 | Error error `json:"-"`
25 | }
26 |
27 | func NewError(code int, err error) *Error {
28 | newErr := &Error{
29 | Code: code,
30 | Message: err.Error(),
31 | Error: err,
32 | }
33 |
34 | return newErr
35 | }
36 |
--------------------------------------------------------------------------------
/pkg/adapter/controllers/tv_controller.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package controllers
20 |
21 | import (
22 | "net/http"
23 | "time"
24 |
25 | "github.com/gin-gonic/gin"
26 | "github.com/hirokisan/bybit/v2"
27 | "github.com/rluisr/tvbit-bot/pkg/adapter/gateway"
28 | "github.com/rluisr/tvbit-bot/pkg/external/logging"
29 | "github.com/rluisr/tvbit-bot/pkg/usecase"
30 | "gorm.io/gorm"
31 | )
32 |
33 | type TVController struct {
34 | Interactor usecase.TVInteractor
35 | }
36 |
37 | func NewTVController(log *logging.Logging, rwDB, roDB *gorm.DB, bybitClient *bybit.Client) *TVController {
38 | return &TVController{
39 | Interactor: usecase.TVInteractor{
40 | TVRepository: &gateway.TVRepository{
41 | RWDB: rwDB,
42 | RODB: roDB,
43 | Log: log,
44 | },
45 | BybitRepository: &gateway.BybitRepository{
46 | Client: bybitClient,
47 | },
48 | },
49 | }
50 | }
51 |
52 | func (controller *TVController) Handle(c *gin.Context) {
53 | order, err := controller.Interactor.CreateOrder(c)
54 | if err != nil {
55 | c.JSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err))
56 | controller.Interactor.TVRepository.Logging().Error("CreateOrder", err.Error(), err)
57 | return
58 | }
59 |
60 | c.JSON(200, order)
61 | }
62 |
63 | // FetchOrder は PL が 0 のままになっている注文の PL を取得する
64 | func (controller *TVController) FetchOrder() error {
65 | return controller.Interactor.FetchPL()
66 | }
67 |
68 | func (controller *TVController) InventoryCheck(cancelAfter time.Duration) error {
69 | return controller.Interactor.InventoryCheck(cancelAfter)
70 | }
71 |
--------------------------------------------------------------------------------
/pkg/adapter/gateway/bybit_repository.go:
--------------------------------------------------------------------------------
1 | package gateway
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "net/http"
7 | "strconv"
8 | "strings"
9 | "time"
10 |
11 | "github.com/hirokisan/bybit/v2"
12 | "github.com/rluisr/tvbit-bot/pkg/domain"
13 | "github.com/rluisr/tvbit-bot/utils"
14 | "github.com/shopspring/decimal"
15 | )
16 |
17 | type (
18 | BybitRepository struct {
19 | BaseURL string
20 | APIKey string
21 | APISecretKey string
22 | HTTPClient *http.Client
23 | Client *bybit.Client
24 | }
25 | )
26 |
27 | func (r *BybitRepository) CreateOrder(req *domain.Order) error {
28 | orderParam := bybit.V5CreateOrderParam{
29 | Category: bybit.CategoryV5Linear,
30 | OrderType: bybit.OrderTypeMarket,
31 | Symbol: bybit.SymbolV5(req.Symbol),
32 | Qty: req.QTY,
33 | TakeProfit: &req.TP,
34 | StopLoss: &req.SL,
35 | Side: bybit.Side(req.Side),
36 | }
37 |
38 | if req.Type == "Limit" {
39 | // 10001, timeInForce invalid
40 | // tif := bybit.TimeInForceImmediateOrCancel
41 | // orderParam.TimeInForce = &tif
42 |
43 | orderParam.OrderType = bybit.OrderTypeLimit
44 | orderParam.Price = &req.Price
45 | }
46 |
47 | if req.Side == "Buy" {
48 | buyHedge := bybit.PositionIdxHedgeBuy
49 | orderParam.PositionIdx = &buyHedge
50 | } else {
51 | sellHedge := bybit.PositionIdxHedgeSell
52 | orderParam.PositionIdx = &sellHedge
53 | }
54 |
55 | resp, err := r.Client.V5().Order().CreateOrder(orderParam)
56 | if err != nil {
57 | return fmt.Errorf("failed CreateOrder: %w", err)
58 | }
59 | req.OrderID = resp.Result.OrderID
60 |
61 | return nil
62 | }
63 |
64 | func (r *BybitRepository) CancelOrder(req *domain.Order) error {
65 | _, err := r.Client.V5().Order().CancelOrder(bybit.V5CancelOrderParam{
66 | Category: bybit.CategoryV5Linear,
67 | Symbol: bybit.SymbolV5(req.Symbol),
68 | OrderID: &req.OrderID,
69 | })
70 |
71 | return err
72 | }
73 |
74 | func (r *BybitRepository) FetchOpenOrder(req *domain.Order) error {
75 | symbol := bybit.SymbolV5(req.Symbol)
76 | settle := bybit.CoinUSDT
77 |
78 | for i := 0; i < 10; i++ {
79 | order, err := r.Client.V5().Order().GetOpenOrders(bybit.V5GetOpenOrdersParam{
80 | Category: bybit.CategoryV5Linear,
81 | Symbol: &symbol,
82 | OrderID: &req.OrderID,
83 | SettleCoin: &settle,
84 | })
85 | if err != nil {
86 | if strings.Contains(err.Error(), "does not exist") {
87 | continue
88 | }
89 | return fmt.Errorf("failed GetOrder: %w", err)
90 | }
91 |
92 | if len(order.Result.List) == 0 {
93 | time.Sleep(1 * time.Second)
94 | continue
95 | }
96 |
97 | var entryPriceStr string
98 | if req.Type == "Market" {
99 | entryPriceStr = order.Result.List[0].AvgPrice
100 | } else {
101 | entryPriceStr = req.Price
102 | }
103 |
104 | entryPrice, err := decimal.NewFromString(entryPriceStr)
105 | if err != nil {
106 | return err
107 | }
108 |
109 | req.EntryPrice = entryPrice
110 | break
111 | }
112 |
113 | return nil
114 | }
115 |
116 | func (r *BybitRepository) GetOpenOrders() (*bybit.V5GetOrdersResponse, error) {
117 | settle := bybit.CoinUSDT
118 |
119 | orders, err := r.Client.V5().Order().GetOpenOrders(bybit.V5GetOpenOrdersParam{
120 | Category: bybit.CategoryV5Linear,
121 | SettleCoin: &settle,
122 | })
123 | if err != nil {
124 | return nil, fmt.Errorf("failed GetOpenOrders: %w", err)
125 | }
126 |
127 | return orders, nil
128 | }
129 |
130 | func (r *BybitRepository) GetClosedPNL(param bybit.V5GetClosedPnLParam) (*bybit.V5GetClosedPnLResponse, error) {
131 | return r.Client.V5().Position().GetClosedPnL(param)
132 | }
133 |
134 | // CalculateTPSL returns TP and SL
135 | // "tp" and "sl" are not allowed to be 0 or not specified.
136 | func (r *BybitRepository) CalculateTPSL(req *domain.Order) error {
137 | var (
138 | currentPrice float64
139 | err error
140 | )
141 |
142 | if req.Type == "Market" {
143 | // INFO: テストネットとメインでは価格差が大きく、テストネットで注文を行う際に TP/SL の範囲外になる可能性があり、注文が失敗することがある
144 | currentPrice, err = r.getPrice(req.Symbol)
145 | if err != nil {
146 | return err
147 | }
148 | } else {
149 | currentPrice = utils.StringToFloat64(req.Price)
150 | }
151 |
152 | var (
153 | tp string
154 | sl string
155 | )
156 |
157 | if strings.Contains(req.TP, "%") {
158 | tp, sl, err = r.calculateTPSLByPercentage(req, currentPrice)
159 | } else {
160 | tp, sl, err = r.calculateTPSLByFixedPrice(req, currentPrice)
161 | }
162 | if err != nil {
163 | return err
164 | }
165 |
166 | req.TP = tp
167 | req.SL = sl
168 |
169 | return nil
170 | }
171 |
172 | func (r *BybitRepository) calculateTPSLByPercentage(req *domain.Order, currentPrice float64) (tp string, sl string, err error) {
173 | tpStr := strings.Replace(req.TP, "%", "", 1)
174 | tpF64, err := strconv.ParseFloat(tpStr, 64)
175 | if err != nil {
176 | return "0", "0", errors.New("failed to parse to float64 " + tpStr)
177 | }
178 | tpF64 /= 100 // パーセンテージを小数に変換
179 |
180 | slStr := strings.Replace(req.SL, "%", "", 1)
181 | slF64, err := strconv.ParseFloat(slStr, 64)
182 | if err != nil {
183 | return "0", "0", errors.New("failed to parse to float64 " + slStr)
184 | }
185 | slF64 /= 100 // パーセンテージを小数に変換
186 |
187 | switch req.Side {
188 | case "Buy":
189 | tp = utils.Float64ToString(currentPrice * (1 + tpF64)) // 現在価格にn%を加える
190 | sl = utils.Float64ToString(currentPrice * (1 - slF64)) // 現在価格からn%を引く
191 | case "Sell":
192 | tp = utils.Float64ToString(currentPrice * (1 - tpF64)) // 現在価格からn%を引く
193 | sl = utils.Float64ToString(currentPrice * (1 + slF64)) // 現在価格にn%を加える
194 | default:
195 | return "0", "0", errors.New("invalid side")
196 | }
197 |
198 | return tp, sl, nil
199 | }
200 |
201 | // calculateTPSLByFixedPrice returns TP and SL
202 | // req.TP contains "+" or "-" and a number (e.g. "+100", "-100")
203 | // it means the price difference from the current price
204 | func (r *BybitRepository) calculateTPSLByFixedPrice(req *domain.Order, currentPrice float64) (tp string, sl string, err error) {
205 | var inputPrice float64
206 |
207 | // TP
208 | switch {
209 | case strings.Contains(req.TP, "+"):
210 | inputPriceStr := strings.Replace(req.TP, "+", "", 1)
211 | inputPrice, err = strconv.ParseFloat(inputPriceStr, 64)
212 | if err != nil {
213 | return "0", "0", err
214 | }
215 | tp = utils.Float64ToString(currentPrice + inputPrice)
216 | case strings.Contains(req.TP, "-"):
217 | inputPriceStr := strings.Replace(req.TP, "-", "", 1)
218 | inputPrice, err = strconv.ParseFloat(inputPriceStr, 64)
219 | if err != nil {
220 | return "0", "0", err
221 | }
222 | tp = utils.Float64ToString(currentPrice - inputPrice)
223 | default:
224 | tp = req.TP
225 | }
226 |
227 | // SL
228 | switch {
229 | case strings.Contains(req.SL, "+"):
230 | inputPriceStr := strings.Replace(req.SL, "+", "", 1)
231 | inputPrice, err = strconv.ParseFloat(inputPriceStr, 64)
232 | if err != nil {
233 | return "0", "0", err
234 | }
235 | sl = utils.Float64ToString(currentPrice + inputPrice)
236 | case strings.Contains(req.SL, "-"):
237 | inputPriceStr := strings.Replace(req.SL, "-", "", 1)
238 | inputPrice, err = strconv.ParseFloat(inputPriceStr, 64)
239 | if err != nil {
240 | return "0", "0", err
241 | }
242 | sl = utils.Float64ToString(currentPrice - inputPrice)
243 | default:
244 | sl = req.SL
245 | }
246 |
247 | return tp, sl, nil
248 | }
249 |
250 | // getPrice returns index price
251 | func (r *BybitRepository) getPrice(symbol string) (float64, error) {
252 | v5symbol := bybit.SymbolV5(symbol)
253 |
254 | resp, err := r.Client.V5().Market().GetTickers(bybit.V5GetTickersParam{
255 | Category: bybit.CategoryV5Linear,
256 | Symbol: &v5symbol,
257 | })
258 | if err != nil {
259 | return 0, fmt.Errorf("bybit GetTickers(): %w", err)
260 | }
261 |
262 | return utils.StringToFloat64(resp.Result.LinearInverse.List[0].IndexPrice), nil
263 | }
264 |
265 | func (r *BybitRepository) GetWalletBalance() (float64, error) {
266 | resp, err := r.Client.V5().Account().GetWalletBalance(bybit.AccountTypeUnified, []bybit.Coin{bybit.CoinUSDT})
267 | if err != nil {
268 | return 0, err
269 | }
270 |
271 | balance, err := strconv.ParseFloat(resp.Result.List[0].TotalAvailableBalance, 64)
272 | if err != nil {
273 | return 0, err
274 | }
275 |
276 | return balance, nil
277 | }
278 |
--------------------------------------------------------------------------------
/pkg/adapter/gateway/tv_repository.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package gateway
20 |
21 | import (
22 | "github.com/rluisr/tvbit-bot/pkg/domain"
23 | "github.com/rluisr/tvbit-bot/pkg/external/logging"
24 | "gorm.io/gorm"
25 | )
26 |
27 | type (
28 | TVRepository struct {
29 | RWDB *gorm.DB
30 | RODB *gorm.DB
31 | Log *logging.Logging
32 | }
33 | )
34 |
35 | func (r *TVRepository) Logging() *logging.Logging {
36 | return r.Log
37 | }
38 |
39 | func (r *TVRepository) UpdateOrder(order *domain.Order) error {
40 | return r.RWDB.Save(&order).Error
41 | }
42 |
43 | func (r *TVRepository) SaveOrder(order *domain.Order) error {
44 | order.CEX = "bybit"
45 | return r.RWDB.Save(order).Error
46 | }
47 |
48 | func (r *TVRepository) SaveClosedPnL(closedPnL []*domain.ClosedPnL) error {
49 | return r.RWDB.CreateInBatches(closedPnL, 1000).Error
50 | }
51 |
52 | // GetUniqueSymbol returns unique symbol
53 | func (r *TVRepository) GetUniqueSymbol() ([]string, error) {
54 | var symbols []string
55 | err := r.RODB.Model(&domain.Order{}).Distinct("symbol").Find(&symbols).Error
56 | return symbols, err
57 | }
58 |
59 | func (r *TVRepository) TruncateClosedPnL() error {
60 | return r.RWDB.Exec("TRUNCATE closed_pnl;").Error
61 | }
62 |
--------------------------------------------------------------------------------
/pkg/adapter/interfaces/context.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package interfaces
20 |
21 | type Context interface {
22 | Param(string) string
23 | Bind(interface{}) error
24 | Status(int)
25 | JSON(int, interface{})
26 | }
27 |
--------------------------------------------------------------------------------
/pkg/domain/tv.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package domain
20 |
21 | import (
22 | "time"
23 |
24 | "github.com/shopspring/decimal"
25 | "gorm.io/gorm"
26 | )
27 |
28 | type Order struct {
29 | gorm.Model
30 | Name string `gorm:"type:varchar(255);default:null" json:"name"` // alert name, description or something
31 | CEX string `gorm:"type:varchar(255);not null" json:"-"`
32 | OrderID string `gorm:"type:varchar(255);uniqueIndex:order_id;not null"`
33 | Type string `gorm:"type:varchar(255)" json:"type" binding:"required"` // "Market" or "Limit"
34 | Symbol string `gorm:"type:varchar(255)" json:"symbol" binding:"required"` // eg: BTCUSDT
35 | Side string `gorm:"type:varchar(255)" json:"side" binding:"required"` // "Buy" or "Sell"
36 | Price string `gorm:"-" json:"price"` // Set 0 if order_type is Market
37 | EntryPrice decimal.Decimal `gorm:"type:decimal(10,4)" json:"-"`
38 | QTY string `gorm:"type:float" json:"qty" binding:"required"`
39 | TP string `gorm:"type:float" json:"tp" binding:"required"`
40 | SL string `gorm:"type:float" json:"sl" binding:"required"`
41 | }
42 |
43 | type ClosedPnL struct {
44 | ID int `gorm:"primaryKey"`
45 | OrderID string `gorm:"type:varchar(255);uniqueIndex:order_id;not null"`
46 | Symbol string `gorm:"type:varchar(255);not null"`
47 | Side string `gorm:"type:varchar(255);not null"`
48 | Qty string `gorm:"type:float;not null"`
49 | OrderPrice decimal.Decimal `gorm:"type:decimal(10,4);not null"`
50 | ClosedSize decimal.Decimal `gorm:"type:decimal(10,4);not null"`
51 | CumEntryValue decimal.Decimal `gorm:"type:decimal(10,4);not null"`
52 | AvgEntryPrice decimal.Decimal `gorm:"type:decimal(10,4);not null"`
53 | CumExitValue decimal.Decimal `gorm:"type:decimal(10,4);not null"`
54 | AvgExitPrice decimal.Decimal `gorm:"type:decimal(10,4);not null"`
55 | ClosedPnL decimal.Decimal `gorm:"type:decimal(10,4);column:closed_pnl;not null"`
56 | CreatedAt time.Time `gorm:"type:datetime;not null"`
57 | UpdatedAt time.Time `gorm:"type:datetime;not null"`
58 | }
59 |
60 | func (c ClosedPnL) TableName() string {
61 | return "closed_pnl"
62 | }
63 |
64 | type TVOrderResponse struct {
65 | Success bool `json:"successful" binding:"required"`
66 | Reason string `json:"reason,omitempty" binding:"required"`
67 | Order *Order `json:"order"`
68 | }
69 |
--------------------------------------------------------------------------------
/pkg/external/bybit/bybit.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package bybit
20 |
21 | import (
22 | "fmt"
23 | "net/http"
24 |
25 | "github.com/hirokisan/bybit/v2"
26 | )
27 |
28 | func Init(httpClient *http.Client) *bybit.Client {
29 | config, err := NewConfig()
30 | if err != nil {
31 | panic(fmt.Errorf("bybit.NewConfig err: %w", err))
32 | }
33 |
34 | var client *bybit.Client
35 |
36 | if config.IsTestnet {
37 | client = bybit.NewTestClient().WithAuth(config.APIKey, config.APISecret).WithHTTPClient(httpClient)
38 | } else {
39 | client = bybit.NewClient().WithAuth(config.APIKey, config.APISecret).WithHTTPClient(httpClient)
40 | }
41 |
42 | return client
43 | }
44 |
--------------------------------------------------------------------------------
/pkg/external/bybit/config.go:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * tvbit-bot
4 | * Copyright (C) 2022 rluisr(Takuya Hasegawa)
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | * /
19 | */
20 |
21 | package bybit
22 |
23 | import "github.com/Netflix/go-env"
24 |
25 | type Config struct {
26 | APIKey string `env:"BYBIT_API_KEY,required"`
27 | APISecret string `env:"BYBIT_API_SECRET,required"`
28 | IsTestnet bool `env:"BYBIT_IS_TESTNET,required"`
29 | }
30 |
31 | func NewConfig() (*Config, error) {
32 | var config Config
33 |
34 | _, err := env.UnmarshalFromEnviron(&config)
35 | return &config, err
36 | }
37 |
--------------------------------------------------------------------------------
/pkg/external/cron.go:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * tvbit-bot
4 | * Copyright (C) 2022 rluisr(Takuya Hasegawa)
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | * /
19 | */
20 |
21 | package external
22 |
23 | import (
24 | "os"
25 | "os/signal"
26 | "time"
27 |
28 | "github.com/go-co-op/gocron/v2"
29 | )
30 |
31 | func Cron() {
32 | s, err := gocron.NewScheduler()
33 | if err != nil {
34 | panic(err)
35 | }
36 |
37 | _, err = s.NewJob(
38 | gocron.CronJob("0 * * * *", false),
39 | gocron.NewTask(func() {
40 | foErr := tvController.FetchOrder()
41 | if foErr != nil {
42 | tvController.Interactor.TVRepository.Logging().Error("FetchOrder", foErr.Error(), foErr)
43 | return
44 | }
45 | tvController.Interactor.TVRepository.Logging().Info("FetchOrder is done")
46 | }),
47 | )
48 | if err != nil {
49 | tvController.Interactor.TVRepository.Logging().Error("NewJob: FetchOrder", err.Error(), err)
50 | }
51 |
52 | _, err = s.NewJob(
53 | // KeepAlive を続けるために短い間隔で行う
54 | gocron.DurationJob(
55 | 3*time.Second,
56 | ),
57 | gocron.NewTask(func() {
58 | icErr := tvController.InventoryCheck(5 * time.Minute)
59 | if icErr != nil {
60 | tvController.Interactor.TVRepository.Logging().Error("InventoryCheck", icErr.Error(), icErr)
61 | return
62 | }
63 | }),
64 | )
65 | if err != nil {
66 | tvController.Interactor.TVRepository.Logging().Error("NewJob", err.Error(), err)
67 | }
68 |
69 | s.Start()
70 |
71 | quit := make(chan os.Signal, 1)
72 | signal.Notify(quit, os.Interrupt)
73 | <-quit
74 |
75 | _ = s.Shutdown()
76 | }
77 |
--------------------------------------------------------------------------------
/pkg/external/http.go:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * tvbit-bot
4 | * Copyright (C) 2022 rluisr(Takuya Hasegawa)
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | * /
19 | */
20 |
21 | package external
22 |
23 | import (
24 | "net"
25 | "net/http"
26 | "time"
27 | )
28 |
29 | func NewHTTPClient() *http.Client {
30 | return &http.Client{
31 | Transport: &http.Transport{
32 | DialContext: (&net.Dialer{
33 | Timeout: 30 * time.Second,
34 | KeepAlive: 30 * time.Second,
35 | }).DialContext,
36 | MaxIdleConns: 128,
37 | MaxIdleConnsPerHost: 100,
38 | IdleConnTimeout: 90 * time.Second,
39 | TLSHandshakeTimeout: 10 * time.Second,
40 | ResponseHeaderTimeout: 10 * time.Second,
41 | ExpectContinueTimeout: 1 * time.Second,
42 | },
43 | Timeout: 60 * time.Second,
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/pkg/external/init.go:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * tvbit-bot
4 | * Copyright (C) 2022 rluisr(Takuya Hasegawa)
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | * /
19 | */
20 |
21 | package external
22 |
23 | import (
24 | "context"
25 |
26 | "github.com/rluisr/tvbit-bot/pkg/adapter/controllers"
27 | tvbitBybit "github.com/rluisr/tvbit-bot/pkg/external/bybit"
28 | "github.com/rluisr/tvbit-bot/pkg/external/logging"
29 | "github.com/rluisr/tvbit-bot/pkg/external/mysql"
30 | "go.opentelemetry.io/otel"
31 | "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
32 | otelresource "go.opentelemetry.io/otel/sdk/resource"
33 | oteltrace "go.opentelemetry.io/otel/sdk/trace"
34 | semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
35 | )
36 |
37 | var (
38 | tvController *controllers.TVController
39 | )
40 |
41 | // OTLP Exporter
42 | func newOTLPExporter(ctx context.Context) (oteltrace.SpanExporter, error) {
43 | // Change default HTTPS -> HTTP
44 | insecureOpt := otlptracehttp.WithInsecure()
45 | return otlptracehttp.New(ctx, insecureOpt)
46 | }
47 |
48 | // TracerProvider is an OpenTelemetry TracerProvider.
49 | // It provides Tracers to instrumentation so it can trace operational flow through a system.
50 | func newTraceProvider(serviceName string, exp oteltrace.SpanExporter) *oteltrace.TracerProvider {
51 | // Ensure default SDK resources and the required service name are set.
52 | r, err := otelresource.Merge(
53 | otelresource.Default(),
54 | otelresource.NewWithAttributes(
55 | semconv.SchemaURL,
56 | semconv.ServiceName(serviceName),
57 | ),
58 | )
59 |
60 | if err != nil {
61 | panic(err)
62 | }
63 |
64 | return oteltrace.NewTracerProvider(
65 | oteltrace.WithBatcher(exp),
66 | oteltrace.WithResource(r),
67 | )
68 | }
69 |
70 | func Init(source string) (err error) {
71 | log, err := logging.New(source)
72 | if err != nil {
73 | return err
74 | }
75 |
76 | ctx := context.Background()
77 | exp, err := newOTLPExporter(ctx)
78 | if err != nil {
79 | return err
80 | }
81 | tp := newTraceProvider(source, exp) // logger for middleware
82 |
83 | otel.SetTracerProvider(tp)
84 |
85 | rwDB, roDB, err := mysql.Connect()
86 | if err != nil {
87 | return err
88 | }
89 |
90 | httpClient := NewHTTPClient()
91 | bybitClient := tvbitBybit.Init(httpClient)
92 |
93 | tvController = controllers.NewTVController(log, rwDB, roDB, bybitClient)
94 |
95 | return nil
96 | }
97 |
--------------------------------------------------------------------------------
/pkg/external/logging/config.go:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * tvbit-bot
4 | * Copyright (C) 2022 rluisr(Takuya Hasegawa)
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | * /
19 | */
20 |
21 | package logging
22 |
23 | import "github.com/Netflix/go-env"
24 |
25 | type Config struct {
26 | LokiBasicPass string `env:"LOKI_BASIC_PASS"`
27 | LokiBasicUser string `env:"LOKI_BASIC_USER"`
28 | LokiURL string `env:"LOKI_URL"`
29 | }
30 |
31 | func NewConfig() (*Config, error) {
32 | var config Config
33 |
34 | _, err := env.UnmarshalFromEnviron(&config)
35 | return &config, err
36 | }
37 |
--------------------------------------------------------------------------------
/pkg/external/logging/log.go:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * tvbit-bot
4 | * Copyright (C) 2022 rluisr(Takuya Hasegawa)
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | * /
19 | */
20 |
21 | package logging
22 |
23 | import (
24 | "fmt"
25 | "log"
26 | "os"
27 |
28 | "github.com/ic2hrmk/promtail"
29 | )
30 |
31 | const (
32 | envLocal = "local"
33 | )
34 |
35 | type Logging struct {
36 | Log promtail.Client
37 | }
38 |
39 | func New(source string) (*Logging, error) {
40 | config, err := NewConfig()
41 | if err != nil {
42 | panic(fmt.Errorf("logging.NewConfig err: %w", err))
43 | }
44 |
45 | identifiers := map[string]string{
46 | "source": source,
47 | }
48 |
49 | promtailClient, err := promtail.NewJSONv1Client(config.LokiURL, identifiers, promtail.WithBasicAuth(config.LokiBasicUser, config.LokiBasicPass))
50 | if err != nil {
51 | return nil, err
52 | }
53 |
54 | return &Logging{Log: promtailClient}, nil
55 | }
56 |
57 | func (l *Logging) Info(msg string) {
58 | if os.Getenv("SERVER_ENV") != envLocal {
59 | l.Log.Infof(msg)
60 | }
61 |
62 | log.Println(msg)
63 | }
64 |
65 | func (l *Logging) Error(funcName, msg string, err error) {
66 | body := fmt.Sprintf("func_name: %s, msg: %s, error: %s", funcName, msg, err.Error())
67 |
68 | if os.Getenv("SERVER_ENV") != envLocal {
69 | l.Log.Errorf(body)
70 | }
71 |
72 | log.Println(body)
73 | }
74 |
75 | func (l *Logging) Fatal(funcName, msg string, err error) {
76 | body := fmt.Sprintf("func_name: %s, msg: %s, error: %s", funcName, msg, err.Error())
77 |
78 | if os.Getenv("SERVER_ENV") != envLocal {
79 | l.Log.Errorf(body)
80 | }
81 |
82 | log.Fatal(body)
83 | }
84 |
--------------------------------------------------------------------------------
/pkg/external/mysql/config.go:
--------------------------------------------------------------------------------
1 | package mysql
2 |
3 | import "github.com/Netflix/go-env"
4 |
5 | type Config struct {
6 | MySQLHostRW string `env:"MYSQL_HOST_RW,required=true"`
7 | MySQLHostRO string `env:"MYSQL_HOST_RO,required=true"`
8 | MySQLUser string `env:"MYSQL_USER,required=true"`
9 | MySQLPass string `env:"MYSQL_PASS,required=true"`
10 | MySQLDBName string `env:"MYSQL_DB_NAME,required=true"`
11 | }
12 |
13 | func NewConfig() (*Config, error) {
14 | var config Config
15 |
16 | _, err := env.UnmarshalFromEnviron(&config)
17 | return &config, err
18 | }
19 |
--------------------------------------------------------------------------------
/pkg/external/mysql/mysql.go:
--------------------------------------------------------------------------------
1 | package mysql
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 | "time"
8 |
9 | "github.com/rluisr/tvbit-bot/pkg/domain"
10 | "gorm.io/driver/mysql"
11 | "gorm.io/gorm"
12 | "gorm.io/gorm/logger"
13 | gormTracing "gorm.io/plugin/opentelemetry/tracing"
14 | )
15 |
16 | var (
17 | rwDB *gorm.DB
18 | roDB *gorm.DB
19 | )
20 |
21 | const (
22 | DBMaxOpenConn = 10
23 | DBMaxIdleConn = 5
24 | DBMaxLifeTime = time.Second
25 | )
26 |
27 | func Connect() (*gorm.DB, *gorm.DB, error) {
28 | config, err := NewConfig()
29 | if err != nil {
30 | panic(fmt.Errorf("mysql.NewConfig err: %w", err))
31 | }
32 |
33 | gormLogger := logger.New(
34 | log.New(os.Stdout, "\r\n", log.LstdFlags),
35 | logger.Config{
36 | SlowThreshold: 300 * time.Millisecond,
37 | LogLevel: logger.Warn,
38 | IgnoreRecordNotFoundError: true,
39 | Colorful: true,
40 | },
41 | )
42 |
43 | dsnRW := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local&interpolateParams=true", config.MySQLUser, config.MySQLPass, config.MySQLHostRW, config.MySQLDBName)
44 | rwDB, err = gorm.Open(mysql.New(mysql.Config{
45 | DSN: dsnRW,
46 | DontSupportRenameColumn: false,
47 | DontSupportRenameIndex: false,
48 | }), &gorm.Config{
49 | DisableForeignKeyConstraintWhenMigrating: true,
50 | Logger: gormLogger,
51 | PrepareStmt: true,
52 | })
53 | if err != nil {
54 | return nil, nil, err
55 | }
56 |
57 | rwSQL, err := rwDB.DB()
58 | if err != nil {
59 | panic(fmt.Errorf("rwDB.DB() err: %w", err))
60 | }
61 | rwSQL.SetMaxOpenConns(DBMaxOpenConn)
62 | rwSQL.SetMaxIdleConns(DBMaxIdleConn)
63 | rwSQL.SetConnMaxLifetime(DBMaxLifeTime)
64 | err = rwSQL.Ping()
65 | if err != nil {
66 | return nil, nil, err
67 | }
68 | err = rwDB.AutoMigrate(&domain.Order{}, &domain.ClosedPnL{})
69 | if err != nil {
70 | return nil, nil, err
71 | }
72 |
73 | dsnRO := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local&interpolateParams=true", config.MySQLUser, config.MySQLPass, config.MySQLHostRO, config.MySQLDBName)
74 | roDB, err = gorm.Open(mysql.Open(dsnRO), &gorm.Config{
75 | DisableForeignKeyConstraintWhenMigrating: true,
76 | Logger: gormLogger,
77 | PrepareStmt: true,
78 | })
79 | if err != nil {
80 | return nil, nil, err
81 | }
82 |
83 | roSQL, err := roDB.DB()
84 | if err != nil {
85 | panic(fmt.Errorf("roDB.DB() err: %w", err))
86 | }
87 | roSQL.SetMaxOpenConns(DBMaxOpenConn)
88 | roSQL.SetMaxIdleConns(DBMaxIdleConn)
89 | roSQL.SetConnMaxLifetime(DBMaxLifeTime)
90 | err = roSQL.Ping()
91 | if err != nil {
92 | return nil, nil, err
93 | }
94 |
95 | err = rwDB.Use(gormTracing.NewPlugin())
96 | if err != nil {
97 | return nil, nil, err
98 | }
99 | err = roDB.Use(gormTracing.NewPlugin())
100 | if err != nil {
101 | return nil, nil, err
102 | }
103 |
104 | return rwDB, roDB, nil
105 | }
106 |
107 | func CloseConn() {
108 | rwSQL, _ := rwDB.DB()
109 | rwSQL.Close()
110 |
111 | roSQL, _ := roDB.DB()
112 | roSQL.Close()
113 | }
114 |
--------------------------------------------------------------------------------
/pkg/external/router.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package external
20 |
21 | import (
22 | "context"
23 | "log"
24 | "net/http"
25 | "os"
26 | "os/signal"
27 | "time"
28 |
29 | "github.com/gin-gonic/gin"
30 | "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
31 | )
32 |
33 | func Run(serviceName string) {
34 | r := gin.Default()
35 | r.Use(otelgin.Middleware(serviceName, otelgin.WithFilter(func(req *http.Request) bool {
36 | return req.URL.Path != "/"
37 | })))
38 | r.ForwardedByClientIP = true
39 |
40 | r.GET("/", func(c *gin.Context) {
41 | c.JSON(http.StatusOK, map[string]string{
42 | "repo": "https://github.com/rluisr/tvbit-bot",
43 | "owner": "rluisr / rarirureluis",
44 | })
45 | })
46 |
47 | tv := r.Group("/tv")
48 | tv.GET("", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/") })
49 | tv.POST("", func(c *gin.Context) { tvController.Handle(c) })
50 |
51 | var addr string
52 | if os.Getenv("SERVER_ENV") == "local" {
53 | r.Use(gin.Logger())
54 | addr = ":3001"
55 | } else {
56 | addr = ":8082"
57 | }
58 | if os.Getenv("PORT") != "" {
59 | addr = ":" + os.Getenv("PORT")
60 | }
61 |
62 | srv := &http.Server{
63 | Addr: addr,
64 | Handler: r,
65 | ReadHeaderTimeout: 100 * time.Millisecond,
66 | }
67 |
68 | go func() {
69 | if err := srv.ListenAndServe(); err != nil {
70 | log.Printf("listen: %s\n", err)
71 | }
72 | }()
73 |
74 | quit := make(chan os.Signal, 1)
75 | signal.Notify(quit, os.Interrupt)
76 | <-quit
77 | log.Println("Shutdown Server ...")
78 |
79 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
80 | if err := srv.Shutdown(ctx); err != nil {
81 | log.Fatal("Server Shutdown:", err)
82 | }
83 | defer cancel()
84 | log.Println("Server exiting")
85 | }
86 |
--------------------------------------------------------------------------------
/pkg/usecase/interfaces/repositories.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package interfaces
20 |
21 | import (
22 | "github.com/hirokisan/bybit/v2"
23 | "github.com/rluisr/tvbit-bot/pkg/domain"
24 | "github.com/rluisr/tvbit-bot/pkg/external/logging"
25 | )
26 |
27 | type TVRepository interface {
28 | Logging() *logging.Logging
29 | SaveOrder(*domain.Order) error
30 | SaveClosedPnL(closedPnL []*domain.ClosedPnL) error
31 | UpdateOrder(*domain.Order) error
32 | GetUniqueSymbol() ([]string, error)
33 | TruncateClosedPnL() error
34 | }
35 |
36 | type BybitRepository interface {
37 | CreateOrder(*domain.Order) error
38 | CancelOrder(req *domain.Order) error
39 | FetchOpenOrder(*domain.Order) error
40 | GetOpenOrders() (*bybit.V5GetOrdersResponse, error)
41 | GetClosedPNL(param bybit.V5GetClosedPnLParam) (*bybit.V5GetClosedPnLResponse, error)
42 | CalculateTPSL(*domain.Order) error
43 | GetWalletBalance() (float64, error)
44 | }
45 |
--------------------------------------------------------------------------------
/pkg/usecase/tv_interactor.go:
--------------------------------------------------------------------------------
1 | /*
2 | tvbit-bot
3 | Copyright (C) 2022 rluisr(Takuya Hasegawa)
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package usecase
20 |
21 | import (
22 | "fmt"
23 | "time"
24 |
25 | "github.com/gin-gonic/gin"
26 | "github.com/hirokisan/bybit/v2"
27 | "github.com/rluisr/tvbit-bot/pkg/domain"
28 | "github.com/rluisr/tvbit-bot/pkg/usecase/interfaces"
29 | "github.com/rluisr/tvbit-bot/utils"
30 | "github.com/shopspring/decimal"
31 | )
32 |
33 | type TVInteractor struct {
34 | TVRepository interfaces.TVRepository
35 | BybitRepository interfaces.BybitRepository
36 | }
37 |
38 | func (i *TVInteractor) CreateOrder(c *gin.Context) (domain.TVOrderResponse, error) {
39 | var req domain.Order
40 | err := c.ShouldBindJSON(&req)
41 | if err != nil {
42 | return domain.TVOrderResponse{
43 | Success: false,
44 | Reason: err.Error(),
45 | Order: nil,
46 | }, err
47 | }
48 |
49 | err = i.BybitRepository.CalculateTPSL(&req)
50 | if err != nil {
51 | return domain.TVOrderResponse{
52 | Success: false,
53 | Reason: err.Error(),
54 | Order: nil,
55 | }, err
56 | }
57 |
58 | err = i.BybitRepository.CreateOrder(&req)
59 | if err != nil {
60 | return domain.TVOrderResponse{
61 | Success: false,
62 | Reason: err.Error(),
63 | Order: nil,
64 | }, err
65 | }
66 |
67 | err = i.BybitRepository.FetchOpenOrder(&req)
68 | if err != nil {
69 | return domain.TVOrderResponse{
70 | Success: false,
71 | Reason: err.Error(),
72 | Order: &req,
73 | }, err
74 | }
75 |
76 | err = i.TVRepository.SaveOrder(&req)
77 | if err != nil {
78 | return domain.TVOrderResponse{
79 | Success: false,
80 | Reason: err.Error(),
81 | Order: &req,
82 | }, err
83 | }
84 |
85 | i.TVRepository.Logging().Info(fmt.Sprintf("created order: %+v", req))
86 |
87 | return domain.TVOrderResponse{Success: true, Order: &req}, nil
88 | }
89 |
90 | func (i *TVInteractor) FetchPL() error {
91 | // TODO TRUNCATE せずに増分更新する
92 | err := i.TVRepository.TruncateClosedPnL()
93 | if err != nil {
94 | return err
95 | }
96 |
97 | symbols, err := i.TVRepository.GetUniqueSymbol()
98 | if err != nil {
99 | return err
100 | }
101 |
102 | var closedOrders []bybit.V5GetClosedPnLItem
103 |
104 | for _, symbol := range symbols {
105 | bSymbol := bybit.SymbolV5(symbol)
106 | limit := 100
107 |
108 | var temp []bybit.V5GetClosedPnLItem
109 |
110 | resp, gcPNLErr := i.BybitRepository.GetClosedPNL(bybit.V5GetClosedPnLParam{
111 | Category: bybit.CategoryV5Linear,
112 | Symbol: &bSymbol,
113 | Limit: &limit,
114 | })
115 | if gcPNLErr != nil {
116 | return gcPNLErr
117 | }
118 | temp = append(temp, resp.Result.List...)
119 |
120 | if resp.Result.NextPageCursor != "" {
121 | for {
122 | resp, err = i.BybitRepository.GetClosedPNL(bybit.V5GetClosedPnLParam{
123 | Category: bybit.CategoryV5Linear,
124 | Symbol: &bSymbol,
125 | Limit: &limit,
126 | Cursor: &resp.Result.NextPageCursor,
127 | })
128 | if err != nil {
129 | return err
130 | }
131 | temp = append(temp, resp.Result.List...)
132 |
133 | if resp.Result.NextPageCursor == "" {
134 | break
135 | }
136 | }
137 | }
138 |
139 | closedOrders = append(closedOrders, temp...)
140 | }
141 |
142 | var closedPnLs []*domain.ClosedPnL
143 | for _, order := range closedOrders {
144 | orderPrice, fErr := decimal.NewFromString(order.OrderPrice)
145 | if fErr != nil {
146 | return fErr
147 | }
148 |
149 | closedSize, fErr := decimal.NewFromString(order.ClosedSize)
150 | if fErr != nil {
151 | return fErr
152 | }
153 |
154 | cumEntryValue, fErr := decimal.NewFromString(order.CumEntryValue)
155 | if fErr != nil {
156 | return fErr
157 | }
158 |
159 | avgEntryPrice, fErr := decimal.NewFromString(order.AvgEntryPrice)
160 | if fErr != nil {
161 | return fErr
162 | }
163 |
164 | cumExitValue, fErr := decimal.NewFromString(order.CumExitValue)
165 | if fErr != nil {
166 | return fErr
167 | }
168 |
169 | avgExitPrice, fErr := decimal.NewFromString(order.AvgExitPrice)
170 | if fErr != nil {
171 | return fErr
172 | }
173 |
174 | closedPnL, fErr := decimal.NewFromString(order.ClosedPnl)
175 | if fErr != nil {
176 | return fErr
177 | }
178 |
179 | createTime, fErr := utils.TimestampMSToTime(order.CreatedTime)
180 | if fErr != nil {
181 | return fErr
182 | }
183 |
184 | updateTime, fErr := utils.TimestampMSToTime(order.UpdatedTime)
185 | if fErr != nil {
186 | return fErr
187 | }
188 |
189 | a := &domain.ClosedPnL{
190 | OrderID: order.OrderID,
191 | Symbol: string(order.Symbol),
192 | Side: string(order.Side),
193 | Qty: order.Qty,
194 | OrderPrice: orderPrice,
195 | ClosedSize: closedSize,
196 | CumEntryValue: cumEntryValue,
197 | AvgEntryPrice: avgEntryPrice,
198 | CumExitValue: cumExitValue,
199 | AvgExitPrice: avgExitPrice,
200 | ClosedPnL: closedPnL,
201 | CreatedAt: createTime,
202 | UpdatedAt: updateTime,
203 | }
204 | closedPnLs = append(closedPnLs, a)
205 | }
206 |
207 | return i.TVRepository.SaveClosedPnL(closedPnLs)
208 | }
209 |
210 | // InventoryCheck は約定していない注文で、n分経過したものをキャンセルする
211 | func (i *TVInteractor) InventoryCheck(cancelAfter time.Duration) error {
212 | orders, err := i.BybitRepository.GetOpenOrders()
213 | if err != nil {
214 | return err
215 | }
216 |
217 | for _, order := range orders.Result.List {
218 | // New: 新規注文(ポジションは持ってない)
219 | // Untriggered: TP/SL のみの注文(ポジション注文は通っているが、TP/SL 注文がある状態)
220 | if order.OrderStatus == bybit.OrderStatusNew {
221 | createdAt, cErr := utils.TimestampMSToTime(order.CreatedTime)
222 | if cErr != nil {
223 | return cErr
224 | }
225 |
226 | if createdAt.Add(cancelAfter).Before(time.Now()) {
227 | err = i.BybitRepository.CancelOrder(&domain.Order{
228 | OrderID: order.OrderID,
229 | Symbol: string(order.Symbol),
230 | })
231 | if err != nil {
232 | return err
233 | }
234 |
235 | i.TVRepository.Logging().Info(fmt.Sprintf("canceled order: %+v", order))
236 | }
237 | }
238 | }
239 |
240 | return nil
241 | }
242 |
--------------------------------------------------------------------------------
/utils/convert.go:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * tvbit-bot
4 | * Copyright (C) 2022 rluisr(Takuya Hasegawa)
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Affero General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Affero General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Affero General Public License
17 | * along with this program. If not, see .
18 | * /
19 | */
20 |
21 | package utils
22 |
23 | import (
24 | "strconv"
25 | "time"
26 | )
27 |
28 | func StringToFloat64(str string) float64 {
29 | f, err := strconv.ParseFloat(str, 64)
30 | if err != nil {
31 | panic(err)
32 | }
33 | return f
34 | }
35 |
36 | func Float64ToString(f float64) string {
37 | return strconv.FormatFloat(f, 'f', -1, 64)
38 | }
39 |
40 | func TimestampMSToTime(timestampStr string) (time.Time, error) {
41 | timestampInt64, err := strconv.ParseInt(timestampStr, 10, 64)
42 | if err != nil {
43 | return time.Now(), err
44 | }
45 |
46 | // Convert milliseconds to seconds
47 | timestampSec := timestampInt64 / 1000
48 | timestampNanoSec := (timestampInt64 % 1000) * int64(time.Millisecond)
49 |
50 | t := time.Unix(timestampSec, timestampNanoSec)
51 |
52 | return t, nil
53 | }
54 |
--------------------------------------------------------------------------------